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 ProbeInstanceCount { get; private set; } internal static ConfigEntry ProbeInstanceScale { get; private set; } internal static ConfigEntry ProbeRadius { get; private set; } internal static ConfigEntry TestStaffProgram { get; private set; } internal static ConfigEntry ExportPlayerDocs { get; private set; } internal static ConfigEntry VoxelDensity { get; private set; } internal static ConfigEntry SelfDamage { get; private set; } internal static ConfigEntry ManaDrainOrder { get; private set; } internal static ConfigEntry StaffModelPosition { get; private set; } internal static ConfigEntry StaffModelRotation { get; private set; } internal static ConfigEntry StaffModelScale { get; private set; } internal static ConfigEntry DeveloperMode { get; private set; } internal static ConfigEntry SoundBrowseFrom { get; private set; } internal static ConfigEntry 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("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(0, 300000), Array.Empty())); ProbeInstanceScale = ((BaseUnityPlugin)this).Config.Bind("RenderProbe", "InstanceScale", 0.15f, new ConfigDescription("Size of a single probe instance, in metres.", (AcceptableValueBase)(object)new AcceptableValueRange(0.01f, 2f), Array.Empty())); ProbeRadius = ((BaseUnityPlugin)this).Config.Bind("RenderProbe", "Radius", 6f, new ConfigDescription("Radius of the probe cloud, in metres.", (AcceptableValueBase)(object)new AcceptableValueRange(0.5f, 50f), Array.Empty())); TestStaffProgram = ((BaseUnityPlugin)this).Config.Bind("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("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("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(0.1f, 8f), Array.Empty())); SelfDamage = ((BaseUnityPlugin)this).Config.Bind("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("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("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("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("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("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("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("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 _alertShown = new Dictionary(); 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 _castFrom = new Dictionary(); private readonly Queue _castFromOrder = new Queue(); 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 list = new List(); List list2 = new List(); 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.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(); 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.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 list = new List(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.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.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.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 Returned = new Dictionary(); private static readonly Dictionary Prices = new Dictionary(); 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.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 equippedItems = instance.EquipmentManager.EquippedItems; Credit(equippedItems, (InventorySlot)4, num2, now); Credit(equippedItems, (InventorySlot)5, num2, now); } } } private static bool AnyBreechEquipped() { GameManager instance = StaticInstance.Instance; Dictionary 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 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 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.Instance; List 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.Instance; Dictionary 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.Instance; Dictionary 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.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.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 "" + string.Format(SpellText.Get("preview.full", "{0} has no room for another spell"), localizedDisplayName) + ""; } 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 list = new List(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 "" + string.Join("
", list) + ""; } 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.Instance; Dictionary 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.Instance; Dictionary 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("UnholyRites_Staff_Mesh"); Palette = _bundle.LoadAsset("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(); obj.sprite = Triangle(); ((Graphic)obj).color = new Color(1f, 0.92f, 0.6f, 0.95f); ((Graphic)obj).raycastTarget = false; val.AddComponent().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 Pools = new ConditionalWeakTable(); 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 Movable = new List(); 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 list = Rows(description); if (list == null) { return; } int count = item.enchantments.Count; int num = 0; Movable.Clear(); HashSet hashSet = new HashSet(); 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 = "" + ((TMP_Text)val.textComp).text + ""; } (((Component)val).GetComponent() ?? ((Component)val).gameObject.AddComponent()).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 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:") + "
" + spellSegments.Summary.Replace("\r\n", "\n").Replace("\n", "
"); List 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 + "
" + string.Format(SpellText.Get("idle.row", "{0} does nothing here: {1}"), arg, idleRow.Reason) + ""; } _addText.Invoke(description, new object[2] { text, num + 1 }); } } private static List 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; } 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() : 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 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.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(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(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(); 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(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 list = new List(); 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(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().sharedMesh = StaffAssets.Mesh; MeshRenderer val2 = val.AddComponent(); ((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.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 invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: 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_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_014a: Unknown result type (might be due to invalid IL or missing references) string value = Plugin.StaffModelPosition.Value; string value2 = Plugin.StaffModelRotation.Value; float value3 = Plugin.StaffModelScale.Value; Vector3 val = (((Object)(object)((Component)this).transform.parent != (Object)null) ? ((Component)this).transform.parent.lossyScale : Vector3.one); if (!(value == _appliedPosition) || !(value2 == _appliedRotation) || !value3.Equals(_appliedScale) || !(val == _appliedParentScale)) { _appliedPosition = value; _appliedRotation = value2; _appliedScale = value3; _appliedParentScale = val; Vector3 val2 = InverseScale(val); ((Component)this).transform.localPosition = Vector3.Scale(ParseVector(value) + Offset, val2); ((Component)this).transform.localScale = val2 * ((value3 > 0f) ? value3 : 1f); Quaternion val3 = (((Object)(object)Root != (Object)null) ? (Quaternion.Inverse(((Component)this).transform.parent.rotation) * Root.rotation) : Quaternion.identity); ((Component)this).transform.localRotation = val3 * Quaternion.Euler(ParseVector(value2)); Report(val, val2); } } private void Report(Vector3 parentScale, Vector3 inverse) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_008a: 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_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: 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) //IL_00c7: 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_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) if (!_reported) { _reported = true; MeshFilter component = ((Component)this).GetComponent(); Vector3 val; if (!((Object)(object)component != (Object)null) || !((Object)(object)component.sharedMesh != (Object)null)) { val = Vector3.zero; } else { Bounds bounds = component.sharedMesh.bounds; val = ((Bounds)(ref bounds)).size; } Vector3 val2 = val; Vector3 lossyScale = ((Component)this).transform.lossyScale; ManualLogSource log = Plugin.Log; string[] obj = new string[8] { "Staff model placed on '", ((Object)((Component)this).transform.parent).name, "': ", $"parentScale={parentScale:F3} localScale={((Component)this).transform.localScale:F4} ", $"worldScale={lossyScale:F3} meshSize={val2:F3} ", $"drawnAs={Vector3.Scale(val2, lossyScale):F3} m, ", $"layer={LayerMask.LayerToName(((Component)this).gameObject.layer)}({((Component)this).gameObject.layer}) ", null }; Renderer component2 = ((Component)this).GetComponent(); obj[7] = $"renderingLayerMask={((component2 != null) ? new uint?(component2.renderingLayerMask) : ((uint?)null))}"; log.LogInfo((object)string.Concat(obj)); } } private static Vector3 InverseScale(Vector3 scale) { //IL_0000: 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_0025: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0061: 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) return new Vector3(Mathf.Approximately(scale.x, 0f) ? 1f : (1f / scale.x), Mathf.Approximately(scale.y, 0f) ? 1f : (1f / scale.y), Mathf.Approximately(scale.z, 0f) ? 1f : (1f / scale.z)); } private static Vector3 ParseVector(string text) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(text)) { return Vector3.zero; } string[] array = text.Split(new char[1] { ',' }); if (array.Length != 3) { return Vector3.zero; } Vector3 result = default(Vector3); for (int i = 0; i < 3; i++) { if (!float.TryParse(array[i].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result2)) { return Vector3.zero; } ((Vector3)(ref result))[i] = result2; } return result; } } public static class StaffProgram { private sealed class CachedPlan { internal SpellSegments Plan; internal int Version = -1; internal string Oath; internal EnchantmentDefinition[] Rows; internal List Idle; } internal readonly struct IdleRow { internal readonly int Index; internal readonly SpellKey Spell; internal readonly string Name; internal readonly string Reason; internal IdleRow(int index, SpellKey spell, string name, string reason) { Index = index; Spell = spell; Name = name; Reason = reason; } } private static readonly ConditionalWeakTable Cache = new ConditionalWeakTable(); private static readonly List NoIdleRows = new List(); private static readonly Dictionary FieldsOf = new Dictionary(); private static int _generation; internal static List IdleRows(InventoryItem staff) { SpellSegments spellSegments = For(staff); if (spellSegments == null || StaffDefinitions.Of(staff).HandSlots > 0) { return NoIdleRows; } CachedPlan value = Cache.GetValue(staff, (InventoryItem _) => new CachedPlan()); if (value.Idle != null) { return value.Idle; } string oath = Oaths.Active(); HashSet hashSet = new HashSet(); string text = Fingerprint(spellSegments); float num = Chant(spellSegments); List list = new List(); bool flag = true; while (flag) { flag = false; for (int num2 = staff.enchantments.Count - 1; num2 >= 0; num2--) { EnchantmentDefinition val = staff.enchantments[num2]; if (!hashSet.Contains(num2) && !((Object)(object)val == (Object)null) && SpellContent.TryGetSpell(val, out var key) && ContentBootstrap.Catalog.TryGet(key, out var definition) && definition != null) { hashSet.Add(num2); SpellSegments segments = Compile(staff, oath, hashSet); if (Fingerprint(segments) != text) { hashSet.Remove(num2); } else { float num3 = Chant(segments); list.Add(new IdleRow(num2, key, definition.DisplayName, ReasonFor(definition, Math.Abs(num3 - num) > 0.05f))); num = num3; flag = true; } } } } list.Sort(delegate(IdleRow a, IdleRow b) { int index = a.Index; return index.CompareTo(b.Index); }); value.Idle = list; return list; } private static string ReasonFor(SpellDefinition spell, bool onlyChant) { if (onlyChant) { return SpellText.Get("idle.chant", "a chant that strengthens nothing"); } return spell.Category switch { SpellCategory.Transform => SpellText.Get("idle.modifier", "it changes nothing that is cast"), SpellCategory.Payload => SpellText.Get("idle.trigger", "it triggers nothing"), SpellCategory.Segment => SpellText.Get("idle.segment", "it splits off no part that casts"), _ => SpellText.Get("idle.other", "left out, see the lines above"), }; } private static string Fingerprint(SpellSegments segments) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < segments.Plans.Count; i++) { CastPlan castPlan = segments.Plans[i]; stringBuilder.Append('[').Append(castPlan.TotalCost.ToString("R", CultureInfo.InvariantCulture)).Append(' ') .Append(castPlan.BloodCost.ToString("R", CultureInfo.InvariantCulture)) .Append(' ') .Append(castPlan.Targeting) .Append(' ') .Append(castPlan.Flags & ~CastFlags.Stands) .Append(' ') .Append(castPlan.Truncated); for (int j = 0; j < castPlan.Emissions.Count; j++) { Dump(stringBuilder, castPlan.Emissions[j], 0); } for (int k = 0; k < castPlan.Payloads.Count; k++) { PayloadPlan payloadPlan = castPlan.Payloads[k]; stringBuilder.Append(" {").Append(payloadPlan.Depth).Append(' ') .Append(payloadPlan.Trigger) .Append(' ') .Append(payloadPlan.ChargedCost.ToString("R", CultureInfo.InvariantCulture)); for (int l = 0; l < payloadPlan.Emissions.Count; l++) { Dump(stringBuilder, payloadPlan.Emissions[l], 0); } stringBuilder.Append('}'); } stringBuilder.Append(']'); } return stringBuilder.ToString(); } private static void Dump(StringBuilder sb, object value, int depth) { if (value == null) { sb.Append(" null"); return; } Type type = value.GetType(); if (depth > 4 || type.IsPrimitive || type.IsEnum || value is string || value is decimal) { sb.Append(' ').Append((value is IFormattable formattable) ? formattable.ToString(null, CultureInfo.InvariantCulture) : value.ToString()); return; } if (!FieldsOf.TryGetValue(type, out var value2)) { value2 = type.GetFields(BindingFlags.Instance | BindingFlags.Public); FieldsOf[type] = value2; } if (value2.Length == 0) { sb.Append(' ').Append(value); return; } sb.Append(" ("); for (int i = 0; i < value2.Length; i++) { Dump(sb, value2[i].GetValue(value), depth + 1); } sb.Append(')'); } private static bool SameRows(EnchantmentDefinition[] cached, List now) { if (cached == null || now == null || cached.Length != now.Count) { return false; } for (int i = 0; i < cached.Length; i++) { if (cached[i] != now[i]) { return false; } } return true; } private static float Chant(SpellSegments segments) { float num = 0f; for (int i = 0; i < segments.Plans.Count; i++) { num += segments.Plans[i].CastTime; } return num; } public static void Invalidate() { _generation++; } public static SpellSegments For(InventoryItem staff) { if ((Object)(object)staff == (Object)null || !SpellContent.IsStaff(staff.itemDefinition)) { return null; } string text = Oaths.Active(); CachedPlan value = Cache.GetValue(staff, (InventoryItem _) => new CachedPlan()); if (value.Version == _generation && value.Plan != null && value.Oath == text && SameRows(value.Rows, staff.enchantments)) { return value.Plan; } value.Plan = Compile(staff, text); value.Version = _generation; value.Oath = text; value.Rows = staff.enchantments.ToArray(); value.Idle = null; return value.Plan; } internal static SpellSegments CompileWith(InventoryItem staff, SpellDefinition extra) { if (!((Object)(object)staff == (Object)null)) { return Compile(staff, Oaths.Active(), null, extra); } return null; } internal static bool SameEffect(SpellSegments a, SpellSegments b, out bool chantDiffers) { chantDiffers = a != null && b != null && Math.Abs(Chant(a) - Chant(b)) > 0.05f; if (a != null && b != null) { return Fingerprint(a) == Fingerprint(b); } return false; } internal static string IdleReason(SpellDefinition spell, bool onlyChant) { return ReasonFor(spell, onlyChant); } internal static float TotalCost(SpellSegments segments) { float num = 0f; for (int i = 0; i < segments.Plans.Count; i++) { num += segments.Plans[i].TotalCost; } return num; } internal static float ChantOf(SpellSegments segments) { return Chant(segments); } private static SpellSegments Compile(InventoryItem staff, string oath, HashSet skip = null, SpellDefinition extra = null) { StaffDefinition staffDefinition = StaffDefinitions.Of(staff); if (staffDefinition.HandSlots > 0) { return CompileHands(staff, oath, staffDefinition, extra); } List list = new List(staff.enchantments.Count); for (int i = 0; i < staff.enchantments.Count; i++) { EnchantmentDefinition val = staff.enchantments[i]; if ((skip == null || !skip.Contains(i)) && !((Object)(object)val == (Object)null) && SpellContent.TryGetSpell(val, out var key) && ContentBootstrap.Catalog.TryGet(key, out var definition) && definition != null) { list.Add(definition); } } if (extra != null) { list.Add(extra); } return SpellSegments.Compile(WithLockedRows(WithOathRows(list, oath), staffDefinition), ContentBootstrap.Catalog); } private static SpellSegments CompileHands(InventoryItem staff, string oath, StaffDefinition kind, SpellDefinition extra = null) { List list = new List(staff.enchantments.Count + 1); List list2 = new List(staff.enchantments.Count + 1); int num = -1; int num2 = staff.enchantments.Count + ((extra != null) ? 1 : 0); for (int i = 0; i < num2; i++) { SpellDefinition definition = null; if (i < staff.enchantments.Count) { EnchantmentDefinition val = staff.enchantments[i]; if ((Object)(object)val == (Object)null || !SpellContent.TryGetSpell(val, out var key) || !ContentBootstrap.Catalog.TryGet(key, out definition)) { continue; } } else { definition = extra; } if (definition == null) { continue; } if (definition.Category == SpellCategory.Segment) { if (num < 0) { num = list.Count; } } else { list.Add(definition); list2.Add(i); } } List list3 = new List(kind.HandSlots); List list4 = new List(kind.HandSlots); for (int j = 0; j < list.Count; j++) { (((num >= 0) ? (j < num) : (list2[j] < kind.HandSlots)) ? list3 : list4).Add(list[j]); } int dropped = Trim(list3, kind.HandSlots) + Trim(list4, kind.HandSlots); return SpellSegments.CompileHands(WithLockedRows(WithOathRows(list3, oath), kind), WithLockedRows(WithOathRows(list4, oath), kind), ContentBootstrap.Catalog, dropped, kind.HandSlots); } private static int Trim(List hand, int most) { int num = hand.Count - most; if (num <= 0) { return 0; } hand.RemoveRange(most, num); return num; } internal static List WithOathRows(List program, string oath) { string text = Oaths.RowOf(oath); if (text == null || !ContentBootstrap.Catalog.TryGet(new SpellKey(text), out var definition) || definition == null) { return program; } List list = new List(program.Count + 2); bool flag = false; for (int i = 0; i < program.Count; i++) { if (program[i] != null && program[i].Category == SpellCategory.Segment) { if (flag) { list.Add(definition); } flag = false; } else if (program[i] != null) { flag = true; } list.Add(program[i]); } if (flag) { list.Add(definition); } return list; } internal static List WithLockedRows(List program, StaffDefinition kind) { if (kind == null || string.IsNullOrEmpty(kind.LockedRow) || !ContentBootstrap.Catalog.TryGet(new SpellKey(kind.LockedRow), out var definition) || definition == null) { return program; } List list = new List(program.Count + 4); for (int i = 0; i < program.Count; i++) { SpellDefinition spellDefinition = program[i]; if (spellDefinition != null && (spellDefinition.Category == SpellCategory.Payload || spellDefinition.Category == SpellCategory.Segment)) { list.Add(definition); } list.Add(spellDefinition); } list.Add(definition); return list; } } internal sealed class StaffRowDrag : MonoBehaviour, IBeginDragHandler, IEventSystemHandler, IDragHandler, IEndDragHandler { private const string HeldMarker = ""; private static StaffRowDrag _dragging; private InventoryItem _staff; private int _index; private bool _movable; private int _boundary = -1; private TextMeshProUGUI _label; private string _restingText; private bool _resting; internal void Bind(InventoryItem staff, int index, bool movable) { _staff = staff; _index = index; _movable = movable; if ((Object)(object)_label == (Object)null) { ItemDescriptionText component = ((Component)this).GetComponent(); _label = (((Object)(object)component != (Object)null) ? component.textComp : ((Component)this).GetComponentInChildren()); } if ((Object)(object)_label != (Object)null) { _restingText = ((TMP_Text)_label).text; _resting = true; } } public void OnBeginDrag(PointerEventData eventData) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (_movable && !((Object)(object)_staff == (Object)null) && (int)eventData.button == 0) { _dragging = this; _boundary = -1; ShowHeld(); } } public void OnDrag(PointerEventData eventData) { //IL_000f: 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) if (!((Object)(object)_dragging != (Object)(object)this)) { if (StaffPanel.TryResolveBoundary(eventData.position, out var boundary, out var worldPoint)) { _boundary = boundary; Transform transform = ((Component)this).transform; StaffDropCaret.ShowAt((RectTransform)(object)((transform is RectTransform) ? transform : null), worldPoint); } else { _boundary = -1; StaffDropCaret.Hide(); } } } public void OnEndDrag(PointerEventData eventData) { if (!((Object)(object)_dragging != (Object)(object)this)) { _dragging = null; StaffDropCaret.Hide(); Restore(); if (_boundary >= 0) { StaffPanel.MoveToBoundary(_staff, _index, _boundary); } _boundary = -1; } } private void ShowHeld() { if ((Object)(object)_label != (Object)null && _resting) { ((TMP_Text)_label).text = "" + _restingText; } } private void Restore() { if ((Object)(object)_label != (Object)null && _resting) { ((TMP_Text)_label).text = _restingText; } } } } namespace UnholyRites.Spells { public struct Emission { public SpellKey Source; public ProjectileArchetype Archetype; public DeliverySpec Delivery; public FormationKind Formation; public int FormationIndex; public int FormationCount; public float Cost; public bool Raises; public float RaiseDelay; public bool Consumes; public int HitSlot; public int MissSlot; public int KillSlot; public int Kills; public float Carried; public int Hits; public int Pierces; public int Bounces; public float Push; } public sealed class PayloadPlan { public int Depth { get; } public PayloadTrigger Trigger { get; } public IReadOnlyList Emissions { get; } public float ChargedCost { get; } public int EmissionCount => Emissions.Count; public PayloadPlan(PayloadTrigger trigger, List emissions, float chargedCost, int depth = 1) { Trigger = trigger; Emissions = emissions; ChargedCost = chargedCost; Depth = depth; } } public sealed class CastPlan { private static readonly SpellKey[] NoProgram = new SpellKey[0]; private static readonly PayloadPlan[] NoPayloads = new PayloadPlan[0]; public static CastPlan Empty => new CastPlan(new List(), 0f, SpellText.Get("ui.nothing", "Nothing"), truncated: false); public IReadOnlyList Payloads { get; } public SpellKey[] Program { get; } public IReadOnlyList Emissions { get; } public ElementKind Element { get { if (Emissions.Count <= 0) { return ElementKind.None; } return Emissions[0].Archetype.Element; } } public bool Raises { get { for (int i = 0; i < Emissions.Count; i++) { if (Emissions[i].Raises) { return true; } } return false; } } public bool Consumes { get { for (int i = 0; i < Emissions.Count; i++) { if (Emissions[i].Consumes) { return true; } } return false; } } public float TotalCost { get; } public CastFlags Flags { get; } public float BloodCost { get; } public float ManaCost => TotalCost - BloodCost; public TargetingKind Targeting { get; } public float CastTime { get; } public bool IsRitual => CastTime > 0.05f; public bool IsBeam { get { if (Emissions.Count > 0) { return Emissions[0].Archetype.Channelled; } return false; } } public ProjectileArchetype BeamArchetype { get { if (Emissions.Count <= 0) { return default(ProjectileArchetype); } return Emissions[0].Archetype; } } public string Summary { get; } public bool Truncated { get; } public int EmissionCount => Emissions.Count; public CastPlan(List emissions, float totalCost, string summary, bool truncated, TargetingKind targeting = TargetingKind.Forward, float castTime = 0f, SpellKey[] program = null, IReadOnlyList payloads = null, float bloodCost = 0f, CastFlags flags = CastFlags.None) { Flags = flags; Emissions = emissions; TotalCost = totalCost; BloodCost = ((bloodCost < 0f) ? 0f : ((bloodCost > totalCost) ? totalCost : bloodCost)); Summary = summary; Truncated = truncated; Targeting = targeting; CastTime = castTime; Program = program ?? NoProgram; Payloads = payloads ?? NoPayloads; } } public sealed class SpellCatalog : ISpellSource { private readonly Dictionary _spells = new Dictionary(); public IEnumerable All => _spells.Values; public void Add(SpellDefinition definition) { if (definition != null && definition.Key.IsValid) { _spells[definition.Key] = definition; } } public bool TryGet(SpellKey key, out SpellDefinition definition) { return _spells.TryGetValue(key, out definition); } public SpellDefinition Get(string key) { _spells.TryGetValue(new SpellKey(key), out var value); return value; } public static SpellCatalog CreateSample() { SpellCatalog spellCatalog = new SpellCatalog(); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("fireball"), DisplayName = "Fireball", Category = SpellCategory.Projectile, BaseCost = 20f, Projectile = new ProjectileArchetype { Element = ElementKind.Fire, Motion = MotionKind.Straight, Collision = CollisionKind.Sphere, Visual = VisualKind.Motes, Damage = 20f, Speed = 30f, Scale = 0.4f, Lifetime = 4f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("frostbolt"), DisplayName = "Frostbolt", Category = SpellCategory.Projectile, BaseCost = 12f, Projectile = new ProjectileArchetype { Element = ElementKind.Frost, Motion = MotionKind.Straight, Collision = CollisionKind.Point, Visual = VisualKind.Motes, Damage = 12f, Speed = 45f, Scale = 0.25f, Lifetime = 3f, Mark = MarkKind.Chill, MarkAmount = 20f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("venom"), DisplayName = "Venom Flask", Category = SpellCategory.Projectile, BaseCost = 16f, Projectile = new ProjectileArchetype { Element = ElementKind.Poison, Motion = MotionKind.Arc, Collision = CollisionKind.Sphere, Visual = VisualKind.Motes, Damage = 10f, Speed = 22f, Scale = 0.35f, Lifetime = 5f, Mark = MarkKind.Poison, MarkAmount = 12f, Spill = 3 } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("meteor"), DisplayName = "Meteor", Category = SpellCategory.Projectile, BaseCost = 120f, Projectile = new ProjectileArchetype { Element = ElementKind.Explosive, Bursts = true, Motion = MotionKind.Arc, Collision = CollisionKind.Sphere, Visual = VisualKind.Cluster, Damage = 80f, Speed = 18f, Scale = 1.4f, Lifetime = 8f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("sigil"), DisplayName = "Withering Sigil", Category = SpellCategory.Projectile, BaseCost = 60f, Targeting = TargetingKind.Point, CastTime = 0.8f, Delivery = new DeliverySpec { Kind = DeliveryKind.Anchored }, Projectile = new ProjectileArchetype { Element = ElementKind.Dark, Collision = CollisionKind.Sphere, Visual = VisualKind.Cluster, Pattern = VoxelPattern.Sigil, Damage = 12f, Scale = 3.2f, Lifetime = 9f, TickInterval = 0.6f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("skyfall"), DisplayName = "Skyfall", Category = SpellCategory.Transform, Targeting = TargetingKind.Point, CastTime = 0.6f, Transform = new TransformSpec { Kind = TransformKind.Deliver, Delivery = DeliveryKind.Descend, ArrivalDelay = 1f, ArrivalHeight = 28f, CostMultiplier = 1.35f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("ritual"), DisplayName = "Ritual", Category = SpellCategory.Transform, CastTime = 2.5f, Transform = new TransformSpec { Kind = TransformKind.Amplify, DamageMultiplier = 2.2f, ScaleMultiplier = 1.4f, SpeedMultiplier = 1f, CostMultiplier = 1f, SparesBeams = true, Stand = true } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("split"), DisplayName = "Split", Category = SpellCategory.Transform, Transform = new TransformSpec { Kind = TransformKind.Multiply, MultiplyFactor = 2, CostMultiplier = 1f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("empower"), DisplayName = "Empower", Category = SpellCategory.Transform, Transform = new TransformSpec { Kind = TransformKind.Amplify, DamageMultiplier = 1.6f, ScaleMultiplier = 1.25f, SpeedMultiplier = 1f, CostMultiplier = 1.5f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("onhit"), DisplayName = "On Hit", Category = SpellCategory.Payload, Payload = new PayloadSpec { Trigger = PayloadTrigger.OnHit, CostMultiplier = 1f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("onmiss"), DisplayName = "On Miss", Category = SpellCategory.Payload, Payload = new PayloadSpec { Trigger = PayloadTrigger.OnMiss, CostMultiplier = 1f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("onkill"), DisplayName = "On Kill", Category = SpellCategory.Payload, Payload = new PayloadSpec { Trigger = PayloadTrigger.OnKill, CostMultiplier = 1f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("catalyst"), DisplayName = "Catalyst", Category = SpellCategory.Flag, Flag = CastFlags.Catalyst }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("stake"), DisplayName = "Sigil Stake", Category = SpellCategory.Projectile, Internal = true, BaseCost = 0f, Targeting = TargetingKind.Point, Delivery = new DeliverySpec { Kind = DeliveryKind.Anchored }, Projectile = new ProjectileArchetype { Element = ElementKind.Holy, Collision = CollisionKind.None, Visual = VisualKind.Cluster, Pattern = VoxelPattern.Sigil, Damage = 0f, Scale = 0.8f, Lifetime = 20f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("vial"), DisplayName = "Sealed Vial", Category = SpellCategory.Projectile, Internal = true, BaseCost = 0f, Projectile = new ProjectileArchetype { Element = ElementKind.Holy, Motion = MotionKind.Arc, Collision = CollisionKind.Sphere, Visual = VisualKind.Motes, Damage = 0f, Speed = 20f, Scale = 0.3f, Lifetime = 5f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("nail"), DisplayName = "Nail", Category = SpellCategory.Flag, Flag = CastFlags.Nail }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("vigil"), DisplayName = "Vigil", Category = SpellCategory.Flag, Flag = CastFlags.Vigil }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("bloodrite"), DisplayName = "Blood Rite", Category = SpellCategory.Flag, Flag = CastFlags.BloodRite }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("spare"), DisplayName = "Spare", Category = SpellCategory.Flag, Flag = CastFlags.Spare }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("stitch"), DisplayName = "Stitch", Category = SpellCategory.Flag, Flag = CastFlags.Stitch }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("blood"), DisplayName = "Blood Price", Category = SpellCategory.Transform, Transform = new TransformSpec { Kind = TransformKind.Blood, CostMultiplier = 1f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("radiance"), DisplayName = "Radiance", Category = SpellCategory.Projectile, BaseCost = 35f, Delivery = new DeliverySpec { Kind = DeliveryKind.Anchored }, Projectile = new ProjectileArchetype { Element = ElementKind.Holy, Collision = CollisionKind.Sphere, Visual = VisualKind.Cluster, Pattern = VoxelPattern.Burst, Damage = 0f, Scale = 9f, Lifetime = 0.6f, TickInterval = 0.2f, Mark = MarkKind.Blind, MarkAmount = 10f, MarkOnly = true, AtCaster = true, FlashesCaster = 1.5f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("sanctuary"), DisplayName = "Sanctuary", Category = SpellCategory.Projectile, BaseCost = 45f, Targeting = TargetingKind.Point, CastTime = 0.6f, Delivery = new DeliverySpec { Kind = DeliveryKind.Anchored }, Projectile = new ProjectileArchetype { Element = ElementKind.Holy, Collision = CollisionKind.Sphere, Visual = VisualKind.Cluster, Pattern = VoxelPattern.Sigil, Damage = 0f, Scale = 3f, Lifetime = 8f, TickInterval = 0.5f, Mark = MarkKind.Fear, MarkAmount = 40f, MarkOnly = true } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("stone"), DisplayName = "Stone Seal", Category = SpellCategory.Projectile, BaseCost = 40f, Projectile = new ProjectileArchetype { Element = ElementKind.Holy, Motion = MotionKind.Straight, Collision = CollisionKind.Point, Visual = VisualKind.Motes, Damage = 1f, Speed = 35f, Scale = 0.3f, Lifetime = 3f, Mark = MarkKind.Stone, MarkAmount = 10f, Alone = true } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("hex"), DisplayName = "Hex", Category = SpellCategory.Projectile, BaseCost = 20f, Projectile = new ProjectileArchetype { Element = ElementKind.Dark, Motion = MotionKind.Straight, Collision = CollisionKind.Point, Visual = VisualKind.Motes, Damage = 6f, Speed = 40f, Scale = 0.25f, Lifetime = 3f, Mark = MarkKind.Hex, MarkAmount = 100f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("brand"), DisplayName = "Brand", Category = SpellCategory.Projectile, BaseCost = 18f, Projectile = new ProjectileArchetype { Element = ElementKind.Holy, Motion = MotionKind.Straight, Collision = CollisionKind.Point, Visual = VisualKind.Motes, Damage = 6f, Speed = 45f, Scale = 0.25f, Lifetime = 3f, Mark = MarkKind.Brand, MarkAmount = 35f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("next"), DisplayName = "Next", Category = SpellCategory.Segment }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("concussion"), DisplayName = "Concussion", Category = SpellCategory.Transform, Transform = new TransformSpec { Kind = TransformKind.Knockback, Push = 1, CostMultiplier = 1f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("gather"), DisplayName = "Gather", Category = SpellCategory.Transform, Transform = new TransformSpec { Kind = TransformKind.Knockback, Push = -1, CostMultiplier = 1f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("pierce"), DisplayName = "Pierce", Category = SpellCategory.Transform, Transform = new TransformSpec { Kind = TransformKind.Pierce, CostMultiplier = 1f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("bounce"), DisplayName = "Bounce", Category = SpellCategory.Transform, Transform = new TransformSpec { Kind = TransformKind.Bounce, CostMultiplier = 1f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("pulse"), DisplayName = "Pulse", Category = SpellCategory.Transform, Transform = new TransformSpec { Kind = TransformKind.Pulse, CostMultiplier = 1f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("else"), DisplayName = "Else", Category = SpellCategory.Payload, Payload = new PayloadSpec { Otherwise = true, CostMultiplier = 1f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("raise"), DisplayName = "Raise", Category = SpellCategory.Transform, Transform = new TransformSpec { Kind = TransformKind.Raise, RaiseDelay = 0.9f, CostMultiplier = 1.9f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("grave_goods"), DisplayName = "Grave Goods", Category = SpellCategory.Transform, Transform = new TransformSpec { Kind = TransformKind.Sacrifice, CostMultiplier = 1.15f } }); spellCatalog.Add(new SpellDefinition { Key = new SpellKey("lightning"), DisplayName = "Lightning", Category = SpellCategory.Projectile, BaseCost = 34f, Projectile = new ProjectileArchetype { Element = ElementKind.Electric, Collision = CollisionKind.Sphere, Visual = VisualKind.Motes, Pattern = VoxelPattern.Beam, Channelled = true, Damage = 12f, TickInterval = 0.2f, Reach = 20f, Scale = 0.45f, Mark = MarkKind.Shock, MarkAmount = 45f } }); return spellCatalog; } } public interface ISpellSource { bool TryGet(SpellKey key, out SpellDefinition definition); } public static class SpellCompiler { private struct Branches { public int HitSlot; public float HitCost; public float HitBlood; public int MissSlot; public float MissCost; public float MissBlood; public int KillSlot; public float KillCost; public float KillBlood; } private sealed class Phase { public readonly List Spells = new List(); public PayloadTrigger Trigger; public int Parent = -1; public int HitChild = -1; public int MissChild = -1; public int KillChild = -1; public bool Dropped; public float CostMultiplier; public readonly List Working = new List(); public float CastTime; public TargetingKind Targeting; public bool Stands; public int Child(PayloadTrigger trigger) { return trigger switch { PayloadTrigger.OnHit => HitChild, PayloadTrigger.OnKill => KillChild, _ => MissChild, }; } public void SetChild(PayloadTrigger trigger, int index) { switch (trigger) { case PayloadTrigger.OnHit: HitChild = index; break; case PayloadTrigger.OnKill: KillChild = index; break; default: MissChild = index; break; } } public void Collect(SpellDefinition spell) { CastTime += ((spell.CastTime > 0f) ? spell.CastTime : 0f); Stands |= spell.Category == SpellCategory.Transform && spell.Transform.Stand; if (spell.Targeting > Targeting) { Targeting = spell.Targeting; } } public void CollectSurvivors() { HashSet hashSet = new HashSet(); for (int i = 0; i < Working.Count; i++) { if (hashSet.Add(Working[i].Slot)) { Collect(Spells[Working[i].Slot]); } } } } private struct Omitted { public int FromBeam; public int BeamsInPayloads; public bool PayloadsBehindBeam; public bool CutOffBehindEmpty; public bool HitThatCannotHappen; public bool MissThatCannotHappen; public bool UnpairedElse; public int NotAlone; public bool Any { get { if (FromBeam <= 0 && BeamsInPayloads <= 0 && !PayloadsBehindBeam && !CutOffBehindEmpty && !HitThatCannotHappen && !MissThatCannotHappen && !UnpairedElse) { return NotAlone > 0; } return true; } } } private struct WorkingEmission { public int Slot; public SpellKey Source; public ProjectileArchetype Archetype; public DeliverySpec Delivery; public FormationKind Formation; public float BaseCost; public float CostMultiplier; public bool Raises; public float RaiseDelay; public bool Consumes; public bool Blood; public bool Stood; public int Pulses; public int Pierces; public int Bounces; public bool Pushes; public bool Pulls; public bool PushFirst; } private struct SummaryRow { public SpellKey Source; public FormationKind Formation; public MotionKind Motion; public DeliveryKind Delivery; public float Damage; public int Count; public MarkKind Mark; public float MarkAmount; public int Spill; public bool Bursts; public int Hits; public int Pierces; public int Bounces; public float Push; public bool Raises; public bool Consumes; public float TickInterval; public bool Matches(Emission e) { if (Source == e.Source && TickInterval == e.Archetype.TickInterval && Formation == e.Formation && Motion == e.Archetype.Motion && Delivery == e.Delivery.Kind && Damage == e.Archetype.Damage && Mark == e.Archetype.Mark && MarkAmount == e.Archetype.MarkAmount && Spill == e.Archetype.Spill && Bursts == e.Archetype.Bursts && Hits == e.Hits && Pierces == e.Pierces && Bounces == e.Bounces && Push == e.Push && Raises == e.Raises) { return Consumes == e.Consumes; } return false; } } public const int MaxEmissions = 512; public const int MaxGroundHits = 4; public const int PierceCount = 2; public const float PierceFalloff = 0.7f; public const float PierceSurcharge = 1.2f; public const int BounceCount = 2; public const float BounceSurcharge = 1.2f; public const float KnockbackPower = 6f; public const float KnockbackSurcharge = 1.15f; public const float DefaultArrivalDelay = 1f; public const float DefaultArrivalHeight = 26f; public const float DefaultRaiseDelay = 0.9f; public const float RaiseAfterglow = 1.1f; private const long MaxReportedPotential = 1000000L; public static CastPlan Compile(IReadOnlyList program, ISpellSource spells) { if (program == null || program.Count == 0) { return CastPlan.Empty; } bool truncated = false; Omitted omitted = default(Omitted); CastFlags flags = CastFlags.None; List list = Partition(program, ref omitted, ref flags); for (int i = 0; i < list.Count; i++) { BuildPhase(list[i], spells, ref truncated); omitted.NotAlone += LeaveOutNotAlone(list[i].Working, i == 0); } bool flag = AnyChannelled(list[0].Working); if (flag) { omitted.FromBeam = list[0].Working.RemoveAll((WorkingEmission e) => !e.Archetype.Channelled); for (int num = 1; num < list.Count; num++) { omitted.PayloadsBehindBeam |= list[num].Spells.Count > 0; list[num].Dropped = true; } } else { for (int num2 = 1; num2 < list.Count; num2++) { Phase phase = list[num2]; Phase phase2 = list[phase.Parent]; if (phase2.Dropped) { phase.Dropped = true; continue; } omitted.BeamsInPayloads += phase.Working.RemoveAll((WorkingEmission e) => e.Archetype.Channelled); if (phase.Working.Count == 0) { phase.Dropped = true; omitted.CutOffBehindEmpty |= phase.HitChild >= 0 || phase.MissChild >= 0 || phase.KillChild >= 0; } else if (!AnyCanTake(phase2.Working, phase.Trigger)) { phase.Dropped = true; if (phase.Trigger != PayloadTrigger.OnMiss) { omitted.HitThatCannotHappen = true; } else { omitted.MissThatCannotHappen = true; } } } } for (int num3 = 0; num3 < list.Count; num3++) { if (!list[num3].Dropped) { list[num3].CollectSurvivors(); } } if (StandsIn(list, 0)) { flags |= CastFlags.Stands; } float castTime = Chant(list, 0); TargetingKind targeting = list[0].Targeting; int[] array = new int[list.Count]; List list2 = new List(); for (int num4 = 1; num4 < list.Count; num4++) { if (!list[num4].Dropped) { list2.Add(num4); array[num4] = list2.Count; } } float[] array2 = new float[list.Count]; float[] array3 = new float[list.Count]; PayloadPlan[] array4 = new PayloadPlan[list2.Count]; for (int num5 = list2.Count - 1; num5 >= 0; num5--) { int num6 = list2[num5]; Phase phase3 = list[num6]; float total; float blood; List emissions = Resolve(phase3.Working, BranchesOf(list, phase3, array, array2, array3), out total, out blood); array2[num6] = Positive(phase3.CostMultiplier) * total; array3[num6] = Positive(phase3.CostMultiplier) * blood; array4[num5] = new PayloadPlan(phase3.Trigger, emissions, array2[num6], DepthOf(list, num6)); } List list3 = new List(program.Count); for (int num7 = 0; num7 < program.Count; num7++) { if (program[num7] != null) { list3.Add(program[num7].Key); } } return Finish(list3.ToArray(), list[0].Working, array4, BranchesOf(list, list[0], array, array2, array3), MoreBelow(list, 0), truncated, spells, targeting, castTime, flag, omitted, flags); } private static int Budget(DeliverySpec delivery, ProjectileArchetype archetype, int pulses, int pierces, PayloadTrigger trigger) { bool flag = delivery.Kind == DeliveryKind.Anchored || (delivery.Kind == DeliveryKind.Descend && archetype.TickInterval > 0f); if (trigger == PayloadTrigger.OnHit || trigger == PayloadTrigger.OnKill) { if (!flag) { if (delivery.Kind != DeliveryKind.Projectile || archetype.Channelled || archetype.Bursts) { return 1; } return 1 + pierces; } if (!(archetype.TickInterval > 0f)) { return 0; } return Math.Min(1 + pulses, 4); } if (delivery.Kind != DeliveryKind.Descend || flag) { return 1; } return 0; } private static bool AnyCanTake(List carriers, PayloadTrigger trigger) { for (int i = 0; i < carriers.Count; i++) { if (Budget(carriers[i].Delivery, carriers[i].Archetype, carriers[i].Pulses, carriers[i].Pierces, trigger) > 0) { return true; } } return false; } private static Branches BranchesOf(List phases, Phase phase, int[] slotOf, float[] charged, float[] chargedBlood) { Branches result = default(Branches); if (phase.HitChild >= 0 && !phases[phase.HitChild].Dropped) { result.HitSlot = slotOf[phase.HitChild]; result.HitCost = charged[phase.HitChild]; result.HitBlood = chargedBlood[phase.HitChild]; } if (phase.MissChild >= 0 && !phases[phase.MissChild].Dropped) { result.MissSlot = slotOf[phase.MissChild]; result.MissCost = charged[phase.MissChild]; result.MissBlood = chargedBlood[phase.MissChild]; } if (phase.KillChild >= 0 && !phases[phase.KillChild].Dropped) { result.KillSlot = slotOf[phase.KillChild]; result.KillCost = charged[phase.KillChild]; result.KillBlood = chargedBlood[phase.KillChild]; } return result; } private static float Chant(List phases, int index) { Phase phase = phases[index]; return phase.CastTime + Math.Max(ChantOf(phases, phase.HitChild) + ChantOf(phases, phase.KillChild), ChantOf(phases, phase.MissChild)); } private static float ChantOf(List phases, int index) { if (index < 0 || phases[index].Dropped) { return 0f; } return Chant(phases, index); } private static long MoreBelow(List phases, int index) { Phase phase = phases[index]; long num = Through(phases, phase.HitChild); long num2 = Through(phases, phase.MissChild); long num3 = Through(phases, phase.KillChild); long num4 = 0L; for (int i = 0; i < phase.Working.Count; i++) { WorkingEmission workingEmission = phase.Working[i]; long num5 = Budget(workingEmission.Delivery, workingEmission.Archetype, workingEmission.Pulses, workingEmission.Pierces, PayloadTrigger.OnHit) * num; long val = Budget(workingEmission.Delivery, workingEmission.Archetype, workingEmission.Pulses, workingEmission.Pierces, PayloadTrigger.OnMiss) * num2; long num6 = Budget(workingEmission.Delivery, workingEmission.Archetype, workingEmission.Pulses, workingEmission.Pierces, PayloadTrigger.OnKill) * num3; num4 = Clamp(num4 + Math.Max(Clamp(num5 + num6), val)); } return num4; } private static long Through(List phases, int index) { if (index < 0 || phases[index].Dropped) { return 0L; } return Clamp(phases[index].Working.Count + MoreBelow(phases, index)); } private static int DepthOf(List phases, int index) { int num = 0; while (phases[index].Parent >= 0) { index = phases[index].Parent; num++; } return num; } private static int LeaveOutNotAlone(List working, bool carrierPhase) { Dictionary copies = null; for (int i = 0; i < working.Count; i++) { if (working[i].Archetype.Alone) { copies = copies ?? new Dictionary(); copies.TryGetValue(working[i].Slot, out var value); copies[working[i].Slot] = value + 1; } } if (copies == null) { return 0; } return working.RemoveAll((WorkingEmission e) => e.Archetype.Alone && (!carrierPhase || copies[e.Slot] > 1 || e.Delivery.Kind != DeliveryKind.Projectile || e.Archetype.Channelled)); } private static bool StandsIn(List phases, int index) { if (index < 0 || phases[index].Dropped) { return false; } Phase phase = phases[index]; if (phase.Stands) { return true; } float num = ChantOf(phases, phase.HitChild) + ChantOf(phases, phase.KillChild); float num2 = ChantOf(phases, phase.MissChild); if (!(num >= num2)) { return StandsIn(phases, phase.MissChild); } if (!StandsIn(phases, phase.HitChild)) { return StandsIn(phases, phase.KillChild); } return true; } private static bool AnyChannelled(List working) { for (int i = 0; i < working.Count; i++) { if (working[i].Archetype.Channelled) { return true; } } return false; } private static List Partition(IReadOnlyList program, ref Omitted omitted, ref CastFlags flags) { List list = new List { new Phase() }; int num = 0; bool flag = false; for (int i = 0; i < program.Count; i++) { SpellDefinition spellDefinition = program[i]; if (spellDefinition == null || spellDefinition.Category == SpellCategory.Segment) { continue; } if (spellDefinition.Category == SpellCategory.Flag) { flags |= spellDefinition.Flag; } else if (spellDefinition.Category == SpellCategory.Payload) { int num2 = (spellDefinition.Payload.Otherwise ? OpenOtherwise(list, num, spellDefinition) : OpenBranch(list, num, flag, spellDefinition)); if (num2 >= 0) { num = num2; flag = false; } else if (spellDefinition.Payload.Otherwise) { omitted.UnpairedElse = true; } } else { flag |= spellDefinition.Category == SpellCategory.Projectile; list[num].Spells.Add(spellDefinition); } } return list; } private static int OpenBranch(List phases, int current, bool currentHasProjectile, SpellDefinition spell) { Phase phase = phases[current]; if (!currentHasProjectile || phase.Child(spell.Payload.Trigger) >= 0) { return -1; } if (current == 0 && spell.Targeting > phase.Targeting) { phase.Targeting = spell.Targeting; } return Add(phases, current, spell.Payload.Trigger, spell); } private static int OpenOtherwise(List phases, int current, SpellDefinition spell) { Phase phase = phases[current]; if (phase.Parent < 0 || phase.Trigger == PayloadTrigger.OnKill) { return -1; } PayloadTrigger trigger = ((phase.Trigger == PayloadTrigger.OnHit) ? PayloadTrigger.OnMiss : PayloadTrigger.OnHit); if (phases[phase.Parent].Child(trigger) >= 0) { return -1; } return Add(phases, phase.Parent, trigger, spell); } private static int Add(List phases, int parent, PayloadTrigger trigger, SpellDefinition spell) { Phase item = new Phase { Parent = parent, Trigger = trigger, CostMultiplier = spell.Payload.CostMultiplier, CastTime = ((spell.CastTime > 0f) ? spell.CastTime : 0f) }; phases.Add(item); int num = phases.Count - 1; phases[parent].SetChild(trigger, num); return num; } private static void BuildPhase(Phase phase, ISpellSource source, ref bool truncated) { List spells = phase.Spells; List working = phase.Working; for (int i = 0; i < spells.Count; i++) { SpellDefinition spellDefinition = spells[i]; if (spellDefinition.Category == SpellCategory.Projectile) { if (working.Count >= 512) { truncated = true; continue; } working.Add(new WorkingEmission { Slot = i, Source = spellDefinition.Key, Archetype = spellDefinition.Projectile, Delivery = spellDefinition.Delivery, Formation = FormationKind.Single, BaseCost = spellDefinition.BaseCost, CostMultiplier = 1f }); } else { phase.Collect(spellDefinition); if (working.Count != 0) { ApplyTransform(spellDefinition, working, source, ref truncated); } } } } private static void ApplyTransform(SpellDefinition spell, List working, ISpellSource spells, ref bool truncated) { TransformSpec transform = spell.Transform; List list = null; switch (transform.Kind) { case TransformKind.Multiply: { int num2 = ((transform.MultiplyFactor <= 1) ? 1 : transform.MultiplyFactor); int count = working.Count; int num3 = count * num2; if (num3 > 512) { num3 = 512; truncated = true; } for (int num4 = count; num4 < num3; num4++) { working.Add(working[num4 % count]); } break; } case TransformKind.Amplify: { if (transform.SparesBeams) { list = new List(); } for (int num8 = 0; num8 < working.Count; num8++) { WorkingEmission value11 = working[num8]; if (transform.SparesBeams) { if (value11.Archetype.Channelled || (transform.Stand && value11.Stood)) { continue; } list.Add(num8); } if (transform.Stand) { value11.Stood = true; } value11.Archetype.Damage *= Positive(transform.DamageMultiplier); value11.Archetype.Scale *= Positive(transform.ScaleMultiplier); value11.Archetype.Speed *= Positive(transform.SpeedMultiplier); working[num8] = value11; } break; } case TransformKind.Convert: { if (spells == null || !spells.TryGet(transform.ConvertTarget, out var definition) || definition == null || definition.Category != SpellCategory.Projectile) { return; } for (int l = 0; l < working.Count; l++) { WorkingEmission value4 = working[l]; value4.Source = definition.Key; value4.Archetype = definition.Projectile; value4.Stood = false; value4.BaseCost = definition.BaseCost; working[l] = value4; } break; } case TransformKind.Knockback: { for (int num6 = 0; num6 < working.Count; num6++) { WorkingEmission value9 = working[num6]; if (transform.Push > 0 && !value9.Pushes) { value9.Pushes = true; value9.PushFirst = !value9.Pulls; } else if (transform.Push < 0 && !value9.Pulls) { value9.Pulls = true; } working[num6] = value9; } break; } case TransformKind.Bounce: { list = new List(); for (int n = 0; n < working.Count; n++) { WorkingEmission value6 = working[n]; if (value6.Bounces <= 0) { value6.Bounces = 2; working[n] = value6; list.Add(n); } } break; } case TransformKind.Pierce: { list = new List(); for (int j = 0; j < working.Count; j++) { WorkingEmission value2 = working[j]; if (value2.Pierces <= 0) { value2.Pierces = 2; working[j] = value2; list.Add(j); } } break; } case TransformKind.Pulse: { for (int num7 = 0; num7 < working.Count; num7++) { WorkingEmission value10 = working[num7]; value10.Pulses = Math.Min(value10.Pulses + 1, 3); working[num7] = value10; } break; } case TransformKind.Shape: { for (int num5 = 0; num5 < working.Count; num5++) { WorkingEmission value8 = working[num5]; value8.Formation = transform.Formation; working[num5] = value8; } break; } case TransformKind.Deliver: { for (int num = 0; num < working.Count; num++) { WorkingEmission value7 = working[num]; value7.Delivery.Kind = transform.Delivery; if (transform.Delivery == DeliveryKind.Descend) { value7.Delivery.ArrivalDelay = ((transform.ArrivalDelay > 0f) ? transform.ArrivalDelay : 1f); value7.Delivery.ArrivalHeight = ((transform.ArrivalHeight > 0f) ? transform.ArrivalHeight : 26f); } working[num] = value7; } break; } case TransformKind.Raise: { list = new List(); for (int m = 0; m < working.Count; m++) { WorkingEmission value5 = working[m]; if ((value5.Delivery.Kind == DeliveryKind.Anchored || value5.Delivery.Kind == DeliveryKind.Descend) && value5.Archetype.Element == ElementKind.Dark && !value5.Raises) { value5.Raises = true; value5.RaiseDelay = ((transform.RaiseDelay > 0f) ? transform.RaiseDelay : 0.9f); value5.Archetype.Pattern = VoxelPattern.Rise; value5.Archetype.Damage = 0f; value5.Archetype.TickInterval = 0f; value5.Archetype.Lifetime = value5.RaiseDelay + 1.1f; working[m] = value5; list.Add(m); } } break; } case TransformKind.Blood: { list = new List(); for (int k = 0; k < working.Count; k++) { WorkingEmission value3 = working[k]; if (!value3.Blood && !value3.Archetype.Channelled) { value3.Blood = true; working[k] = value3; list.Add(k); } } break; } case TransformKind.Sacrifice: { list = new List(); for (int i = 0; i < working.Count; i++) { WorkingEmission value = working[i]; if (value.Raises && !value.Consumes) { value.Consumes = true; working[i] = value; list.Add(i); } } break; } } ApplySurcharge(spell, working, list); } private static void ApplySurcharge(SpellDefinition spell, List working, List caught) { float num = Positive(spell.Transform.CostMultiplier); if (num == 1f) { return; } if (caught == null) { for (int i = 0; i < working.Count; i++) { WorkingEmission value = working[i]; value.CostMultiplier *= num; working[i] = value; } return; } for (int j = 0; j < caught.Count; j++) { int index = caught[j]; WorkingEmission value2 = working[index]; value2.CostMultiplier *= num; working[index] = value2; } } private static List Resolve(List working, Branches branches, out float total, out float blood) { Dictionary dictionary = new Dictionary(); for (int i = 0; i < working.Count; i++) { dictionary.TryGetValue(working[i].Formation, out var value); dictionary[working[i].Formation] = value + 1; } Dictionary dictionary2 = new Dictionary(); List list = new List(working.Count); total = 0f; blood = 0f; for (int j = 0; j < working.Count; j++) { WorkingEmission workingEmission = working[j]; dictionary2.TryGetValue(workingEmission.Formation, out var value2); dictionary2[workingEmission.Formation] = value2 + 1; bool flag = workingEmission.Pierces > 0 && workingEmission.Delivery.Kind == DeliveryKind.Projectile && !workingEmission.Archetype.Channelled && !workingEmission.Archetype.Bursts; bool flag2 = workingEmission.Pulls && workingEmission.Delivery.Kind != DeliveryKind.Projectile; int num = ((!(workingEmission.Archetype.Damage <= 0f)) ? ((workingEmission.Pushes && (!flag2 || workingEmission.PushFirst)) ? 1 : (flag2 ? (-1) : 0)) : 0); bool flag3 = workingEmission.Bounces > 0 && workingEmission.Delivery.Kind == DeliveryKind.Projectile && !workingEmission.Archetype.Channelled && !workingEmission.Archetype.Bursts && (workingEmission.Archetype.Motion == MotionKind.Straight || workingEmission.Archetype.Motion == MotionKind.Arc || workingEmission.Archetype.Motion == MotionKind.Homing); float num2 = workingEmission.BaseCost * workingEmission.CostMultiplier * (flag ? 1.2f : 1f) * (flag3 ? 1.2f : 1f) * ((num != 0) ? 1.15f : 1f); int num3 = Budget(workingEmission.Delivery, workingEmission.Archetype, workingEmission.Pulses, workingEmission.Pierces, PayloadTrigger.OnHit); int num4 = Budget(workingEmission.Delivery, workingEmission.Archetype, workingEmission.Pulses, workingEmission.Pierces, PayloadTrigger.OnMiss); int num5 = Budget(workingEmission.Delivery, workingEmission.Archetype, workingEmission.Pulses, workingEmission.Pierces, PayloadTrigger.OnKill); float num6 = (float)num3 * branches.HitCost; float num7 = (float)num4 * branches.MissCost; float num8 = ((branches.KillSlot > 0) ? ((float)num5 * branches.KillCost) : 0f); float num9 = Math.Max(num6, num7) + num8; total += num2 + num9; if (workingEmission.Blood) { blood += num2 + num9; } else if (num9 > 0f) { blood += ((num6 >= num7) ? ((float)num3 * branches.HitBlood) : ((float)num4 * branches.MissBlood)); if (num8 > 0f) { blood += (float)num5 * branches.KillBlood; } } list.Add(new Emission { Source = workingEmission.Source, Archetype = workingEmission.Archetype, Delivery = workingEmission.Delivery, Formation = workingEmission.Formation, FormationIndex = value2, FormationCount = dictionary[workingEmission.Formation], Cost = num2, Carried = num9, HitSlot = ((num3 > 0) ? branches.HitSlot : 0), Hits = ((num3 > 0 && branches.HitSlot > 0) ? num3 : 0), Pierces = (flag ? workingEmission.Pierces : 0), Bounces = (flag3 ? workingEmission.Bounces : 0), Push = (float)num * 6f, MissSlot = ((num4 > 0) ? branches.MissSlot : 0), KillSlot = ((num5 > 0) ? branches.KillSlot : 0), Kills = ((num5 > 0 && branches.KillSlot > 0) ? num5 : 0), Raises = workingEmission.Raises, RaiseDelay = workingEmission.RaiseDelay, Consumes = workingEmission.Consumes }); } return list; } private static CastPlan Finish(SpellKey[] keys, List working, PayloadPlan[] payloads, Branches branches, long potential, bool truncated, ISpellSource spells, TargetingKind targeting, float castTime, bool beam, Omitted omitted, CastFlags flags) { if (working.Count == 0) { if (!omitted.Any) { return CastPlan.Empty; } StringBuilder stringBuilder = new StringBuilder(SpellText.Get("ui.nothing", "Nothing")); AppendOmitted(stringBuilder, omitted); return new CastPlan(new List(), 0f, stringBuilder.ToString(), truncated: false); } float total; float blood; List emissions = Resolve(working, branches, out total, out blood); return new CastPlan(summary: BuildSummary(emissions, payloads, potential, total, truncated, spells, targeting, castTime, beam, omitted, blood), emissions: emissions, totalCost: total, truncated: truncated, targeting: targeting, castTime: castTime, program: keys, payloads: payloads, bloodCost: blood, flags: flags); } private static string BuildSummary(List emissions, PayloadPlan[] payloads, long potential, float totalCost, bool truncated, ISpellSource spells, TargetingKind targeting, float castTime, bool beam, Omitted omitted, float bloodCost) { StringBuilder stringBuilder = new StringBuilder(); AppendRows(stringBuilder, emissions, spells, 0, null, beam); for (int i = 0; i < payloads.Length; i++) { AppendRows(stringBuilder, payloads[i].Emissions, spells, payloads[i].Depth, payloads[i].Trigger, beam: false); } StringBuilder stringBuilder2 = new StringBuilder(); stringBuilder2.Append(SpellText.Get("ui.total", "Total")).Append(SpellText.Colon).Append(emissions.Count.ToString(CultureInfo.InvariantCulture)) .Append(' ') .Append(SpellText.Get("ui.emissions", (emissions.Count == 1) ? "effect" : "effects")); if (potential > 0) { stringBuilder2.Append(SpellText.Sep).Append(SpellText.Get("ui.trigger_more_before", "up to")).Append(' ') .Append(potential.ToString(CultureInfo.InvariantCulture)) .Append(' ') .Append(SpellText.Get("ui.trigger_more_after", "more once triggered")); } stringBuilder2.Append(SpellText.Sep).Append(totalCost.ToString("0.#", CultureInfo.InvariantCulture)).Append(' ') .Append(beam ? SpellText.Get("ui.mana_per_second", "mana per second held") : SpellText.Get("ui.mana", "mana")); if (bloodCost > 0f) { stringBuilder2.Append(SpellText.OpenParen).Append(SpellText.Get("ui.paid_in_blood_before", string.Empty)).Append(bloodCost.ToString("0.#", CultureInfo.InvariantCulture)) .Append(' ') .Append(SpellText.Get("ui.paid_in_blood_after", "mana of it paid in health")) .Append(SpellText.CloseParen); } if (truncated) { stringBuilder2.Append(SpellText.OpenParen).Append(SpellText.Get("ui.capped", "capped at")).Append(' ') .Append(512.ToString(CultureInfo.InvariantCulture)) .Append(SpellText.CloseParen); } if (castTime > 0.05f) { stringBuilder2.Append('\n').Append(SpellText.Get("ui.cast_time", "Cast time")).Append(SpellText.Colon) .Append(castTime.ToString("0.#", CultureInfo.InvariantCulture)) .Append(SpellText.Get("ui.seconds", "s")); } if (targeting == TargetingKind.Point) { stringBuilder2.Append((castTime > 0.05f) ? SpellText.Sep : "\n").Append(SpellText.Get("ui.targeting_point", "aimed at a point on the ground")); } stringBuilder2.Append('\n').Append(stringBuilder.ToString().TrimEnd(new char[1] { '\n' })); AppendOmitted(stringBuilder2, omitted); return stringBuilder2.ToString(); } private static void AppendOmitted(StringBuilder sb, Omitted omitted) { if (omitted.Any) { if (omitted.FromBeam > 0) { sb.Append('\n').Append(Format("ui.omitted_from_beam", (omitted.FromBeam == 1) ? "Left out, because a beam is held rather than fired: {0} effect" : "Left out, because a beam is held rather than fired: {0} effects", omitted.FromBeam)); } if (omitted.PayloadsBehindBeam) { sb.Append('\n').Append(SpellText.Get("ui.beam_no_payload", "A beam can't carry spells: everything after On Hit, On Miss or On Kill is left out")); } if (omitted.BeamsInPayloads > 0) { sb.Append('\n').Append(Format("ui.omitted_payload_beam", (omitted.BeamsInPayloads == 1) ? "Left out, because a carried beam can't be held: {0} beam" : "Left out, because a carried beam can't be held: {0} beams", omitted.BeamsInPayloads)); } if (omitted.NotAlone > 0) { sb.Append('\n').Append(SpellText.Get("ui.not_alone", "Left out and not charged: Stone Seal only works on its own, not split, called down, carried or in a beam")); } if (omitted.UnpairedElse) { sb.Append('\n').Append(SpellText.Get("ui.unpaired_else", "An Else with no On Hit or On Miss before it to pair with does nothing; the spells after it stay where they are")); } if (omitted.HitThatCannotHappen) { sb.Append('\n').Append(SpellText.Get("ui.omitted_hit_on_ground", "Left out and not charged: On Hit behind a ground sigil that deals no damage (such as a raising sigil) can never trigger")); } if (omitted.MissThatCannotHappen) { sb.Append('\n').Append(SpellText.Get("ui.omitted_miss_from_above", "Left out and not charged: On Miss behind something called down can never trigger, because it always lands")); } if (omitted.CutOffBehindEmpty) { sb.Append('\n').Append(SpellText.Get("ui.cut_off_behind_empty", "A trigger with nothing left to carry casts nothing, so the spells inscribed after it are left out too")); } } } private static string Percent(float fraction) { return Math.Round(fraction * 100f).ToString(CultureInfo.InvariantCulture); } private static string Format(string key, string fallback, params object[] values) { return string.Format(CultureInfo.InvariantCulture, SpellText.Get(key, fallback), values); } private static void AppendRows(StringBuilder sb, IReadOnlyList emissions, ISpellSource spells, int depth, PayloadTrigger? trigger, bool beam) { List list = new List(); for (int i = 0; i < emissions.Count; i++) { Emission e = emissions[i]; bool flag = false; for (int j = 0; j < list.Count; j++) { if (list[j].Matches(e)) { SummaryRow value = list[j]; value.Count++; list[j] = value; flag = true; break; } } if (!flag) { list.Add(new SummaryRow { Source = e.Source, Formation = e.Formation, Damage = e.Archetype.Damage, Mark = e.Archetype.Mark, MarkAmount = e.Archetype.MarkAmount, Spill = e.Archetype.Spill, Bursts = e.Archetype.Bursts, Hits = e.Hits, Pierces = e.Pierces, Bounces = e.Bounces, Push = e.Push, Motion = e.Archetype.Motion, Delivery = e.Delivery.Kind, Raises = e.Raises, Consumes = e.Consumes, TickInterval = e.Archetype.TickInterval, Count = 1 }); } } for (int k = 0; k < list.Count; k++) { SummaryRow summaryRow = list[k]; sb.Append(' ', depth * 2); if (trigger.HasValue) { sb.Append(SpellText.TriggerEach(trigger.Value)).Append(SpellText.Colon); } sb.Append(SpellText.Count(summaryRow.Count, SpellText.Spell(summaryRow.Source, DisplayNameOf(summaryRow.Source, spells)))); if (summaryRow.Formation != FormationKind.Single) { sb.Append(SpellText.OpenParen).Append(SpellText.Formation(summaryRow.Formation)).Append(SpellText.CloseParen); } if (trigger.HasValue) { sb.Append(SpellText.Sep).Append(PayloadOrigin(summaryRow.Delivery)); if (summaryRow.Delivery == DeliveryKind.Projectile && summaryRow.Motion != MotionKind.Straight) { sb.Append(SpellText.Sep).Append(SpellText.Motion(summaryRow.Motion)); } } else if (summaryRow.Delivery != DeliveryKind.Projectile) { sb.Append(SpellText.Sep).Append(SpellText.Delivery(summaryRow.Delivery)); } else if (summaryRow.Motion != MotionKind.Straight) { sb.Append(SpellText.Sep).Append(SpellText.Motion(summaryRow.Motion)); } if (summaryRow.Damage > 0f && beam) { sb.Append(SpellText.Sep).Append(Format((summaryRow.Count > 1) ? "ui.damage_every_per_beam" : "ui.damage_every", (summaryRow.Count > 1) ? "{0} dmg every {1}s per beam" : "{0} dmg every {1}s", summaryRow.Damage.ToString("0.#", CultureInfo.InvariantCulture), summaryRow.TickInterval.ToString("0.##", CultureInfo.InvariantCulture))); } else if (summaryRow.Damage > 0f) { sb.Append(SpellText.Sep).Append(summaryRow.Damage.ToString("0.#", CultureInfo.InvariantCulture)).Append(' ') .Append((summaryRow.Count > 1) ? SpellText.Get("ui.damage_each", "dmg each") : SpellText.Get("ui.damage", "dmg")); } if (summaryRow.Mark != MarkKind.None && summaryRow.MarkAmount > 0f) { sb.Append(SpellText.Sep).Append("+").Append(summaryRow.MarkAmount.ToString("0.#", CultureInfo.InvariantCulture)) .Append(' ') .Append(SpellText.Mark(summaryRow.Mark)); } if (summaryRow.Bursts && summaryRow.Delivery == DeliveryKind.Projectile) { sb.Append(SpellText.Sep).Append(SpellText.Get("ui.bursts", "bursts where it stops")); } if (summaryRow.Push > 0f) { sb.Append(SpellText.Sep).Append(SpellText.Get("ui.pushes", "knocks back what it strikes")); } else if (summaryRow.Push < 0f) { sb.Append(SpellText.Sep).Append(SpellText.Get("ui.pulls", "pulls what it strikes inwards")); } if (summaryRow.Pierces > 0) { sb.Append(SpellText.Sep).Append(Format("ui.pierces", "passes through {0}, losing {1}% each time", summaryRow.Pierces, Percent(0.3f))); } if (summaryRow.Bounces > 0) { sb.Append(SpellText.Sep).Append(Format("ui.bounces", "glances off walls and floors up to {0} times", summaryRow.Bounces)); } if (summaryRow.Hits > 1 && summaryRow.Pierces == 0) { sb.Append(SpellText.Sep).Append(Format("ui.ground_hits", "triggers its On Hit spells up to {0} times", summaryRow.Hits)); } if (summaryRow.Spill > 0) { sb.Append(SpellText.Sep).Append(summaryRow.Spill.ToString(CultureInfo.InvariantCulture)).Append(' ') .Append(SpellText.Get("ui.pools", "pools where it lands")); } if (summaryRow.Raises) { sb.Append(SpellText.Sep).Append(SpellText.Get("ui.raises", "raises the dead in it")); } if (summaryRow.Consumes) { sb.Append(SpellText.Sep).Append(SpellText.Get("ui.consumes", "buries the goods lying in it with them")); } sb.Append('\n'); } } private static string TriggerLabel(PayloadTrigger trigger) { return trigger switch { PayloadTrigger.OnMiss => SpellText.Get("trigger.on_miss", "on miss"), PayloadTrigger.OnKill => SpellText.Get("trigger.on_kill", "on kill"), _ => SpellText.Get("trigger.on_hit", "on hit"), }; } private static string PayloadOrigin(DeliveryKind delivery) { return delivery switch { DeliveryKind.Anchored => SpellText.Get("payload.at_point", "at that point"), DeliveryKind.Descend => SpellText.Get("payload.onto_point", "onto that point"), _ => SpellText.Get("payload.onward", "onward from that point"), }; } private static long Clamp(long value) { if (value <= 1000000) { return value; } return 1000000L; } private static string DisplayNameOf(SpellKey key, ISpellSource spells) { if (spells != null && spells.TryGet(key, out var definition) && definition != null && !string.IsNullOrEmpty(definition.DisplayName)) { return definition.DisplayName; } return key.Value; } private static float Positive(float value) { if (!(value > 0f)) { return 1f; } return value; } } public enum SpellCategory { Projectile, Transform, Payload, Segment, Flag } [Flags] public enum CastFlags { None = 0, Catalyst = 1, Vigil = 2, Nail = 4, Stitch = 8, Spare = 0x10, BloodRite = 0x20, Stands = 0x40 } public enum PayloadTrigger { OnHit, OnMiss, OnKill } public struct PayloadSpec { public PayloadTrigger Trigger; public bool Otherwise; public float CostMultiplier; } public enum TransformKind { Multiply, Pulse, Pierce, Knockback, Amplify, Convert, Shape, Deliver, Raise, Sacrifice, Blood, Bounce } public enum ElementKind { None, Fire, Frost, Holy, Dark, Electric, Poison, Explosive } public enum MarkKind { None, Burn, Chill, Poison, Oil, Soak, Shock, Brand, Hex, Stone, Fear, Blind } public enum DeliveryKind { Projectile, Anchored, Descend } public enum TargetingKind { Forward, Point } public enum VoxelPattern { Ball, Sigil, Converge, Column, Burst, Beam, Rise, Wisp } public enum IntensityCurve { FadeOut, BuildUp } public enum MotionKind { Straight, Spiral, Orbit, Homing, Arc } public enum CollisionKind { None, Point, Sphere } public enum VisualKind { Motes, Cluster, Beam } public enum FormationKind { Single, Spread, Ring, Spiral } public enum SpellVoice { Element, Blast } public struct ProjectileArchetype { public ElementKind Element; public MotionKind Motion; public CollisionKind Collision; public VisualKind Visual; public VoxelPattern Pattern; public SpellVoice Voice; public float Damage; public float Speed; public float Reach; public bool Channelled; public float Scale; public float Lifetime; public float TickInterval; public MarkKind Mark; public float MarkAmount; public int Spill; public bool Bursts; public bool Alone; public bool MarkOnly; public bool AtCaster; public float FlashesCaster; } public struct DeliverySpec { public DeliveryKind Kind; public float ArrivalDelay; public float ArrivalHeight; } public struct TransformSpec { public TransformKind Kind; public int MultiplyFactor; public float DamageMultiplier; public float ScaleMultiplier; public float SpeedMultiplier; public bool SparesBeams; public bool Stand; public SpellKey ConvertTarget; public FormationKind Formation; public int Push; public DeliveryKind Delivery; public float ArrivalDelay; public float ArrivalHeight; public float RaiseDelay; public float CostMultiplier; } public sealed class SpellDefinition { public SpellKey Key; public string DisplayName; public SpellCategory Category; public float BaseCost; public TargetingKind Targeting; public float CastTime; public ProjectileArchetype Projectile; public DeliverySpec Delivery; public TransformSpec Transform; public PayloadSpec Payload; public CastFlags Flag; public bool Internal; public override string ToString() { if (!string.IsNullOrEmpty(DisplayName)) { return DisplayName; } return Key.Value; } } public readonly struct SpellKey : IEquatable { public static readonly SpellKey None; private readonly string _value; public bool IsValid => !string.IsNullOrEmpty(_value); public string Value => _value ?? string.Empty; public SpellKey(string value) { _value = value; } public bool Equals(SpellKey other) { return string.Equals(_value, other._value, StringComparison.Ordinal); } public override bool Equals(object obj) { if (obj is SpellKey other) { return Equals(other); } return false; } public override int GetHashCode() { if (_value == null) { return 0; } return _value.GetHashCode(); } public static bool operator ==(SpellKey a, SpellKey b) { return a.Equals(b); } public static bool operator !=(SpellKey a, SpellKey b) { return !a.Equals(b); } public override string ToString() { return Value; } } public static class SpellOrder { private const string Retired = null; private static readonly string[] Keys = new string[40] { "fireball", "frostbolt", "meteor", null, "sigil", "split", "empower", null, null, "skyfall", "ritual", "onhit", "onmiss", "raise", "grave_goods", "venom", null, "lightning", "else", "pulse", "pierce", "concussion", "gather", "next", "brand", "hex", "stone", "sanctuary", "radiance", "blood", "catalyst", "vigil", "nail", "stake", "vial", "stitch", "onkill", "bounce", "spare", "bloodrite" }; public static int Count => Keys.Length; public static SpellKey KeyAt(int index) { if (index < 0 || index >= Keys.Length || Keys[index] == null) { return SpellKey.None; } return new SpellKey(Keys[index]); } public static int IndexOf(SpellKey key) { if (!key.IsValid) { return -1; } for (int i = 0; i < Keys.Length; i++) { if (Keys[i] != null && Keys[i] == key.Value) { return i; } } return -1; } } public static class SpellPresets { public struct Preset { public string Program; public string English; public string Chinese; } public static readonly Preset[] All = new Preset[43] { new Preset { Program = "fireball", English = "one fireball, the baseline", Chinese = "单发火球,基准" }, new Preset { Program = "fireball > split", English = "split: two fireballs, fanned apart so they are countable", Chinese = "分裂:两颗火球,会岔开以便数清" }, new Preset { Program = "fireball > empower > frostbolt", English = "empower catches only the fireball before it", Chinese = "强化只吃到它前面的火球,冰弹不受影响" }, new Preset { Program = "fireball > frostbolt > empower", English = "same three spells, moved: now both are strengthened", Chinese = "同样三个法术换位置:两个都被强化了" }, new Preset { Program = "fireball > split > frostbolt", English = "split before the second spell: two fire, one frost", Chinese = "分裂在第二个法术之前:两火一冰" }, new Preset { Program = "fireball > frostbolt > split", English = "split after it: two fire, two frost", Chinese = "分裂在它之后:两火两冰" }, new Preset { Program = "empower > split > fireball", English = "modifiers first: they catch nothing, so only a plain fireball", Chinese = "修饰放最前面:前面没东西可作用,只剩一颗普通火球" }, new Preset { Program = "frostbolt > split > split", English = "four bolts of cold at once. Against something healthy that is a heavy slow; against something already dying it shatters. Fire on a frozen target melts the ice into water", Chinese = "四发寒冰同时命中。打健康的敌人是大幅减速,打已经濒死的敌人则直接碎裂。之后再用火打被冻住的目标,冰会融成水" }, new Preset { Program = "sigil", English = "placed: a sigil draws itself where you aim and stays there", Chinese = "钉在原地:法阵在你瞄准的地面上自己画出来,并停留一段时间" }, new Preset { Program = "fireball > skyfall", English = "the same fireball, called down onto the point you aim at", Chinese = "还是那颗火球,改成砸向你指定的地点" }, new Preset { Program = "meteor > skyfall", English = "a meteor called down from above", Chinese = "陨石从天而降" }, new Preset { Program = "frostbolt > skyfall > split", English = "frostbolt falls too, then splits", Chinese = "冰弹一样能天降,再分裂成两发" }, new Preset { Program = "fireball > split > split > skyfall", English = "four fireballs called down, spread around the aimed point", Chinese = "四颗火球散开砸在指定点周围" }, new Preset { Program = "meteor > skyfall > ritual", English = "a full ritual: a long chant while the sigil forms, then one empowered strike", Chinese = "完整仪式:长咏唱时法阵逐渐成形,然后落下一发强化天降" }, new Preset { Program = "ritual > meteor > skyfall", English = "ritual first: identical chant length, but it empowers nothing", Chinese = "仪式放最前面:咏唱一样长,却什么都没强化到,白等" }, new Preset { Program = "fireball > onhit > fireball > split", English = "the fireball hits, and two more burst out of it and keep going the way it was flying", Chinese = "火球命中后,从命中点再冒出两颗,沿原来的方向继续飞" }, new Preset { Program = "fireball > onhit > sigil", English = "delivery and effect come apart: the fireball carries the sigil there, and the sigil appears where it hit, no ground aiming needed", Chinese = "投送与效果分离:火球把法阵带过去,法阵画在命中的地方,不需要瞄准地面" }, new Preset { Program = "fireball > onmiss > meteor > skyfall", English = "betting on a miss: nothing extra if it hits something living, a meteor where it stops if it doesn't (a wall counts as a miss)", Chinese = "赌落空:命中生物就没有额外效果,没命中生物就在停下处落一颗陨石(打在墙上算落空)" }, new Preset { Program = "meteor > skyfall > onhit > sigil", English = "anything called down always lands, so the sigil it carries is never wasted", Chinese = "天降的东西必定落地,所以它携带的法阵从不浪费" }, new Preset { Program = "sigil > onhit > frostbolt > split > split > skyfall", English = "a trap: the first enemy to stand in the sigil has four bolts of cold called down on its head", Chinese = "陷阱:第一个站进法阵的敌人,头顶落下四发寒冰" }, new Preset { Program = "sigil > pulse > pulse > pulse > onhit > fireball > skyfall", English = "pulse lets the sigil do it again: up to four fireballs, each on whoever is standing in it at the time, each paid for in advance", Chinese = "脉动让法阵可以再来一次:最多四颗火球,每颗砸在当时站在阵里的敌人头上,每一颗都预先付费" }, new Preset { Program = "venom > split > split > skyfall > next > fireball", English = "two presses: the first calls four flasks down, the second throws the fire that detonates what they left. Reload to start from the first again", Chinese = "按两下:第一下砸下四个毒液瓶,第二下扔出引爆它们的火球。按装填键回到第一下" }, new Preset { Program = "fireball > pierce > onhit > sigil", English = "lined up, three bodies each get a sigil: the fireball goes through the first two, weaker each time, and leaves a sigil under every one it struck", Chinese = "排成一线时三个人脚下各留一个法阵:火球穿过前两个,一次比一次弱,命中的每个人脚下都画一个" }, new Preset { Program = "fireball > onhit > frostbolt > split > split > skyfall > else > venom > skyfall", English = "both outcomes on one fireball: strike something and four bolts of cold fall on it; miss and a flask falls where it stopped. Only one can happen, so only the dearer is paid for", Chinese = "一颗火球带两种结局:打中,四发寒冰砸在它头上;落空,就在停下的地方落一瓶毒。两支只会发生一支,所以只按较贵的那支付费" }, new Preset { Program = "fireball > onhit > meteor > onmiss > sigil", English = "nesting: the fireball carries a meteor for a hit, and that meteor carries a sigil for when it misses", Chinese = "嵌套:火球命中生物才放陨石,那颗陨石又带着一个落空才画的法阵" }, new Preset { Program = "sigil > raise", English = "kill a few things first: the sigil raises what is lying in it, and how many is up to the fight before it, not to the program", Chinese = "先杀几个再放:法阵会把躺在里面的尸体起出来,起几具取决于之前那场仗,而不是取决于程序" }, new Preset { Program = "sigil > raise > ritual", English = "the chant, stood through, widens the sigil, so it raises the dead from further out; it costs no more, so they stand no longer", Chinese = "站着念完的咏唱让法阵更大,能从更远处起尸;不多花法力,亡灵也就不会站得更久" }, new Preset { Program = "sigil > raise > grave_goods", English = "throw whatever you can spare into the sigil first: the goods are consumed and split between however many rise, so one corpse and a full bag makes a champion", Chinese = "先把用不上的东西丢进法阵:物品会被消耗,价值按起身的具数均分,一具尸体加一整包货,出来的就是一个精锐" }, new Preset { Program = "sigil > grave_goods", English = "grave goods with nothing being raised: it catches nothing and costs exactly a plain sigil, and no item on the floor is touched", Chinese = "没有招魂的陪葬:什么都没抓到,花费和一个普通法阵一样,地上的东西一件不动" }, new Preset { Program = "fireball > raise", English = "raise needs a dark sigil on the ground; a fireball is neither, so it catches nothing and costs the same as a plain fireball", Chinese = "招魂要的是一个停在地上的暗属性法阵,火球两样都不是,所以什么都没抓到,花费和一颗普通火球一样" }, new Preset { Program = "fireball > onmiss > sigil > raise", English = "shoot into the corpses: the fireball stops without hitting anything living, which counts as a miss, so the sigil lands among the dead", Chinese = "朝尸堆打:火球没命中生物就停下,算落空,法阵就落在尸体中间" }, new Preset { Program = "sigil > raise > skyfall", English = "the same rite called down onto a point instead. It waits out the fall before it raises, so the sigil finishes drawing exactly as it lands", Chinese = "同一场仪式,改成砸向指定地点。它会等落地之后才起尸,法阵正好在落地那一刻画完" }, new Preset { Program = "meteor > skyfall > sigil > ritual", English = "placement decides what each modifier catches: skyfall takes only the meteor, the sigil stays on the ground, the chant strengthens both", Chinese = "位置决定每个修饰抓到谁:天降只抓陨石,法阵留在地上,咏唱两个都强化" }, new Preset { Program = "venom", English = "one flask: nearly as much poison as an enemy can hold on what it hits, and pools of it where it breaks", Chinese = "单个毒液瓶:命中的敌人差不多被灌满毒,碎开的地方留下毒液水洼" }, new Preset { Program = "venom > split > split", English = "four flasks fanned apart. One already nearly fills a target, so the other three are for whatever stands beside it: poison is spread wide, then collected by fire", Chinese = "四个毒液瓶岔开扔。一瓶就差不多灌满一个目标,另外三瓶是给它旁边的:毒要铺开,再用火来收" }, new Preset { Program = "venom > split > split > skyfall", English = "four flasks called down around a point, which is area denial rather than a shot", Chinese = "四个毒液瓶散开砸在一个点周围,是堵路而不是攻击" }, new Preset { Program = "venom > onhit > fireball", English = "poison, then fire, in that order: the fireball is carried by the flask, so it can only arrive after the poison, and one flask is enough to detonate", Chinese = "先毒后火,顺序有保证:火球由毒液瓶携带,只可能在上毒之后到,一瓶的毒就够引爆" }, new Preset { Program = "fireball", English = "one fireball, thrown at poison somebody else left: pools burn where they lie, and a target poisoned past two thirds of what it can hold detonates", Chinese = "单发火球,扔向别处留下的毒:地上的水洼就地烧起来,中毒超过上限三分之二的目标会被引爆" }, new Preset { Program = "lightning", English = "hold it and sweep: a beam that stays where you point it and drains while it is open, whether or not it is on anything", Chinese = "按住不放来回扫:光束一直指向你瞄的地方,开着就耗法力,打没打到都一样" }, new Preset { Program = "lightning > empower", English = "the same beam, harder and dearer per second; empower works on a beam exactly as on anything else", Chinese = "同一道光束,每秒更疼也更贵,强化对光束的作用和对别的东西完全一样" }, new Preset { Program = "lightning > split", English = "two beams fanned apart, each able to hit a different target", Chinese = "两道光束岔开,可以各打一个目标" }, new Preset { Program = "lightning > split > split > skyfall", English = "four beams called down, standing spread around the aimed point and moving with it", Chinese = "四道光束从天上落下,散开立在指定点周围,跟着准星一起移动" }, new Preset { Program = "lightning > skyfall", English = "called down: the beam comes out of the sky onto the point you aim at and stays there while you hold it", Chinese = "天降:光束从天上落到你指定的点上,按住不放就一直打在那儿" } }; public static string Describe(int index) { if (index < 0 || index >= All.Length) { return string.Empty; } Preset preset = All[index]; if (!SpellText.IsChinese) { return preset.English; } return preset.Chinese; } } public enum ReactionEffect { Detonate, Amplify, Convert, Chain } public struct Reaction { public ElementKind Trigger; public MarkKind Consumes; public float Threshold; public ReactionEffect Effect; public float DamagePerPoint; public bool LeavesMark; public MarkKind OnlyIfTargetLacks; public bool NotInWater; public bool OncePerCast; public float MaxPoints; public float BaseRadius; public float RadiusPerPoint; public float MaxRadius; public ElementKind DamageAs; public MarkKind Produces; public float ProducePerPoint; public float MaxProduced; public bool ReachesTheDead; public int Puddles; public int ChainHops; public float ChainRange; public float ChainFalloff; public float LiquidReach; public float LiquidBurn; public float LiquidBurnTime; public float LiquidBurnRadius; } public static class SpellReactions { public static readonly Reaction[] All = new Reaction[4] { new Reaction { Trigger = ElementKind.Fire, Consumes = MarkKind.Chill, Threshold = 35f, Effect = ReactionEffect.Convert, MaxPoints = 100f, Produces = MarkKind.Soak, ProducePerPoint = 0.6f, MaxProduced = 60f, DamageAs = ElementKind.Frost, ReachesTheDead = true, Puddles = 3 }, new Reaction { Trigger = ElementKind.Electric, Consumes = MarkKind.Soak, Threshold = 1f, Effect = ReactionEffect.Chain, LeavesMark = true, OnlyIfTargetLacks = MarkKind.Shock, ChainHops = 3, ChainRange = 6f, ChainFalloff = 0.6f, DamageAs = ElementKind.Electric }, new Reaction { Trigger = ElementKind.Frost, Consumes = MarkKind.Soak, Threshold = 1f, Effect = ReactionEffect.Convert, MaxPoints = 100f, Produces = MarkKind.Chill, ProducePerPoint = 0.2f, MaxProduced = 20f, NotInWater = true, OncePerCast = true }, new Reaction { Trigger = ElementKind.Fire, Consumes = MarkKind.Poison, Threshold = 10f, Effect = ReactionEffect.Detonate, DamagePerPoint = 3.5f, MaxPoints = 15f, BaseRadius = 1.5f, RadiusPerPoint = 0.135f, MaxRadius = 3.5f, DamageAs = ElementKind.Poison, LiquidReach = 3f, LiquidBurn = 20f, LiquidBurnTime = 4f, LiquidBurnRadius = 1.8f } }; public static bool TryFind(ElementKind element, MarkKind mark, float amount, out Reaction rule) { for (int i = 0; i < All.Length; i++) { Reaction reaction = All[i]; if (reaction.Trigger == element && reaction.Consumes == mark && amount >= reaction.Threshold) { rule = reaction; return true; } } rule = default(Reaction); return false; } } public sealed class SpellSegments { public bool Hands { get; } public string Key { get; } public IReadOnlyList Plans { get; } public string Summary { get; } public int Count => Plans.Count; private SpellSegments(List plans, string summary, string key, bool hands = false) { Plans = plans; Summary = summary; Key = key; Hands = hands; } public static SpellSegments Compile(IReadOnlyList program, ISpellSource spells) { List> list = new List> { new List() }; if (program != null) { for (int i = 0; i < program.Count; i++) { SpellDefinition spellDefinition = program[i]; if (spellDefinition != null) { if (spellDefinition.Category == SpellCategory.Segment) { list.Add(new List()); } else { list[list.Count - 1].Add(spellDefinition); } } } } List list2 = new List(); int num = 0; StringBuilder stringBuilder = new StringBuilder(); for (int j = 0; j < list.Count; j++) { if (list[j].Count != 0) { CastPlan castPlan = SpellCompiler.Compile(list[j], spells); if (castPlan.EmissionCount > 0) { list2.Add(castPlan); stringBuilder.Append(string.Join(">", castPlan.Program)).Append('|'); } else { num++; } } } if (list2.Count == 0) { list2.Add(CastPlan.Empty); } return new SpellSegments(list2, Describe(list2, num), stringBuilder.ToString()); } public static SpellSegments CompileHands(IReadOnlyList left, IReadOnlyList right, ISpellSource spells, int dropped = 0, int handSlots = 0) { CastPlan castPlan = Hand(left, spells); CastPlan castPlan2 = Hand(right, spells); List plans = new List { castPlan, castPlan2 }; string key = "L:" + string.Join(">", castPlan.Program) + "|R:" + string.Join(">", castPlan2.Program); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(SpellText.Get("ui.hand_left", "Trigger hand")).Append('\n').Append((castPlan.EmissionCount > 0) ? castPlan.Summary : SpellText.Get("ui.hand_empty", "Casts nothing")) .Append('\n') .Append(SpellText.Get("ui.hand_right", "Aim-button hand")) .Append('\n') .Append((castPlan2.EmissionCount > 0) ? castPlan2.Summary : SpellText.Get("ui.hand_empty", "Casts nothing")); if (dropped > 0) { stringBuilder.Append('\n').Append(string.Format(SpellText.Get("ui.hand_overflow", "A hand holds at most {0} spells; {1} past that were left out"), handSlots, dropped)); } if (castPlan2.EmissionCount == 0 && castPlan.EmissionCount > 0) { stringBuilder.Append('\n').Append(SpellText.Get("ui.hand_hint", "Spells after a Next go to the aim-button hand")); } return new SpellSegments(plans, stringBuilder.ToString(), key, hands: true); } private static CastPlan Hand(IReadOnlyList program, ISpellSource spells) { List list = new List(); if (program != null) { for (int i = 0; i < program.Count; i++) { if (program[i] != null && program[i].Category != SpellCategory.Segment) { list.Add(program[i]); } } } if (list.Count == 0) { return CastPlan.Empty; } CastPlan castPlan = SpellCompiler.Compile(list, spells); if (castPlan.EmissionCount <= 0) { return CastPlan.Empty; } return castPlan; } private static string Describe(List plans, int dropped) { string text = ((dropped > 0) ? ("\n" + SpellText.Get("ui.segment_dropped", "A segment that fires nothing was left out")) : string.Empty); if (plans.Count == 1) { return plans[0].Summary + text; } StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < plans.Count; i++) { if (i > 0) { stringBuilder.Append('\n'); } stringBuilder.Append(string.Format(CultureInfo.InvariantCulture, SpellText.Get("ui.segment", "Segment {0} of {1}"), i + 1, plans.Count)).Append('\n').Append(plans[i].Summary); } return stringBuilder.Append(text).ToString(); } } public enum SpellLanguage { English, Chinese, TraditionalChinese } public static class SpellText { private static readonly Dictionary Chinese = new Dictionary { { "fireball", "火球" }, { "frostbolt", "冰弹" }, { "meteor", "陨石" }, { "split", "分裂" }, { "empower", "强化" }, { "ring", "环形" }, { "transmute_meteor", "转化:陨石" }, { "meteor_strike", "陨石天降" }, { "sigil", "蚀骨法阵" }, { "ritual", "仪式" }, { "lightning", "雷电" }, { "skyfall", "天降" }, { "onhit", "命中之后" }, { "onmiss", "落空之后" }, { "else", "否则" }, { "pulse", "脉动" }, { "pierce", "穿透" }, { "concussion", "震退" }, { "gather", "聚拢" }, { "next", "下一发" }, { "brand", "圣印" }, { "hex", "咒缚" }, { "stone", "石印" }, { "sanctuary", "圣域" }, { "radiance", "圣辉" }, { "blood", "血价" }, { "catalyst", "催化" }, { "vigil", "守望" }, { "nail", "圣钉" }, { "stake", "法阵钉" }, { "vial", "封瓶" }, { "stitch", "缝尸线" }, { "spare", "不伤自己" }, { "bloodrite", "血祭" }, { "onkill", "击杀之后" }, { "bounce", "弹跳" }, { "raise", "招魂" }, { "grave_goods", "陪葬" }, { "venom", "毒液瓶" }, { "trigger.on_hit", "命中之后" }, { "trigger.on_miss", "落空之后" }, { "trigger.on_kill", "击杀之后" }, { "trigger.each_hit", "每次命中后" }, { "trigger.each_miss", "每次落空后" }, { "trigger.each_kill", "每次击杀后" }, { "ui.bounces", "碰到墙壁和地面会弹开,最多 {0} 次" }, { "payload.onward", "自触发点继续" }, { "payload.at_point", "出现在触发点" }, { "payload.onto_point", "落向触发点" }, { "delivery.anchored", "出现在指定点" }, { "delivery.descend", "从天而降" }, { "formation.spread", "散射" }, { "formation.ring", "环形" }, { "formation.spiral", "螺旋" }, { "motion.spiral", "螺旋飞行" }, { "motion.orbit", "环绕" }, { "motion.homing", "追踪" }, { "motion.arc", "抛物线" }, { "mark.burn", "燃烧" }, { "mark.chill", "冰冻" }, { "mark.poison", "猛毒" }, { "mark.oil", "油性" }, { "mark.soak", "潮湿" }, { "mark.shock", "触电" }, { "mark.brand", "圣印" }, { "mark.hex", "咒缚" }, { "mark.stone", "石化" }, { "mark.fear", "恐惧" }, { "mark.blind", "失明" }, { "ui.times", "个" }, { "ui.damage_each", "点伤害/个" }, { "ui.damage", "点伤害" }, { "ui.total", "合计" }, { "ui.emissions", "个效果" }, { "ui.trigger_more_before", "触发后至多" }, { "ui.trigger_more_after", "个" }, { "ui.mana", "法力" }, { "ui.paid_in_blood_before", "其中 " }, { "ui.paid_in_blood_after", "法力改用生命值支付" }, { "ui.health", "生命" }, { "ui.capped", "上限" }, { "ui.nothing", "无效果" }, { "ui.pools", "处水洼" }, { "ui.bursts", "在停下处炸开一片" }, { "ui.raises", "范围内的尸体会作为亡灵起身" }, { "ui.consumes", "范围内的物品会作为陪葬品被消耗" }, { "ui.cast_time", "咏唱时间" }, { "ui.seconds", " 秒" }, { "ui.targeting_point", "需要指向地面上的一个点" }, { "ui.per_second", "秒" }, { "ui.mana_per_second", "法力/秒(按住期间)" }, { "ui.damage_every", "每 {1} 秒 {0} 点伤害" }, { "ui.damage_every_per_beam", "每道光束每 {1} 秒 {0} 点伤害" }, { "ui.omitted_from_beam", "光束需要按住,不是光束的法术不随它施放,已略去 {0} 个效果" }, { "ui.beam_no_payload", "光束无法携带法术:“命中之后”“落空之后”“击杀之后”后面的法术已略去" }, { "ui.omitted_payload_beam", "被携带的光束无法按住,已略去 {0} 道光束" }, { "ui.segment", "第 {0} 段(共 {1} 段)" }, { "ui.segment_dropped", "有一段什么都不施放,已略去" }, { "ui.hand_left", "扳机:" }, { "ui.hand_right", "瞄准键:" }, { "ui.hand_empty", "什么都不施放" }, { "ui.hand_overflow", "每边最多 {0} 个法术,多出的 {1} 个未计入" }, { "ui.hand_hint", "“下一发”之后的法术归瞄准键" }, { "ui.staff_casts", "这根法杖会放出:" }, { "idle.row", "{0}没起作用:{1}" }, { "preview.full", "{0}已经刻满了" }, { "preview.cost", "刻到{0}上:法力 {1} → {2}" }, { "preview.chant", ",咏唱 {0} 秒 → {1} 秒" }, { "preview.idle", "刻在那里不会起作用:{0}" }, { "preview.waits", "{0}上它后面还没有法术:刻上它之后,再刻要它带的法术" }, { "idle.chant", "白念一段咏唱,什么都没强化" }, { "idle.modifier", "放出来的东西没有任何变化" }, { "idle.trigger", "什么都没触发" }, { "idle.segment", "它没有分出能放的一段" }, { "idle.other", "被略去,原因见上面几行" }, { "cast.next_segment", "下一发:第 {0} 段(共 {1} 段)" }, { "cast.ritual_moved", "仪式被打断:咏唱时移动了。" }, { "ui.pushes", "击退命中的目标" }, { "ui.pulls", "把命中的目标拉向中心" }, { "ui.pierces", "穿过 {0} 个目标,每穿一次伤害减 {1}%" }, { "ui.ground_hits", "“命中之后”最多触发 {0} 次" }, { "ui.not_alone", "已略去且不扣费:石印只能单独施放,不能被分裂、天降、携带或放进光束" }, { "ui.unpaired_else", "前面没有可配对的“命中之后”或“落空之后”,这个“否则”无效,它后面的法术留在原处" }, { "ui.omitted_hit_on_ground", "已略去且不扣费:放在不造成伤害的地面法阵(如招魂法阵)后面的“命中之后”永远不会触发" }, { "ui.omitted_miss_from_above", "已略去且不扣费:天降的东西必定落地,放在它后面的“落空之后”永远不会触发" }, { "ui.cut_off_behind_empty", "有一层被携带的法术全被略去,触发不了任何东西,刻在它后面的法术也一并略去" }, { "cast.fired", "施放" }, { "cast.left", "剩余" }, { "cast.beam_open", "光束已开启" }, { "cast.beam_close", "光束已关闭" }, { "cast.not_enough", "法力不足:需要" }, { "cast.blood_floor", "生命值不足以支付血价" }, { "cast.blood_spent", "本层的血价已付到上限" }, { "cast.have", "当前" }, { "cast.empty", "法杖上没有法术。" }, { "cast.all_left_out", "法杖上的法术都放不出来。" }, { "cast.compiled", "法杖就绪" }, { "cast.preset", "预设" }, { "cast.channel_start", "开始咏唱" }, { "cast.channel_cancel", "咏唱被打断。" }, { "cast.staff_in_hand", "手里拿着法杖,由它决定施放什么。收起法杖才能用测试程序。" }, { "render.look", "渲染" }, { "render.per_spell", "按法术:每种图案用它自己该有的渲染" } }; private static readonly Dictionary Traditional = new Dictionary { { "fireball", "火球" }, { "frostbolt", "冰彈" }, { "meteor", "隕石" }, { "split", "分裂" }, { "empower", "強化" }, { "ring", "環形" }, { "transmute_meteor", "轉化:隕石" }, { "meteor_strike", "隕石天降" }, { "sigil", "蝕骨法陣" }, { "ritual", "儀式" }, { "lightning", "雷電" }, { "skyfall", "天降" }, { "onhit", "命中之後" }, { "onmiss", "落空之後" }, { "else", "否則" }, { "pulse", "脈動" }, { "pierce", "穿透" }, { "concussion", "震退" }, { "gather", "聚攏" }, { "next", "下一發" }, { "brand", "聖印" }, { "hex", "咒縛" }, { "stone", "石印" }, { "sanctuary", "聖域" }, { "radiance", "聖輝" }, { "blood", "血價" }, { "catalyst", "催化" }, { "vigil", "守望" }, { "nail", "聖釘" }, { "stake", "法陣釘" }, { "vial", "封瓶" }, { "stitch", "縫屍線" }, { "spare", "不傷自己" }, { "bloodrite", "血祭" }, { "onkill", "擊殺之後" }, { "bounce", "彈跳" }, { "raise", "招魂" }, { "grave_goods", "陪葬" }, { "venom", "毒液瓶" }, { "trigger.on_hit", "命中之後" }, { "trigger.on_miss", "落空之後" }, { "trigger.on_kill", "擊殺之後" }, { "trigger.each_hit", "每次命中後" }, { "trigger.each_miss", "每次落空後" }, { "trigger.each_kill", "每次擊殺後" }, { "ui.bounces", "碰到牆壁和地面會彈開,最多 {0} 次" }, { "payload.onward", "從觸發點繼續" }, { "payload.at_point", "出現在觸發點" }, { "payload.onto_point", "落向觸發點" }, { "delivery.anchored", "出現在指定點" }, { "delivery.descend", "從天而降" }, { "formation.spread", "散射" }, { "formation.ring", "環形" }, { "formation.spiral", "螺旋" }, { "motion.spiral", "螺旋飛行" }, { "motion.orbit", "環繞" }, { "motion.homing", "追蹤" }, { "motion.arc", "拋物線" }, { "mark.burn", "燃燒" }, { "mark.chill", "凍結" }, { "mark.poison", "中毒" }, { "mark.oil", "滿身油" }, { "mark.soak", "落湯雞" }, { "mark.shock", "觸電" }, { "mark.brand", "聖印" }, { "mark.hex", "咒縛" }, { "mark.stone", "石化" }, { "mark.fear", "恐懼" }, { "mark.blind", "致盲" }, { "ui.times", "個" }, { "ui.damage_each", "點傷害/個" }, { "ui.damage", "點傷害" }, { "ui.total", "合計" }, { "ui.emissions", "個效果" }, { "ui.trigger_more_before", "觸發後至多" }, { "ui.trigger_more_after", "個" }, { "ui.mana", "法力" }, { "ui.paid_in_blood_before", "其中 " }, { "ui.paid_in_blood_after", "法力改用 HP 支付" }, { "ui.health", "HP" }, { "ui.capped", "上限" }, { "ui.nothing", "無效果" }, { "ui.pools", "處水窪" }, { "ui.bursts", "在停下處炸開一片" }, { "ui.raises", "範圍內的屍體會作為亡靈起身" }, { "ui.consumes", "範圍內的物品會作為陪葬品被消耗" }, { "ui.cast_time", "詠唱時間" }, { "ui.seconds", " 秒" }, { "ui.targeting_point", "需要指向地面上的一個點" }, { "ui.per_second", "秒" }, { "ui.mana_per_second", "法力/秒(按住期間)" }, { "ui.damage_every", "每 {1} 秒 {0} 點傷害" }, { "ui.damage_every_per_beam", "每道光束每 {1} 秒 {0} 點傷害" }, { "ui.omitted_from_beam", "光束需要按住,不是光束的法術不隨它施放,已略去 {0} 個效果" }, { "ui.beam_no_payload", "光束無法攜帶法術:「命中之後」「落空之後」「擊殺之後」後面的法術已略去" }, { "ui.omitted_payload_beam", "被攜帶的光束無法按住,已略去 {0} 道光束" }, { "ui.segment", "第 {0} 段(共 {1} 段)" }, { "ui.segment_dropped", "有一段什麼都不施放,已略去" }, { "ui.hand_left", "扳機:" }, { "ui.hand_right", "瞄準鍵:" }, { "ui.hand_empty", "什麼都不施放" }, { "ui.hand_overflow", "每邊最多 {0} 個法術,多出的 {1} 個未計入" }, { "ui.hand_hint", "「下一發」之後的法術歸瞄準鍵" }, { "ui.staff_casts", "這根法杖會放出:" }, { "idle.row", "{0}沒起作用:{1}" }, { "preview.full", "{0}已經刻滿了" }, { "preview.cost", "刻到{0}上:法力 {1} → {2}" }, { "preview.chant", ",詠唱 {0} 秒 → {1} 秒" }, { "preview.idle", "刻在那裡不會起作用:{0}" }, { "preview.waits", "{0}上它後面還沒有法術:刻上它之後,再刻要它帶的法術" }, { "idle.chant", "白念一段詠唱,什麼都沒強化" }, { "idle.modifier", "放出來的東西沒有任何變化" }, { "idle.trigger", "什麼都沒觸發" }, { "idle.segment", "它沒有分出能放的一段" }, { "idle.other", "被略去,原因見上面幾行" }, { "cast.next_segment", "下一發:第 {0} 段(共 {1} 段)" }, { "cast.ritual_moved", "儀式被打斷:詠唱時移動了。" }, { "ui.pushes", "擊退命中的目標" }, { "ui.pulls", "把命中的目標拉向中心" }, { "ui.pierces", "穿過 {0} 個目標,每穿一次傷害減 {1}%" }, { "ui.ground_hits", "「命中之後」最多觸發 {0} 次" }, { "ui.not_alone", "已略去且不扣費:石印只能單獨施放,不能被分裂、天降、攜帶或放進光束" }, { "ui.unpaired_else", "前面沒有可配對的「命中之後」或「落空之後」,這個「否則」無效,它後面的法術留在原處" }, { "ui.omitted_hit_on_ground", "已略去且不扣費:放在不造成傷害的地面法陣(如招魂法陣)後面的「命中之後」永遠不會觸發" }, { "ui.omitted_miss_from_above", "已略去且不扣費:天降的東西必定落地,放在它後面的「落空之後」永遠不會觸發" }, { "ui.cut_off_behind_empty", "有一層被攜帶的法術全被略去,觸發不了任何東西,刻在它後面的法術也一併略去" }, { "cast.fired", "施放" }, { "cast.left", "剩餘" }, { "cast.beam_open", "光束已開啟" }, { "cast.beam_close", "光束已關閉" }, { "cast.not_enough", "法力不足:需要" }, { "cast.blood_floor", "HP 不足以支付血價" }, { "cast.blood_spent", "本層的血價已付到上限" }, { "cast.have", "目前" }, { "cast.empty", "法杖上沒有法術。" }, { "cast.all_left_out", "法杖上的法術都放不出來。" }, { "cast.compiled", "法杖就緒" }, { "cast.preset", "預設組合" }, { "cast.channel_start", "開始詠唱" }, { "cast.channel_cancel", "詠唱被打斷。" }, { "cast.staff_in_hand", "手裡拿著法杖,由它決定施放什麼。收起法杖才能用測試程式。" }, { "render.look", "渲染" }, { "render.per_spell", "按法術:每種圖案用它自己該有的渲染" } }; public static SpellLanguage Language { get; set; } = SpellLanguage.English; public static bool IsChinese => Language != SpellLanguage.English; public static string Sep { get { if (!IsChinese) { return ", "; } return ","; } } public static string Colon { get { if (!IsChinese) { return ": "; } return ":"; } } public static string OpenParen { get { if (!IsChinese) { return " ("; } return "("; } } public static string CloseParen { get { if (!IsChinese) { return ")"; } return ")"; } } public static string Get(string key, string fallback) { if (Language == SpellLanguage.TraditionalChinese && Traditional.TryGetValue(key, out var value)) { return value; } if (IsChinese && Chinese.TryGetValue(key, out var value2)) { return value2; } return fallback; } public static string Spell(SpellKey key, string fallback) { return Get(key.Value, fallback); } public static string Formation(FormationKind formation) { string text = formation.ToString().ToLowerInvariant(); return Get("formation." + text, text); } public static string Motion(MotionKind motion) { string text = motion.ToString().ToLowerInvariant(); return Get("motion." + text, text); } public static string Count(int count, string name) { string text = count.ToString(CultureInfo.InvariantCulture); return Language switch { SpellLanguage.Chinese => text + " 个" + name, SpellLanguage.TraditionalChinese => text + " 個" + name, _ => text + " x " + name, }; } public static string TriggerEach(PayloadTrigger trigger) { return trigger switch { PayloadTrigger.OnMiss => Get("trigger.each_miss", "On each miss"), PayloadTrigger.OnKill => Get("trigger.each_kill", "On each kill"), _ => Get("trigger.each_hit", "On each hit"), }; } public static string Mark(MarkKind mark) { string text = mark.ToString().ToLowerInvariant(); return Get("mark." + text, EnglishMark(mark) ?? text); } private static string EnglishMark(MarkKind mark) { return mark switch { MarkKind.Burn => "Burning", MarkKind.Chill => "Frozen", MarkKind.Poison => "Poisoned", MarkKind.Oil => "Oily", MarkKind.Soak => "Wet", MarkKind.Shock => "Electrocuted", MarkKind.Brand => "Brand", MarkKind.Hex => "Hex", MarkKind.Stone => "Petrified", MarkKind.Fear => "Feared", MarkKind.Blind => "Blind", _ => null, }; } public static string Delivery(DeliveryKind delivery) { return delivery switch { DeliveryKind.Anchored => Get("delivery.anchored", "appears at the point"), DeliveryKind.Descend => Get("delivery.descend", "falls from above"), _ => Get("delivery.projectile", "travels"), }; } } } namespace UnholyRites.Spells.Runtime { internal static class SpellGroups { private static int _last; internal static int Next() { _last++; if (_last == 0) { _last = 1; } return _last; } } public struct VoxelInstance { public float3 Position; public float3 Offset; public float3 Color; public float3 CoreColor; public float Scale; public uint Random; } public struct VoxelRange { public int Start; public int Count; } public struct ActiveEmission { public DeliveryKind Delivery; public MotionKind Motion; public VoxelPattern Pattern; public IntensityCurve Intensity; public float3 Origin; public float3 Direction; public float3 Right; public float3 Up; public float Speed; public float BirthTime; public float Lifetime; public float Scale; public float GrowDuration; public float ArrivalDelay; public float ArrivalHeight; public float3 Color; public float3 CoreColor; public float Power; public int VoxelCount; public int DrawCount; public uint Seed; public CollisionKind Collision; public ElementKind Element; public SpellVoice Voice; public float Damage; public float HitRadius; public float ImpactRadius; public float TickInterval; public MarkKind Mark; public float MarkAmount; public bool MarkOnce; public bool Bursts; public int Spill; public float NextTickAge; public bool Spent; public bool NoReaction; public bool Raises; public float RaiseAge; public bool Raised; public bool Consumes; public bool LocalCast; public bool SuppressDamage; public int CasterSlot; public int GroupId; public bool FollowsCaster; public int HitSlot; public int MissSlot; public int KillSlot; public int KillBudget; public int HitsLeft; public int PierceLeft; public int BounceLeft; public int IgnoreUnit; public bool Pierced; public float Push; public uint CastSeed; public CastFlags Flags; public bool MarkOnly; public int BeamIndex; public int WriteOffset; } public sealed class SpellRuntime : IDisposable { private struct ExpandJob : IJobParallelFor { [ReadOnly] public NativeArray emissions; [NativeDisableParallelForRestriction] [WriteOnly] public NativeArray output; public float now; private const float CloseStart = 0.72f; public void Execute(int index) { //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_0137: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Unknown result type (might be due to invalid IL or missing references) //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_0169: Unknown result type (might be due to invalid IL or missing references) //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_01ac: Unknown result type (might be due to invalid IL or missing references) //IL_01b1: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_01f7: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_01fa: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_0206: Unknown result type (might be due to invalid IL or missing references) //IL_0208: Unknown result type (might be due to invalid IL or missing references) //IL_0210: Unknown result type (might be due to invalid IL or missing references) //IL_021a: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Unknown result type (might be due to invalid IL or missing references) //IL_0231: Unknown result type (might be due to invalid IL or missing references) //IL_0236: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Unknown result type (might be due to invalid IL or missing references) //IL_01dc: Unknown result type (might be due to invalid IL or missing references) ActiveEmission e = emissions[index]; if (e.DrawCount > 0) { float num = now - e.BirthTime; float3 val = Evaluate(in e, num); float num2 = ((e.Lifetime > 0f) ? math.saturate(num / e.Lifetime) : 1f); float num3 = ((e.Intensity == IntensityCurve.BuildUp) ? (0.35f + 1.15f * num2 * num2) : (1f - math.smoothstep(0.7f, 1f, num2))); float grow = ((e.GrowDuration > 0f) ? math.saturate(num / e.GrowDuration) : 1f); for (int i = 0; i < e.DrawCount; i++) { float u = CastGeometry.Hash01(e.Seed, i, 0); float u2 = CastGeometry.Hash01(e.Seed, i, 1); float num4 = CastGeometry.Hash01(e.Seed, i, 2); float u3 = CastGeometry.Hash01(e.Seed, i, 3); float brightness = 1f; float3 val2 = (float3)(e.Pattern switch { VoxelPattern.Sigil => Sigil(in e, i, u, u2, num4, u3, num, grow, out brightness), VoxelPattern.Converge => Converge(in e, u, u2, num4, u3, num, out brightness), VoxelPattern.Beam => Beam(in e, u, u2, num4, u3, num, out brightness), VoxelPattern.Column => Column(in e, u, u2, num4, num, grow, out brightness), VoxelPattern.Burst => Burst(in e, u, u2, num4, num2, out brightness), VoxelPattern.Rise => Rise(in e, u, u2, num4, u3, num, grow, num2, out brightness), VoxelPattern.Wisp => Wisp(in e, u, u2, num4, u3, num, num2, out brightness), _ => Ball(in e, u, u2, num4, u3, num), }); output[e.WriteOffset + i] = new VoxelInstance { Position = val + val2, Offset = val2, Color = e.Color * (num3 * brightness), CoreColor = e.CoreColor * (num3 * brightness), Scale = e.Scale * (0.09f + 0.05f * num4), Random = CastGeometry.Hash(e.Seed, i, 7) }; } } } private static float3 Ball(in ActiveEmission e, float u0, float u1, float u2, float u3, float age) { //IL_0080: Unknown result type (might be due to invalid IL or missing references) float num = 2f * u1 - 1f; float num2 = math.sqrt(math.max(0f, 1f - num * num)); float num3 = (u3 - 0.5f) * 2.4f; float num4 = default(float); float num5 = default(float); math.sincos(u0 * 2f * (float)Math.PI + age * num3, ref num4, ref num5); float num6 = e.Scale * math.pow(math.max(u2, 0.0001f), 1f / 3f); return new float3(num6 * num2 * num5, num6 * num, num6 * num2 * num4); } private static float3 Sigil(in ActiveEmission e, int v, float u0, float u1, float u2, float u3, float age, float grow, out float brightness) { //IL_00d6: Unknown result type (might be due to invalid IL or missing references) int num = (int)(u0 * 4f); float num2 = (float)(num + 1) / 4f; float num3 = (brightness = math.saturate((grow - (float)num * 0.18f) / 0.35f)); float num4 = e.Scale * num2 * num3; float num5 = ((num % 2 == 0) ? 1f : (-1f)); float num6 = u1 * 2f * (float)Math.PI + age * 0.5f * num5; if (u2 > 0.72f) { num6 = math.floor(u1 * 6f) / 6f * 2f * (float)Math.PI + age * 0.5f * num5; num4 = e.Scale * num3 * (0.15f + u3 * num2); } float num7 = default(float); float num8 = default(float); math.sincos(num6, ref num7, ref num8); float num9 = 0.05f + u3 * 0.12f; return new float3(num4 * num8, num9, num4 * num7); } private static float Closing(in ActiveEmission e, float life) { if (e.Intensity != IntensityCurve.BuildUp) { return math.smoothstep(0.72f, 1f, life); } return 0f; } private static float3 Rise(in ActiveEmission e, float u0, float u1, float u2, float u3, float age, float grow, float life, out float brightness) { //IL_0115: 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) float num = default(float); float num2 = default(float); math.sincos(u1 * 2f * (float)Math.PI + age * 0.22f, ref num, ref num2); float num3 = Closing(in e, life); if (u2 > 0.72f) { float num4 = e.Scale * grow * (0.9f + u3 * 0.12f) * (1f - num3 * 0.88f); float num5 = 0.06f + u0 * 0.1f; brightness = 1.2f; return new float3(num4 * num2, num5, num4 * num); } float num6 = u2 / 0.72f; float num7 = e.Scale * grow * num6 * num6 * (1f - num3 * 0.75f); float num8 = 1.1f + u3 * 1.3f; float num9 = math.saturate(math.frac((age + u0 * num8) / num8) + num3 * 0.55f); float num10 = num9 * e.Scale * (1.5f - num6); float num11 = 1f - num9; brightness = num11 * num11 * (0.7f + 1.9f * (1f - num6)); return new float3(num7 * num2, num10, num7 * num); } private static float3 Wisp(in ActiveEmission e, float u0, float u1, float u2, float u3, float age, float life, out float brightness) { //IL_003d: 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) float num = 2.2f + u3 * 2.4f; float num2 = ((e.GrowDuration > 0f) ? e.GrowDuration : num); float num3 = age - u0 * num2; if (num3 < 0f) { brightness = 0f; return float3.zero; } float num4 = math.frac(num3 / num); float num5 = e.Scale * (0.12f + u2 * 0.8f); float num6 = math.sin(age * 0.9f + u0 * ((float)Math.PI * 2f)) * 0.55f * num4; float num7 = default(float); float num8 = default(float); math.sincos(u1 * 2f * (float)Math.PI + num4 * 1.5f + num6, ref num7, ref num8); float num9 = num5 * (1f + num4 * 0.5f); float num10 = num4 * e.Scale * 2.3f; brightness = math.smoothstep(0f, 0.1f, num4) * (1f - num4) * (1f - num4) * 2.7f; if (e.GrowDuration > 0f && age - num4 * num >= e.GrowDuration) { brightness = 0f; } return new float3(num9 * num8, num10, num9 * num7); } private static float3 Converge(in ActiveEmission e, float u0, float u1, float u2, float u3, float age, out float brightness) { //IL_00a5: Unknown result type (might be due to invalid IL or missing references) float num = 1.1f + u3 * 1.4f; float num2 = math.frac((age + u0 * num) / num); float num3 = e.Scale * (1f - num2) * (0.7f + u2 * 0.6f); float num4 = (1f - num2) * (1f - num2) * e.Scale * 0.9f + 0.1f; float num5 = default(float); float num6 = default(float); math.sincos(u1 * 2f * (float)Math.PI + num2 * 6f, ref num5, ref num6); brightness = math.smoothstep(0f, 0.25f, num2) * (0.4f + 0.6f * num2); return new float3(num3 * num6, num4, num3 * num5); } private static float3 Burst(in ActiveEmission e, float u0, float u1, float u2, float life, out float brightness) { //IL_0085: Unknown result type (might be due to invalid IL or missing references) float num = math.lerp(-0.15f, 1f, u1); float num2 = math.sqrt(math.max(0f, 1f - num * num)); float num3 = default(float); float num4 = default(float); math.sincos(u0 * 2f * (float)Math.PI, ref num3, ref num4); float num5 = e.Scale * math.sqrt(life) * (0.55f + u2 * 0.65f); brightness = (1f - life) * 1.8f; return new float3(num5 * num2 * num4, num5 * num * 0.55f, num5 * num2 * num3); } private static float3 Beam(in ActiveEmission e, float u0, float u1, float u2, float u3, float age, out float brightness) { //IL_008c: 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) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: 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) float num = u0 * e.ArrivalHeight; float num2 = default(float); float num3 = default(float); math.sincos(u1 * 2f * (float)Math.PI + age * (5f + u2 * 7f), ref num2, ref num3); float num4 = e.Scale * (0.25f + 0.75f * (num / math.max(e.ArrivalHeight, 0.001f))); float num5 = num4 * (0.15f + u3 * 0.85f); brightness = 0.5f + 0.9f * (1f - num5 / math.max(num4, 0.001f)); return e.Direction * num + e.Right * (num5 * num3) + e.Up * (num5 * num2); } private static float3 Column(in ActiveEmission e, float u0, float u1, float u2, float age, float grow, out float brightness) { //IL_006d: Unknown result type (might be due to invalid IL or missing references) float num = u1 * u1; float num2 = num * e.ArrivalHeight * grow; float num3 = 1f - 0.65f * num; float num4 = e.Scale * num3 * (0.35f + u2 * 0.5f); float num5 = default(float); float num6 = default(float); math.sincos(u0 * 2f * (float)Math.PI + age * 2.2f, ref num5, ref num6); brightness = 0.45f + 0.75f * num3; return new float3(num4 * num6, num2, num4 * num5); } } public const int MaxEmissions = 512; public const int MaxVoxels = 65536; private NativeArray _emissions; private int _count; public int ActiveCount => _count; public int VoxelCount { get; private set; } public bool HasFollowers { get { for (int i = 0; i < _count; i++) { if (_emissions[i].FollowsCaster) { return true; } } return false; } } public SpellRuntime() { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) _emissions = new NativeArray(512, (Allocator)4, (NativeArrayOptions)1); } public bool TryAdd(in ActiveEmission emission) { if (_count >= 512) { return false; } _emissions[_count++] = emission; return true; } public void Clear() { _count = 0; VoxelCount = 0; } public bool TryGet(int index, out ActiveEmission emission) { if (index < 0 || index >= _count) { emission = default(ActiveEmission); return false; } emission = _emissions[index]; return true; } public void Set(int index, in ActiveEmission emission) { if (index >= 0 && index < _count) { _emissions[index] = emission; } } public void RetireAt(int index) { if (index >= 0 && index < _count) { for (int i = index + 1; i < _count; i++) { _emissions[i - 1] = _emissions[i]; } _count--; } } public void RetireAll(IReadOnlyList ascending) { if (ascending == null || ascending.Count == 0) { return; } int num = 0; int num2 = 0; for (int i = 0; i < _count; i++) { if (num < ascending.Count && ascending[num] == i) { num++; continue; } if (num2 != i) { _emissions[num2] = _emissions[i]; } num2++; } _count = num2; } public void Retire(float now) { int num = 0; for (int i = 0; i < _count; i++) { if (now - _emissions[i].BirthTime < _emissions[i].Lifetime) { if (num != i) { _emissions[num] = _emissions[i]; } num++; } } _count = num; } public void MoveFollowers(float3 origin) { //IL_0026: 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) for (int i = 0; i < _count; i++) { if (_emissions[i].FollowsCaster) { ActiveEmission activeEmission = _emissions[i]; activeEmission.Origin = origin; _emissions[i] = activeEmission; } } } public void AimBeam(int groupId, int beamIndex, float3 origin, float3 direction, float3 right, float3 up, float reach) { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004c: 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_0057: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < _count; i++) { if (_emissions[i].GroupId == groupId && _emissions[i].BeamIndex == beamIndex) { ActiveEmission activeEmission = _emissions[i]; activeEmission.Origin = origin; activeEmission.Direction = direction; activeEmission.Right = right; activeEmission.Up = up; activeEmission.ArrivalHeight = reach; _emissions[i] = activeEmission; break; } } } public void RetireGroup(int groupId) { if (groupId == 0) { return; } int num = 0; for (int i = 0; i < _count; i++) { if (_emissions[i].GroupId != groupId) { if (num != i) { _emissions[num] = _emissions[i]; } num++; } } _count = num; } public int BuildVoxels(NativeArray output, float now, int[] groupOfPattern, VoxelRange[] ranges) { //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01ef: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Unknown result type (might be due to invalid IL or missing references) //IL_01f7: Unknown result type (might be due to invalid IL or missing references) //IL_020f: Unknown result type (might be due to invalid IL or missing references) //IL_0215: Unknown result type (might be due to invalid IL or missing references) //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < ranges.Length; i++) { ranges[i] = default(VoxelRange); } if (_count == 0) { VoxelCount = 0; return 0; } int num = math.min(output.Length, 65536); int num2 = 0; for (int j = 0; j < _count; j++) { ActiveEmission activeEmission = _emissions[j]; int num3 = num - num2; bool flag = now < activeEmission.BirthTime; activeEmission.DrawCount = ((!flag && num3 > 0) ? math.min(activeEmission.VoxelCount, num3) : 0); num2 += activeEmission.DrawCount; _emissions[j] = activeEmission; if (activeEmission.DrawCount > 0) { int num4 = GroupOf(groupOfPattern, ranges.Length, activeEmission.Pattern); ranges[num4].Count += activeEmission.DrawCount; } } VoxelCount = num2; if (num2 == 0) { return 0; } int num5 = 0; for (int k = 0; k < ranges.Length; k++) { ranges[k].Start = num5; num5 += ranges[k].Count; } for (int l = 0; l < _count; l++) { ActiveEmission activeEmission2 = _emissions[l]; if (activeEmission2.DrawCount > 0) { int num6 = GroupOf(groupOfPattern, ranges.Length, activeEmission2.Pattern); activeEmission2.WriteOffset = ranges[num6].Start; ranges[num6].Start += activeEmission2.DrawCount; _emissions[l] = activeEmission2; } } for (int m = 0; m < ranges.Length; m++) { ranges[m].Start -= ranges[m].Count; } ExpandJob obj = new ExpandJob { emissions = _emissions, output = output, now = now }; int count = _count; JobHandle val = default(JobHandle); val = IJobParallelForExtensions.Schedule(obj, count, 8, val); ((JobHandle)(ref val)).Complete(); return num2; } private static int GroupOf(int[] groupOfPattern, int groupCount, VoxelPattern pattern) { if (groupOfPattern == null || pattern < VoxelPattern.Ball || (int)pattern >= groupOfPattern.Length) { return 0; } int num = groupOfPattern[(int)pattern]; if (num < 0 || num >= groupCount) { return 0; } return num; } public void Dispose() { if (_emissions.IsCreated) { _emissions.Dispose(); } } public static float3 Evaluate(in ActiveEmission e, float age) { //IL_0012: 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_005a: 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_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) switch (e.Delivery) { case DeliveryKind.Anchored: return e.Origin; case DeliveryKind.Descend: { if (e.ArrivalDelay <= 0f) { return e.Origin; } float num = math.saturate(age / e.ArrivalDelay); float num2 = num * num; return e.Origin + new float3(0f, e.ArrivalHeight * (1f - num2), 0f); } default: return EvaluateProjectile(in e, age); } } private static float3 EvaluateProjectile(in ActiveEmission e, float age) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: 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_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: 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_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_0129: 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_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) float3 val = e.Direction * (e.Speed * age); switch (e.Motion) { case MotionKind.Arc: return e.Origin + val + new float3(0f, -9.8f, 0f) * (0.5f * age * age); case MotionKind.Spiral: { float num3 = default(float); float num4 = default(float); math.sincos(age * 2.2f * 2f * (float)Math.PI, ref num3, ref num4); return e.Origin + val + (e.Right * num4 + e.Up * num3) * 0.55f; } case MotionKind.Orbit: { float num = default(float); float num2 = default(float); math.sincos(age * 0.9f * 2f * (float)Math.PI, ref num, ref num2); return e.Origin + val * 0.2f + (e.Right * num2 + e.Up * num) * 2.2f; } case MotionKind.Homing: return e.Origin + val; default: return e.Origin + val; } } } } namespace UnholyRites.Spells.Casting { public readonly struct CastAuthority { private readonly bool _elsewhere; public bool SuppressDamage { get; } public int CasterSlot { get; } public bool Mine => !_elsewhere; public static CastAuthority Local => default(CastAuthority); public static CastAuthority Own => new CastAuthority(suppressDamage: true, 0, elsewhere: false); public static CastAuthority VisualOnly => new CastAuthority(suppressDamage: true, 0, elsewhere: true); private CastAuthority(bool suppressDamage, int casterSlot, bool elsewhere) { SuppressDamage = suppressDamage; CasterSlot = casterSlot; _elsewhere = elsewhere; } public static CastAuthority Replayed(int rosterIndex) { if (rosterIndex < 0) { return VisualOnly; } return new CastAuthority(suppressDamage: false, rosterIndex + 1, elsewhere: true); } public static CastAuthority Inherited(bool suppressDamage, int casterSlot, bool mine) { return new CastAuthority(suppressDamage, casterSlot, !mine); } } public struct LaunchFrame { public float3 Origin; public float3 Direction; public float3 Right; public float3 Up; } public static class CastGeometry { public static LaunchFrame Resolve(in Emission emission, float3 origin, float3 aimDirection, uint castSeed) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0030: 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_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_0228: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: 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_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Unknown result type (might be due to invalid IL or missing references) //IL_0182: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_018a: Unknown result type (might be due to invalid IL or missing references) //IL_018d: Unknown result type (might be due to invalid IL or missing references) //IL_0192: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01a6: Unknown result type (might be due to invalid IL or missing references) //IL_01ed: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: Unknown result type (might be due to invalid IL or missing references) //IL_01fe: Unknown result type (might be due to invalid IL or missing references) //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_020f: Unknown result type (might be due to invalid IL or missing references) //IL_0218: Unknown result type (might be due to invalid IL or missing references) //IL_021d: Unknown result type (might be due to invalid IL or missing references) //IL_0222: Unknown result type (might be due to invalid IL or missing references) float3 val = math.normalizesafe(aimDirection, new float3(0f, 0f, 1f)); BuildBasis(val, out var right, out var up); LaunchFrame result = new LaunchFrame { Origin = origin, Direction = val, Right = right, Up = up }; int formationIndex = emission.FormationIndex; int num = ((emission.FormationCount <= 0) ? 1 : emission.FormationCount); switch (emission.Formation) { case FormationKind.Single: if (num > 1) { float num8 = (float)formationIndex / (float)(num - 1) * 2f - 1f; result.Origin = origin + right * (num8 * 0.28f); result.Direction = math.normalizesafe(val + right * (num8 * 0.05f), val); } break; case FormationKind.Spread: { float num6 = Hash01(castSeed, formationIndex, 0) * 2f - 1f; float num7 = Hash01(castSeed, formationIndex, 1) * 2f - 1f; result.Direction = math.normalizesafe(val + right * (num6 * 0.14f) + up * (num7 * 0.14f), val); break; } case FormationKind.Ring: { float num9 = default(float); float num10 = default(float); math.sincos((num > 1) ? ((float)formationIndex / (float)num * 2f * (float)Math.PI) : 0f, ref num9, ref num10); result.Origin = origin + (right * num10 + up * num9) * 1.1f; break; } case FormationKind.Spiral: { float num2 = ((num > 1) ? ((float)formationIndex / (float)(num - 1)) : 0f); float num3 = default(float); float num4 = default(float); math.sincos(num2 * 4f * (float)Math.PI, ref num3, ref num4); float num5 = 0.35f + num2 * 0.9f; result.Origin = origin + (right * num4 + up * num3) * num5 + val * (num2 * 1.5f); break; } } BuildBasis(result.Direction, out result.Right, out result.Up); return result; } public static float3 ResolveGroundOffset(in Emission emission, float3 anchor) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_0152: 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_0099: 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_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) int formationIndex = emission.FormationIndex; int num = ((emission.FormationCount <= 0) ? 1 : emission.FormationCount); if (num <= 1) { return anchor; } float3 val = default(float3); ((float3)(ref val))..ctor(1f, 0f, 0f); float3 val2 = default(float3); ((float3)(ref val2))..ctor(0f, 0f, 1f); FormationKind formation = emission.Formation; if ((uint)(formation - 2) <= 1u) { float num2 = default(float); float num3 = default(float); math.sincos((float)formationIndex / (float)num * 2f * (float)Math.PI, ref num2, ref num3); float num4 = ((emission.Formation == FormationKind.Spiral) ? (0.9f + (float)formationIndex / (float)num * 1.8f) : 1.6f); return anchor + (val * num3 + val2 * num2) * num4; } float num5 = ((num > 1) ? ((float)formationIndex / (float)(num - 1)) : 0f); float num6 = default(float); float num7 = default(float); math.sincos((float)formationIndex * 2.399963f, ref num6, ref num7); float num8 = 1.7f * math.sqrt(num5); float num9 = 0.35f; float num10 = num7 * num8 + (Hash01(2654435769u, formationIndex, 0) * 2f - 1f) * num9; float num11 = num6 * num8 + (Hash01(2654435769u, formationIndex, 1) * 2f - 1f) * num9; return anchor + (val * num10 + val2 * num11); } public static void BuildBasis(float3 forward, out float3 right, out float3 up) { //IL_0000: 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_0021: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_003e: 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_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: 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_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: 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) float3 val = ((math.abs(forward.y) > 0.99f) ? new float3(1f, 0f, 0f) : new float3(0f, 1f, 0f)); right = math.normalizesafe(math.cross(val, forward), new float3(1f, 0f, 0f)); up = math.cross(forward, right); } public static uint Hash(uint seed, int a, int b) { int num = (int)(seed ^ (uint)(a * 747796405)) ^ (int)(b * 2891336453u); int num2 = (num ^ (num >>> 15)) * -2048144777; int num3 = (num2 ^ (num2 >>> 13)) * -1028477379; return (uint)(num3 ^ (num3 >>> 16)); } public static float Hash01(uint seed, int a, int b) { return (float)(Hash(seed, a, b) & 0xFFFFFF) / 16777215f; } } public sealed class ManaPool { private float _updatedAt = -1f; public float Capacity { get; private set; } public float RechargePerSecond { get; private set; } public float Current { get; private set; } public float QuietUntil { get; private set; } = float.NegativeInfinity; public float Normalized { get { if (!(Capacity > 0f)) { return 0f; } return Current / Capacity; } } public ManaPool(float capacity, float rechargePerSecond) { Capacity = ((capacity > 0f) ? capacity : 1f); RechargePerSecond = ((rechargePerSecond > 0f) ? rechargePerSecond : 0f); Current = Capacity; } public bool CanAfford(float cost) { return cost <= Current; } public void Recharge(float deltaSeconds) { if (!(deltaSeconds <= 0f) && !(Current >= Capacity)) { Current += RechargePerSecond * deltaSeconds; if (Current > Capacity) { Current = Capacity; } } } public void CatchUp(float now) { if (_updatedAt >= 0f && now > _updatedAt) { float num = ((_updatedAt > QuietUntil) ? _updatedAt : QuietUntil); if (now > num) { Recharge(now - num); } } _updatedAt = now; } public bool TryConsume(float cost) { if (cost > Current) { return false; } Current -= cost; if (Current < 0f) { Current = 0f; } return true; } public void Configure(float capacity, float rechargePerSecond) { Capacity = ((capacity > 0f) ? capacity : 1f); RechargePerSecond = ((rechargePerSecond > 0f) ? rechargePerSecond : 0f); if (Current > Capacity) { Current = Capacity; } } public void Hush(float until) { if (until > QuietUntil) { QuietUntil = until; } } public void Add(float amount) { if (!(amount <= 0f)) { Current += amount; if (Current > Capacity) { Current = Capacity; } } } public void Refill() { Current = Capacity; } } public sealed class PayloadTable { public struct Entry { public PayloadTrigger Trigger; public IReadOnlyList Emissions; public float ChargedCost; public int BaseSlot; } public const int MaxEntries = 512; private readonly List _entries = new List(); private readonly Dictionary _bases = new Dictionary(StringComparer.Ordinal); public int Count => _entries.Count; public bool Overflowed { get; private set; } public int Register(CastPlan plan) { if (plan == null || plan.Payloads.Count == 0) { return 0; } string key = ProgramKey(plan); if (_bases.TryGetValue(key, out var value)) { return value; } if (_entries.Count + plan.Payloads.Count > 512) { Overflowed = true; return 0; } int num = _entries.Count + 1; for (int i = 0; i < plan.Payloads.Count; i++) { PayloadPlan payloadPlan = plan.Payloads[i]; _entries.Add(new Entry { Trigger = payloadPlan.Trigger, Emissions = payloadPlan.Emissions, ChargedCost = payloadPlan.ChargedCost, BaseSlot = num }); } _bases[key] = num; return num; } private static string ProgramKey(CastPlan plan) { SpellKey[] program = plan.Program; string[] array = new string[program.Length]; for (int i = 0; i < program.Length; i++) { array[i] = program[i].Value; } return string.Join(">", array); } public bool TryGet(int slot, out Entry entry) { if (slot < 1 || slot > _entries.Count) { entry = default(Entry); return false; } entry = _entries[slot - 1]; return true; } public static int Resolve(int localSlot, int baseSlot) { if (localSlot > 0 && baseSlot > 0) { return baseSlot + localSlot - 1; } return 0; } public void Clear() { _entries.Clear(); _bases.Clear(); Overflowed = false; } } public static class RecentCasts { public struct Record { public uint Seed; public int BaseSlot; public bool SuppressDamage; public int CasterSlot; public bool Mine; public CastFlags Flags; public float At; } public const float Memory = 60f; private static readonly Record[] Ring = new Record[256]; private static int _next; public static void Note(uint seed, int baseSlot, in CastAuthority authority, CastFlags flags, float now) { Ring[_next] = new Record { Seed = seed, BaseSlot = baseSlot, SuppressDamage = authority.SuppressDamage, CasterSlot = authority.CasterSlot, Mine = authority.Mine, Flags = flags, At = now }; _next = (_next + 1) % Ring.Length; } public static bool TryGet(uint seed, float now, out Record record) { for (int i = 1; i <= Ring.Length; i++) { int num = (_next - i + Ring.Length) % Ring.Length; Record record2 = Ring[num]; if (record2.At > 0f && record2.Seed == seed && now - record2.At <= 60f && now >= record2.At) { record = record2; return true; } } record = default(Record); return false; } public static void Clear() { Array.Clear(Ring, 0, Ring.Length); _next = 0; } } public enum CastResult { Fired, NothingToCast, NotEnoughMana, OnCooldown } public static class SpellPresentation { public static void Colors(ElementKind element, out float3 main, out float3 core) { //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_0053: 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_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) //IL_0088: 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_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_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_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0161: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) switch (element) { case ElementKind.Fire: main = new float3(1f, 0.35f, 0.08f); core = new float3(1f, 0.9f, 0.6f); break; case ElementKind.Frost: main = new float3(0.35f, 0.7f, 1f); core = new float3(0.85f, 0.96f, 1f); break; case ElementKind.Holy: main = new float3(1f, 0.94f, 0.66f); core = new float3(1f, 1f, 0.92f); break; case ElementKind.Dark: main = new float3(0.42f, 0.12f, 0.55f); core = new float3(0.8f, 0.5f, 0.95f); break; case ElementKind.Explosive: main = new float3(0.55f, 0.36f, 0.22f); core = new float3(1f, 0.78f, 0.38f); break; default: main = new float3(0.8f, 0.8f, 0.8f); core = new float3(1f, 1f, 1f); break; } } public static void RaisedColors(out float3 main, out float3 core) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) main = new float3(0.28f, 0.08f, 0.42f); core = new float3(0.95f, 0.95f, 1f); } public static void RaisedWispColors(out float3 main, out float3 core) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) main = new float3(0.3f, 0.95f, 0.45f); core = new float3(0.82f, 1f, 0.8f); } public static int VoxelCount(VisualKind visual, float scale, float densityMultiplier) { int num = visual switch { VisualKind.Cluster => 220, VisualKind.Beam => 48, _ => 110, }; float num2 = math.clamp(scale / 0.4f, 0.6f, 2.5f); float num3 = math.clamp(densityMultiplier, 0.1f, 8f); return math.max(4, (int)((float)num * num2 * num3)); } } public struct CastTarget { public float3 Origin; public float3 Direction; public float3 Point; public bool HasPoint; public float3 Caster; } public static class SpellCaster { private const float WispTail = 2.4f; private const float ReleaseLife = 0.8f; private const uint WispSalt = 2654435769u; public static CastResult Cast(CastPlan plan, SpellRuntime runtime, ManaPool mana, PayloadTable payloads, in CastTarget target, uint seed, float now, float voxelDensity = 1f, CastAuthority authority = default(CastAuthority)) { if (plan == null || plan.EmissionCount == 0) { return CastResult.NothingToCast; } if (mana != null && !mana.CanAfford(plan.ManaCost)) { return CastResult.NotEnoughMana; } mana?.TryConsume(plan.ManaCost); int num = payloads?.Register(plan) ?? 0; RecentCasts.Note(seed, num, in authority, plan.Flags, now); for (int i = 0; i < plan.EmissionCount; i++) { Emission emission = plan.Emissions[i]; ActiveEmission emission2 = Build(in emission, in target, seed, now, voxelDensity, i, Weight(in emission), num, plan.IsRitual); emission2.SuppressDamage = authority.SuppressDamage; emission2.CasterSlot = authority.CasterSlot; emission2.LocalCast = authority.Mine; emission2.Flags = plan.Flags; if (!runtime.TryAdd(in emission2)) { break; } if (emission2.Delivery == DeliveryKind.Descend && emission2.ArrivalDelay > 0f) { QueueImpact(runtime, in emission2, seed, now, voxelDensity); } if (emission2.Raises && !plan.IsRitual) { AddWisps(runtime, in emission2, seed, voxelDensity); } } return CastResult.Fired; } public static void CastPayload(in PayloadTable.Entry payload, SpellRuntime runtime, in CastTarget target, uint seed, float now, float voxelDensity, CastAuthority authority, PayloadTable table = null, int ignoreUnit = 0, uint castSeed = 0u, CastFlags flags = CastFlags.None) { IReadOnlyList emissions = payload.Emissions; if (emissions == null || emissions.Count == 0) { return; } for (int i = 0; i < emissions.Count; i++) { ActiveEmission emission = Build(emissions[i], in target, seed, now, voxelDensity, i, Weight(emissions[i]), payload.BaseSlot); emission.SuppressDamage = authority.SuppressDamage; emission.CasterSlot = authority.CasterSlot; emission.LocalCast = authority.Mine; emission.IgnoreUnit = ignoreUnit; emission.CastSeed = castSeed; emission.Flags = flags; if (runtime.TryAdd(in emission)) { if (emission.Delivery == DeliveryKind.Descend && emission.ArrivalDelay > 0f) { QueueImpact(runtime, in emission, seed, now, voxelDensity); } if (emission.Raises) { AddWisps(runtime, in emission, seed, voxelDensity); } continue; } break; } } private static float Weight(in Emission emission) { return emission.Cost + emission.Carried; } private static ActiveEmission Build(in Emission emission, in CastTarget target, uint seed, float now, float voxelDensity, int index, float weight, int payloadBaseSlot, bool alreadyDrawn = false) { //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: 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_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_0284: Unknown result type (might be due to invalid IL or missing references) //IL_028a: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Unknown result type (might be due to invalid IL or missing references) //IL_02a0: Unknown result type (might be due to invalid IL or missing references) //IL_02a9: Unknown result type (might be due to invalid IL or missing references) //IL_02ae: Unknown result type (might be due to invalid IL or missing references) //IL_02b7: Unknown result type (might be due to invalid IL or missing references) //IL_02bc: Unknown result type (might be due to invalid IL or missing references) //IL_02c5: Unknown result type (might be due to invalid IL or missing references) //IL_02ca: Unknown result type (might be due to invalid IL or missing references) //IL_02f8: Unknown result type (might be due to invalid IL or missing references) //IL_02db: Unknown result type (might be due to invalid IL or missing references) //IL_02e1: Unknown result type (might be due to invalid IL or missing references) //IL_02eb: Unknown result type (might be due to invalid IL or missing references) //IL_02f0: Unknown result type (might be due to invalid IL or missing references) //IL_02fd: Unknown result type (might be due to invalid IL or missing references) //IL_036d: Unknown result type (might be due to invalid IL or missing references) //IL_036f: Unknown result type (might be due to invalid IL or missing references) //IL_0374: Unknown result type (might be due to invalid IL or missing references) //IL_038a: Unknown result type (might be due to invalid IL or missing references) //IL_038f: Unknown result type (might be due to invalid IL or missing references) //IL_03a5: Unknown result type (might be due to invalid IL or missing references) //IL_03aa: Unknown result type (might be due to invalid IL or missing references) //IL_03c0: Unknown result type (might be due to invalid IL or missing references) //IL_03c5: Unknown result type (might be due to invalid IL or missing references) //IL_032a: Unknown result type (might be due to invalid IL or missing references) //IL_032f: Unknown result type (might be due to invalid IL or missing references) //IL_0333: Unknown result type (might be due to invalid IL or missing references) //IL_0339: Unknown result type (might be due to invalid IL or missing references) //IL_033b: Unknown result type (might be due to invalid IL or missing references) //IL_0345: Unknown result type (might be due to invalid IL or missing references) //IL_034a: Unknown result type (might be due to invalid IL or missing references) //IL_035e: Unknown result type (might be due to invalid IL or missing references) //IL_0363: Unknown result type (might be due to invalid IL or missing references) //IL_0368: Unknown result type (might be due to invalid IL or missing references) ProjectileArchetype archetype = emission.Archetype; DeliverySpec delivery = emission.Delivery; SpellPresentation.Colors(archetype.Element, out var main, out var core); if (emission.Raises) { SpellPresentation.RaisedColors(out main, out core); } float num = ((archetype.Scale > 0f) ? archetype.Scale : 0.3f); ActiveEmission result = new ActiveEmission { Delivery = delivery.Kind, Motion = archetype.Motion, Pattern = archetype.Pattern, Speed = archetype.Speed, BirthTime = now, Lifetime = ((archetype.Lifetime > 0f) ? archetype.Lifetime : 3f), Scale = num, Color = main, CoreColor = core, ArrivalDelay = delivery.ArrivalDelay, ArrivalHeight = delivery.ArrivalHeight, VoxelCount = SpellPresentation.VoxelCount(archetype.Visual, num, voxelDensity), Power = SpellScale.Power(weight), Collision = archetype.Collision, Element = archetype.Element, Voice = archetype.Voice, Damage = archetype.Damage, Mark = archetype.Mark, MarkAmount = archetype.MarkAmount, Spill = archetype.Spill, Bursts = archetype.Bursts, MarkOnly = archetype.MarkOnly, HitRadius = ((archetype.Collision == CollisionKind.Sphere) ? num : 0.08f), ImpactRadius = SpellScale.ImpactRadius(num, weight), Seed = (seed ^ (uint)(int)(index * 2654435761u)), HitSlot = PayloadTable.Resolve(emission.HitSlot, payloadBaseSlot), MissSlot = PayloadTable.Resolve(emission.MissSlot, payloadBaseSlot), KillSlot = PayloadTable.Resolve(emission.KillSlot, payloadBaseSlot), KillBudget = emission.Kills, HitsLeft = emission.Hits, PierceLeft = emission.Pierces, BounceLeft = emission.Bounces, Push = emission.Push, CastSeed = seed }; if (delivery.Kind == DeliveryKind.Anchored && archetype.TickInterval > 0f) { result.TickInterval = archetype.TickInterval; result.NextTickAge = archetype.TickInterval; result.HitRadius = num; } if (delivery.Kind == DeliveryKind.Projectile) { LaunchFrame launchFrame = CastGeometry.Resolve(in emission, target.Origin, target.Direction, seed); result.Origin = launchFrame.Origin; result.Direction = launchFrame.Direction; result.Right = launchFrame.Right; result.Up = launchFrame.Up; return result; } float3 anchor = (target.HasPoint ? target.Point : (target.Origin + target.Direction * 8f)); if (archetype.AtCaster) { float3 val = default(float3); ((float3)(ref val))..ctor(target.Direction.x, 0f, target.Direction.z); anchor = target.Origin - math.normalizesafe(val, default(float3)) * 1.2f + new float3(0f, -1.5f, 0f); } result.Origin = CastGeometry.ResolveGroundOffset(in emission, anchor); result.Direction = new float3(0f, -1f, 0f); result.Right = new float3(1f, 0f, 0f); result.Up = new float3(0f, 0f, 1f); if (delivery.Kind == DeliveryKind.Descend) { if (result.ArrivalHeight <= 0f) { result.ArrivalHeight = 25f; } if (result.ArrivalDelay <= 0f) { result.ArrivalDelay = 1f; } if (archetype.TickInterval > 0f && !emission.Raises) { result.TickInterval = archetype.TickInterval; result.NextTickAge = result.ArrivalDelay + archetype.TickInterval; result.HitRadius = num; result.Lifetime += result.ArrivalDelay; } } if (emission.Raises) { result.Raises = true; result.Consumes = emission.Consumes; float num2 = ((delivery.Kind == DeliveryKind.Descend) ? result.ArrivalDelay : 0f); if (alreadyDrawn) { result.Pattern = VoxelPattern.Burst; result.Intensity = IntensityCurve.FadeOut; result.GrowDuration = 0f; result.Lifetime = num2 + 0.8f; result.RaiseAge = num2; } else { result.RaiseAge = num2 + emission.RaiseDelay; result.GrowDuration = result.RaiseAge; result.Lifetime = math.max(result.Lifetime, result.RaiseAge + 1.1f); } } return result; } public static void BeginWindup(CastPlan plan, SpellRuntime runtime, in CastTarget target, uint seed, float now, int groupId, bool followsCaster, float voxelDensity = 1f) { //IL_0024: 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_0029: 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_008e: 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_006a: 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_006f: Unknown result type (might be due to invalid IL or missing references) if (plan != null && !(plan.CastTime <= 0.05f)) { bool hasPoint = target.HasPoint; float3 anchor = (hasPoint ? target.Point : target.Caster); ElementKind element = ((plan.EmissionCount > 0) ? plan.Emissions[0].Archetype.Element : ElementKind.Dark); if (plan.Raises) { SpellPresentation.RaisedColors(out var main, out var core); BuildWindup(plan, runtime, in target, seed, now, groupId, followsCaster, voxelDensity, main, core, hasPoint, anchor, raises: true); } else { SpellPresentation.Colors(element, out var main2, out var core2); BuildWindup(plan, runtime, in target, seed, now, groupId, followsCaster, voxelDensity, main2, core2, hasPoint, anchor, raises: false); } } } private static void BuildWindup(CastPlan plan, SpellRuntime runtime, in CastTarget target, uint seed, float now, int groupId, bool followsCaster, float voxelDensity, float3 main, float3 core, bool aimed, float3 anchor, bool raises) { //IL_0036: 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_006f: 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_0078: 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_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_016f: 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) //IL_0178: Unknown result type (might be due to invalid IL or missing references) float power = SpellScale.Power(plan.TotalCost); ActiveEmission emission = new ActiveEmission { Delivery = DeliveryKind.Anchored, Pattern = ((!raises) ? VoxelPattern.Sigil : VoxelPattern.Rise), Intensity = IntensityCurve.BuildUp, Origin = anchor, BirthTime = now, Lifetime = plan.CastTime, GrowDuration = plan.CastTime, Scale = SpellScale.SigilRadius(plan), Color = main, CoreColor = core, VoxelCount = SpellScale.Voxels(700f, power, voxelDensity), Seed = (seed ^ 0x51ED270B), GroupId = groupId, FollowsCaster = (followsCaster && !aimed), Consumes = (raises && plan.Consumes), LocalCast = followsCaster }; runtime.TryAdd(in emission); if (raises) { runtime.TryAdd(BuildWisps(plan, anchor, seed, now, voxelDensity, groupId, followsCaster && !aimed)); } else if (aimed) { emission = new ActiveEmission { Delivery = DeliveryKind.Anchored, Pattern = VoxelPattern.Converge, Intensity = IntensityCurve.BuildUp, Origin = anchor, BirthTime = now, Lifetime = plan.CastTime, GrowDuration = plan.CastTime, Scale = SpellScale.VortexRadius(plan), Color = core, CoreColor = core, VoxelCount = SpellScale.Voxels(400f, power, voxelDensity), Seed = (seed ^ 0x2545F491), GroupId = groupId }; runtime.TryAdd(in emission); } } public static void Culminate(CastPlan plan, SpellRuntime runtime, in CastTarget target, uint seed, float now, bool followsCaster, float voxelDensity = 1f) { //IL_001f: 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_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0204: Unknown result type (might be due to invalid IL or missing references) //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_0242: Unknown result type (might be due to invalid IL or missing references) //IL_0249: Unknown result type (might be due to invalid IL or missing references) //IL_024b: 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_012a: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0166: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) if (plan == null || plan.EmissionCount == 0) { return; } bool hasPoint = target.HasPoint; float3 val = (hasPoint ? target.Point : target.Caster); bool raises = plan.Raises; float3 main; float3 core; if (raises) { SpellPresentation.RaisedColors(out main, out core); } else { SpellPresentation.Colors(plan.Emissions[0].Archetype.Element, out main, out core); } float num = 0f; float num2 = 0f; for (int i = 0; i < plan.EmissionCount; i++) { DeliverySpec delivery = plan.Emissions[i].Delivery; if (delivery.Kind == DeliveryKind.Descend) { num = math.max(num, delivery.ArrivalDelay); num2 = math.max(num2, delivery.ArrivalHeight); } } float arrivalHeight = ((num2 > 0f) ? num2 : 14f); float num3 = ((num > 0f) ? (num + 0.35f) : 0.9f); float power = SpellScale.Power(plan.TotalCost); ActiveEmission emission; if (hasPoint && num > 0f) { emission = new ActiveEmission { Delivery = DeliveryKind.Anchored, Pattern = VoxelPattern.Column, Intensity = IntensityCurve.FadeOut, Origin = val, BirthTime = now, Lifetime = num3, GrowDuration = 0.18f, Scale = SpellScale.BeamThickness(plan), ArrivalHeight = arrivalHeight, Color = core, CoreColor = new float3(1f, 1f, 1f), VoxelCount = SpellScale.Voxels(800f, power, voxelDensity), Seed = (seed ^ 0x7F4A7C15) }; runtime.TryAdd(in emission); } if (raises) { runtime.TryAdd(BuildWisps(plan, val, seed, now - plan.CastTime, voxelDensity, 0, followsCaster && !hasPoint)); return; } emission = new ActiveEmission { Delivery = DeliveryKind.Anchored, Pattern = VoxelPattern.Sigil, Intensity = IntensityCurve.FadeOut, Origin = val, BirthTime = now, Lifetime = math.max(num3, 1.2f), GrowDuration = 0.001f, Scale = SpellScale.SigilRadius(plan), Color = main, CoreColor = core, VoxelCount = SpellScale.Voxels(500f, power, voxelDensity), Seed = (seed ^ 0x51ED270B), FollowsCaster = (followsCaster && !hasPoint) }; runtime.TryAdd(in emission); } private static ActiveEmission BuildWisps(CastPlan plan, float3 anchor, uint seed, float birth, float voxelDensity, int groupId, bool followsCaster) { //IL_002b: 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_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0070: 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) SpellPresentation.RaisedWispColors(out var main, out var core); return new ActiveEmission { Delivery = DeliveryKind.Anchored, Pattern = VoxelPattern.Wisp, Intensity = IntensityCurve.FadeOut, Origin = anchor, BirthTime = birth, Lifetime = plan.CastTime + 2.4f, GrowDuration = plan.CastTime, Scale = SpellScale.SigilRadius(plan), Color = main, CoreColor = core, Power = SpellScale.Power(plan.TotalCost), VoxelCount = SpellScale.Voxels(150f, SpellScale.Power(plan.TotalCost), voxelDensity), Seed = (seed ^ 0x9E3779B9u), GroupId = groupId, FollowsCaster = followsCaster }; } private static void AddWisps(SpellRuntime runtime, in ActiveEmission rite, uint seed, float voxelDensity) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0047: 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_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: 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_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008f: 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) SpellPresentation.RaisedWispColors(out var main, out var core); ActiveEmission emission = new ActiveEmission { Delivery = DeliveryKind.Anchored, Pattern = VoxelPattern.Wisp, Intensity = IntensityCurve.FadeOut, Origin = rite.Origin, Direction = rite.Direction, Right = rite.Right, Up = rite.Up, BirthTime = rite.BirthTime, Lifetime = rite.Lifetime, Scale = rite.Scale, Color = main, CoreColor = core, Power = rite.Power, GrowDuration = rite.RaiseAge, VoxelCount = math.max(12, rite.VoxelCount / 5), Seed = (rite.Seed ^ 0x9E3779B9u), CasterSlot = rite.CasterSlot, SuppressDamage = true, FollowsCaster = rite.FollowsCaster }; runtime.TryAdd(in emission); } private static void QueueImpact(SpellRuntime runtime, in ActiveEmission arrival, uint seed, float now, float voxelDensity) { //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_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) ActiveEmission emission = new ActiveEmission { Delivery = DeliveryKind.Anchored, Pattern = VoxelPattern.Burst, Intensity = IntensityCurve.FadeOut, Origin = arrival.Origin, BirthTime = now + arrival.ArrivalDelay, Lifetime = 0.55f, Scale = ((arrival.ImpactRadius > 0f) ? arrival.ImpactRadius : (3f + arrival.Scale * 2f)), Power = arrival.Power, Color = arrival.Color, CoreColor = new float3(1f, 1f, 1f), VoxelCount = (int)math.clamp(900f * voxelDensity, 150f, 4000f), Seed = (arrival.Seed ^ 0x9E3779B9u) }; runtime.TryAdd(in emission); } } public static class SpellScale { private const float ReferenceCost = 60f; private const float ReferenceDamage = 60f; public static float Power(float totalCost) { return math.clamp(math.sqrt(math.max(totalCost, 0f) / 60f), 0.5f, 4f); } public static float PowerFromDamage(float damage) { return math.clamp(math.sqrt(math.max(damage, 0f) / 60f), 0.5f, 4f); } public static float SigilRadius(CastPlan plan) { return 0.9f + 1.7f * Power(plan?.TotalCost ?? 0f); } public static float VortexRadius(CastPlan plan) { return SigilRadius(plan) * 1.9f; } public static float BeamThickness(CastPlan plan) { return 0.7f + 0.75f * Power(plan?.TotalCost ?? 0f); } public static float ImpactRadius(float projectileScale, float totalCost) { return (1.4f + projectileScale * 2.2f) * math.clamp(Power(totalCost), 0.7f, 2.2f); } public static int Voxels(float baseCount, float power, float density) { return (int)math.clamp(baseCount * math.clamp(power, 0.6f, 2.6f) * math.clamp(density, 0.1f, 8f), 60f, 5000f); } } } namespace UnholyRites.Rendering { internal enum VoxelBackendState { Pending, Ready, Failed } internal interface ISpellVoxelBackend : IDisposable { string Name { get; } VoxelBackendState State { get; } VoxelBackendState Prepare(int capacity); void Upload(NativeArray voxels, int count); void Draw(ScriptableRenderContext context, Camera camera, in VoxelLook look, int slot, int start, int count); } internal sealed class ProjectileMaterialBackend : ISpellVoxelBackend, IDisposable { private struct ConvertJob : IJobParallelFor { [ReadOnly] public NativeArray voxels; [WriteOnly] public NativeArray instances; public void Execute(int i) { //IL_002c: 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) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0048: 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_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: 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_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007d: 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_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //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_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) VoxelInstance voxelInstance = voxels[i]; float3 val = default(float3); ((float3)(ref val))..ctor(0f, 0.012f, 0f); instances[i] = new InstanceData { position0 = voxelInstance.Position, position1 = voxelInstance.Position - val, position2 = voxelInstance.Position - val * 2f, position3 = voxelInstance.Position - val * 3f, position4 = voxelInstance.Position - val * 4f, mainColor = voxelInstance.Color, coreColor = voxelInstance.CoreColor, scale = voxelInstance.Scale, innerWidth = voxelInstance.Scale * 0.5f, outerWidth = voxelInstance.Scale }; } } private const string InstanceBufferProperty = "_ProjectilesInstanceData"; private NativeArray _instances; private ComputeBuffer _buffer; private Material _material; private Mesh _mesh; private VoxelBackendState _state; private bool _warnedAboutOffset; public string Name => "standin"; public VoxelBackendState State => _state; public VoxelBackendState Prepare(int capacity) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Expected O, but got Unknown //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Expected O, but got Unknown //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) if (_state != VoxelBackendState.Pending) { return _state; } SulfurCustomRendering instance = SulfurCustomRendering.instance; if ((Object)(object)instance == (Object)null || (Object)(object)instance.projectileMesh == (Object)null || (Object)(object)instance.projectileMaterial == (Object)null) { return VoxelBackendState.Pending; } try { _mesh = instance.projectileMesh; _material = new Material(instance.projectileMaterial) { name = "UnholyRites_SpellVoxels_StandIn", hideFlags = (HideFlags)61 }; int num = Marshal.SizeOf(); _buffer = new ComputeBuffer(capacity, num); _material.SetBuffer("_ProjectilesInstanceData", _buffer); _instances = new NativeArray(capacity, (Allocator)4, (NativeArrayOptions)0); _state = VoxelBackendState.Ready; Plugin.Log.LogInfo((object)($"Voxel backend '{Name}' ready: {capacity} voxels, stride {num} bytes, " + $"mesh '{((Object)_mesh).name}' ({_mesh.vertexCount} verts).")); } catch (Exception arg) { _state = VoxelBackendState.Failed; Plugin.Log.LogError((object)$"Voxel backend '{Name}' failed to initialise: {arg}"); } return _state; } public void Upload(NativeArray voxels, int count) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //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_0026: 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_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) if (_state == VoxelBackendState.Ready && count > 0) { ConvertJob obj = new ConvertJob { voxels = voxels, instances = _instances }; JobHandle val = default(JobHandle); val = IJobParallelForExtensions.Schedule(obj, count, 256, val); ((JobHandle)(ref val)).Complete(); _buffer.SetData(_instances, 0, 0, count); } } public void Draw(ScriptableRenderContext context, Camera camera, in VoxelLook look, int slot, int start, int count) { if (_state != VoxelBackendState.Ready || count <= 0) { return; } if (start != 0) { if (!_warnedAboutOffset) { _warnedAboutOffset = true; Plugin.Log.LogWarning((object)($"Voxel backend '{Name}' was asked to draw from offset {start} and cannot. " + "It has no instance-offset uniform, so it is only usable as a look that draws everything.")); } } else { CommandBuffer val = CommandBufferPool.Get("UnholyRites.SpellVoxels.StandIn"); val.DrawMeshInstancedProcedural(_mesh, 0, _material, 0, count, (MaterialPropertyBlock)null); ((ScriptableRenderContext)(ref context)).ExecuteCommandBuffer(val); CommandBufferPool.Release(val); } } public void Dispose() { _state = VoxelBackendState.Pending; if (_buffer != null) { _buffer.Release(); _buffer = null; } if (_instances.IsCreated) { _instances.Dispose(); } if ((Object)(object)_material != (Object)null) { Object.Destroy((Object)(object)_material); _material = null; } _mesh = null; } void ISpellVoxelBackend.Draw(ScriptableRenderContext context, Camera camera, in VoxelLook look, int slot, int start, int count) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) Draw(context, camera, in look, slot, start, count); } } internal sealed class SpellVoxelRenderer : IDisposable { private static readonly int PatternCount = Enum.GetValues(typeof(VoxelPattern)).Length; private readonly int _capacity; private NativeArray _voxels; private ISpellVoxelBackend _backend; private readonly int[] _groupOfPattern = new int[PatternCount]; private VoxelLook[] _looks = new VoxelLook[1]; private VoxelRange[] _ranges = new VoxelRange[1]; private VoxelLook? _groupedFor = VoxelLooks.Default; private bool _grouped; private string _requested; private bool _allocated; private int _builtFrame = -1; private int _drawCount; public int LastDrawCount => _drawCount; public SpellVoxelRenderer(int capacity) { _capacity = Mathf.Clamp(capacity, 256, 65536); } public void Build(SpellRuntime runtime, float now) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) if (runtime != null && EnsureBuffer() && _builtFrame != Time.frameCount) { _builtFrame = Time.frameCount; _drawCount = 0; EnsureGroups(); ISpellVoxelBackend spellVoxelBackend = EnsureBackend(); runtime.Retire(now); int num = (_drawCount = runtime.BuildVoxels(_voxels, now, _groupOfPattern, _ranges)); if (spellVoxelBackend != null && num != 0) { spellVoxelBackend.Upload(_voxels, num); } } } public void Draw(ScriptableRenderContext context, Camera camera) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Invalid comparison between Unknown and I4 //IL_0042: Unknown result type (might be due to invalid IL or missing references) if (_backend == null || _drawCount <= 0 || (Object)(object)camera == (Object)null || (int)camera.cameraType != 1) { return; } for (int i = 0; i < _ranges.Length; i++) { if (_ranges[i].Count > 0) { _backend.Draw(context, camera, in _looks[i], i, _ranges[i].Start, _ranges[i].Count); } } } private void EnsureGroups() { VoxelLook? voxelLook = VoxelLooks.Override; if (_grouped && Nullable.Equals(voxelLook, _groupedFor)) { return; } _groupedFor = voxelLook; _grouped = true; if (voxelLook.HasValue) { _looks = new VoxelLook[1] { voxelLook.Value }; Array.Clear(_groupOfPattern, 0, _groupOfPattern.Length); _ranges = new VoxelRange[1]; return; } List list = new List(); for (int i = 0; i < _groupOfPattern.Length; i++) { VoxelLook look = VoxelLooks.For((VoxelPattern)i); int num = list.FindIndex((VoxelLook other) => SameLook(in other, in look)); if (num < 0) { num = list.Count; list.Add(look); } _groupOfPattern[i] = num; } _looks = list.ToArray(); _ranges = new VoxelRange[_looks.Length]; } private static bool SameLook(in VoxelLook a, in VoxelLook b) { if (string.Equals(a.Backend, b.Backend, StringComparison.Ordinal) && a.Shape == b.Shape && a.Blending == b.Blending && a.Brightness == b.Brightness && a.Softness == b.Softness && a.CoreSharpness == b.CoreSharpness && a.CoreMix == b.CoreMix && a.Saturation == b.Saturation && a.Spin == b.Spin) { return a.AlignToOffset == b.AlignToOffset; } return false; } private ISpellVoxelBackend EnsureBackend() { string text = VoxelBackends.Normalise(_looks[0].Backend); if (!string.Equals(text, _requested, StringComparison.Ordinal)) { _requested = text; Swap(VoxelBackends.Create(text), "configuration asked for '" + text + "'"); } if (_backend == null) { return null; } switch (_backend.Prepare(_capacity)) { case VoxelBackendState.Ready: return _backend; case VoxelBackendState.Pending: return null; default: { if (_backend is ProjectileMaterialBackend) { Swap(null, "no backend could be brought up"); return null; } string name = _backend.Name; Swap(new ProjectileMaterialBackend(), "'" + name + "' is unavailable"); if (_backend.Prepare(_capacity) != VoxelBackendState.Ready) { return null; } return _backend; } } } private void Swap(ISpellVoxelBackend backend, string reason) { _backend?.Dispose(); _backend = backend; Plugin.Log.LogInfo((object)("Voxel backend is now '" + (backend?.Name ?? "none") + "' — " + reason + ".")); } private bool EnsureBuffer() { //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 (_allocated) { return true; } _voxels = new NativeArray(_capacity, (Allocator)4, (NativeArrayOptions)0); _allocated = true; return true; } public void Dispose() { _backend?.Dispose(); _backend = null; if (_voxels.IsCreated) { _voxels.Dispose(); } _allocated = false; } } internal static class VoxelBackends { internal const string StandIn = "standin"; internal const string Custom = "custom"; internal static string Normalise(string value) { string text = (value ?? string.Empty).Trim().ToLowerInvariant(); if (text.Length != 0) { return text; } return "standin"; } internal static ISpellVoxelBackend Create(string requested) { if (!(requested == "custom")) { if (requested == "standin") { return new ProjectileMaterialBackend(); } Plugin.Log.LogWarning((object)("Unknown voxel backend '" + requested + "'; using the stand-in. Valid values are 'standin' and 'custom'.")); return new ProjectileMaterialBackend(); } return new VoxelShaderBackend(); } } internal enum VoxelBlending { Additive, Max, Solid } internal struct VoxelLook { public string Backend; public VoxelShape Shape; public VoxelBlending Blending; public float Brightness; public float Softness; public float CoreSharpness; public float CoreMix; public float Saturation; public float Spin; public bool AlignToOffset; public string English; public string Chinese; public string Describe() { if (!SpellText.IsChinese) { return English; } return Chinese; } } internal static class VoxelLooks { internal static readonly VoxelLook Default = new VoxelLook { Backend = "custom", Shape = VoxelShape.Cube, Blending = VoxelBlending.Additive, Brightness = 0.15f, Softness = 0.45f, CoreSharpness = 2.5f, CoreMix = 0.12f, Saturation = 1f, Spin = 1f, English = "default: glowing debris, blocks at random angles adding up", Chinese = "默认渲染方式:发光碎片,随机朝向的方块互相叠加" }; internal static readonly VoxelLook[] All = new VoxelLook[10] { Default, Inscribed, new VoxelLook { Backend = "custom", Shape = VoxelShape.Cube, Blending = VoxelBlending.Additive, Brightness = 0.15f, Softness = 0.45f, CoreSharpness = 2.5f, CoreMix = 0.12f, Saturation = 1f, Spin = 0f, AlignToOffset = false, English = "default, but every block axis-aligned: no rotation at all", Chinese = "默认方式,但方块全部轴对齐:完全不旋转" }, new VoxelLook { Backend = "custom", Shape = VoxelShape.Cube, Blending = VoxelBlending.Additive, Brightness = 0.15f, Softness = 0.45f, CoreSharpness = 2.5f, CoreMix = 0.12f, Saturation = 1f, Spin = 0.35f, AlignToOffset = true, English = "facing the centre, rolled a little: tiles without the perfect regularity", Chinese = "朝向中心,略带滚转:铺开但不至于太整齐" }, new VoxelLook { Backend = "standin", English = "the game's own projectile material — the baseline everything is judged against", Chinese = "游戏自己的子弹材质——所有对比的基准" }, new VoxelLook { Backend = "custom", Shape = VoxelShape.Cube, Blending = VoxelBlending.Solid, Brightness = 1f, Softness = 0.45f, CoreSharpness = 2.5f, CoreMix = 0.12f, Saturation = 1f, Spin = 0f, English = "voxels proper: axis-aligned solid blocks, so a sigil reads as rings again", Chinese = "真正的体素:轴对齐实心方块,法阵能重新看出环和辐条" }, new VoxelLook { Backend = "custom", Shape = VoxelShape.Cube, Blending = VoxelBlending.Solid, Brightness = 1f, Softness = 0.45f, CoreSharpness = 2.5f, CoreMix = 0.12f, Saturation = 1f, Spin = 1f, English = "solid debris: the same blocks occluding each other instead of adding", Chinese = "实心碎片:同样的方块,改成互相遮挡而不是叠加" }, new VoxelLook { Backend = "custom", Shape = VoxelShape.Billboard, Blending = VoxelBlending.Additive, Brightness = 0.3f, Softness = 0.08f, CoreSharpness = 8f, CoreMix = 0.0375f, Saturation = 1f, Spin = 1f, English = "hard-edged embers: motes with the blur and the white core taken out", Chinese = "硬边余烬:光点,去掉模糊和白核" }, new VoxelLook { Backend = "custom", Shape = VoxelShape.Billboard, Blending = VoxelBlending.Additive, Brightness = 0.3f, Softness = 0.45f, CoreSharpness = 2.5f, CoreMix = 0.12f, Saturation = 1f, Spin = 1f, English = "soft motes, added together: the dreamy end of the billboard", Chinese = "柔和光点,叠加:billboard 偏梦幻的那一端" }, new VoxelLook { Backend = "custom", Shape = VoxelShape.Billboard, Blending = VoxelBlending.Solid, Brightness = 1f, Softness = 0.05f, CoreSharpness = 8f, CoreMix = 0.0375f, Saturation = 1f, Spin = 1f, English = "hard discs: billboards that occlude, the flattest the mote gets", Chinese = "硬圆片:会遮挡的 billboard,光点最扁平的一端" } }; internal static readonly VoxelLook Inscribed = new VoxelLook { Backend = "custom", Shape = VoxelShape.Cube, Blending = VoxelBlending.Additive, Brightness = 0.15f, Softness = 0.45f, CoreSharpness = 2.5f, CoreMix = 0.12f, Saturation = 1f, Spin = 0f, AlignToOffset = true, English = "inscribed: every block faces the effect's centre, so rings read as rings", Chinese = "铺开:每个方块朝向法术中心,环看起来就是环" }; private static int index; internal static VoxelLook? Override { get; private set; } internal static VoxelLook For(VoxelPattern pattern) { if (pattern != VoxelPattern.Sigil && pattern != VoxelPattern.Rise) { return Default; } return Inscribed; } internal static void Cycle() { index = (index + 1) % (All.Length + 1); Override = ((index == 0) ? ((VoxelLook?)null) : new VoxelLook?(All[index - 1])); string text = ((index == 0) ? SpellText.Get("render.per_spell", "per spell: each pattern drawn with the look it asked for") : All[index - 1].Describe()); Plugin.Log.LogInfo((object)string.Format("{0} {1}/{2}: {3}", SpellText.Get("render.look", "Render"), index, All.Length, text)); } } internal enum VoxelShape { Billboard, Cube } internal static class VoxelMeshes { private const float Extent = 0.5f; private static readonly Bounds Everywhere = new Bounds(Vector3.zero, Vector3.one * 10000f); private static Mesh _quad; private static Mesh _cube; internal static Mesh For(VoxelShape shape) { if (shape != VoxelShape.Cube) { return Quad(); } return Cube(); } private static Mesh Quad() { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0051: 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_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_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: 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_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_quad != (Object)null) { return _quad; } Mesh val = New("UnholyRites_VoxelQuad"); val.SetVertices((Vector3[])(object)new Vector3[4] { new Vector3(-0.5f, -0.5f, 0f), new Vector3(0.5f, -0.5f, 0f), new Vector3(-0.5f, 0.5f, 0f), new Vector3(0.5f, 0.5f, 0f) }); val.SetNormals((Vector3[])(object)new Vector3[4] { Vector3.back, Vector3.back, Vector3.back, Vector3.back }); val.SetUVs(0, (Vector2[])(object)new Vector2[4] { new Vector2(0f, 0f), new Vector2(1f, 0f), new Vector2(0f, 1f), new Vector2(1f, 1f) }); val.SetTriangles(new int[6] { 0, 2, 1, 2, 3, 1 }, 0); val.bounds = Everywhere; val.UploadMeshData(true); _quad = val; return _quad; } private static Mesh Cube() { //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_0032: 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_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: 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_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: 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_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_0298: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: 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) //IL_00c0: 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_00c4: 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) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: 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_00f1: 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_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_016a: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0182: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Unknown result type (might be due to invalid IL or missing references) //IL_01b5: Unknown result type (might be due to invalid IL or missing references) //IL_01ca: Unknown result type (might be due to invalid IL or missing references) //IL_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: Unknown result type (might be due to invalid IL or missing references) //IL_01fe: Unknown result type (might be due to invalid IL or missing references) //IL_0203: 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_0215: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_cube != (Object)null) { return _cube; } Mesh val = New("UnholyRites_VoxelCube"); Vector3[] array = (Vector3[])(object)new Vector3[6] { Vector3.up, Vector3.down, Vector3.forward, Vector3.back, Vector3.right, Vector3.left }; Vector3[] array2 = (Vector3[])(object)new Vector3[24]; Vector3[] array3 = (Vector3[])(object)new Vector3[24]; Vector2[] array4 = (Vector2[])(object)new Vector2[24]; int[] array5 = new int[36]; for (int i = 0; i < 6; i++) { Vector3 val2 = array[i]; Vector3 val3 = ((Mathf.Abs(val2.y) > 0.5f) ? Vector3.right : Vector3.up); Vector3 val4 = Vector3.Cross(val2, val3); val3 = Vector3.Cross(val4, val2); Vector3 val5 = val2 * 0.5f; int num = i * 4; array2[num] = val5 - val3 * 0.5f - val4 * 0.5f; array2[num + 1] = val5 + val3 * 0.5f - val4 * 0.5f; array2[num + 2] = val5 - val3 * 0.5f + val4 * 0.5f; array2[num + 3] = val5 + val3 * 0.5f + val4 * 0.5f; array4[num] = new Vector2(0f, 0f); array4[num + 1] = new Vector2(1f, 0f); array4[num + 2] = new Vector2(0f, 1f); array4[num + 3] = new Vector2(1f, 1f); for (int j = 0; j < 4; j++) { array3[num + j] = val2; } int num2 = i * 6; array5[num2] = num; array5[num2 + 1] = num + 2; array5[num2 + 2] = num + 1; array5[num2 + 3] = num + 2; array5[num2 + 4] = num + 3; array5[num2 + 5] = num + 1; } val.SetVertices(array2); val.SetNormals(array3); val.SetUVs(0, array4); val.SetTriangles(array5, 0); val.bounds = Everywhere; val.UploadMeshData(true); _cube = val; return _cube; } private static Mesh New(string name) { //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_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown return new Mesh { name = name, hideFlags = (HideFlags)61 }; } internal static void Release() { if ((Object)(object)_quad != (Object)null) { Object.Destroy((Object)(object)_quad); _quad = null; } if ((Object)(object)_cube != (Object)null) { Object.Destroy((Object)(object)_cube); _cube = null; } } } internal static class VoxelRenderProbe { private struct FillJob : IJobParallelFor { [WriteOnly] public NativeArray voxels; public float3 origin; public float time; public float radius; public float scale; public void Execute(int i) { //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) float num = Hash01(i, 0); float num2 = Hash01(i, 1); float num3 = Hash01(i, 2); float num4 = num * 2f * (float)Math.PI + time * 0.2f; float num5 = math.acos(2f * num2 - 1f); float num6 = radius * (0.6f + 0.4f * num3); float num7 = default(float); float num8 = default(float); math.sincos(num5, ref num7, ref num8); float num9 = default(float); float num10 = default(float); math.sincos(num4, ref num9, ref num10); float3 val = default(float3); ((float3)(ref val))..ctor(num6 * num7 * num10, num6 * num8 + math.sin(time + num * 6.283f) * 0.5f, num6 * num7 * num9); voxels[i] = new VoxelInstance { Position = origin + val, Color = new float3(1f, 0.35f + 0.4f * num3, 0.1f), CoreColor = new float3(1f, 0.9f, 0.7f), Scale = scale, Random = Hash(i, 3) }; } private static uint Hash(int index, int channel) { int num = (int)(index * 747796405 + channel * 2891336453u); int num2 = (num ^ (num >>> 15)) * -2048144777; int num3 = (num2 ^ (num2 >>> 13)) * -1028477379; return (uint)(num3 ^ (num3 >>> 16)); } private static float Hash01(int index, int channel) { return (float)(Hash(index, channel) & 0xFFFFFF) / 16777215f; } } private const int MaxInstances = 300000; private static NativeArray _voxels; private static ISpellVoxelBackend _backend; private static string _requested; private static int _preparedCapacity; private static int _capacity; private static int _filledFrame = -1; private static int _activeCount; private static readonly Stopwatch FillTimer = new Stopwatch(); private static readonly Stopwatch UploadTimer = new Stopwatch(); private static double _fillMs; private static double _uploadMs; private static float _reportAccumulator; private static int _reportFrames; private static float _reportFrameTime; internal static void Draw(ScriptableRenderContext context, Camera camera) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Invalid comparison between Unknown and I4 //IL_007f: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)camera == (Object)null || (int)camera.cameraType != 1) { return; } int num = Mathf.Clamp(Plugin.ProbeInstanceCount.Value, 0, 300000); if (num == 0) { return; } ISpellVoxelBackend spellVoxelBackend = EnsureBackend(num); if (spellVoxelBackend != null && EnsureBuffer(num)) { if (_filledFrame != Time.frameCount) { _filledFrame = Time.frameCount; _activeCount = num; Fill(camera, num); Upload(spellVoxelBackend, num); Report(num, spellVoxelBackend.Name); } if (_activeCount > 0) { spellVoxelBackend.Draw(context, camera, Look(), 0, 0, _activeCount); } } } private static ISpellVoxelBackend EnsureBackend(int requested) { string text = VoxelBackends.Normalise(Look().Backend); int num = Capacity(requested); if (!string.Equals(text, _requested, StringComparison.Ordinal) || num > _preparedCapacity) { _requested = text; _backend?.Dispose(); _backend = VoxelBackends.Create(text); _preparedCapacity = num; ReleaseBuffer(); } if (_backend == null) { return null; } switch (_backend.Prepare(_preparedCapacity)) { case VoxelBackendState.Ready: return _backend; case VoxelBackendState.Pending: return null; default: if (_backend is ProjectileMaterialBackend) { Plugin.Log.LogWarning((object)"Render probe has no backend that can draw; disabling."); Plugin.ProbeInstanceCount.Value = 0; return null; } Plugin.Log.LogWarning((object)("Render probe: backend '" + _backend.Name + "' is unavailable, measuring the stand-in instead.")); _backend.Dispose(); _backend = new ProjectileMaterialBackend(); ReleaseBuffer(); if (_backend.Prepare(_preparedCapacity) != VoxelBackendState.Ready) { return null; } return _backend; } } private static VoxelLook Look() { return VoxelLooks.Override ?? VoxelLooks.Default; } private static int Capacity(int requested) { return Mathf.Min(Mathf.NextPowerOfTwo(Mathf.Max(requested, 1024)), 300000); } private static bool EnsureBuffer(int requested) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (_voxels.IsCreated && _capacity >= requested) { return true; } try { ReleaseBuffer(); _capacity = Capacity(requested); _voxels = new NativeArray(_capacity, (Allocator)4, (NativeArrayOptions)0); Plugin.Log.LogInfo((object)$"Render probe buffer allocated: {_capacity} voxels."); } catch (Exception arg) { Plugin.Log.LogError((object)$"Render probe could not allocate its buffer, disabling: {arg}"); Plugin.ProbeInstanceCount.Value = 0; return false; } return true; } private static void Fill(Camera camera, int count) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: 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_0047: 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_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_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) FillTimer.Restart(); Transform transform = ((Component)camera).transform; FillJob obj = new FillJob { voxels = _voxels, origin = float3.op_Implicit(transform.position) + float3.op_Implicit(transform.forward) * 12f, time = Time.time, radius = Mathf.Max(Plugin.ProbeRadius.Value, 0.1f), scale = Mathf.Max(Plugin.ProbeInstanceScale.Value, 0.001f) }; JobHandle val = default(JobHandle); val = IJobParallelForExtensions.Schedule(obj, count, 512, val); ((JobHandle)(ref val)).Complete(); FillTimer.Stop(); _fillMs = FillTimer.Elapsed.TotalMilliseconds; } private static void Upload(ISpellVoxelBackend backend, int count) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) UploadTimer.Restart(); backend.Upload(_voxels, count); UploadTimer.Stop(); _uploadMs = UploadTimer.Elapsed.TotalMilliseconds; } private static void Report(int count, string backendName) { _reportFrames++; _reportFrameTime += Time.unscaledDeltaTime; _reportAccumulator += Time.unscaledDeltaTime; if (!(_reportAccumulator < 2f)) { float num = _reportFrameTime / (float)Mathf.Max(_reportFrames, 1) * 1000f; Plugin.Log.LogInfo((object)($"Render probe [{backendName}]: {count} instances | frame {num:F2} ms " + $"({1000f / Mathf.Max(num, 0.001f):F0} fps) | " + $"fill {_fillMs:F2} ms | upload {_uploadMs:F2} ms")); _reportAccumulator = 0f; _reportFrames = 0; _reportFrameTime = 0f; } } internal static void Dispose() { _backend?.Dispose(); _backend = null; _requested = null; _preparedCapacity = 0; ReleaseBuffer(); } private static void ReleaseBuffer() { if (_voxels.IsCreated) { _voxels.Dispose(); } _capacity = 0; _activeCount = 0; _filledFrame = -1; } } internal sealed class VoxelShaderBackend : ISpellVoxelBackend, IDisposable { private sealed class Slot : IDisposable { private VoxelShape _shape = (VoxelShape)(-1); private VoxelBlending _blending = (VoxelBlending)(-1); private bool _applied; private Vector4 _numbers = new Vector4(float.NaN, float.NaN, float.NaN, float.NaN); private Vector2 _colour = new Vector2(float.NaN, float.NaN); private float _align = float.NaN; private float _offset = float.NaN; internal Material Material { get; private set; } internal Mesh Mesh { get; private set; } internal Slot(Material material) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_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) Material = material; } internal void Apply(in VoxelLook look, int instanceOffset) { ApplyShape(look.Shape); ApplyBlend(look.Blending); ApplyNumbers(in look); if ((float)instanceOffset != _offset) { _offset = instanceOffset; Material.SetFloat(InstanceOffsetId, (float)instanceOffset); } _applied = true; } private void ApplyShape(VoxelShape shape) { if (shape != _shape || !_applied) { _shape = shape; Mesh = VoxelMeshes.For(shape); if (shape == VoxelShape.Billboard) { Material.EnableKeyword("_VOXEL_BILLBOARD"); Material.SetFloat(CullId, 0f); } else { Material.DisableKeyword("_VOXEL_BILLBOARD"); Material.SetFloat(CullId, 2f); } } } private void ApplyBlend(VoxelBlending blending) { if (blending != _blending || !_applied) { _blending = blending; switch (blending) { case VoxelBlending.Solid: Material.SetFloat(SrcBlendId, 1f); Material.SetFloat(DstBlendId, 0f); Material.SetFloat(BlendOpId, 0f); Material.SetFloat(ZWriteId, 1f); Material.SetFloat(AlphaClipId, 0.5f); break; case VoxelBlending.Max: Material.SetFloat(SrcBlendId, 1f); Material.SetFloat(DstBlendId, 1f); Material.SetFloat(BlendOpId, 4f); Material.SetFloat(ZWriteId, 0f); Material.SetFloat(AlphaClipId, 0.003f); break; default: Material.SetFloat(SrcBlendId, 1f); Material.SetFloat(DstBlendId, 1f); Material.SetFloat(BlendOpId, 0f); Material.SetFloat(ZWriteId, 0f); Material.SetFloat(AlphaClipId, 0.003f); break; } } } private void ApplyNumbers(in VoxelLook look) { //IL_0047: 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_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007d: 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_0095: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: 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_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_0103: 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_0057: Unknown result type (might be due to invalid IL or missing references) Vector4 val = default(Vector4); ((Vector4)(ref val))..ctor(look.Brightness, look.Softness, look.CoreSharpness, look.Spin); Vector2 val2 = default(Vector2); ((Vector2)(ref val2))..ctor(look.CoreMix, look.Saturation); float num = (look.AlignToOffset ? 1f : 0f); if (!(val == _numbers) || !(val2 == _colour) || num != _align || !_applied) { _numbers = val; _colour = val2; _align = num; Material.SetFloat(CoreMixId, val2.x); Material.SetFloat(SaturationId, val2.y); Material.SetFloat(BrightnessId, val.x); Material.SetFloat(EdgeSoftnessId, val.y); Material.SetFloat(CoreSharpnessId, val.z); Material.SetFloat(SpinId, val.w); Material.SetFloat(AlignToOffsetId, num); } } public void Dispose() { if ((Object)(object)Material != (Object)null) { Object.Destroy((Object)(object)Material); Material = null; } Mesh = null; } } private const string InstanceBufferProperty = "_VoxelInstances"; private const string BillboardKeyword = "_VOXEL_BILLBOARD"; private static readonly int BrightnessId = Shader.PropertyToID("_Brightness"); private static readonly int CoreSharpnessId = Shader.PropertyToID("_CoreSharpness"); private static readonly int EdgeSoftnessId = Shader.PropertyToID("_EdgeSoftness"); private static readonly int CoreMixId = Shader.PropertyToID("_CoreMix"); private static readonly int SpinId = Shader.PropertyToID("_Spin"); private static readonly int AlignToOffsetId = Shader.PropertyToID("_AlignToOffset"); private static readonly int SaturationId = Shader.PropertyToID("_Saturation"); private static readonly int BlendOpId = Shader.PropertyToID("_BlendOp"); private static readonly int AlphaClipId = Shader.PropertyToID("_AlphaClip"); private static readonly int InstanceOffsetId = Shader.PropertyToID("_InstanceOffset"); private static readonly int SrcBlendId = Shader.PropertyToID("_SrcBlend"); private static readonly int DstBlendId = Shader.PropertyToID("_DstBlend"); private static readonly int ZWriteId = Shader.PropertyToID("_ZWrite"); private static readonly int CullId = Shader.PropertyToID("_Cull"); private readonly List _slots = new List(); private ComputeBuffer _buffer; private Material _template; private VoxelBackendState _state; public string Name => "custom"; public VoxelBackendState State => _state; public VoxelBackendState Prepare(int capacity) { //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Expected O, but got Unknown if (_state != VoxelBackendState.Pending) { return _state; } Material val = VoxelShaderBundle.Load(); if ((Object)(object)val == (Object)null) { _state = VoxelBackendState.Failed; Plugin.Log.LogWarning((object)("Voxel backend '" + Name + "' unavailable: " + VoxelShaderBundle.FailureReason)); return _state; } try { _template = val; int num = Marshal.SizeOf(); _buffer = new ComputeBuffer(capacity, num); _state = VoxelBackendState.Ready; Plugin.Log.LogInfo((object)($"Voxel backend '{Name}' ready: {capacity} voxels, stride {num} bytes, " + "shader '" + ((Object)val.shader).name + "'.")); } catch (Exception arg) { _state = VoxelBackendState.Failed; Plugin.Log.LogError((object)$"Voxel backend '{Name}' failed to initialise: {arg}"); } return _state; } public void Upload(NativeArray voxels, int count) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) if (_state == VoxelBackendState.Ready && count > 0) { _buffer.SetData(voxels, 0, 0, count); } } public void Draw(ScriptableRenderContext context, Camera camera, in VoxelLook look, int slot, int start, int count) { if (_state == VoxelBackendState.Ready && count > 0) { Slot slot2 = SlotFor(slot); if (slot2 != null) { slot2.Apply(in look, start); CommandBuffer val = CommandBufferPool.Get("UnholyRites.SpellVoxels.Custom"); val.DrawMeshInstancedProcedural(slot2.Mesh, 0, slot2.Material, 0, count, (MaterialPropertyBlock)null); ((ScriptableRenderContext)(ref context)).ExecuteCommandBuffer(val); CommandBufferPool.Release(val); } } } private Slot SlotFor(int index) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown if (index < 0) { return null; } while (_slots.Count <= index) { Material val = new Material(_template) { name = $"UnholyRites_SpellVoxels_Custom_{_slots.Count}", hideFlags = (HideFlags)61 }; val.enableInstancing = true; val.SetBuffer("_VoxelInstances", _buffer); _slots.Add(new Slot(val)); } return _slots[index]; } public void Dispose() { _state = VoxelBackendState.Pending; if (_buffer != null) { _buffer.Release(); _buffer = null; } for (int i = 0; i < _slots.Count; i++) { _slots[i].Dispose(); } _slots.Clear(); _template = null; } void ISpellVoxelBackend.Draw(ScriptableRenderContext context, Camera camera, in VoxelLook look, int slot, int start, int count) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) Draw(context, camera, in look, slot, start, count); } } internal static class VoxelShaderBundle { internal const string FileName = "unholyrites-voxel.bundle"; private const string MaterialName = "UnholyRites_SpellVoxel"; private static AssetBundle _bundle; private static Material _material; private static bool _attempted; internal static string FailureReason { get; private set; } internal static Material Load() { if (_attempted) { return _material; } _attempted = true; string text = ResolvePath(); if (text == null) { FailureReason = "'unholyrites-voxel.bundle' was not found next to the plugin. Build it from UnityProject and copy it into the plugin folder."; return null; } try { _bundle = AssetBundle.LoadFromFile(text); } catch (Exception ex) { FailureReason = "'" + text + "' could not be opened: " + ex.Message; return null; } 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 null; } _material = _bundle.LoadAsset("UnholyRites_SpellVoxel"); if ((Object)(object)_material == (Object)null) { Material[] array = _bundle.LoadAllAssets(); if (array == null || array.Length == 0) { FailureReason = "'" + text + "' loaded but holds no material. Assets found: " + string.Join(", ", _bundle.GetAllAssetNames() ?? new string[0]) + "."; return null; } _material = array[0]; Plugin.Log.LogWarning((object)("Voxel bundle holds no material named 'UnholyRites_SpellVoxel'; using '" + ((Object)_material).name + "' instead. Rename it in the builder to match.")); } if ((Object)(object)_material.shader == (Object)null || ((Object)_material.shader).name == "Hidden/InternalErrorShader") { FailureReason = "'" + text + "' loaded but its shader did not. The bundle must be built with the same Unity and URP versions the game uses."; _material = null; return null; } Plugin.Log.LogInfo((object)("Voxel bundle loaded from '" + text + "': material '" + ((Object)_material).name + "', shader '" + ((Object)_material.shader).name + "'.")); return _material; } 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-voxel.bundle"); if (!File.Exists(text)) { return null; } return text; } } } namespace UnholyRites.Patches { [HarmonyPatch(typeof(EntityStats), "ModifyWorldResource", new Type[] { typeof(WorldResource), typeof(int), typeof(object) })] internal static class BreechChamberPatch { private static void Prefix(EntityStats __instance, WorldResource worldResource, int amount, object source, out int __state) { __state = -1; try { if (amount != 0 && !((Object)(object)worldResource == (Object)null)) { Weapon val = (Weapon)((source is Weapon) ? source : null); if (val != null && !((Object)(object)((Holdable)val).inventoryItem == (Object)null) && !SpellContent.IsStaff(((Holdable)val).inventoryItem.itemDefinition) && IsLocalPlayer(__instance)) { __state = __instance.GetWorldResource(worldResource); } } } catch (Exception arg) { Plugin.Log.LogError((object)$"Breech chamber read failed: {arg}"); } } private static void Postfix(EntityStats __instance, WorldResource worldResource, int __state) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) if (__state < 0) { return; } try { int num = __instance.GetWorldResource(worldResource) - __state; if (num < 0) { ManaChambers.OnAmmoTaken(worldResource.id, -num, Time.time); } else { ManaChambers.OnAmmoReturned(worldResource.id, num); } } catch (Exception arg) { Plugin.Log.LogError((object)$"Breech chamber credit failed: {arg}"); } } private static bool IsLocalPlayer(EntityStats stats) { GameManager instance = StaticInstance.Instance; if (stats != null && (Object)(object)instance != (Object)null && (Object)(object)stats.owner != (Object)null) { return stats.owner == instance.PlayerUnit; } return false; } } [HarmonyPatch(typeof(ExtendedAdvancedWalkerController), "GetMovementSpeed")] internal static class ChannelMovementPatch { private static void Postfix(ref float __result) { try { SpellSession session = Plugin.Session; if (session != null && session.IsChannelling) { float chantMoveFactor = session.ChantMoveFactor; __result *= ((chantMoveFactor < 0.05f) ? 0.05f : ((chantMoveFactor > 1f) ? 1f : chantMoveFactor)); } } catch (Exception arg) { Plugin.Log.LogError((object)$"Channel movement adjustment failed: {arg}"); } } } [HarmonyPatch(typeof(AttributeEffect), "DealCrusaderDamage")] internal static class CrusaderEchoPatch { private static bool Prefix(Unit unit, float damage, DamageSourceData sourceData) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: 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) try { if ((int)sourceData.sourceEffect != 21 && (Object)(object)sourceData.sourceWeapon != (Object)null) { NailLedger.Bank(unit, damage); } return SpellDamageScope.Indirect <= 0; } catch (Exception arg) { Plugin.Log.LogError((object)$"Crusader echo check failed: {arg}"); return true; } } } [HarmonyPatch(typeof(ExtendedCameraController), "RotateCamera")] internal static class DevPanelLookPatch { private static void Prefix(ref float newHorizontalInput, ref float newVerticalInput) { try { if (DevTools.CapturingInput) { newHorizontalInput = 0f; newVerticalInput = 0f; } } catch (Exception arg) { Plugin.Log.LogError((object)$"Developer panel look suppression failed: {arg}"); } } } [HarmonyPatch(typeof(DevToolsManager), "PopulateSpawnMenuItems")] internal static class DevToolsCategoryPatch { private const string CategoryName = "Unholy Rites"; private static FieldInfo _categoriesField; private static bool _resolved; private static void Prefix(DevToolsManager __instance) { //IL_00b0: Unknown result type (might be due to invalid IL or missing references) try { if (SpellContent.SpawnableItems.Count == 0) { return; } if (!_resolved) { _resolved = true; _categoriesField = AccessTools.Field(typeof(DevToolsManager), "itemListsByCategory"); } if (_categoriesField == null) { Plugin.Log.LogWarning((object)"Could not find the spawn menu's category table; mod items will not be listed."); } else { if (!(_categoriesField.GetValue(__instance) is Dictionary> dictionary)) { return; } if (!dictionary.TryGetValue("Unholy Rites", out var value)) { value = (dictionary["Unholy Rites"] = new Dictionary()); } IReadOnlyList spawnableItems = SpellContent.SpawnableItems; for (int i = 0; i < spawnableItems.Count; i++) { if ((Object)(object)spawnableItems[i] != (Object)null) { value[spawnableItems[i].id] = spawnableItems[i]; } } } } catch (Exception arg) { Plugin.Log.LogError((object)$"Failed to add the spell category to the spawn menu: {arg}"); } } } [HarmonyPatch(typeof(InventoryItem), "IsEnchantmentCompatible", new Type[] { typeof(EnchantmentDefinition) })] internal static class EnchantmentCompatibilityPatch { private static bool Prefix(InventoryItem __instance, EnchantmentDefinition enchantment, ref bool __result) { try { if ((Object)(object)enchantment == (Object)null) { return true; } bool flag = SpellContent.IsStaff(__instance.itemDefinition); bool flag2 = SpellContent.IsSpellEnchantment(enchantment); if (!flag && !flag2) { return true; } if (flag != flag2) { __result = false; return false; } StaffDefinition staffDefinition = StaffDefinitions.Of(__instance); __result = __instance.enchantments.Count < staffDefinition.Slots && (staffDefinition.HandSlots <= 0 || !IsDivider(enchantment) || !HoldsDivider(__instance)); return false; } catch (Exception arg) { Plugin.Log.LogError((object)$"Enchantment compatibility check failed: {arg}"); return true; } } private static bool HoldsDivider(InventoryItem staff) { for (int i = 0; i < staff.enchantments.Count; i++) { if ((Object)(object)staff.enchantments[i] != (Object)null && IsDivider(staff.enchantments[i])) { return true; } } return false; } private static bool IsDivider(EnchantmentDefinition enchantment) { if (SpellContent.TryGetSpell(enchantment, out var key) && ContentBootstrap.Catalog.TryGet(key, out var definition) && definition != null) { return definition.Category == SpellCategory.Segment; } return false; } } [HarmonyPatch(typeof(InventoryItem), "EmptyEnchantmentSlots")] internal static class StaffEmptySlotsPatch { private static void Postfix(InventoryItem __instance, ref int __result) { try { if (!((Object)(object)__instance == (Object)null) && SpellContent.IsStaff(__instance.itemDefinition)) { int num = StaffDefinitions.Of(__instance).Slots - __instance.enchantments.Count; __result = ((num > 0) ? num : 0); } } catch (Exception arg) { Plugin.Log.LogError((object)$"Staff free-slot count failed: {arg}"); } } } [HarmonyPatch(typeof(InstancingPass), "Execute")] internal static class InstancingPassPatch { private static bool _loggedFirstCall; private static void Postfix(ScriptableRenderContext context, ref RenderingData renderingData) { //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) Camera camera = ((CameraData)(ref renderingData.cameraData)).camera; if (!_loggedFirstCall) { _loggedFirstCall = true; Plugin.Log.LogInfo((object)("Instancing pass hook reached. First camera: '" + (((Object)(object)camera != (Object)null) ? ((Object)camera).name : "null") + "' type " + (((Object)(object)camera != (Object)null) ? ((object)camera.cameraType/*cast due to .constrained prefix*/).ToString() : "n/a") + ".")); } try { Plugin.Session?.Draw(context, camera); } catch (Exception arg) { Plugin.Log.LogError((object)$"Spell voxel draw failed: {arg}"); } if (Plugin.ProbeInstanceCount == null || Plugin.ProbeInstanceCount.Value <= 0) { return; } try { VoxelRenderProbe.Draw(context, camera); } catch (Exception arg2) { Plugin.Log.LogError((object)$"Render probe draw failed, disabling: {arg2}"); Plugin.ProbeInstanceCount.Value = 0; } } } [HarmonyPatch(typeof(ItemDescription), "Setup", new Type[] { typeof(InventoryItem) })] internal static class ItemDescriptionClearPatch { private static MethodInfo _clear; private static bool _resolved; private static bool _reported; private static void Prefix(ItemDescription __instance) { try { if (!_resolved) { _resolved = true; _clear = AccessTools.Method(typeof(ItemDescription), "ClearDescription", (Type[])null, (Type[])null); } if (_clear == null) { if (!_reported) { _reported = true; Plugin.Log.LogWarning((object)"The item description's clear step is not where it was, so descriptions may still stack when the panel is filled without being hidden first."); } } else { _clear.Invoke(__instance, null); } } catch (Exception arg) { Plugin.Log.LogError((object)$"Could not clear the item description: {arg}"); } } } internal static class LanguageSourcesLoadedPatch { private static bool _fired; internal static bool Apply(Harmony harmony) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected O, but got Unknown MethodBase methodBase = AccessTools.EnumeratorMoveNext((MethodBase)AccessTools.Method(typeof(AsyncAssetLoading), "LoadLanguage", (Type[])null, (Type[])null)); if (methodBase == null) { Plugin.Log.LogError((object)"AsyncAssetLoading.LoadLanguage was not found; names will stay in English."); return false; } harmony.Patch(methodBase, (HarmonyMethod)null, new HarmonyMethod(typeof(LanguageSourcesLoadedPatch), "Postfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); return true; } private static void Postfix(bool __result) { if (__result || _fired) { return; } _fired = true; try { SpellLocalization.Register(); } catch (Exception arg) { Plugin.Log.LogError((object)$"Localization was not registered: {arg}"); } } } [HarmonyPatch(typeof(Unit), "CheckShouldDie")] internal static class MartyrBeadsPatch { private static void Postfix(Unit __instance, ref bool __result) { if (!__result || (Object)(object)__instance == (Object)null) { return; } try { GameManager instance = StaticInstance.Instance; if ((Object)(object)instance != (Object)null && (Object)(object)__instance == (Object)(object)instance.PlayerUnit && MartyrBeads.TryRescue(__instance)) { __result = false; } } catch (Exception ex) { Plugin.Log.LogError((object)("Martyr's beads failed: " + ex.Message)); } } } [HarmonyPatch(typeof(Unit), "ReceiveDamage", new Type[] { typeof(float), typeof(DamageSourceData), typeof(Data), typeof(Vector3?) })] internal static class PenitentRobePatch { private static void Prefix(Unit __instance, out float __state) { __state = -1f; try { GameManager instance = StaticInstance.Instance; if ((Object)(object)instance != (Object)null && (Object)(object)__instance != (Object)null && (Object)(object)__instance == (Object)(object)instance.PlayerUnit && __instance.Stats != null) { __state = __instance.Stats.GetStatus((EntityAttributes)92); } } catch (Exception) { __state = -1f; } } private static void Postfix(Unit __instance, DamageSourceData sourceData, float __state) { if (__state < 0f || (Object)(object)__instance == (Object)null || __instance.Stats == null) { return; } try { float taken = __state - __instance.Stats.GetStatus((EntityAttributes)92); PenitentRobe.OnStruck(__instance, taken, in sourceData, Time.time); } catch (Exception ex) { Plugin.Log.LogError((object)("Penitent robe failed: " + ex.Message)); } } } [HarmonyPatch(typeof(SingleItemPerSlotGrid), "PassesFilter")] internal static class RerollGridFilterPatch { private static bool Prefix(SingleItemPerSlotGrid __instance, InventoryItem item, ref bool __result) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 try { if ((int)__instance.filterType != 1 || (Object)(object)item == (Object)null || !SpellContent.IsSpellScroll(item.itemDefinition)) { return true; } __result = false; return false; } catch (Exception arg) { Plugin.Log.LogError((object)$"Reroll grid filter check failed: {arg}"); return true; } } } [HarmonyPatch(typeof(OilRerollStation), "UpdateCombination")] internal static class RerollCombinationPatch { private static void Postfix(List ___itemsToReroll, Button ___rerollConfirmButton) { try { if (___itemsToReroll != null && ___itemsToReroll.RemoveAll((InventoryItem item) => (Object)(object)item != (Object)null && SpellContent.IsSpellScroll(item.itemDefinition)) > 0 && ___itemsToReroll.Count == 0 && (Object)(object)___rerollConfirmButton != (Object)null) { ((Selectable)___rerollConfirmButton).interactable = false; } } catch (Exception arg) { Plugin.Log.LogError((object)$"Reroll combination filter failed: {arg}"); } } } [HarmonyPatch(typeof(ThrowableWeapon), "Throw")] internal static class SigilStakePatch { private static readonly FieldRef IgnoreThrowing = AccessTools.FieldRefAccess("ignoreThrowing"); private static bool Prefix(ThrowableWeapon __instance) { //IL_006e: 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_008b: 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_0092: 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_009c: 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) try { if ((Object)(object)__instance == (Object)null || (Object)(object)((Holdable)__instance).inventoryItem == (Object)null || SpellContent.ItemKeyOf(((Holdable)__instance).inventoryItem.itemDefinition) != "ryuka.sulfur.unholy_rites:sigil_stake" || IgnoreThrowing.Invoke(__instance)) { return true; } Camera main = Camera.main; SpellSession session = Plugin.Session; if ((Object)(object)main == (Object)null || session == null) { return true; } Transform transform = ((Component)main).transform; CastTrace.Forward(transform.position, transform.forward, 25f, SpellSession.LocalPlayer, out var point); Vector3 point2 = float3.op_Implicit(CastTrace.Below(point, 40f, point)); session.PlantStake(point2); __instance.ConsumeWithoutThrowing(); return false; } catch (Exception arg) { Plugin.Log.LogError((object)$"Sigil stake throw failed: {arg}"); return true; } } } [HarmonyPatch(typeof(Unit), "SpawnLoot")] internal static class SignatureLootPatch { private static void Prefix(bool ___hasDroppedLoot, out bool __state) { __state = ___hasDroppedLoot; } private static void Postfix(Unit __instance, bool ___hasDroppedLoot, bool __state) { if (!__state && ___hasDroppedLoot) { Acquisition.OnUnitPaidOut(__instance); } } } internal static class StaffDescription { internal static bool Describing; private static readonly FieldInfo TextsField = AccessTools.Field(typeof(ItemDescription), "localizedTextsCache"); internal static bool IsWeaponStat(string key, string value) { object obj = TextsField?.GetValue(null); if (obj == null) { return false; } Traverse val = Traverse.Create(obj); if (!Matches(key, val.Field("Label_Type").GetValue()) && !Matches(key, val.Field("Label_Damage").GetValue()) && !Matches(key, val.Field("Label_MagSize").GetValue()) && !Matches(key, val.Field("Label_Spread").GetValue())) { return Matches(value, val.Field("Label_RPM").GetValue()); } return true; } private static bool Matches(string a, string b) { if (!string.IsNullOrEmpty(a) && !string.IsNullOrEmpty(b)) { return a == b; } return false; } } [HarmonyPatch(typeof(ItemDescription), "Setup", new Type[] { typeof(InventoryItem) })] internal static class StaffDescriptionScopePatch { [HarmonyPriority(800)] private static void Prefix(InventoryItem inventoryItem) { try { StaffDescription.Describing = (Object)(object)inventoryItem != (Object)null && SpellContent.IsStaff(inventoryItem.itemDefinition); } catch (Exception arg) { StaffDescription.Describing = false; Plugin.Log.LogError((object)$"Could not tell whether a description is a staff's: {arg}"); } } private static Exception Finalizer(Exception __exception) { StaffDescription.Describing = false; return __exception; } } [HarmonyPatch(typeof(ItemDescription), "AddAttribute")] internal static class StaffDescriptionAttributePatch { private static bool Prefix(string key, string value) { try { return !StaffDescription.Describing || !StaffDescription.IsWeaponStat(key, value); } catch (Exception arg) { Plugin.Log.LogError((object)$"Staff description row check failed: {arg}"); return true; } } } [HarmonyPatch(typeof(ItemDescription), "AddAmmoType")] internal static class StaffDescriptionAmmoPatch { private static bool Prefix() { return !StaffDescription.Describing; } } [HarmonyPatch(typeof(ItemDescription), "AddDurability")] internal static class StaffDescriptionDurabilityPatch { private static bool Prefix() { return !StaffDescription.Describing; } } [HarmonyPatch(typeof(EquipmentManager), "Reload")] internal static class StaffReloadPatch { private static void Prefix() { try { if (HeldStaff.Equipped) { Plugin.Session?.ResetSegments(); } } catch (Exception arg) { Plugin.Log.LogError((object)$"Staff reload check failed: {arg}"); } } } [HarmonyPatch(typeof(Weapon), "AttemptShoot")] internal static class StaffAttemptShootPatch { private static bool Prefix(Weapon __instance) { try { return !HeldStaff.IsStaff(__instance); } catch (Exception arg) { Plugin.Log.LogError((object)$"Staff fire check failed: {arg}"); return true; } } } [HarmonyPatch(typeof(Holdable), "SetTrigger")] internal static class StaffSetTriggerPatch { private static void Postfix(Holdable __instance, bool state) { try { HeldStaff.OnTrigger((Weapon)(object)((__instance is Weapon) ? __instance : null), state); } catch (Exception arg) { Plugin.Log.LogError((object)$"Staff trigger tracking failed: {arg}"); } } } [HarmonyPatch] internal static class StaffProgramInvalidationPatch { [HarmonyPostfix] [HarmonyPatch(typeof(InventoryItem), "AddEnchantment")] private static void AfterAdd() { StaffProgram.Invalidate(); } [HarmonyPostfix] [HarmonyPatch(typeof(InventoryItem), "ClearAllEnchantments")] private static void AfterClear() { StaffProgram.Invalidate(); } [HarmonyPostfix] [HarmonyPatch(typeof(InventoryItem), "SetupEnchantmentsFromData")] private static void AfterLoad() { StaffProgram.Invalidate(); } } [HarmonyPatch(/*Could not decode attribute arguments.*/)] internal static class StaffPricePatch { private static void Postfix(InventoryItem __instance, ref int __result) { //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) try { if ((Object)(object)__instance == (Object)null || !SpellContent.IsStaff(__instance.itemDefinition)) { return; } int num = __instance.itemDefinition.basePrice; if (__instance.attachments != null) { for (int i = 0; i < __instance.attachments.Count; i++) { ItemDefinition val = __instance.attachments[i]; if ((Object)(object)val != (Object)null && val.id != ItemIds.Attachment_Insurance) { num += (int)((float)val.basePrice * 0.75f); } } } __result = num; } catch (Exception arg) { Plugin.Log.LogError((object)$"Staff price adjustment failed: {arg}"); } } } [HarmonyPatch(typeof(InventoryItem), "CanRecieveCaliberMod")] internal static class StaffCaliberModPatch { private static bool Prefix(InventoryItem __instance, ref bool __result) { try { if ((Object)(object)__instance == (Object)null || !SpellContent.IsStaff(__instance.itemDefinition)) { return true; } __result = false; return false; } catch (Exception arg) { Plugin.Log.LogError((object)$"Staff calibre check failed: {arg}"); return true; } } } [HarmonyPatch(typeof(InventoryItem), "SetCompatibleAttachments")] internal static class StaffAttachmentPatch { private static void Prefix(InventoryItem __instance, ref List attachmentsList) { //IL_0041: 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) try { if (attachmentsList == null || (Object)(object)__instance == (Object)null || !SpellContent.IsStaff(__instance.itemDefinition)) { return; } List list = new List(); foreach (ItemDefinition attachments in attachmentsList) { if ((Object)(object)attachments != (Object)null && attachments.id == ItemIds.Attachment_Insurance) { list.Add(attachments); } } for (int i = 0; i < ManaChambers.Keys.Length; i++) { if (SpellContent.TryGetItem(ManaChambers.Keys[i], out var definition)) { list.Add(definition); } } attachmentsList = list; } catch (Exception arg) { Plugin.Log.LogError((object)$"Staff attachment filter failed: {arg}"); } } } [HarmonyPatch(typeof(InventoryItem), "IsAttachmentCompatible")] internal static class StaffOneChamberPatch { private static void Postfix(InventoryItem __instance, ItemDefinition attachmentItem, ref bool __result) { try { if (__result && !((Object)(object)__instance == (Object)null) && !((Object)(object)attachmentItem == (Object)null) && SpellContent.IsStaff(__instance.itemDefinition) && ManaChambers.KindOf(attachmentItem) != ChamberKind.None) { __result = ManaChambers.Of(__instance) == ChamberKind.None; } } catch (Exception arg) { Plugin.Log.LogError((object)$"Staff chamber check failed: {arg}"); } } } [HarmonyPatch(typeof(ItemDescription), "Setup", new Type[] { typeof(InventoryItem) })] internal static class StaffPanelRowsPatch { private static void Postfix(ItemDescription __instance, InventoryItem inventoryItem) { try { StaffPanel.AttachTo(__instance, inventoryItem); } catch (Exception arg) { Plugin.Log.LogError((object)$"Could not prepare the staff panel rows: {arg}"); } } } [HarmonyPatch(typeof(EquipmentManager), "HandleAimInput")] internal static class TwinStaffAimPatch { private static FieldRef _altFire; private static FieldRef _prevented; private static FieldRef _controller; private static bool _resolved; private static bool _failed; private static void Postfix(EquipmentManager __instance, bool holdingMeleeAction) { if (_failed) { return; } try { if (!_resolved) { _resolved = true; _altFire = AccessTools.FieldRefAccess("altFireAction"); _prevented = AccessTools.FieldRefAccess("shootingPrevented"); _controller = AccessTools.FieldRefAccess("controller"); } InputAction val = _altFire.Invoke(__instance); if (HeldStaff.OnAimButton(val != null && val.IsPressed() && !holdingMeleeAction && !_prevented.Invoke(__instance))) { ExtendedAdvancedWalkerController val2 = _controller.Invoke(__instance); if ((Object)(object)val2 != (Object)null) { val2.ToggleSprint(false); } } } catch (Exception ex) { _failed = true; Plugin.Log.LogError((object)("Twin staff aim button could not be read; its second hand will not cast: " + ex.Message)); } } } [HarmonyPatch(typeof(Unit), "SpawnLoot")] internal static class UndeadLootPatch { private static bool Prefix(Unit __instance) { return !RaisedBody.Marks((Component)(object)__instance); } } [HarmonyPatch(typeof(ThrowableWeapon), "Throw")] internal static class VialThrowPatch { private static readonly FieldRef IgnoreThrowing = AccessTools.FieldRefAccess("ignoreThrowing"); private static bool Prefix(ThrowableWeapon __instance) { try { SealedVials.Kind kind = (((Object)(object)__instance != (Object)null && (Object)(object)((Holdable)__instance).inventoryItem != (Object)null) ? SealedVials.Find(SpellContent.ItemKeyOf(((Holdable)__instance).inventoryItem.itemDefinition)) : null); if (kind == null || IgnoreThrowing.Invoke(__instance)) { return true; } if (SealedVials.Usable() != kind) { UIManager instance = StaticInstance.Instance; if ((Object)(object)instance != (Object)null) { instance.ShowSmallAlert(LocalizationManager.GetTermTranslation("UnholyRites/VialRefused", true, 0, true, false, (GameObject)null, (string)null, true) ?? SpellTerms.VialRefused.English, 2.5f, (UISounds)0); } Plugin.Log.LogInfo((object)("Sealed vial '" + kind.ItemKey + "' was not thrown: another kind comes first in the gadget slots.")); return false; } SpellSession session = Plugin.Session; if (session == null || !session.ThrowVial(kind)) { return false; } __instance.ConsumeWithoutThrowing(); return false; } catch (Exception arg) { Plugin.Log.LogError((object)$"Sealed vial throw failed: {arg}"); return false; } } } [HarmonyPatch(typeof(AttributeEffect), "DistributeVoodooDamage")] internal static class VoodooSharePatch { private static bool Prefix(DamageSourceData sourceData, out bool __state) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Invalid comparison between Unknown and I4 __state = false; try { if (SpellDamageScope.Indirect > 0 || (int)sourceData.sourceEffect == 21) { return false; } SpellDamageScope.Indirect++; __state = true; return true; } catch (Exception arg) { Plugin.Log.LogError((object)$"Voodoo share check failed: {arg}"); return true; } } private static Exception Finalizer(Exception __exception, bool __state) { if (__state) { SpellDamageScope.Indirect--; } return __exception; } } } namespace UnholyRites.Net { internal enum SpellSessionRole { Offline, Host, Client } internal interface ISpellTransport : IDisposable { SpellSessionRole Role { get; } bool FriendlyFireEnabled { get; } event Action Received; int ResolvePlayerIndex(string peerId); bool SendToHost(byte[] payload); bool Broadcast(byte[] payload, string exceptPeerId = null); IDisposable RegisterHostSpawnOwner(MonoBehaviour owner); bool IsSharedWorldItem(Component pickup); bool ConsumeSharedWorldItem(Component pickup); int NameSpawnedUnit(Component unit); Component ResolveNamedUnit(int name); } internal sealed class SessionWorld : ISessionWorld { private readonly ISpellTransport _transport; internal SessionWorld(ISpellTransport transport) { _transport = transport; } public bool IsShared(Component pickup) { if (_transport != null) { return _transport.IsSharedWorldItem(pickup); } return false; } public bool Consume(Component pickup) { if (_transport != null) { return _transport.ConsumeSharedWorldItem(pickup); } return false; } public int NameOf(Component unit) { if (_transport == null) { return 0; } return _transport.NameSpawnedUnit(unit); } public Component Resolve(int name) { if (_transport == null) { return null; } return _transport.ResolveNamedUnit(name); } } internal enum SpellMessageKind : byte { Cast, WindupBegin, WindupCancel, Offering, Endowment, BeamBegin, BeamAim, BeamEnd, Kill } internal struct SpellCastMessage { internal const byte Version = 27; internal const int MaxProgram = 32; private const int HeaderBytes = 4; private const int VectorBytes = 12; private const int FixedBytes = 62; internal const float MaxClaimedOffering = 10000000f; private const byte FlagHasPoint = 1; internal SpellMessageKind Kind; internal float3 Origin; internal float3 Direction; internal float3 Point; internal float3 Caster; internal bool HasPoint; internal uint Seed; internal float Offering; internal ushort Subject; internal ushort[] Program; internal static SpellCastMessage Cancel() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) return new SpellCastMessage { Kind = SpellMessageKind.WindupCancel, Direction = new float3(0f, 0f, 1f), Program = new ushort[0] }; } internal static SpellCastMessage Aim(in CastTarget target, uint seed) { //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) //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_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) return new SpellCastMessage { Kind = SpellMessageKind.BeamAim, Origin = target.Origin, Direction = target.Direction, Point = target.Point, Caster = target.Caster, HasPoint = target.HasPoint, Seed = seed, Program = new ushort[0] }; } internal static SpellCastMessage BeamClosed() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) return new SpellCastMessage { Kind = SpellMessageKind.BeamEnd, Direction = new float3(0f, 0f, 1f), Program = new ushort[0] }; } internal static SpellCastMessage Offer(uint seed, float perBody) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) return new SpellCastMessage { Kind = SpellMessageKind.Offering, Direction = new float3(0f, 0f, 1f), Seed = seed, Offering = perBody, Program = new ushort[0] }; } internal static SpellCastMessage Killed(uint castSeed, ushort branch, float3 point, float3 direction, float maxHealth) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) return new SpellCastMessage { Kind = SpellMessageKind.Kill, Point = point, HasPoint = true, Direction = direction, Seed = castSeed, Subject = branch, Offering = maxHealth, Program = new ushort[0] }; } internal static SpellCastMessage Endow(int name, ushort definition, float perBody) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) return new SpellCastMessage { Kind = SpellMessageKind.Endowment, Direction = new float3(0f, 0f, 1f), Seed = (uint)name, Subject = definition, Offering = perBody, Program = new ushort[0] }; } internal static SpellCastMessage From(SpellMessageKind kind, in CastTarget target, uint seed, SpellKey[] program) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0047: 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_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) ushort[] array = new ushort[program.Length]; for (int i = 0; i < program.Length; i++) { array[i] = (ushort)SpellOrder.IndexOf(program[i]); } return new SpellCastMessage { Kind = kind, Origin = target.Origin, Direction = target.Direction, Point = target.Point, Caster = target.Caster, HasPoint = target.HasPoint, Seed = seed, Program = array }; } internal CastTarget ToTarget() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0018: 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_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_0032: 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) return new CastTarget { Origin = Origin, Direction = Direction, Point = Point, Caster = Caster, HasPoint = HasPoint }; } internal byte[] Encode() { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004f: 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_006b: Unknown result type (might be due to invalid IL or missing references) ushort[] program = Program; int num = ((program != null) ? program.Length : 0); byte[] array = new byte[62 + num * 2]; array[0] = 27; array[1] = (HasPoint ? ((byte)1) : ((byte)0)); array[2] = (byte)num; array[3] = (byte)Kind; int at = 4; at = WriteVector(array, at, Origin); at = WriteVector(array, at, Direction); at = WriteVector(array, at, Point); at = WriteVector(array, at, Caster); at = WriteUInt(array, at, Seed); at = WriteFloat(array, at, Offering); at = WriteUShort(array, at, Subject); for (int i = 0; i < num; i++) { at = WriteUShort(array, at, Program[i]); } return array; } internal static bool TryDecode(byte[] payload, out SpellCastMessage message, out string reason) { //IL_0166: Unknown result type (might be due to invalid IL or missing references) //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_0180: Unknown result type (might be due to invalid IL or missing references) //IL_018d: Unknown result type (might be due to invalid IL or missing references) //IL_01a3: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Unknown result type (might be due to invalid IL or missing references) message = default(SpellCastMessage); if (payload == null || payload.Length < 62) { reason = $"payload is {((payload != null) ? payload.Length : 0)} bytes, shorter than the {62} a cast needs"; return false; } if (payload[0] != 27) { reason = $"version {payload[0]}, expected {(byte)27}"; return false; } int num = payload[2]; if (num > 32) { reason = $"program claims {num} spells, more than the {32} accepted"; return false; } int num2 = 62 + num * 2; if (payload.Length != num2) { reason = $"payload is {payload.Length} bytes; a {num}-spell cast is {num2}"; return false; } message.HasPoint = (payload[1] & 1) != 0; byte b = payload[3]; if (b > 8) { reason = $"message kind {b} is not one this build knows"; return false; } message.Kind = (SpellMessageKind)b; int at = 4; at = ReadVector(payload, at, out message.Origin); at = ReadVector(payload, at, out message.Direction); at = ReadVector(payload, at, out message.Point); at = ReadVector(payload, at, out message.Caster); at = ReadUInt(payload, at, out message.Seed); at = ReadFloat(payload, at, out message.Offering); at = ReadUShort(payload, at, out message.Subject); if (!(message.Offering >= 0f) || float.IsInfinity(message.Offering)) { message.Offering = 0f; } if (!IsFinite(message.Origin) || !IsFinite(message.Direction) || !IsFinite(message.Point) || !IsFinite(message.Caster)) { reason = "a coordinate is not a finite number"; return false; } if (math.lengthsq(message.Direction) < 1E-06f) { reason = "aim direction is zero length"; return false; } message.Direction = math.normalize(message.Direction); message.Program = new ushort[num]; for (int i = 0; i < num; i++) { at = ReadUShort(payload, at, out message.Program[i]); } reason = null; return true; } internal bool TryResolve(SpellCatalog catalog, out SpellDefinition[] program, out string reason) { program = null; ushort[] program2 = Program; int num = ((program2 != null) ? program2.Length : 0); SpellDefinition[] array = new SpellDefinition[num]; for (int i = 0; i < num; i++) { SpellKey spellKey = SpellOrder.KeyAt(Program[i]); if (!spellKey.IsValid) { reason = $"spell id {Program[i]} is not one this build knows"; return false; } SpellDefinition spellDefinition = catalog?.Get(spellKey.Value); if (spellDefinition == null) { reason = $"spell '{spellKey}' is named but not in the catalogue"; return false; } array[i] = spellDefinition; } program = array; reason = null; return true; } private static bool IsFinite(float3 v) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) return math.all(math.isfinite(v)); } private static int WriteVector(byte[] buffer, int at, float3 value) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) at = WriteFloat(buffer, at, value.x); at = WriteFloat(buffer, at, value.y); return WriteFloat(buffer, at, value.z); } private static int ReadVector(byte[] buffer, int at, out float3 value) { //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) at = ReadFloat(buffer, at, out var value2); at = ReadFloat(buffer, at, out var value3); at = ReadFloat(buffer, at, out var value4); value = new float3(value2, value3, value4); return at; } private static int WriteFloat(byte[] buffer, int at, float value) { return WriteUInt(buffer, at, math.asuint(value)); } private static int ReadFloat(byte[] buffer, int at, out float value) { at = ReadUInt(buffer, at, out var value2); value = math.asfloat(value2); return at; } private static int WriteUInt(byte[] buffer, int at, uint value) { buffer[at] = (byte)value; buffer[at + 1] = (byte)(value >> 8); buffer[at + 2] = (byte)(value >> 16); buffer[at + 3] = (byte)(value >> 24); return at + 4; } private static int ReadUInt(byte[] buffer, int at, out uint value) { value = (uint)(buffer[at] | (buffer[at + 1] << 8) | (buffer[at + 2] << 16) | (buffer[at + 3] << 24)); return at + 4; } private static int WriteUShort(byte[] buffer, int at, ushort value) { buffer[at] = (byte)value; buffer[at + 1] = (byte)(value >> 8); return at + 2; } private static int ReadUShort(byte[] buffer, int at, out ushort value) { value = (ushort)(buffer[at] | (buffer[at + 1] << 8)); return at + 2; } } internal sealed class SpellNetwork : IDisposable { private sealed class RemoteBeam { internal BeamChannel Channel; internal uint Seed; internal float LastHeard; internal float OpenedAt; internal int Aims; } internal const float BeamAimInterval = 0.1f; private const float BeamSilence = 3f; private readonly SpellCatalog _catalog; private readonly SpellRuntime _runtime; private readonly SpellHitResolver _hits; private readonly PayloadTable _payloads; private ISpellTransport _transport; private int _rejected; private int _unattributed; private int _overclaimed; private readonly Dictionary _windups = new Dictionary(); private readonly Dictionary _beams = new Dictionary(); private readonly List _silent = new List(); private IDisposable _spawnOwner; internal SpellSessionRole Role => _transport?.Role ?? SpellSessionRole.Offline; internal bool ResolvesOwnDamage => Role != SpellSessionRole.Client; internal bool FriendlyFire => _transport?.FriendlyFireEnabled ?? false; internal CastAuthority OwnAuthority { get { if (!ResolvesOwnDamage) { return CastAuthority.Own; } return CastAuthority.Local; } } internal SpellNetwork(SpellCatalog catalog, SpellRuntime runtime, SpellHitResolver hits, PayloadTable payloads) { _catalog = catalog; _runtime = runtime; _hits = hits; _payloads = payloads; _transport = SpellTransports.Create(); if (_transport != null) { _transport.Received += OnReceived; try { _spawnOwner = _transport.RegisterHostSpawnOwner((MonoBehaviour)(object)Plugin.Behaviour); } catch (Exception ex) { Plugin.Log.LogWarning((object)("The session would not take responsibility for raised units, so they will exist only on the machine that raised them: " + ex.Message)); } Session.Current = new SessionWorld(_transport); } Offerings.Claimed += OnClaimed; Offerings.Endowed += OnEndowed; SpellHitResolver.KillSettled += OnKillSettled; } private void OnKillSettled(uint castSeed, ushort branch, float3 point, float3 direction, float maxHealth, bool mine) { //IL_0023: 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) if (_transport != null && Role == SpellSessionRole.Host && !(branch == 0 && mine)) { _transport.Broadcast(SpellCastMessage.Killed(castSeed, branch, point, direction, maxHealth).Encode()); } } private void OnClaimed(uint seed, float perBody) { if (_transport != null && Role == SpellSessionRole.Client) { _transport.SendToHost(SpellCastMessage.Offer(seed, perBody).Encode()); } } private void OnEndowed(Unit unit, float perBody) { if (_transport != null && Role == SpellSessionRole.Host && !((Object)(object)unit == (Object)null)) { int num = _transport.NameSpawnedUnit((Component)(object)unit); if (num > 0) { ushort definition = (ushort)(((Object)(object)unit.unitSO != (Object)null) ? unit.unitSO.id.value : 0); _transport.Broadcast(SpellCastMessage.Endow(num, definition, perBody).Encode()); } } } internal bool Announce(SpellMessageKind kind, in CastTarget target, uint seed, SpellKey[] program) { if (_transport == null || Role == SpellSessionRole.Offline) { return false; } if (program == null || program.Length == 0 || program.Length > 32) { Plugin.Log.LogWarning((object)($"A {kind} carried {((program != null) ? program.Length : 0)} spells, which is not something that " + "can be sent, so it was not. Other players will not see it.")); return false; } SpellCastMessage spellCastMessage = SpellCastMessage.From(kind, in target, seed, program); for (int i = 0; i < spellCastMessage.Program.Length; i++) { if (SpellOrder.KeyAt(spellCastMessage.Program[i]) != program[i]) { Plugin.Log.LogWarning((object)($"Spell '{program[i]}' has no position in SpellOrder, so the cast was not " + "sent. Other players will not see it.")); return false; } } Send(spellCastMessage.Encode()); return true; } internal void AnnounceCancel() { if (_transport != null && Role != SpellSessionRole.Offline) { Send(SpellCastMessage.Cancel().Encode()); } } internal void AnnounceBeamAim(in CastTarget target, uint seed) { if (_transport != null && Role != SpellSessionRole.Offline) { Send(SpellCastMessage.Aim(in target, seed).Encode()); } } internal void AnnounceBeamEnd() { if (_transport != null && Role != SpellSessionRole.Offline) { Send(SpellCastMessage.BeamClosed().Encode()); } } internal void Tick(float now) { if (_beams.Count == 0) { return; } foreach (KeyValuePair beam in _beams) { if (now - beam.Value.LastHeard > 3f) { _silent.Add(beam.Key); } else { beam.Value.Channel.Drive(now); } } for (int i = 0; i < _silent.Count; i++) { CloseBeam(_silent[i], "went quiet"); } _silent.Clear(); } private void CloseBeam(string peerId, string why) { if (peerId != null && _beams.TryGetValue(peerId, out var value)) { _beams.Remove(peerId); value.Channel.Close(); Plugin.Log.LogInfo((object)("Closed the beam replayed for '" + peerId + "' (" + (why ?? "ended") + "): " + $"{Time.time - value.OpenedAt:0.#}s, " + $"{value.Aims} aims, {value.Channel.Ticks} ticks.")); } } private void Send(byte[] payload) { if (Role == SpellSessionRole.Host) { _transport.Broadcast(payload); } else { _transport.SendToHost(payload); } } private void OnReceived(string senderPeerId, byte[] payload) { //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_02c8: Unknown result type (might be due to invalid IL or missing references) //IL_02bf: Unknown result type (might be due to invalid IL or missing references) //IL_04d7: Unknown result type (might be due to invalid IL or missing references) //IL_0458: Unknown result type (might be due to invalid IL or missing references) if (!SpellCastMessage.TryDecode(payload, out var message, out var reason)) { Reject(senderPeerId, reason); return; } if (message.Kind == SpellMessageKind.WindupCancel) { RetireWindup(senderPeerId); Relay(payload, senderPeerId); return; } if (message.Kind == SpellMessageKind.BeamAim) { if (_beams.TryGetValue(senderPeerId, out var value) && value.Seed == message.Seed) { value.Channel.Aim(message.ToTarget()); value.LastHeard = Time.time; value.Aims++; } Relay(payload, senderPeerId); return; } if (message.Kind == SpellMessageKind.BeamEnd) { CloseBeam(senderPeerId, null); Relay(payload, senderPeerId); return; } if (message.Kind == SpellMessageKind.Offering) { if (Role == SpellSessionRole.Host) { float num = Math.Min(message.Offering, 10000000f); if (num < message.Offering) { ReportOverclaim(senderPeerId, message.Offering); } Offerings.Receive(message.Seed, num); } return; } if (message.Kind == SpellMessageKind.Kill) { if (Role == SpellSessionRole.Client) { float time = Time.time; bool flag = message.Subject > 0 && _hits.ReplayKill(_runtime, message.Seed, message.Subject, message.Point, message.Direction, time); RecentCasts.Record record; bool flag2 = RecentCasts.TryGet(message.Seed, time, out record) && record.Mine; if (flag2) { SpellHitResolver.CreditKill(message.Seed, message.Offering); } Plugin.Log.LogInfo((object)($"The host says cast {message.Seed} killed: mine={flag2}, " + ((message.Subject > 0) ? ($"branch {message.Subject} " + (flag ? "played here." : "not played: this machine has no such cast.")) : "no branch."))); } return; } if (message.Kind == SpellMessageKind.Endowment) { if (Role == SpellSessionRole.Client) { EndowedPuppets.Endow((int)message.Seed, message.Subject, message.Offering); } return; } if (!message.TryResolve(_catalog, out var program, out reason)) { Reject(senderPeerId, reason); return; } CastPlan castPlan = SpellCompiler.Compile(program, _catalog); if (message.Kind == SpellMessageKind.Cast && castPlan.IsBeam) { Reject(senderPeerId, "a cast that compiles to a beam here; the sender's build differs"); return; } CastTarget target = message.ToTarget(); float time2 = Time.time; if (message.Kind == SpellMessageKind.WindupBegin) { RetireWindup(senderPeerId); int num2 = SpellGroups.Next(); _windups[senderPeerId] = num2; SpellCaster.BeginWindup(castPlan, _runtime, in target, message.Seed, time2, num2, followsCaster: false, Plugin.VoxelDensity.Value); SpellAudio.Chant(castPlan.Element, target.HasPoint ? target.Point : target.Caster, SpellScale.Power(castPlan.TotalCost)); Relay(payload, senderPeerId); } else if (message.Kind == SpellMessageKind.BeamBegin) { if (RetireWindup(senderPeerId)) { SpellCaster.Culminate(castPlan, _runtime, in target, message.Seed, time2, followsCaster: false, Plugin.VoxelDensity.Value); } CloseBeam(senderPeerId, "replaced"); if (!castPlan.IsBeam) { Reject(senderPeerId, "a beam was announced for a program that does not channel"); return; } BeamChannel beamChannel = new BeamChannel(castPlan, _runtime, _hits, in target, message.Seed, AuthorityFor(senderPeerId), time2, Plugin.VoxelDensity.Value); _beams[senderPeerId] = new RemoteBeam { Channel = beamChannel, Seed = message.Seed, LastHeard = time2, OpenedAt = time2 }; Plugin.Log.LogInfo((object)($"Replaying a beam from '{senderPeerId}': {beamChannel.Figures}/{castPlan.EmissionCount}" + $" figures x {castPlan.BeamArchetype.Damage:0.#}" + $" / {castPlan.BeamArchetype.TickInterval:0.##}s.")); if (beamChannel.Figures < castPlan.EmissionCount) { Plugin.Log.LogWarning((object)($"The runtime was full, so only {beamChannel.Figures} of " + $"{castPlan.EmissionCount} beam figures could be drawn for '{senderPeerId}'.")); } SpellAudio.Cast(castPlan.Element, target.Origin, SpellScale.Power(castPlan.TotalCost)); Relay(payload, senderPeerId); } else { if (RetireWindup(senderPeerId)) { SpellCaster.Culminate(castPlan, _runtime, in target, message.Seed, time2, followsCaster: false, Plugin.VoxelDensity.Value); } SpellCaster.Cast(castPlan, _runtime, null, _payloads, in target, message.Seed, time2, Plugin.VoxelDensity.Value, AuthorityFor(senderPeerId)); SpellAudio.Cast(castPlan.Element, target.Origin, SpellScale.Power(castPlan.TotalCost)); Relay(payload, senderPeerId); } } private CastAuthority AuthorityFor(string senderPeerId) { if (Role != SpellSessionRole.Host) { return CastAuthority.VisualOnly; } int num = _transport.ResolvePlayerIndex(senderPeerId); CastAuthority result = CastAuthority.Replayed(num); if (result.SuppressDamage) { ReportUnattributed(senderPeerId, num); } return result; } private void ReportUnattributed(string senderPeerId, int index) { _unattributed++; if (_unattributed <= 3 || _unattributed % 50 == 0) { Plugin.Log.LogWarning((object)("A cast from '" + senderPeerId + "' could not be attributed to a player " + $"(roster index {index}), so it was drawn without resolving damage. " + $"({_unattributed} so far.)")); } } private void Relay(byte[] payload, string senderPeerId) { if (Role == SpellSessionRole.Host) { _transport.Broadcast(payload, senderPeerId); } } private bool RetireWindup(string peerId) { if (peerId == null || !_windups.TryGetValue(peerId, out var value)) { return false; } _windups.Remove(peerId); _runtime.RetireGroup(value); return true; } private void ReportOverclaim(string senderPeerId, float claimed) { _overclaimed++; if (_overclaimed <= 3 || _overclaimed % 50 == 0) { Plugin.Log.LogWarning((object)($"'{senderPeerId}' claimed a rite was given {claimed:0}, above the " + $"{10000000f:0} a peer may claim, so it was capped. " + $"({_overclaimed} so far.)")); } } private void Reject(string senderPeerId, string reason) { _rejected++; if (_rejected <= 3 || _rejected % 50 == 0) { Plugin.Log.LogWarning((object)$"Dropped a cast from '{senderPeerId}': {reason}. ({_rejected} dropped so far.)"); } } public void Dispose() { _windups.Clear(); foreach (KeyValuePair beam in _beams) { beam.Value.Channel.Close(); } _beams.Clear(); _silent.Clear(); Offerings.Claimed -= OnClaimed; Offerings.Endowed -= OnEndowed; Session.Current = NoSession.Instance; _spawnOwner?.Dispose(); _spawnOwner = null; if (_transport != null) { _transport.Received -= OnReceived; _transport.Dispose(); _transport = null; } } } internal static class SpellTransports { private const string SulfurTogetherId = "com.ryuka.sulfur.together"; internal static ISpellTransport Create() { if (!Chainloader.PluginInfos.ContainsKey("com.ryuka.sulfur.together")) { Plugin.Log.LogInfo((object)"SULFUR Together is not loaded; spells are single player. Nothing is sent and every cast is this machine's own."); return null; } try { return CreateSulfurTogether(); } catch (Exception ex) { Plugin.Log.LogWarning((object)("SULFUR Together is loaded but its message channel could not be used, so spells stay local: " + ex.Message)); return null; } } [MethodImpl(MethodImplOptions.NoInlining)] private static ISpellTransport CreateSulfurTogether() { return new SulfurTogetherTransport(); } } internal sealed class SulfurTogetherTransport : ISpellTransport, IDisposable { private const string ChannelId = "ryuka.sulfur.unholy_rites.cast"; private IDisposable _registration; public SpellSessionRole Role { get { //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_000c: Invalid comparison between Unknown and I4 SessionRole role = NetSessionInfo.Role; if ((int)role != 1) { if ((int)role == 2) { return SpellSessionRole.Client; } return SpellSessionRole.Offline; } return SpellSessionRole.Host; } } public bool FriendlyFireEnabled => NetSessionInfo.FriendlyFireEnabled; public event Action Received; internal SulfurTogetherTransport() { _registration = (IDisposable)NetExternalChannel.Register("ryuka.sulfur.unholy_rites.cast", (Action)OnReceive); Plugin.Log.LogInfo((object)("Spell casts will travel over SULFUR Together (channel 'ryuka.sulfur.unholy_rites.cast', " + $"API version {1}).")); } public int ResolvePlayerIndex(string peerId) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(peerId)) { return -1; } IReadOnlyList peers = NetSessionInfo.Peers; for (int i = 0; i < peers.Count; i++) { ExternalPeer val = peers[i]; if (string.Equals(((ExternalPeer)(ref val)).PeerId, peerId, StringComparison.Ordinal)) { val = peers[i]; return ((ExternalPeer)(ref val)).PlayerIndex; } } return -1; } public IDisposable RegisterHostSpawnOwner(MonoBehaviour owner) { return (IDisposable)NetExternalSpawns.RegisterHostAuthoritativeOwner(owner); } public bool IsSharedWorldItem(Component pickup) { return NetExternalWorldItems.IsShared(pickup); } public bool ConsumeSharedWorldItem(Component pickup) { return NetExternalWorldItems.Consume(pickup); } public int NameSpawnedUnit(Component unit) { return NetExternalSpawns.GetSpawnId(unit); } public Component ResolveNamedUnit(int name) { return NetExternalSpawns.ResolveSpawn(name); } public bool SendToHost(byte[] payload) { if (Role != SpellSessionRole.Client) { return false; } return NetExternalChannel.Send("ryuka.sulfur.unholy_rites.cast", payload, (ExternalDelivery)0, (ExternalTarget)0, (string)null); } public bool Broadcast(byte[] payload, string exceptPeerId = null) { //IL_0030: 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) if (Role != SpellSessionRole.Host) { return false; } if (string.IsNullOrEmpty(exceptPeerId)) { return NetExternalChannel.Send("ryuka.sulfur.unholy_rites.cast", payload, (ExternalDelivery)0, (ExternalTarget)1, (string)null); } IReadOnlyList peers = NetSessionInfo.Peers; bool flag = false; for (int i = 0; i < peers.Count; i++) { ExternalPeer val = peers[i]; if (!((ExternalPeer)(ref val)).IsLocal && !((ExternalPeer)(ref val)).IsHost && !string.Equals(((ExternalPeer)(ref val)).PeerId, exceptPeerId, StringComparison.Ordinal)) { flag |= NetExternalChannel.Send("ryuka.sulfur.unholy_rites.cast", payload, (ExternalDelivery)0, (ExternalTarget)2, ((ExternalPeer)(ref val)).PeerId); } } return flag; } private void OnReceive(string senderPeerId, byte[] payload) { this.Received?.Invoke(senderPeerId, payload); } public void Dispose() { _registration?.Dispose(); _registration = null; this.Received = null; } } } namespace UnholyRites.Localization { internal static class SpellLocalization { [CompilerGenerated] private static class <>O { public static Func <0>__SetEnchantmentName; public static Func <1>__SetItemName; public static Func <2>__SetItemDescription; public static Func <3>__SetItemFlavor; public static OnLanguageChange <4>__OnLanguageChanged; } private const string EnglishLanguage = "English"; private const string ChineseLanguage = "Chinese"; private static LanguageSourceData _source; private static OnLanguageChange _handler; internal static string EnglishName => "English"; internal static void Register() { if (_source != null) { return; } try { _source = BuildSource(); if (_source != null) { LocalizationManager.AddSource(_source); LocalizationManager.LocalizeAll(true); FollowGameLanguage(); HookLanguageChange(); Plugin.Log.LogInfo((object)($"Localization registered: {_source.mTerms.Count} terms across " + $"{_source.mLanguages.Count} languages. Current: {LocalizationManager.CurrentLanguage} " + $"({LocalizationManager.CurrentLanguageCode}), mod text in {SpellText.Language}")); } } catch (Exception arg) { _source = null; Plugin.Log.LogError((object)$"Could not register localization; names will fall back to English: {arg}"); } } private static LanguageSourceData BuildSource() { //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_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Expected O, but got Unknown //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected O, but got Unknown //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Expected O, but got Unknown //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Expected O, but got Unknown //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Expected O, but got Unknown //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Expected O, but got Unknown //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Expected O, but got Unknown //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Expected O, but got Unknown //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Expected O, but got Unknown //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Expected O, but got Unknown //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Expected O, but got Unknown List list = MirrorGameLanguages(); if (list.Count == 0) { Plugin.Log.LogWarning((object)"The game has no language sources yet; localization was not registered."); return null; } LanguageSourceData val = new LanguageSourceData { mLanguages = list, mTerms = new List() }; AddTerm(val, "UnholyRites/VialRefused", SpellTerms.VialRefused); AddTerm(val, "UnholyRites/RitualBroken", SpellTerms.RitualBroken); AddTerm(val, "UnholyRites/ManaShort", SpellTerms.ManaShort); AddTerm(val, "UnholyRites/BloodShort", SpellTerms.BloodShort); AddTerm(val, "UnholyRites/BloodSpent", SpellTerms.BloodSpent); AddTerm(val, "UnholyRites/StaffEmpty", SpellTerms.StaffEmpty); AddTerm(val, "TutorialHints/UnholyRites_Staff", SpellTerms.StaffHint); AddTerm(val, "TutorialHints/UnholyRites_Order", SpellTerms.OrderHint); AddTerm(val, "UnholyRites/AllLeftOut", SpellTerms.AllLeftOut); AddTerm(val, "UnholyRites/ChantReleased", SpellTerms.ChantReleased); val.UpdateDictionary(true); return val; } internal static void GiveContentTexts() { foreach (KeyValuePair spellName in SpellTerms.SpellNames) { string key = spellName.Key; Give((Func)ContentTexts.SetEnchantmentName, SpellContent.EnchantmentKey(key), spellName.Value); string key2 = SpellContent.ScrollKey(key); Give((Func)ContentTexts.SetItemName, key2, SpellTerms.ScrollName(spellName.Value)); Give((Func)ContentTexts.SetItemDescription, key2, DescribeScroll(key)); } for (int i = 0; i < SealedVials.All.Length; i++) { SealedVials.Kind kind = SealedVials.All[i]; GiveItem(kind.ItemKey, SpellTerms.VialText(kind.Spell)); } for (int j = 0; j < RecipePages.All.Length; j++) { RecipePages.Page page = RecipePages.All[j]; Give((Func)ContentTexts.SetItemName, page.ItemKey, SpellTerms.PageName(page.Spell)); Give((Func)ContentTexts.SetItemDescription, page.ItemKey, SpellTerms.PageDescription(page.Spell)); } GiveItem("ryuka.sulfur.unholy_rites:martyr_beads", SpellTerms.BeadsText()); GiveItem("ryuka.sulfur.unholy_rites:penitent_robe", SpellTerms.RobeText()); GiveItem("ryuka.sulfur.unholy_rites:sigil_stake", SpellTerms.StakeText()); for (int k = 0; k < Oaths.Keys.Length; k++) { GiveItem(Oaths.Keys[k], SpellTerms.OathTextFor(Oaths.Keys[k])); } for (int l = 0; l < ManaChambers.Keys.Length; l++) { GiveItem(ManaChambers.Keys[l], SpellTerms.ChamberTextFor(ManaChambers.Keys[l])); } for (int m = 0; m < StaffDefinitions.All.Length; m++) { string itemKey = StaffDefinitions.All[m].ItemKey; SpellTerms.StaffText staffText = SpellTerms.StaffTextFor(itemKey); Give((Func)ContentTexts.SetItemName, itemKey, staffText.Name); Give((Func)ContentTexts.SetItemDescription, itemKey, new SpellTerms.Entry(staffText.Description.English + "
" + SpellTerms.StaffEditHint.English, staffText.Description.Chinese + "
" + SpellTerms.StaffEditHint.Chinese, staffText.Description.Traditional + "
" + SpellTerms.StaffEditHint.Traditional)); Give((Func)ContentTexts.SetItemFlavor, itemKey, staffText.Flavor); } } private static void GiveItem(string key, SpellTerms.ChamberText text) { Give((Func)ContentTexts.SetItemName, key, text.Name); Give((Func)ContentTexts.SetItemDescription, key, text.Description); } private static void Give(Func set, string key, SpellTerms.Entry entry) { set(key, "en", entry.English); set(key, "zh-CN", entry.Chinese); set(key, "zh-TW", entry.Traditional); } private static List MirrorGameLanguages() { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Expected O, but got Unknown List list = new List(); for (int i = 0; i < LocalizationManager.Sources.Count; i++) { LanguageSourceData val = LocalizationManager.Sources[i]; if (val == null || val.mLanguages == null || val == _source) { continue; } for (int j = 0; j < val.mLanguages.Count; j++) { LanguageData val2 = val.mLanguages[j]; if (val2 != null && !Contains(list, val2.Name)) { list.Add(new LanguageData { Name = val2.Name, Code = val2.Code }); } } } return list; } private static bool Contains(List languages, string name) { for (int i = 0; i < languages.Count; i++) { if (string.Equals(languages[i].Name, name, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } private static void AddTerm(LanguageSourceData source, string term, SpellTerms.Entry entry) { TermData val = source.AddTerm(term, (eTermType)0, true); val.Languages = new string[source.mLanguages.Count]; for (int i = 0; i < source.mLanguages.Count; i++) { LanguageData val2 = source.mLanguages[i]; val.Languages[i] = entry.In(LanguageOf(val2?.Code, val2?.Name)); } } internal static SpellTerms.Entry DescribeScroll(string spellKey) { SpellTerms.Entry value; SpellTerms.Entry result = (SpellTerms.SpellDescriptions.TryGetValue(spellKey, out value) ? value : SpellTerms.ScrollDescriptionAttack); if (!ContentBootstrap.Catalog.TryGet(new SpellKey(spellKey), out var definition) || definition == null) { return result; } string text = string.Empty; string text2 = string.Empty; string text3 = string.Empty; if (definition.Category == SpellCategory.Projectile && SpellTerms.Elements.TryGetValue(definition.Projectile.Element.ToString(), out var value2)) { text = text + Colored(value2.Color, value2.Name.English) + "
"; text2 = text2 + Colored(value2.Color, value2.Name.Chinese) + "
"; text3 = text3 + Colored(value2.Color, value2.Name.Traditional) + "
"; } SpellTerms.Entry entry; switch (definition.Category) { case SpellCategory.Transform: entry = SpellTerms.CategoryTransform; break; case SpellCategory.Payload: case SpellCategory.Segment: entry = SpellTerms.CategoryPayload; break; default: entry = SpellTerms.CategoryProjectile; break; } text = text + entry.English + "
"; text2 = text2 + entry.Chinese + "
"; text3 = text3 + entry.Traditional + "
"; return new SpellTerms.Entry(text + result.English, text2 + result.Chinese, text3 + result.Traditional); } private static string Colored(string hex, string text) { return "" + text + ""; } internal static SpellLanguage LanguageOf(string code, string name) { if (!string.IsNullOrEmpty(code)) { if (string.Equals(code, "zh-TW", StringComparison.OrdinalIgnoreCase) || string.Equals(code, "zh", StringComparison.OrdinalIgnoreCase)) { return SpellLanguage.TraditionalChinese; } if (!code.StartsWith("zh", StringComparison.OrdinalIgnoreCase)) { return SpellLanguage.English; } return SpellLanguage.Chinese; } if (name != null && name.IndexOf("Chinese", StringComparison.OrdinalIgnoreCase) >= 0) { if (name.IndexOf("Traditional", StringComparison.OrdinalIgnoreCase) < 0) { return SpellLanguage.Chinese; } return SpellLanguage.TraditionalChinese; } return SpellLanguage.English; } private static void HookLanguageChange() { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Expected O, but got Unknown //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown AsyncAssetLoading instance = StaticInstance.Instance; if (!((Object)(object)instance == (Object)null) && _handler == null) { object obj = <>O.<4>__OnLanguageChanged; if (obj == null) { OnLanguageChange val = OnLanguageChanged; <>O.<4>__OnLanguageChanged = val; obj = (object)val; } _handler = (OnLanguageChange)obj; instance.onLanguageChange = (OnLanguageChange)Delegate.Combine((Delegate?)(object)instance.onLanguageChange, (Delegate?)(object)_handler); } } private static void Rebuild() { try { if (_source != null) { LocalizationManager.RemoveSource(_source); _source = null; } _source = BuildSource(); if (_source != null) { LocalizationManager.AddSource(_source); LocalizationManager.LocalizeAll(true); } } catch (Exception arg) { Plugin.Log.LogError((object)$"Could not rebuild localization for the new language: {arg}"); } } internal static void OnLanguageChanged() { Rebuild(); FollowGameLanguage(); StaffProgram.Invalidate(); } internal static void FollowGameLanguage() { SpellText.Language = LanguageOf(LocalizationManager.CurrentLanguageCode, LocalizationManager.CurrentLanguage); } internal static void Unregister() { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Expected O, but got Unknown AsyncAssetLoading instance = StaticInstance.Instance; if ((Object)(object)instance != (Object)null && _handler != null) { instance.onLanguageChange = (OnLanguageChange)Delegate.Remove((Delegate?)(object)instance.onLanguageChange, (Delegate?)(object)_handler); } _handler = null; if (_source != null) { LocalizationManager.RemoveSource(_source); _source = null; } } } internal static class SpellTerms { internal struct Entry { public string English; public string Chinese; public string Traditional; public Entry(string english, string chinese, string traditional) { English = english; Chinese = chinese; Traditional = traditional; } public string In(SpellLanguage language) { return language switch { SpellLanguage.Chinese => Chinese, SpellLanguage.TraditionalChinese => Traditional, _ => English, }; } } internal readonly struct ChamberText { internal readonly Entry Name; internal readonly Entry Description; internal ChamberText(Entry name, Entry description) { Name = name; Description = description; } } internal readonly struct StaffText { internal readonly Entry Name; internal readonly Entry Description; internal readonly Entry Flavor; internal StaffText(Entry name, Entry description, Entry flavor) { Name = name; Description = description; Flavor = flavor; } } internal struct ElementLabel { public Entry Name; public string Color; public ElementLabel(string english, string chinese, string traditional, string color) { Name = new Entry(english, chinese, traditional); Color = color; } } internal const string ItemPrefix = "Items/"; internal const string EnchantmentPrefix = "EnchantmentDefinitions/"; internal static readonly Dictionary SpellNames = new Dictionary { { "fireball", new Entry("Fireball", "火球", "火球") }, { "frostbolt", new Entry("Frostbolt", "冰弹", "冰彈") }, { "meteor", new Entry("Meteor", "陨石", "隕石") }, { "sigil", new Entry("Withering Sigil", "蚀骨法阵", "蝕骨法陣") }, { "split", new Entry("Split", "分裂", "分裂") }, { "empower", new Entry("Empower", "强化", "強化") }, { "skyfall", new Entry("Skyfall", "天降", "天降") }, { "ritual", new Entry("Ritual", "仪式", "儀式") }, { "onhit", new Entry("On Hit", "命中之后", "命中之後") }, { "onmiss", new Entry("On Miss", "落空之后", "落空之後") }, { "onkill", new Entry("On Kill", "击杀之后", "擊殺之後") }, { "bounce", new Entry("Bounce", "弹跳", "彈跳") }, { "else", new Entry("Else", "否则", "否則") }, { "pulse", new Entry("Pulse", "脉动", "脈動") }, { "pierce", new Entry("Pierce", "穿透", "穿透") }, { "concussion", new Entry("Concussion", "震退", "震退") }, { "gather", new Entry("Gather", "聚拢", "聚攏") }, { "next", new Entry("Next", "下一发", "下一發") }, { "brand", new Entry("Brand", "圣印", "聖印") }, { "hex", new Entry("Hex", "咒缚", "咒縛") }, { "stone", new Entry("Stone Seal", "石印", "石印") }, { "sanctuary", new Entry("Sanctuary", "圣域", "聖域") }, { "radiance", new Entry("Radiance", "圣辉", "聖輝") }, { "blood", new Entry("Blood Price", "血价", "血價") }, { "raise", new Entry("Raise", "招魂", "招魂") }, { "grave_goods", new Entry("Grave Goods", "陪葬", "陪葬") }, { "venom", new Entry("Venom Flask", "毒液瓶", "毒液瓶") }, { "lightning", new Entry("Lightning", "雷电", "雷電") } }; internal static readonly Entry StaffName = new Entry("Unholy Rite", "不洁仪式", "不潔儀式"); internal static readonly Entry StaffDescription = new Entry("A guttering flame that remembers every rite it was made to serve. Inscribe spells onto it; the order they are inscribed in is the spell.", "一簇将熄的火,记得它侍奉过的每一场仪式。把法术刻上去,刻写的顺序本身就是法术。", "一簇將熄的火,記得它侍奉過的每一場儀式。把法術刻上去,刻寫的順序本身就是法術。"); internal static readonly Entry StaffEditHint = new Entry("Hold Ctrl to reorder the spells.", "按住 Ctrl 可调整法术顺序。", "按住 Ctrl 可調整法術順序。"); internal static readonly Entry StaffFlavor = new Entry("It has burned longer than the church it came from.", "它烧得比那座教堂还久。", "它燒得比那座教堂還久。"); internal static readonly Entry LongStaffName = new Entry("Long Vigil", "长守之杖", "長守之杖"); internal static readonly Entry LongStaffDescription = new Entry("A long staff that holds eight spells. It is slow to cast again, but chanting with it doesn't slow you down.", "一根长杖,可刻八个法术。施法间隔长,但咏唱时不会减速。", "一根長杖,可刻八個法術。施法間隔長,但詠唱時不會減速。"); internal static readonly Entry LongStaffFlavor = new Entry("Made for vigils that last till dawn.", "为守到天明的夜祷而做。", "為守到天明的夜禱而做。"); internal static readonly Entry GravekeeperName = new Entry("Gravekeeper's Rite", "守墓者", "守墓者"); internal static readonly Entry GravekeeperDescription = new Entry("A staff that keeps the dead. Every cast ends with a Raise that takes no slot, so each Withering Sigil it casts raises the dead; that Raise costs what an inscribed one would, and nothing when there is no sigil for it.", "看守亡者的法杖。每次施法末尾都自带一次不占位置的招魂,放出的蚀骨法阵都会唤起死者;这次招魂和刻上去的一样收费,没有法阵时不收费。", "看守亡者的法杖。每次施法結尾都自帶一次不佔位置的招魂,放出的蝕骨法陣都會喚起死者;這次招魂和刻上去的一樣收費,沒有法陣時不收費。"); internal static readonly Entry GravekeeperFlavor = new Entry("It has buried more than it has lost.", "它埋下的,比它失去的多。", "它埋下的,比它失去的多。"); internal static readonly Entry TwinStaffName = new Entry("Twin Rite", "双生杖", "雙生杖"); internal static readonly Entry TwinStaffDescription = new Entry("Spells before a Next cast with the trigger and spells after it with the aim button, up to four each; without a Next, the first four go to the trigger. Both share one cooldown, and since the aim button casts, it can't aim down sights.", "“下一发”之前的法术用扳机施放,之后的用瞄准键施放,每边最多四个;没有“下一发”时,前四个归扳机。两边共用冷却;瞄准键用来施法,所以不能开镜。", "「下一發」之前的法術用扳機施放,之後的用瞄準鍵施放,每邊最多四個;沒有「下一發」時,前四個歸扳機。兩邊共用冷卻;瞄準鍵用來施法,所以無法開鏡瞄準。"); internal static readonly Entry TwinStaffFlavor = new Entry("Each hand keeps its own prayer.", "两只手,各守各的祷词。", "兩隻手,各守各的禱詞。"); internal const string VialRefusedTerm = "UnholyRites/VialRefused"; internal const string RitualBrokenTerm = "UnholyRites/RitualBroken"; internal static readonly Entry RitualBroken = new Entry("The ritual broke: you moved while chanting", "仪式被打断:咏唱时移动了", "儀式被打斷:詠唱時移動了"); internal const string ManaShortTerm = "UnholyRites/ManaShort"; internal static readonly Entry ManaShort = new Entry("Not enough mana", "法力不足", "法力不足"); internal const string BloodShortTerm = "UnholyRites/BloodShort"; internal static readonly Entry BloodShort = new Entry("Not enough health to pay in blood", "生命值不够付血价", "HP 不夠付血價"); internal static readonly Entry StaffHint = new Entry("A staff casts the spells inscribed on it, in order. Drag a spell scroll onto the staff to inscribe it, and hold Ctrl over the staff and drag a row to change the order. Hover over the staff to see what it will cast and what that costs.\n\nThe full guide: github.com/ryuka-dev/Unholy_Rites/tree/master/docs/players/en", "法杖按顺序施放刻在它上面的法术。把法术卷轴拖到法杖上就能刻写;鼠标停在法杖上按住 Ctrl,拖动某一行可以调整顺序。鼠标停在法杖上,能看到它会放出什么、要花多少法力。\n\n完整说明:github.com/ryuka-dev/Unholy_Rites/tree/master/docs/players/zh-CN", "法杖會依序施放刻在上面的法術。把法術卷軸拖到法杖上就能刻寫;滑鼠停在法杖上按住 Ctrl,拖動某一行可以調整順序。滑鼠停在法杖上,就能看到它會放出什麼、要花多少法力。\n\n完整說明(簡體中文):github.com/ryuka-dev/Unholy_Rites/tree/master/docs/players/zh-CN"); internal static readonly Entry OrderHint = new Entry("Order matters. A modifier such as Empower or Split changes the spells inscribed before it. A trigger such as On Hit makes the spells after it ride on the ones before it and go off where those hit. A row that does nothing where it is turns grey, and the staff's description says why.", "顺序很重要。强化、分裂这类修饰法术,只改它前面的法术。命中之后这类触发法术,让后面的法术由前面的法术带着,在它们命中的地方施放。放的位置不起作用的那一行会变灰,法杖说明里会写原因。", "順序很重要。強化、分裂這類修飾法術,只改它前面的法術。命中之後這類觸發法術,讓後面的法術由前面的法術帶著,在它們命中的地方施放。放的位置不起作用的那一行會變灰,法杖說明裡會寫原因。"); internal const string StaffEmptyTerm = "UnholyRites/StaffEmpty"; internal static readonly Entry StaffEmpty = new Entry("This staff has no spells yet: drag a spell scroll onto it", "这根法杖上还没有法术:把法术卷轴拖到它上面", "這根法杖上還沒有法術:把法術卷軸拖到它上面"); internal const string AllLeftOutTerm = "UnholyRites/AllLeftOut"; internal static readonly Entry AllLeftOut = new Entry("None of these spells can be cast: hover over the staff to see why", "这些法术都放不出来:鼠标停在法杖上看原因", "這些法術都放不出來:滑鼠停在法杖上看原因"); internal const string ChantReleasedTerm = "UnholyRites/ChantReleased"; internal static readonly Entry ChantReleased = new Entry("Let go too soon: hold the trigger until the chant is done", "松手太早:要一直按住扳机,直到咏唱念完", "放手太早:要一直按住扳機,直到詠唱念完"); internal const string BloodSpentTerm = "UnholyRites/BloodSpent"; internal static readonly Entry BloodSpent = new Entry("You have paid all the blood this floor allows", "这一层能付的血已经付满了", "這一層能付的血已經付滿了"); internal static readonly Entry VialRefused = new Entry("Only your first kind of vial can be thrown", "只有排在最前的那种封瓶扔得出去", "只有排在最前面的那種封瓶扔得出去"); internal static readonly Entry ScrollDescriptionAttack = new Entry("Inscribe onto a staff.", "刻写到法杖上。", "刻寫到法杖上。"); internal static readonly Entry CategoryProjectile = new Entry("Base spell", "基础法术", "基礎法術"); internal static readonly Entry CategoryTransform = new Entry("Modifier spell", "修饰法术", "修飾法術"); internal static readonly Entry CategoryPayload = new Entry("Trigger spell", "触发法术", "觸發法術"); internal static readonly Dictionary Elements = new Dictionary { { "Fire", new ElementLabel("Fire damage", "火系伤害", "火炎傷害", "FF8C3F") }, { "Frost", new ElementLabel("Frost damage", "冰系伤害", "冰霜傷害", "6FC3FF") }, { "Holy", new ElementLabel("Holy damage", "神圣伤害", "神聖傷害", "FFF0B8") }, { "Dark", new ElementLabel("Dark damage", "暗影伤害", "闇屬性傷害", "B478F0") }, { "Electric", new ElementLabel("Electric damage", "电系伤害", "電擊傷害", "E8E85A") }, { "Poison", new ElementLabel("Poison damage", "毒系伤害", "毒傷害", "99E066") }, { "Explosive", new ElementLabel("Explosive damage", "爆炸伤害", "爆炸傷害", "F2B272") } }; internal static readonly Dictionary SpellDescriptions = new Dictionary { { "fireball", new Entry("A bolt of fire thrown along your aim. Fire sets alight the poison lying on the ground, and detonates a heavily poisoned target.", "沿准星飞出的火焰弹。火会点燃地上的毒液,也会引爆中毒够深的目标。", "沿準心飛出的火焰彈。火會點燃地上的毒液,也會引爆中毒夠深的目標。") }, { "frostbolt", new Entry("A fast, thin shard of cold that slows whatever it strikes. Enough cold at once will shatter something already close to death.", "一枚快速的寒冰碎片,会使命中的目标减速。同时积累足够的寒气,能让濒死的敌人当场碎裂。", "一枚快速的寒冰碎片,會使命中的目標減速。同時累積足夠的寒氣,能讓瀕死的敵人當場碎裂。") }, { "meteor", new Entry("A heavy charge thrown on an arc that bursts where it stops, catching everything near it, its caster included.", "抛物线飞出的沉重爆裂物,在停下处炸开一片,施法者离得太近也会被波及。", "沿拋物線飛出的沉重爆裂物,在停下處炸開一片,施法者離得太近也會被波及。") }, { "venom", new Entry("A flask thrown on an arc that breaks into pools of poison where it lands.", "抛物线掷出的毒瓶,落地碎开成毒液水洼。", "沿拋物線擲出的毒瓶,落地碎開成毒液水窪。") }, { "sigil", new Entry("Draws a sigil on the ground that eats away at whatever stands in it.", "在地面刻出法阵,持续腐蚀站在其中的目标。", "在地面刻出法陣,持續腐蝕站在其中的目標。") }, { "split", new Entry("Casts everything inscribed before it twice. Doubles the cost.", "之前刻写的法术施放两次。代价翻倍。", "之前刻寫的法術施放兩次。代價翻倍。") }, { "empower", new Entry("Raises the damage and size of everything inscribed before it. Costs 50% more mana.", "提高之前刻写法术的伤害和范围,法力消耗增加 50%。", "提高之前刻寫法術的傷害和範圍,法力消耗增加 50%。") }, { "skyfall", new Entry("Everything inscribed before it falls from the sky onto a chosen point instead of flying from your hand. The spells themselves don't change.", "之前刻写的法术改为从天空落向指定地点,不再从手中飞出。法术本身不变。", "之前刻寫的法術改為從天空落向指定地點,不再從手中飛出。法術本身不變。") }, { "lightning", new Entry("A beam held open for as long as the trigger is, sweeping wherever it is aimed and passing through bodies. Mana drains while it burns, whether or not it is on anything.", "按住扳机不放,光束就一直存在,指向哪里扫到哪里,并且会穿透生物。开着就持续消耗法力,打没打到都一样。", "按住扳機不放,光束就一直存在,指向哪裡掃到哪裡,並且會穿透生物。開著就持續消耗法力,打沒打到都一樣。") }, { "ritual", new Entry("Raises the damage and size of everything inscribed before it (no effect on beams, and a second Ritual adds no more). It costs no mana, only a long chant you must stand still through: walking breaks it, being knocked back doesn't.", "提高之前刻写法术的伤害和范围(对光束无效,刻两个也只生效一次)。不耗法力,代价是一段必须站着不动的长咏唱:自己走动会打断,被击退不会。", "提高之前刻寫法術的傷害和範圍(對光束無效,刻兩個也只生效一次)。不耗法力,代價是一段必須站著不動的長詠唱:自己走動會打斷,被擊退不會。") }, { "onhit", new Entry("Spells inscribed after it are carried by the ones before it and cast where those hit something living. You pay for them when you cast, even if they never go off.", "它后面的法术由它前面的法术携带,在命中生物处施放。被携带的法术在施法时就扣费,没触发也一样。", "它後面的法術由它前面的法術攜帶,在命中生物處施放。被攜帶的法術在施法時就扣費,沒觸發也一樣。") }, { "onmiss", new Entry("Spells inscribed after it are carried by the ones before it and cast where those stop without hitting anything living (a wall counts as a miss). You pay for them when you cast, even if they never go off.", "它后面的法术由它前面的法术携带,在没命中生物而停下的地方施放(打墙也算)。被携带的法术在施法时就扣费,没触发也一样。", "它後面的法術由它前面的法術攜帶,在沒命中生物而停下的地方施放(打到牆也算)。被攜帶的法術在施法時就扣費,沒觸發也一樣。") }, { "bounce", new Entry("The spells inscribed before it bounce off walls and floors twice before they stop. Hitting a body or anything breakable still stops them.", "之前刻写的飞行法术碰到墙壁和地面会弹开两次再停下;打中生物或可破坏物照样停下。", "之前刻寫的飛行法術碰到牆壁和地面會彈開兩次再停下;打中生物或可破壞物照樣停下。") }, { "onkill", new Entry("Spells inscribed after it are carried by the ones before it and cast where those kill something themselves (not through reactions or lingering damage). You pay for them when you cast, even if they never go off.", "它后面的法术由它前面的法术携带,在它们亲手击杀目标处施放(反应和持续伤害造成的击杀不算)。被携带的法术在施法时就扣费,没触发也一样。", "它後面的法術由它前面的法術攜帶,在它們親手擊殺目標處施放(反應和持續傷害造成的擊殺不算)。被攜帶的法術在施法時就扣費,沒觸發也一樣。") }, { "blood", new Entry("The spells inscribed before it, and whatever is later done to them, cost health instead of mana, 1 health per 4 mana. It never takes you below a quarter of your health, or more than your full health per floor.", "之前刻写的法术,连同之后对它们的强化,改用生命值支付,每 4 点法力折 1 点生命值。不会让生命值低于四分之一,每层最多付满一整条生命值。", "之前刻寫的法術,連同之後對它們的強化,改用 HP 支付,每 4 點法力折 1 點 HP。不會讓 HP 低於四分之一,每層最多付滿一整條 HP。") }, { "radiance", new Entry("A flash of holy light around you. Enemies near you are blinded and lose sight of you for a moment.", "以自身为中心爆出一圈圣光。附近的敌人被致盲,一时看不见你。", "以自身為中心爆出一圈聖光。附近的敵人被致盲,一時看不見你。") }, { "sanctuary", new Entry("Draws a circle of holy light on the ground. Enemies that come into it flee in terror.", "在地上画出圣光之圈。闯进来的敌人会惊恐逃走。", "在地上畫出聖光之圈。闖進來的敵人會驚恐逃走。") }, { "stone", new Entry("Turns what it strikes to stone, which only melee can break. It works only on its own: split, called down or carried, it does nothing and costs nothing.", "把命中的目标变成石像,只有近战能打碎。只能单独施放:被分裂、天降或携带时无效,也不耗法力。", "把命中的目標變成石像,只有近戰能打碎。只能單獨施放:被分裂、天降或攜帶時無效,也不耗法力。") }, { "hex", new Entry("Links each enemy it hits with the others you have hexed, up to four at once. A direct hit on one also deals half its damage to each of the others, even through walls.", "命中的敌人会和你咒缚过的其他敌人连在一起,最多同时四个。其中一个受到直接伤害时,其余每个也承受一半,无视掩体。", "命中的敵人會和你咒縛過的其他敵人連在一起,最多同時四個。其中一個受到直接傷害時,其餘每個也承受一半,無視掩體。") }, { "brand", new Entry("A light holy bolt. Every hit on the target it brands, this one included and from anyone, deals 35% extra as holy damage; damage from reactions doesn't count.", "轻型神圣弹。被圣印标记的目标每挨一下(含这一发,谁打的都算)额外受到 35% 神圣伤害,反应造成的伤害不算。", "輕型神聖彈。被聖印標記的目標每挨一下(含這一發,誰打的都算)額外受到 35% 神聖傷害,反應造成的傷害不算。") }, { "next", new Entry("Ends one cast: the spells after it go off on your next trigger press. Each press casts the next part in order, and reloading goes back to the first.", "结束这一发:后面的法术在下一次扣扳机时施放。每按一次依次施放下一段,按装填键回到第一段。", "結束這一發:後面的法術在下一次扣扳機時施放。每按一次依序施放下一段,按裝填鍵回到第一段。") }, { "concussion", new Entry("What is inscribed before it knocks back what it strikes, once per cast.", "之前刻写的法术会把命中的目标击退,每次施法每个目标一次。", "之前刻寫的法術會把命中的目標擊退,每次施法每個目標一次。") }, { "gather", new Entry("Spells inscribed before it that are called down or placed on the ground pull what they hit towards their centre, once per target per cast.", "之前刻写的天降法术和地面法术会把命中的目标拉向中心,每次施法每个目标一次。", "之前刻寫的天降法術和地面法術會把命中的目標拉向中心,每次施法每個目標一次。") }, { "pierce", new Entry("Projectiles inscribed before it pass through the first two living things they hit, weaker each time, and trigger the spells they carry at each one.", "之前刻写的投射物会穿过最先命中的两个生物,每穿一次伤害减弱,每次都会触发所携带的法术。", "之前刻寫的投射物會穿過最先命中的兩個生物,每穿一次傷害減弱,每次都會觸發所攜帶的法術。") }, { "pulse", new Entry("Each Pulse lets a ground sigil inscribed before it trigger its On Hit spells once more when an enemy stands in it, up to 4 times in all.", "之前刻写的地面法阵,每加一个脉动,有敌人站进来时就能多触发一次“命中之后”,最多共 4 次。", "之前刻寫的地面法陣,每加一個脈動,有敵人站進來時就能多觸發一次「命中之後」,最多共 4 次。") }, { "else", new Entry("The spells after it go off when the nearest On Hit or On Miss before it doesn't, carried by the same spell. Only one side can happen, so you pay only for the dearer one.", "它后面的法术,在它前面最近的“命中之后”或“落空之后”没有发生时施放,由同一个法术携带。两边只会发生一边,所以只按较贵的那边付费。", "它後面的法術,在它前面最近的「命中之後」或「落空之後」沒有發生時施放,由同一個法術攜帶。兩邊只會發生一邊,所以只按較貴的那邊付費。") }, { "raise", new Entry("Makes the dead inside a Withering Sigil rise. They fight for you at half their strength, and lie back down when their time is up.", "使蚀骨法阵范围内的尸体作为亡灵起身。亡灵以一半的实力为你作战,时间到了便重新倒下。", "使蝕骨法陣範圍內的屍體作為亡靈起身。亡靈以一半的實力為你作戰,時間到了便重新倒下。") }, { "grave_goods", new Entry("Consumes the items inside the sigil to strengthen the dead it raises; the more valuable they are, the stronger. Must be inscribed after Raise.", "消耗法阵内的物品强化起身的亡灵,物品越贵重,强化越多。须刻在招魂之后。", "消耗法陣內的物品強化起身的亡靈,物品越貴重,強化越多。須刻在招魂之後。") } }; internal static ChamberText StakeText() { return new ChamberText(new Entry("Sigil Stake", "法阵钉", "法陣釘"), new Entry("Throw it to plant it where you aim, up to 25 m away; your next spell aimed at the ground towards it lands on the stake, even out of sight. It falls after 20 seconds or if you go too far away.", "扔出后插在准星处(最远 25 米),下一次朝它方向、指向地面施放的法术会落在钉子上,看不见也行。20 秒后或走得太远时,钉子会倒下。", "扔出後插在準心處(最遠 25 公尺),下一次朝它方向、指向地面施放的法術會落在釘子上,看不見也行。20 秒後或走得太遠時,釘子會倒下。")); } internal static ChamberText VialText(string spell) { Entry value; Entry obj = (SpellNames.TryGetValue(spell, out value) ? value : new Entry(spell, spell, spell)); string english = obj.English; string chinese = obj.Chinese; string traditional = obj.Traditional; return new ChamberText(new Entry("Sealed Vial: " + english, "封瓶:" + chinese, "封瓶:" + traditional), new Entry("Throw it to cast " + english + " where it lands, with no modifiers and no mana. If you carry several kinds, only the one that comes first can be thrown.", "扔出后在落点施放一次" + chinese + ",不带修饰,不耗法力。带着多种封瓶时,只能扔出排在最前面的那种。", "扔出後在落點施放一次" + traditional + ",不帶修飾,不耗法力。帶著多種封瓶時,只能扔出排在最前面的那種。")); } internal static ChamberText BeadsText() { return new ChamberText(new Entry("Martyr's Beads", "殉道念珠", "殉道念珠"), new Entry("A killing blow leaves you at 1 health instead, clear of burning, poison and bleeding, with 4 seconds in which nothing can hurt you, and the staff in your hand casts its spells once around you, free and harmless to you (a beam is not cast). The beads are used up; an Instant Defibrillator you carry goes first.", "受到致命一击时改为保留 1 点生命值,清除燃烧、猛毒和流血,4 秒内不受伤害,手中法杖免费在你身边施放一次(不伤自己,光束不会施放)。念珠随即消耗;同时带着即刻除颤仪时,除颤仪先生效。", "受到致命一擊時改為保留 1 點 HP,清除燃燒、中毒和流血,4 秒內不受傷害,手中法杖免費在你身邊施放一次(不傷自己,光束不會施放)。念珠隨即消耗;同時帶著瞬間心臟除顫器時,除顫器先生效。")); } internal static ChamberText RobeText() { return new ChamberText(new Entry("Penitent Robe", "苦修衣", "苦修衣"), new Entry("It protects nothing. Each point of health an enemy takes from you gives the staff in your hand 2 mana, up to 30 mana per second and three times the staff's maximum mana per floor.", "毫无防护。敌人每打掉你 1 点生命值,手中法杖回 2 点法力;每秒最多回 30 点,每层合计不超过法力上限的三倍。", "毫無防護。敵人每打掉你 1 點 HP,手中法杖回 2 點法力;每秒最多回 30 點,每層合計不超過法力上限的三倍。")); } internal static ChamberText OathTextFor(string key) { return key switch { "ryuka.sulfur.unholy_rites:oath_nail" => new ChamberText(new Entry("Oath of the Nail", "圣钉誓", "聖釘誓"), new Entry("An oath. Weapon damage dealt to a branded enemy is stored, and your next direct spell hit on it (not a beam, and not the cast that branded it) releases half of it as holy damage, up to 105, and removes the brand. Only your first oath counts.", "誓约。武器对带圣印的敌人造成的伤害会被记下;你的法术下一次直接命中它时(光束和挂上圣印的那次施法不算),把记下的一半一次性转为神圣伤害(最多 105),并消耗圣印。只有排在最前的誓约生效。", "誓約。武器對帶聖印的敵人造成的傷害會被記下;你的法術下一次直接命中它時(光束和掛上聖印的那次施法不算),把記下的一半一次性轉為神聖傷害(最多 105),並消耗聖印。只有排在最前面的誓約生效。")), "ryuka.sulfur.unholy_rites:oath_blood" => new ChamberText(new Entry("Blood Oath", "血祭誓", "血祭誓"), new Entry("An oath. When a cast with Ritual in it is short of mana, the rest is taken from your health once you have stood through the chant: 1 health per 4 mana, never below a quarter of your health, and counted against Blood Price's limit per floor. Only your first oath counts.", "誓约。带仪式的施法法力不够时,站着念完后差额改扣生命值:每 4 点法力折 1 点生命值,不会扣到生命值的四分之一以下,并与血价共用每层上限。只有排在最前的誓约生效。", "誓約。帶儀式的施法法力不夠時,站著念完後差額改扣 HP:每 4 點法力折 1 點 HP,不會扣到 HP 的四分之一以下,並與血價共用每層上限。只有排在最前面的誓約生效。")), "ryuka.sulfur.unholy_rites:oath_suture" => new ChamberText(new Entry("Suture Thread", "缝尸线", "縫屍線"), new Entry("An oath. Your Raise sews every body it takes into one undead: the largest of them, with their health added together up to three times its own, and all the grave goods. Only your first oath counts.", "誓约。你的招魂把圈到的尸体缝成一个亡灵:取其中最大的那具,生命值相加,最多到它自己的三倍,陪葬品全给它。只有排在最前的誓约生效。", "誓約。你的招魂把圈到的屍體縫成一個亡靈:取其中最大的那具,HP 相加,最多到它自己的三倍,陪葬品全給它。只有排在最前面的誓約生效。")), "ryuka.sulfur.unholy_rites:oath_vigil" => new ChamberText(new Entry("Oath of Vigil", "守望誓", "守望誓"), new Entry("An oath. When an enemy you feared or blinded dies, its remaining fear or blindness passes to the nearest enemy it could see within 6 m, and goes no further. Only your first oath counts.", "誓约。被你恐惧或致盲的敌人死亡时,剩余的恐惧或失明会转到它看得见的 6 米内最近的敌人身上,只转一次。只有排在最前的誓约生效。", "誓約。被你恐懼或致盲的敵人死亡時,剩餘的恐懼或致盲會轉到它看得見的 6 公尺內最近的敵人身上,只轉一次。只有排在最前面的誓約生效。")), _ => new ChamberText(new Entry("Catalyst Stone", "催化石", "催化石"), new Entry("An oath. When a reaction you set off bursts, every enemy it reaches that carries the same status sets off its own too, at half strength and hurting only itself. Only your first oath counts.", "誓约。你引发的反应爆开时,被波及且身上带同类状态的敌人也会各自引爆,威力减半,只伤它自己。只有排在最前的誓约生效。", "誓約。你引發的反應爆開時,被波及且身上帶同類狀態的敵人也會各自引爆,威力減半,只傷它自己。只有排在最前面的誓約生效。")), }; } internal static ChamberText ChamberTextFor(string key) { return key switch { "ryuka.sulfur.unholy_rites:chamber_cell" => new ChamberText(new Entry("Cell Chamber", "电池仓", "電池艙"), new Entry("A staff attachment. The staff no longer regains mana over time, and when a cast is short of mana, energy cells from your pack make up the rest. Once fitted, it can't be taken off.", "法杖附件。法杖不再随时间回复法力;施法法力不够时,消耗背包里的能量电池补足。装上拆不下来。", "法杖配件。法杖不再隨時間回復法力;施法法力不夠時,消耗背包裡的能量電池補足。裝上就拆不下來。")), "ryuka.sulfur.unholy_rites:chamber_reap" => new ChamberText(new Entry("Reaping Chamber", "收割仓", "收割艙"), new Entry("A staff attachment. The staff no longer regains mana over time; an enemy killed directly by your spell gives back half its maximum health as mana, up to half the staff's maximum mana. Once fitted, it can't be taken off.", "法杖附件。法杖不再随时间回复法力;被你的法术直接打死的敌人,按其生命值上限的一半返还法力,每次最多返还法力上限的一半。装上拆不下来。", "法杖配件。法杖不再隨時間回復法力;被你的法術直接打死的敵人,按其 HP 上限的一半返還法力,每次最多返還法力上限的一半。裝上就拆不下來。")), "ryuka.sulfur.unholy_rites:chamber_breech" => new ChamberText(new Entry("Breech Chamber", "装填仓", "裝填艙"), new Entry("A staff attachment. The staff no longer regains mana over time; ammo your guns take from your pack when they reload is turned into mana by its price. Once fitted, it can't be taken off.", "法杖附件。法杖不再随时间回复法力;你的枪装填时从背包取用的子弹,按价格转化为法力。装上拆不下来。", "法杖配件。法杖不再隨時間回復法力;你的槍裝填時從背包取用的彈藥,按價格轉化為法力。裝上就拆不下來。")), _ => new ChamberText(new Entry("Still Chamber", "静息仓", "靜息艙"), new Entry("A staff attachment. The staff regains nothing while you cast, chant or hold a beam, but leave it alone for a moment and it refills quickly. Once fitted, it can't be taken off.", "法杖附件。施法、咏唱或开着光束时法杖不回法力;停手片刻后快速回复。装上拆不下来。", "法杖配件。施法、詠唱或開著光束時法杖不回法力;停手片刻後快速回復。裝上就拆不下來。")), }; } internal static StaffText StaffTextFor(string itemKey) { return itemKey switch { "ryuka.sulfur.unholy_rites:longstaff" => new StaffText(LongStaffName, LongStaffDescription, LongStaffFlavor), "ryuka.sulfur.unholy_rites:gravekeeper" => new StaffText(GravekeeperName, GravekeeperDescription, GravekeeperFlavor), "ryuka.sulfur.unholy_rites:twinstaff" => new StaffText(TwinStaffName, TwinStaffDescription, TwinStaffFlavor), _ => new StaffText(StaffName, StaffDescription, StaffFlavor), }; } internal static Entry ScrollName(Entry spell) { return new Entry("Scroll of " + spell.English, spell.Chinese + "卷轴", spell.Traditional + "卷軸"); } internal static Entry PageName(string spell) { Entry value; Entry entry = (SpellNames.TryGetValue(spell, out value) ? value : new Entry(spell, spell, spell)); return new Entry("Page: " + entry.English, "残页:" + entry.Chinese, "殘頁:" + entry.Traditional); } internal static Entry PageDescription(string spell) { Entry value; Entry entry = (SpellNames.TryGetValue(spell, out value) ? value : new Entry(spell, spell, spell)); return new Entry("Read it to learn which two scrolls the Scholar combines into " + entry.English + ".", "读后学会在学者处组合出" + entry.Chinese + "的配方。", "讀過後就學會在學者那裡組合出" + entry.Traditional + "的配方。"); } } } namespace UnholyRites.Hud { internal sealed class ManaVessel { private const float RedrawThreshold = 0.00390625f; private static readonly Color32 Empty = new Color32((byte)0, (byte)0, (byte)0, (byte)0); private readonly ManaVesselShape _shape; private readonly Texture2D _texture; private readonly Color32[] _pixels; private float _drawnFill = -1f; private float _drawnPhase; internal Sprite Sprite { get; } internal Color Liquid { get; set; } = new Color(0.35f, 0.62f, 1f, 1f); internal Color Vessel { get; set; } = new Color(0.16f, 0.22f, 0.34f, 0.55f); internal Color Surface { get; set; } = new Color(0.85f, 0.95f, 1f, 1f); internal ManaVessel(int width, int height, DrainOrder order) { //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_003f: 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_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: 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_0086: 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_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Expected O, but got Unknown //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) _shape = ManaVesselShape.Build(width, height, order); _texture = new Texture2D(width, height, (TextureFormat)4, false) { filterMode = (FilterMode)1, wrapMode = (TextureWrapMode)1, hideFlags = (HideFlags)61 }; _pixels = (Color32[])(object)new Color32[width * height]; Sprite = Sprite.Create(_texture, new Rect(0f, 0f, (float)width, (float)height), new Vector2(0.5f, 0.5f)); ((Object)Sprite).hideFlags = (HideFlags)61; } internal void Redraw(float fill, float time, bool force = false) { //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_0144: 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) fill = Mathf.Clamp01(fill); float num = time * 1.6f; if (!force && Mathf.Abs(fill - _drawnFill) < 0.00390625f && Mathf.Abs(num - _drawnPhase) < 0.08f) { return; } _drawnFill = fill; _drawnPhase = num; int width = _shape.Width; int height = _shape.Height; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { int num2 = i * width + j; float num3 = _shape.Coverage[num2]; if (num3 <= 0f) { _pixels[num2] = Empty; continue; } float num4 = Mathf.Sin(num + (float)j * 0.35f) * 0.006f; float num5 = fill + num4; float num6 = _shape.Order[num2]; float num7 = 0.02f; float num8 = Mathf.Clamp01((num5 - num6) / num7); Color val = Color.Lerp(Vessel, Liquid, num8); float num9 = num8 * (1f - num8) * 4f; val = Color.Lerp(val, Surface, num9 * 0.8f); val.a *= num3; _pixels[num2] = Color32.op_Implicit(val); } } _texture.SetPixels32(_pixels); _texture.Apply(false); } } public enum DrainOrder { Level, Spiral } internal sealed class ManaVesselShape { internal int Width { get; } internal int Height { get; } internal float[] Coverage { get; } internal float[] Order { get; } private ManaVesselShape(int width, int height) { Width = width; Height = height; Coverage = new float[width * height]; Order = new float[width * height]; } internal static ManaVesselShape Build(int width, int height, DrainOrder order) { ManaVesselShape manaVesselShape = new ManaVesselShape(width, height); float num = 0.0001f; for (int i = 0; i < height; i++) { float v = ((float)i + 0.5f) / (float)height; for (int j = 0; j < width; j++) { float u = ((float)j + 0.5f) / (float)width; int num2 = i * width + j; float num3 = Capsule(u, v, width, height); manaVesselShape.Coverage[num2] = num3; if (!(num3 <= 0f)) { float num4 = ((order == DrainOrder.Spiral) ? SpiralOrder(u, v) : LevelOrder(v)); manaVesselShape.Order[num2] = num4; if (num4 > num) { num = num4; } } } } for (int k = 0; k < manaVesselShape.Order.Length; k++) { manaVesselShape.Order[k] /= num; } return manaVesselShape; } private static float Capsule(float u, float v, int width, int height) { float num = Mathf.Abs(u - 0.5f); float num2 = (float)height / (float)width; float num3 = 0.34f / num2; float num4 = 0f; if (v < num3) { num4 = (num3 - v) * num2; } else if (v > 1f - num3) { num4 = (v - (1f - num3)) * num2; } float num5 = Mathf.Sqrt(num * num + num4 * num4); float num6 = 1f / (float)width; return Mathf.Clamp01((0.34f - num5) / num6); } private static float LevelOrder(float v) { return v; } private static float SpiralOrder(float u, float v) { float num = u - 0.5f; float num2 = v - 0.5f; float num3 = Mathf.Clamp01(Mathf.Sqrt(num * num + num2 * num2) / 0.5f); float num4 = (Mathf.Atan2(num2, num) + (float)Math.PI) / ((float)Math.PI * 2f); return num3 * 3f + num4; } } internal static class StaffManaHud { private static FieldInfo _activeCounterField; private static bool _resolved; private static bool _loggedMissing; private static PlayerHUD _hud; private static float _missingSince; private static bool _loggedPlacement; private static AmmoCounter _claimed; private static Image _image; private static ManaVessel _vessel; private static DrainOrder _builtWith; internal static void Tick(ManaPool mana, float now, string segment = null) { try { if (!HeldStaff.Equipped || mana == null) { Release(); return; } AmmoCounter val = ActiveCounter(); if ((Object)(object)val == (Object)null) { ReportMissingOnce(now); Release(); return; } _missingSince = 0f; Claim(val); if ((Object)(object)val.storageText != (Object)null) { ((Behaviour)val.storageText).enabled = segment != null; if (segment != null) { ((TMP_Text)val.storageText).text = segment; } } if (_vessel != null) { _vessel.Redraw(mana.Normalized, now); } } catch (Exception arg) { Plugin.Log.LogError((object)$"Mana display failed, hiding it: {arg}"); Release(); } } private static void ReportMissingOnce(float now) { //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) if (_missingSince <= 0f) { _missingSince = now; } else if (!_loggedMissing && !(now - _missingSince < 2f)) { _loggedMissing = true; GameManager instance = StaticInstance.Instance; EquipmentManager val = ((instance != null) ? instance.EquipmentManager : null); Weapon weapon = HeldStaff.Weapon; Weapon val2 = ((val != null) ? val.lastEquippedWeapon : null); WeaponSO val3 = (((Object)(object)weapon != (Object)null) ? weapon.weaponDefinition : null); Plugin.Log.LogInfo((object)("No counter to draw mana in. held='" + (((Object)(object)weapon != (Object)null) ? ((Object)weapon).name : "null") + "', lastEquipped='" + (((Object)(object)val2 != (Object)null) ? ((Object)val2).name : "null") + "', " + $"sameObject={weapon == val2}, " + "currentSlot=" + (((Object)(object)val != (Object)null) ? ((object)val.weaponCurrentSlot/*cast due to .constrained prefix*/).ToString() : "n/a") + ", counterPrefab=" + (((Object)(object)val3 != (Object)null && (Object)(object)val3.ammoCounterPrefab != (Object)null) ? ((Object)val3.ammoCounterPrefab).name : "none") + ", hud=" + (((Object)(object)Hud() != (Object)null) ? "found" : "missing"))); } } private static void Claim(AmmoCounter counter) { //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: 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_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00df: 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_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0109: 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_0124: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_0057: 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_01c1: Unknown result type (might be due to invalid IL or missing references) //IL_01cc: Unknown result type (might be due to invalid IL or missing references) //IL_01d1: Unknown result type (might be due to invalid IL or missing references) //IL_01e0: Unknown result type (might be due to invalid IL or missing references) //IL_01e5: Unknown result type (might be due to invalid IL or missing references) DrainOrder drainOrder = Order(); if (_claimed == counter && _vessel != null && _builtWith == drainOrder) { return; } Release(); _claimed = counter; _builtWith = drainOrder; HideRounds(counter); Transform transform = ((Component)counter).transform; RectTransform val = (RectTransform)(object)((transform is RectTransform) ? transform : null); if (!((Object)(object)val == (Object)null)) { if (!RoundsFootprint(counter, val, out var footprint)) { footprint = val.rect; } int width = Mathf.Clamp(Mathf.RoundToInt(((Rect)(ref footprint)).width), 24, 160); int height = Mathf.Clamp(Mathf.RoundToInt(((Rect)(ref footprint)).height), 24, 256); _vessel = new ManaVessel(width, height, drainOrder); GameObject val2 = new GameObject("UnholyRites_ManaVessel", new Type[1] { typeof(RectTransform) }); RectTransform val3 = (RectTransform)val2.transform; ((Transform)val3).SetParent((Transform)(object)val, false); val3.anchorMin = new Vector2(0.5f, 0.5f); val3.anchorMax = new Vector2(0.5f, 0.5f); val3.pivot = new Vector2(0.5f, 0.5f); val3.sizeDelta = new Vector2(((Rect)(ref footprint)).width, ((Rect)(ref footprint)).height); Vector2 center = ((Rect)(ref footprint)).center; Rect rect = val.rect; val3.anchoredPosition = center - ((Rect)(ref rect)).center; _image = val2.AddComponent(); _image.sprite = _vessel.Sprite; ((Graphic)_image).raycastTarget = false; _vessel.Redraw(0f, 0f, force: true); if (!_loggedPlacement) { _loggedPlacement = true; ManualLogSource log = Plugin.Log; string text = $"Mana vessel placed on '{((Object)counter).name}': {((Rect)(ref footprint)).width:0}x{((Rect)(ref footprint)).height:0} "; object arg = ((Rect)(ref footprint)).center; rect = val.rect; object arg2 = ((Rect)(ref rect)).width; rect = val.rect; log.LogInfo((object)(text + $"at {arg}, counter rect {arg2:0}x{((Rect)(ref rect)).height:0}.")); } } } private static bool RoundsFootprint(AmmoCounter counter, RectTransform host, out Rect footprint) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008f: 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) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) footprint = default(Rect); if (counter.bullets == null || counter.bullets.Length == 0) { return false; } float num = float.MaxValue; float num2 = float.MaxValue; float num3 = float.MinValue; float num4 = float.MinValue; Vector3[] array = (Vector3[])(object)new Vector3[4]; bool flag = false; for (int i = 0; i < counter.bullets.Length; i++) { Image val = counter.bullets[i]; if ((Object)(object)val == (Object)null) { continue; } Transform transform = ((Component)val).transform; RectTransform val2 = (RectTransform)(object)((transform is RectTransform) ? transform : null); if (!((Object)(object)val2 == (Object)null)) { val2.GetWorldCorners(array); for (int j = 0; j < 4; j++) { Vector3 val3 = ((Transform)host).InverseTransformPoint(array[j]); num = Mathf.Min(num, val3.x); num2 = Mathf.Min(num2, val3.y); num3 = Mathf.Max(num3, val3.x); num4 = Mathf.Max(num4, val3.y); } flag = true; } } if (!flag || num3 <= num || num4 <= num2) { return false; } footprint = Rect.MinMaxRect(num, num2, num3, num4); return true; } private static void HideRounds(AmmoCounter counter) { if (counter.bullets != null) { for (int i = 0; i < counter.bullets.Length; i++) { if ((Object)(object)counter.bullets[i] != (Object)null) { ((Behaviour)counter.bullets[i]).enabled = false; } } } if ((Object)(object)counter.ammoTypeIcon != (Object)null) { ((Behaviour)counter.ammoTypeIcon).enabled = false; } if ((Object)(object)counter.storageText != (Object)null) { ((Behaviour)counter.storageText).enabled = false; } } internal static void Release() { if ((Object)(object)_claimed != (Object)null) { if (_claimed.bullets != null) { for (int i = 0; i < _claimed.bullets.Length; i++) { if ((Object)(object)_claimed.bullets[i] != (Object)null) { ((Behaviour)_claimed.bullets[i]).enabled = true; } } } if ((Object)(object)_claimed.ammoTypeIcon != (Object)null) { ((Behaviour)_claimed.ammoTypeIcon).enabled = true; } if ((Object)(object)_claimed.storageText != (Object)null) { ((Behaviour)_claimed.storageText).enabled = true; } } if ((Object)(object)_image != (Object)null) { Object.Destroy((Object)(object)((Component)_image).gameObject); } _image = null; _vessel = null; _claimed = null; } private static PlayerHUD Hud() { if ((Object)(object)_hud != (Object)null) { return _hud; } _hud = Object.FindAnyObjectByType(); return _hud; } private static DrainOrder Order() { if (!((Plugin.ManaDrainOrder?.Value ?? "level").Trim().ToLowerInvariant() == "spiral")) { return DrainOrder.Level; } return DrainOrder.Spiral; } private static AmmoCounter ActiveCounter() { PlayerHUD val = Hud(); if ((Object)(object)val == (Object)null) { return null; } if (!_resolved) { _resolved = true; _activeCounterField = AccessTools.Field(typeof(PlayerHUD), "_lastActiveAmmoCounter"); if (_activeCounterField == null) { Plugin.Log.LogWarning((object)"The HUD's active ammo counter is not where it was; mana will not be shown."); } } GameManager instance = StaticInstance.Instance; EquipmentManager val2 = ((instance != null) ? instance.EquipmentManager : null); if ((Object)(object)val2 == (Object)null || HeldStaff.Weapon != val2.lastEquippedWeapon) { return null; } object? obj = _activeCounterField?.GetValue(val); AmmoCounter val3 = (AmmoCounter)((obj is AmmoCounter) ? obj : null); if (!((Object)(object)val3 != (Object)null) || !((Component)val3).gameObject.activeInHierarchy) { return null; } return val3; } } } namespace UnholyRites.Dev { internal static class DevFont { private static Font _typeface; private static bool _resolved; internal static Font Typeface() { if (_resolved) { return _typeface; } _resolved = true; string[] array = new string[6] { "Microsoft YaHei UI", "Microsoft YaHei", "SimHei", "SimSun", "Noto Sans CJK SC", "Arial Unicode MS" }; for (int i = 0; i < array.Length; i++) { try { Font val = Font.CreateDynamicFontFromOSFont(array[i], 14); if ((Object)(object)val != (Object)null) { _typeface = val; Plugin.Log.LogInfo((object)("Development panels are using the '" + array[i] + "' font.")); return _typeface; } } catch (Exception) { } } Plugin.Log.LogWarning((object)"No CJK font was found, so the development panels' labels will not render. Everything still works; only the text is missing."); return null; } } internal static class DevTools { private static bool _lastEnabled; private static bool _reported; private static readonly SoundBrowserPanel Sounds = new SoundBrowserPanel(); private static readonly SpellBenchPanel Spells = new SpellBenchPanel(); internal static bool Enabled { get { if (Plugin.DeveloperMode == null || !Plugin.DeveloperMode.Value) { return false; } try { return SulfurSaveState.active?.CHEATS_ENABLED ?? false; } catch (Exception) { return false; } } } internal static bool CapturingInput { get { if (Enabled) { if (!Sounds.Visible) { return Spells.Visible; } return true; } return false; } } internal static void Tick() { bool enabled = Enabled; if (enabled != _lastEnabled) { _lastEnabled = enabled; Announce(enabled); if (!enabled) { Sounds.Close(); Spells.Close(); } } if (!enabled) { return; } Keyboard current = Keyboard.current; if (current != null && !Spells.Typing) { if (((ButtonControl)current.hKey).wasPressedThisFrame) { Plugin.Session?.CyclePreset(); } if (((ButtonControl)current.jKey).wasPressedThisFrame) { VoxelLooks.Cycle(); } if (((ButtonControl)current.kKey).wasPressedThisFrame) { SoundCatalog.Next(); } if (((ButtonControl)current.lKey).wasPressedThisFrame) { Sounds.Toggle(); } if (((ButtonControl)current.pKey).wasPressedThisFrame) { Spells.Toggle(); } } } internal static void Draw() { if (Enabled) { Sounds.Draw(); Spells.Draw(); } } internal static bool DebugCastHeld() { if (!Enabled) { return false; } Keyboard current = Keyboard.current; if (current != null) { return ((ButtonControl)current.gKey).isPressed; } return false; } private static void Announce(bool enabled) { if (enabled) { _reported = true; Plugin.Log.LogInfo((object)"Developer tools armed: H cycles test programs, J cycles the voxel look, K steps the sound catalogue, L opens the sound workbench, P opens the spell workbench, G casts without a staff."); } else if (_reported) { bool flag = Plugin.DeveloperMode != null && Plugin.DeveloperMode.Value; Plugin.Log.LogInfo((object)(flag ? "Developer tools are disarmed: this save was not started with cheats enabled." : "Developer tools are disarmed: DeveloperMode is off in the configuration.")); } } } internal static class PlayerDocsExport { private sealed class Lang { internal readonly string Folder; internal readonly string Code; internal readonly bool Chinese; internal Lang(string folder, string code, bool chinese) { Folder = folder; Code = code; Chinese = chinese; } internal string T(SpellTerms.Entry entry) { return Clean(Chinese ? entry.Chinese : entry.English); } internal string T(string english, string chinese) { if (!Chinese) { return english; } return chinese; } } private static readonly Lang[] Langs = new Lang[2] { new Lang("en", "en", chinese: false), new Lang("zh-CN", "zh-CN", chinese: true) }; private static readonly Regex Tags = new Regex("<[^>]+>"); internal static void OnRequested() { string text = ((Plugin.ExportPlayerDocs != null) ? Plugin.ExportPlayerDocs.Value : null); if (string.IsNullOrWhiteSpace(text)) { return; } Plugin.ExportPlayerDocs.Value = string.Empty; if (Plugin.DeveloperMode == null || !Plugin.DeveloperMode.Value) { Plugin.Log.LogWarning((object)"Player pages were not exported: DeveloperMode is off."); return; } try { int num = 0; Lang[] langs = Langs; foreach (Lang lang in langs) { string text2 = Path.Combine(text.Trim(), lang.Folder); Directory.CreateDirectory(text2); Write(text2, "spells.md", Spells(lang)); Write(text2, "staves-and-gear.md", StavesAndGear(lang)); Write(text2, "obtaining.md", Obtaining(lang)); Write(text2, "examples.md", Examples(lang)); num += 4; } Plugin.Log.LogInfo((object)$"Player pages exported: {num} pages to '{text.Trim()}'."); } catch (Exception arg) { Plugin.Log.LogError((object)$"Player pages were not exported: {arg}"); } } private static void Write(string dir, string name, string text) { File.WriteAllText(Path.Combine(dir, name), text.Replace("\r\n", "\n"), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); } private static string Spells(Lang l) { StringBuilder stringBuilder = Header(l, "Spells", "法术"); stringBuilder.Append(l.T("Every spell scroll the mod adds. A staff casts its spells in the order they were inscribed; see [How order works](order.md). Mana and chant are for the spell on its own, or after a Fireball for a modifier.", "本 mod 加入的全部法术卷轴。法杖按刻写的顺序施放法术,见[顺序规则](order.md)。法力和咏唱时间是这个法术单独刻写时的数值;修饰法术按刻在火球后面计算。")).Append("\n\n"); Section(stringBuilder, l, SpellCategory.Projectile, l.T("Base spells", "基础法术")); Section(stringBuilder, l, SpellCategory.Transform, l.T("Modifiers", "修饰法术")); Section(stringBuilder, l, SpellCategory.Payload, l.T("Triggers and Next", "触发法术与下一发")); return stringBuilder.ToString(); } private static void Section(StringBuilder sb, Lang l, SpellCategory category, string title) { sb.Append("## ").Append(title).Append("\n\n"); sb.Append(l.T("| Spell | Mana | Chant | How to get | What it does |", "| 法术 | 法力 | 咏唱 | 获取 | 作用 |")).Append('\n'); sb.Append("|---|---|---|---|---|\n"); foreach (string item in Inscribable()) { SpellDefinition spellDefinition = ContentBootstrap.Catalog.Get(item); bool flag = spellDefinition.Category == SpellCategory.Payload || spellDefinition.Category == SpellCategory.Segment; if ((category == SpellCategory.Payload) ? flag : (spellDefinition.Category == category)) { string text = l.T(NameOf(item)); if (spellDefinition.Category == SpellCategory.Projectile && SpellTerms.Elements.TryGetValue(spellDefinition.Projectile.Element.ToString(), out var value)) { text = text + "
" + l.T(value.Name); } string value2 = "—"; string value3 = "—"; CastPlan castPlan = null; if (spellDefinition.Category == SpellCategory.Projectile) { castPlan = Compile(item); } else if (spellDefinition.Category == SpellCategory.Transform) { castPlan = Compile("fireball", item); } if (castPlan != null && castPlan.EmissionCount > 0) { value2 = Number(castPlan.TotalCost) + (castPlan.IsBeam ? l.T("/s", "/秒") : string.Empty); value3 = ((castPlan.CastTime > 0.05f) ? (Number(castPlan.CastTime) + l.T(" s", " 秒")) : "—"); } SpellTerms.Entry value4; string text2 = (SpellTerms.SpellDescriptions.TryGetValue(item, out value4) ? l.T(value4) : l.T(SpellTerms.ScrollDescriptionAttack)); sb.Append("| ").Append(Cell(text)).Append(" | ") .Append(value2) .Append(" | ") .Append(value3) .Append(" | ") .Append(Cell(HowToGet(l, item))) .Append(" | ") .Append(Cell(text2)) .Append(" |\n"); } } sb.Append('\n'); } private static IEnumerable Inscribable() { for (int i = 0; i < SpellOrder.Count; i++) { SpellKey key = SpellOrder.KeyAt(i); if (key.Value != null && ScrollTiers.TierOf(key.Value) > 0 && ContentBootstrap.Catalog.TryGet(key, out var definition) && definition != null) { yield return key.Value; } } } private static string HowToGet(Lang l, string key) { //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) if (ScrollTiers.TierOf(key) == 1) { return l.T("Tier 1: found in levels, sold by ", "一阶:关卡中拾取,") + l.T(Game("UnitNames/FexShuen", "Fex Shuen")) + l.T("", "有售"); } for (int i = 0; i < ScrollTiers.SecondTier.Length; i++) { ScrollTiers.Recipe recipe = ScrollTiers.SecondTier[i]; if (!(recipe.Result != key)) { string text = l.T("Tier 2: the Scholar combines ", "二阶:学者用") + l.T(SpellTerms.ScrollName(NameOf(recipe.From))) + l.T(" and ", "和") + ((recipe.OtherSpell != null) ? l.T(SpellTerms.ScrollName(NameOf(recipe.OtherSpell))) : l.T(VanillaItem(recipe.OtherVanilla))) + l.T("", "组合"); RecipePages.Page? page = PageFor(key); return text + (page.HasValue ? (l.T("; learn it from a page found in ", ";配方要从") + l.T(RegionName(page.Value.Region)) + l.T(", or by trying the combination", "的残页学会,或自己试出这个组合")) : l.T("; known from the start", ";配方开局就会")); } } return "—"; } private static string StavesAndGear(Lang l) { StringBuilder stringBuilder = Header(l, "Staves and gear", "法杖与装备"); stringBuilder.Append("## ").Append(l.T("Staves", "法杖")).Append("\n\n"); stringBuilder.Append(l.T("| Staff | Spells | Mana | Cooldown | Chanting slows you to | Sold by | Description |", "| 法杖 | 法术数 | 法力 | 冷却 | 咏唱时移速 | 出售 | 说明 |")).Append('\n'); stringBuilder.Append("|---|---|---|---|---|---|---|\n"); StaffDefinition[] all = StaffDefinitions.All; foreach (StaffDefinition staffDefinition in all) { SpellTerms.StaffText staffText = SpellTerms.StaffTextFor(staffDefinition.ItemKey); string text = ((staffDefinition.ItemKey == "ryuka.sulfur.unholy_rites:staff") ? (l.T(Game("UnitNames/FexShuen", "Fex Shuen")) + l.T(", always", ",常备")) : (l.T(Game("UnitNames/BlondMagus", "Blond Magus")) + l.T(", always, once you have drawn a staff", ",拿过法杖后常备"))); stringBuilder.Append("| ").Append(Cell(l.T(staffText.Name))).Append(" | ") .Append(staffDefinition.Slots) .Append(" | ") .Append(Number(staffDefinition.ManaCapacity)) .Append(" | ") .Append(Number(staffDefinition.Cooldown)) .Append(l.T(" s", " 秒")) .Append(" | ") .Append(Percent(staffDefinition.ChantMoveFactor)) .Append(" | ") .Append(Cell(text)) .Append(" | ") .Append(Cell(l.T(staffText.Description))) .Append(" |\n"); } string text2 = l.T(Game("UnitNames/BlondMagus", "Blond Magus")); string text3 = l.T(Game("UnitNames/FexShuen", "Fex Shuen")); stringBuilder.Append("\n## ").Append(l.T("Mana chambers", "法力仓")).Append("\n\n"); Table(stringBuilder, l, ManaChambers.Keys, SpellTerms.ChamberTextFor, text2 + l.T(" and ", "、") + text3 + l.T(", now and then", ",随机出现")); stringBuilder.Append("\n## ").Append(l.T("Oaths", "誓约")).Append("\n\n"); Table(stringBuilder, l, Oaths.Keys, SpellTerms.OathTextFor, text2 + l.T(", now and then", ",随机出现")); stringBuilder.Append("\n## ").Append(l.T("Other gear", "其他装备")).Append("\n\n"); stringBuilder.Append(l.T("| Item | What it does | Where |", "| 物品 | 作用 | 来源 |")).Append('\n'); stringBuilder.Append("|---|---|---|\n"); Row(stringBuilder, l, SpellTerms.StakeText(), text2 + l.T(" and ", "、") + text3 + l.T(", now and then", ",随机出现")); Row(stringBuilder, l, SpellTerms.BeadsText(), text2 + l.T(", now and then", ",随机出现")); Row(stringBuilder, l, SpellTerms.RobeText(), text2 + l.T(", now and then", ",随机出现")); string text4 = l.T(Game("Items/Item_Solution", "Solution")); for (int j = 0; j < SealedVials.All.Length; j++) { SealedVials.Kind kind = SealedVials.All[j]; Row(stringBuilder, l, SpellTerms.VialText(kind.Spell), l.T("Cooking station: ", "烹饪台:") + l.T(SpellTerms.ScrollName(NameOf(kind.Spell))) + l.T(" and ", " + ") + text4 + l.T(" make two", ",做出两个")); } return stringBuilder.ToString(); } private static void Table(StringBuilder sb, Lang l, string[] keys, Func text, string where) { sb.Append(l.T("| Item | What it does | Where |", "| 物品 | 作用 | 来源 |")).Append('\n'); sb.Append("|---|---|---|\n"); for (int i = 0; i < keys.Length; i++) { Row(sb, l, text(keys[i]), where); } } private static void Row(StringBuilder sb, Lang l, SpellTerms.ChamberText text, string where) { sb.Append("| ").Append(Cell(l.T(text.Name))).Append(" | ") .Append(Cell(l.T(text.Description))) .Append(" | ") .Append(Cell(where)) .Append(" |\n"); } private static string Obtaining(Lang l) { //IL_03b1: Unknown result type (might be due to invalid IL or missing references) //IL_041c: Unknown result type (might be due to invalid IL or missing references) StringBuilder stringBuilder = Header(l, "Getting spells and gear", "获取与合成"); string text = l.T(Game("UnitNames/FexShuen", "Fex Shuen")); string value = l.T(Game("UnitNames/BlondMagus", "Blond Magus")); string text2 = l.T(Game("UnitNames/CongregationScholar", "Scholar")); stringBuilder.Append("## ").Append(l.T("The first staff", "第一根法杖")).Append("\n\n"); stringBuilder.Append(l.T(text + " always has one. The mod's scrolls and gear drop and are sold only once you have drawn a staff in this save; the enemies listed below leave their scrolls either way.", text + "常备一根。在这个存档里拿起过一次法杖之后,本 mod 的卷轴和装备才会开始掉落和出售;下面列出的敌人留下卷轴不受这个限制。")).Append("\n\n"); stringBuilder.Append("## ").Append(l.T("First-tier scrolls", "一阶卷轴")).Append("\n\n"); List list = new List(); string[] firstTier = ScrollTiers.FirstTier; foreach (string key in firstTier) { list.Add(l.T(SpellTerms.ScrollName(NameOf(key)))); } stringBuilder.Append(l.T("Found in levels where the game's own scrolls are, and sold by " + text + ": ", "在关卡里会和原版卷轴一起掉落," + text + "也有售:")).Append(string.Join(l.T(", ", "、"), list)).Append(l.T(".", "。")) .Append("\n\n"); stringBuilder.Append(l.T("Some enemies leave a scroll of their own:", "有些敌人会留下自己的卷轴:")).Append("\n\n"); stringBuilder.Append("- ").Append(l.T(Game("UnitNames/BlackGuildLucia", "Saint Lucia"))).Append(l.T(" always leaves ", "必定留下")) .Append(l.T(SpellTerms.ScrollName(NameOf("raise")))) .Append(l.T(".", "。")) .Append('\n'); string[] array = new string[4] { "Fire", "Frost", "Poison", "Electricity" }; string[] array2 = new string[4] { "fireball", "frostbolt", "venom", "lightning" }; for (int j = 0; j < array.Length; j++) { stringBuilder.Append("- ").Append(l.T(Game("UnitNames/GoblinWizard" + array[j], "Wizard of " + array[j]))).Append(l.T(" leaves ", "有五分之一的机会留下")) .Append(l.T(SpellTerms.ScrollName(NameOf(array2[j])))) .Append(l.T(" one time in five.", "。")) .Append('\n'); } stringBuilder.Append("\n## ").Append(l.T("Second-tier scrolls: the Scholar", "二阶卷轴:学者")).Append("\n\n"); stringBuilder.Append(l.T("Combine two scrolls at the " + text2 + "'s station. A recipe is \"known\" when the station lists it; eight are learned from a page instead, and combining the two scrolls still works without the page.", "在" + text2 + "的工作台组合两张卷轴。“开局就会”的配方会直接出现在列表里;有八张要读残页才学会,不读残页直接组合也能做出来。")).Append("\n\n"); stringBuilder.Append(l.T("| Result | Combine | Recipe |", "| 结果 | 组合 | 配方 |")).Append('\n'); stringBuilder.Append("|---|---|---|\n"); ScrollTiers.Recipe[] secondTier = ScrollTiers.SecondTier; for (int i = 0; i < secondTier.Length; i++) { ScrollTiers.Recipe recipe = secondTier[i]; string text3 = ((recipe.OtherSpell != null) ? l.T(SpellTerms.ScrollName(NameOf(recipe.OtherSpell))) : l.T(VanillaItem(recipe.OtherVanilla))); RecipePages.Page? page = PageFor(recipe.Result); string text4 = (page.HasValue ? (l.T("Page found in ", "残页,出现在") + l.T(RegionName(page.Value.Region))) : l.T("Known from the start", "开局就会")); stringBuilder.Append("| ").Append(Cell(l.T(SpellTerms.ScrollName(NameOf(recipe.Result))))).Append(" | ") .Append(Cell(l.T(SpellTerms.ScrollName(NameOf(recipe.From))) + " + " + text3)) .Append(" | ") .Append(Cell(text4)) .Append(" |\n"); } stringBuilder.Append("\n## ").Append(l.T("Vendors", "商人")).Append("\n\n"); stringBuilder.Append("- ").Append(text).Append(l.T(": the first staff (always), first-tier scrolls, and now and then a mana chamber or the sigil stake. He stands in rooms every region shares.", ":第一根法杖(常备)、一阶卷轴,偶尔有法力仓或法阵钉。他出现在各区域共用的房间里。")) .Append('\n'); stringBuilder.Append("- ").Append(value).Append(l.T(": the other three staves (always, once you have drawn a staff), and now and then mana chambers, oaths, the sigil stake, the penitent robe and the martyr's beads. He is rare: a castle room in act one, desert rooms in act three.", ":另外三根法杖(拿过法杖后常备),偶尔有法力仓、誓约、法阵钉、苦修衣和殉道念珠。他很少见:第一幕在城堡的一个房间,第三幕在沙漠。")) .Append("\n"); return stringBuilder.ToString(); } private static RecipePages.Page? PageFor(string spell) { RecipePages.Page[] all = RecipePages.All; for (int i = 0; i < all.Length; i++) { RecipePages.Page value = all[i]; if (value.Spell == spell) { return value; } } return null; } private unsafe static SpellTerms.Entry RegionName(LootTableKind region) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected I4, but got Unknown string text; switch (region - 5) { case 4: text = "Act_01_Sewers"; break; case 1: text = "Act_01_Dungeon"; break; case 3: text = "Act_01_Caves"; break; case 2: text = "Act_01_Castle"; break; case 0: text = "Act_01_Shanty"; break; case 6: text = "Act_02_Forest"; break; case 7: text = "Act_02_Fortress"; break; case 5: text = "Act_03_Desert"; break; default: return new SpellTerms.Entry(((object)(*(LootTableKind*)(®ion))/*cast due to .constrained prefix*/).ToString(), ((object)(*(LootTableKind*)(®ion))/*cast due to .constrained prefix*/).ToString(), ((object)(*(LootTableKind*)(®ion))/*cast due to .constrained prefix*/).ToString()); } return Game("Environments/" + text, text); } private static string Examples(Lang l) { StringBuilder stringBuilder = Header(l, "Example staves", "示例"); stringBuilder.Append(l.T("Programs worth trying, with what they do. Mana and chant are what the staff pays for one cast.", "值得一试的写法和它们的效果。法力和咏唱时间是一次施法的花费。")).Append("\n\n"); stringBuilder.Append(l.T("| Spells, in order | Mana | Chant | What happens |", "| 法术(按顺序) | 法力 | 咏唱 | 效果 |")).Append('\n'); stringBuilder.Append("|---|---|---|---|\n"); SpellPresets.Preset[] all = SpellPresets.All; for (int i = 0; i < all.Length; i++) { SpellPresets.Preset preset = all[i]; string[] array = preset.Program.Split(new char[2] { '>', ',' }, StringSplitOptions.RemoveEmptyEntries); List list = new List(); bool flag = true; for (int j = 0; j < array.Length; j++) { string text = array[j].Trim(); if (ScrollTiers.TierOf(text) == 0) { flag = false; break; } list.Add(l.T(NameOf(text))); } if (flag) { CastPlan castPlan = Compile(Array.ConvertAll(array, (string k) => k.Trim())); string value = ((castPlan.EmissionCount > 0) ? (Number(castPlan.TotalCost) + (castPlan.IsBeam ? l.T("/s", "/秒") : string.Empty)) : "—"); string value2 = ((castPlan.CastTime > 0.05f) ? (Number(castPlan.CastTime) + l.T(" s", " 秒")) : "—"); stringBuilder.Append("| ").Append(Cell(string.Join(" > ", list))).Append(" | ") .Append(value) .Append(" | ") .Append(value2) .Append(" | ") .Append(Cell(Sentence(l.T(preset.English, preset.Chinese)))) .Append(" |\n"); } } return stringBuilder.ToString(); } private static StringBuilder Header(Lang l, string english, string chinese) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("\n\n"); stringBuilder.Append("# ").Append(l.T(english, chinese)).Append("\n\n"); return stringBuilder; } private static SpellTerms.Entry NameOf(string key) { if (!SpellTerms.SpellNames.TryGetValue(key, out var value)) { return new SpellTerms.Entry(key, key, key); } return value; } private static CastPlan Compile(params string[] keys) { List list = new List(keys.Length); foreach (string key in keys) { list.Add(ContentBootstrap.Catalog.Get(key)); } return SpellCompiler.Compile(list, ContentBootstrap.Catalog); } private unsafe static SpellTerms.Entry VanillaItem(ItemId id) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) AsyncAssetLoading instance = StaticInstance.Instance; ItemDefinition val = (((Object)(object)instance != (Object)null && (Object)(object)instance.itemDatabase != (Object)null) ? instance.itemDatabase[id] : null); if (!((Object)(object)val != (Object)null)) { return new SpellTerms.Entry(((object)(*(ItemId*)(&id))/*cast due to .constrained prefix*/).ToString(), ((object)(*(ItemId*)(&id))/*cast due to .constrained prefix*/).ToString(), ((object)(*(ItemId*)(&id))/*cast due to .constrained prefix*/).ToString()); } return Game("Items/" + ((Object)val).name, val.displayName); } private static SpellTerms.Entry Game(string term, string fallback) { string text = Lookup(term, "en") ?? fallback; string text2 = Lookup(term, "zh-CN") ?? text; return new SpellTerms.Entry(text, text2, Lookup(term, "zh-TW") ?? text2); } private static string Lookup(string term, string code) { foreach (LanguageSourceData source in LocalizationManager.Sources) { TermData val = ((source != null) ? source.GetTermData(term, false) : null); if (val != null) { int languageIndexFromCode = source.GetLanguageIndexFromCode(code, true, false); string text = ((languageIndexFromCode >= 0) ? val.GetTranslation(languageIndexFromCode, (string)null, false) : null); if (!string.IsNullOrEmpty(text)) { return text.Trim(); } } } return null; } private static string Clean(string text) { if (string.IsNullOrEmpty(text)) { return string.Empty; } return Tags.Replace(text.Replace("
", " "), string.Empty).Trim(); } private static string Sentence(string text) { if (!string.IsNullOrEmpty(text)) { return char.ToUpperInvariant(text[0]) + text.Substring(1); } return string.Empty; } private static string Cell(string text) { return (text ?? string.Empty).Replace("|", "\\|").Replace("\n", " "); } private static string Number(float value) { return value.ToString("0.#", CultureInfo.InvariantCulture); } private static string Percent(float factor) { return Number(factor * 100f) + "%"; } } internal sealed class SoundBrowserPanel { private const int WindowId = 1431193649; private static readonly string[] GroupNames = new string[4] { "音色", "音量与空间", "包络", "其他" }; private Rect _window = new Rect(24f, 24f, 500f, 560f); private Vector2 _scroll; private SoundTweaks _tweaks = new SoundTweaks(); private int _tweakedIndex = int.MinValue; private readonly bool[] _expanded = new bool[4] { true, true, false, false }; private readonly List _shortlist = new List(); private bool _sustain; private float _nextRetrigger; private CursorLockMode _lockBefore; private bool _visibleBefore; internal bool Visible { get; private set; } internal void Toggle() { //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) if (Visible) { Close(); } else if (SoundCatalog.Ready()) { Visible = true; _lockBefore = Cursor.lockState; _visibleBefore = Cursor.visible; Cursor.lockState = (CursorLockMode)0; Cursor.visible = true; } } internal void Close() { //IL_001d: Unknown result type (might be due to invalid IL or missing references) if (Visible) { Visible = false; _sustain = false; SoundCatalog.StopAllPlayed(); Cursor.lockState = _lockBefore; Cursor.visible = _visibleBefore; } } internal void Draw() { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown //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) if (Visible) { Sustain(); Font font = GUI.skin.font; Font val = DevFont.Typeface(); if ((Object)(object)val != (Object)null) { GUI.skin.font = val; } _window = GUILayout.Window(1431193649, _window, new WindowFunction(DrawWindow), "Unholy Rites — 音效工作台", Array.Empty()); GUI.skin.font = font; } } private void Sustain() { if (_sustain && !(Time.unscaledTime < _nextRetrigger)) { int cursor = SoundCatalog.Cursor; SoundCatalog.TryDescribe(cursor, out var _, out var _, out var length, out var loops); SoundCatalog.PlayAt(cursor, _tweaks.Build()); _nextRetrigger = (loops ? float.MaxValue : (Time.unscaledTime + Mathf.Max(length, 0.15f))); } } private void DrawWindow(int id) { //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008d: 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_005f: Unknown result type (might be due to invalid IL or missing references) int cursor = SoundCatalog.Cursor; if (cursor != _tweakedIndex) { _tweakedIndex = cursor; _tweaks = new SoundTweaks(); _nextRetrigger = 0f; } if (!SoundCatalog.TryDescribe(cursor, out var path, out var asset, out var length, out var loops)) { GUILayout.Label("目录还没建好。进到关卡里再打开。", Array.Empty()); GUI.DragWindow(new Rect(0f, 0f, 10000f, 20f)); return; } DrawHeader(cursor, path, asset, length, loops); DrawTransport(); _scroll = GUILayout.BeginScrollView(_scroll, Array.Empty()); DrawKnobs(); GUILayout.EndScrollView(); DrawClipboard(cursor, path, asset, length, loops); GUI.DragWindow(new Rect(0f, 0f, 10000f, 20f)); } private void DrawHeader(int index, string path, string asset, float length, bool loops) { GUILayout.Label($"#{index} / {SoundCatalog.Count - 1} {path}", Array.Empty()); GUILayout.Label(string.Format("{0} {1:0.00}s {2}", asset, length, loops ? "循环" : "单发"), Array.Empty()); } private void DrawTransport() { //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Expected O, but got Unknown //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Expected O, but got Unknown //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Expected O, but got Unknown GUILayout.BeginHorizontal(Array.Empty()); if (GUILayout.Button("◀ 上一个", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) })) { SoundCatalog.Move(-1); } if (GUILayout.Button("▶ 播放", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) })) { SoundCatalog.PlayAt(SoundCatalog.Cursor, _tweaks.Build()); } if (GUILayout.Button(new GUIContent("■ 停止", "停掉这个工作台播过的所有声音,不只是当前这个。"), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _sustain = false; SoundCatalog.StopAllPlayed(); } if (GUILayout.Button("下一个 ▶", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) })) { SoundCatalog.Move(1); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); bool flag = GUILayout.Toggle(_sustain, new GUIContent(" 持续播放", "循环音会一直响;单发音会按自己的长度反复触发 —— Sonity 没有循环参数,循环是烧在资源里的。"), Array.Empty()); if (flag != _sustain) { _sustain = flag; _nextRetrigger = 0f; if (!flag) { SoundCatalog.StopAllPlayed(); } } if (GUILayout.Button(new GUIContent("静音全场", "停掉游戏里当前所有声音,用来在安静的环境下判断一个音效。自带循环的东西会自己再响起来。"), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) })) { SoundCatalog.SilenceGame(); } GUILayout.FlexibleSpace(); bool enabled = GUI.enabled; GUI.enabled = _tweaks.AnyChanged(); if (GUILayout.Button("重置全部", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) }) && _tweaks.AnyChanged()) { _tweaks.ResetAll(); } GUI.enabled = enabled; GUILayout.EndHorizontal(); } private void DrawKnobs() { for (int i = 0; i < GroupNames.Length; i++) { int num = CountChanged((KnobGroup)i); GUILayout.BeginHorizontal(Array.Empty()); _expanded[i] = GUILayout.Toggle(_expanded[i], " " + (_expanded[i] ? "▼" : "▶") + " " + GroupNames[i], GUI.skin.label, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); GUILayout.Label((num > 0) ? $"已改 {num}" : string.Empty, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) }); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); if (!_expanded[i]) { continue; } for (int j = 0; j < SoundTweaks.Knobs.Length; j++) { if (SoundTweaks.Knobs[j].Group == (KnobGroup)i) { DrawKnob(j); } } GUILayout.Space(6f); } } private void DrawKnob(int knob) { //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown SoundTweaks.Knob knob2 = SoundTweaks.Knobs[knob]; bool flag = _tweaks.IsChanged(knob); GUILayout.BeginHorizontal(Array.Empty()); GUILayout.Label(new GUIContent((flag ? "● " : " ") + knob2.Label, knob2.Help), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }); if (knob2.Kind == KnobKind.Bool) { bool flag2 = GUILayout.Toggle(_tweaks[knob] > 0.5f, string.Empty, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(200f) }); _tweaks[knob] = (flag2 ? 1f : 0f); } else { float num = GUILayout.HorizontalSlider(_tweaks[knob], knob2.Min, knob2.Max, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(200f) }); _tweaks[knob] = ((knob2.Kind == KnobKind.Int) ? Mathf.Round(num) : num); } GUILayout.Label(_tweaks.Format(knob), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) }); bool enabled = GUI.enabled; GUI.enabled = flag; if (GUILayout.Button("↺", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(26f) }) && flag) { _tweaks.Reset(knob); } GUI.enabled = enabled; GUILayout.EndHorizontal(); } private int CountChanged(KnobGroup group) { int num = 0; for (int i = 0; i < SoundTweaks.Knobs.Length; i++) { if (SoundTweaks.Knobs[i].Group == group && _tweaks.IsChanged(i)) { num++; } } return num; } private void DrawClipboard(int index, string path, string asset, float length, bool loops) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown GUILayout.Space(4f); GUILayout.BeginHorizontal(Array.Empty()); if (GUILayout.Button(new GUIContent("复制原版", "把这个音效未经改动的信息放到剪贴板。"), Array.Empty())) { Copy(Line(index, path, asset, length, loops, withTweaks: false)); } if (GUILayout.Button(new GUIContent("复制含调整", "把这个音效的信息连同你改过的每一项放到剪贴板。"), Array.Empty())) { Copy(Line(index, path, asset, length, loops, withTweaks: true)); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); if (GUILayout.Button($"加入清单 ({_shortlist.Count})", Array.Empty())) { _shortlist.Add(Line(index, path, asset, length, loops, withTweaks: true)); } if (GUILayout.Button("复制清单", Array.Empty())) { Copy(string.Join("\n", _shortlist.ToArray())); } if (GUILayout.Button("清空", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) })) { _shortlist.Clear(); } GUILayout.EndHorizontal(); } private string Line(int index, string path, string asset, float length, bool loops, bool withTweaks) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('#').Append(index).Append(" ") .Append(path) .Append(" ") .Append(asset) .Append(" ") .Append(length.ToString("0.00")) .Append('s') .Append(" ") .Append(loops ? "loop" : "one-shot"); if (!withTweaks) { return stringBuilder.ToString(); } string text = _tweaks.Describe(); if (text.Length > 0) { stringBuilder.Append(" | ").Append(text); } if (_sustain) { stringBuilder.Append(" | 持续"); } return stringBuilder.ToString(); } private static void Copy(string text) { try { GUIUtility.systemCopyBuffer = text ?? string.Empty; Plugin.Log.LogInfo((object)("Copied to clipboard:\n" + text)); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Could not reach the clipboard: " + ex.Message)); } } } internal enum KnobGroup { Timbre, Level, Envelope, Other } internal enum KnobKind { Float, Bool, Int } internal sealed class SoundTweaks { internal readonly struct Knob { internal string Label { get; } internal string Unit { get; } internal KnobKind Kind { get; } internal KnobGroup Group { get; } internal float Min { get; } internal float Max { get; } internal float Default { get; } internal string Help { get; } internal Knob(string label, string unit, KnobKind kind, KnobGroup group, float min, float max, float fallback, string help) { Label = label; Unit = unit; Kind = kind; Group = group; Min = min; Max = max; Default = fallback; Help = help; } } internal static readonly Knob[] Knobs = new Knob[20] { new Knob("音高", "st", KnobKind.Float, KnobGroup.Timbre, -24f, 24f, 0f, "半音。往下调是让一个声音变「重」的主要手段 —— 陨石和飞镖可以是同一段录音。"), new Knob("倒放", "", KnobKind.Bool, KnobGroup.Timbre, 0f, 1f, 0f, "倒过来播。撞击音倒放通常就是很好的「蓄力」声,咏唱值得试。"), new Knob("失真", "", KnobKind.Float, KnobGroup.Timbre, 0f, 1f, 0f, "加脏。少量失真能让干净的音效变得像被诅咒过。"), new Knob("起始位置", "", KnobKind.Float, KnobGroup.Timbre, 0f, 1f, 0f, "从中间开始播,用来跳过慢起音头,让声音更「顶」。"), new Knob("音量", "dB", KnobKind.Float, KnobGroup.Level, -40f, 20f, 0f, "分贝。单独调它最弱 —— 小声音放大声还是小声音。"), new Knob("传播距离", "x", KnobKind.Float, KnobGroup.Level, 0.1f, 8f, 1f, "可听半径的倍数。这个是混音伪造不出来的:决定隔一个房间听不听得见。"), new Knob("2D 化", "", KnobKind.Float, KnobGroup.Level, 0f, 1f, 0f, "越高越不受方位影响、越贴在耳边。自己施法的声音适合偏高。"), new Knob("强制 2D", "", KnobKind.Bool, KnobGroup.Level, 0f, 1f, 0f, "完全不定位。"), new Knob("声像", "", KnobKind.Float, KnobGroup.Level, -1f, 1f, 0f, "左右。对定位音基本没用,列出来是为了完整。"), new Knob("混响量", "dB", KnobKind.Float, KnobGroup.Level, -40f, 20f, 0f, "送进场景混响的量。调高会让声音听起来发生在更大的空间里。"), new Knob("延迟", "s", KnobKind.Float, KnobGroup.Envelope, 0f, 5f, 0f, "推迟多久才响。"), new Knob("淡入", "s", KnobKind.Float, KnobGroup.Envelope, 0f, 10f, 0f, "持续音要不突兀地起来,靠这个。"), new Knob("淡入曲线", "", KnobKind.Float, KnobGroup.Envelope, -1f, 1f, 0f, "淡入是先快后慢还是反过来。"), new Knob("淡出", "s", KnobKind.Float, KnobGroup.Envelope, 0f, 10f, 0f, "法阵熄灭时该收多久。"), new Knob("淡出曲线", "", KnobKind.Float, KnobGroup.Envelope, -1f, 1f, 0f, "淡出是先快后慢还是反过来。"), new Knob("强度", "", KnobKind.Float, KnobGroup.Other, 0f, 1f, 1f, "Sonity 自己的强度输入。只有在该音效作者写了强度曲线时才有效果。"), new Knob("复音上限", "", KnobKind.Int, KnobGroup.Other, 0f, 32f, 0f, "同时最多几个。0 = 用音效自带的设置。齐射会不会糊成一团由它决定。"), new Knob("跳过混响区", "", KnobKind.Bool, KnobGroup.Other, 0f, 1f, 0f, "无视场景混响。"), new Knob("跳过监听器效果", "", KnobKind.Bool, KnobGroup.Other, 0f, 1f, 0f, ""), new Knob("跳过语音效果", "", KnobKind.Bool, KnobGroup.Other, 0f, 1f, 0f, "") }; private const int Pitch = 0; private const int Reverse = 1; private const int Distortion = 2; private const int StartPosition = 3; private const int Volume = 4; private const int Distance = 5; private const int Increase2D = 6; private const int Force2D = 7; private const int Pan = 8; private const int ReverbMix = 9; private const int Delay = 10; private const int FadeIn = 11; private const int FadeInShape = 12; private const int FadeOut = 13; private const int FadeOutShape = 14; private const int Intensity = 15; private const int Polyphony = 16; private const int BypassReverb = 17; private const int BypassListener = 18; private const int BypassVoice = 19; private readonly float[] _values = new float[Knobs.Length]; internal float this[int knob] { get { return _values[knob]; } set { _values[knob] = value; } } internal SoundTweaks() { ResetAll(); } internal bool IsChanged(int knob) { return Math.Abs(_values[knob] - Knobs[knob].Default) > 0.0001f; } internal bool AnyChanged() { for (int i = 0; i < _values.Length; i++) { if (IsChanged(i)) { return true; } } return false; } internal void Reset(int knob) { _values[knob] = Knobs[knob].Default; } internal void ResetAll() { for (int i = 0; i < _values.Length; i++) { _values[i] = Knobs[i].Default; } } internal SoundParameterInternals[] Build() { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Expected O, but got Unknown //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Expected O, but got Unknown //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: 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_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Expected O, but got Unknown //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Expected O, but got Unknown //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Expected O, but got Unknown //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Expected O, but got Unknown //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Expected O, but got Unknown //IL_0166: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Expected O, but got Unknown //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_018e: Expected O, but got Unknown //IL_01a3: Unknown result type (might be due to invalid IL or missing references) //IL_01ad: Expected O, but got Unknown //IL_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01cc: Expected O, but got Unknown //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Expected O, but got Unknown //IL_0200: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Expected O, but got Unknown //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Expected O, but got Unknown //IL_0274: Unknown result type (might be due to invalid IL or missing references) //IL_027e: Expected O, but got Unknown //IL_024e: Unknown result type (might be due to invalid IL or missing references) //IL_0258: Expected O, but got Unknown //IL_029a: Unknown result type (might be due to invalid IL or missing references) //IL_02a4: Expected O, but got Unknown //IL_02c0: Unknown result type (might be due to invalid IL or missing references) //IL_02ca: Expected O, but got Unknown if (!AnyChanged()) { return null; } List list = new List(); if (IsChanged(0)) { list.Add((SoundParameterInternals)new SoundParameterPitchSemitone(_values[0], (UpdateMode)1)); } bool flag = IsChanged(1) && _values[1] > 0.5f; if (IsChanged(1)) { list.Add((SoundParameterInternals)new SoundParameterReverse(_values[1] > 0.5f, (UpdateMode)1)); } if (IsChanged(2)) { list.Add((SoundParameterInternals)new SoundParameterDistortionIncrease(_values[2], (UpdateMode)1)); } if (IsChanged(3)) { list.Add((SoundParameterInternals)new SoundParameterStartPosition(_values[3])); } else if (flag) { list.Add((SoundParameterInternals)new SoundParameterStartPosition(1f)); } if (IsChanged(4)) { list.Add((SoundParameterInternals)new SoundParameterVolumeDecibel(_values[4], (UpdateMode)1)); } if (IsChanged(5)) { list.Add((SoundParameterInternals)new SoundParameterDistanceScale(_values[5])); } if (IsChanged(6)) { list.Add((SoundParameterInternals)new SoundParameterIncrease2D(_values[6], (UpdateMode)1)); } if (IsChanged(7)) { list.Add((SoundParameterInternals)new SoundParameterForce2D(_values[7] > 0.5f)); } if (IsChanged(8)) { list.Add((SoundParameterInternals)new SoundParameterStereoPan(_values[8], (UpdateMode)1)); } if (IsChanged(9)) { list.Add((SoundParameterInternals)new SoundParameterReverbZoneMixDecibel(_values[9], (UpdateMode)1)); } if (IsChanged(10)) { list.Add((SoundParameterInternals)new SoundParameterDelay(_values[10])); } if (IsChanged(11)) { list.Add((SoundParameterInternals)new SoundParameterFadeInLength(_values[11], (UpdateMode)1)); } if (IsChanged(12)) { list.Add((SoundParameterInternals)new SoundParameterFadeInShape(_values[12], (UpdateMode)1)); } if (IsChanged(13)) { list.Add((SoundParameterInternals)new SoundParameterFadeOutLength(_values[13], (UpdateMode)1)); } if (IsChanged(14)) { list.Add((SoundParameterInternals)new SoundParameterFadeOutShape(_values[14], (UpdateMode)1)); } if (IsChanged(15)) { list.Add((SoundParameterInternals)new SoundParameterIntensity(_values[15], (UpdateMode)1)); } if (IsChanged(16) && _values[16] >= 1f) { list.Add((SoundParameterInternals)new SoundParameterPolyphony((int)_values[16])); } if (IsChanged(17)) { list.Add((SoundParameterInternals)new SoundParameterBypassReverbZones(_values[17] > 0.5f, (UpdateMode)1)); } if (IsChanged(18)) { list.Add((SoundParameterInternals)new SoundParameterBypassListenerEffects(_values[18] > 0.5f, (UpdateMode)1)); } if (IsChanged(19)) { list.Add((SoundParameterInternals)new SoundParameterBypassVoiceEffects(_values[19] > 0.5f, (UpdateMode)1)); } return list.ToArray(); } internal string Format(int knob) { Knob knob2 = Knobs[knob]; float num = _values[knob]; switch (knob2.Kind) { case KnobKind.Bool: if (!(num > 0.5f)) { return "关"; } return "开"; case KnobKind.Int: return ((int)num).ToString(CultureInfo.InvariantCulture); default: { string text = num.ToString("0.##", CultureInfo.InvariantCulture); if (knob2.Unit == "dB" || knob2.Unit == "st") { return ((num > 0f) ? "+" : string.Empty) + text + knob2.Unit; } return text + knob2.Unit; } } } internal string Describe() { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < Knobs.Length; i++) { if (IsChanged(i)) { if (stringBuilder.Length > 0) { stringBuilder.Append(" "); } stringBuilder.Append(Knobs[i].Label).Append(' ').Append(Format(i)); } } return stringBuilder.ToString(); } } internal sealed class SpellBenchPanel { private const int WindowId = 1431193650; private Rect _window = new Rect(560f, 24f, 520f, 600f); private Vector2 _listScroll; private Vector2 _summaryScroll; private string _typed = string.Empty; private CursorLockMode _lockBefore; private bool _visibleBefore; private const string FieldName = "unholyrites.program"; private bool _fieldFocused; private static string _available; internal bool Visible { get; private set; } internal bool Typing { get { if (Visible) { return _fieldFocused; } return false; } } internal void Toggle() { //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) if (Visible) { Close(); return; } Visible = true; SpellSession session = Plugin.Session; if (session != null && _typed.Length == 0) { _typed = session.CurrentProgram; } _lockBefore = Cursor.lockState; _visibleBefore = Cursor.visible; Cursor.lockState = (CursorLockMode)0; Cursor.visible = true; } internal void Close() { //IL_001e: Unknown result type (might be due to invalid IL or missing references) if (Visible) { Visible = false; _fieldFocused = false; GUI.FocusControl((string)null); Cursor.lockState = _lockBefore; Cursor.visible = _visibleBefore; } } internal void Draw() { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Expected O, but got Unknown //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) if (Visible) { Font font = GUI.skin.font; Font val = DevFont.Typeface(); if ((Object)(object)val != (Object)null) { GUI.skin.font = val; } _window = GUILayout.Window(1431193650, _window, new WindowFunction(DrawWindow), "Unholy Rites — 法术工作台", Array.Empty()); GUI.skin.font = font; } } private void DrawWindow(int id) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) SpellSession session = Plugin.Session; if (session == null) { GUILayout.Label("会话还没建立。进到关卡里再打开。", Array.Empty()); GUI.DragWindow(new Rect(0f, 0f, 10000f, 20f)); return; } DrawProgramField(session); DrawList(session); DrawSummary(session); if (GUILayout.Button("关闭", Array.Empty())) { Close(); } GUI.DragWindow(new Rect(0f, 0f, 10000f, 20f)); } private void DrawProgramField(SpellSession session) { GUILayout.Label("自己写一个(用 > 或 , 分隔)", Array.Empty()); GUILayout.BeginHorizontal(Array.Empty()); GUI.SetNextControlName("unholyrites.program"); _typed = GUILayout.TextField(_typed ?? string.Empty, Array.Empty()); _fieldFocused = GUI.GetNameOfFocusedControl() == "unholyrites.program"; if (GUILayout.Button("编译", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) })) { session.SetProgram(_typed); } GUILayout.EndHorizontal(); GUILayout.Label("可用:" + Available(), Array.Empty()); GUILayout.Space(6f); } private static string Available() { if (_available != null) { return _available; } StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < SpellOrder.Count; i++) { SpellKey spellKey = SpellOrder.KeyAt(i); if (spellKey.IsValid) { if (stringBuilder.Length > 0) { stringBuilder.Append(", "); } stringBuilder.Append(spellKey.Value); } } _available = stringBuilder.ToString(); return _available; } private void DrawList(SpellSession session) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) GUILayout.Label($"预设({SpellPresets.All.Length} 个)", Array.Empty()); _listScroll = GUILayout.BeginScrollView(_listScroll, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(260f) }); int presetIndex = session.PresetIndex; for (int i = 0; i < SpellPresets.All.Length; i++) { SpellPresets.Preset preset = SpellPresets.All[i]; bool flag = i == presetIndex; GUILayout.BeginHorizontal(Array.Empty()); GUILayout.Label(flag ? "▶" : " ", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(16f) }); if (GUILayout.Button($"{i + 1}. {preset.Program}", Array.Empty())) { session.SelectPreset(i); _typed = preset.Program; } GUILayout.EndHorizontal(); if (flag) { GUILayout.Label(" " + SpellPresets.Describe(i), Array.Empty()); } } GUILayout.EndScrollView(); GUILayout.Space(6f); } private void DrawSummary(SpellSession session) { //IL_0093: 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) CastPlan plan = session.Plan; ManaPool mana = session.Mana; if (plan == null) { GUILayout.Label("还没有编译出任何东西。", Array.Empty()); return; } GUILayout.Label($"耗魔 {plan.TotalCost:0.#} 咏唱 {plan.CastTime:0.##}s " + $"投射物 {plan.EmissionCount} 法力 {mana.Current:0}/{mana.Capacity:0}", Array.Empty()); if (HeldStaff.Equipped) { GUILayout.Label("手里有法杖 —— 法杖说了算,收起来才能用上面的按钮。", Array.Empty()); } _summaryScroll = GUILayout.BeginScrollView(_summaryScroll, Array.Empty()); GUILayout.Label(plan.Summary ?? string.Empty, Array.Empty()); GUILayout.EndScrollView(); } } } namespace UnholyRites.Content { internal static class Acquisition { internal const string StaffDrawnCheckpoint = "ryuka.sulfur.unholy_rites:staff_drawn"; internal const string StarterSpellCheckpoint = "ryuka.sulfur.unholy_rites:starter_spell"; internal const string StarterSpell = "fireball"; internal const int FirstTierScrollLootWeight = 19; internal const string FexShuen = "FexShuen"; internal const string BlondMagus = "BlondMagus"; internal const int FexScrollWeight = 40; internal const int MagusGearWeight = 1; internal const int FexGearWeight = 10; internal const float GoblinMageScrollChance = 0.2f; internal static void Register() { int num = 0; for (int i = 0; i < ScrollTiers.FirstTier.Length; i++) { if (ContentLoot.AddToLoot(SpellContent.ScrollKey(ScrollTiers.FirstTier[i]), (LootTableKind)0, 19, (Func)HasDrawnStaff)) { num++; } } int num2 = RecipePages.Register(HasDrawnStaff); int num3 = 0; num3 += (ContentLoot.AddToShop("ryuka.sulfur.unholy_rites:staff", "FexShuen", 0, true, (Func)null) ? 1 : 0); for (int j = 0; j < ScrollTiers.FirstTier.Length; j++) { num3 += (ContentLoot.AddToShop(SpellContent.ScrollKey(ScrollTiers.FirstTier[j]), "FexShuen", 40, false, (Func)HasDrawnStaff) ? 1 : 0); } num3 += (ContentLoot.AddToShop("ryuka.sulfur.unholy_rites:longstaff", "BlondMagus", 0, true, (Func)HasDrawnStaff) ? 1 : 0); num3 += (ContentLoot.AddToShop("ryuka.sulfur.unholy_rites:gravekeeper", "BlondMagus", 0, true, (Func)HasDrawnStaff) ? 1 : 0); num3 += (ContentLoot.AddToShop("ryuka.sulfur.unholy_rites:twinstaff", "BlondMagus", 0, true, (Func)HasDrawnStaff) ? 1 : 0); num3 += AddGear(ManaChambers.Keys); num3 += AddGear(Oaths.Keys); num3 += AddGear(new string[3] { "ryuka.sulfur.unholy_rites:sigil_stake", "ryuka.sulfur.unholy_rites:penitent_robe", "ryuka.sulfur.unholy_rites:martyr_beads" }); for (int k = 0; k < ManaChambers.Keys.Length; k++) { num3 += (ContentLoot.AddToShop(ManaChambers.Keys[k], "FexShuen", 10, false, (Func)HasDrawnStaff) ? 1 : 0); } num3 += (ContentLoot.AddToShop("ryuka.sulfur.unholy_rites:sigil_stake", "FexShuen", 10, false, (Func)HasDrawnStaff) ? 1 : 0); Plugin.Log.LogInfo((object)$"Acquisition: {num} first-tier scrolls drop once a staff has been drawn; {num2} region pages; {num3} vendor entries."); } private static int AddGear(string[] keys) { int num = 0; for (int i = 0; i < keys.Length; i++) { num += (ContentLoot.AddToShop(keys[i], "BlondMagus", 1, false, (Func)HasDrawnStaff) ? 1 : 0); } return num; } internal static void OnUnitPaidOut(Unit unit) { //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_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_003f: Unknown result type (might be due to invalid IL or missing references) //IL_008e: 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_00b5: 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_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) try { UnitSO val = (((Object)(object)unit != (Object)null) ? unit.unitSO : null); if ((Object)(object)val == (Object)null) { return; } UnitId id = val.id; string text = null; if (id == UnitIds.BlackGuildLucia) { text = "raise"; } else { text = GoblinMageScroll(id); if (text != null && Random.value >= 0.2f) { text = null; } } if (text != null && SpellContent.TryGetItem(SpellContent.ScrollKey(text), out var definition)) { LootManager instance = StaticInstance.Instance; if (!((Object)(object)instance == (Object)null)) { instance.SpawnLootFrom(new List { new LootEntry { lootItem = definition, lootWeight = 1f } }, ((Component)unit).transform.position + Vector3.up * 0.1f, false, unit.currentRoom); Plugin.Log.LogInfo((object)(((Object)val).name + " left a " + text + " scroll.")); } } } catch (Exception ex) { Plugin.Log.LogError((object)("A unit's signature scroll was not dropped: " + ex.Message)); } } private static string GoblinMageScroll(UnitId id) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0026: 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_0039: 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) if (id == UnitIds.GoblinWizardFire) { return "fireball"; } if (id == UnitIds.GoblinWizardFrost) { return "frostbolt"; } if (id == UnitIds.GoblinWizardPoison) { return "venom"; } if (id == UnitIds.GoblinWizardElectricity) { return "lightning"; } return null; } internal static bool HasDrawnStaff() { if (SulfurSaveState.active != null) { return PlayerProgress.GetCheckpointReached("ryuka.sulfur.unholy_rites:staff_drawn"); } return false; } internal static void OfferStarterSpell(InventoryItem staff) { try { if (!((Object)(object)staff == (Object)null) && staff.enchantments != null && staff.enchantments.Count <= 0 && SulfurSaveState.active != null && !PlayerProgress.GetCheckpointReached("ryuka.sulfur.unholy_rites:starter_spell") && SpellContent.TryGetItem(SpellContent.ScrollKey("fireball"), out var definition)) { staff.AddEnchantment(definition, false); PlayerProgress.SetCheckpointReached("ryuka.sulfur.unholy_rites:starter_spell", true); StaffProgram.Invalidate(); Plugin.Log.LogInfo((object)"First staff in this save: a fireball was inscribed on it."); } } catch (Exception ex) { Plugin.Log.LogError((object)("The starter spell was not inscribed: " + ex.Message)); } } internal static void OnStaffDrawn() { try { if (SulfurSaveState.active != null && !PlayerProgress.GetCheckpointReached("ryuka.sulfur.unholy_rites:staff_drawn")) { PlayerProgress.SetCheckpointReached("ryuka.sulfur.unholy_rites:staff_drawn", true); Plugin.Log.LogInfo((object)"First staff drawn in this save: spell scrolls now drop."); } } catch (Exception ex) { Plugin.Log.LogError((object)("Could not record the first staff drawn: " + ex.Message)); } } } public static class ContentBootstrap { private static bool _reported; public static SpellCatalog Catalog { get; } = SpellCatalog.CreateSample(); public static void OnContentSealed() { if (!_reported) { _reported = true; SpellContent.ReportBuilt(); RecipePages.Bind(); } } } internal static class FirstTimeHints { internal const string StaffKey = "UnholyRites_Staff"; internal const string OrderKey = "UnholyRites_Order"; internal const string TermPrefix = "TutorialHints/"; private static bool _inventoryOpen; internal static void OnInventoryState(UIState state) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 _inventoryOpen = (int)state == 1; if (_inventoryOpen && CarriesStaff()) { ShowOnce("UnholyRites_Staff"); } } internal static void OnInscribed(InventoryItem item, ItemDefinition scroll) { if (_inventoryOpen && (Object)(object)item != (Object)null && SpellContent.IsStaff(item.itemDefinition) && (Object)(object)scroll != (Object)null && SpellContent.ItemKeyOf(scroll) != null) { ShowOnce("UnholyRites_Order"); } } private static bool CarriesStaff() { GameManager instance = StaticInstance.Instance; if ((Object)(object)instance == (Object)null || (Object)(object)instance.EquipmentManager == (Object)null || instance.EquipmentManager.EquippedItems == null) { return false; } foreach (InventoryItem value in instance.EquipmentManager.EquippedItems.Values) { if ((Object)(object)value != (Object)null && SpellContent.IsStaff(value.itemDefinition)) { return true; } } return false; } private static void ShowOnce(string key) { SulfurSaveState active = SulfurSaveState.active; UIManager instance = StaticInstance.Instance; if (active != null && !((Object)(object)instance == (Object)null) && active.INFORMATION_DIALOGS_SHOWN != null && !active.INFORMATION_DIALOGS_SHOWN.Contains(key)) { instance.ShowInformationDialog(key); } } } [HarmonyPatch(typeof(InventoryUI), "SetState")] internal static class FirstTimeHintsInventoryPatch { private static void Postfix(UIState state) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) try { FirstTimeHints.OnInventoryState(state); } catch (Exception ex) { Plugin.Log.LogError((object)("A first-time note was not shown: " + ex.Message)); } } } [HarmonyPatch(typeof(InventoryItem), "AddEnchantment")] internal static class FirstTimeHintsInscribePatch { private static void Postfix(InventoryItem __instance, ItemDefinition enchantmentItem) { try { FirstTimeHints.OnInscribed(__instance, enchantmentItem); } catch (Exception ex) { Plugin.Log.LogError((object)("A first-time note was not shown: " + ex.Message)); } } } internal static class RecipePages { internal readonly struct Page { internal readonly string Spell; internal readonly LootTableKind Region; internal readonly int Weight; internal string ItemKey => "ryuka.sulfur.unholy_rites:page_" + Spell; internal Page(string spell, LootTableKind region, int weight = 1) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) Spell = spell; Region = region; Weight = weight; } } internal static readonly Page[] All = new Page[8] { new Page("raise", (LootTableKind)6, 2), new Page("blood", (LootTableKind)10), new Page("hex", (LootTableKind)9, 2), new Page("brand", (LootTableKind)7), new Page("sanctuary", (LootTableKind)5), new Page("stone", (LootTableKind)8), new Page("gather", (LootTableKind)11), new Page("radiance", (LootTableKind)12, 2) }; private static readonly HashSet Bound = new HashSet(StringComparer.Ordinal); private static readonly HashSet ReportedLearned = new HashSet(StringComparer.Ordinal); internal static bool IsBound(string itemKey) { return Bound.Contains(itemKey); } internal static bool Teaches(string spell) { for (int i = 0; i < All.Length; i++) { if (All[i].Spell == spell) { return true; } } return false; } internal static bool IsPage(string itemKey) { for (int i = 0; i < All.Length; i++) { if (All[i].ItemKey == itemKey) { return true; } } return false; } internal static void Bind() { //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) int num = 0; ItemDefinition val = default(ItemDefinition); RecipeData val2 = default(RecipeData); for (int i = 0; i < All.Length; i++) { Page page = All[i]; if (ContentManifest.TryGetItem(page.ItemKey, ref val)) { if (!ContentManifest.TryGetRecipe(ScrollTiers.RecipeKey(page.Spell), ref val2)) { val.includedInEarlyAccess = false; Plugin.Log.LogWarning((object)("The page for '" + page.Spell + "' teaches nothing: its recipe was not built. It will not drop.")); continue; } val.recipesTaughtOnConsume = new List { val2.id }; Bound.Add(page.ItemKey); num++; } } Plugin.Log.LogInfo((object)$"Region pages: {num} of {All.Length} teach their recipe."); } internal static int Register(Func gate) { //IL_0058: Unknown result type (might be due to invalid IL or missing references) int num = 0; for (int i = 0; i < All.Length; i++) { Page page = All[i]; string recipeKey = ScrollTiers.RecipeKey(page.Spell); if (ContentLoot.AddToLoot(page.ItemKey, page.Region, page.Weight, (Func)(() => gate() && IsBound(page.ItemKey) && !Learned(recipeKey)))) { num++; } } return num; } private static bool Learned(string recipeKey) { RecipeData val = default(RecipeData); int num; if (ContentManifest.TryGetRecipe(recipeKey, ref val)) { num = (((RecipeData)(ref val)).IsLearned ? 1 : 0); if (num != 0 && ReportedLearned.Add(recipeKey)) { Plugin.Log.LogInfo((object)("Region pages: '" + recipeKey + "' is already learned; its page stays out of draws.")); } } else { num = 0; } return (byte)num != 0; } } internal static class ScrollTiers { internal readonly struct Recipe { internal readonly string Result; internal readonly string From; internal readonly string OtherSpell; internal readonly ItemId OtherVanilla; private Recipe(string result, string from, string otherSpell, ItemId otherVanilla) { //IL_0016: 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) Result = result; From = from; OtherSpell = otherSpell; OtherVanilla = otherVanilla; } internal static Recipe WithElement(string result, string from, ItemId element) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) return new Recipe(result, from, null, element); } internal static Recipe WithSpell(string result, string from, string other) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) return new Recipe(result, from, other, ItemId.None); } } internal const int FirstTierPrice = 1000; internal const int SecondTierPrice = 2500; internal static readonly string[] FirstTier = new string[6] { "fireball", "frostbolt", "venom", "sigil", "empower", "onhit" }; internal static readonly Recipe[] SecondTier = new Recipe[22] { Recipe.WithElement("lightning", "frostbolt", ItemIds.Enchantment_Electricity), Recipe.WithElement("pierce", "frostbolt", ItemIds.Enchantment_Frost), Recipe.WithElement("stone", "frostbolt", ItemIds.Enchantment_Earth), Recipe.WithElement("meteor", "fireball", ItemIds.Enchantment_Earth), Recipe.WithElement("radiance", "fireball", ItemIds.Enchantment_Light), Recipe.WithElement("raise", "sigil", ItemIds.Enchantment_Dark), Recipe.WithElement("skyfall", "sigil", ItemIds.Enchantment_Electricity), Recipe.WithElement("sanctuary", "sigil", ItemIds.Enchantment_Earth), Recipe.WithElement("brand", "venom", ItemIds.Enchantment_Light), Recipe.WithElement("hex", "venom", ItemIds.Enchantment_Dark), Recipe.WithElement("grave_goods", "raise", ItemIds.Enchantment_Earth), Recipe.WithElement("onmiss", "onhit", ItemIds.Enchantment_Dark), Recipe.WithElement("pulse", "onhit", ItemIds.Enchantment_Water), Recipe.WithElement("next", "onhit", ItemIds.Enchantment_Nature), Recipe.WithSpell("else", "onhit", "onmiss"), Recipe.WithElement("onkill", "onhit", ItemIds.Enchantment_Fire), Recipe.WithElement("bounce", "frostbolt", ItemIds.Enchantment_Water), Recipe.WithElement("split", "empower", ItemIds.Enchantment_Light), Recipe.WithElement("concussion", "empower", ItemIds.Enchantment_Electricity), Recipe.WithElement("gather", "empower", ItemIds.Enchantment_Nature), Recipe.WithElement("blood", "empower", ItemIds.Enchantment_Dark), Recipe.WithElement("ritual", "empower", ItemIds.Enchantment_Earth) }; internal static int TierOf(string spellKey) { if (Array.IndexOf(FirstTier, spellKey) >= 0) { return 1; } for (int i = 0; i < SecondTier.Length; i++) { if (SecondTier[i].Result == spellKey) { return 2; } } return 0; } internal static string RecipeKey(string resultSpell) { return "ryuka.sulfur.unholy_rites:recipe_" + resultSpell; } } public static class SpellContent { public const string StaffKey = "ryuka.sulfur.unholy_rites:staff"; public const string LongStaffKey = "ryuka.sulfur.unholy_rites:longstaff"; public const string GravekeeperKey = "ryuka.sulfur.unholy_rites:gravekeeper"; public const string TwinStaffKey = "ryuka.sulfur.unholy_rites:twinstaff"; public const string StakeKey = "ryuka.sulfur.unholy_rites:sigil_stake"; private static readonly Dictionary SpellByEnchantmentKey = new Dictionary(StringComparer.Ordinal); private static readonly List DeclaredItemKeys = new List(); private static readonly Dictionary EnchantmentKeyByScrollKey = new Dictionary(StringComparer.Ordinal); private static bool _declared; private static List _spawnable; private static ItemDefinition _scrollBase; public static IReadOnlyList SpawnableItems { get { if (_spawnable != null) { return _spawnable; } List list = new List(DeclaredItemKeys.Count); if (!ContentManifest.IsSealed) { return list; } ItemDefinition item = default(ItemDefinition); EnchantmentDefinition val = default(EnchantmentDefinition); for (int i = 0; i < DeclaredItemKeys.Count; i++) { string text = DeclaredItemKeys[i]; if (!ContentManifest.TryGetItem(text, ref item)) { continue; } if (StaffDefinitions.FindByKey(text) == null && Array.IndexOf(ManaChambers.Keys, text) < 0 && Array.IndexOf(Oaths.Keys, text) < 0) { switch (text) { default: { if (SealedVials.Find(text) == null && (!RecipePages.IsPage(text) || !RecipePages.IsBound(text)) && (!EnchantmentKeyByScrollKey.TryGetValue(text, out var value) || !ContentManifest.TryGetEnchantment(value, ref val))) { continue; } break; } case "ryuka.sulfur.unholy_rites:sigil_stake": case "ryuka.sulfur.unholy_rites:penitent_robe": case "ryuka.sulfur.unholy_rites:martyr_beads": break; } } list.Add(item); } _spawnable = list; return list; } } public static string ScrollKey(string spellKey) { return "ryuka.sulfur.unholy_rites:scroll_" + spellKey; } public static string EnchantmentKey(string spellKey) { return "ryuka.sulfur.unholy_rites:spell_" + spellKey; } public static bool IsStaff(ItemDefinition definition) { return StaffDefinitions.Find(definition) != null; } internal static bool TryGetItem(string key, out ItemDefinition definition) { definition = null; if (ContentManifest.IsSealed && ContentManifest.TryGetItem(key, ref definition)) { return (Object)(object)definition != (Object)null; } return false; } internal static string ItemKeyOf(ItemDefinition definition) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) string result = default(string); if (!((Object)(object)definition != (Object)null) || !ContentManifest.TryGetKey(definition.id, ref result)) { return null; } return result; } public static bool TryGetSpell(EnchantmentDefinition enchantment, out SpellKey key) { key = SpellKey.None; string key2 = default(string); if ((Object)(object)enchantment != (Object)null && ContentManifest.TryGetKey(enchantment, ref key2)) { return SpellByEnchantmentKey.TryGetValue(key2, out key); } return false; } public static bool IsSpellEnchantment(EnchantmentDefinition enchantment) { SpellKey key; return TryGetSpell(enchantment, out key); } public static bool IsSpellScroll(ItemDefinition definition) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) string key = default(string); if ((Object)(object)definition != (Object)null && ContentManifest.TryGetKey(definition.id, ref key)) { return EnchantmentKeyByScrollKey.ContainsKey(key); } return false; } public static void Declare(SpellCatalog catalog) { if (_declared || catalog == null) { return; } _declared = true; for (int i = 0; i < StaffDefinitions.All.Length; i++) { StaffDefinition kind = StaffDefinitions.All[i]; if (ContentRegistry.DeclareItem(kind.ItemKey, (Func)(() => BuildStaff(kind)))) { DeclaredItemKeys.Add(kind.ItemKey); } } for (int num = 0; num < ManaChambers.Keys.Length; num++) { string chamberKey = ManaChambers.Keys[num]; if (ContentRegistry.DeclareItem(chamberKey, (Func)(() => BuildChamber(chamberKey)))) { DeclaredItemKeys.Add(chamberKey); } } if (ContentRegistry.DeclareItem("ryuka.sulfur.unholy_rites:sigil_stake", (Func)BuildStake)) { DeclaredItemKeys.Add("ryuka.sulfur.unholy_rites:sigil_stake"); } if (ContentRegistry.DeclareItem("ryuka.sulfur.unholy_rites:penitent_robe", (Func)BuildRobe)) { DeclaredItemKeys.Add("ryuka.sulfur.unholy_rites:penitent_robe"); } if (ContentRegistry.DeclareItem("ryuka.sulfur.unholy_rites:martyr_beads", (Func)BuildBeads)) { DeclaredItemKeys.Add("ryuka.sulfur.unholy_rites:martyr_beads"); } for (int num2 = 0; num2 < SealedVials.All.Length; num2++) { SealedVials.Kind vial = SealedVials.All[num2]; if (ContentRegistry.DeclareItem(vial.ItemKey, (Func)(() => BuildVial(vial)))) { DeclaredItemKeys.Add(vial.ItemKey); } } for (int num3 = 0; num3 < RecipePages.All.Length; num3++) { RecipePages.Page page = RecipePages.All[num3]; if (ContentRegistry.DeclareItem(page.ItemKey, (Func)(() => BuildPage(page)))) { DeclaredItemKeys.Add(page.ItemKey); } } for (int num4 = 0; num4 < Oaths.Keys.Length; num4++) { string oathKey = Oaths.Keys[num4]; if (ContentRegistry.DeclareItem(oathKey, (Func)(() => BuildOath(oathKey)))) { DeclaredItemKeys.Add(oathKey); } } for (int num5 = 0; num5 < SpellOrder.Count; num5++) { SpellKey spellKey = SpellOrder.KeyAt(num5); if (!spellKey.IsValid) { continue; } SpellDefinition spell = catalog.Get(spellKey.Value); if (spell == null) { Plugin.Log.LogWarning((object)$"No spell named '{spellKey}'; its scroll was not declared."); } else { if (spell.Category == SpellCategory.Flag || spell.Internal) { continue; } string text = ScrollKey(spellKey.Value); string text2 = EnchantmentKey(spellKey.Value); if (ContentRegistry.DeclareItem(text, (Func)(() => BuildScroll(spell)))) { DeclaredItemKeys.Add(text); if (ContentRegistry.DeclareEnchantment(text2, text, (Func)(() => BuildEnchantment(spell)))) { SpellByEnchantmentKey[text2] = spell.Key; EnchantmentKeyByScrollKey[text] = text2; } } } } int num6 = DeclareRecipes() + DeclareVialRecipes(); Plugin.Log.LogInfo((object)($"Spell content declared: {DeclaredItemKeys.Count} items, " + $"{SpellByEnchantmentKey.Count} enchantments, {num6} recipes.")); } private static int DeclareRecipes() { int num = 0; for (int i = 0; i < ScrollTiers.SecondTier.Length; i++) { ScrollTiers.Recipe recipe = ScrollTiers.SecondTier[i]; if (!DeclaredItemKeys.Contains(ScrollKey(recipe.Result)) || !DeclaredItemKeys.Contains(ScrollKey(recipe.From)) || (recipe.OtherSpell != null && !DeclaredItemKeys.Contains(ScrollKey(recipe.OtherSpell)))) { Plugin.Log.LogWarning((object)("The recipe for '" + recipe.Result + "' names a scroll that was not declared; it was left out.")); } else if (ContentRegistry.DeclareRecipe(ScrollTiers.RecipeKey(recipe.Result), (Func)(() => BuildRecipe(recipe)), !RecipePages.Teaches(recipe.Result))) { num++; } } return num; } private static int DeclareVialRecipes() { int num = 0; for (int i = 0; i < SealedVials.All.Length; i++) { SealedVials.Kind vial = SealedVials.All[i]; if (DeclaredItemKeys.Contains(vial.ItemKey) && DeclaredItemKeys.Contains(ScrollKey(vial.Spell)) && ContentRegistry.DeclareRecipe(vial.ItemKey + "_recipe", (Func)(() => BuildVialRecipe(vial)), true)) { num++; } } return num; } private static RecipeData BuildVialRecipe(SealedVials.Kind vial) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0019: 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_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0075: 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_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008b: 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_00a3: Unknown result type (might be due to invalid IL or missing references) ItemDefinition val = default(ItemDefinition); ContentManifest.TryGetItem(vial.ItemKey, ref val); return new RecipeData { type = (Types)1, createsItem = (((Object)(object)val != (Object)null) ? val.id : ItemId.None), quantityCreated = 2, canBeCrafted = true, itemsNeeded = new List { new IngredientDefinition { item = ScrollId(vial.Spell), quantity = 1 }, new IngredientDefinition { item = ItemIds.Item_Solution, quantity = 1 } } }; } private static RecipeData BuildRecipe(ScrollTiers.Recipe recipe) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_001b: 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_0027: 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_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008a: 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_00a2: Unknown result type (might be due to invalid IL or missing references) ItemId item = ((recipe.OtherSpell != null) ? ScrollId(recipe.OtherSpell) : recipe.OtherVanilla); return new RecipeData { type = (Types)2, createsItem = ScrollId(recipe.Result), quantityCreated = 1, canBeCrafted = true, itemsNeeded = new List { new IngredientDefinition { item = ScrollId(recipe.From), quantity = 1 }, new IngredientDefinition { item = item, quantity = 1 } } }; } private static ItemId ScrollId(string spellKey) { //IL_0018: 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) ItemDefinition val = default(ItemDefinition); if (!ContentManifest.TryGetItem(ScrollKey(spellKey), ref val) || !((Object)(object)val != (Object)null)) { return ItemId.None; } return val.id; } public static void ReportBuilt() { if (!ContentManifest.IsSealed) { Plugin.Log.LogWarning((object)"SULFUR Content Lib has not sealed yet, so what was built cannot be counted."); return; } if (ContentManifest.IsFaulted) { Plugin.Log.LogError((object)"SULFUR Content Lib reports a fault; see its own log lines. It writes no save that holds library items for the rest of this session."); } List list = new List(); int num = 0; ItemDefinition val = default(ItemDefinition); for (int i = 0; i < DeclaredItemKeys.Count; i++) { if (ContentManifest.TryGetItem(DeclaredItemKeys[i], ref val)) { num++; } else { list.Add("Item '" + DeclaredItemKeys[i] + "' was declared but not built."); } } int num2 = 0; EnchantmentDefinition val2 = default(EnchantmentDefinition); foreach (string key in SpellByEnchantmentKey.Keys) { if (ContentManifest.TryGetEnchantment(key, ref val2)) { num2++; } else { list.Add("Enchantment '" + key + "' was declared but not built."); } } if (num == 0 && num2 == 0 && ContentManifest.IsFaulted) { Plugin.Log.LogError((object)"No spell content exists this session: the staff and the scrolls are unavailable, and nothing can be inscribed or cast."); return; } for (int j = 0; j < list.Count; j++) { Plugin.Log.LogError((object)list[j]); } Plugin.Log.LogInfo((object)($"Spell content ready: {num} of {DeclaredItemKeys.Count} items, " + $"{num2} of {SpellByEnchantmentKey.Count} enchantments.")); } private static ItemDefinition BuildChamber(string key) { //IL_0000: 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_007e: Unknown result type (might be due to invalid IL or missing references) ItemDefinition asset = AssetAccess.GetAsset(ItemIds.Attachment_PrimingBolt); if ((Object)(object)asset == (Object)null) { throw new InvalidOperationException("no vanilla chamber module to base a mana chamber on"); } ItemDefinition obj = ItemTemplates.Clone(asset); StripInheritedEffects(obj); ClearInheritedLifecycleFlags(obj); SpellTerms.ChamberText chamberText = SpellTerms.ChamberTextFor(key); obj.displayName = chamberText.Name.English; obj.description = chamberText.Description.English; obj.flavor = string.Empty; obj.hasCustomDescription = true; obj.useType = (UseType)2; obj.basePrice = 800; obj.itemQuality = (ItemQuality)1; return obj; } private static ItemDefinition BuildOath(string key) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Invalid comparison between Unknown and I4 //IL_00dc: Unknown result type (might be due to invalid IL or missing references) ItemDefinition val = null; List rawList = StaticInstance.Instance.itemDatabase.GetRawList(); for (int i = 0; i < rawList.Count; i++) { if ((Object)(object)rawList[i] != (Object)null && (int)rawList[i].slotType == 10 && (Object)(object)rawList[i].artwork != (Object)null && !rawList[i].deprecated) { val = rawList[i]; break; } } if ((Object)(object)val == (Object)null) { throw new InvalidOperationException("no vanilla passive enhancement to base an oath on"); } ItemDefinition obj = ItemTemplates.Clone(val); StripInheritedEffects(obj); ClearInheritedLifecycleFlags(obj); SpellTerms.ChamberText chamberText = SpellTerms.OathTextFor(key); obj.displayName = chamberText.Name.English; obj.description = chamberText.Description.English; obj.flavor = string.Empty; obj.hasCustomDescription = true; obj.basePrice = 1500; obj.itemQuality = (ItemQuality)2; return obj; } private static ItemDefinition BuildStake() { //IL_0000: 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_009e: Unknown result type (might be due to invalid IL or missing references) ItemDefinition asset = AssetAccess.GetAsset(ItemIds.Weapon_ThrowingKnives); WeaponSO val = ItemTemplates.Clone((WeaponSO)(object)(((asset is WeaponSO) ? asset : null) ?? throw new InvalidOperationException("no vanilla throwable to base the sigil stake on"))); ClearInheritedLifecycleFlags((ItemDefinition)(object)val); ItemDefinition asset2 = AssetAccess.GetAsset(ItemIds.Item_WoodenCross); if ((Object)(object)asset2 != (Object)null && (Object)(object)asset2.artwork != (Object)null) { ((ItemDefinition)val).artwork = asset2.artwork; } SpellTerms.ChamberText chamberText = SpellTerms.StakeText(); ((ItemDefinition)val).displayName = chamberText.Name.English; ((ItemDefinition)val).description = chamberText.Description.English; ((ItemDefinition)val).flavor = string.Empty; ((ItemDefinition)val).hasCustomDescription = true; ((ItemDefinition)val).basePrice = 300; ((ItemDefinition)val).itemQuality = (ItemQuality)1; return (ItemDefinition)(object)val; } private static ItemDefinition BuildVial(SealedVials.Kind vial) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) ItemDefinition asset = AssetAccess.GetAsset(ItemIds.Weapon_MolotovCocktail); WeaponSO obj = ItemTemplates.Clone((WeaponSO)(object)(((asset is WeaponSO) ? asset : null) ?? throw new InvalidOperationException("no vanilla bottle to base a sealed vial on"))); ClearInheritedLifecycleFlags((ItemDefinition)(object)obj); SpellTerms.ChamberText chamberText = SpellTerms.VialText(vial.Spell); ((ItemDefinition)obj).displayName = chamberText.Name.English; ((ItemDefinition)obj).description = chamberText.Description.English; ((ItemDefinition)obj).flavor = string.Empty; ((ItemDefinition)obj).hasCustomDescription = true; ((ItemDefinition)obj).includedInEarlyAccess = true; ((ItemDefinition)obj).basePrice = 500; ((ItemDefinition)obj).itemQuality = (ItemQuality)2; return (ItemDefinition)(object)obj; } private static ItemDefinition BuildRobe() { //IL_0000: 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) ItemDefinition asset = AssetAccess.GetAsset(ItemIds.Item_SafetyVest); if ((Object)(object)asset == (Object)null) { throw new InvalidOperationException("no vanilla torso piece to base the penitent robe on"); } ItemDefinition obj = ItemTemplates.Clone(asset); ClearInheritedLifecycleFlags(obj); obj.modifiersOnEquipNew = new List(); obj.modifiersOnInventoryNew = new List(); obj.maxDurability = 500f; SpellTerms.ChamberText chamberText = SpellTerms.RobeText(); obj.displayName = chamberText.Name.English; obj.description = chamberText.Description.English; obj.flavor = string.Empty; obj.hasCustomDescription = true; obj.includedInEarlyAccess = true; obj.basePrice = 900; obj.itemQuality = (ItemQuality)2; return obj; } private static ItemDefinition BuildBeads() { //IL_0000: 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) ItemDefinition asset = AssetAccess.GetAsset(ItemIds.Item_InstantDefibrilator); if ((Object)(object)asset == (Object)null) { throw new InvalidOperationException("no vanilla defibrillator to base the martyr's beads on"); } ItemDefinition obj = ItemTemplates.Clone(asset); StripInheritedEffects(obj); ClearInheritedLifecycleFlags(obj); SpellTerms.ChamberText chamberText = SpellTerms.BeadsText(); obj.displayName = chamberText.Name.English; obj.description = chamberText.Description.English; obj.flavor = string.Empty; obj.hasCustomDescription = true; obj.includedInEarlyAccess = true; obj.basePrice = 1200; obj.itemQuality = (ItemQuality)2; return obj; } private static ItemDefinition BuildPage(RecipePages.Page page) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) ItemDefinition asset = AssetAccess.GetAsset(ItemIds.Manual_Recipe_Bread_1); if ((Object)(object)asset == (Object)null) { throw new InvalidOperationException("no vanilla recipe page to base a region page on"); } ItemDefinition obj = ItemTemplates.Clone(asset); StripInheritedEffects(obj); ClearInheritedLifecycleFlags(obj); obj.displayName = SpellTerms.PageName(page.Spell).English; obj.description = SpellTerms.PageDescription(page.Spell).English; obj.flavor = string.Empty; obj.hasCustomDescription = true; obj.includedInEarlyAccess = true; return obj; } private static ItemDefinition BuildStaff(StaffDefinition kind) { //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_0104: 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_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) WeaponSO obj = FindStaffBase(kind); if ((Object)(object)obj == (Object)null) { throw new InvalidOperationException("no usable vanilla weapon to base the staff on"); } WeaponSO val = ItemTemplates.Clone(obj); ClearInheritedLifecycleFlags((ItemDefinition)(object)val); SpellTerms.StaffText staffText = SpellTerms.StaffTextFor(kind.ItemKey); ((ItemDefinition)val).displayName = staffText.Name.English; ((ItemDefinition)val).description = staffText.Description.English; ((ItemDefinition)val).flavor = staffText.Flavor.English; if (kind.ClearBodyAttributes) { ((ItemDefinition)val).baseAttributes = new List(); } if (kind.NoAim) { ((ItemDefinition)val).baseAttributes = new List(((ItemDefinition)val).baseAttributes ?? new List()) { new ItemAttributeContainer { attribute = (ItemAttributes)8, value = 1f } }; } ((ItemDefinition)val).hasCustomDescription = true; val.caliber = (CaliberTypes)0; val.projectileType = (ProjectileTypes)5; val.overrideDamage = 0f; ((ItemDefinition)val).basePrice = kind.BasePrice; ((ItemDefinition)val).itemQuality = kind.Quality; val.hideRpm = true; EnsureAmmoCounter(val); EnsureModel(val, kind.ModelOffset, kind.MountBone); return (ItemDefinition)(object)val; } private static void EnsureModel(WeaponSO staff, Vector3 offset, string mountBone) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) GameObject val = StaffPrefab.Build(((ItemDefinition)staff).prefab, offset, mountBone); if ((Object)(object)val != (Object)null) { ((ItemDefinition)staff).prefab = val; } } private static void EnsureAmmoCounter(WeaponSO staff) { if ((Object)(object)staff.ammoCounterPrefab != (Object)null) { return; } List rawList = StaticInstance.Instance.itemDatabase.GetRawList(); WeaponSO val = null; int num = 0; for (int i = 0; i < rawList.Count; i++) { ItemDefinition obj = rawList[i]; WeaponSO val2 = (WeaponSO)(object)((obj is WeaponSO) ? obj : null); if (val2 != null && !((Object)(object)val2.ammoCounterPrefab == (Object)null) && val2.ammoCounterPrefab.bullets != null) { int num2 = val2.ammoCounterPrefab.bullets.Length; if (num2 > num) { num = num2; val = val2; } } } if ((Object)(object)val == (Object)null) { Plugin.Log.LogWarning((object)"No weapon carries an ammunition counter to borrow; mana will not be shown."); return; } staff.ammoCounterPrefab = val.ammoCounterPrefab; Plugin.Log.LogInfo((object)$"Staff borrowed the magazine readout from '{((Object)val).name}' ({num} rounds)."); } private static ItemDefinition ArtFor(SpellDefinition spell, ItemDefinition fallback) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) if (spell.Key.Value != "lightning") { return fallback; } ItemDefinition asset = AssetAccess.GetAsset(ItemIds.Enchantment_Thunderbolt); if ((Object)(object)asset == (Object)null || (Object)(object)asset.artwork == (Object)null) { Plugin.Log.LogWarning((object)"Scroll of Thunderbolt has no artwork to borrow, so the lightning scroll keeps the shared scroll look."); return fallback; } return asset; } private static EnchantmentDefinition BuildEnchantment(SpellDefinition spell) { //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) EnchantmentDefinition obj = ScriptableObject.CreateInstance(); obj.enchantmentName = spell.DisplayName; obj.textColor = RowColor(spell); obj.CostsDurability = false; obj.IsElemental = false; obj.modifiersApplied = new List(); return obj; } private static ItemDefinition BuildScroll(SpellDefinition spell) { //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_scrollBase == (Object)null) { _scrollBase = FindScrollBase(); } if ((Object)(object)_scrollBase == (Object)null) { throw new InvalidOperationException("no usable vanilla item to base a scroll on; a blank definition is not an option, because the game iterates serialized lists it would leave null"); } ItemDefinition obj = ItemTemplates.Clone(ArtFor(spell, _scrollBase)); StripInheritedEffects(obj); ClearInheritedLifecycleFlags(obj); obj.displayName = "Scroll of " + spell.DisplayName; obj.description = SpellLocalization.DescribeScroll(spell.Key.Value).English; obj.flavor = string.Empty; obj.hasCustomDescription = true; obj.useType = (UseType)3; int num = ScrollTiers.TierOf(spell.Key.Value); obj.includedInEarlyAccess = true; obj.basePrice = ((num == 1) ? 1000 : 2500); obj.itemQuality = (ItemQuality)((num == 1) ? 3 : 4); return obj; } private static void StripInheritedEffects(ItemDefinition definition) { //IL_0070: Unknown result type (might be due to invalid IL or missing references) definition.modifiersOnEquipNew = new List(); definition.modifiersOnInventoryNew = new List(); definition.modifiersOnAttachToItem = new List(); definition.removeStatusOnConsume = new List(); definition.addStatusOnConsume = new List(); definition.buffsOnConsume = new List(); definition.valueChangeOnItemConsume = new List(); definition.resourceOnConsume = new List(); definition.recipesTaughtOnConsume = new List(); definition.baseAttributes = new List(); definition.modifiesCaliber = (CaliberTypes)0; } private static void ClearInheritedLifecycleFlags(ItemDefinition definition) { definition.deprecated = false; definition.unlocksCheckpointWhenBroughtToChurch = false; } private static Color RowColor(SpellDefinition spell) { //IL_0018: 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_0089: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: 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_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) if (spell.Category == SpellCategory.Transform) { return new Color(0.72f, 0.66f, 0.95f); } if (spell.Category == SpellCategory.Payload || spell.Category == SpellCategory.Segment) { return new Color(0.95f, 0.78f, 0.45f); } return (Color)(spell.Projectile.Element switch { ElementKind.Fire => new Color(1f, 0.55f, 0.25f), ElementKind.Frost => new Color(0.55f, 0.8f, 1f), ElementKind.Holy => new Color(1f, 0.95f, 0.72f), ElementKind.Dark => new Color(0.7f, 0.45f, 0.95f), ElementKind.Electric => new Color(0.85f, 0.9f, 0.35f), ElementKind.Poison => new Color(0.6f, 0.9f, 0.4f), ElementKind.Explosive => new Color(0.95f, 0.7f, 0.45f), _ => Color.white, }); } private static WeaponSO FindStaffBase(StaffDefinition kind) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) ItemDefinition asset = AssetAccess.GetAsset(kind.Body); WeaponSO val = (WeaponSO)(object)((asset is WeaponSO) ? asset : null); if (val != null && val.TypeIsEnchantable && (Object)(object)((ItemDefinition)val).prefab != (Object)null) { return val; } Plugin.Log.LogWarning((object)("The body of '" + kind.ItemKey + "' was unusable as a staff base; falling back to a scan.")); List rawList = StaticInstance.Instance.itemDatabase.GetRawList(); for (int i = 0; i < rawList.Count; i++) { ItemDefinition obj = rawList[i]; WeaponSO val2 = (WeaponSO)(object)((obj is WeaponSO) ? obj : null); if (val2 != null && val2.usableByPlayer && val2.TypeIsEnchantable && (Object)(object)((ItemDefinition)val2).prefab != (Object)null) { return val2; } } return null; } private static ItemDefinition FindScrollBase() { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Invalid comparison between Unknown and I4 List rawList = StaticInstance.Instance.itemDatabase.GetRawList(); ItemDefinition val = null; for (int i = 0; i < rawList.Count; i++) { ItemDefinition val2 = rawList[i]; if (!((Object)(object)val2 == (Object)null) && !((Object)(object)val2.artwork == (Object)null)) { if ((int)val2.useType == 3) { return val2; } if ((Object)(object)val == (Object)null) { val = val2; } } } if ((Object)(object)val != (Object)null) { Plugin.Log.LogWarning((object)("No vanilla enchantment item found; cloning '" + ((Object)val).name + "' instead so scrolls still have valid serialized data.")); } return val; } } } namespace UnholyRites.Combat { internal sealed class BeamChannel { private const float BeamDrop = 0.35f; private readonly CastPlan _plan; private readonly SpellRuntime _runtime; private readonly SpellHitResolver _hits; private readonly uint _seed; private readonly int _group; private readonly CastAuthority _authority; private CastTarget _aim; private float _nextTick; internal int Figures { get; private set; } internal int Ticks { get; private set; } internal BeamChannel(CastPlan plan, SpellRuntime runtime, SpellHitResolver hits, in CastTarget aim, uint seed, CastAuthority authority, float now, float voxelDensity) { //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: 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_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Unknown result type (might be due to invalid IL or missing references) _plan = plan; _runtime = runtime; _hits = hits; _seed = seed; _authority = authority; _aim = aim; _group = SpellGroups.Next(); _nextTick = now; for (int i = 0; i < plan.Emissions.Count; i++) { Emission emission = plan.Emissions[i]; ProjectileArchetype archetype = emission.Archetype; float power = SpellScale.Power(emission.Cost); SpellPresentation.Colors(archetype.Element, out var main, out var core); Frame(in emission, in aim, seed, out var origin, out var direction, out var reach); Basis(direction, out var right, out var up); if (runtime.TryAdd(new ActiveEmission { Delivery = emission.Delivery.Kind, Element = archetype.Element, Pattern = VoxelPattern.Beam, Intensity = IntensityCurve.FadeOut, Origin = origin, Direction = direction, Right = right, Up = up, ArrivalHeight = reach, Scale = archetype.Scale, BirthTime = now, Lifetime = 3600f, Power = power, Color = main, CoreColor = core, VoxelCount = SpellScale.Voxels(90f, power, voxelDensity), Seed = (seed ^ (uint)(int)(i * 2654435761u)), GroupId = _group, BeamIndex = i, CasterSlot = authority.CasterSlot, LocalCast = authority.Mine, Damage = 0f, Collision = CollisionKind.None, HitRadius = math.max(archetype.Scale, 0.2f) })) { Figures++; continue; } break; } } internal void Aim(in CastTarget aim) { _aim = aim; } internal void Drive(float now) { //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_008f: 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_007f: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: 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_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) bool flag = now >= _nextTick; if (flag) { _nextTick = now + math.max(_plan.BeamArchetype.TickInterval, 0.05f); Ticks++; } for (int i = 0; i < _plan.Emissions.Count; i++) { Emission emission = _plan.Emissions[i]; Frame(in emission, in _aim, _seed, out var origin, out var direction, out var reach); float num = (flag ? Strike(in emission, origin, direction, reach, now) : _hits.MeasureBeam(origin, direction, reach)); Basis(direction, out var right, out var up); _runtime.AimBeam(_group, i, origin, direction, right, up, num); if (flag) { SpellBeamVfx.Push(origin, origin + direction * num, emission.Archetype.Element, emission.Archetype.Damage); } } } internal void Close() { _runtime.RetireGroup(_group); } private float Strike(in Emission emission, float3 origin, float3 direction, float reach, float now) { //IL_003d: 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_0045: 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_0123: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) ProjectileArchetype archetype = emission.Archetype; ActiveEmission e = new ActiveEmission { Delivery = emission.Delivery.Kind, Element = archetype.Element, Voice = archetype.Voice, Origin = origin, Direction = direction, BirthTime = now, Power = SpellScale.Power(emission.Cost), Seed = _seed, CastSeed = _seed, Flags = _plan.Flags, Push = emission.Push, Damage = archetype.Damage, HitRadius = math.max(archetype.Scale, 0.2f), Mark = archetype.Mark, MarkAmount = archetype.MarkAmount, MarkOnce = true, SuppressDamage = _authority.SuppressDamage, CasterSlot = _authority.CasterSlot, LocalCast = _authority.Mine }; return _hits.StrikeBeam(origin, direction, reach, in e); } private static void Frame(in Emission emission, in CastTarget aim, uint seed, out float3 origin, out float3 direction, out float reach) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: 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) //IL_0056: 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_005a: Unknown result type (might be due to invalid IL or missing references) //IL_006a: 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_0078: 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_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0092: 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_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) ProjectileArchetype archetype = emission.Archetype; reach = ((archetype.Reach > 0f) ? archetype.Reach : 20f); if (emission.Delivery.Kind == DeliveryKind.Projectile) { Basis(aim.Direction, out var _, out var up); float3 origin2 = aim.Origin - up * 0.35f; LaunchFrame launchFrame = CastGeometry.Resolve(in emission, origin2, aim.Direction, seed); origin = launchFrame.Origin; direction = launchFrame.Direction; return; } float3 anchor = (aim.HasPoint ? aim.Point : (aim.Origin + aim.Direction * 8f)); origin = CastGeometry.ResolveGroundOffset(in emission, anchor); if (emission.Delivery.Kind == DeliveryKind.Descend) { float num = ((emission.Delivery.ArrivalHeight > 0f) ? emission.Delivery.ArrivalHeight : 25f); origin += new float3(0f, num, 0f); direction = new float3(0f, -1f, 0f); reach = num; } else { direction = new float3(0f, 1f, 0f); } } private static void Basis(float3 direction, out float3 right, out float3 up) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //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_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0032: 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_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) right = math.normalizesafe(math.cross(direction, math.up()), new float3(1f, 0f, 0f)); up = math.normalizesafe(math.cross(right, direction), math.up()); } } internal static class BloodPrice { internal const float ManaPerHealth = 4f; internal const float FloorFraction = 0.25f; internal const float PerLevelFraction = 1f; private static long _level = long.MinValue; private static float _paidThisLevel; internal static float HealthFor(CastPlan plan, float owedMana = 0f) { float num = ((plan != null && plan.BloodCost > 0f) ? plan.BloodCost : 0f); if (owedMana > 0f) { num += owedMana; } return num / 4f; } internal static bool CanPay(CastPlan plan, float owedMana, Unit caster, out string why) { why = null; float num = HealthFor(plan, owedMana); if (num <= 0f) { return true; } if ((Object)(object)caster == (Object)null || caster.Stats == null) { why = "cast.blood_floor"; return false; } float attribute = caster.Stats.GetAttribute((EntityAttributes)60); if (caster.Stats.GetStatus((EntityAttributes)92) - num < attribute * 0.25f) { why = "cast.blood_floor"; return false; } if (PaidThisLevel() + num > attribute * 1f) { why = "cast.blood_spent"; return false; } return true; } internal static void Pay(CastPlan plan, float owedMana, Unit caster) { float num = HealthFor(plan, owedMana); if (!(num <= 0f) && !((Object)(object)caster == (Object)null) && caster.Stats != null) { float status = caster.Stats.GetStatus((EntityAttributes)92); caster.Stats.SetStatus((EntityAttributes)92, status - num, false); PaidThisLevel(); _paidThisLevel += num; } } private static float PaidThisLevel() { GameManager instance = StaticInstance.Instance; long num = (((Object)(object)instance != (Object)null) ? (instance.currentSeed ^ ((long)instance.currentLevelIndex << 48)) : 0); if (num != _level) { _level = num; _paidThisLevel = 0f; } return _paidThisLevel; } } internal static class CastTrace { private const int MaxSteps = 8; private const float Step = 0.02f; private const float Lift = 0.5f; internal static bool Forward(Vector3 from, Vector3 direction, float reach, Unit ignore, out Vector3 point) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: 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_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_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_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006a: 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) Vector3 val = from; float num = reach; RaycastHit val2 = default(RaycastHit); for (int i = 0; i < 8; i++) { if (!(num > 0f)) { break; } if (!Physics.Raycast(val, direction, ref val2, num, -1, (QueryTriggerInteraction)1)) { break; } if ((Object)(object)((RaycastHit)(ref val2)).collider == (Object)null || (Object)(object)ignore == (Object)null || (Object)(object)((Component)((RaycastHit)(ref val2)).collider).GetComponentInParent() != (Object)(object)ignore) { point = ((RaycastHit)(ref val2)).point; return true; } float num2 = ((RaycastHit)(ref val2)).distance + 0.02f; val += direction * num2; num -= num2; } point = from + direction * reach; return false; } internal static float3 Below(Vector3 from, float reach, Vector3 fallback) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_009b: 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_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0059: 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_0073: 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_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) Vector3 val = from + Vector3.up * 0.5f; float num = reach + 0.5f; RaycastHit val2 = default(RaycastHit); for (int i = 0; i < 8; i++) { if (!(num > 0f)) { break; } if (!Physics.Raycast(val, Vector3.down, ref val2, num, -1, (QueryTriggerInteraction)1)) { break; } if ((Object)(object)((RaycastHit)(ref val2)).collider == (Object)null || (Object)(object)((Component)((RaycastHit)(ref val2)).collider).GetComponentInParent() == (Object)null) { return float3.op_Implicit(((RaycastHit)(ref val2)).point); } float num2 = ((RaycastHit)(ref val2)).distance + 0.02f; val += Vector3.down * num2; num -= num2; } return float3.op_Implicit(fallback); } } internal static class EndowedPuppets { private struct Pending { public int Name; public ushort Definition; public float Value; public float Since; } private const float Patience = 10f; private const float RetryInterval = 0.2f; private static readonly List Waiting = new List(); private static readonly Dictionary Applied = new Dictionary(); private static float _retryAt; private static bool _reportedFailure; internal static void Endow(int name, ushort definition, float value) { if (name > 0 && !(value < 0f) && (!Applied.TryGetValue(name, out var value2) || !(value <= value2)) && !TryApply(name, definition, value)) { Waiting.Add(new Pending { Name = name, Definition = definition, Value = value, Since = Time.time }); } } internal static void Tick(float now) { if (Waiting.Count == 0 || now < _retryAt) { return; } _retryAt = now + 0.2f; for (int num = Waiting.Count - 1; num >= 0; num--) { Pending pending = Waiting[num]; if (TryApply(pending.Name, pending.Definition, pending.Value) || now - pending.Since > 10f) { Waiting.RemoveAt(num); } } } internal static void Clear() { Waiting.Clear(); Applied.Clear(); } private static bool TryApply(int name, ushort definition, float value) { if (Applied.TryGetValue(name, out var value2) && value <= value2) { return true; } try { Component val = Session.Current.Resolve(name); if ((Object)(object)val == (Object)null) { return false; } Unit val2 = (Unit)(((object)((val is Unit) ? val : null)) ?? ((object)val.GetComponent())); if ((Object)(object)val2 == (Object)null) { return false; } if (definition != 0 && DefinitionOf(val2) != definition) { Applied[name] = float.MaxValue; return true; } Applied[name] = value; RaisedBody.Mark((Component)(object)val2); Endowment.ApplyRaised(val2, value); return true; } catch (Exception ex) { if (!_reportedFailure) { _reportedFailure = true; Endowment.Report("a mirrored unit", ex); } Applied[name] = float.MaxValue; return true; } } private static ushort DefinitionOf(Unit unit) { UnitSO unitSO = unit.unitSO; if (!((Object)(object)unitSO != (Object)null)) { return 0; } return unitSO.id.value; } } internal static class Endowment { private const float RaisedFraction = 0.5f; private const float ValuePerHealthStep = 500f; private const float ValuePerDamageStep = 2000f; private const float SizeCeiling = 1.4f; private const float SpeedCeiling = 1.5f; private const float SizeFromHealth = 0.12f; private const float SpeedFromHealth = 0.15f; private static readonly uint HealthId = (uint)"UnholyRites.GraveGoods.Health".GetHashCode(); private static readonly uint DamageId = (uint)"UnholyRites.GraveGoods.Damage".GetHashCode(); internal static void ApplyRaised(Unit unit, float goods) { //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Expected O, but got Unknown if (!((Object)(object)unit == (Object)null)) { float num = ((goods > 0f) ? (goods / 500f) : 0f); float num2 = 0.5f * (1f + num); float attribute = unit.Stats.GetAttribute((EntityAttributes)60); float status = unit.Stats.GetStatus((EntityAttributes)92); float num3 = ((attribute > 0f) ? (status / attribute) : 1f); unit.Stats.RemoveModifier((EntityAttributes)60, HealthId); unit.Stats.AddModifier((EntityAttributes)60, new StatModifier(num2 - 1f, (StatModType)300, HealthId)); unit.Stats.SetStatus((EntityAttributes)92, unit.Stats.GetAttribute((EntityAttributes)60) * num3, false); Npc val = (Npc)(object)((unit is Npc) ? unit : null); if (val != null) { ((Unit)val).ScaleUnit(Saturating(num, 0.12f, 1.4f), 1f); val.SetBonusMoveSpeed(Saturating(num, 0.15f, 1.5f)); } } } internal static float HealthEquivalent(float goods, float stitch) { if (!(stitch > 1f) || float.IsInfinity(stitch)) { return goods; } float num = ((goods > 0f) ? (goods / 500f) : 0f); return 500f * (stitch * (1f + num) - 1f); } internal static void ApplyStrength(Unit unit, float goods) { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Expected O, but got Unknown //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Expected O, but got Unknown if (!((Object)(object)unit == (Object)null) && !(goods <= 0f)) { float num = goods / 2000f; unit.Stats.RemoveModifier((EntityAttributes)115, DamageId); unit.Stats.RemoveModifier((EntityAttributes)61, DamageId); unit.Stats.AddModifier((EntityAttributes)115, new StatModifier(num, (StatModType)100, DamageId)); unit.Stats.AddModifier((EntityAttributes)61, new StatModifier(num, (StatModType)300, DamageId)); } } private static float Saturating(float health, float rate, float ceiling) { float num = ceiling - 1f; return 1f + num * (1f - Mathf.Exp((0f - health) * rate / num)); } internal static void Report(string what, Exception ex) { Plugin.Log.LogWarning((object)("Grave goods could not be spent on " + what + ": " + ex.Message)); } } internal static class GraveGoods { private const float VerticalReach = 3f; private const float FittedFraction = 0.75f; private const float DrawSpeed = 3.5f; private const float DrawSettled = 0.2f; private const float DrawDeadband = 0.35f; private const float SweepInterval = 0.25f; private static readonly List Found = new List(32); private static Pickup[] _sweep = Array.Empty(); private static float _sweptAt = float.NegativeInfinity; private static bool _reportedFailure; internal static void Draw(in ActiveEmission e, float now) { //IL_001c: 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_0026: 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_0063: Unknown result type (might be due to invalid IL or missing references) //IL_006b: 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_0098: 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_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: 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_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: 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_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) try { float num = Reach(in e); if (num <= 0f) { return; } Pickup[] array = Sweep(now); Vector3 val = float3.op_Implicit(e.Origin); Vector3 val5 = default(Vector3); foreach (Pickup val2 in array) { if (!Eligible(val2, val, num)) { continue; } Rigidbody body = val2.body; if ((Object)(object)body == (Object)null || body.isKinematic) { continue; } Vector3 val3 = val - ((Component)val2).transform.position; val3.y = 0f; float magnitude = ((Vector3)(ref val3)).magnitude; if (!(magnitude <= 0.2f)) { Vector3 val4 = val3 / magnitude * math.min(3.5f, magnitude * 2.5f); Vector3 linearVelocity = body.linearVelocity; ((Vector3)(ref val5))..ctor(val4.x - linearVelocity.x, 0f, val4.z - linearVelocity.z); if (!(((Vector3)(ref val5)).sqrMagnitude < 0.122499995f)) { body.linearVelocity = new Vector3(val4.x, linearVelocity.y, val4.z); } } } } catch (Exception ex) { Report(ex); } } internal static float Claim(in ActiveEmission e, bool local, bool shared) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) if (!local && !shared) { return 0f; } try { float num = Reach(in e); if (num <= 0f) { return 0f; } Collect(e.Origin, num); float num2 = 0f; int num3 = 0; int num4 = 0; for (int i = 0; i < Found.Count; i++) { Pickup val = Found[i]; if ((Object)(object)val == (Object)null) { continue; } float num5 = Appraise(val); if (Session.Current.IsShared((Component)(object)val)) { if (shared && Session.Current.Consume((Component)(object)val)) { num3++; } else { num4++; } } else if (local) { Remove(val); num3++; } else { num4++; } num2 += num5; } Plugin.Log.LogInfo((object)($"Grave goods: {Found.Count} in reach, {num3} taken, {num4} left to another " + $"machine, worth {num2:0} (local={local} shared={shared}).")); return num2; } catch (Exception ex) { Report(ex); return 0f; } finally { Found.Clear(); } } private static float Appraise(Pickup p) { ItemDefinition itemSO = p.ItemSO; if ((Object)(object)itemSO == (Object)null) { return 0f; } InventoryData inventoryData = p.inventoryData; int num = ((inventoryData == null || inventoryData.quantity <= 1) ? 1 : inventoryData.quantity); float num2 = (float)itemSO.basePrice * (float)num; if (inventoryData == null) { return num2; } num2 += Fitted(inventoryData.attachmentIds); return num2 + Fitted(inventoryData.enchantmentIds); } private static float Fitted(ItemId[] ids) { //IL_0052: Unknown result type (might be due to invalid IL or missing references) if (ids == null || ids.Length == 0) { return 0f; } ItemDatabase val = (((Object)(object)StaticInstance.Instance != (Object)null) ? StaticInstance.Instance.itemDatabase : null); if ((Object)(object)val == (Object)null) { return 0f; } float num = 0f; for (int i = 0; i < ids.Length; i++) { if (((ItemId)(ref ids[i])).IsValid) { ItemDefinition val2 = val[ids[i]]; if ((Object)(object)val2 != (Object)null) { num += (float)val2.basePrice * 0.75f; } } } return num; } private static float Reach(in ActiveEmission e) { return math.max(e.Scale, e.HitRadius); } private static void Collect(float3 centre, float radius) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: 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) Found.Clear(); Pickup[] array = FindAll(); Vector3 centre2 = float3.op_Implicit(centre); for (int i = 0; i < array.Length; i++) { if (Eligible(array[i], centre2, radius)) { Found.Add(array[i]); } } } private static bool Eligible(Pickup p, Vector3 centre, float radius) { //IL_0058: 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_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)p == (Object)null || (Object)(object)p.ItemSO == (Object)null || !((Component)p).gameObject.activeInHierarchy) { return false; } if ((Object)(object)p.spawnedIn != (Object)null) { return false; } if (Insured(p.inventoryData) || Protected(p.ItemSO)) { return false; } Vector3 val = ((Component)p).transform.position - centre; if (val.y > 3f || val.y < -3f) { return false; } val.y = 0f; return ((Vector3)(ref val)).sqrMagnitude <= radius * radius; } private static bool Protected(ItemDefinition definition) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Invalid comparison between Unknown and I4 //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Invalid comparison between Unknown and I4 if (!SpellContent.IsStaff(definition) && Array.IndexOf(Oaths.Keys, SpellContent.ItemKeyOf(definition)) < 0 && (int)definition.ItemType != 11 && !definition.purgeQuestsWithThisItem && (int)definition.useType != 7) { return definition.unlocksCheckpointWhenBroughtToChurch; } return true; } private static bool Insured(InventoryData data) { //IL_0018: 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) ItemId[] array = data?.attachmentIds; if (array == null) { return false; } for (int i = 0; i < array.Length; i++) { if (array[i] == ItemIds.Attachment_Insurance) { return true; } } return false; } private static void Remove(Pickup p) { InteractionManager instance = StaticInstance.Instance; if ((Object)(object)instance == (Object)null) { return; } try { instance.RemovePickup(p); } catch (Exception ex) { Report(ex); } } private static Pickup[] Sweep(float now) { if (now - _sweptAt < 0.25f) { return _sweep; } _sweptAt = now; _sweep = FindAll(); return _sweep; } private static Pickup[] FindAll() { return Object.FindObjectsByType((FindObjectsInactive)0, (FindObjectsSortMode)0) ?? Array.Empty(); } private static void Report(Exception ex) { if (!_reportedFailure) { _reportedFailure = true; Plugin.Log.LogWarning((object)$"The grave goods could not be gathered: {ex}"); } } } internal static class HexLinks { private const int PerCaster = 4; private static readonly Dictionary> Links = new Dictionary>(); private static readonly List Gone = new List(); internal static void Linked(Unit caster, Unit target) { if ((Object)(object)caster == (Object)null || (Object)(object)target == (Object)null || target.Stats == null || !(target.Stats.GetStatus((EntityAttributes)32) > 0f)) { return; } if (!target.IsAlive) { Release(target); return; } if (Links.Count > 8) { Forget(); } int instanceID = ((Object)caster).GetInstanceID(); if (!Links.TryGetValue(instanceID, out var value)) { value = new List(5); Links[instanceID] = value; } for (int num = value.Count - 1; num >= 0; num--) { Unit val = value[num]; if ((Object)(object)val == (Object)null) { value.RemoveAt(num); } else { bool flag = val.Stats != null && val.Stats.GetStatus((EntityAttributes)32) > 0f; if (flag && !val.IsAlive) { Release(val); flag = false; } if (!flag || val == target) { value.RemoveAt(num); } } } value.Add(target); while (value.Count > 4) { Unit unit = value[0]; value.RemoveAt(0); Release(unit); } } private static void Forget() { Gone.Clear(); foreach (KeyValuePair> link in Links) { link.Value.RemoveAll((Unit u) => (Object)(object)u == (Object)null); if (link.Value.Count == 0) { Gone.Add(link.Key); } } for (int num = 0; num < Gone.Count; num++) { Links.Remove(Gone[num]); } } private static void Release(Unit unit) { if ((Object)(object)unit != (Object)null && unit.Stats != null) { unit.Stats.SetStatus((EntityAttributes)32, 0f, false); } } } internal interface ISessionWorld { bool IsShared(Component pickup); bool Consume(Component pickup); int NameOf(Component unit); Component Resolve(int name); } internal static class Session { internal static ISessionWorld Current { get; set; } = NoSession.Instance; } internal sealed class NoSession : ISessionWorld { internal static readonly ISessionWorld Instance = new NoSession(); public bool IsShared(Component pickup) { return false; } public bool Consume(Component pickup) { return false; } public int NameOf(Component unit) { return 0; } public Component Resolve(int name) { return null; } } internal static class NailLedger { private struct Entry { internal float Banked; internal uint Seed; } internal const float Share = 0.5f; internal const float Cap = 105f; private static readonly Dictionary Accounts = new Dictionary(); private static readonly List Dead = new List(); private static long _level = long.MinValue; internal static void Branded(Unit target, uint castSeed) { if (!((Object)(object)target == (Object)null)) { ForgetOnNewLevel(); if (!Accounts.TryGetValue(target, out var value) || SpellMarks.Read(target, MarkKind.Brand) <= 0f) { value.Banked = 0f; } value.Seed = castSeed; Accounts[target] = value; } } internal static void Bank(Unit unit, float damage) { if (!((Object)(object)unit == (Object)null) && !(damage <= 0f) && SpellDamageScope.Spell <= 0 && SpellDamageScope.Indirect <= 0) { ForgetOnNewLevel(); Prune(); Accounts.TryGetValue(unit, out var value); value.Banked += damage; Accounts[unit] = value; } } internal static float Cash(Unit target, uint castSeed) { if ((Object)(object)target == (Object)null || target.Stats == null || SpellMarks.Read(target, MarkKind.Brand) <= 0f || !Accounts.TryGetValue(target, out var value)) { return 0f; } if (castSeed != 0 && value.Seed == castSeed) { return 0f; } float num = value.Banked * 0.5f; if (num > 105f) { num = 105f; } target.Stats.SetStatus((EntityAttributes)21, 0f, false); Accounts.Remove(target); Plugin.Log.LogInfo((object)$"Nail: cashed {value.Banked:0.#} banked on {((Object)target).name} for {num:0.#} holy."); return num; } private static void Prune() { if (Accounts.Count < 128) { return; } Dead.Clear(); foreach (KeyValuePair account in Accounts) { if ((Object)(object)account.Key == (Object)null || !account.Key.IsAlive) { Dead.Add(account.Key); } } for (int i = 0; i < Dead.Count; i++) { Accounts.Remove(Dead[i]); } } private static void ForgetOnNewLevel() { GameManager instance = StaticInstance.Instance; long num = (((Object)(object)instance != (Object)null) ? (instance.currentSeed ^ ((long)instance.currentLevelIndex << 48)) : 0); if (num != _level) { _level = num; Accounts.Clear(); } } } internal static class Necromancy { private const float StandingSeconds = 18f; private static readonly List Candidates = new List(32); private const float StitchCeiling = 3f; private static bool _reportedFailure; internal static void Raise(in ActiveEmission e, Unit master, bool authoritative) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) try { float num = Mathf.Max(e.Scale, e.HitRadius); if (num <= 0f) { return; } Collect(e.Origin, num); if (Candidates.Count == 0) { return; } bool flag = (e.Flags & CastFlags.Stitch) != CastFlags.None && Candidates.Count > 1; float stitch = 1f; int num2 = -1; if (flag) { num2 = Largest(out stitch); } Plugin.Log.LogInfo((object)($"A rite takes {Candidates.Count} of the dead " + $"(mine={e.LocalCast} authoritative={authoritative} consumes={e.Consumes}" + (flag ? $", stitched into one x{stitch:0.##}" : string.Empty) + ").")); if (e.Consumes) { float num3 = GraveGoods.Claim(in e, e.LocalCast, authoritative); if (e.LocalCast) { Offerings.Claim(e.Seed, flag ? num3 : (num3 / (float)Candidates.Count)); } } float seconds = Mathf.Max(1f, 18f * e.Power); for (int i = 0; i < Candidates.Count; i++) { Npc val = Candidates[i]; if (!((Object)(object)val == (Object)null)) { UnitSO unitSO = ((Unit)val).unitSO; Vector3 position = ((Component)val).transform.position; Quaternion rotation = ((Component)val).transform.rotation; if (authoritative && (Object)(object)master != (Object)null && (!flag || i == num2)) { Summon(unitSO, position, rotation, master, seconds, e.Consumes ? new uint?(e.Seed) : ((uint?)null), stitch); } val.SpawnGibExplosion(); } } } catch (Exception ex) { Report(ex); } finally { Candidates.Clear(); } } private static int Largest(out float stitch) { int num = -1; float num2 = 0f; float num3 = 0f; for (int i = 0; i < Candidates.Count; i++) { Npc val = Candidates[i]; float num4 = (((Object)(object)val != (Object)null && ((Unit)val).Stats != null) ? ((Unit)val).Stats.GetAttribute((EntityAttributes)60) : 0f); if (float.IsNaN(num4) || float.IsInfinity(num4) || num4 < 0f) { num4 = 0f; } num3 += num4; if (num < 0 || num4 > num2) { num = i; num2 = num4; } } stitch = ((num2 > 0f) ? Mathf.Clamp(num3 / num2, 1f, 3f) : 1f); return num; } private static void Collect(float3 centre, float radius) { //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_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007c: 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_0082: Unknown result type (might be due to invalid IL or missing references) Candidates.Clear(); UnitManager instance = StaticInstance.Instance; if ((Object)(object)instance == (Object)null) { return; } Npc[] allNpcs = instance.GetAllNpcs(true); if (allNpcs == null) { return; } float num = radius * radius; Vector3 val = float3.op_Implicit(centre); foreach (Npc val2 in allNpcs) { if (!((Object)(object)val2 == (Object)null) && (int)((Unit)val2).UnitState == 0 && !((Object)(object)((Unit)val2).unitSO == (Object)null) && !RaisedBody.Marks((Component)(object)val2) && IsEligible(val2)) { Vector3 val3 = ((Component)val2).transform.position - val; if (!(((Vector3)(ref val3)).sqrMagnitude > num)) { Candidates.Add(val2); } } } } private static bool IsEligible(Npc npc) { //IL_0012: 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) //IL_001a: Invalid comparison between Unknown and I4 UnitSO unitSO = ((Unit)npc).unitSO; if (unitSO.isCivilian) { return false; } return (unitSO.unitType & 8) == 0; } private static async void Summon(UnitSO definition, Vector3 at, Quaternion facing, Unit master, float seconds, uint? rite, float stitch) { //IL_0016: 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_001e: 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) try { Unit val = await definition.SpawnUnitAsync((MonoBehaviour)(object)Plugin.Behaviour, at, facing); if (!((Object)(object)val == (Object)null)) { Configure(val, master, seconds, rite, stitch); } } catch (Exception ex) { Report(ex); } } private static void Configure(Unit raised, Unit master, float seconds, uint? rite, float stitch) { raised.RegisterAppliedStatus((EntityAttributes)20, master); raised.Stats.SetStatus((EntityAttributes)20, 20f, false); Endowment.ApplyRaised(raised, Endowment.HealthEquivalent(0f, stitch)); Npc val = (Npc)(object)((raised is Npc) ? raised : null); if (val != null) { val.RequestUnitOpacity(0f); } RaisedBody.Mark((Component)(object)raised); RaisedUndead raisedUndead = ((Component)raised).gameObject.AddComponent(); raisedUndead.Bind(raised, master, seconds, stitch); Offerings.Announce(raised, Endowment.HealthEquivalent(0f, stitch)); if (rite.HasValue) { Offerings.Endow(rite.Value, raisedUndead); } } private static void Report(Exception ex) { if (!_reportedFailure) { _reportedFailure = true; Plugin.Log.LogWarning((object)$"The dead could not be raised: {ex}"); } } } internal static class Offerings { private struct Given { public float Value; public float At; } private sealed class Pending { public readonly List Units = new List(2); public float At; } private const float Keep = 60f; private static readonly Dictionary Recorded = new Dictionary(); private static readonly Dictionary Waiting = new Dictionary(); private static float _prunedAt; internal static event Action Claimed; internal static event Action Endowed; internal static void Announce(Unit unit, float value) { if (!((Object)(object)unit == (Object)null) && !(value < 0f)) { Offerings.Endowed?.Invoke(unit, value); } } internal static void Claim(uint seed, float perBody) { Record(seed, perBody); Offerings.Claimed?.Invoke(seed, perBody); } internal static void Receive(uint seed, float perBody) { Record(seed, perBody); } internal static void Endow(uint seed, RaisedUndead undead) { if ((Object)(object)undead == (Object)null) { return; } Prune(); if (Recorded.TryGetValue(seed, out var value)) { undead.Endow(value.Value); return; } if (!Waiting.TryGetValue(seed, out var value2)) { value2 = new Pending(); Waiting[seed] = value2; } value2.At = Time.time; value2.Units.Add(undead); } internal static void Clear() { Recorded.Clear(); Waiting.Clear(); } private static void Record(uint seed, float perBody) { if (perBody <= 0f || !IsFinite(perBody)) { return; } Prune(); Recorded[seed] = new Given { Value = perBody, At = Time.time }; if (!Waiting.TryGetValue(seed, out var value)) { return; } Waiting.Remove(seed); for (int i = 0; i < value.Units.Count; i++) { if ((Object)(object)value.Units[i] != (Object)null) { value.Units[i].Endow(perBody); } } } private static bool IsFinite(float value) { if (!float.IsNaN(value)) { return !float.IsInfinity(value); } return false; } private static void Prune() { float time = Time.time; if (time - _prunedAt < 60f) { return; } _prunedAt = time; List list = null; foreach (KeyValuePair item in Recorded) { if (!(time - item.Value.At < 60f)) { if (list == null) { list = new List(); } list.Add(item.Key); } } foreach (KeyValuePair item2 in Waiting) { if (!(time - item2.Value.At < 60f)) { if (list == null) { list = new List(); } list.Add(item2.Key); } } if (list != null) { for (int i = 0; i < list.Count; i++) { Recorded.Remove(list[i]); Waiting.Remove(list[i]); } } } } internal static class PoisonFountain { private const float Floor = 10f; private const float SlowestInterval = 1.1f; private const float FastestInterval = 0.3f; private const int DropsPerSpray = 3; private const float LobSpeed = 5f; private const int MaxSprayers = 6; private const float ScanInterval = 0.35f; private static readonly Dictionary NextSpray = new Dictionary(); private static readonly List Candidates = new List(); private static readonly List Stale = new List(); private static float _nextScan; internal static void Clear() { NextSpray.Clear(); _nextScan = 0f; } internal static void Tick(float now, bool authoritative) { //IL_0057: 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) if (!authoritative) { return; } try { if (now >= _nextScan) { _nextScan = now + 0.35f; Rescan(now); } Spray(now); } catch (Exception arg) { GameManager instance = StaticInstance.Instance; Plugin.Log.LogWarning((object)("The poison fountain stopped for a frame. state=" + (((Object)(object)instance != (Object)null) ? ((object)instance.gameState/*cast due to .constrained prefix*/).ToString() : "no GameManager") + " " + $"graphContext={(Object)(object)instance != (Object)null && (Object)(object)instance.graphContext != (Object)null} " + $"unitRoot={(Object)(object)instance != (Object)null && HasUnitRoot(instance)} " + $"player={(Object)(object)instance != (Object)null && (Object)(object)instance.PlayerUnit != (Object)null} " + $"units={(Object)(object)StaticInstance.Instance != (Object)null} " + $"candidates={Candidates.Count}{Environment.NewLine}{arg}")); } } private static bool HasUnitRoot(GameManager game) { if ((Object)(object)game.graphContext != (Object)null) { return (Object)(object)game.graphContext.unitRoot != (Object)null; } return false; } private static void Rescan(float now) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Invalid comparison between Unknown and I4 //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) Candidates.Clear(); UnitManager instance = StaticInstance.Instance; GameManager instance2 = StaticInstance.Instance; if ((Object)(object)instance == (Object)null || (Object)(object)instance2 == (Object)null || (int)instance2.gameState == 1 || (int)instance2.gameState == 0 || !HasUnitRoot(instance2)) { return; } Npc[] allNpcs = instance.GetAllNpcs(false); if (allNpcs == null) { return; } Unit playerUnit = instance2.PlayerUnit; Vector3 eye = (((Object)(object)playerUnit != (Object)null) ? ((Component)playerUnit).transform.position : Vector3.zero); foreach (Npc val in allNpcs) { if (!((Object)(object)val == (Object)null) && ((Unit)val).IsAlive && ((Unit)val).Stats != null && !(((Unit)val).Stats.GetStatus((EntityAttributes)28) < 10f)) { Candidates.Add(val); } } if (Candidates.Count > 6) { Candidates.Sort(delegate(Npc a, Npc b) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: 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: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) Vector3 val2 = ((Component)a).transform.position - eye; float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude; val2 = ((Component)b).transform.position - eye; return sqrMagnitude.CompareTo(((Vector3)(ref val2)).sqrMagnitude); }); Candidates.RemoveRange(6, Candidates.Count - 6); } Stale.Clear(); foreach (KeyValuePair item in NextSpray) { bool flag = false; for (int num = 0; num < Candidates.Count; num++) { if (((Object)Candidates[num]).GetInstanceID() == item.Key) { flag = true; break; } } if (!flag) { Stale.Add(item.Key); } } for (int num2 = 0; num2 < Stale.Count; num2++) { NextSpray.Remove(Stale[num2]); } } private static void Spray(float now) { for (int i = 0; i < Candidates.Count; i++) { Npc val = Candidates[i]; if ((Object)(object)val == (Object)null || !((Unit)val).IsAlive || ((Unit)val).Stats == null) { continue; } float status = ((Unit)val).Stats.GetStatus((EntityAttributes)28); if (status < 10f) { continue; } int instanceID = ((Object)val).GetInstanceID(); if (!NextSpray.TryGetValue(instanceID, out var value) || !(now < value)) { if (!NextSpray.ContainsKey(instanceID)) { NextSpray[instanceID] = now + Random.Range(0f, Interval(status)); continue; } NextSpray[instanceID] = now + Interval(status); Throw(val, status); } } } private static float Interval(float carried) { float num = Mathf.InverseLerp(10f, 100f, carried); return Mathf.Lerp(1.1f, 0.3f, num); } private static void Throw(Npc npc, float carried) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004c: 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_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) Vector3 val = ((Component)npc).transform.position + Vector3.up * HeadHeight(npc); float num = Mathf.Lerp(4f, 7f, Mathf.InverseLerp(10f, 100f, carried)); float num2 = val.y - ((Component)npc).transform.position.y; float num3 = Mathf.Abs(Physics.gravity.y); float num4 = (5f + Mathf.Sqrt(25f + 2f * num3 * num2)) / num3; float num5 = num / Mathf.Max(num4, 0.1f); for (int i = 0; i < 3; i++) { float num6 = Random.Range(0f, (float)Math.PI * 2f); float num7 = num5 * Random.Range(0.65f, 1.15f); SpellLiquid.Throw(new Vector3(Mathf.Cos(num6) * num7, 5f, Mathf.Sin(num6) * num7), val, (Unit)(object)npc); } } private static float HeadHeight(Npc npc) { Collider mainCollider = ((Unit)npc).mainCollider; CapsuleCollider val = (CapsuleCollider)(object)((mainCollider is CapsuleCollider) ? mainCollider : null); if (val != null && val.height > 0.1f) { return val.height * 0.9f; } return 1.7f; } } internal sealed class RaisedBody : MonoBehaviour { internal static bool Marks(Component candidate) { if ((Object)(object)candidate != (Object)null) { return (Object)(object)candidate.GetComponent() != (Object)null; } return false; } internal static void Mark(Component unit) { if (!((Object)(object)unit == (Object)null) && !Marks(unit)) { unit.gameObject.AddComponent(); } } } internal sealed class RaisedUndead : MonoBehaviour { private const float RenewInterval = 0.5f; private const float CharmValue = 20f; private Unit _unit; private Unit _master; private float _expiresAt; private float _renewAt; private bool _collapsed; private bool _endowed; private float _stitch = 1f; internal void Bind(Unit unit, Unit master, float seconds, float stitch = 1f) { _stitch = Mathf.Max(1f, stitch); _unit = unit; _master = master; _expiresAt = Time.time + seconds; _renewAt = 0f; } internal void Endow(float value) { if (!_endowed && !_collapsed && !((Object)(object)_unit == (Object)null) && !(value <= 0f)) { _endowed = true; try { Endowment.ApplyRaised(_unit, Endowment.HealthEquivalent(value, _stitch)); Endowment.ApplyStrength(_unit, value); } catch (Exception ex) { Endowment.Report("a raised unit", ex); } Offerings.Announce(_unit, Endowment.HealthEquivalent(value, _stitch)); } } private void Update() { //IL_001d: Unknown result type (might be due to invalid IL or missing references) if (!_collapsed && !((Object)(object)_unit == (Object)null)) { if ((int)_unit.UnitState == 0) { _collapsed = true; } else if (Time.time >= _expiresAt) { Collapse(); } else if (Time.time >= _renewAt) { _renewAt = Time.time + 0.5f; Renew(); } } } private void Renew() { try { if ((Object)(object)_master == (Object)null) { Collapse(); return; } _unit.RegisterAppliedStatus((EntityAttributes)20, _master); _unit.Stats.SetStatus((EntityAttributes)20, 20f, false); } catch (Exception ex) { Plugin.Log.LogWarning((object)("A raised unit could not be kept: " + ex.Message)); Collapse(); } } private void Collapse() { //IL_001b: Unknown result type (might be due to invalid IL or missing references) _collapsed = true; try { if ((Object)(object)_unit != (Object)null && (int)_unit.UnitState != 0) { _unit.Die(); } } catch (Exception ex) { Plugin.Log.LogWarning((object)("A raised unit could not be laid back down: " + ex.Message)); } } } internal static class SigilStake { internal const float Reach = 25f; internal const float ConeDegrees = 30f; internal const float Lifetime = 20f; private static bool _planted; private static float3 _point; private static float _plantedAt; internal static bool Planted => _planted; internal static void Plant(float3 point, float now) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_001c: 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_0032: Unknown result type (might be due to invalid IL or missing references) _planted = true; _point = point; _plantedAt = now; Plugin.Log.LogInfo((object)$"Stake planted at ({point.x:0.0}, {point.y:0.0}, {point.z:0.0})."); } internal static bool TryTakeOver(ref CastTarget target, float now) { //IL_0023: 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_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0034: 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_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: 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_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) if (!_planted) { return false; } if (now - _plantedAt > 20f) { Fall("its time is up"); return false; } float3 val = _point - target.Origin; if (math.length(val) > 25f) { Fall("the caster walked out of reach"); return false; } float3 val2 = math.normalizesafe(val, target.Direction); if (math.dot(math.normalizesafe(target.Direction, default(float3)), val2) < math.cos(math.radians(30f))) { return false; } target.Point = _point; target.HasPoint = true; _planted = false; Plugin.Log.LogInfo((object)"Stake took the cast."); return true; } internal static void Clear() { _planted = false; } private static void Fall(string why) { _planted = false; Plugin.Log.LogInfo((object)("Stake fell: " + why + ".")); } } internal static class SoundCatalog { private struct Entry { public string Path; public SoundEvent Sound; } private static readonly string[] BankFields = new string[16] { "soundImpactRicochet", "soundImpactHitCrit", "soundUiWeaponOilEnchant", "soundUiQuestComplete", "soundUiPositiveServiceConfirm", "soundUiDurabilityApparelBreak", "soundUiOptionsMenuOpen", "soundUiOptionsMenuClose", "soundUiGenericInventoryUp", "soundUiGenericInventoryDown", "soundLadderStep", "soundWaterSplashBig", "soundWaterSplashMedium", "soundWaterSplashSmall", "soundWaterSplashCasing", "soundWaterSplashProjectile" }; private static readonly List Entries = new List(); private static readonly HashSet _playing = new HashSet(); private static bool _built; private static int _cursor = -1; private static int _appliedJump = int.MinValue; internal static int Count => Entries.Count; internal static int Cursor => _cursor; internal static bool Ready() { if (!Build()) { return false; } if (_cursor < 0) { _cursor = 0; } return true; } internal static void Next() { if (!Build()) { return; } int value = Plugin.SoundBrowseFrom.Value; if (value != _appliedJump) { _appliedJump = value; if (value >= 0 && value < Entries.Count) { _cursor = value - 1; } } Move(1); } internal static void Move(int delta) { if (Build()) { StopAllPlayed(); _cursor = ((_cursor + delta) % Entries.Count + Entries.Count) % Entries.Count; Announce(_cursor); PlayAt(_cursor, null); } } internal static bool TryDescribe(int index, out string path, out string asset, out float length, out bool loops) { path = null; asset = null; length = 0f; loops = false; if (index < 0 || index >= Entries.Count) { return false; } Entry entry = Entries[index]; path = entry.Path; asset = (((Object)(object)entry.Sound != (Object)null) ? ((Object)entry.Sound).name : "?"); try { length = entry.Sound.GetMaxLength(); loops = entry.Sound.GetContainsLoop(); } catch (Exception) { } return true; } internal static void PlayAt(int index, SoundParameterInternals[] parameters) { if (index >= 0 && index < Entries.Count) { _playing.Add(index); Play(Entries[index].Sound, parameters); } } internal static void StopAt(int index) { if (index < 0 || index >= Entries.Count) { return; } _playing.Remove(index); try { Entries[index].Sound.StopEverywhere(false); } catch (Exception ex) { Plugin.Log.LogWarning((object)("That sound could not be stopped: " + ex.Message)); } } internal static void SilenceGame() { _playing.Clear(); try { SoundManager instance = SoundManager.Instance; if ((Object)(object)instance != (Object)null) { instance.StopEverything(false); } } catch (Exception ex) { Plugin.Log.LogWarning((object)("Could not silence the game: " + ex.Message)); } } internal static void StopAllPlayed() { if (_playing.Count != 0) { int[] array = new int[_playing.Count]; _playing.CopyTo(array); for (int i = 0; i < array.Length; i++) { StopAt(array[i]); } _playing.Clear(); } } private static bool Build() { if (_built) { return Entries.Count > 0; } AsyncAssetLoading instance = StaticInstance.Instance; if ((Object)(object)instance == (Object)null || instance.assetSets == null) { Plugin.Log.LogInfo((object)"The game has not finished loading its assets, so there is nothing to audition yet. Try again once a level is up."); return false; } _built = true; try { HashSet seen = new HashSet(); CollectEffects(instance, seen); CollectAttributes(instance, seen); CollectExplosions(instance, seen); CollectProjectiles(instance, seen); CollectMaterials(instance, seen); CollectBank(seen); CollectLoadedLoops(seen); } catch (Exception arg) { Plugin.Log.LogWarning((object)$"The sound catalogue is incomplete: {arg}"); } int num = CountLoops(); Plugin.Log.LogInfo((object)($"Sound catalogue built: {Entries.Count} distinct sounds, {num} of them looping. " + "Indices under 'scene/' come from whatever this level has loaded and are not stable between levels; everything before them is. Browse key steps, Testing/SoundBrowseFrom jumps.")); return Entries.Count > 0; } private static void CollectEffects(AsyncAssetLoading assets, HashSet seen) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) ProjectileEffectDefinition[] projectileEffects = assets.assetSets.projectileEffects; if (projectileEffects == null) { return; } for (int i = 0; i < projectileEffects.Length; i++) { ProjectileEffectDefinition val = projectileEffects[i]; if (!((Object)(object)val == (Object)null)) { string text = ((object)(ProjectileEffect)i/*cast due to .constrained prefix*/).ToString(); Add("effect/" + text + "/shot", val.soundEventShot, seen); Add("effect/" + text + "/impact", val.soundEventImpact, seen); ProjectileEffectBehaviour trailEffectPrefab = val.trailEffectPrefab; if ((Object)(object)trailEffectPrefab != (Object)null) { Add("effect/" + text + "/loop", trailEffectPrefab.loopEvent, seen); } } } } private static void CollectAttributes(AsyncAssetLoading assets, HashSet seen) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) AttributeEffect[] attributeEffects = assets.assetSets.attributeEffects; if (attributeEffects == null) { return; } for (int i = 0; i < attributeEffects.Length; i++) { AttributeEffect val = attributeEffects[i]; if (!((Object)(object)val == (Object)null)) { string text = ((object)(EntityAttributes)(ushort)i/*cast due to .constrained prefix*/).ToString(); Add("status/" + text + "/loop", val.loopEvent, seen); Add("status/" + text + "/activate", val.activateEvent, seen); } } } private static void CollectExplosions(AsyncAssetLoading assets, HashSet seen) { ExplosionDefinition[] explosionDefinitions = assets.assetSets.explosionDefinitions; if (explosionDefinitions == null) { return; } for (int i = 0; i < explosionDefinitions.Length; i++) { ExplosionDefinition val = explosionDefinitions[i]; if (!((Object)(object)val == (Object)null)) { Add($"explosion/{(object)(ExplosionTypes)i}", val.soundEventExplosion, seen); } } } private static void CollectProjectiles(AsyncAssetLoading assets, HashSet seen) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) ProjectileDefinition[] projectileTypes = assets.assetSets.projectileTypes; if (projectileTypes == null) { return; } for (int i = 0; i < projectileTypes.Length; i++) { ProjectileDefinition val = projectileTypes[i]; if (!((Object)(object)val == (Object)null)) { string text = ((object)(ProjectileTypes)i/*cast due to .constrained prefix*/).ToString(); Add("projectile/" + text + "/passby", val.soundPassby, seen); Add("projectile/" + text + "/impact", val.soundImpactOverride, seen); Add("projectile/" + text + "/playerDamage", val.soundPlayerDamage, seen); } } } private static void CollectMaterials(AsyncAssetLoading assets, HashSet seen) { List materialSettings = assets.materialSettings; if (materialSettings == null) { return; } for (int i = 0; i < materialSettings.Count; i++) { MaterialSetting val = materialSettings[i]; if (!((Object)(object)val == (Object)null)) { Add("material/" + ((Object)val).name + "/bullet", val.soundImpactBullet, seen); Add("material/" + ((Object)val).name + "/footstep", val.soundFootstepPlayer, seen); } } } private static void CollectBank(HashSet seen) { SoundBank instance = StaticInstance.Instance; if ((Object)(object)instance == (Object)null) { return; } Type typeFromHandle = typeof(SoundBank); for (int i = 0; i < BankFields.Length; i++) { FieldInfo field = typeFromHandle.GetField(BankFields[i]); if (!(field == null) && typeof(SoundEvent).IsAssignableFrom(field.FieldType)) { string path = "bank/" + BankFields[i]; object? value = field.GetValue(instance); Add(path, (SoundEvent)((value is SoundEvent) ? value : null), seen); } } } private static void CollectLoadedLoops(HashSet seen) { SoundEvent[] array = Resources.FindObjectsOfTypeAll(); if (array == null) { return; } List list = new List(); foreach (SoundEvent val in array) { if ((Object)(object)val == (Object)null || seen.Contains(val)) { continue; } try { if (val.GetContainsLoop()) { list.Add(val); } } catch (Exception) { } } list.Sort((SoundEvent a, SoundEvent b) => string.CompareOrdinal(((Object)a).name, ((Object)b).name)); for (int num = 0; num < list.Count; num++) { Add("scene/" + ((Object)list[num]).name, list[num], seen); } } private static int CountLoops() { int num = 0; for (int i = 0; i < Entries.Count; i++) { try { if (Entries[i].Sound.GetContainsLoop()) { num++; } } catch (Exception) { } } return num; } private static void Add(string path, SoundEvent sound, HashSet seen) { if (!((Object)(object)sound == (Object)null) && seen.Add(sound)) { Entries.Add(new Entry { Path = path, Sound = sound }); } } private static void Announce(int index) { Entry entry = Entries[index]; string text = "?"; string text2 = "?"; try { text = entry.Sound.GetMaxLength().ToString("0.00") + "s"; text2 = (entry.Sound.GetContainsLoop() ? "loop" : "one-shot"); } catch (Exception) { } Plugin.Log.LogInfo((object)($"[sound {index}/{Entries.Count - 1}] {entry.Path} " + "asset=" + ((Object)entry.Sound).name + " " + text + " " + text2)); } private static void Play(SoundEvent sound, SoundParameterInternals[] parameters) { //IL_003e: 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_0043: 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_004e: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)sound == (Object)null) { return; } try { GameManager instance = StaticInstance.Instance; Camera main = Camera.main; if (!((Object)(object)instance == (Object)null)) { Vector3 val = (((Object)(object)main != (Object)null) ? ((Component)main).transform.position : ((Component)instance).transform.position); if (parameters == null) { sound.PlayAtPosition(((Component)instance).transform, val); } else { sound.PlayAtPosition(((Component)instance).transform, val, parameters); } } } catch (Exception ex) { Plugin.Log.LogWarning((object)("That sound could not be played: " + ex.Message)); } } } internal static class SpellAmbience { private sealed class Voice { public GameObject Owner; public SoundEvent Sound; } private const string DarkLoopAsset = "SFX_Bullet_Effect_Dark_Loop_SE"; private static readonly Dictionary Voices = new Dictionary(); private static readonly HashSet Seen = new HashSet(); private static readonly List Ended = new List(); private static SoundEvent _darkLoop; private static bool _darkLoopResolved; private static bool _reportedFailure; internal static void Sync(SpellRuntime runtime, float now) { if (runtime == null) { StopAll(); return; } try { Seen.Clear(); for (int i = 0; i < runtime.ActiveCount; i++) { if (runtime.TryGet(i, out var emission) && !(now < emission.BirthTime)) { SoundEvent val = Ambience(in emission, now - emission.BirthTime); if (!((Object)(object)val == (Object)null)) { Seen.Add(emission.Seed); Follow(in emission, val, now); } } } Sweep(); } catch (Exception ex) { Report(ex); } } private static SoundEvent Ambience(in ActiveEmission e, float age) { if (e.Delivery != DeliveryKind.Anchored) { return null; } if (e.Pattern == VoxelPattern.Wisp) { if (!(age >= e.GrowDuration)) { return null; } return SpellAudio.AttributeSound((EntityAttributes)23, loop: true); } if (e.Pattern != VoxelPattern.Sigil && e.Pattern != VoxelPattern.Rise) { return null; } if (e.Element != ElementKind.Dark) { return null; } return DarkLoop(); } internal static bool Covers(in ActiveEmission e) { return (Object)(object)Ambience(in e, 0f) != (Object)null; } private static void Follow(in ActiveEmission e, SoundEvent sound, float now) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Expected O, but got Unknown //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) float3 val = SpellRuntime.Evaluate(in e, now - e.BirthTime); if (Voices.TryGetValue(e.Seed, out var value)) { if ((Object)(object)value.Owner == (Object)null) { Voices.Remove(e.Seed); } else { if (!((Object)(object)value.Sound != (Object)(object)sound)) { value.Owner.transform.position = float3.op_Implicit(val); return; } Silence(e.Seed); } } GameObject val2 = new GameObject("UnholyRites ambience"); val2.transform.position = float3.op_Implicit(val); SoundParameterInternals[] array = SpellAudio.Scaling(e.Power); if (array == null) { sound.Play(val2.transform); } else { sound.Play(val2.transform, array); } Voices.Add(e.Seed, new Voice { Owner = val2, Sound = sound }); } private static void Sweep() { if (Voices.Count == 0) { return; } Ended.Clear(); foreach (KeyValuePair voice in Voices) { if (!Seen.Contains(voice.Key)) { Ended.Add(voice.Key); } } for (int i = 0; i < Ended.Count; i++) { Silence(Ended[i]); } } internal static void StopAll() { if (Voices.Count == 0) { return; } Ended.Clear(); foreach (uint key in Voices.Keys) { Ended.Add(key); } for (int i = 0; i < Ended.Count; i++) { Silence(Ended[i]); } } private static void Silence(uint seed) { if (!Voices.TryGetValue(seed, out var value)) { return; } Voices.Remove(seed); try { if ((Object)(object)value.Owner != (Object)null) { value.Sound.Stop(value.Owner.transform, true); Object.Destroy((Object)(object)value.Owner); } } catch (Exception ex) { Report(ex); } } private static SoundEvent DarkLoop() { if (_darkLoopResolved) { return _darkLoop; } try { SoundEvent[] array = Resources.FindObjectsOfTypeAll(); if (array == null || array.Length == 0) { return null; } for (int i = 0; i < array.Length; i++) { if ((Object)(object)array[i] != (Object)null && ((Object)array[i]).name == "SFX_Bullet_Effect_Dark_Loop_SE") { _darkLoop = array[i]; break; } } _darkLoopResolved = true; Plugin.Log.LogInfo((object)(((Object)(object)_darkLoop != (Object)null) ? "Dark ground effects will hum with 'SFX_Bullet_Effect_Dark_Loop_SE'." : "'SFX_Bullet_Effect_Dark_Loop_SE' is not loaded in this build, so dark ground effects will stand there silently. Nothing else is affected.")); } catch (Exception ex) { _darkLoopResolved = true; Report(ex); } return _darkLoop; } private static void Report(Exception ex) { if (!_reportedFailure) { _reportedFailure = true; Plugin.Log.LogWarning((object)$"Spell ambience is unavailable and will stay silent: {ex}"); } } } internal static class SpellAudio { private const int ExpectedDefinitions = 37; private static bool _reportedInventory; private static bool _reportedFailure; internal static void Cast(ElementKind element, float3 position, float power) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) Play(Departure(element), position, power); } internal static void Chant(ElementKind element, float3 position, float power) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) Play(Departure(element), position, power); } private static SoundEvent Departure(ElementKind element) { if (element == ElementKind.Dark) { SoundEvent val = AttributeSound((EntityAttributes)32, loop: false); if ((Object)(object)val != (Object)null) { return val; } } if (element == ElementKind.Explosive) { element = ElementKind.Fire; } ProjectileEffectDefinition val2 = Definition(element); if (!((Object)(object)val2 != (Object)null)) { return null; } return val2.soundEventShot; } internal static SoundEvent AttributeSound(EntityAttributes id, bool loop) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected I4, but got Unknown try { AsyncAssetLoading instance = StaticInstance.Instance; if ((Object)(object)instance == (Object)null || instance.assetSets == null || instance.assetSets.attributeEffects == null) { return null; } AttributeEffect[] attributeEffects = instance.assetSets.attributeEffects; int num = (int)id; if (num < 0 || num >= attributeEffects.Length || (Object)(object)attributeEffects[num] == (Object)null) { return null; } return loop ? attributeEffects[num].loopEvent : attributeEffects[num].activateEvent; } catch (Exception ex) { Report(ex); return null; } } internal static void Impact(ElementKind element, SpellVoice voice, float3 position, float power, Collider surface = null) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) try { SoundEvent val = Arrival(element, voice); if ((Object)(object)val == (Object)null) { val = SurfaceSound(surface); } Play(val, position, power); } catch (Exception ex) { Report(ex); } } private static SoundEvent Arrival(ElementKind element, SpellVoice voice) { if (voice == SpellVoice.Blast || element == ElementKind.Explosive) { SoundEvent val = Explosion((ExplosionTypes)2); if ((Object)(object)val != (Object)null) { return val; } } ProjectileEffectDefinition val2 = Definition(element); if ((Object)(object)val2 == (Object)null) { return null; } if (!((Object)(object)val2.soundEventImpact != (Object)null)) { return val2.soundEventShot; } return val2.soundEventImpact; } private static SoundEvent Explosion(ExplosionTypes type) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected I4, but got Unknown AsyncAssetLoading instance = StaticInstance.Instance; if ((Object)(object)instance == (Object)null || instance.assetSets == null || instance.assetSets.explosionDefinitions == null) { return null; } ExplosionDefinition[] explosionDefinitions = instance.assetSets.explosionDefinitions; int num = (int)type; if (num < 0 || num >= explosionDefinitions.Length || (Object)(object)explosionDefinitions[num] == (Object)null) { return null; } return explosionDefinitions[num].soundEventExplosion; } private static SoundEvent SurfaceSound(Collider surface) { AsyncAssetLoading instance = StaticInstance.Instance; if ((Object)(object)instance == (Object)null || instance.materialSettings == null) { return null; } int num = MaterialIndex(instance, surface); if (num < 0 || num >= instance.materialSettings.Count) { return null; } MaterialSetting val = instance.materialSettings[num]; if (!((Object)(object)val != (Object)null)) { return null; } return val.soundImpactBullet; } internal static void Hit(ElementKind element, SpellVoice voice, float3 position, float power) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) Play(Arrival(element, voice), position, power); } internal static void Tick(ElementKind element, SpellVoice voice, float3 position, float power) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) Play(Arrival(element, voice), position, power); } private static void Play(SoundEvent sound, float3 position, float power) { //IL_0041: 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_002d: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)sound == (Object)null) { return; } try { GameManager instance = StaticInstance.Instance; if (!((Object)(object)instance == (Object)null)) { SoundParameterInternals[] array = Scaling(power); if (array == null) { sound.PlayAtPosition(((Component)instance).transform, float3.op_Implicit(position)); } else { sound.PlayAtPosition(((Component)instance).transform, float3.op_Implicit(position), array); } } } catch (Exception ex) { Report(ex); } } internal static SoundParameterInternals[] Scaling(float power) { //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Expected O, but got Unknown //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Expected O, but got Unknown //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Expected O, but got Unknown float value = Plugin.SoundPowerScaling.Value; if (value <= 0f) { return null; } float num = math.log2(math.clamp(power, 0.25f, 8f)) * value; if (math.abs(num) < 0.02f) { return null; } return (SoundParameterInternals[])(object)new SoundParameterInternals[3] { (SoundParameterInternals)new SoundParameterVolumeDecibel(math.clamp(6f * num, -8f, 9f), (UpdateMode)1), (SoundParameterInternals)new SoundParameterPitchSemitone(math.clamp(-4f * num, -7f, 4f), (UpdateMode)1), (SoundParameterInternals)new SoundParameterDistanceScale(math.clamp(math.exp2(num), 0.7f, 3.5f)) }; } private static ProjectileEffectDefinition Definition(ElementKind element) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Expected I4, but got Unknown try { AsyncAssetLoading instance = StaticInstance.Instance; if ((Object)(object)instance == (Object)null || instance.assetSets == null || instance.assetSets.projectileEffects == null) { return null; } ReportOnce(instance); int num = (int)SpellDamage.ToProjectileEffect(element); ProjectileEffectDefinition[] projectileEffects = instance.assetSets.projectileEffects; return (num >= 0 && num < projectileEffects.Length) ? projectileEffects[num] : null; } catch (Exception ex) { Report(ex); return null; } } private static int MaterialIndex(AsyncAssetLoading assets, Collider surface) { int defaultPhysicMaterialIndex = assets.defaultPhysicMaterialIndex; if ((Object)(object)surface == (Object)null || assets.physicMaterials == null) { return defaultPhysicMaterialIndex; } int num = assets.physicMaterials.IndexOf(surface.sharedMaterial); if (num < 0 || assets.materialSettings == null || num >= assets.materialSettings.Count) { return defaultPhysicMaterialIndex; } return num; } private static void ReportOnce(AsyncAssetLoading assets) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected I4, but got Unknown if (_reportedInventory) { return; } _reportedInventory = true; try { ProjectileEffectDefinition[] projectileEffects = assets.assetSets.projectileEffects; StringBuilder stringBuilder = new StringBuilder("Spell audio, per element: "); foreach (ElementKind value in Enum.GetValues(typeof(ElementKind))) { int num = (int)SpellDamage.ToProjectileEffect(value); ProjectileEffectDefinition val = ((num >= 0 && num < projectileEffects.Length) ? projectileEffects[num] : null); stringBuilder.Append(value).Append('='); if ((Object)(object)val == (Object)null) { stringBuilder.Append("no definition; "); } else { stringBuilder.Append(((Object)(object)val.soundEventShot != (Object)null) ? "shot" : "no-shot").Append('/').Append(((Object)(object)val.soundEventImpact != (Object)null) ? "impact" : "no-impact") .Append("; "); } } stringBuilder.Append("materials=").Append((assets.materialSettings != null) ? assets.materialSettings.Count : 0).Append(", definitions=") .Append(projectileEffects.Length) .Append('/') .Append(37); Plugin.Log.LogInfo((object)stringBuilder.ToString()); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Could not report spell audio: " + ex.Message)); } } private static void Report(Exception ex) { if (!_reportedFailure) { _reportedFailure = true; Plugin.Log.LogWarning((object)$"Spell audio is unavailable and will stay silent: {ex}"); } } } internal static class SpellBeamVfx { private const int Segments = 12; private const float Wander = 0.28f; private static readonly List Points = new List(13); private static bool _reportedMissing; private static bool _reportedFailed; internal static void Push(float3 from, float3 to, ElementKind element, float damage) { //IL_0036: 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_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) RailgunVFX instance = StaticInstance.Instance; if ((Object)(object)instance == (Object)null) { if (!_reportedMissing) { _reportedMissing = true; Plugin.Log.LogWarning((object)"The game's beam renderer is not present, so a beam spell is drawn by its voxels alone."); } return; } SpellPresentation.Colors(element, out var main, out var core); Build(from, to); float num = SpellScale.PowerFromDamage(damage); float num2 = 0.16f + 0.14f * math.clamp(num, 0.5f, 3f); float num3 = num2 * 3.2f; try { instance.PushBeam(Points, new Vector3(core.x, core.y, core.z), new Vector3(main.x, main.y, main.z), num2, num3, false); } catch (Exception ex) { if (!_reportedFailed) { _reportedFailed = true; Plugin.Log.LogWarning((object)("The game's beam renderer refused a beam, so it is drawn by its voxels alone: " + ex.Message)); } } } private static void Build(float3 from, float3 to) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0012: 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_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_005a: 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_0064: 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_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0067: 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_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0026: 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_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: 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_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: 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_00f4: Unknown result type (might be due to invalid IL or missing references) Points.Clear(); float3 val = to - from; float num = math.length(val); if (num < 0.01f) { Points.Add(from); Points.Add(to); return; } float3 val2 = val / num; float3 val3 = math.normalizesafe(math.cross(val2, math.up()), new float3(1f, 0f, 0f)); float3 val4 = math.normalizesafe(math.cross(val3, val2), math.up()); float2 val5 = default(float2); for (int i = 0; i <= 12; i++) { float num2 = (float)i / 12f; float num3 = math.sin(num2 * (float)Math.PI); float num4 = 0.28f * num3; ((float2)(ref val5))..ctor(Random.Range(0f - num4, num4), Random.Range(0f - num4, num4)); Points.Add(from + val2 * (num * num2) + val3 * val5.x + val4 * val5.y); } } } internal static class SpellChain { private static readonly Collider[] Nearby = (Collider[])(object)new Collider[64]; internal static Unit Nearest(Vector3 from, float range, MarkKind mark, List visited) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007d: 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_0083: Unknown result type (might be due to invalid IL or missing references) if (range <= 0f) { return null; } Unit result = null; float num = float.MaxValue; try { int num2 = Physics.OverlapSphereNonAlloc(from, range, Nearby, SpellHitResolver.TargetMask(), (QueryTriggerInteraction)1); for (int i = 0; i < num2; i++) { Collider val = Nearby[i]; if ((Object)(object)val == (Object)null) { continue; } Unit componentInParent = ((Component)val).GetComponentInParent(); if (!((Object)(object)componentInParent == (Object)null) && componentInParent.IsAlive && !visited.Contains(componentInParent) && !(SpellMarks.Read(componentInParent, mark) <= 0f)) { Vector3 val2 = ((Component)componentInParent).transform.position - from; float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude; if (sqrMagnitude < num) { num = sqrMagnitude; result = componentInParent; } } } return result; } catch (Exception ex) { Plugin.Log.LogWarning((object)$"A chain could not look for {mark}: {ex.Message}"); return null; } } } internal static class SpellDamage { internal static DamageTypes ToDamageType(ElementKind element) { return (DamageTypes)(element switch { ElementKind.Fire => 4, ElementKind.Frost => 5, ElementKind.Holy => 6, ElementKind.Dark => 15, ElementKind.Electric => 2, ElementKind.Poison => 9, ElementKind.Explosive => 3, _ => 7, }); } internal static float PlayerShare(ElementKind element) { if (element != ElementKind.Explosive) { return 1f; } return 0.2f; } internal static ProjectileEffect ToProjectileEffect(ElementKind element) { return (ProjectileEffect)(element switch { ElementKind.Fire => 0, ElementKind.Frost => 1, ElementKind.Holy => 29, ElementKind.Dark => 21, ElementKind.Electric => 30, ElementKind.Poison => 3, ElementKind.Explosive => 7, _ => 5, }); } } internal static class SpellDamageScope { internal static int Indirect; internal static int Spell; } internal static class SpellFire { private const string FlameName = "MolotovFireParticle"; private const int MaxLiveFires = 24; private const int MinFlameSize = 4; private const int MaxFlameSize = 8; private const float BurstForce = 15f; private static FireSpreader _template; private static bool _searched; private static bool _reportedMissing; internal static int LiveFires { get; set; } internal static void Clear() { LiveFires = 0; } internal static void Light(Vector3 where, in Reaction rule, int hopsLeft) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) if (LiveFires >= 24) { return; } FireSpreader val = Template(); if ((Object)(object)val == (Object)null) { return; } try { GameObject val2 = Object.Instantiate(((Component)val).gameObject, where + Vector3.up * 0.4f, Quaternion.identity); val2.SetActive(true); FireSpreader component = val2.GetComponent(); if ((Object)(object)component != (Object)null) { component.Initialize(Random.Range(4, 8)); } Burst(val2); LiveFires++; if (hopsLeft > 0 && rule.LiquidReach > 0f) { val2.AddComponent().Configure(in rule, hopsLeft); } else { val2.AddComponent(); } } catch (Exception ex) { Plugin.Log.LogWarning((object)("A fire could not be lit: " + ex.Message)); } } private static void Burst(GameObject flame) { //IL_0041: 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_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_0065: Unknown result type (might be due to invalid IL or missing references) Rigidbody component = flame.GetComponent(); if (!((Object)(object)component == (Object)null)) { component.isKinematic = false; float num = Random.Range(0f, (float)Math.PI * 2f); Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor(Mathf.Cos(num), 0f, Mathf.Sin(num)); component.AddForce((val * Random.Range(0.4f, 1f) + Vector3.up) * 15f, (ForceMode)1); } } private static FireSpreader Template() { if ((Object)(object)_template != (Object)null) { return _template; } if (_searched && (Object)(object)_template == (Object)null) { _searched = false; } _searched = true; try { FireSpreader[] array = Resources.FindObjectsOfTypeAll(); FireSpreader val = null; foreach (FireSpreader val2 in array) { if (!((Object)(object)val2 == (Object)null)) { if ((Object)(object)val == (Object)null) { val = val2; } if (((Object)val2).name.StartsWith("MolotovFireParticle", StringComparison.Ordinal) && !((Component)val2).gameObject.activeInHierarchy) { _template = val2; break; } } } if ((Object)(object)_template == (Object)null) { _template = val; } if ((Object)(object)_template != (Object)null) { Plugin.Log.LogInfo((object)$"Spell fire will copy '{((Object)_template).name}' (of {array.Length} found)."); } else if (!_reportedMissing) { _reportedMissing = true; Plugin.Log.LogWarning((object)"No FireSpreader could be found, so lighting poison will do nothing. The game's Molotov flame is reached by type and name; if it has been renamed, that is where to look."); } } catch (Exception ex) { Plugin.Log.LogWarning((object)("The fire template could not be looked up: " + ex.Message)); } return _template; } } internal sealed class FireTally : MonoBehaviour { private void OnDestroy() { SpellFire.LiveFires = Mathf.Max(0, SpellFire.LiveFires - 1); } } internal sealed class PoisonFireChain : MonoBehaviour { private const float Delay = 0.55f; private static readonly List Found = new List(); private Reaction _rule; private int _hopsLeft; private float _due; private bool _spread; internal void Configure(in Reaction rule, int hopsLeft) { _rule = rule; _hopsLeft = hopsLeft; _due = Time.time + 0.55f; } private void Update() { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) if (_spread || Time.time < _due) { return; } _spread = true; try { int num = SpellLiquid.ConsumePools(((Component)this).transform.position, _rule.LiquidReach, _rule.Consumes, Found); for (int i = 0; i < num; i++) { SpellFire.Light(Found[i], in _rule, _hopsLeft - 1); } } catch (Exception ex) { Plugin.Log.LogWarning((object)("A fire could not spread: " + ex.Message)); } } private void OnDestroy() { SpellFire.LiveFires = Mathf.Max(0, SpellFire.LiveFires - 1); } } internal sealed class SpellHitResolver { private struct PendingReaction { public Reaction Rule; public float Amount; public Vector3 Point; public Unit Caster; public ActiveEmission Source; public Unit Target; } private struct PendingKill { public uint CastSeed; public int Branch; public int Slot; public float3 Point; public float3 Direction; public float MaxHealth; public bool SuppressDamage; public int CasterSlot; public bool Mine; public CastFlags Flags; } private const int MaxOverlap = 128; private const uint PayloadSeedSalt = 461845907u; private static readonly float3 UpAxis = new float3(0f, 1f, 0f); private const float GroundHitDrop = 2.4f; private const float OcclusionLift = 0.5f; private static readonly string[] TargetLayers = new string[4] { "Entities", "Breakable", "Player", "Hitbox" }; private readonly Collider[] _overlap = (Collider[])(object)new Collider[128]; private readonly List _struck = new List(128); private PayloadTable _payloads; private bool _reportedOverlapLimit; private bool _reportedTargeting; private bool _friendlyFire; private SpellRuntime _runtime; private readonly List _reactions = new List(); private static int _unitMask; private static bool _unitMaskResolved; private static int _geometryMask; private static bool _geometryMaskResolved; private readonly List _kills = new List(); private readonly Dictionary _killsBy = new Dictionary(); private readonly List _killsForget = new List(); private static readonly uint KillSalt = 19217u; private const float KillLift = 1f; private const float KillDrop = 2.4f; private readonly List _retireAfterSweep = new List(); private static int _reportedBounces; private const float ArcRestitution = 0.5f; private readonly Dictionary _shoved = new Dictionary(); private readonly List _forget = new List(); private float _lastForget; private readonly RaycastHit[] _beamHits = (RaycastHit[])(object)new RaycastHit[64]; private bool _reportedBeamLimit; internal static event Action KillSettled; internal static event Action KillCredited; private static int UnitMask() { if (_unitMaskResolved) { return _unitMask; } _unitMaskResolved = true; int num = 0; for (int i = 0; i < TargetLayers.Length; i++) { int num2 = LayerMask.NameToLayer(TargetLayers[i]); if (num2 >= 0) { num |= 1 << num2; } } if (num == 0) { Plugin.Log.LogWarning((object)"None of the layers spells damage were found, so area damage falls back to querying every layer. Large effects may drop targets."); num = -1; } _unitMask = num; return _unitMask; } private static int GeometryMask() { if (_geometryMaskResolved) { return _geometryMask; } GameManager instance = StaticInstance.Instance; if ((Object)(object)instance == (Object)null) { return 0; } _geometryMaskResolved = true; _geometryMask = ((LayerMask)(ref instance.geometryLayer)).value; if (_geometryMask == 0) { Plugin.Log.LogWarning((object)"The game reports no geometry layers, so area spells will reach through walls."); } return _geometryMask; } internal void Resolve(SpellRuntime runtime, PayloadTable payloads, float now, float deltaTime, bool friendlyFire) { //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) if (runtime == null || deltaTime <= 0f) { return; } _payloads = payloads; _friendlyFire = friendlyFire; _runtime = runtime; int activeCount = runtime.ActiveCount; _retireAfterSweep.Clear(); for (int i = 0; i < activeCount; i++) { if (!runtime.TryGet(i, out var emission) || now < emission.BirthTime) { continue; } float num = now - emission.BirthTime; try { if (!emission.Spent && emission.Lifetime > 0f && num >= emission.Lifetime && FirePayload(runtime, in emission, PayloadTrigger.OnMiss, SpellRuntime.Evaluate(in emission, num), UpAxis, now)) { emission.Spent = true; runtime.Set(i, in emission); continue; } Unit val = ResolveCaster(emission.CasterSlot); bool flag = !emission.SuppressDamage && (Object)(object)val != (Object)null; if (emission.Consumes && emission.LocalCast && !emission.Raised) { GraveGoods.Draw(in emission, now); } if (emission.Raises && !emission.Raised && num >= emission.RaiseAge) { emission.Raised = true; runtime.Set(i, in emission); Necromancy.Raise(in emission, val, flag); } if (emission.Collision != CollisionKind.None && !emission.Spent) { switch (emission.Delivery) { case DeliveryKind.Projectile: ResolveProjectile(runtime, i, ref emission, val, flag, num, deltaTime, now); break; case DeliveryKind.Descend: ResolveDescend(runtime, i, ref emission, val, flag, num, now); break; case DeliveryKind.Anchored: ResolveAnchored(runtime, i, ref emission, val, flag, num, now); break; } } } catch (Exception arg) { emission.Spent = true; runtime.Set(i, in emission); Plugin.Log.LogError((object)$"Spell hit resolution failed: {arg}"); } } runtime.RetireAll(_retireAfterSweep); _retireAfterSweep.Clear(); FireReactions(); FireKills(runtime, now); } internal static void CreditKill(uint castSeed, float maxHealth) { try { SpellHitResolver.KillCredited?.Invoke(castSeed, maxHealth); } catch (Exception ex) { Plugin.Log.LogError((object)("A kill could not be credited: " + ex.Message)); } } private void QueueKill(in ActiveEmission e, Unit target, float now) { //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_0175: Unknown result type (might be due to invalid IL or missing references) //IL_0177: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_0180: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0121: 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_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0059: 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_0083: Unknown result type (might be due to invalid IL or missing references) int branch = 0; int slot = 0; if (e.KillSlot > 0 && _payloads != null && _payloads.TryGet(e.KillSlot, out var entry) && entry.Trigger == PayloadTrigger.OnKill) { float2 value; float2 val = (_killsBy.TryGetValue(e.Seed, out value) ? value : float2.zero); if (val.x < (float)e.KillBudget) { _killsBy[e.Seed] = new float2(val.x + 1f, now); branch = e.KillSlot - entry.BaseSlot + 1; slot = e.KillSlot; } } float3 val2 = float3.op_Implicit(((Component)target).transform.position); float3 direction; float3 point; if (e.Delivery == DeliveryKind.Projectile) { float3 val3 = default(float3); ((float3)(ref val3))..ctor(e.Direction.x, 0f, e.Direction.z); direction = (float3)((math.lengthsq(val3) > 1E-06f) ? math.normalize(val3) : new float3(0f, 0f, 1f)); point = val2 + UpAxis * 1f; } else { direction = -UpAxis; point = val2 + UpAxis * 2.4f; } _kills.Add(new PendingKill { CastSeed = e.CastSeed, Branch = branch, Slot = slot, Point = point, Direction = direction, MaxHealth = ((target.Stats != null) ? target.Stats.GetAttribute((EntityAttributes)60) : 0f), SuppressDamage = e.SuppressDamage, CasterSlot = e.CasterSlot, Mine = e.LocalCast, Flags = e.Flags }); } private void FireKills(SpellRuntime runtime, float now) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0173: Unknown result type (might be due to invalid IL or missing references) if (_killsBy.Count > 256) { foreach (KeyValuePair item in _killsBy) { if (now - item.Value.y > 60f) { _killsForget.Add(item.Key); } } for (int i = 0; i < _killsForget.Count; i++) { _killsBy.Remove(_killsForget[i]); } _killsForget.Clear(); } for (int j = 0; j < _kills.Count; j++) { PendingKill pendingKill = _kills[j]; if (pendingKill.Branch >= 0 && pendingKill.Branch <= 65535) { bool flag = pendingKill.Branch > 0 && FireKillBranch(runtime, pendingKill.CastSeed, (ushort)pendingKill.Branch, pendingKill.Slot, pendingKill.Point, pendingKill.Direction, now, CastAuthority.Inherited(pendingKill.SuppressDamage, pendingKill.CasterSlot, pendingKill.Mine), pendingKill.Flags); if (pendingKill.Mine) { CreditKill(pendingKill.CastSeed, pendingKill.MaxHealth); } try { SpellHitResolver.KillSettled?.Invoke(pendingKill.CastSeed, (ushort)pendingKill.Branch, pendingKill.Point, pendingKill.Direction, pendingKill.MaxHealth, pendingKill.Mine); } catch (Exception ex) { Plugin.Log.LogError((object)("A kill could not be announced: " + ex.Message)); } Plugin.Log.LogInfo((object)($"A spell's own blow killed: cast {pendingKill.CastSeed}, mine={pendingKill.Mine}, " + ((pendingKill.Branch > 0) ? ($"branch {pendingKill.Branch} " + (flag ? "played here." : "not played.")) : "no branch."))); } } _kills.Clear(); } internal bool ReplayKill(SpellRuntime runtime, uint castSeed, ushort branch, float3 point, float3 direction, float now) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) if (_payloads == null || !RecentCasts.TryGet(castSeed, now, out var record)) { return false; } int slot = PayloadTable.Resolve(branch, record.BaseSlot); if (!_payloads.TryGet(slot, out var entry) || entry.BaseSlot != record.BaseSlot || entry.Trigger != PayloadTrigger.OnKill) { return false; } return FireKillBranch(runtime, castSeed, branch, slot, point, direction, now, CastAuthority.Inherited(record.SuppressDamage, record.CasterSlot, record.Mine), record.Flags); } private bool FireKillBranch(SpellRuntime runtime, uint castSeed, ushort branch, int slot, float3 point, float3 direction, float now, CastAuthority authority, CastFlags flags) { //IL_001c: 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_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: 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_00ab: Unknown result type (might be due to invalid IL or missing references) if (slot <= 0 || runtime == null) { return false; } return FirePayload(runtime, new ActiveEmission { Delivery = DeliveryKind.Projectile, Direction = direction, HitRadius = 0.05f, KillSlot = slot, Seed = (castSeed ^ KillSalt ^ (uint)(branch * -1640531535) ^ math.hash(math.round(point * 100f))), SuppressDamage = authority.SuppressDamage, CasterSlot = authority.CasterSlot, LocalCast = authority.Mine, CastSeed = castSeed, Flags = flags }, PayloadTrigger.OnKill, point, -direction, now); } private void ResolveProjectile(SpellRuntime runtime, int index, ref ActiveEmission e, Unit caster, bool damages, float age, float deltaTime, float now) { //IL_0012: 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_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: 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_0026: 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_0049: 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_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0053: 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_005c: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_01cc: Unknown result type (might be due to invalid IL or missing references) //IL_01d1: Unknown result type (might be due to invalid IL or missing references) //IL_01d8: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01ef: Unknown result type (might be due to invalid IL or missing references) //IL_01f4: Unknown result type (might be due to invalid IL or missing references) //IL_01f7: Unknown result type (might be due to invalid IL or missing references) //IL_0331: Unknown result type (might be due to invalid IL or missing references) //IL_0338: Unknown result type (might be due to invalid IL or missing references) //IL_0249: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_018d: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_01a0: 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_03aa: Unknown result type (might be due to invalid IL or missing references) //IL_03af: Unknown result type (might be due to invalid IL or missing references) //IL_0385: Unknown result type (might be due to invalid IL or missing references) //IL_038a: Unknown result type (might be due to invalid IL or missing references) //IL_0369: Unknown result type (might be due to invalid IL or missing references) //IL_03d3: Unknown result type (might be due to invalid IL or missing references) //IL_03d8: Unknown result type (might be due to invalid IL or missing references) //IL_03df: Unknown result type (might be due to invalid IL or missing references) //IL_03e4: Unknown result type (might be due to invalid IL or missing references) //IL_02dc: Unknown result type (might be due to invalid IL or missing references) //IL_02f7: Unknown result type (might be due to invalid IL or missing references) //IL_02fc: Unknown result type (might be due to invalid IL or missing references) //IL_040c: Unknown result type (might be due to invalid IL or missing references) float num = math.max(0f, age - deltaTime); float3 val = SpellRuntime.Evaluate(in e, num); float3 val2 = SpellRuntime.Evaluate(in e, age) - val; float num2 = math.length(val2); if (num2 < 0.0001f) { return; } float num3 = math.max(e.HitRadius, 0.05f); float3 val3 = val2 / num2; float3 val4 = val; float num4 = num2; RaycastHit hit; Unit val5; bool flag; while (true) { if (!Sweep(val4, num3, val3, num4, e.IgnoreUnit, out hit)) { return; } val5 = ((Component)((RaycastHit)(ref hit)).collider).GetComponentInParent(); if ((Object)(object)val5 != (Object)null && IsShield(val5, ((RaycastHit)(ref hit)).point, num3)) { val5 = null; } flag = (Object)(object)val5 != (Object)null && val5.IsAlive; if (!flag || e.PierceLeft <= 0 || e.Bursts) { break; } if (damages && !IsExcluded(val5, caster, e.Flags)) { Strike(val5, caster, in e, ((RaycastHit)(ref hit)).point, ((RaycastHit)(ref hit)).normal); } int instanceID = ((Object)val5).GetInstanceID(); SpellAudio.Hit(e.Element, e.Voice, float3.op_Implicit(((RaycastHit)(ref hit)).point), e.Power); FirePayload(runtime, in e, PayloadTrigger.OnHit, float3.op_Implicit(((RaycastHit)(ref hit)).point), float3.op_Implicit(((RaycastHit)(ref hit)).normal), now, downward: false, instanceID); e.PierceLeft--; e.Damage *= 0.7f; e.IgnoreUnit = instanceID; e.Pierced = true; e.MissSlot = 0; runtime.Set(index, in e); val4 += val3 * ((RaycastHit)(ref hit)).distance; num4 -= ((RaycastHit)(ref hit)).distance; if (num4 <= 0.0001f) { return; } } if (e.Bursts) { if (damages) { float3 centre = float3.op_Implicit(((RaycastHit)(ref hit)).point) + float3.op_Implicit(((RaycastHit)(ref hit)).normal) * (num3 + 0.1f); StrikeArea(centre, (e.ImpactRadius > 0f) ? e.ImpactRadius : (num3 * 4f), in e, caster, val5); } } else if ((Object)(object)val5 != (Object)null && damages && !IsExcluded(val5, caster, e.Flags)) { Strike(val5, caster, in e, ((RaycastHit)(ref hit)).point, ((RaycastHit)(ref hit)).normal); } if (!e.Bursts && e.BounceLeft > 0 && (Object)(object)val5 == (Object)null && (Object)(object)((RaycastHit)(ref hit)).collider != (Object)null && CanBounce(e.Motion) && ((1 << ((Component)((RaycastHit)(ref hit)).collider).gameObject.layer) & GeometryMask()) != 0) { float num5 = num2 - num4 + ((RaycastHit)(ref hit)).distance; float age2 = num + deltaTime * math.saturate(num5 / num2); Rebound(runtime, index, ref e, hit, num3, age2, caster); SpellAudio.Impact(e.Element, e.Voice, float3.op_Implicit(((RaycastHit)(ref hit)).point), e.Power, ((RaycastHit)(ref hit)).collider); return; } e.Spent = true; runtime.Set(index, in e); SpellLiquid.Spill(e.Element, e.Spill, ((RaycastHit)(ref hit)).point, ((RaycastHit)(ref hit)).normal, caster, damages, e.Seed); if (damages && ((Object)(object)val5 == (Object)null || !val5.IsPetrified)) { SpellReactor.Arrive(runtime, in e, caster, ((RaycastHit)(ref hit)).point); } if (flag) { SpellAudio.Hit(e.Element, e.Voice, float3.op_Implicit(((RaycastHit)(ref hit)).point), e.Power); } else { SpellAudio.Impact(e.Element, e.Voice, float3.op_Implicit(((RaycastHit)(ref hit)).point), e.Power, ((RaycastHit)(ref hit)).collider); } FirePayload(runtime, in e, (!flag) ? PayloadTrigger.OnMiss : PayloadTrigger.OnHit, float3.op_Implicit(((RaycastHit)(ref hit)).point), float3.op_Implicit(((RaycastHit)(ref hit)).normal), now, downward: false, (flag && e.Pierced) ? ((Object)val5).GetInstanceID() : 0); SpawnImpact(runtime, in e, ((RaycastHit)(ref hit)).point, (e.ImpactRadius > 0f) ? e.ImpactRadius : (num3 * 4f)); _retireAfterSweep.Add(index); } private static void Rebound(SpellRuntime runtime, int index, ref ActiveEmission e, RaycastHit hit, float radius, float age, Unit caster) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: 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) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0074: 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_007b: 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_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0042: 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_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0054: 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_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0067: 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_008e: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: 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_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Unknown result type (might be due to invalid IL or missing references) float3 val = math.normalizesafe(float3.op_Implicit(((RaycastHit)(ref hit)).normal), UpAxis); float3 val2 = e.Direction * e.Speed; float3 val3; if (e.Motion == MotionKind.Arc) { val2 += new float3(0f, -9.8f, 0f) * age; float num = math.dot(val2, val); val3 = val2 - 1.5f * num * val; } else { val3 = val2 - 2f * math.dot(val2, val) * val; } float num2 = math.length(val3); if (num2 < 0.5f) { num2 = math.max(e.Speed, 0.5f); val3 = val * num2; } e.Origin = float3.op_Implicit(((RaycastHit)(ref hit)).point) + val * (radius + 0.02f); e.Direction = val3 / num2; e.Speed = num2; e.Lifetime = math.max(0.05f, e.Lifetime - age); e.BirthTime += age; e.BounceLeft--; e.IgnoreUnit = (((Object)(object)caster != (Object)null) ? ((Object)caster).GetInstanceID() : 0); runtime.Set(index, in e); if (_reportedBounces < 3) { _reportedBounces++; Plugin.Log.LogInfo((object)$"A projectile glanced off '{((Object)((RaycastHit)(ref hit)).collider).name}' at {float3.op_Implicit(((RaycastHit)(ref hit)).point)}, {e.BounceLeft} bounce(s) left."); } } internal static bool CanBounce(MotionKind motion) { if (motion != MotionKind.Straight && motion != MotionKind.Arc) { return motion == MotionKind.Homing; } return true; } private void ResolveDescend(SpellRuntime runtime, int index, ref ActiveEmission e, Unit caster, bool damages, float age, float now) { //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //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_00d3: Unknown result type (might be due to invalid IL or missing references) if (age < e.ArrivalDelay) { return; } bool flag = e.TickInterval > 0f; if (flag) { e.Delivery = DeliveryKind.Anchored; } else { e.Spent = true; } runtime.Set(index, in e); if (!flag) { FirePayload(runtime, in e, PayloadTrigger.OnHit, e.Origin, UpAxis, now); } SpellAudio.Impact(e.Element, e.Voice, e.Origin, e.Power); SpellLiquid.Spill(e.Element, e.Spill, float3.op_Implicit(e.Origin), Vector3.up, caster, damages, e.Seed); if (damages) { SpellReactor.Arrive(runtime, in e, caster, float3.op_Implicit(e.Origin)); if (!flag) { float radius = ((e.ImpactRadius > 0f) ? e.ImpactRadius : 3f); StrikeArea(e.Origin, radius, in e, caster); } } } private void ResolveAnchored(SpellRuntime runtime, int index, ref ActiveEmission e, Unit caster, bool damages, float age, float now) { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: 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_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) if (e.TickInterval <= 0f || age < e.NextTickAge) { return; } do { e.NextTickAge += e.TickInterval; } while (e.NextTickAge <= age); runtime.Set(index, in e); if (!SpellAmbience.Covers(in e)) { SpellAudio.Tick(e.Element, e.Voice, e.Origin, e.Power); } float radius = ((e.HitRadius > 0f) ? e.HitRadius : e.Scale); if (e.HitSlot > 0 && e.HitsLeft > 0 && FindHostileInside(e.Origin, radius, out var feet) && FirePayload(runtime, in e, PayloadTrigger.OnHit, float3.op_Implicit(feet + Vector3.up * 2.4f), UpAxis, now, downward: true)) { e.HitsLeft--; e.MissSlot = 0; runtime.Set(index, in e); } if (damages) { if (e.MarkOnly) { MarkArea(e.Origin, radius, in e, caster); } else { StrikeArea(e.Origin, radius, in e, caster); } } } private bool FirePayload(SpellRuntime runtime, in ActiveEmission carrier, PayloadTrigger trigger, float3 point, float3 normal, float now, bool downward = false, int ignoreUnit = 0) { //IL_0046: 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_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0054: 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_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_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) int num = trigger switch { PayloadTrigger.OnKill => carrier.KillSlot, PayloadTrigger.OnHit => carrier.HitSlot, _ => carrier.MissSlot, }; if (num == 0 || _payloads == null) { return false; } if (!_payloads.TryGet(num, out var entry) || entry.Trigger != trigger) { return false; } float3 val = ((math.lengthsq(normal) > 1E-06f) ? math.normalize(normal) : UpAxis); float num2 = ((carrier.Delivery == DeliveryKind.Projectile) ? (math.max(carrier.HitRadius, 0.05f) + 0.3f) : 0.3f); float3 val2 = (downward ? (-UpAxis) : ((carrier.Delivery == DeliveryKind.Projectile) ? carrier.Direction : UpAxis)); if (math.lengthsq(val2) < 1E-06f) { val2 = UpAxis; } SpellCaster.CastPayload(in entry, runtime, new CastTarget { Origin = point + val * num2, Direction = math.normalize(val2), Point = (NeedsGround(in entry) ? CastTrace.Below(float3.op_Implicit(point), 30f, float3.op_Implicit(point)) : point), HasPoint = true }, (uint)((int)(carrier.Seed ^ 0x1B873593) + carrier.HitsLeft * -1640531535 + carrier.PierceLeft * 40503), now, Plugin.VoxelDensity.Value, CastAuthority.Inherited(carrier.SuppressDamage, carrier.CasterSlot, carrier.LocalCast), _payloads, ignoreUnit, carrier.CastSeed, carrier.Flags); return true; } private static bool NeedsGround(in PayloadTable.Entry payload) { IReadOnlyList emissions = payload.Emissions; if (emissions == null) { return false; } for (int i = 0; i < emissions.Count; i++) { if (emissions[i].Delivery.Kind != DeliveryKind.Projectile) { return true; } } return false; } private void StrikeArea(float3 centre, float radius, in ActiveEmission e, Unit caster, Unit applied = null) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_006f: 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_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01a6: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_01ac: Unknown result type (might be due to invalid IL or missing references) //IL_01b1: Unknown result type (might be due to invalid IL or missing references) //IL_01b9: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_0117: 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) //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) ReportTargetingOnce(); int num = Physics.OverlapSphereNonAlloc(float3.op_Implicit(centre), radius, _overlap, UnitMask(), (QueryTriggerInteraction)1); if (num >= 128 && !_reportedOverlapLimit) { _reportedOverlapLimit = true; Plugin.Log.LogWarning((object)($"A spell area query filled all {128} slots at radius {radius:0.#}. " + "Targets beyond that were not considered, so some damage was dropped.")); } _struck.Clear(); Vector3 eye = float3.op_Implicit(centre) + Vector3.up * 0.5f; int occlusionMask = GeometryMask(); for (int i = 0; i < num; i++) { Collider val = _overlap[i]; if (!((Object)(object)val == (Object)null)) { Unit componentInParent = ((Component)val).GetComponentInParent(); if (!((Object)(object)componentInParent == (Object)null) && !IsExcluded(componentInParent, caster, e.Flags) && !_struck.Contains(componentInParent) && (!((Object)(object)componentInParent != (Object)(object)applied) || !IsOccluded(eye, val, occlusionMask))) { _struck.Add(componentInParent); Vector3 val2 = val.ClosestPoint(float3.op_Implicit(centre)); Vector3 normal = val2 - float3.op_Implicit(centre); normal = ((((Vector3)(ref normal)).sqrMagnitude > 1E-06f) ? ((Vector3)(ref normal)).normalized : Vector3.up); Strike(componentInParent, caster, in e, val2, normal); } } } if ((Object)(object)applied != (Object)null && !_struck.Contains(applied) && !IsExcluded(applied, caster, e.Flags)) { _struck.Add(applied); Vector3 position = ((Component)applied).transform.position; Vector3 val3 = position - float3.op_Implicit(centre); Strike(applied, caster, in e, position, (((Vector3)(ref val3)).sqrMagnitude > 1E-06f) ? ((Vector3)(ref val3)).normalized : Vector3.up); } } private void Strike(Unit target, Unit caster, in ActiveEmission e, Vector3 point, Vector3 normal) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0059: 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_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008e: 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_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //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_017d: Unknown result type (might be due to invalid IL or missing references) //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_024d: Unknown result type (might be due to invalid IL or missing references) //IL_0278: Unknown result type (might be due to invalid IL or missing references) //IL_0280: 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) //IL_0294: Unknown result type (might be due to invalid IL or missing references) //IL_031d: Unknown result type (might be due to invalid IL or missing references) //IL_031f: Unknown result type (might be due to invalid IL or missing references) //IL_0324: Unknown result type (might be due to invalid IL or missing references) //IL_0326: Unknown result type (might be due to invalid IL or missing references) //IL_032b: Unknown result type (might be due to invalid IL or missing references) //IL_032d: Unknown result type (might be due to invalid IL or missing references) //IL_0331: Unknown result type (might be due to invalid IL or missing references) //IL_0337: Unknown result type (might be due to invalid IL or missing references) //IL_03c7: Unknown result type (might be due to invalid IL or missing references) //IL_03e7: Unknown result type (might be due to invalid IL or missing references) //IL_03ed: Unknown result type (might be due to invalid IL or missing references) //IL_03ef: Unknown result type (might be due to invalid IL or missing references) //IL_03f6: Expected O, but got Unknown //IL_041d: Unknown result type (might be due to invalid IL or missing references) if (!(e.Damage <= 0f)) { Reaction rule = default(Reaction); float amount = 0f; bool flag = !target.IsPetrified && SpellReactor.Pending(target, in e, out rule, out amount); bool flag2 = (Object)(object)caster != (Object)null && (Object)(object)target == (Object)(object)caster; DamageTypes val = (DamageTypes)(flag2 ? 14 : ((int)SpellDamage.ToDamageType(e.Element))); ProjectileRay val2 = default(ProjectileRay); ((ProjectileRay)(ref val2))..ctor(float3.op_Implicit(point), (ProjectileTypes)5); val2.radius = math.max(e.HitRadius, 0.05f); val2.effect = SpellDamage.ToProjectileEffect(e.Element); val2.shotOrLastBounceFrom = e.Origin; bool flag3 = e.Push != 0f && !flag2 && !e.SuppressDamage && target is Npc && FirstShove(e.CastSeed, target); val2.barrelPosition = e.Origin; val2.startTime = Time.time; val2.ownerInstID = ((Object)caster).GetInstanceID(); val2.playImpactSounds = true; float num = (flag2 ? (e.Damage * SpellDamage.PlayerShare(e.Element)) : e.Damage); ref FixedList32Bytes damageComps = ref val2.damageComps; ProjectileDamage val3 = new ProjectileDamage(num, val, 0f); damageComps.Add(ref val3); ProjectileData val4 = new ProjectileData { damageType = val, caliber = (CaliberTypes)0, isPlayer = caster.isPlayer, sourceUnit = caster, ownerPosition = float3.op_Implicit(((Component)caster).transform.position), explicitDamage = 0f }; EntityAttributes val5 = SpellMarks.ToStatus(e.Mark); bool flag4 = e.MarkOnce && SpellMarks.Read(target, e.Mark) > 0f; float num2 = 0f; if ((e.Flags & CastFlags.Nail) != CastFlags.None && !flag2 && !e.SuppressDamage && SpellDamageScope.Indirect <= 0 && !target.IsPetrified) { num2 = NailLedger.Cash(target, e.CastSeed); } float num3 = (SpellMarks.TopsUp(e.Mark) ? (e.MarkAmount - SpellMarks.Read(target, e.Mark)) : e.MarkAmount); bool flag5 = e.Mark == MarkKind.Hex && target.Stats != null && target.Stats.GetStatus((EntityAttributes)20) > 0f; bool flag6 = (int)val5 != 0 && num3 > 0f && !flag4 && !flag2 && !flag5; if (flag6) { ref FixedList32Bytes modifiersOnHit = ref val4.modifiersOnHit; ModifierData val6 = new ModifierData { attribute = val5, value = num3, modType = (StatModType)100, procChance = 100f }; modifiersOnHit.Add(ref val6); } if (flag6 && e.Mark == MarkKind.Brand) { NailLedger.Branded(target, e.CastSeed); } bool flag7 = !flag2 && !e.SuppressDamage && SpellDamageScope.Indirect <= 0 && target.IsAlive && target.IsHostileTo((FactionIds)16) && (target.Stats == null || target.Stats.GetStatus((EntityAttributes)20) <= 0f); SpellDamageScope.Spell++; try { ProjectileUtilities.ProcessUnitHit(float3.op_Implicit(point), float3.op_Implicit(normal), val2, val4, default(ShapeId), target, caster); } finally { SpellDamageScope.Spell--; } if (flag7 && !target.IsAlive) { QueueKill(in e, target, Time.time); } if (num2 > 0f && target.IsAlive) { ActiveEmission e2 = e; e2.Damage = num2; e2.Element = ElementKind.Holy; e2.Mark = MarkKind.None; e2.MarkAmount = 0f; e2.Push = 0f; e2.NoReaction = true; e2.Flags = CastFlags.None; StrikeUnit(target, caster, in e2, point); } if (flag6 && e.Mark == MarkKind.Hex) { HexLinks.Linked(caster, target); } if (flag3) { Shove((Npc)target, in e, point, normal); } ReportAttacker(target, caster, flag2); if (flag && _runtime != null && SpellReactor.Spend(target, in rule, e.Seed)) { QueueReaction(in rule, amount, point, caster, in e, target); } } } private void MarkArea(float3 centre, float radius, in ActiveEmission e, Unit caster) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: 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_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) if (e.MarkAmount <= 0f) { return; } int num = Physics.OverlapSphereNonAlloc(float3.op_Implicit(centre), radius, _overlap, UnitMask(), (QueryTriggerInteraction)1); Vector3 eye = float3.op_Implicit(centre) + Vector3.up * 0.5f; int occlusionMask = GeometryMask(); _struck.Clear(); for (int i = 0; i < num; i++) { Collider val = _overlap[i]; Unit val2 = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponentInParent() : null); if ((Object)(object)val2 == (Object)null || _struck.Contains(val2) || val2.isPlayer || !val2.IsAlive) { continue; } Npc val3 = (Npc)(object)((val2 is Npc) ? val2 : null); if (val3 != null && !((Unit)val3).IsProtectedNpc && val2.IsHostileTo((FactionIds)16) && (val2.Stats == null || !(val2.Stats.GetStatus((EntityAttributes)20) > 0f)) && !IsOccluded(eye, val, occlusionMask)) { _struck.Add(val2); float num2 = e.MarkAmount - SpellMarks.Read(val2, e.Mark); if (num2 > 0f) { SpellMarks.Apply(val2, e.Mark, num2, caster); } if ((e.Flags & CastFlags.Vigil) != CastFlags.None) { VigilLedger.Record(val2, e.Mark, caster); } } } } private bool FindHostileInside(float3 centre, float radius, out Vector3 feet) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0020: 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_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0030: 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) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) feet = default(Vector3); int num = Physics.OverlapSphereNonAlloc(float3.op_Implicit(centre), radius, _overlap, UnitMask(), (QueryTriggerInteraction)1); Vector3 eye = float3.op_Implicit(centre) + Vector3.up * 0.5f; int occlusionMask = GeometryMask(); float num2 = float.MaxValue; for (int i = 0; i < num; i++) { Collider val = _overlap[i]; Unit val2 = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponentInParent() : null); if ((Object)(object)val2 == (Object)null || val2.isPlayer || !val2.IsAlive) { continue; } Npc val3 = (Npc)(object)((val2 is Npc) ? val2 : null); if (val3 != null && !((Unit)val3).IsProtectedNpc && val2.IsHostileTo((FactionIds)16) && (val2.Stats == null || !(val2.Stats.GetStatus((EntityAttributes)20) > 0f)) && !IsOccluded(eye, val, occlusionMask)) { Vector3 position = ((Component)val2).transform.position; Vector3 val4 = float3.op_Implicit(centre) - position; float sqrMagnitude = ((Vector3)(ref val4)).sqrMagnitude; if (sqrMagnitude < num2) { num2 = sqrMagnitude; feet = position; } } } return num2 < float.MaxValue; } private static bool Sweep(float3 from, float radius, float3 direction, float distance, int ignore, out RaycastHit hit) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0086: 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_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //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) Vector3 val = float3.op_Implicit(from); float num = distance; for (int i = 0; i < 4; i++) { if (!Physics.SphereCast(val, radius, float3.op_Implicit(direction), ref hit, num, -1, (QueryTriggerInteraction)1)) { return false; } Unit val2 = ((ignore != 0) ? ((Component)((RaycastHit)(ref hit)).collider).GetComponentInParent() : null); if ((Object)(object)val2 == (Object)null || ((Object)val2).GetInstanceID() != ignore) { return true; } float num2 = ((RaycastHit)(ref hit)).distance + 0.02f; val += float3.op_Implicit(direction) * num2; num -= num2; if (num <= 0f) { break; } } hit = default(RaycastHit); return false; } private bool FirstShove(uint castSeed, Unit target) { float time = Time.time; if (_shoved.Count > 256 && time - _lastForget > 5f) { _lastForget = time; _forget.Clear(); foreach (KeyValuePair item in _shoved) { if (time - item.Value > 30f) { _forget.Add(item.Key); } } for (int i = 0; i < _forget.Count; i++) { _shoved.Remove(_forget[i]); } } long key = (long)(((ulong)castSeed << 32) | (uint)((Object)target).GetInstanceID()); if (_shoved.ContainsKey(key)) { return false; } _shoved[key] = time; return true; } private static void Shove(Npc npc, in ActiveEmission e, Vector3 point, Vector3 normal) { //IL_0010: 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_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_011e: 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_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: 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_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) Vector3 val = ((e.Delivery == DeliveryKind.Projectile && !e.Bursts) ? float3.op_Implicit(e.Direction) : normal); val.y = 0f; if (((Vector3)(ref val)).sqrMagnitude < 0.04f) { val = ((Component)npc).transform.position - float3.op_Implicit(e.Origin); val.y = 0f; } if (!(((Vector3)(ref val)).sqrMagnitude < 0.0001f)) { ((Vector3)(ref val)).Normalize(); float num = math.abs(e.Push) * 80f; if (e.Push < 0f) { val = -val; Vector3 val2 = ((Component)npc).transform.position - float3.op_Implicit(e.Origin); val2.y = 0f; float num2 = ((e.HitRadius > 0f) ? e.HitRadius : 3f); num *= Mathf.Clamp(((Vector3)(ref val2)).magnitude / num2, 0.25f, 1f); } float num3 = Mathf.Lerp(100f, 500f, Mathf.InverseLerp(80f, 960f, num)); npc.ReceiveKnockback(val, num, num3, true, false); } } private static bool IsShield(Unit target, Vector3 point, float radius) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Invalid comparison between Unknown and I4 Hitmesh hitmesh = target.hitmesh; ShapeId val = default(ShapeId); Vector3 val2 = default(Vector3); if ((Object)(object)hitmesh != (Object)null && hitmesh.hitboxFrameIndex != -1 && hitmesh.PointInShape(float3.op_Implicit(point), ref val, ref val2, radius)) { return (int)((ShapeId)(ref val)).part == 1; } return false; } private static void ReportAttacker(Unit target, Unit caster, bool self) { //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) if (self || (Object)(object)caster == (Object)null || caster.isPlayer) { return; } Npc val = (Npc)(object)((target is Npc) ? target : null); if (val != null && !((Object)(object)val.AiAgent == (Object)null) && ((Unit)val).IsAlive) { val.AiAgent.ReportLastSeen(caster, ((Component)caster).transform.position, ((Component)val).transform.position, true); if (!val.hasBeenAggroedOnce) { val.OnFirstAggro(); } } } internal void QueueReaction(in Reaction rule, float amount, Vector3 point, Unit caster, in ActiveEmission source, Unit target = null) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) _reactions.Add(new PendingReaction { Rule = rule, Amount = amount, Point = point, Caster = caster, Source = source, Target = target }); } private void FireReactions() { //IL_0047: Unknown result type (might be due to invalid IL or missing references) if (_reactions.Count == 0) { return; } for (int i = 0; i < _reactions.Count; i++) { PendingReaction pendingReaction = _reactions[i]; try { SpellReactor.Fire(_runtime, this, pendingReaction.Caster, pendingReaction.Target, in pendingReaction.Source, in pendingReaction.Rule, pendingReaction.Amount, pendingReaction.Point); } catch (Exception arg) { Plugin.Log.LogError((object)$"An element reaction failed: {arg}"); } } _reactions.Clear(); } internal void CopyStruck(List into) { into.Clear(); into.AddRange(_struck); } internal void StrikeReaction(float3 centre, float radius, in ActiveEmission burst, Unit caster) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) SpellDamageScope.Indirect++; try { StrikeArea(centre, radius, in burst, caster); } finally { SpellDamageScope.Indirect--; } } internal float StrikeBeam(float3 origin, float3 direction, float reach, in ActiveEmission e) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) SpellDamageScope.Indirect++; try { return StrikeBeamOnce(origin, direction, reach, in e); } finally { SpellDamageScope.Indirect--; } } private float StrikeBeamOnce(float3 origin, float3 direction, float reach, in ActiveEmission e) { //IL_0020: 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_0026: 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_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_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0038: 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_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0057: 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_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) Unit val = ResolveCaster(e.CasterSlot); if ((Object)(object)val == (Object)null) { return MeasureBeam(origin, direction, reach); } Vector3 val2 = float3.op_Implicit(origin); Vector3 val3 = float3.op_Implicit(direction); Vector3 normalized = ((Vector3)(ref val3)).normalized; float num = MeasureBeam(origin, direction, reach); float num2 = math.max(e.HitRadius, 0.15f); int num3 = Physics.SphereCastNonAlloc(val2, num2, normalized, _beamHits, num, UnitMask(), (QueryTriggerInteraction)1); if (num3 >= _beamHits.Length && !_reportedBeamLimit) { _reportedBeamLimit = true; Plugin.Log.LogWarning((object)($"A beam filled all {_beamHits.Length} of its hit slots. Anything past that " + "was not struck.")); } _struck.Clear(); for (int i = 0; i < num3; i++) { Collider collider = ((RaycastHit)(ref _beamHits[i])).collider; if (!((Object)(object)collider == (Object)null)) { Unit componentInParent = ((Component)collider).GetComponentInParent(); if (!((Object)(object)componentInParent == (Object)null) && !_struck.Contains(componentInParent) && !IsExcluded(componentInParent, val, e.Flags)) { _struck.Add(componentInParent); Vector3 point = collider.ClosestPoint(val2 + normalized * ((RaycastHit)(ref _beamHits[i])).distance); Strike(componentInParent, val, in e, point, -normalized); } } } return num; } internal float MeasureBeam(float3 origin, float3 direction, float reach) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0012: 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_001a: Unknown result type (might be due to invalid IL or missing references) int num = GeometryMask(); if (num == 0) { return reach; } Vector3 val = float3.op_Implicit(origin); Vector3 val2 = float3.op_Implicit(direction); RaycastHit val3 = default(RaycastHit); if (!Physics.Raycast(val, ((Vector3)(ref val2)).normalized, ref val3, reach, num, (QueryTriggerInteraction)1)) { return reach; } return ((RaycastHit)(ref val3)).distance; } internal void StrikeUnit(Unit target, Unit caster, in ActiveEmission e, Vector3 point) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) SpellDamageScope.Indirect++; try { StrikeUnitOnce(target, caster, in e, point); } finally { SpellDamageScope.Indirect--; } } private void StrikeUnitOnce(Unit target, Unit caster, in ActiveEmission e, Vector3 point) { //IL_0023: 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_0030: 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_004d: 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_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)target == (Object)null) && !((Object)(object)caster == (Object)null) && !IsExcluded(target, caster, e.Flags)) { Vector3 normal = point - ((Component)target).transform.position; normal = ((((Vector3)(ref normal)).sqrMagnitude > 1E-06f) ? ((Vector3)(ref normal)).normalized : Vector3.up); Strike(target, caster, in e, point, normal); } } internal static int TargetMask() { return UnitMask(); } internal static Unit NearestEnemyInSight(Vector3 centre, float reach, Unit except, Func accept) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //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_0023: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: 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_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) Collider[] array = Physics.OverlapSphere(centre, reach, UnitMask(), (QueryTriggerInteraction)1); Vector3 eye = centre + Vector3.up * 0.5f; int occlusionMask = GeometryMask(); Unit result = null; float num = float.MaxValue; foreach (Collider val in array) { Unit val2 = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponentInParent() : null); if ((Object)(object)val2 == (Object)null || (Object)(object)val2 == (Object)(object)except || val2.isPlayer || !val2.IsAlive) { continue; } Npc val3 = (Npc)(object)((val2 is Npc) ? val2 : null); if (val3 != null && !((Unit)val3).IsProtectedNpc && val2.IsHostileTo((FactionIds)16) && (val2.Stats == null || !(val2.Stats.GetStatus((EntityAttributes)20) > 0f)) && (accept == null || accept(val2)) && !IsOccluded(eye, val, occlusionMask)) { Vector3 val4 = ((Component)val2).transform.position - centre; float sqrMagnitude = ((Vector3)(ref val4)).sqrMagnitude; if (sqrMagnitude < num) { num = sqrMagnitude; result = val2; } } } return result; } private static bool IsOccluded(Vector3 eye, Collider collider, int occlusionMask) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: 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_002f: Unknown result type (might be due to invalid IL or missing references) if (occlusionMask == 0) { return false; } Bounds bounds = collider.bounds; Vector3 val = ((Bounds)(ref bounds)).center - eye; float magnitude = ((Vector3)(ref val)).magnitude; if (magnitude < 0.01f) { return false; } return Physics.Raycast(eye, val / magnitude, magnitude, occlusionMask); } private bool IsExcluded(Unit target, Unit caster, CastFlags flags) { if ((Object)(object)target == (Object)null) { return true; } if ((Object)(object)target == (Object)(object)caster) { if ((flags & CastFlags.Spare) == 0) { return !Plugin.SelfDamage.Value; } return true; } if (!_friendlyFire && IsRosterPlayer(target)) { return IsRosterPlayer(caster); } return false; } private static bool IsRosterPlayer(Unit unit) { if ((Object)(object)unit == (Object)null) { return false; } GameManager instance = StaticInstance.Instance; if ((Object)(object)instance == (Object)null) { return false; } if ((Object)(object)instance.PlayerUnit == (Object)(object)unit) { return true; } List players = instance.Players; if (players == null) { return false; } for (int i = 0; i < players.Count; i++) { Player val = players[i]; if ((Object)(object)val != (Object)null && (Object)(object)val.playerUnit == (Object)(object)unit) { return true; } } return false; } private static void SpawnImpact(SpellRuntime runtime, in ActiveEmission source, Vector3 point, float radius) { //IL_0023: 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_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) ActiveEmission emission = new ActiveEmission { Delivery = DeliveryKind.Anchored, Pattern = VoxelPattern.Burst, Intensity = IntensityCurve.FadeOut, Origin = float3.op_Implicit(point), BirthTime = Time.time, Lifetime = 0.4f, Scale = math.max(radius, 0.5f), Power = source.Power, Color = source.Color, CoreColor = new float3(1f, 1f, 1f), VoxelCount = math.max(source.VoxelCount / 2, 60), Seed = (source.Seed ^ 0xB5297A4Du) }; runtime.TryAdd(in emission); } private static Unit ResolveCaster(int casterSlot) { GameManager instance = StaticInstance.Instance; if ((Object)(object)instance == (Object)null) { return null; } if (casterSlot <= 0) { return instance.PlayerUnit; } List players = instance.Players; int num = casterSlot - 1; if (players == null || num >= players.Count) { return null; } Player val = players[num]; if (!((Object)(object)val != (Object)null)) { return null; } return val.playerUnit; } private void ReportTargetingOnce() { if (_reportedTargeting) { return; } _reportedTargeting = true; try { GameManager instance = StaticInstance.Instance; Unit unit = (((Object)(object)instance != (Object)null) ? instance.PlayerUnit : null); List list = (((Object)(object)instance != (Object)null) ? instance.Players : null); StringBuilder stringBuilder = new StringBuilder(); if (list != null) { for (int i = 0; i < list.Count; i++) { Unit unit2 = (((Object)(object)list[i] != (Object)null) ? list[i].playerUnit : null); stringBuilder.Append((i == 0) ? " roster=[" : ", "); stringBuilder.Append(i).Append(':').Append(DescribeLayer(unit2)); } if (list.Count > 0) { stringBuilder.Append(']'); } } Plugin.Log.LogInfo((object)("Spell area targeting: query=" + DescribeMask(UnitMask()) + " occlusion=" + DescribeMask(GeometryMask()) + " localPlayer=" + DescribeLayer(unit) + " " + $"players={list?.Count ?? 0}{stringBuilder}")); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Could not report spell area targeting: " + ex.Message)); } } private static string DescribeMask(int mask) { if (mask == 0) { return "none"; } StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < 32; i++) { if ((mask & (1 << i)) != 0) { string text = LayerMask.LayerToName(i); if (stringBuilder.Length > 0) { stringBuilder.Append('|'); } stringBuilder.Append(string.IsNullOrEmpty(text) ? i.ToString() : text); } } return stringBuilder.ToString(); } private static string DescribeLayer(Unit unit) { if ((Object)(object)unit == (Object)null) { return "none"; } int layer = ((Component)unit).gameObject.layer; string text = LayerMask.LayerToName(layer); return string.Format("{0}({1})", string.IsNullOrEmpty(text) ? "?" : text, layer); } } internal static class SpellLiquid { private static bool _reportedMissing; private static bool _reportedOverlapLimit; private static BloodEffectData _water; private const float GroundReach = 6f; private static bool _reportedNoPool; private static bool _reportedPour; private static bool _reportedMaterial; private static readonly Color Tint = new Color(0.42f, 0.62f, 0.72f, 0.85f); private static int _poolMask; private static bool _poolMaskResolved; private static readonly Collider[] Overlap = (Collider[])(object)new Collider[256]; private const float SpawnSpeedScale = 50f; private static bool TryLiquidOf(ElementKind element, out DecalType type) { if (element == ElementKind.Poison) { type = (DecalType)2; return true; } type = (DecalType)0; return false; } internal static void Spill(ElementKind element, int drops, Vector3 point, Vector3 normal, Unit caster, bool authoritative, uint seed) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected I4, but got Unknown //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: 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_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) if (!authoritative || drops <= 0 || !TryLiquidOf(element, out var type)) { return; } try { BloodProjectileSystemNEW instance = StaticInstance.Instance; if ((Object)(object)instance == (Object)null || instance.bloodEffectData == null) { ReportMissing("the blood projectile system is not present"); return; } int num = (int)type; if (num < 0 || num >= instance.bloodEffectData.Length) { ReportMissing($"{type} is outside the blood effect table"); return; } BloodEffectData val = instance.bloodEffectData[num]; if ((Object)(object)val == (Object)null) { ReportMissing($"{type} has no blood effect asset"); return; } int num2 = -1; if ((Object)(object)caster != (Object)null && (Object)(object)caster.currentRoom != (Object)null) { num2 = caster.currentRoom.roomIndex; } Vector3 val2 = point + ((((Vector3)(ref normal)).sqrMagnitude > 1E-06f) ? ((Vector3)(ref normal)).normalized : Vector3.up) * 0.15f; for (int i = 0; i < drops; i++) { instance.Spawn(val2, Scatter(seed, i), val, num2); } } catch (Exception ex) { Plugin.Log.LogWarning((object)$"A spell could not spill {element} liquid: {ex.Message}"); } } internal static void Throw(Vector3 velocity, Vector3 from, Unit source) { //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_0065: Unknown result type (might be due to invalid IL or missing references) try { BloodProjectileSystemNEW instance = StaticInstance.Instance; if ((Object)(object)instance == (Object)null || instance.bloodEffectData == null) { return; } int num = 2; if (num < instance.bloodEffectData.Length && !((Object)(object)instance.bloodEffectData[num] == (Object)null)) { int num2 = -1; if ((Object)(object)source != (Object)null && (Object)(object)source.currentRoom != (Object)null) { num2 = source.currentRoom.roomIndex; } instance.Spawn(from, velocity * 50f, instance.bloodEffectData[num], num2); } } catch (Exception ex) { Plugin.Log.LogWarning((object)("A drop of poison could not be thrown: " + ex.Message)); } } internal static void Pour(MarkKind mark, int count, Vector3 point, uint seed) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: 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_005a: 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_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0068: 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_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) if (count <= 0 || !TryAuraOf(mark, out var aura)) { return; } try { AutoPool instance = StaticInstance.Instance; if ((Object)(object)instance == (Object)null || (Object)(object)aura.decalPrefab == (Object)null) { return; } int num = 0; int num2 = 0; BloodDecal sample = null; BloodDecal val3 = default(BloodDecal); for (int i = 0; i < count; i++) { Vector3 val = point + Offset(seed, i); Vector3 val2 = float3.op_Implicit(CastTrace.Below(val, 6f, val)); if (val2 != val) { num2++; } if (!instance.TryGetInstance(((Component)aura.decalPrefab).gameObject, ref val3) || (Object)(object)val3 == (Object)null) { ReportNoPool(); return; } ((Component)val3).transform.SetLocalPositionAndRotation(val2, Quaternion.LookRotation(Vector3.down)); ((Component)val3).gameObject.SetActive(true); val3.Setup(aura, 1f); num++; sample = val3; } ReportFirstPour(mark, count, num, num2, sample); } catch (Exception ex) { Plugin.Log.LogWarning((object)$"A spell could not pour {mark}: {ex.Message}"); } } private static bool TryAuraOf(MarkKind mark, out BloodEffectData aura) { aura = null; if (mark != MarkKind.Soak) { return false; } if ((Object)(object)_water == (Object)null) { BuildWater(); } aura = _water; return (Object)(object)aura != (Object)null; } private static void ReportNoPool() { if (!_reportedNoPool) { _reportedNoPool = true; Plugin.Log.LogWarning((object)"The blood decal prefab is not registered with the pool, so spells can lay no liquid of their own. Reactions still spend their marks and still draw."); } } private static void ReportFirstPour(MarkKind mark, int asked, int placed, int grounded, BloodDecal sample) { if (!_reportedPour) { _reportedPour = true; bool flag = (Object)(object)sample != (Object)null && ((Component)sample).gameObject.activeInHierarchy && (Object)(object)sample.trigger != (Object)null && ((Collider)sample.trigger).enabled; string text = (((Object)(object)sample != (Object)null && (Object)(object)sample.trigger != (Object)null) ? $"{sample.trigger.radius:0.##}m" : "no trigger"); Plugin.Log.LogInfo((object)($"{mark} poured: asked {asked}, placed {placed}, found a floor under {grounded}; " + "trigger " + (flag ? "on" : "OFF") + " reaching " + text + " on prefab '" + (((Object)(object)sample != (Object)null) ? ((Object)sample).name : "none") + "'" + (((Object)(object)sample != (Object)null && (Object)(object)sample.data != (Object)null) ? $", {sample.data.value:0.#} every {sample.data.period:0.##}s" : ", with no aura on the decal"))); } } private static void BuildWater() { try { BloodProjectileSystemNEW instance = StaticInstance.Instance; if ((Object)(object)instance == (Object)null || instance.bloodEffectData == null) { ReportMissing("the blood projectile system is not present"); return; } int num = 2; if (num >= instance.bloodEffectData.Length || (Object)(object)instance.bloodEffectData[num] == (Object)null) { ReportMissing("there is no corrosive aura to take a decal from"); return; } BloodEffectData art = Aura(instance, (DecalType)8); _water = Clone(instance.bloodEffectData[num], art, WaterStatus()); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Water could not be prepared: " + ex.Message)); } } private static BloodEffectData Aura(BloodProjectileSystemNEW system, DecalType type) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Expected I4, but got Unknown int num = (int)type; if (num < 0 || num >= system.bloodEffectData.Length) { return null; } return system.bloodEffectData[num]; } private static EntityAttribute WaterStatus() { return AssetAccess.GetAsset((EntityAttributes)33); } private static BloodEffectData Clone(BloodEffectData donor, BloodEffectData art, EntityAttribute status) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) BloodEffectData val = ScriptableObject.CreateInstance(); val.bloodType = donor.bloodType; val.trailMaterial = donor.trailMaterial; val.decalMaterial = WaterMaterial(donor.decalMaterial); val.decalPrefab = (art ?? donor).decalPrefab; val.bloodColor = Tint; val.bloodDropSize = donor.bloodDropSize; val.decalOverlapRadius = donor.decalOverlapRadius; val.shrinkDelay = 12f; val.shrinkDuration = 4f; val.statusToApply = status; if ((Object)(object)status != (Object)null) { val.value = 15f; val.period = 0.5f; val.radius = 1f; val.initialDelay = 0f; val.duration = 0f; } return val; } private static Material WaterMaterial(Material donor) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_008a: 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_009e: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)donor == (Object)null) { return null; } Material val = new Material(donor); Shader shader = donor.shader; string text = string.Empty; string text2 = "the shader could not be read"; if ((Object)(object)shader != (Object)null) { StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder2 = new StringBuilder(); int propertyCount = shader.GetPropertyCount(); for (int i = 0; i < propertyCount; i++) { string propertyName = shader.GetPropertyName(i); ShaderPropertyType propertyType = shader.GetPropertyType(i); if (stringBuilder.Length > 0) { stringBuilder.Append(", "); } stringBuilder.Append(propertyName).Append(':').Append(propertyType); if ((int)propertyType == 0) { val.SetColor(propertyName, Tint); if (stringBuilder2.Length > 0) { stringBuilder2.Append(", "); } stringBuilder2.Append(propertyName); } } text2 = ((stringBuilder.Length > 0) ? stringBuilder.ToString() : "no properties at all"); text = ((stringBuilder2.Length > 0) ? stringBuilder2.ToString() : string.Empty); } if (!_reportedMaterial) { _reportedMaterial = true; Plugin.Log.LogInfo((object)("Water borrows the decal material '" + ((Object)donor).name + "' on shader '" + (((Object)(object)shader != (Object)null) ? ((Object)shader).name : "none") + "'. " + ((text.Length > 0) ? ("Tinted: " + text + ".") : ("It exposes no colour property, so the puddle keeps the donor's colour. Every property: [" + text2 + "]")))); } return val; } private static Vector3 Offset(uint seed, int index) { //IL_0071: Unknown result type (might be due to invalid IL or missing references) uint num = (uint)((int)seed * -2048144777 + index * 668265263); num ^= num >> 13; float num2 = (float)(num & 0xFFFF) / 65535f * (float)Math.PI * 2f; float num3 = ((index == 0) ? 0f : (0.5f + (float)((num >> 16) & 0xFF) / 255f * 0.9f)); return new Vector3(Mathf.Cos(num2) * num3, 0f, Mathf.Sin(num2) * num3); } private static int PoolMask() { if (_poolMaskResolved) { return _poolMask; } int num = 0; try { BloodProjectileSystemNEW instance = StaticInstance.Instance; if ((Object)(object)instance != (Object)null && instance.bloodEffectData != null) { for (int i = 0; i < instance.bloodEffectData.Length; i++) { BloodEffectData val = instance.bloodEffectData[i]; if (!((Object)(object)val == (Object)null) && !((Object)(object)val.decalPrefab == (Object)null)) { Collider[] componentsInChildren = ((Component)val.decalPrefab).GetComponentsInChildren(true); for (int j = 0; j < componentsInChildren.Length; j++) { num |= 1 << ((Component)componentsInChildren[j]).gameObject.layer; } } } } } catch (Exception ex) { Plugin.Log.LogWarning((object)("The pool layer mask could not be read: " + ex.Message)); } if (num == 0) { return -1; } _poolMask = num; _poolMaskResolved = true; Plugin.Log.LogInfo((object)("Pool sweeps are masked to layer(s) " + LayerNames(num) + ", read off the decal prefabs.")); return num; } private static string LayerNames(int mask) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < 32; i++) { if ((mask & (1 << i)) != 0) { if (stringBuilder.Length > 0) { stringBuilder.Append(", "); } string text = LayerMask.LayerToName(i); stringBuilder.Append(string.IsNullOrEmpty(text) ? i.ToString() : text); } } if (stringBuilder.Length <= 0) { return "none"; } return stringBuilder.ToString(); } internal static int ConsumePools(Vector3 point, float radius, MarkKind mark, List found) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) found.Clear(); EntityAttributes val = SpellMarks.ToStatus(mark); if ((int)val == 0 || radius <= 0f) { return 0; } try { int num = Physics.OverlapSphereNonAlloc(point, radius, Overlap, PoolMask(), (QueryTriggerInteraction)2); if (num >= Overlap.Length && !_reportedOverlapLimit) { _reportedOverlapLimit = true; Plugin.Log.LogWarning((object)($"A pool sweep filled all {Overlap.Length} slots at radius {radius:0.#}, " + "with the mask already applied. Pools beyond that were not set off.")); } for (int i = 0; i < num; i++) { Collider val2 = Overlap[i]; if (!((Object)(object)val2 == (Object)null)) { BloodDecal componentInParent = ((Component)val2).GetComponentInParent(); if (!((Object)(object)componentInParent == (Object)null) && !((Object)(object)componentInParent.data == (Object)null) && !((Object)(object)componentInParent.data.statusToApply == (Object)null) && componentInParent.data.statusToApply.id == val && componentInParent.data.value != 0f) { found.Add(((Component)componentInParent).transform.position); Retire(componentInParent); } } } } catch (Exception ex) { Plugin.Log.LogWarning((object)$"A spell could not gather {mark} pools: {ex.Message}"); } return found.Count; } private static void Retire(BloodDecal decal) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) ((Component)decal).gameObject.SetActive(false); AutoPooledObject poolReference = decal.poolReference; if ((Object)(object)poolReference != (Object)null && poolReference.actuallyPooled && (int)poolReference.poolType == 0) { StaticInstance.Instance.ReleaseInstance(poolReference); } } private static Vector3 Scatter(uint seed, int index) { //IL_0067: 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) uint num = (uint)((int)seed * -1640531535 + index * 40503); num ^= num >> 15; float num2 = (float)(num & 0xFFFF) / 65535f * (float)Math.PI * 2f; float num3 = 1.8f + (float)((num >> 16) & 0xFF) / 255f * 1.8f; return new Vector3(Mathf.Cos(num2) * num3, 1.2f, Mathf.Sin(num2) * num3) * 50f; } private static void ReportMissing(string reason) { if (!_reportedMissing) { _reportedMissing = true; Plugin.Log.LogWarning((object)("Spells will spill no liquid: " + reason + ".")); } } } internal static class SpellMarks { internal static EntityAttributes ToStatus(MarkKind mark) { return (EntityAttributes)(mark switch { MarkKind.Burn => 19, MarkKind.Chill => 25, MarkKind.Poison => 28, MarkKind.Oil => 26, MarkKind.Soak => 33, MarkKind.Shock => 22, MarkKind.Brand => 21, MarkKind.Hex => 32, MarkKind.Stone => 27, MarkKind.Fear => 23, MarkKind.Blind => 18, _ => 0, }); } internal static bool TopsUp(MarkKind mark) { if (mark != MarkKind.Brand && mark != MarkKind.Hex && mark != MarkKind.Fear) { return mark == MarkKind.Blind; } return true; } internal static float Read(Unit unit, MarkKind mark) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0018: 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) EntityAttributes val = ToStatus(mark); if ((Object)(object)unit == (Object)null || unit.Stats == null || (int)val == 0) { return 0f; } return unit.Stats.GetStatus(val); } internal static float Fullness(Unit unit, MarkKind mark) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) float num = Read(unit, mark); if (num <= 0f) { return 0f; } float num2 = Ceiling(unit, ToStatus(mark)); return num / ((num2 > 0f && !float.IsInfinity(num2)) ? num2 : 100f); } private static float Ceiling(Unit unit, EntityAttributes status) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected I4, but got Unknown if (((unit != null) ? unit.Stats : null) == null) { return float.PositiveInfinity; } ActiveStatsList activeMaxEntityStatusValues = unit.Stats.activeMaxEntityStatusValues; float[] maxEntityStatusValues = unit.Stats.maxEntityStatusValues; int num = (int)status; if (activeMaxEntityStatusValues == null || maxEntityStatusValues == null || num < 0 || num >= maxEntityStatusValues.Length || !activeMaxEntityStatusValues.Contains(num)) { return float.PositiveInfinity; } return maxEntityStatusValues[num]; } internal static float Apply(Unit unit, MarkKind mark, float amount, Unit applier) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_002f: 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_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) EntityAttributes val = ToStatus(mark); if ((Object)(object)unit == (Object)null || unit.Stats == null || (int)val == 0 || amount <= 0f) { return 0f; } float status = unit.Stats.GetStatus(val); if ((Object)(object)applier != (Object)null) { unit.RegisterAppliedStatus(val, applier); } unit.Stats.ModifyStatus(val, amount, false); float num = unit.Stats.GetStatus(val) - status; if (mark == MarkKind.Soak && num > 0f) { unit.Stats.SetStatus((EntityAttributes)19, 0f, false); unit.Stats.SetStatus((EntityAttributes)28, 0f, false); } return num; } } internal static class SpellReactor { internal const float CatalystShare = 0.5f; private static readonly List Catalysed = new List(); private static readonly Dictionary Reacted = new Dictionary(); private static readonly List Expired = new List(); private static float _lastForget; private const int ChainHops = 3; private static readonly List Lit = new List(); private static readonly List Pools = new List(); private static readonly HashSet ReportedConversions = new HashSet(); private static readonly List Visited = new List(); internal static bool Pending(Unit target, in ActiveEmission e, out Reaction rule, out float amount) { rule = default(Reaction); amount = 0f; if (e.NoReaction || (Object)(object)target == (Object)null) { return false; } bool isAlive = target.IsAlive; float num = 0f; for (int i = 0; i < SpellReactions.All.Length; i++) { MarkKind consumes = SpellReactions.All[i].Consumes; float num2 = SpellMarks.Read(target, consumes); float num3 = SpellMarks.Fullness(target, consumes); if (!(num2 <= 0f) && !(num3 <= num) && SpellReactions.TryFind(e.Element, consumes, num2, out var rule2) && (isAlive || rule2.ReachesTheDead) && (rule2.OnlyIfTargetLacks == MarkKind.None || !(SpellMarks.Read(target, rule2.OnlyIfTargetLacks) > 0f)) && (!rule2.NotInWater || !target.isSubmerged) && (!rule2.OncePerCast || !AlreadyReacted(e.CastSeed, target))) { rule = rule2; amount = Capped(in rule2, num2); num = num3; } } if (num > 0f && rule.OncePerCast) { RecordReacted(e.CastSeed, target); } return num > 0f; } private static void Catalyse(SpellHitResolver resolver, Unit caster, in ActiveEmission burst, in Reaction rule) { //IL_00ac: Unknown result type (might be due to invalid IL or missing references) resolver.CopyStruck(Catalysed); int num = 0; float num2 = 0f; for (int i = 0; i < Catalysed.Count; i++) { Unit val = Catalysed[i]; if ((Object)(object)val == (Object)null || !val.IsAlive) { continue; } float num3 = SpellMarks.Read(val, rule.Consumes); if (num3 < rule.Threshold) { continue; } float num4 = Capped(in rule, num3); if (Spend(val, in rule, burst.Seed)) { float num5 = num4 * rule.DamagePerPoint * 0.5f; if (!(num5 <= 0f)) { ActiveEmission e = burst; e.Damage = num5; e.Flags = CastFlags.None; resolver.StrikeUnit(val, caster, in e, ((Component)val).transform.position); num++; num2 += num5; } } } Catalysed.Clear(); if (num > 0) { Plugin.Log.LogInfo((object)$"Catalyst: {num} unit(s) cashed their own {rule.Consumes} for {num2:0.#} damage."); } } private static long ReactedKey(uint castSeed, Unit target) { return (long)(((ulong)castSeed << 32) | (uint)((Object)target).GetInstanceID()); } private static bool AlreadyReacted(uint castSeed, Unit target) { return Reacted.ContainsKey(ReactedKey(castSeed, target)); } private static void RecordReacted(uint castSeed, Unit target) { float time = Time.time; if (Reacted.Count > 256 && time - _lastForget > 5f) { _lastForget = time; Expired.Clear(); foreach (KeyValuePair item in Reacted) { if (time - item.Value > 30f) { Expired.Add(item.Key); } } for (int i = 0; i < Expired.Count; i++) { Reacted.Remove(Expired[i]); } } Reacted[ReactedKey(castSeed, target)] = time; } internal static bool Spend(Unit target, in Reaction rule, uint seed) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: 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) EntityAttributes val = SpellMarks.ToStatus(rule.Consumes); if ((int)val == 0 || (Object)(object)target == (Object)null || target.Stats == null) { return false; } if (rule.LeavesMark) { return true; } bool num = SpellThaw.WasStanding(target); target.Stats.SetStatus(val, 0f, false); if (num) { SpellThaw.Fall(target, seed); } return true; } internal static void Fire(SpellRuntime runtime, SpellHitResolver resolver, Unit caster, Unit target, in ActiveEmission source, in Reaction rule, float amount, Vector3 point) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) switch (rule.Effect) { case ReactionEffect.Detonate: Detonate(runtime, resolver, caster, in source, in rule, amount, point); break; case ReactionEffect.Convert: Convert(runtime, caster, target, in source, in rule, amount, point); break; case ReactionEffect.Chain: Chain(resolver, caster, target, in source, in rule, point); break; default: Plugin.Log.LogWarning((object)($"Reaction effect {rule.Effect} is not implemented; {rule.Trigger} on " + $"{rule.Consumes} spent its mark and did nothing.")); break; } } internal static void Arrive(SpellRuntime runtime, in ActiveEmission e, Unit caster, Vector3 point) { //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) if (e.NoReaction || runtime == null) { return; } for (int i = 0; i < SpellReactions.All.Length; i++) { Reaction rule = SpellReactions.All[i]; if (rule.Trigger != e.Element || rule.LiquidReach <= 0f || rule.LiquidBurn <= 0f) { continue; } int num = SpellLiquid.ConsumePools(point, rule.LiquidReach, rule.Consumes, Pools); Lit.Clear(); for (int j = 0; j < num; j++) { if (!Crowded(Pools[j], rule.LiquidBurnRadius)) { Lit.Add(Pools[j]); SpellFire.Light(Pools[j], in rule, 3); } } } } private static bool Crowded(Vector3 where, float radius) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001a: 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) float num = radius * 0.75f; float num2 = num * num; for (int i = 0; i < Lit.Count; i++) { Vector3 val = Lit[i] - where; if (((Vector3)(ref val)).sqrMagnitude < num2) { return true; } } return false; } private static float Capped(in Reaction rule, float found) { if (!(rule.MaxPoints > 0f)) { return found; } return math.min(found, rule.MaxPoints); } private static void Convert(SpellRuntime runtime, Unit caster, Unit target, in ActiveEmission source, in Reaction rule, float amount, Vector3 point) { //IL_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) float num = rule.ProducePerPoint * amount; if (rule.MaxProduced > 0f) { num = math.min(num, rule.MaxProduced); } bool flag = (Object)(object)target != (Object)null && target.IsAlive && rule.Produces != MarkKind.None && num > 0f; float landed = (flag ? SpellMarks.Apply(target, rule.Produces, num, caster) : 0f); ReportFirstConversion(in rule, target, amount, flag ? num : 0f, landed); float power = math.clamp(0.5f + amount / 100f, 0.5f, 1.5f); float scale = math.max(rule.BaseRadius, 1.2f); SpellPresentation.Colors(rule.DamageAs, out var main, out var core); if (runtime != null) { ActiveEmission emission = new ActiveEmission { Delivery = DeliveryKind.Anchored, Element = rule.DamageAs, Pattern = VoxelPattern.Burst, Intensity = IntensityCurve.FadeOut, Origin = float3.op_Implicit(point), BirthTime = Time.time, Lifetime = 0.45f, Scale = scale, Power = power, Color = main, CoreColor = core, VoxelCount = SpellScale.Voxels(180f, power, 1f), Seed = (source.Seed ^ 0x85EBCA6Bu), CasterSlot = source.CasterSlot, LocalCast = source.LocalCast, NoReaction = true, Damage = 0f, Collision = CollisionKind.None }; runtime.TryAdd(in emission); } SpellLiquid.Pour(rule.Produces, rule.Puddles, point, source.Seed); SpellAudio.Impact(rule.DamageAs, SpellVoice.Element, float3.op_Implicit(point), power); } private static void ReportFirstConversion(in Reaction rule, Unit target, float consumed, float asked, float landed) { if (ReportedConversions.Add(((int)rule.Trigger << 16) | (int)rule.Consumes)) { string arg = ((asked <= 0f) ? (((Object)(object)target != (Object)null && !target.IsAlive) ? "nothing marked — the target is dead, which is the melting case" : "nothing marked") : ((!(landed < asked * 0.99f)) ? $"asked {asked:0.#}, landed {landed:0.#}" : $"asked {asked:0.#}, landed {landed:0.#} (the target resists it)")); Plugin.Log.LogInfo((object)($"{rule.Trigger} converted {consumed:0.#} {rule.Consumes} " + $"into {rule.Produces}: {arg}")); } } private static void Chain(SpellHitResolver resolver, Unit caster, Unit target, in ActiveEmission source, in Reaction rule, Vector3 point) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: 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_00bc: 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_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) if (resolver == null || rule.ChainHops <= 0) { return; } Visited.Clear(); if ((Object)(object)target != (Object)null) { Visited.Add(target); } Vector3 val = point; float num = source.Damage; for (int i = 0; i < rule.ChainHops; i++) { num *= rule.ChainFalloff; if (num <= 0.5f) { break; } Unit val2 = SpellChain.Nearest(val, rule.ChainRange, rule.Consumes, Visited); if ((Object)(object)val2 == (Object)null) { break; } Visited.Add(val2); ActiveEmission e = source; e.Damage = num; e.Element = rule.DamageAs; e.NoReaction = true; Vector3 val3 = ((Component)val2).transform.position + Vector3.up; SpellBeamVfx.Push(float3.op_Implicit(val), float3.op_Implicit(val3), rule.DamageAs, num); resolver.StrikeUnit(val2, caster, in e, val3); val = val3; } } private static void Detonate(SpellRuntime runtime, SpellHitResolver resolver, Unit caster, in ActiveEmission source, in Reaction rule, float amount, Vector3 point) { //IL_0071: 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) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: 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_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) float num = amount * rule.DamagePerPoint; float num2 = math.min(rule.BaseRadius + amount * rule.RadiusPerPoint, rule.MaxRadius); float power = SpellScale.PowerFromDamage(num); SpellPresentation.Colors(rule.DamageAs, out var main, out var core); ActiveEmission emission = new ActiveEmission { Delivery = DeliveryKind.Anchored, Element = rule.DamageAs, Pattern = VoxelPattern.Burst, Intensity = IntensityCurve.FadeOut, Origin = float3.op_Implicit(point), BirthTime = Time.time, Lifetime = 0.5f, Scale = num2, Power = power, Color = main, CoreColor = core, VoxelCount = SpellScale.Voxels(220f, power, 1f), Seed = (source.Seed ^ 0x9E3779B9u), CasterSlot = source.CasterSlot, LocalCast = source.LocalCast, NoReaction = true, Damage = num, Collision = CollisionKind.Sphere, HitRadius = num2 }; runtime.TryAdd(in emission); SpellAudio.Impact(rule.DamageAs, SpellVoice.Blast, float3.op_Implicit(point), power); resolver.StrikeReaction(float3.op_Implicit(point), num2, in emission, caster); if ((source.Flags & CastFlags.Catalyst) != CastFlags.None) { Catalyse(resolver, caster, in emission, in rule); } Plugin.Log.LogInfo((object)($"{rule.Trigger} detonated {amount:0.#} {rule.Consumes}: {num:0.#} damage, " + $"radius {num2:0.##}m")); } } internal static class SpellSelfFlash { internal static void AfterCast(CastPlan plan, Unit caster) { if (plan == null || (Object)(object)caster == (Object)null || caster.Stats == null || !caster.isPlayer) { return; } float num = 0f; for (int i = 0; i < plan.EmissionCount; i++) { float flashesCaster = plan.Emissions[i].Archetype.FlashesCaster; if (flashesCaster > num) { num = flashesCaster; } } if (!(num <= 0f) && !(caster.Stats.GetAttribute((EntityAttributes)90) > 0f) && !(caster.Stats.GetAttribute((EntityAttributes)46) > 0f)) { float num2 = num - caster.Stats.GetStatus((EntityAttributes)24); if (num2 > 0f) { caster.Stats.ModifyStatus((EntityAttributes)24, num2, false); } } } } internal static class SpellThaw { internal static bool WasStanding(Unit unit) { Npc val = (Npc)(object)((unit is Npc) ? unit : null); if (val != null && !((Unit)val).IsAlive) { return ((Unit)val).IsFrozenSolid; } return false; } internal static void Fall(Unit unit, uint seed) { Npc val = (Npc)(object)((unit is Npc) ? unit : null); if (val == null) { return; } Animator animator = ((Unit)val).animator; if ((Object)(object)animator != (Object)null) { animator.SetBool("Frozen", false); if (val.hasDeathAnimation) { animator.SetBool("Dead", true); animator.SetBool("DeathRight", (seed & 1) == 0); } } if ((Object)(object)((Unit)val).Rigidbody != (Object)null) { ((Unit)val).Rigidbody.constraints = (RigidbodyConstraints)112; } } } internal static class VigilLedger { private struct Entry { internal Unit Caster; internal bool Fear; internal bool Blind; } [CompilerGenerated] private static class <>O { public static OnDeath <0>__OnDeath; } internal const float Reach = 6f; private const float FearFloor = 10f; private const float FearCeiling = 40f; private const float BlindFloor = 3f; private const float BlindCeiling = 10f; private static readonly Dictionary Watched = new Dictionary(); private static long _level = long.MinValue; internal static void Record(Unit target, MarkKind mark, Unit caster) { //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Expected O, but got Unknown //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown if ((Object)(object)target == (Object)null || (Object)(object)caster == (Object)null || (mark != MarkKind.Fear && mark != MarkKind.Blind)) { return; } ForgetOnNewLevel(); if (!Watched.TryGetValue(target, out var value)) { value = default(Entry); OnDeath onDeath = target.onDeath; object obj = <>O.<0>__OnDeath; if (obj == null) { OnDeath val = OnDeath; <>O.<0>__OnDeath = val; obj = (object)val; } target.onDeath = (OnDeath)Delegate.Combine((Delegate?)(object)onDeath, (Delegate?)obj); } value.Caster = caster; value.Fear |= mark == MarkKind.Fear; value.Blind |= mark == MarkKind.Blind; Watched[target] = value; } private static void OnDeath(Unit unit) { try { Pass(unit); } catch (Exception arg) { Plugin.Log.LogError((object)$"Vigil transfer failed: {arg}"); } } private static void Pass(Unit unit) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown if ((Object)(object)unit == (Object)null) { return; } OnDeath onDeath = unit.onDeath; object obj = <>O.<0>__OnDeath; if (obj == null) { OnDeath val = OnDeath; <>O.<0>__OnDeath = val; obj = (object)val; } unit.onDeath = (OnDeath)Delegate.Remove((Delegate?)(object)onDeath, (Delegate?)obj); if (!Watched.TryGetValue(unit, out var value)) { return; } Watched.Remove(unit); if (!((Object)(object)value.Caster == (Object)null)) { if (value.Fear) { PassOn(unit, MarkKind.Fear, 10f, 40f, value.Caster); } if (value.Blind) { PassOn(unit, MarkKind.Blind, 3f, 10f, value.Caster); } } } private static void PassOn(Unit dead, MarkKind mark, float floor, float ceiling, Unit caster) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) float num = SpellMarks.Read(dead, mark); if (num <= 0f) { return; } float num2 = ((num < floor) ? floor : ((num > ceiling) ? ceiling : num)); Unit val = SpellHitResolver.NearestEnemyInSight(((Component)dead).transform.position, 6f, dead, (Unit candidate) => SpellMarks.Read(candidate, mark) <= 0f); if ((Object)(object)val == (Object)null) { Plugin.Log.LogInfo((object)$"Vigil: {mark} {num:0.#} on {((Object)dead).name} found nobody within {6f:0}m to pass to."); return; } float num3 = SpellMarks.Apply(val, mark, num2, caster); if (Watched.TryGetValue(val, out var value)) { if (mark == MarkKind.Fear) { value.Fear = false; } else { value.Blind = false; } Watched[val] = value; } Plugin.Log.LogInfo((object)($"Vigil: {mark} {num:0.#} passed from {((Object)dead).name} to {((Object)val).name} " + $"({num2:0.#} asked, {num3:0.#} landed).")); } private static void ForgetOnNewLevel() { //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Expected O, but got Unknown //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_0080: Expected O, but got Unknown GameManager instance = StaticInstance.Instance; long num = (((Object)(object)instance != (Object)null) ? (instance.currentSeed ^ ((long)instance.currentLevelIndex << 48)) : 0); if (num == _level) { return; } _level = num; foreach (KeyValuePair item in Watched) { if ((Object)(object)item.Key != (Object)null) { Unit key = item.Key; OnDeath onDeath = key.onDeath; object obj = <>O.<0>__OnDeath; if (obj == null) { OnDeath val = OnDeath; <>O.<0>__OnDeath = val; obj = (object)val; } key.onDeath = (OnDeath)Delegate.Remove((Delegate?)(object)onDeath, (Delegate?)obj); } } Watched.Clear(); } } }