Decompiled source of RogueGolf v1.1.5
plugins/RogueGolf/RogueGolf.Core.dll
Decompiled 3 weeks ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyVersion("0.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 RogueGolf.Shared.Physics { public sealed class GravityResolver { public sealed class Override { public string Source; public float Total; public int Priority; public double Until; } private readonly Dictionary<string, float> ordinary = new Dictionary<string, float>(); private readonly Dictionary<string, Override> overrides = new Dictionary<string, Override>(); public IEnumerable<KeyValuePair<string, float>> Ordinary => ordinary.OrderBy<KeyValuePair<string, float>, string>((KeyValuePair<string, float> x) => x.Key, StringComparer.Ordinal); public IEnumerable<Override> Overrides => overrides.Values.OrderByDescending((Override x) => x.Priority).ThenBy<Override, string>((Override x) => x.Source, StringComparer.Ordinal); public float Underlying => ordinary.Values.Aggregate(1f, (float a, float b) => a * b); public void SetOrdinary(string source, float factor) { Validate(source, factor); ordinary[source] = factor; } public void RemoveOrdinary(string source) { ordinary.Remove(source); } public void SetOverride(string source, float total, int priority, double until) { Validate(source, total); if (double.IsNaN(until) || double.IsInfinity(until)) { throw new ArgumentException("Invalid deadline"); } overrides[source] = new Override { Source = source, Total = total, Priority = priority, Until = until }; } public void RemoveOverride(string source) { overrides.Remove(source); } public Override Winner(double now) { return Overrides.FirstOrDefault((Override x) => x.Until > now); } public float Resolve(double now) { return Winner(now)?.Total ?? Underlying; } public void Expire(double now) { Override[] array = overrides.Values.Where((Override x) => x.Until <= now).ToArray(); foreach (Override obj in array) { overrides.Remove(obj.Source); } } private static void Validate(string source, float value) { if (string.IsNullOrEmpty(source) || float.IsNaN(value) || float.IsInfinity(value) || value < 0.1f || value > 16f) { throw new ArgumentException("Invalid gravity contribution"); } } public string Inspect(double now) { return "Underlying: " + Underlying.ToString("F3") + "x [" + string.Join(", ", Ordinary.Select((KeyValuePair<string, float> x) => x.Key + "=" + x.Value.ToString("F3"))) + "]\nOverrides: " + string.Join(", ", Overrides.Select((Override x) => x.Source + " total=" + x.Total.ToString("F3") + " priority=" + x.Priority + " remaining=" + Math.Max(0.0, x.Until - now).ToString("F1"))) + "\nWinning: " + (Winner(now)?.Source ?? "none") + "; FINAL: " + Resolve(now).ToString("F3") + "x"; } } } namespace RogueGolf.CustomItems { public static class GreenFieldEnvelope { public static float Pulse(double remaining) { double num = 2.0 - remaining; if (num < 0.0 || num >= 1.3) { return 0f; } int num2 = (int)(num / 0.5); if (num2 >= 3) { return 0f; } double num3 = (num - (double)num2 * 0.5) / 0.3; if (!(num3 >= 1.0)) { return (float)Math.Sin(num3 * Math.PI); } return 0f; } public static float Opacity(double remaining) { float num = (float)Math.Max(0.0, Math.Min(1.0, remaining / 0.65)); return num * num * (3f - 2f * num); } } } namespace RogueGolf.Core { public static class BalanceMigration { public static int Apply0101(IDictionary<string, float> values, bool alreadyApplied) { if (alreadyApplied) { return 0; } int changed = 0; Replace("TimedLow", 0.6f, 0.35f); Replace("TimedHigh", 1.5f, 2f); Replace("glass_cannon.Outgoing", 1.5f, 2f); Replace("glass_cannon.Incoming", 1.5f, 2f); Replace("golf_kart_warfare.TrafficRate", 2f, 3f); Replace("friendly_fire_sale.Outgoing", 2f, 2.5f); Replace("total_war.Ammo", 8f, 7f); return changed; void Replace(string key, float before, float after) { if (values.TryGetValue(key, out var value) && value == before) { values[key] = after; changed++; } } } } public static class BuildIdentity { public static string Compute(string version, byte[] core, byte[] plugin, int optionalFeatures) { if (string.IsNullOrEmpty(version) || core == null || core.Length == 0 || plugin == null || plugin.Length == 0) { throw new ArgumentException("Build identity requires both assembly images"); } using MemoryStream memoryStream = new MemoryStream(); using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8, leaveOpen: true)) { binaryWriter.Write("RogueGolf/build/1"); binaryWriter.Write(version); binaryWriter.Write(optionalFeatures); binaryWriter.Write(core.Length); binaryWriter.Write(core); binaryWriter.Write(plugin.Length); binaryWriter.Write(plugin); } using SHA256 sHA = SHA256.Create(); return BitConverter.ToString(sHA.ComputeHash(memoryStream.ToArray()), 0, 16).Replace("-", "").ToLowerInvariant(); } public static bool Valid(string value) { if (value == null || value.Length != 32) { return false; } foreach (char c in value) { if ((c < '0' || c > '9') && (c < 'a' || c > 'f')) { return false; } } return true; } } public enum Parameter { ShotPower, Gravity, BallMass, BallScale, Bounce, Friction, Outgoing, Incoming, ItemRate, Ammo, ItemQuality, Protection, TrafficRate, BallGravity, CartGravity, CartSpeed, Count } [Flags] public enum Mechanic { None = 0, HotStart = 1, RandomLoadout = 2, EqualLoadout = 4, Pacifist = 8, SuddenInventory = 0x10, ChaosLoadout = 0x20, DeathExplosion = 0x40, ExplosiveCollisions = 0x80, MusicalChairs = 0x100, LeaderTax = 0x200, LastPlaceInsurance = 0x400, ComebackSeason = 0x800, UnstableReality = 0x1000, RandomRules = 0x2000, GravityRoulette = 0x4000, RealityBreakdown = 0x8000, TotalWar = 0x10000, NuclearGolf = 0x20000, LawOfZeus = 0x40000, DunkGolf = 0x80000, Formula1 = 0x100000 } public readonly struct Contribution { public readonly Parameter Parameter; public readonly float Factor; public Contribution(Parameter parameter, float factor) { if (parameter < Parameter.ShotPower || parameter >= Parameter.Count || !VoteSettings.Finite(factor) || factor < 0.01f || factor > 120f) { throw new ArgumentException("Invalid contribution"); } Parameter = parameter; Factor = factor; } } public static class CanonicalCatalog { public static float Minimum(Parameter p) { return p switch { Parameter.Friction => 0.01f, Parameter.BallScale => 0.2f, Parameter.Gravity => 0.1f, _ => 0.25f, }; } public static float Maximum(Parameter p) { return p switch { Parameter.ShotPower => 3, Parameter.TrafficRate => 3, Parameter.Bounce => 2, Parameter.ItemQuality => 10, Parameter.ItemRate => 12, Parameter.Ammo => 20, Parameter.BallMass => 10, Parameter.BallScale => 10, Parameter.CartSpeed => 3, Parameter.CartGravity => 10, _ => 4, }; } public static string TemporaryRuleId(int variant) { return (new string[8] { "power_surge", "dead_arms", "bouncy_ball", "fast_greens", "low_gravity", "small_ball", "thick_skin", "big_ball" })[variant % 8]; } public static bool IsTimed(Mechanic m) { return (m & (Mechanic.UnstableReality | Mechanic.RandomRules | Mechanic.GravityRoulette | Mechanic.RealityBreakdown)) != 0; } public static EffectChannel Required(Parameter p) { switch (p) { case Parameter.ShotPower: return EffectChannel.ShotPower; case Parameter.Gravity: case Parameter.BallGravity: return EffectChannel.Gravity; case Parameter.BallMass: return EffectChannel.BallMass; case Parameter.BallScale: return EffectChannel.Scale; case Parameter.Bounce: return EffectChannel.Bounce; case Parameter.Friction: return EffectChannel.Friction; case Parameter.Outgoing: case Parameter.Incoming: return EffectChannel.Knockback; case Parameter.ItemRate: case Parameter.ItemQuality: return EffectChannel.ItemSpawn; case Parameter.Ammo: case Parameter.CartGravity: case Parameter.CartSpeed: return EffectChannel.Inventory; case Parameter.Protection: return EffectChannel.Protection; case Parameter.TrafficRate: return EffectChannel.Traffic; default: throw new ArgumentException("Unknown parameter"); } } public static Contribution[] Variation(Mechanic rule, int variant, ModifierSettings settings = null) { if (!IsTimed(rule)) { return Array.Empty<Contribution>(); } settings = settings ?? new ModifierSettings(); if (rule == Mechanic.GravityRoulette) { return new Contribution[1] { new Contribution(Parameter.Gravity, (new float[4] { settings.Get("RouletteMoon", 0.2f), settings.Get("RouletteLow", 0.6f), 1f, settings.Get("RouletteHigh", 1.5f) })[variant % 4]) }; } RunRandom random = new RunRandom((uint)((variant + 1) * 7919)); Parameter[] array = new Parameter[6] { Parameter.Gravity, Parameter.Bounce, Parameter.Friction, Parameter.ShotPower, Parameter.Incoming, Parameter.BallScale }; if (rule == Mechanic.RealityBreakdown) { return array.Select((Parameter p) => new Contribution(p, (random.Next(2) == 0) ? settings.Get("TimedLow", 0.35f) : settings.Get("TimedHigh", 2f))).ToArray(); } Parameter parameter = array[variant % array.Length]; return new Contribution[1] { new Contribution(parameter, (variant / array.Length % 2 == 0) ? settings.Get("TimedLow", 0.35f) : settings.Get("TimedHigh", 2f)) }; } public static ModifierDefinition[] Create(ModifierSettings s) { List<ModifierDefinition> result = new List<ModifierDefinition>(); ModifierRarity rarity = ModifierRarity.Common; ModifierRarity rarity2 = ModifierRarity.Rare; ModifierRarity rarity3 = ModifierRarity.Legendary; ModifierRarity rarity4 = ModifierRarity.Boss; EffectDuration duration = EffectDuration.OneHole; Contribution[] terms = Array.Empty<Contribution>(); EffectChannel effectChannel = EffectChannel.Inventory; EffectChannel effectChannel2 = EffectChannel.Knockback; EffectChannel needs = EffectChannel.ShotPower | EffectChannel.Gravity | EffectChannel.Scale | EffectChannel.Bounce | EffectChannel.Friction | effectChannel2; Add("power_surge", "Power Surge", rarity, new Contribution[1] { C(Parameter.ShotPower, s.PowerSurge) }); Add("dead_arms", "Dead Arms", rarity, new Contribution[1] { C(Parameter.ShotPower, 0.8f) }); Add("heavy_ball", "Heavy Ball", rarity, new Contribution[1] { C(Parameter.BallGravity, s.HeavyBall) }, Mechanic.None, EffectDuration.Run, "ball_gravity"); Add("featherweight", "Featherweight", rarity, new Contribution[1] { C(Parameter.BallGravity, s.Featherweight) }, Mechanic.None, EffectDuration.Run, "ball_gravity"); Add("bouncy_ball", "Bouncy Ball", rarity, new Contribution[1] { C(Parameter.Bounce, 1.4f) }); Add("big_ball", "Big Ball", rarity, new Contribution[1] { C(Parameter.BallScale, 1.25f) }, Mechanic.None, EffectDuration.Run, "scale"); Add("small_ball", "Small Ball", rarity, new Contribution[1] { C(Parameter.BallScale, 0.75f) }, Mechanic.None, EffectDuration.Run, "scale"); Add("fast_greens", "Fast Greens", rarity, new Contribution[1] { C(Parameter.Friction, 0.6f) }, Mechanic.None, EffectDuration.Run, "friction"); Add("sticky_greens", "Sticky Greens", rarity, new Contribution[1] { C(Parameter.Friction, 1.6f) }, Mechanic.None, EffectDuration.Run, "friction"); Add("item_rush", "Item Rush", rarity, new Contribution[1] { C(Parameter.ItemRate, 2f) }); Add("strong_arms", "Strong Arms", rarity, new Contribution[1] { C(Parameter.Outgoing, 1.25f) }); Add("thick_skin", "Thick Skin", rarity, new Contribution[1] { C(Parameter.Incoming, 0.8f) }); Add("glass_jaw", "Glass Jaw", rarity, new Contribution[1] { C(Parameter.Incoming, 1.25f) }); Add("extra_ammo", "Extra Ammo", rarity, new Contribution[1] { C(Parameter.Ammo, 2f) }); Add("hot_start", "Hot Start", rarity, terms, Mechanic.HotStart, EffectDuration.Run, "starting_loadout", effectChannel, "Basic item each hole"); Add("low_gravity", "Low Gravity", rarity2, new Contribution[1] { C(Parameter.Gravity, s.LowGravity) }, Mechanic.None, EffectDuration.Run, "gravity"); Add("high_gravity", "High Gravity", rarity2, new Contribution[1] { C(Parameter.Gravity, s.HighGravity) }, Mechanic.None, EffectDuration.Run, "gravity"); Add("tiny_ball", "Tiny Ball", rarity2, new Contribution[1] { C(Parameter.BallScale, 0.5f) }, Mechanic.None, EffectDuration.Run, "scale"); Add("giant_ball", "Giant Ball", rarity2, new Contribution[1] { C(Parameter.BallScale, 2f) }, Mechanic.None, EffectDuration.Run, "scale"); Add("high_knockback", "High Knockback", rarity2, new Contribution[1] { C(Parameter.Incoming, 1.75f) }); Add("sumo_golf", "Sumo Golf", rarity2, new Contribution[3] { C(Parameter.BallMass, 3f), C(Parameter.Outgoing, 1.5f), C(Parameter.Incoming, 0.6f) }); Add("pinball", "Pinball", rarity2, new Contribution[2] { C(Parameter.Bounce, 1.7f), C(Parameter.Friction, 0.35f) }); Add("ice_rink", "Ice Rink", rarity2, new Contribution[1] { C(Parameter.Friction, 0.1f) }, Mechanic.None, EffectDuration.Run, "friction"); Add("supercharged", "Supercharged", rarity2, new Contribution[1] { C(Parameter.ShotPower, 1.5f) }); Add("weaklings", "Weaklings", rarity2, new Contribution[1] { C(Parameter.ShotPower, 0.5f) }); Add("arms_race", "Arms Race", rarity2, new Contribution[1] { C(Parameter.ItemQuality, 3f) }); Add("pacifist_golf", "Pacifist Golf", rarity2, terms, Mechanic.Pacifist, duration, "", effectChannel | effectChannel2, "Offensive item hits blocked"); Add("random_loadout", "Random Loadout", rarity2, terms, Mechanic.RandomLoadout, EffectDuration.Run, "starting_loadout", effectChannel, "Independent random item each hole"); Add("equal_opportunity_violence", "Equal Opportunity Violence", rarity2, terms, Mechanic.EqualLoadout, EffectDuration.Run, "starting_loadout", effectChannel, "Same random item for everyone each hole"); Add("glass_cannon", "Glass Cannon", rarity2, new Contribution[2] { C(Parameter.Outgoing, 2f), C(Parameter.Incoming, 2f) }); Add("juggernauts", "Juggernauts", rarity2, new Contribution[2] { C(Parameter.Incoming, 0.4f), C(Parameter.BallMass, 3f) }); Add("leader_tax", "Leader Tax", rarity2, terms, Mechanic.LeaderTax, EffectDuration.Run, "", EffectChannel.ShotPower | EffectChannel.Ranking, "Leader shot power: " + (s.Get("LeaderTaxFactor", 0.8f) * 100f).ToString("0") + "%"); Add("last_place_insurance", "Last Place Insurance", rarity2, terms, Mechanic.LastPlaceInsurance, EffectDuration.Run, "", EffectChannel.ShotPower | EffectChannel.Ranking, "Last place shot power: " + (s.Get("LastPlaceFactor", 1.2f) * 100f).ToString("0") + "%"); Add("no_mercy", "No Mercy", rarity2, new Contribution[1] { C(Parameter.Protection, 0.5f) }); Add("sudden_inventory", "Sudden Inventory", rarity2, terms, Mechanic.SuddenInventory, EffectDuration.Run, "", effectChannel, "Periodic random item grants"); Add("moon_golf", "Moon Golf", rarity3, new Contribution[1] { C(Parameter.Gravity, 0.2f) }, Mechanic.None, EffectDuration.Run, "gravity"); Add("jupiter_golf", "Jupiter Golf", rarity3, new Contribution[1] { C(Parameter.Gravity, 2.5f) }, Mechanic.None, EffectDuration.Run, "gravity"); Add("knockback_apocalypse", "Knockback Apocalypse", rarity3, new Contribution[1] { C(Parameter.Incoming, 3f) }); Add("arsenal", "Arsenal", rarity3, new Contribution[2] { C(Parameter.ItemRate, 4f), C(Parameter.ItemQuality, 5f) }); Add("infinite_warfare", "Infinite Warfare", rarity3, new Contribution[1] { C(Parameter.Ammo, 5f) }); Add("death_explosion", "Death Explosion", rarity3, terms, Mechanic.DeathExplosion, EffectDuration.Run, "", EffectChannel.Explosions, "Explode on elimination"); Add("explosive_collisions", "Explosive Collisions", rarity3, terms, Mechanic.ExplosiveCollisions, EffectDuration.Run, "", EffectChannel.Explosions, "Fast ball landings explode without affecting the triggering ball; incoming combat/vehicle hits explode against only the hit player"); Add("balloon_animals", "Balloon Animals", rarity3, new Contribution[4] { C(Parameter.BallScale, 3f), C(Parameter.BallMass, 0.3f), C(Parameter.Incoming, 1.6f), C(Parameter.Bounce, 1.4f) }); Add("cannonballs", "Cannonballs", rarity3, new Contribution[3] { C(Parameter.BallScale, 0.5f), C(Parameter.BallMass, 8f), C(Parameter.Incoming, 0.5f) }); Add("chaos_loadout", "Chaos Loadout", rarity3, terms, Mechanic.ChaosLoadout, EffectDuration.Run, "", effectChannel, "Periodic inventory rerolls"); Add("musical_chairs", "Musical Chairs", rarity4, terms, Mechanic.MusicalChairs, duration, "", EffectChannel.Teleport, "Periodically swap ball positions"); Add("rubber_world", "Rubber World", rarity3, new Contribution[1] { C(Parameter.Bounce, 2f) }); Add("zero_traction", "Zero Traction", rarity3, new Contribution[1] { C(Parameter.Friction, 0.01f) }, Mechanic.None, EffectDuration.Run, "friction"); Add("maximum_overdrive", "Maximum Overdrive", rarity3, new Contribution[1] { C(Parameter.ShotPower, 2f) }); Add("golf_kart_warfare", "Golf Kart Warfare", rarity3, new Contribution[1] { C(Parameter.TrafficRate, 3f) }, Mechanic.None, EffectDuration.Run, "", EffectChannel.None, "Compatible traffic courses only"); Add("formula_1", "Formula 1", rarity4, new Contribution[2] { C(Parameter.CartGravity, 10f), C(Parameter.CartSpeed, 3f) }, Mechanic.Formula1, duration, "", effectChannel, "Everyone starts the hole with a Golf Cart item"); Add("friendly_fire_sale", "Friendly Fire Sale", rarity3, new Contribution[1] { C(Parameter.Outgoing, 2.5f) }, Mechanic.None, EffectDuration.Run, "", EffectChannel.None, "Player versus player knockback boosted"); Add("comeback_season", "Comeback Season", rarity3, terms, Mechanic.ComebackSeason, EffectDuration.Run, "", EffectChannel.ShotPower | EffectChannel.Ranking, "Rank shot power up to " + (s.Get("ComebackMaximum", 1.3f) * 100f).ToString("0") + "%"); Add("unstable_reality", "Unstable Reality", rarity3, terms, Mechanic.UnstableReality, EffectDuration.Run, "", needs, "One physics property rerolls periodically"); Add("random_rules", "Random Rules", rarity3, terms, Mechanic.RandomRules, EffectDuration.Run, "", needs, "One removable physics rule rotates periodically"); Add("law_of_zeus", "LAW OF ZEUS", rarity4, terms, Mechanic.LawOfZeus, duration, "", EffectChannel.WorldEvents, "The gods are displeased"); Add("dunk_golf", "Dunk Golf", rarity4, new Contribution[2] { C(Parameter.Gravity, 0.35f), C(Parameter.BallScale, 10f) }, Mechanic.DunkGolf, duration, "", EffectChannel.HoleGeometry | effectChannel, "The whole green becomes a giant rim. Rocket Driver supplied"); Add("gravity_roulette", "Gravity Roulette", rarity4, terms, Mechanic.GravityRoulette, duration, "", EffectChannel.Gravity, "Gravity presets cycle periodically"); Add("reality_breakdown", "Reality Breakdown", rarity4, terms, Mechanic.RealityBreakdown, duration, "", needs, "Multiple physics properties reroll"); Add("item_storm", "Item Storm", rarity4, new Contribution[1] { C(Parameter.ItemRate, 10f) }, Mechanic.None, duration); Add("total_war", "Total War", rarity4, new Contribution[1] { C(Parameter.Ammo, 7f) }, Mechanic.TotalWar, duration, "", effectChannel, "Powerful loadouts replenished periodically"); Add("nuclear_golf", "Nuclear Golf", rarity4, terms, Mechanic.NuclearGolf, duration, "", EffectChannel.Explosions, "Large bounded death and impact explosions"); Add("ballpocalypse", "Ballpocalypse", rarity4, new Contribution[2] { C(Parameter.BallScale, 4f), C(Parameter.BallMass, 3f) }, Mechanic.None, duration); Add("micro_golf", "Micro Golf", rarity4, new Contribution[1] { C(Parameter.BallScale, 0.2f) }, Mechanic.None, duration); Add("orbital_golf", "Orbital Golf", rarity4, new Contribution[2] { C(Parameter.Gravity, 0.15f), C(Parameter.ShotPower, 2.5f) }, Mechanic.None, duration); Add("pinball_hell", "Pinball Hell", rarity4, new Contribution[3] { C(Parameter.Bounce, 2f), C(Parameter.Friction, 0.05f), C(Parameter.Incoming, 3f) }, Mechanic.None, duration); Add("arsenal_apocalypse", "Arsenal Apocalypse", rarity4, new Contribution[3] { C(Parameter.ItemRate, 10f), C(Parameter.ItemQuality, 8f), C(Parameter.Ammo, 8f) }, Mechanic.None, duration); return result.ToArray(); void Add(string id, string name, ModifierRarity modifierRarity, Contribution[] source, Mechanic rule = Mechanic.None, EffectDuration effectDuration = EffectDuration.Run, string group = "", EffectChannel effectChannel4 = EffectChannel.None, string detail = "") { Contribution[] array = source.Select((Contribution c) => C(c.Parameter, s.Get(id + "." + c.Parameter, c.Factor))).ToArray(); Contribution[] array2 = array; for (int num = 0; num < array2.Length; num++) { Contribution contribution = array2[num]; if (contribution.Factor < Minimum(contribution.Parameter) || contribution.Factor > Maximum(contribution.Parameter)) { throw new ArgumentException("Tuning outside channel bounds: " + id); } } EffectChannel effectChannel3 = effectChannel4; array2 = array; for (int num = 0; num < array2.Length; num++) { Contribution contribution2 = array2[num]; effectChannel3 |= Required(contribution2.Parameter); } string text = string.Join(", ", array.Select((Contribution c) => (c.Factor * 100f).ToString("0", CultureInfo.InvariantCulture) + "% " + ((c.Parameter == Parameter.BallGravity) ? "Ball gravity" : c.Parameter.ToString()))); if (detail != "") { text = text + ((text == "") ? "" : ". ") + detail; } result.Add(new ModifierDefinition(id, name, modifierRarity, effectChannel3, (array.Length == 1) ? array[0].Factor : 1f, group, effectDuration, modifierRarity switch { ModifierRarity.Legendary => 2, ModifierRarity.Rare => 3, ModifierRarity.Common => 4, _ => 1, }, array, rule, modifierRarity.ToString() + " | " + text + ". " + ((effectDuration == EffectDuration.OneHole) ? "Next hole only." : "For this run."))); } static Contribution C(Parameter p, float f) { return new Contribution(p, f); } } } public static class CompatibilityPolicy { public const int Version = 1; public const double AdmissionTimeout = 12.0; public static readonly IReadOnlyDictionary<string, string[]> Fields = new Dictionary<string, string[]> { ["PlayerAudio"] = new string[19] { "serverJumpCommandRateLimiter", "serverSwingCommandRateLimiter", "serverOverchargedSwingCommandRateLimiter", "serverSwingHitCommandRateLimiter", "serverPistolShotCommandRateLimiter", "serverElephantGunShotCommandRateLimiter", "serverBulletWhizzCommandRateLimiter", "serverRocketLauncherShotCommandRateLimiter", "serverRailgunShotCommandRateLimiter", "serverItemAimCommandRateLimiter", "serverItemUseCommandRateLimiter", "serverCancelItemUseCommandRateLimiter", "serverCancelItemFlourishCommandRateLimiter", "serverLandminePlantCommandRateLimiter", "serverRocketDriverEnteredOverchargeCommandRateLimiter", "serverFreezeBombShotCommandRateLimiter", "serverSmokeBombExplodeCommandRateLimiter", "serverMovingInFoliageCommandRateLimiter", "serverStopMovingInFoliageCommandRateLimiter" }, ["PlayerMovement"] = new string[9] { "serverKnockoutBlockedCommandRateLimiter", "serverInformKnockedOutCommandRateLimiter", "serverJumboBurgerGrowEffectsCommandRateLimiter", "serverInformGroundedCommandRateLimiter", "serverSpringBootsLandingCommandRateLimiter", "serverJumboBurgerLandingEffectsCommandRateLimiter", "serverInformTeleportedCommandRateLimiter", "serverSpeedBoostEffectCommandRateLimiter", "serverCollisionKnockoutEffectsCommandRateLimiter" }, ["PlayerGolfer"] = new string[4] { "serverSwingVfxCommandRateLimiter", "serverRocketDriverPostHitSpinEffectsCommandRateLimiter", "serverRocketDriverMissVfxCommandRateLimiter", "serverHitOwnBallCommandRateLimiter" }, ["PlayerInventory"] = new string[22] { "serverItemFlourishVfxCommandRateLimiter", "serverSpringBootsActivationCommandRateLimiter", "serverDropItemCommandRateLimiter", "serverRemoveItemCommandRateLimiter", "serverGolfCartBriefcaseEffectsCommandRateLimiter", "serverSpawnLandmineCommandRateLimiter", "serverActivateOrbitalLaserCommandRateLimiter", "serverThunderstormUseEffectsCommandRateLimiter", "serverCreateThunderstormCommandRateLimiter", "serverJumboBurgerEatEffectsCommandRateLimiter", "serverThrowUsedItemCommandRateLimiter", "serverInformInterruptedPlayerWithAirhornRateLimiter", "serverInformShotRocketCommandRateLimiter", "serverInformShotFreezeBombCommandRateLimiter", "serverActivateElectromagnetCommandRateLimiter", "serverActivatedOrbitalLaserCommandRateLimiter", "serverDecrementItemUseCommandRateLimiter", "serverAirhornCommandRateLimiter", "serverFlashCameraCommandRateLimiter", "serverCancelAirhornVfxCommandRateLimiter", "serverPlayRailgunChargeCancellationEffectsCommandRateLimiter", "serverPlayRailgunShotEffectsCommandRateLimiter" } }; public static bool PrivateLobby(string mode) { if (!(mode == "private")) { return mode == "friends"; } return true; } public static bool MayRelax(bool enabled, bool server, bool privateLobby, bool verified, bool gameplayActive) { return enabled && server && privateLobby && verified && gameplayActive; } public static bool Matches(string build, string expectedBuild, int protocol, int policy, EffectChannel capabilities, EffectChannel expectedCapabilities) { if (BuildIdentity.Valid(build) && build == expectedBuild && protocol == 10 && policy == 1) { return capabilities == expectedCapabilities; } return false; } public static float Interval(float native) { return Math.Min(native * 0.1f, 0.01f); } public static int Suspicion(int native) { return Math.Max(native * 20, 200); } public static int Confirmation(int native) { return Math.Max(native * 50, 1000); } public static float ResetGap(float native) { return Math.Min(native, 0.25f); } } public sealed class AdmissionGate { private sealed class Peer { public string Challenge; public double Deadline; public bool Verified; } private readonly Dictionary<int, Peer> peers = new Dictionary<int, Peer>(); public void Begin(int id, string challenge, double now) { peers[id] = new Peer { Challenge = challenge, Deadline = now + 12.0 }; } public bool Verify(int id, string challenge, bool matches, double now) { if (!peers.TryGetValue(id, out var value) || value.Verified || now >= value.Deadline || !matches || value.Challenge != challenge) { return false; } value.Verified = true; return true; } public bool Verified(int id) { if (peers.TryGetValue(id, out var value)) { return value.Verified; } return false; } public bool Expired(int id, double now) { if (peers.TryGetValue(id, out var value) && !value.Verified) { return now >= value.Deadline; } return false; } public void Remove(int id) { peers.Remove(id); } public void Clear() { peers.Clear(); } } public static class Conditions { public static string Direction(ModifierDefinition d) { if (CanonicalCatalog.IsTimed(d.Rule)) { return "~"; } bool flag = d.Contributions.Any((Contribution c) => c.Factor > 1f); bool flag2 = d.Contributions.Any((Contribution c) => c.Factor < 1f); if (!(flag && flag2)) { if (!flag) { if (!flag2) { return ""; } return "−"; } return "+"; } return "±"; } public static KeyValuePair<string, string>[] Rows(ModifierRegistry registry, ModifierSettings settings, IEnumerable<ActiveModifier> effects, int hole, float personalShot = 1f) { ActiveModifier[] array = effects.Where((ActiveModifier e) => !e.Suspended && e.FirstHole <= hole).ToArray(); EffectValues effectValues = registry.Compose(array); HashSet<Parameter> hashSet = new HashSet<Parameter>(); Mechanic mechanic = Mechanic.None; ActiveModifier[] array2 = array; foreach (ActiveModifier activeModifier in array2) { ModifierDefinition modifierDefinition = registry.Get(activeModifier.Id); mechanic |= modifierDefinition.Rule; foreach (Contribution item in modifierDefinition.Contributions.Concat((modifierDefinition.Rule == Mechanic.RandomRules) ? registry.Get(CanonicalCatalog.TemporaryRuleId(activeModifier.Variant)).Contributions : CanonicalCatalog.Variation(modifierDefinition.Rule, activeModifier.Variant, settings))) { hashSet.Add(item.Parameter); } } if (Math.Abs(personalShot - 1f) > 0.0001f) { hashSet.Add(Parameter.ShotPower); } List<KeyValuePair<string, string>> rows = new List<KeyValuePair<string, string>>(); if ((mechanic & Mechanic.Pacifist) != Mechanic.None) { Add("pacifist", "Offensive items disabled"); } Parameter[] array3 = new Parameter[16] { Parameter.Gravity, Parameter.BallGravity, Parameter.ShotPower, Parameter.BallScale, Parameter.BallMass, Parameter.Bounce, Parameter.Friction, Parameter.Outgoing, Parameter.Incoming, Parameter.Ammo, Parameter.ItemRate, Parameter.ItemQuality, Parameter.Protection, Parameter.TrafficRate, Parameter.CartGravity, Parameter.CartSpeed }; for (int num = 0; num < array3.Length; num++) { Parameter parameter = array3[num]; if (hashSet.Contains(parameter)) { float value = ((parameter == Parameter.ShotPower) ? Math.Max(0.25f, Math.Min(3f, effectValues[parameter] * personalShot)) : effectValues[parameter]); if (parameter == Parameter.BallGravity) { value = effectValues.EffectiveBallGravity; } string text = ((parameter == Parameter.ShotPower) ? "Shot power" : EffectPresentation.ParameterName(parameter)); if (parameter == Parameter.Outgoing && array.Any((ActiveModifier e) => e.Id == "friendly_fire_sale")) { text += " (PvP)"; } Add(parameter.ToString(), text + " ×" + EffectPresentation.Number(value)); } } if ((mechanic & Mechanic.LawOfZeus) != Mechanic.None) { Add("zeus", "Thunderstorms across the course"); } if ((mechanic & Mechanic.TotalWar) != Mechanic.None) { Add("inventory", "Powerful loadouts refill"); } else if ((mechanic & Mechanic.ChaosLoadout) != Mechanic.None) { Add("inventory", "Inventories reroll"); } else if ((mechanic & Mechanic.SuddenInventory) != Mechanic.None) { Add("inventory", "Random items granted"); } if ((mechanic & Mechanic.MusicalChairs) != Mechanic.None) { Add("swap", "Ball positions swap"); } if ((mechanic & Mechanic.Pacifist) == 0) { if ((mechanic & (Mechanic.DeathExplosion | Mechanic.NuclearGolf)) != Mechanic.None) { Add("death", "Explode on elimination"); } if ((mechanic & (Mechanic.ExplosiveCollisions | Mechanic.NuclearGolf)) != Mechanic.None) { Add("impact", "Explosive impacts"); } } return rows.ToArray(); void Add(string id, string value2) { rows.Add(new KeyValuePair<string, string>(id, value2)); } } } public enum ProgressionPhase { Early, EarlyMid, MidLate, Late } public static class CourseProgress { public static float GetNormalizedProgress(int upcomingHole, int totalHoles) { if (upcomingHole <= 2) { return 0f; } if (totalHoles <= 2) { return 1f; } return Math.Max(0f, Math.Min(1f, ((float)upcomingHole - 2f) / ((float)totalHoles - 2f))); } public static float[] MigrateLegacyStarts(int[] starts) { if (starts == null || starts.Length != 4 || starts[0] != 2 || starts.Any((int h) => h < 2 || h > 999) || !starts.SequenceEqual(from h in starts.Distinct() orderby h select h)) { throw new ArgumentException("Invalid legacy progression boundaries"); } if (starts.SequenceEqual(RogueGolfDefaults.LegacyPhaseStarts)) { return RogueGolfDefaults.PhaseThresholds; } return starts.Select((int h) => (float)(h - 2) / 7f * 100f).ToArray(); } } public static class BossSchedule { public static bool IsBoss(int roundOrdinal, bool enabled, int interval) { if (enabled && interval > 0 && roundOrdinal > 0) { return roundOrdinal % interval == 0; } return false; } } public static class CupAccommodation { public static float CollisionScale(float scale, bool dunk, float x, float y, float z, float minX, float minY, float minZ, float maxX, float maxY, float maxZ, float surfaceY, float nativeRadius) { if (dunk || scale == 1f) { return scale; } if (!(x >= minX) || !(x <= maxX) || !(z >= minZ) || !(z <= maxZ) || !(y >= minY - nativeRadius) || !(y <= Math.Max(maxY, surfaceY) + nativeRadius * scale + 3f)) { return scale; } return 1f; } } public static class DunkGoal { public static bool Crossed(float ax, float ay, float az, float bx, float by, float bz, float radius, float ballRadius) { if (!VoteSettings.Finite(ax) || !VoteSettings.Finite(ay) || !VoteSettings.Finite(az) || !VoteSettings.Finite(bx) || !VoteSettings.Finite(by) || !VoteSettings.Finite(bz) || !VoteSettings.Finite(radius) || !VoteSettings.Finite(ballRadius) || radius <= ballRadius || ballRadius < 0f || ay <= 0f || by > 0f) { return false; } double num = (double)ay / ((double)ay - (double)by); double num2 = (double)ax + ((double)bx - (double)ax) * num; double num3 = (double)az + ((double)bz - (double)az) * num; double num4 = radius - ballRadius; return num2 * num2 + num3 * num3 <= num4 * num4; } } public enum EffectGlyph { Bolt, Weight, Feather, Ball, Bounce, Ice, Glue, Gift, Fist, Shield, Ammo, Orbit, Dice, Peace, Crown, Flag, Clock, Explosion, Swap, Car, World, Skull, Infinity, Storm } public readonly struct EffectSymbol { public readonly EffectGlyph Glyph; public readonly int Variant; public EffectSymbol(EffectGlyph glyph, int variant = 0) { Glyph = glyph; Variant = variant; } } public static class EffectPresentation { private static readonly Dictionary<string, EffectSymbol> symbols = BuildSymbols(); private static Dictionary<string, EffectSymbol> BuildSymbols() { Dictionary<string, EffectSymbol> result = new Dictionary<string, EffectSymbol>(); Add(EffectGlyph.Bolt, new string[5] { "power_surge", "supercharged", "maximum_overdrive", "dead_arms", "weaklings" }); Add(EffectGlyph.Weight, new string[3] { "heavy_ball", "sumo_golf", "cannonballs" }); Add(EffectGlyph.Feather, new string[2] { "featherweight", "balloon_animals" }); Add(EffectGlyph.Ball, new string[7] { "dunk_golf", "small_ball", "big_ball", "tiny_ball", "giant_ball", "micro_golf", "ballpocalypse" }); Add(EffectGlyph.Bounce, new string[4] { "bouncy_ball", "pinball", "rubber_world", "pinball_hell" }); Add(EffectGlyph.Ice, new string[3] { "fast_greens", "ice_rink", "zero_traction" }); Add(EffectGlyph.Glue, new string[1] { "sticky_greens" }); Add(EffectGlyph.Gift, new string[4] { "item_rush", "hot_start", "arsenal", "arsenal_apocalypse" }); Add(EffectGlyph.Fist, new string[5] { "strong_arms", "high_knockback", "glass_cannon", "knockback_apocalypse", "friendly_fire_sale" }); Add(EffectGlyph.Shield, new string[5] { "thick_skin", "glass_jaw", "juggernauts", "no_mercy", "last_place_insurance" }); Add(EffectGlyph.Ammo, new string[3] { "extra_ammo", "arms_race", "total_war" }); Add(EffectGlyph.Orbit, new string[6] { "low_gravity", "high_gravity", "moon_golf", "jupiter_golf", "orbital_golf", "gravity_roulette" }); Add(EffectGlyph.Dice, new string[4] { "random_loadout", "equal_opportunity_violence", "chaos_loadout", "random_rules" }); Add(EffectGlyph.Peace, new string[1] { "pacifist_golf" }); Add(EffectGlyph.Crown, new string[1] { "leader_tax" }); Add(EffectGlyph.Flag, new string[1] { "comeback_season" }); Add(EffectGlyph.Clock, new string[1] { "sudden_inventory" }); Add(EffectGlyph.Explosion, new string[3] { "death_explosion", "explosive_collisions", "nuclear_golf" }); Add(EffectGlyph.Swap, new string[1] { "musical_chairs" }); Add(EffectGlyph.Car, new string[2] { "golf_kart_warfare", "formula_1" }); Add(EffectGlyph.World, new string[2] { "unstable_reality", "reality_breakdown" }); Add(EffectGlyph.Infinity, new string[1] { "infinite_warfare" }); Add(EffectGlyph.Storm, new string[2] { "item_storm", "law_of_zeus" }); return result; void Add(EffectGlyph glyph, string[] ids) { for (int i = 0; i < ids.Length; i++) { result.Add(ids[i], new EffectSymbol(glyph, i + 1)); } } } public static EffectSymbol Symbol(string id) { if (!symbols.TryGetValue(id, out var value)) { throw new ArgumentException("Missing effect icon: " + id); } return value; } public static string Number(float value) { return value.ToString("0.##", CultureInfo.InvariantCulture); } public static string ParameterName(Parameter p) { return (new string[16] { "Shot speed", "Gravity", "Ball mass", "Ball size", "Bounce", "Ground friction", "Knockback dealt", "Knockback received", "Item spawn rate", "Item uses", "Powerful-item odds", "Recovery protection", "Traffic rate", "Ball gravity", "Cart gravity", "Cart speed" })[(int)p]; } public static string Factor(Contribution c) { return ParameterName(c.Parameter) + " ×" + Number(c.Factor); } public static string Status(ActiveModifier effect, int currentHole) { string text = ((effect.RemainingHoles < 0) ? "For this run" : ((effect.FirstHole > currentHole) ? "Next hole only" : "This hole only")); return (effect.Suspended ? "Suspended · " : ((effect.FirstHole > currentHole) ? "Upcoming · " : "")) + text; } public static string Details(ModifierDefinition d, ModifierSettings settings, ActiveModifier active = null) { List<string> list = d.Contributions.Select(Factor).ToList(); if (d.Contributions.Any((Contribution c) => c.Parameter == Parameter.Gravity || c.Parameter == Parameter.BallGravity) || CanonicalCatalog.IsTimed(d.Rule)) { list.Add("Final combined gravity never falls below ×0.2; ball gravity multiplies shared gravity."); } string text = "Every " + Number(settings.Interval) + "s"; switch (d.Rule) { case Mechanic.LawOfZeus: list.Add("The gods are displeased. Continuous vanilla storms target greens, players, balls, item points and fairway routes. Host-limited to at most seven storms; one hole only."); break; case Mechanic.HotStart: list.Add("Start each hole with a basic item."); break; case Mechanic.Formula1: list.Add("Everyone starts each hole with a Golf Cart item. Only golf carts receive the extra gravity and driving speed; traffic vehicles, players and balls keep their own physics."); break; case Mechanic.RandomLoadout: list.Add("Each player starts with an independently drawn item."); break; case Mechanic.EqualLoadout: list.Add("Everyone starts with the same randomly drawn item."); break; case Mechanic.Pacifist: list.Add("Offensive item use and offensive item hits are blocked."); break; case Mechanic.SuddenInventory: list.Add(text + ", receive a random item if a slot is free."); break; case Mechanic.ChaosLoadout: list.Add(text + ", inventories reroll. Active item use delays the reroll."); break; case Mechanic.MusicalChairs: list.Add(text + ", balls swap positions. Requires at least two balls."); break; case Mechanic.TotalWar: list.Add(text + ", powerful loadouts are replenished."); break; case Mechanic.LeaderTax: list.Add("Leader shot speed ×" + Number(settings.Get("LeaderTaxFactor", 0.8f)) + ". No solo penalty."); break; case Mechanic.LastPlaceInsurance: list.Add("Last-place shot speed ×" + Number(settings.Get("LastPlaceFactor", 1.2f)) + ". Requires multiple players."); break; case Mechanic.ComebackSeason: list.Add("Rank-based shot speed assistance, up to ×" + Number(settings.Get("ComebackMaximum", 1.3f)) + ". Requires multiple players."); break; case Mechanic.DunkGolf: list.Add("The whole green is a giant rim. Drop the ball through from above. A Rocket Driver is supplied at hole start."); break; case Mechanic.DeathExplosion: case Mechanic.ExplosiveCollisions: case Mechanic.NuclearGolf: list.Add((d.Rule == Mechanic.DeathExplosion) ? "Explode on elimination." : ((d.Rule == Mechanic.ExplosiveCollisions) ? "Fast ball landings and incoming combat/vehicle hits on players cause explosions." : "Eliminations, fast ball landings and incoming combat/vehicle hits on players cause large explosions.")); if (d.Rule != Mechanic.DeathExplosion) { list.Add("Ball landing blasts leave the triggering ball immune to its own blast. Player-hit blasts affect only the recipient, never the attacker, balls or bystanders. Blast victims must settle before triggering another impact explosion. Player jumps, recoil and landings never trigger impact explosions."); } list.Add("Blast radius " + Number(Math.Min(12f, settings.ExplosionRadius * (float)((d.Rule != Mechanic.NuclearGolf) ? 1 : 2))) + "m · cooldown " + Number(settings.ExplosionCooldown) + "s" + ((d.Rule == Mechanic.DeathExplosion) ? "" : (" · landing speed threshold " + Number(settings.ImpactThreshold)))); break; case Mechanic.UnstableReality: case Mechanic.RandomRules: case Mechanic.GravityRoulette: case Mechanic.RealityBreakdown: list.Add(text + ((d.Rule == Mechanic.GravityRoulette) ? ", gravity cycles." : ((d.Rule == Mechanic.RandomRules) ? ", a temporary rule rotates." : ", physics rerolls."))); if (d.Rule == Mechanic.UnstableReality || d.Rule == Mechanic.RealityBreakdown) { list.Add("Reroll factors: ×" + Number(settings.Get("TimedLow", 0.35f)) + " / ×" + Number(settings.Get("TimedHigh", 2f)) + " (combined limits apply)."); } if (active != null) { Contribution[] source = ((d.Rule == Mechanic.RandomRules) ? ModifierRegistry.Create(settings).Get(CanonicalCatalog.TemporaryRuleId(active.Variant)).Contributions : CanonicalCatalog.Variation(d.Rule, active.Variant, settings)); list.Add("Current: " + string.Join(" · ", source.Select(Factor))); } break; } if (d.Id == "golf_kart_warfare") { list.Add("Only active on courses with supported traffic."); } if (d.Id == "friendly_fire_sale") { list.Add("Extra outgoing knockback applies to player-versus-player hits only; native team protections remain."); } return string.Join("\n", list); } public static bool HasCycle(Mechanic rule) { if (!CanonicalCatalog.IsTimed(rule) && rule != Mechanic.SuddenInventory && rule != Mechanic.ChaosLoadout && rule != Mechanic.MusicalChairs) { return rule == Mechanic.TotalWar; } return true; } public static string CycleValues(ModifierDefinition definition, ModifierSettings settings, ActiveModifier active) { if (CanonicalCatalog.IsTimed(definition.Rule)) { Contribution[] source = ((definition.Rule == Mechanic.RandomRules) ? ModifierRegistry.Create(settings).Get(CanonicalCatalog.TemporaryRuleId(active.Variant)).Contributions : CanonicalCatalog.Variation(definition.Rule, active.Variant, settings)); return string.Join(" · ", source.Select(Factor)); } if (definition.Rule != Mechanic.SuddenInventory) { if (definition.Rule != Mechanic.ChaosLoadout) { if (definition.Rule != Mechanic.MusicalChairs) { return "Powerful loadouts replenish"; } return "Ball positions swap"; } return "Inventory reroll"; } return "Random item when a slot is free"; } public static string Combined(ModifierRegistry registry, IEnumerable<ActiveModifier> active) { EffectValues values = registry.Compose(active); IEnumerable<string> values2 = from Parameter p in Enum.GetValues(typeof(Parameter)) where p != Parameter.Count && Math.Abs(values[p] - 1f) > 0.0001f select Factor(new Contribution(p, values[p])); string text = string.Join(" · ", values2); if (!(text == "")) { return text; } return "Standard physics. Item and special rules are listed below."; } } public readonly struct GravityVector { public readonly float X; public readonly float Y; public readonly float Z; public GravityVector(float x, float y, float z) { if (!Valid(x) || !Valid(y) || !Valid(z)) { throw new ArgumentOutOfRangeException("x"); } X = x; Y = y; Z = z; } private static bool Valid(float n) { if (VoteSettings.Finite(n)) { return Math.Abs(n) <= 1000f; } return false; } public GravityVector Scale(float factor) { return new GravityVector(X * factor, Y * factor, Z * factor); } } public sealed class GravityLease { private readonly Func<GravityVector> read; private readonly Action<GravityVector> write; private GravityVector original; private string run = ""; public bool Active => run != ""; public GravityLease(Func<GravityVector> read, Action<GravityVector> write) { this.read = read; this.write = write; } public void Apply(string runId, GravityVector hostBaseline, float factor = 0.6f) { if (string.IsNullOrEmpty(runId)) { throw new ArgumentException("Effect requires a run identity"); } if (!VoteSettings.Finite(factor) || factor < 0.1f || factor > 4f) { throw new ArgumentOutOfRangeException("factor"); } if (run != runId) { Restore(); original = read(); run = runId; } write(hostBaseline.Scale(factor)); } public void Restore() { if (Active) { write(original); run = ""; } } } public static class LowGravity { public const string Id = "low_gravity"; public const float Factor = 0.6f; public static VoteOption[] Candidates(bool skip) { VoteOption voteOption = new VoteOption("low_gravity", "Low Gravity", "60% gravity for balls and players. Lasts this run; does not stack."); if (skip) { return new VoteOption[2] { voteOption, new VoteOption("skip", "Skip", "No new modifier. Uses one shared skip.") }; } return new VoteOption[1] { voteOption }; } } public sealed class ImpactRearm { private double settledSince = double.NaN; public bool Blocked { get; private set; } public void Suppress() { Blocked = true; settledSince = double.NaN; } public void Observe(double now, bool grounded, float speed) { if (!Blocked) { return; } if (!grounded || float.IsNaN(speed) || float.IsInfinity(speed) || speed > 1.5f) { settledSince = double.NaN; return; } if (double.IsNaN(settledSince)) { settledSince = now; } if (now - settledSince >= 0.75) { Blocked = false; settledSince = double.NaN; } } } public sealed class IntermissionGate { private Action continuation; private Func<bool> valid; private string run = ""; private int hole = -1; public bool Held => continuation != null; public bool WasIntercepted(string runId, int holeIndex) { if (run == runId) { return hole == holeIndex; } return false; } public bool Hold(string runId, int holeIndex, Action resume, Func<bool> isValid) { if (Held || WasIntercepted(runId, holeIndex)) { return false; } if (resume == null || isValid == null) { throw new ArgumentNullException(); } run = runId; hole = holeIndex; continuation = resume; valid = isValid; return true; } public bool Release() { if (!Held) { return false; } Action action = continuation; Func<bool> func = valid; continuation = null; valid = null; if (!func()) { return false; } action(); return true; } public void Cancel() { continuation = null; valid = null; run = ""; hole = -1; } } [Flags] public enum EffectChannel { None = 0, ShotPower = 1, Gravity = 2, BallMass = 4, Scale = 8, Bounce = 0x10, Friction = 0x20, Knockback = 0x40, ItemSpawn = 0x80, Inventory = 0x100, Explosions = 0x200, Teleport = 0x400, Ranking = 0x800, Protection = 0x1000, Traffic = 0x2000, WorldEvents = 0x4000, HoleGeometry = 0x8000, All = 0xFFFF } public enum ModifierRarity { Common, Rare, Legendary, Boss } public enum EffectDuration { Run, OneHole } public enum StackPolicy { Unique } public sealed class ModifierDefinition { private readonly Contribution[] contributions; public string Id { get; } public string Name { get; } public string Description { get; } public ModifierRarity Rarity { get; } public EffectDuration Duration { get; } public StackPolicy Stacking => StackPolicy.Unique; public string ExclusiveGroup { get; } public EffectChannel Channel { get; } public float Factor { get; } public int Weight { get; } public Contribution[] Contributions => (Contribution[])contributions.Clone(); public Mechanic Rule { get; } public bool TemporarySafe => Rule == Mechanic.None; public ModifierDefinition(string id, string name, ModifierRarity rarity, EffectChannel channel, float factor, string group = "", EffectDuration duration = EffectDuration.Run, int weight = 1, Contribution[] contributions = null, Mechanic rule = Mechanic.None, string description = null) { if (string.IsNullOrEmpty(id) || (!ValidFactor(factor) && contributions == null) || weight < 1 || weight > 100 || channel == EffectChannel.None || (channel & ~EffectChannel.All) != EffectChannel.None) { throw new ArgumentException("Invalid modifier definition"); } this.contributions = ((contributions != null) ? ((Contribution[])contributions.Clone()) : new Contribution[1] { new Contribution(channel switch { EffectChannel.Gravity => Parameter.Gravity, EffectChannel.ShotPower => Parameter.ShotPower, _ => Parameter.BallMass, }, factor) }); Rule = rule; Id = id; Name = name; Rarity = rarity; Channel = channel; Factor = factor; ExclusiveGroup = group; Duration = duration; Weight = weight; string text = (factor * 100f).ToString("0", CultureInfo.InvariantCulture) + "%"; Description = description ?? (rarity.ToString() + " | " + text + " " + channel switch { EffectChannel.Gravity => "global gravity", EffectChannel.ShotPower => "ball shot speed", _ => "ball mass", } + ". " + ((duration == EffectDuration.Run) ? "For this run." : "Next hole only.")); } public static bool ValidFactor(float f) { if (VoteSettings.Finite(f) && f >= 0.1f) { return f <= 4f; } return false; } } public sealed class ModifierSettings { private readonly Dictionary<string, float> extra; public KeyValuePair<string, float>[] Extra => extra.OrderBy<KeyValuePair<string, float>, string>((KeyValuePair<string, float> p) => p.Key, StringComparer.Ordinal).ToArray(); public float Interval => Get("IntervalSeconds", 20f); public float ImpactThreshold => Get("ImpactThreshold", 12f); public float ExplosionCooldown => Get("ExplosionCooldown", 2f); public float ExplosionRadius => Get("ExplosionRadius", 5f); public float PowerSurge { get; } public float HeavyBall { get; } public float Featherweight { get; } public float LowGravity { get; } public float HighGravity { get; } public float Get(string key, float fallback) { if (!extra.TryGetValue(key, out var value)) { return fallback; } return value; } public ModifierSettings(float power = 1.2f, float heavy = 2f, float feather = 0.5f, float low = 0.6f, float high = 1.5f, IEnumerable<KeyValuePair<string, float>> tuning = null) { if (!ModifierDefinition.ValidFactor(power) || !ModifierDefinition.ValidFactor(heavy) || !ModifierDefinition.ValidFactor(feather) || !ModifierDefinition.ValidFactor(low) || !ModifierDefinition.ValidFactor(high) || power < 1f || power > 3f || heavy < 1f || feather > 1f || low > 1f || high < 1f) { throw new ArgumentOutOfRangeException("power"); } extra = ((tuning == null) ? new Dictionary<string, float>() : tuning.ToDictionary<KeyValuePair<string, float>, string, float>((KeyValuePair<string, float> p) => p.Key, (KeyValuePair<string, float> p) => p.Value, StringComparer.Ordinal)); if (extra.Count > 256 || extra.Any((KeyValuePair<string, float> p) => p.Key.Length > 64 || !VoteSettings.Finite(p.Value) || p.Value < 0.01f || p.Value > 120f)) { throw new ArgumentException("Invalid tuning"); } if (Interval < 5f || Interval > 120f || ImpactThreshold < 5f || ImpactThreshold > 80f || ExplosionCooldown < 0.5f || ExplosionCooldown > 30f || ExplosionRadius < 1f || ExplosionRadius > 12f) { throw new ArgumentException("Unsafe runtime settings"); } PowerSurge = power; HeavyBall = heavy; Featherweight = feather; LowGravity = low; HighGravity = high; } } public sealed class ActiveModifier { private int lastCompleted = -1; public string Id { get; } public int FirstHole { get; } public int RemainingHoles { get; private set; } public bool Suspended { get; set; } public int Variant { get; set; } public ActiveModifier(string id, int firstHole, int remaining = -1, bool suspended = false) { Id = id; FirstHole = firstHole; RemainingHoles = remaining; Suspended = suspended; } public bool CompleteHole(int hole) { if (hole < FirstHole || hole <= lastCompleted || RemainingHoles < 1) { return false; } lastCompleted = hole; RemainingHoles--; return RemainingHoles == 0; } public ActiveModifier Copy() { return new ActiveModifier(Id, FirstHole, RemainingHoles, Suspended) { lastCompleted = lastCompleted, Variant = Variant }; } } public readonly struct EffectValues { private readonly float[] values; public float this[Parameter channel] { get { if (values != null) { return values[(int)channel]; } return 1f; } } public float ShotPower => this[Parameter.ShotPower]; public float Gravity => this[Parameter.Gravity]; public float EffectiveBallGravity => Math.Max(0.2f, Gravity * this[Parameter.BallGravity]); public float BallGravityScale => EffectiveBallGravity / Gravity; public float BallMass => this[Parameter.BallMass]; public static EffectValues Normal => new EffectValues(1f, 1f, 1f); public EffectValues(float shot, float gravity, float mass) { values = Enumerable.Repeat(1f, 16).ToArray(); values[0] = shot; values[1] = gravity; values[2] = mass; } public EffectValues(float[] source) { values = (float[])source.Clone(); } } public sealed class ModifierRegistry { private readonly Dictionary<string, ModifierDefinition> definitions; private readonly ModifierSettings settings; public ModifierDefinition[] Definitions => definitions.Values.OrderBy<ModifierDefinition, string>((ModifierDefinition d) => d.Id, StringComparer.Ordinal).ToArray(); public ModifierRegistry(IEnumerable<ModifierDefinition> source, ModifierSettings settings = null) { this.settings = settings ?? new ModifierSettings(); definitions = source.ToDictionary<ModifierDefinition, string>((ModifierDefinition d) => d.Id, StringComparer.Ordinal); } public ModifierDefinition Get(string id) { if (!definitions.TryGetValue(id, out var value)) { return null; } return value; } public static ModifierRegistry Create(ModifierSettings s) { return new ModifierRegistry(CanonicalCatalog.Create(s), s); } public EffectValues Compose(IEnumerable<ActiveModifier> effects) { double[] array = Enumerable.Repeat(1.0, 16).ToArray(); bool dunk = false; foreach (ActiveModifier item in effects.Where((ActiveModifier e) => !e.Suspended).OrderBy<ActiveModifier, string>((ActiveModifier e) => e.Id, StringComparer.Ordinal)) { ModifierDefinition modifierDefinition = Get(item.Id) ?? throw new ArgumentException("Unknown effect"); dunk |= modifierDefinition.Rule == Mechanic.DunkGolf; foreach (Contribution item2 in modifierDefinition.Contributions.Concat((modifierDefinition.Rule == Mechanic.RandomRules) ? Get(CanonicalCatalog.TemporaryRuleId(item.Variant)).Contributions : CanonicalCatalog.Variation(modifierDefinition.Rule, item.Variant, settings))) { array[(int)item2.Parameter] *= item2.Factor; } } array[1] = Math.Max(0.2, array[1]); return new EffectValues(array.Select((double v, int i) => Clamp(v, CanonicalCatalog.Minimum((Parameter)i), (i == 3 && !dunk) ? 4f : CanonicalCatalog.Maximum((Parameter)i))).ToArray()); } private static float Clamp(double x, double min, double max) { return (float)Math.Max(min, Math.Min(max, x)); } public void Validate(ActiveModifier[] effects, string[] available, PersistenceMode persistence = PersistenceMode.StackForRun) { if (available.Distinct().Count() != available.Length || available.Any((string id) => Get(id) == null) || effects.Select((ActiveModifier e) => e.Id).Distinct().Count() != effects.Length) { throw new ArgumentException("Unknown or duplicate modifiers"); } HashSet<string> hashSet = new HashSet<string>(); foreach (ActiveModifier activeModifier in effects) { ModifierDefinition modifierDefinition = Get(activeModifier.Id); if (modifierDefinition == null || !available.Contains(activeModifier.Id) || activeModifier.FirstHole < 0 || activeModifier.FirstHole > 999 || activeModifier.Variant < 0 || activeModifier.Variant > 31 || (!CanonicalCatalog.IsTimed(modifierDefinition.Rule) && activeModifier.Variant != 0) || activeModifier.RemainingHoles != ((modifierDefinition.Duration != EffectDuration.Run || persistence == PersistenceMode.PerHole) ? 1 : (-1)) || (modifierDefinition.ExclusiveGroup != "" && !hashSet.Add(modifierDefinition.ExclusiveGroup))) { throw new ArgumentException("Invalid active modifier"); } } } } public sealed class ModifierManager { private readonly HashSet<string> available; private readonly List<ActiveModifier> active = new List<ActiveModifier>(); private int breatherHole = -1; public ModifierRegistry Registry { get; } public ActiveModifier[] Active => active.Select(delegate(ActiveModifier e) { ActiveModifier activeModifier = e.Copy(); if (breatherHole >= 0) { activeModifier.Suspended = true; } return activeModifier; }).ToArray(); public string[] Available => available.OrderBy<string, string>((string id) => id, StringComparer.Ordinal).ToArray(); public EffectValues Values => Registry.Compose(Active); public bool HasEligible => Available.Any(CanActivate); public Func<ModifierDefinition, bool> ContextAllows { get; set; } = (ModifierDefinition d) => true; public ModifierManager(ModifierRegistry registry, IEnumerable<string> enabled, EffectChannel capabilities) { Registry = registry; available = new HashSet<string>(enabled.Where((string id) => registry.Get(id) != null && (registry.Get(id).Channel & capabilities) == registry.Get(id).Channel)); } public bool CanActivate(string id) { ModifierDefinition d = Registry.Get(id); if (d != null && ContextAllows(d) && available.Contains(id)) { return !active.Any((ActiveModifier a) => a.Id == id || (d.ExclusiveGroup != "" && Registry.Get(a.Id).ExclusiveGroup == d.ExclusiveGroup)); } return false; } public bool Activate(string id, int firstHole, PersistenceMode persistence = PersistenceMode.StackForRun) { if (firstHole < 0 || firstHole > 999 || !CanActivate(id)) { return false; } ModifierDefinition modifierDefinition = Registry.Get(id); active.Add(new ActiveModifier(id, firstHole, (modifierDefinition.Duration != EffectDuration.Run || persistence == PersistenceMode.PerHole) ? 1 : (-1))); return true; } public bool CompleteHole(int hole) { bool flag = breatherHole >= 0 && hole >= breatherHole; if (flag) { breatherHole = -1; } return active.RemoveAll((ActiveModifier e) => e.CompleteHole(hole)) > 0 || flag; } public void SuspendForHole(int hole) { if (hole < 0 || hole > 999) { throw new ArgumentOutOfRangeException("hole"); } breatherHole = hole; } public bool Remove(string id) { return active.RemoveAll((ActiveModifier e) => e.Id == id) > 0; } public bool Suspend(string id, bool value) { ActiveModifier activeModifier = active.FirstOrDefault((ActiveModifier a) => a.Id == id); if (activeModifier == null || activeModifier.Suspended == value) { return false; } activeModifier.Suspended = value; return true; } public bool SetVariant(string id, int variant) { ActiveModifier activeModifier = active.FirstOrDefault((ActiveModifier a) => a.Id == id); if (activeModifier == null || variant < 0 || variant > 31 || !CanonicalCatalog.IsTimed(Registry.Get(id).Rule)) { return false; } activeModifier.Variant = variant; return true; } public VoteOption[] Candidates(int count, bool skip, RunRandom random) { if (count < 1 || count > 5) { throw new ArgumentOutOfRangeException("count"); } List<ModifierDefinition> list = Available.Where(CanActivate).Select(Registry.Get).ToList(); List<VoteOption> list2 = new List<VoteOption>(); while (list.Count > 0 && list2.Count < count) { int num = random.Next(list.Sum((ModifierDefinition d) => d.Weight)); int index = 0; while (num >= list[index].Weight) { num -= list[index++].Weight; } ModifierDefinition modifierDefinition = list[index]; list.RemoveAt(index); list2.Add(new VoteOption(modifierDefinition.Id, modifierDefinition.Name, modifierDefinition.Description)); } if (list2.Count > 0 && skip) { list2.Add(new VoteOption("skip", "Skip", "No new modifier. Uses one shared skip.")); } return list2.ToArray(); } public void Clear() { active.Clear(); breatherHole = -1; } } public sealed class ScalarLease { private readonly Func<float> read; private readonly Action<float> write; private bool owned; private float baseline; public ScalarLease(Func<float> read, Action<float> write) { this.read = read; this.write = write; } public void Apply(float factor) { if (!VoteSettings.Finite(factor) || factor <= 0f || factor > 10f) { throw new ArgumentOutOfRangeException("factor"); } if (factor == 1f) { Restore(); return; } if (!owned) { baseline = read(); owned = true; } write(baseline * factor); } public void Restore() { if (owned) { write(baseline); owned = false; } } } public enum SelectionMode { Vote, Random, Hybrid } public enum PersistenceMode { StackForRun, PerHole, Mixed } public enum SkipMode { SharedRun, PerPlayer, Unlimited, Disabled } public enum SkipBehavior { NoNewModifier, VanillaHole } public sealed class ProgressionSettings { private readonly int[] tiers; private readonly float[] thresholds; private readonly Dictionary<string, int> weights; public SelectionMode Selection { get; } public PersistenceMode Persistence { get; } public SkipMode Skips { get; } public SkipBehavior SkipEffect { get; } public bool BossEnabled { get; } public int BossInterval { get; } public bool RandomSkips { get; } public int RandomSkipWeight { get; } public int RandomModifierWeight { get; } public int[] TierWeights => (int[])tiers.Clone(); public float[] PhaseThresholds => (float[])thresholds.Clone(); public KeyValuePair<string, int>[] ModifierWeights => weights.OrderBy<KeyValuePair<string, int>, string>((KeyValuePair<string, int> p) => p.Key, StringComparer.Ordinal).ToArray(); public int Weight(string id) { if (!weights.TryGetValue(id, out var value)) { return 100; } return value; } public ProgressionSettings(SelectionMode selection = SelectionMode.Vote, PersistenceMode persistence = PersistenceMode.StackForRun, SkipMode skips = SkipMode.SharedRun, SkipBehavior skipEffect = SkipBehavior.NoNewModifier, bool bossEnabled = true, int bossInterval = 4, bool randomSkips = false, int randomSkipWeight = 10, int randomModifierWeight = 100, int[] tierWeights = null, float[] phaseThresholds = null, IEnumerable<KeyValuePair<string, int>> modifierWeights = null) { if (!Enum.IsDefined(typeof(SelectionMode), selection) || !Enum.IsDefined(typeof(PersistenceMode), persistence) || !Enum.IsDefined(typeof(SkipMode), skips) || !Enum.IsDefined(typeof(SkipBehavior), skipEffect) || bossInterval < 1 || bossInterval > 99 || randomSkipWeight < 0 || randomSkipWeight > 10000 || randomModifierWeight < 1 || randomModifierWeight > 10000) { throw new ArgumentException("Invalid progression settings"); } tiers = (int[])(tierWeights ?? RogueGolfDefaults.TierWeights).Clone(); thresholds = (float[])(phaseThresholds ?? RogueGolfDefaults.PhaseThresholds).Clone(); weights = ((modifierWeights == null) ? new Dictionary<string, int>() : modifierWeights.ToDictionary<KeyValuePair<string, int>, string, int>((KeyValuePair<string, int> p) => p.Key, (KeyValuePair<string, int> p) => p.Value, StringComparer.Ordinal)); if (tiers.Length != 14 || tiers.Any((int w) => w < 0 || w > 10000) || thresholds.Length != 4 || thresholds[0] != 0f || thresholds.Any((float p) => float.IsNaN(p) || float.IsInfinity(p) || p < 0f || p > 15000f) || !thresholds.SequenceEqual(from p in thresholds.Distinct() orderby p select p) || weights.Count > 128 || weights.Any((KeyValuePair<string, int> p) => string.IsNullOrEmpty(p.Key) || p.Key.Length > 32 || p.Value < 0 || p.Value > 10000)) { throw new ArgumentException("Invalid progression weights or bands"); } Selection = selection; Persistence = persistence; Skips = skips; SkipEffect = skipEffect; BossEnabled = bossEnabled; BossInterval = bossInterval; RandomSkips = randomSkips; RandomSkipWeight = randomSkipWeight; RandomModifierWeight = randomModifierWeight; } public bool IsBoss(int roundOrdinal) { return BossSchedule.IsBoss(roundOrdinal, BossEnabled, BossInterval); } public ProgressionPhase GetPhase(float progress) { if (float.IsNaN(progress) || float.IsInfinity(progress)) { throw new ArgumentOutOfRangeException("progress"); } float num = Math.Max(0f, Math.Min(1f, progress)) * 100f; int result = 0; for (int i = 1; i < thresholds.Length; i++) { if (num >= thresholds[i]) { result = i; } } return (ProgressionPhase)result; } public int TierWeight(float progress, ModifierRarity rarity, bool boss) { if (boss) { return rarity switch { ModifierRarity.Boss => tiers[13], ModifierRarity.Legendary => tiers[12], _ => 0, }; } if (rarity == ModifierRarity.Boss) { return 0; } int phase = (int)GetPhase(progress); return tiers[(int)(phase * 3 + rarity)]; } } public static class ProgressionCandidates { public static VoteOption[] Generate(ModifierManager manager, ProgressionSettings settings, int upcomingHole, int totalHoles, bool boss, int count, RunRandom random) { if (count < 1 || count > 5 || upcomingHole < 1 || upcomingHole > 1000) { throw new ArgumentOutOfRangeException("count"); } if (upcomingHole == 1) { return Array.Empty<VoteOption>(); } float progress = CourseProgress.GetNormalizedProgress(upcomingHole, totalHoles); List<ModifierDefinition> list = (from d in manager.Available.Where(manager.CanActivate).Select(manager.Registry.Get) where settings.Weight(d.Id) > 0 && settings.TierWeight(progress, d.Rarity, boss) > 0 select d).OrderBy<ModifierDefinition, string>((ModifierDefinition d) => d.Id, StringComparer.Ordinal).ToList(); List<VoteOption> list2 = new List<VoteOption>(); while (list.Count > 0 && list2.Count < count) { ModifierRarity[] array = (from t in list.Select((ModifierDefinition d) => d.Rarity).Distinct() orderby t select t).ToArray(); int num = random.Next(array.Sum((ModifierRarity t) => settings.TierWeight(progress, t, boss))); ModifierRarity tier = array[0]; ModifierRarity[] array2 = array; for (int num2 = 0; num2 < array2.Length; num2++) { ModifierRarity rarity = (tier = array2[num2]); num -= settings.TierWeight(progress, rarity, boss); if (num < 0) { break; } } ModifierDefinition[] array3 = list.Where((ModifierDefinition d) => d.Rarity == tier).ToArray(); num = random.Next(array3.Sum((ModifierDefinition d) => settings.Weight(d.Id))); ModifierDefinition modifierDefinition = array3[0]; ModifierDefinition[] array4 = array3; foreach (ModifierDefinition modifierDefinition2 in array4) { modifierDefinition = modifierDefinition2; num -= settings.Weight(modifierDefinition2.Id); if (num < 0) { break; } } string text = modifierDefinition.Description; if (settings.Persistence == PersistenceMode.PerHole) { text = text.Replace("For this run.", "Next hole only."); } list2.Add(new VoteOption(modifierDefinition.Id, modifierDefinition.Name, text)); list.Remove(modifierDefinition); } return list2.ToArray(); } public static string Automatic(VoteOption[] candidates, ProgressionSettings settings, bool skipAvailable, RunRandom random) { if (candidates.Length == 0) { return "none"; } if (skipAvailable && settings.RandomSkips && settings.RandomSkipWeight > 0 && random.Next(settings.RandomModifierWeight + settings.RandomSkipWeight) < settings.RandomSkipWeight) { return "skip"; } return candidates[random.Next(candidates.Length)].Id; } } public sealed class SkipLedger { private readonly SkipMode mode; private readonly int initial; private readonly Dictionary<ulong, int> personal = new Dictionary<ulong, int>(); public int Shared { get; private set; } public SkipLedger(SkipMode mode, int budget) { if (budget < 0 || budget > 99) { throw new ArgumentOutOfRangeException("budget"); } this.mode = mode; initial = budget; Shared = budget; } public int Remaining(ulong player) { if (mode == SkipMode.Disabled) { return 0; } if (mode == SkipMode.Unlimited) { return 99; } if (mode == SkipMode.SharedRun) { return Shared; } if (player == 0L) { return 0; } if (!personal.TryGetValue(player, out var value)) { return initial; } return value; } public bool Charge(IEnumerable<ulong> payers) { ulong[] array = payers.Distinct().ToArray(); if (array.Length == 0 || array.Any((ulong id) => Remaining(id) <= 0)) { return false; } if (mode == SkipMode.SharedRun) { Shared--; } if (mode == SkipMode.PerPlayer) { ulong[] array2 = array; foreach (ulong num2 in array2) { personal[num2] = Remaining(num2) - 1; } } return true; } } public sealed class RunChoice { public int Hole { get; } public string Id { get; } public bool Boss { get; } public int PickIndex { get; } public int PickCount { get; } public int AcquisitionOrdinal { get; } public RunChoice(int hole, string id, bool boss, int pickIndex = 1, int pickCount = 1, int acquisitionOrdinal = 0) { if (hole < 2 || hole > 1000 || string.IsNullOrEmpty(id) || id.Length > 32 || pickIndex < 1 || pickIndex > pickCount || pickCount > 5 || (boss && pickCount != 1) || acquisitionOrdinal < 0 || acquisitionOrdinal > 4995) { throw new ArgumentException("Invalid run choice"); } Hole = hole; Id = id; Boss = boss; PickIndex = pickIndex; PickCount = pickCount; AcquisitionOrdinal = acquisitionOrdinal; } } public enum PacketKind : byte { Hello = 1, Snapshot, Vote, BreakTie, Challenge, Proof, Admitted } public sealed class RunSnapshot { public string Session = ""; public string RunId = ""; public string Winner = ""; public string Notice = ""; public long Revision; public RunState State; public int Hole = -1; public int Skips; public int VoteId; public int Recipient; public int Host; public uint Seed; public bool ModifierMode; public ProgressionSettings Progression = new ProgressionSettings(); public int SelectionNumber; public DensitySettings Density = new DensitySettings(); public int RoundOrdinal; public int AcquisitionOrdinal; public int CurrentRoundPickIndex; public int CurrentRoundPickCount; public bool BossSelection; public bool SummaryComplete; public RunChoice[] History = Array.Empty<RunChoice>(); public Dictionary<int, int> PersonalSkips = new Dictionary<int, int>(); public Dictionary<ulong, float> PlayerShotFactors = new Dictionary<ulong, float>(); public GravityVector GravityBaseline; public ModifierSettings ModifierSettings = new ModifierSettings(); public string[] AvailableModifiers = Array.Empty<string>(); public ActiveModifier[] ActiveModifiers = Array.Empty<ActiveModifier>(); public double Deadline; public double TieDeadline; public double RevealUntil; public double NextCycleAt; public VoteSettings Settings = new VoteSettings(); public VoteOption[] Options = Array.Empty<VoteOption>(); public int[] Eligible = Array.Empty<int>(); public Dictionary<int, string> Ballots = new Dictionary<int, string>(); public string[] Tied = Array.Empty<string>(); } public sealed class Packet { public PacketKind Kind; public string Session = ""; public string Nonce = ""; public string RunId = ""; public string Option = ""; public int VoteId; public long Sequence; public EffectChannel Capabilities; public string Build = ""; public int Policy; public RunSnapshot Snapshot; } public static class Wire { public const int Version = 10; public const int MaxBytes = 16384; public const int MaxPlayers = 64; private static readonly Encoding Utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); public static byte[] Encode(Packet packet) { using MemoryStream memoryStream = new MemoryStream(); using BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Utf8, leaveOpen: true); binaryWriter.Write(10); binaryWriter.Write((byte)packet.Kind); Text(binaryWriter, packet.Session, 64); if (packet.Kind == PacketKind.Hello) { Text(binaryWriter, packet.Nonce, 64); binaryWriter.Write((ushort)packet.Capabilities); } else if (packet.Kind == PacketKind.Challenge || packet.Kind == PacketKind.Proof || packet.Kind == PacketKind.Admitted) { Text(binaryWriter, packet.Nonce, 64); Text(binaryWriter, packet.Build, 32); binaryWriter.Write(packet.Policy); binaryWriter.Write((ushort)packet.Capabilities); } else if (packet.Kind == PacketKind.Snapshot) { WriteSnapshot(binaryWriter, packet.Snapshot); } else { if (packet.Kind != PacketKind.Vote && packet.Kind != PacketKind.BreakTie) { throw new InvalidDataException("Unknown packet kind"); } Text(binaryWriter, packet.RunId, 64); binaryWriter.Write(packet.VoteId); binaryWriter.Write(packet.Sequence); Text(binaryWriter, packet.Option, 32); } binaryWriter.Flush(); if (memoryStream.Length > 16384) { throw new InvalidDataException("Oversized packet"); } return memoryStream.ToArray(); } public static Packet Decode(byte[] bytes) { if (bytes == null || bytes.Length > 16384) { throw new InvalidDataException("Oversized packet"); } using MemoryStream memoryStream = new MemoryStream(bytes, writable: false); using BinaryReader binaryReader = new BinaryReader(memoryStream, Utf8, leaveOpen: true); if (binaryReader.ReadInt32() != 10) { throw new InvalidDataException("Protocol mismatch"); } Packet packet = new Packet { Kind = (PacketKind)binaryReader.ReadByte(), Session = Text(binaryReader, 64) }; if (packet.Kind == PacketKind.Hello) { packet.Nonce = Text(binaryReader, 64); packet.Capabilities = (EffectChannel)binaryReader.ReadUInt16(); if ((packet.Capabilities & ~EffectChannel.All) != EffectChannel.None) { throw new InvalidDataException("Invalid capabilities"); } } else if (packet.Kind == PacketKind.Challenge || packet.Kind == PacketKind.Proof || packet.Kind == PacketKind.Admitted) { packet.Nonce = Text(binaryReader, 64); packet.Build = Text(binaryReader, 32); packet.Policy = binaryReader.ReadInt32(); packet.Capabilities = (EffectChannel)binaryReader.ReadUInt16(); if ((packet.Capabilities & ~EffectChannel.All) != EffectChannel.None) { throw new InvalidDataException("Invalid capabilities"); } } else if (packet.Kind == PacketKind.Snapshot) { packet.Snapshot = ReadSnapshot(binaryReader); packet.Snapshot.Session = packet.Session; } else { if (packet.Kind != PacketKind.Vote && packet.Kind != PacketKind.BreakTie) { throw new InvalidDataException("Unknown packet kind"); } packet.RunId = Text(binaryReader, 64); packet.VoteId = binaryReader.ReadInt32(); packet.Sequence = binaryReader.ReadInt64(); packet.Option = Text(binaryReader, 32); } if (memoryStream.Position != memoryStream.Length) { throw new InvalidDataException("Trailing bytes"); } return packet; } private static void WriteSnapshot(BinaryWriter w, RunSnapshot s) { Text(w, s.RunId, 64); w.Write(s.Revision); w.Write((byte)s.State); w.Write(s.Hole); w.Write(s.Skips); w.Write(s.VoteId); w.Write(s.Recipient); w.Write(s.Host); w.Write(s.Seed); w.Write(s.ModifierMode); WriteProgression(w, s); w.Write(s.GravityBaseline.X); w.Write(s.GravityBaseline.Y); w.Write(s.GravityBaseline.Z); w.Write(s.ModifierSettings.PowerSurge); w.Write(s.ModifierSettings.HeavyBall); w.Write(s.ModifierSettings.Featherweight); w.Write(s.ModifierSettings.LowGravity); w.Write(s.ModifierSettings.HighGravity); Count(w, s.ModifierSettings.Extra.Length, 200); KeyValuePair<string, float>[] extra = s.ModifierSettings.Extra; for (int i = 0; i < extra.Length; i++) { KeyValuePair<string, float> keyValuePair = extra[i]; Text(w, keyValuePair.Key, 64); w.Write(keyValuePair.Value); } Count(w, s.PlayerShotFactors.Count, 64); foreach (KeyValuePair<ulong, float> item in s.PlayerShotFactors.OrderBy((KeyValuePair<ulong, float> p) => p.Key)) { w.Write(item.Key); w.Write(item.Value); } Count(w, s.AvailableModifiers.Length, 128); string[] availableModifiers = s.AvailableModifiers; foreach (string value in availableModifiers) { Text(w, value, 32); } Count(w, s.ActiveModifiers.Length, 128); ActiveModifier[] activeModifiers = s.ActiveModifiers; foreach (ActiveModifier activeModifier in activeModifiers) { Text(w, activeModifier.Id, 32); w.Write(activeModifier.FirstHole); w.Write(activeModifier.RemainingHoles); w.Write(activeModifier.Suspended); w.Write(activeModifier.Variant); } w.Write(s.Deadline); w.Write(s.TieDeadline); w.Write(s.RevealUntil); w.Write(s.NextCycleAt); Text(w, s.Winner, 32); Text(w, s.Notice, 256); w.Write(s.Settings.CandidateCount); w.Write(s.Settings.Duration); w.Write(s.Settings.AllowChanges); w.Write(s.Settings.EarlyClose); w.Write((byte)s.Settings.Tie); w.Write(s.Settings.SkipBudget); w.Write(s.Settings.RevealSeconds); Count(w, s.Options.Length, 6); VoteOption[] options = s.Options; foreach (VoteOption voteOption in options) { Text(w, voteOption.Id, 32); Text(w, voteOption.Name, 64); Text(w, voteOption.Description, 256); } Count(w, s.Eligible.Length, 64); int[] eligible = s.Eligible; foreach (int value2 in eligible) { w.Write(value2); } Count(w, s.Ballots.Count, 64); foreach (KeyValuePair<int, string> item2 in s.Ballots.OrderBy((KeyValuePair<int, string> x) => x.Key)) { w.Write(item2.Key); Text(w, item2.Value, 32); } Count(w, s.Tied.Length, 6); availableModifiers = s.Tied; foreach (string value3 in availableModifiers) { Text(w, value3, 32); } } private static RunSnapshot ReadSnapshot(BinaryReader r) { RunSnapshot s = new RunSnapshot { RunId = Text(r, 64), Revision = r.ReadInt64(), State = (RunState)r.ReadByte(), Hole = r.ReadInt32(), Skips = r.ReadInt32(), VoteId = r.ReadInt32(), Recipient = r.ReadInt32(), Host = r.ReadInt32(), Seed = r.ReadUInt32(), ModifierMode = r.ReadBoolean() }; ReadProgression(r, s); s.GravityBaseline = new GravityVector(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()); float power = r.ReadSingle(); float heavy = r.ReadSingle(); float feather = r.ReadSingle(); float low = r.ReadSingle(); float high = r.ReadSingle(); Dictionary<string, float> dictionary = new Dictionary<string, float>(); int num = Count(r, 200); for (int i = 0; i < num; i++) { dictionary.Add(Text(r, 64), r.ReadSingle()); } s.ModifierSettings = new ModifierSettings(power, heavy, feather, low, high, dictionary); int num2 = Count(r, 64); for (int j = 0; j < num2; j++) { ulong key = r.ReadUInt64(); float num3 = r.ReadSingle(); if (!VoteSettings.Finite(num3) || num3 < 0.5f || num3 > 1.5f) { throw new InvalidDataException("Invalid rank factor"); } s.PlayerShotFactors.Add(key, num3); } s.AvailableModifiers = new string[Count(r, 128)]; for (int k = 0; k < s.AvailableModifiers.Length; k++) { s.AvailableModifiers[k] = Text(r, 32); } s.ActiveModifiers = new ActiveModifier[Count(r, 128)]; for (int l = 0; l < s.ActiveModifiers.Length; l++) { s.ActiveModifiers[l] = new ActiveModifier(Text(r, 32), r.ReadInt32(), r.ReadInt32(), r.ReadBoolean()) { Variant = r.ReadInt32() }; } ModifierRegistry.Create(s.ModifierSettings).Validate(s.ActiveModifiers, s.AvailableModifiers, s.Progression.Persistence); s.Deadline = r.ReadDouble(); s.TieDeadline = r.ReadDouble(); s.RevealUntil = r.ReadDouble(); s.NextCycleAt = r.ReadDouble(); s.Winner = Text(r, 32); s.Notice = Text(r, 256); if (s.Revision < 0 || !Enum.IsDefined(typeof(RunState), s.State) || s.Hole < -1 || s.Hole > 999 || s.Skips < 0 || s.Skips > 99 || !VoteSettings.Finite(s.Deadline) || !VoteSettings.Finite(s.TieDeadline) || !VoteSettings.Finite(s.RevealUntil) || !VoteSettings.Finite(s.NextCycleAt) || s.NextCycleAt < 0.0) { throw new InvalidDataException("Invalid snapshot fields"); } if (s.ActiveModifiers.Length != 0 && (!s.ModifierMode || s.RunId == "" || s.State == RunState.Inactive || s.State == RunState.CleaningUp || s.State == RunState.RunComplete)) { throw new InvalidDataException("Effect outside an active modifier run"); } s.Settings = new VoteSettings(r.ReadInt32(), r.ReadDouble(), r.ReadBoolean(), r.ReadBoolean(), (TieRule)r.ReadByte(), r.ReadInt32(), r.ReadDouble()); s.Options = new VoteOption[Count(r, 6)]; for (int m = 0; m < s.Options.Length; m++) { s.Options[m] = new VoteOption(Text(r, 32), Text(r, 64), Text(r, 256)); } s.Eligible = new int[Count(r, 64)]; for (int n = 0; n < s.Eligible.Length; n++) { s.Eligible[n] = r.ReadInt32(); } int num4 = Count(r, 64); for (int num5 = 0; num5 < num4; num5++) { int key2 = r.ReadInt32(); if (s.Ballots.ContainsKey(key2)) { throw new InvalidDataException("Duplicate ballot"); } s.Ballots.Add(key2, Text(r, 32)); } s.Tied = new string[Count(r, 6)]; for (int num6 = 0; num6 < s.Tied.Length; num6++) { s.Tied[num6] = Text(r, 32); } HashSet<string> ids = new HashSet<string>(s.Options.Select((VoteOption o) => o.Id)); if (ids.Count != s.Options.Length || s.Eligible.Distinct().Count() != s.Eligible.Length || s.Ballots.Any((KeyValuePair<int, string> b) => !s.Eligible.Contains(b.Key) || !ids.Contains(b.Value)) || s.Tied.Any((string t) => !ids.Contains(t)) || (s.Winner != "" && !ids.Contains(s.Winner))) { throw new InvalidDataException("Inconsistent snapshot"); } return s; } private static void WriteProgression(BinaryWriter w, RunSnapshot s) { ProgressionSettings progression = s.Progression; w.Write((byte)progression.Selection); w.Write((byte)progression.Persistence); w.Write((byte)progression.Skips); w.Write((byte)progression.SkipEffect); w.Write(progression.BossEnabled); w.Write(progression.BossInterval); w.Write(progression.RandomSkips); w.Write(progression.RandomSkipWeight); w.Write(progression.RandomModifierWeight); int[] tierWeights = progression.TierWeights; foreach (int value in tierWeights) { w.Write(value); } float[] phaseThresholds = progression.PhaseThresholds; foreach (float value2 in phaseThresholds) { w.Write(value2); } Count(w, progression.ModifierWeights.Length, 128); KeyValuePair<string, int>[] modifierWeights = progression.ModifierWeights; for (int i = 0; i < modifierWeights.Length; i++) { KeyValuePair<string, int> keyValuePair = modifierWeights[i]; Text(w, keyValuePair.Key, 32); w.Write(keyValuePair.Value); } w.Write((byte)s.Density.Mode); w.Write(s.Density.ShortRunSelectionFloor); w.Write(s.Density.MaxSelectionsPerOrdinaryRound); w.Write(s.RoundOrdinal); w.Write(s.AcquisitionOrdinal); w.Write(s.CurrentRoundPickIndex); w.Write(s.CurrentRoundPickCount); w.Write(s.SelectionNumber); w.Write(s.BossSelection); w.Write(s.SummaryComplete); Count(w, s.History.Length, 64); RunChoice[] history = s.History; foreach (RunChoice runChoice in history) { w.Write(runChoice.Hole); Text(w, runChoice.Id, 32); w.Write(runChoice.Boss); w.Write(runChoice.PickIndex); w.Write(runChoice.PickCount); w.Write(runChoice.AcquisitionOrdinal); } Count(w, s.PersonalSkips.Count, 64); foreach (KeyValuePair<int, int> item in s.PersonalSkips.OrderBy((KeyValuePair<int, int> pv) => pv.Key)) { w.Write(item.Key); w.Write(item.Value); } } private static void ReadProgression(BinaryReader r, RunSnapshot s) { SelectionMode selection = (SelectionMode)r.ReadByte(); PersistenceMode persistence = (PersistenceMode)r.ReadByte(); SkipMode skips = (SkipMode)r.ReadByte(); SkipBehavior skipEffect = (SkipBehavior)r.ReadByte(); bool bossEnabled = r.ReadBoolean(); int bossInterval = r.ReadInt32(); bool randomSkips = r.ReadBoolean(); int randomSkipWeight = r.ReadInt32(); int randomModifierWeight = r.ReadInt32(); int[] array = new int[14]; for (int i = 0; i < 14; i++) { array[i] = r.ReadInt32(); } float[] array2 = new float[4]; for (int j = 0; j < 4; j++) { array2[j] = r.ReadSingle(); } Dictionary<string, int> dictionary = new Dictionary<string, int>(); int num = Count(r, 128); for (int k = 0; k < num; k++) { dictionary.Add(Text(r, 32), r.ReadInt32()); } s.Progression = new ProgressionSettings(selection, persistence, skips, skipEffect, bossEnabled, bossInterval, randomSkips, randomSkipWeight, randomModifierWeight, array, array2, dictionary); s.Density = new DensitySettings((SelectionDensityMode)r.ReadByte(), r.ReadInt32(), r.ReadInt32()); s.RoundOrdinal = r.ReadInt32(); s.AcquisitionOrdinal = r.ReadInt32(); s.CurrentRoundPickIndex = r.ReadInt32(); s.CurrentRoundPickCount = r.ReadInt32(); if (s.RoundOrdinal < 0 || s.RoundOrdinal > 999 || s.AcquisitionOrdinal < 0 || s.AcquisitionOrdinal > 4995 || s.CurrentRoundPickIndex < 0 || s.CurrentRoundPickIndex > s.CurrentRoundPickCount || s.CurrentRoundPickCount > 5 || (s.CurrentRoundPickCount > 0 && s.CurrentRoundPickIndex == 0)) { throw new InvalidDataException("Invalid density round state"); } s.SelectionNumber = r.ReadInt32(); s.BossSelection = r.ReadBoolean(); s.SummaryComplete = r.ReadBoolean(); if (s.AcquisitionOrdinal > s.SelectionNumber || (s.BossSelection && s.CurrentRoundPickCount > 1)) { throw new InvalidDataException("Inconsistent density state"); } ModifierRegistry registry = ModifierRegistry.Create(new ModifierSettings()); if (s.SelectionNumber < 0 || s.SelectionNumber > 4995 || dictionary.Keys.Any((string id) => registry.Get(id) == null)) { throw new InvalidDataException("Invalid progression state"); } s.History = new RunChoice[Count(r, 64)]; for (int num2 = 0; num2 < s.History.Length; num2++) { RunChoice runChoice = new RunChoice(r.ReadInt32(), Text(r, 32), r.ReadBoolean(), r.ReadInt32(), r.ReadInt32(), r.ReadInt32()); if (runChoice.AcquisitionOrdinal > s.AcquisitionOrdinal || (num2 > 0 && s.History[num2 - 1].AcquisitionOrdinal > runChoice.AcquisitionOrdinal)) { throw new InvalidDataException("Invalid history acquisition order"); } if ((runChoice.Id != "skip" && runChoice.Id != "none" && registry.Get(runChoice.Id) == null) || (num2 > 0 && (s.History[num2 - 1].Hole > runChoice.Hole || (s.History[num2 - 1].Hole == runChoice.Hole && (s.History[num2 - 1].PickIndex >= runChoice.PickIndex || s.History[num2 - 1].PickCount != runChoice.PickCount || s.History[num2 - 1].Boss != runChoice.Boss))))) { throw new InvalidDataException("Invalid run history"); } s.History[num2] = runChoice; } if (s.History.Length > s.SelectionNumber) { throw new InvalidDataException("History exceeds selections"); } num = Count(r, 64); for (int num3 = 0; num3 < num; num3++) { int key = r.ReadInt32(); int num4 = r.ReadInt32(); if (num4 < 0 || num4 > 99) { throw new InvalidDataException("Invalid personal skip budget"); } s.PersonalSkips.Add(key, num4); } } private static void Text(BinaryWriter w, string value, int max) { byte[] bytes = Utf8.GetBytes(value ?? ""); if (bytes.Length > max) { throw new InvalidDataException("String too long"); } w.Write((ushort)bytes.Length); w.Write(bytes); } private static string Text(BinaryReader r, int max) { int num = r.ReadUInt16(); if (num > max) { throw new InvalidDataException("String too long"); } byte[] array = r.ReadBytes(num); if (array.Length != num) { throw new EndOfStreamException(); } return Utf8.GetString(array); } private static void Count(BinaryWriter w, int count, int max) { if (count < 0 || count > max) { throw new InvalidDataException("Collection too large"); } w.Write((byte)count); } private static int Count(BinaryReader r, int max) { byte num = r.ReadByte(); if (num > max) { throw new InvalidDataException("Collection too large"); } return num; } } public sealed class Replica { private string session = ""; public RunSnapshot Current { get; private set; } public void Reset(string expectedSession) { session = expectedSession; Current = null; } public bool Accept(RunSnapshot snapshot) { if (snapshot.Session != session || (Current != null && snapshot.Revision <= Current.Revision)) { return false; } Current = snapshot; return true; } } public static class RankEffects { public static Dictionary<ulong, float> Calculate(IEnumerable<ulong> nativeOrder, Mechanic rules, ModifierSettings settings) { ulong[] array = nativeOrder.ToArray(); if (array.Length > 64 || array.Distinct().Count() != array.Length) { throw new ArgumentException("Invalid leaderboard"); } Dictionary<ulong, float> dictionary = new Dictionary<ulong, float>(); if (array.Length < 2) { return dictionary; } for (int i = 0; i < array.Length; i++) { float num = 1f; if (i == 0 && (rules & Mechanic.LeaderTax) != Mechanic.None) { num *= settings.Get("LeaderTaxFactor", 0.8f); } if (i == array.Length - 1 && (rules & Mechanic.LastPlaceInsurance) != Mechanic.None) { num *= settings.Get("LastPlaceFactor", 1.2f); } if ((rules & Mechanic.ComebackSeason) != Mechanic.None) { num *= 1f + (settings.Get("ComebackMaximum", 1.3f) - 1f) * (float)i / (float)(array.Length - 1); } dictionary[array[i]] = Math.Max(0.5f, Math.Min(1.5f, num)); } return dictionary; } } public static class RogueGolfDefaults { public static class Zeus { public const int StormCap = 7; public const int MinBurst = 1; public const int MaxBurst = 2; public const float MinInterval = 0.8f; public const float MaxInterval = 1.5f; public const bool Verbose = false; public static int[] TargetWeights => new int[5] { 25, 25, 15, 20, 15 }; } public const bool Enabled = true; public const bool ModifierEnabled = true; public const SelectionMode Selection = SelectionMode.Vote; public const PersistenceMode Persistence = PersistenceMode.StackForRun; public const SkipMode SkipBudgetMode = SkipMode.SharedRun; public const SkipBehavior SkipEffect = SkipBehavior.NoNewModifier; public const bool BossEnabled = true; public const bool AutomaticSkips = false; public const int CandidateCards = 4; public const int StartingSkips = 2; public const int Seed = 0; public const int BossInterval = 4; public const int ModifierWeight = 100; public const int AutomaticSkipWeight = 10; public const int AutomaticModifierWeight = 100; public const float VoteSeconds = 15f; public const float RevealSeconds = 3f; public const bool AllowVoteChanges = true; public const bool CloseWhenAllVote = true; public const TieRule Tie = TieRule.Random; public const SelectionDensityMode DensityMode = SelectionDensityMode.Standard; public const int ShortRunSelectionFloor = 11; public const int MaxSelectionsPerOrdinaryRound = 2; public const float PowerSurge = 1.2f; public const float HeavyBall = 2f; public const float Featherweight = 0.5f; public const float LowGravity = 0.6f; public const float HighGravity = 1.5f; public const float LeaderTax = 0.8f; public const float LastPlace = 1.2f; public const float ComebackMaximum = 1.3f; public const float TimedLow = 0.35f; public const float TimedHigh = 2f; public const float RouletteMoon = 0.2f; public const float RouletteLow = 0.6f; public const float RouletteHigh = 1.5f; public const float IntervalSeconds = 20f; public const float ImpactThreshold = 12f; public const float ExplosionCooldown = 2f; public const float ExplosionRadius = 5f; public static int[] TierWeights => new int[14] { 55, 40, 5, 55, 35, 10, 35, 45, 20, 20, 45, 35, 25, 75 }; public static float[] PhaseThresholds => new float[4] { 0f, 25f, 50f, 75f }; public static int[] LegacyPhaseStarts => new int[4] { 2, 4, 6, 8 }; } public enum RunState { Inactive, InitializingRun, StartingHole, PlayingHole, HoleEnding, PreparingVote, Voting, ResolvingVote, ApplyingModifier, RunComplete, CleaningUp } public sealed class RunController { public RunState State { get; private set; } public string RunId { get; private set; } = ""; public long Revision { get; private set; } public int HoleIndex { get; private set; } = -1; public bool Active => State != RunState.Inactive; public event Action<string> Changed; public event Action<string> Warning; public bool Begin(string id) { if (Active) { return false; } if (string.IsNullOrEmpty(id)) { throw new ArgumentException("Run identity is required.", "id"); } RunId = id; HoleIndex = -1; Move(RunState.InitializingRun, "RunStarted"); return true; } public bool HoleLoaded(int index) { if (!Active || index < 0 || index <= HoleIndex) { return false; } if (State != RunState.InitializingRun && State != RunState.StartingHole && State != RunState.HoleEnding) { return Invalid("HoleLoaded"); } HoleIndex = index; Move(RunState.StartingHole, "HoleLoaded"); return true; } public bool HoleStarted(int index) { if (!Active || index != HoleIndex || State == RunState.PlayingHole) { return false; } if (State != RunState.StartingHole) { return Invalid("HoleStarted"); } Move(RunState.PlayingHole, "HoleStarted"); return true; } public bool HoleEnded(int index) { if (!Active || index != HoleIndex || State == RunState.HoleEnding) { return false; } if (State != RunState.PlayingHole && State != RunState.StartingHole) { return false; } Move(RunState.HoleEnding, "HoleEnded"); return true; } public bool Transition(RunState expected, RunState next, string reason) { if (State != expected || !Allowed(expected, next)) { return Invalid(reason); } Move(next, reason); return true; } public void Complete() { if (Active) { Move(RunState.RunComplete, "RunCompleted"); Stop("CourseComplete"); } } public void Stop(string reason) { if (Active) { Move(RunState.CleaningUp, "Cleanup:" + reason); HoleIndex = -1; Move(RunState.Inactive, "RunStopped:" + reason); } } private bool Invalid(string signal) { this.Warning?.Invoke(signal + " rejected in " + State); return false; } private static bool Allowed(RunState from, RunState to) { switch (from) { case RunState.InitializingRun: return to == RunState.StartingHole; case RunState.StartingHole: return to == RunState.PlayingHole; case RunState.PlayingHole: return to == RunState.HoleEnding; case RunState.HoleEnding: if (to != RunState.PreparingVote) { return to == RunState.StartingHole; } return true; case RunState.PreparingVote: if (to != RunState.Voting) { return to == RunState.StartingHole; } return true; case RunState.Voting: if (to != RunState.ResolvingVote) { return to == RunState.StartingHole; } return true; case RunState.ResolvingVote: if (to != RunState.ApplyingModifier) { return to == RunState.StartingHole; } return true; case RunState.ApplyingModifier: if (to != RunState.StartingHole) { return to == RunState.PreparingVote; } return true; default: return false; } } private void Move(RunState state, string reason) { State = state; Revision++; this.Changed?.Invoke(reason); } } public static class SecureVoteRandom { public static int Next(int count) { if (count <= 0) { throw new ArgumentOutOfRangeException("count"); } ulong num = 4294967296L - 4294967296uL % (ulong)(uint)count; byte[] array = new byte[4]; using RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create(); uint num2; do { randomNumberGenerator.GetBytes(array); num2 = BitConverter.ToUInt32(array, 0); } while (num2 >= num); return (int)(num2 % (uint)count); } } public enum SelectionDensityMode { Standard, SinglePick, High, Custom } public sealed class DensitySettings { public SelectionDensityMode Mode { get; } public int ShortRunSelectionFloor { get; } public int MaxSelectionsPerOrdinaryRound { get; } public int EffectiveMaxSelectionsPerOrdinaryRound { get { if (Mode != SelectionDensityMode.SinglePick) { if (Mode != SelectionDensityMode.Standard) { return MaxSelectionsPerOrdinaryRound; } return Math.Min(2, MaxSelectionsPerOrdinaryRound); } return 1; } } public DensitySettings(SelectionDensityMode mode = SelectionDensityMode.Standard, int shortRunSelectionFloor = 11, int maxSelectionsPerOrdinaryRound = 2) { if (!Enum.IsDefined(typeof(SelectionDensityMode), mode) || shortRunSelectionFloor < 0 || shortRunSelectionFloor > 999 || maxSelectionsPerOrdinaryRound < 1 || maxSelectionsPerOrdinaryRound > 5) { throw new ArgumentException("Invalid density settings"); } Mode = mode; ShortRunSelectionFloor = shortRunSelectionFloor; MaxSelectionsPerOrdinaryRound = maxSelectionsPerOrdinaryRound; } } public static class SelectionDensityPlanner { public static int[] Plan(int totalHoles, DensitySettings settings, Func<int, bool> bossRound) { if (totalHoles < 1 || totalHoles > 1000) { return Array.Empty<int>(); } if (settings.Mode == SelectionDensityMode.High) { throw new InvalidOperationException("High density is not available yet. Use Custom to tune the selection floor."); } int[] picks = new int[totalHoles]; fo
plugins/RogueGolf/RogueGolf.Plugin.dll
Decompiled 3 weeks ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using Mirror; using RogueGolf.Core; using RogueGolf.CustomItems; using RogueGolf.CustomItems.Assets; using RogueGolf.Shared; using RogueGolf.Shared.Physics; using Steamworks; using Steamworks.Data; using TMPro; using Unity.Collections; using Unity.Mathematics; using UnityEngine; using UnityEngine.Events; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; using UnityEngine.Localization; using UnityEngine.Localization.Components; using UnityEngine.Localization.Settings; using UnityEngine.Localization.Tables; using UnityEngine.Rendering; using UnityEngine.SceneManagement; using UnityEngine.Splines; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyVersion("0.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 RogueGolf.Shared { internal sealed class SharedGravity { internal readonly GravityResolver Resolver = new GravityResolver(); private Vector3 baseline; private bool owned; internal bool TotalOverride => Resolver.Winner(NetworkTime.time) != null; internal float Effective => Resolver.Resolve(NetworkTime.time); internal Vector3 Base { get { //IL_000f: 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) if (!owned) { return Physics.gravity; } return baseline; } } internal void Underlying(Vector3 baseVector, float combined) { //IL_001b: 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_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) if (!owned) { baseline = Physics.gravity; owned = true; } baseline = baseVector; Resolver.SetOrdinary("modifiers.combined", combined); Apply(); } internal void Override(string source, float total, int priority, double until) { //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) if (!owned) { baseline = Physics.gravity; owned = true; } Resolver.SetOverride(source, total, priority, until); Apply(); } internal void Remove(string source) { Resolver.RemoveOverride(source); Apply(); } internal void ClearModifiers() { Resolver.RemoveOrdinary("modifiers.combined"); Apply(); } internal void Apply() { //IL_001a: 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) Resolver.Expire(NetworkTime.time); if (owned) { Physics.gravity = baseline * Effective; if (!TotalOverride && Resolver.Underlying == 1f) { owned = false; } } } internal string Inspect() { //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_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) return "=== EFFECTIVE GRAVITY STATE ===\nBase vector: " + ((object)Base/*cast due to .constrained prefix*/).ToString() + "\n" + Resolver.Inspect(NetworkTime.time) + "\nActual Physics.gravity: " + ((object)Physics.gravity/*cast due to .constrained prefix*/).ToString(); } } internal sealed class ResetSettingsSnapshot { private readonly Dictionary<ConfigEntryBase, object> values; internal ResetSettingsSnapshot(ConfigFile config, Func<string, bool> section) { values = ((IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)config).Where((KeyValuePair<ConfigDefinition, ConfigEntryBase> p) => section(p.Key.Section)).ToDictionary((KeyValuePair<ConfigDefinition, ConfigEntryBase> p) => p.Value, (KeyValuePair<ConfigDefinition, ConfigEntryBase> p) => p.Value.BoxedValue); } internal T Read<T>(ConfigEntry<T> entry) { if (!values.TryGetValue((ConfigEntryBase)(object)entry, out var value)) { return entry.Value; } return (T)value; } } } namespace RogueGolf.CustomItems { internal sealed class CustomItemRuntime : IDisposable { private sealed class Capture { internal uint Carrier; internal uint Victim; internal int Slot; internal Vector3 Position; internal Vector3 Velocity; internal Vector3 Fallback; internal double Until; internal bool Flying; internal GameObject Visual; } private sealed class CapturedPlayer { internal PlayerInfo Player; internal bool Kinematic; internal bool Visible; internal Vector3 Position; } private sealed class WeightRow { internal GameObject Root; internal SliderOption Slider; } private sealed class GravityEvent { internal string Id; internal double Start; internal double End; internal float Total; internal bool Applied; } private sealed class Blower { internal int Slot; internal Vector3 Direction; internal double Until; internal double NextForce; } private readonly Dictionary<uint, Capture> captures = new Dictionary<uint, Capture>(); private readonly Dictionary<uint, CapturedPlayer> hiddenPlayers = new Dictionary<uint, CapturedPlayer>(); private readonly Dictionary<uint, double> immunity = new Dictionary<uint, double>(); private ConfigEntry<float> captureDuration; private ConfigEntry<float> captureImmunity; private readonly RaycastHit[] captureHits = (RaycastHit[])(object)new RaycastHit[64]; internal static CustomItemRuntime Current; internal readonly CustomItemRegistry Registry; internal readonly SharedGravity Gravity; private readonly Action<string> log; private readonly Func<float> itemQuality; private readonly Func<bool> compatible; private readonly Action<string> notice; private readonly Func<int, bool> peerReady; private readonly Func<bool> clientReady; private readonly Harmony itemHarmony; internal bool Faulted; private readonly Random random = new Random(); private readonly Dictionary<uint, GameObject> held = new Dictionary<uint, GameObject>(); private readonly Dictionary<uint, string> heldIds = new Dictionary<uint, string>(); private double nextVisualScan; private double nextState; private bool lastEnabled; private int scene = -1; private int hole = -2; private ConfigFile itemConfig; private ResetSettingsSnapshot resetSettings; private Action diagnosticCheck; private Action diagnosticUndo; private double diagnosticAt; private const int MaxPacket = 32768; private bool remoteEnabled; private bool serverRegistered; private bool clientRegistered; private long sequence; private long revision; private long acceptedRevision; private string session = ""; private string remoteSession = ""; private readonly Dictionary<int, double> lastRequest = new Dictionary<int, double>(); private readonly Dictionary<int, long> lastSequence = new Dictionary<int, long>(); private readonly Dictionary<int, double> lastHello = new Dictionary<int, double>(); private double nextHello; internal Tuple<bool, int>[] remoteSettings; private readonly Dictionary<string, WeightRow> weightRows = new Dictionary<string, WeightRow>(); private MatchSetupRules weightMenu; private double nextWeightRefresh; private bool weightUiFaulted; private bool weightGridVisible; private readonly HashSet<int> customOnlyPools = new HashSet<int>(); private HashSet<int> poolGuardQueue; private static readonly FieldInfo nativeNonzeroQueue = AccessTools.Field(typeof(MatchSetupRules), "serverEnsureItemPoolSpawnChanceNonZeroQueue"); private UnityAction resetNativeItemWeights; private static readonly FieldInfo nativeSliders = AccessTools.Field(typeof(MatchSetupRules), "spawnChanceSliders"); private static readonly FieldInfo nativeInitialized = AccessTools.Field(typeof(MatchSetupRules), "isInitialized"); private static readonly FieldInfo nativeNavigation = AccessTools.Field(typeof(MatchSetupRules), "gridNavigationGroup"); private static readonly MethodInfo nativePool = AccessTools.DeclaredMethod(typeof(MatchSetupRules), "GetCurrentItemPool", (Type[])null, (Type[])null); private static readonly FieldInfo nativePoolIndex = AccessTools.Field(typeof(MatchSetupRules), "currentItemPoolIndex"); private readonly List<GravityEvent> gravityEvents = new List<GravityEvent>(); private ConfigEntry<float> gravityWarning; private ConfigEntry<float> gravityDuration; private ConfigEntry<float> extremeChance; private readonly List<ConfigEntry<float>> gravityRanges = new List<ConfigEntry<float>>(); private GameObject gravityVisual; private ConfigEntry<float> greenRadius; private ConfigEntry<float> greenWarning; private ConfigEntry<float> greenDuration; private string greenId = ""; private uint greenOwner; private Vector3 greenCenter; private float greenSize; private double greenStart; private double greenEnd; private GameObject greenVisual; private GameObject greenColliders; private static readonly FieldInfo projectileVelocity = AccessTools.Field(typeof(Hittable), "previousVelocity"); private static readonly MethodInfo becomeProjectile = AccessTools.Method(typeof(Hittable), "BecomeSwingProjectile", (Type[])null, (Type[])null); private static readonly MethodInfo setProjectileTarget = AccessTools.Method(typeof(Hittable), "ServerSetHomingTargetHittable", (Type[])null, (Type[])null); private static readonly FieldInfo rocketPrevious = AccessTools.Field(typeof(Rocket), "previousPosition"); private static readonly FieldInfo rocketRadius = AccessTools.Field(typeof(Rocket), "collisionRadius"); private static readonly FieldInfo rocketShootCollider = AccessTools.Field(typeof(Rocket), "shootCollider"); private static readonly FieldInfo rocketTimestamp = AccessTools.Field(typeof(Rocket), "launchOrReflectionTimestamp"); private static readonly FieldInfo rocketReflected = AccessTools.Field(typeof(Rocket), "isReflected"); private static readonly RaycastHit[] greenRocketHits = (RaycastHit[])(object)new RaycastHit[32]; private readonly Dictionary<uint, Blower> blowers = new Dictionary<uint, Blower>(); private readonly Collider[] blowerHits = (Collider[])(object)new Collider[128]; private readonly HashSet<Rigidbody> blowerBodies = new HashSet<Rigidbody>(); private ConfigEntry<float> blowerRange; private ConfigEntry<float> blowerAcceleration; private double nextBlowerInput; internal bool HostEnabled { get { if (!Faulted && NetworkServer.active && Setting<bool>(Registry.Master)) { return compatible(); } return false; } } internal bool Enabled { get { if (!Faulted) { if (!NetworkServer.active) { return remoteEnabled; } return HostEnabled; } return false; } } internal bool Playing { get { //IL_0007: 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_0015: Invalid comparison between Unknown and I4 if (!SingletonBehaviour<DrivingRangeManager>.HasInstance) { if ((int)CourseManager.MatchState >= 3) { return (int)CourseManager.MatchState < 6; } return false; } return true; } } private bool MenuMaster { get { if (!Faulted) { if (!NetworkServer.active) { return remoteEnabled; } return Registry.Master.Value; } return false; } } private bool ReflectionActive { get { if (HostEnabled && (Object)(object)greenColliders != (Object)null && NetworkTime.time >= greenStart) { return NetworkTime.time < greenEnd; } return false; } } private void ConfigureCapture(ConfigFile c) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0034: 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 captureDuration = c.Bind<float>("CustomItems.capture_ball", "MaximumSeconds", 3.5f, new ConfigDescription("Maximum occupied time, including throw flight.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 4f), Array.Empty<object>())); captureImmunity = c.Bind<float>("CustomItems.capture_ball", "ImmunitySeconds", 2.5f, new ConfigDescription("Post-release capture immunity.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 5f), Array.Empty<object>())); } internal bool IsCaptured(uint id) { if (!hiddenPlayers.ContainsKey(id)) { return captures.Values.Any((Capture c) => c.Victim == id && c.Victim != 0); } return true; } internal bool CarrierSlot(uint id, out int slot) { slot = -1; if (!captures.TryGetValue(id, out var value) || value.Victim == 0) { return false; } slot = value.Slot; return true; } private bool ThrowCapture(PlayerInfo p, int slot, Vector3 direction) { //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_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_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) //IL_00f7: 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_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_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_011c: 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_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_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_0049: 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_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) //IL_006a: 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) if (captures.TryGetValue(((NetworkBehaviour)p).netId, out var value)) { if (value.Flying) { return false; } value.Flying = true; value.Position = ((Component)p).transform.position + Vector3.up * 1.2f + direction * 0.8f; value.Velocity = direction * 18f + Vector3.up * 3f; log("Occupied Capture Ball thrown carrier=" + ((NetworkBehaviour)p).netId); return true; } value = new Capture { Carrier = ((NetworkBehaviour)p).netId, Slot = slot, Flying = true, Position = ((Component)p).transform.position + Vector3.up * 1.2f + direction * 0.8f, Velocity = direction * 22f + Vector3.up * 2f, Until = NetworkTime.time + 3.5, Fallback = ((Component)p).transform.position }; captures[((NetworkBehaviour)p).netId] = value; log("Capture Ball launched carrier=" + ((NetworkBehaviour)p).netId); return true; } private void TickProjectiles() { //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_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_0061: 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_0072: 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_00b1: 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_03b8: Unknown result type (might be due to invalid IL or missing references) //IL_03bd: Unknown result type (might be due to invalid IL or missing references) //IL_03be: Unknown result type (might be due to invalid IL or missing references) //IL_03c3: 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_014a: 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_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_015d: Unknown result type (might be due to invalid IL or missing references) //IL_0164: 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_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_01a8: 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_030e: Unknown result type (might be due to invalid IL or missing references) //IL_0313: 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_033e: Unknown result type (might be due to invalid IL or missing references) //IL_0357: Unknown result type (might be due to invalid IL or missing references) //IL_036a: Unknown result type (might be due to invalid IL or missing references) Capture[] array = captures.Values.Where((Capture x) => x.Flying).ToArray(); foreach (Capture capture in array) { capture.Velocity += Physics.gravity * Time.fixedDeltaTime; Vector3 val = capture.Velocity * Time.fixedDeltaTime; int num2 = Physics.SphereCastNonAlloc(capture.Position, 0.2f, ((Vector3)(ref val)).normalized, captureHits, ((Vector3)(ref val)).magnitude, -1, (QueryTriggerInteraction)1); RaycastHit? val2 = null; for (int num3 = 0; num3 < num2; num3++) { RaycastHit value = captureHits[num3]; PlayerInfo componentInParent = ((Component)((RaycastHit)(ref value)).collider).GetComponentInParent<PlayerInfo>(); if ((Object)(object)componentInParent != (Object)null && (((NetworkBehaviour)componentInParent).netId == capture.Carrier || ((NetworkBehaviour)componentInParent).netId == capture.Victim || IsCaptured(((NetworkBehaviour)componentInParent).netId))) { continue; } if (val2.HasValue) { float distance = ((RaycastHit)(ref value)).distance; RaycastHit value2 = val2.Value; if (!(distance < ((RaycastHit)(ref value2)).distance)) { continue; } } val2 = value; } if (val2.HasValue) { RaycastHit value3 = val2.Value; if (((RaycastHit)(ref value3)).distance > 0.001f) { capture.Position = ((RaycastHit)(ref value3)).point + ((RaycastHit)(ref value3)).normal * 0.25f; } if (capture.Victim != 0) { if (SingletonBehaviour<BoundsManager>.HasInstance && !BoundsManager.IsPointInLevelBoundsImmediate(capture.Position)) { KillCaptured(capture); } else { Release(capture, capture.Position, "landing"); } continue; } PlayerInfo componentInParent2 = ((Component)((RaycastHit)(ref value3)).collider).GetComponentInParent<PlayerInfo>(); log("Capture collision " + ((Object)((RaycastHit)(ref value3)).collider).name + " victim=" + (((Object)(object)componentInParent2 == (Object)null) ? "none" : (((NetworkBehaviour)componentInParent2).netId + " eligible=" + Eligible(componentInParent2) + " resolved=" + componentInParent2.AsGolfer.IsMatchResolved + " visible=" + componentInParent2.Movement.IsVisible))); if ((Object)(object)componentInParent2 != (Object)null && Eligible(componentInParent2) && !IsCaptured(((NetworkBehaviour)componentInParent2).netId) && (!immunity.TryGetValue(((NetworkBehaviour)componentInParent2).netId, out var value4) || value4 <= NetworkTime.time)) { PlayerInfo val3 = Player(capture.Carrier); if ((Object)(object)val3 == (Object)null || IsCaptured(((NetworkBehaviour)val3).netId)) { FinishMiss(capture); continue; } capture.Victim = ((NetworkBehaviour)componentInParent2).netId; capture.Fallback = ((Component)componentInParent2).transform.position; capture.Until = NetworkTime.time + (double)Setting<float>(captureDuration); capture.Flying = false; capture.Velocity = Vector3.zero; componentInParent2.AsGolfer.CancelAllActions(); ApplyCapturePlayer(capture.Victim, capture.Fallback, visible: false); BroadcastCapturePlayer(capture.Victim, capture.Fallback, visible: false); Notify("CAPTURED — throw within " + Setting<float>(captureDuration).ToString("F1") + "s"); SendState(); } else { FinishMiss(capture); } } else { capture.Position += val; } } } private void TickCapture() { //IL_0289: Unknown result type (might be due to invalid IL or missing references) //IL_0207: 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_0057: 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_0170: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_01ba: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Unknown result type (might be due to invalid IL or missing references) Capture[] array = captures.Values.ToArray(); foreach (Capture capture in array) { PlayerInfo val = Player(capture.Carrier); PlayerInfo val2 = Player(capture.Victim); if (NetworkServer.active) { if (capture.Victim != 0 && capture.Flying && SingletonBehaviour<BoundsManager>.HasInstance && !BoundsManager.IsPointInLevelBoundsImmediate(capture.Position)) { KillCaptured(capture); continue; } if ((Object)(object)val == (Object)null || !Eligible(val) || IsCaptured(capture.Carrier) || capture.Slot >= val.Inventory.slots.Count || Registry.Get(val.Inventory.slots[capture.Slot].itemType)?.Id != "capture_ball") { if (capture.Victim != 0) { Release(capture, capture.Fallback, "carrier interrupted"); } else { FinishMiss(capture); } continue; } if (capture.Victim != 0 && ((Object)(object)val2 == (Object)null || val2.AsGolfer.IsMatchResolved || val2.AsSpectator.IsSpectating || val2.Movement.IsRespawningOrDrowning)) { Release(capture, capture.Fallback, "victim interrupted"); continue; } if (NetworkTime.time >= capture.Until || !Valid(capture.Position) || capture.Position.y < capture.Fallback.y - 60f) { if (capture.Victim != 0) { Release(capture, capture.Flying ? capture.Position : ((Component)val).transform.position, "timeout/bounds"); } else { FinishMiss(capture); } continue; } } if (capture.Victim != 0) { if (!hiddenPlayers.ContainsKey(capture.Victim) && (Object)(object)val2 != (Object)null) { ApplyCapturePlayer(capture.Victim, capture.Fallback, visible: false); } if ((Object)(object)val != (Object)null && ((NetworkBehaviour)val).isLocalPlayer && val.Inventory.EquippedItemIndex != capture.Slot) { val.Inventory.TrySelectItemSlot(capture.Slot, true); } } if (capture.Flying) { if ((Object)(object)capture.Visual == (Object)null) { capture.Visual = Registry.Assets.Create("capture_ball"); } capture.Visual.transform.position = capture.Position; capture.Visual.transform.Rotate(140f * Time.deltaTime, 200f * Time.deltaTime, 0f); Registry.Assets.Animate(capture.Visual, capture.Victim != 0, blowing: false); } else if ((Object)(object)capture.Visual != (Object)null) { Object.Destroy((Object)(object)capture.Visual); capture.Visual = null; } } uint[] array2 = (from x in immunity where x.Value <= NetworkTime.time select x.Key).ToArray(); foreach (uint key in array2) { immunity.Remove(key); } } private void ApplyCapturePlayer(uint id, Vector3 position, bool visible) { //IL_0076: 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_0091: 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_0155: 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_0135: 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_017b: 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_0190: Unknown result type (might be due to invalid IL or missing references) PlayerInfo val = Player(id); if ((Object)(object)val == (Object)null) { hiddenPlayers.Remove(id); return; } Rigidbody rigidbody = val.AsEntity.Rigidbody; CapturedPlayer value; if (!visible) { if (!hiddenPlayers.ContainsKey(id)) { hiddenPlayers[id] = new CapturedPlayer { Player = val, Kinematic = rigidbody.isKinematic, Visible = val.Movement.IsVisible, Position = ((Component)val).transform.position }; val.AsGolfer.CancelAllActions(); rigidbody.linearVelocity = Vector3.zero; rigidbody.angularVelocity = Vector3.zero; rigidbody.isKinematic = true; val.Movement.NetworkisVisible = false; val.Movement.UpdateEnabledColliders(); log("Captured player suspended id=" + id); } } else if (hiddenPlayers.TryGetValue(id, out value)) { hiddenPlayers.Remove(id); rigidbody.isKinematic = value.Kinematic; val.Movement.NetworkisVisible = value.Visible; val.Movement.UpdateEnabledColliders(); if (((NetworkBehaviour)val).isLocalPlayer) { val.Movement.Teleport(position, ((Component)val).transform.rotation, true); } else { val.AsEntity.InformWillTeleport(); rigidbody.position = position; ((Component)val).transform.position = position; val.AsEntity.InformTeleported(); } if (!rigidbody.isKinematic) { rigidbody.linearVelocity = Vector3.up * 2f; rigidbody.angularVelocity = Vector3.zero; } immunity[id] = NetworkTime.time + (double)Setting<float>(captureImmunity); log("Captured player restored id=" + id + " immunity=" + Setting<float>(captureImmunity)); } } private void BroadcastCapturePlayer(uint id, Vector3 position, bool visible) { //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) Broadcast(Packet(delegate(BinaryWriter w) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) w.Write((byte)2); w.Write(id); Vector(w, position); w.Write(visible); })); } private Vector3 SafeRelease(Vector3 desired, Vector3 fallback, uint victim) { //IL_0166: Unknown result type (might be due to invalid IL or missing references) //IL_0167: 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_0176: 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_001e: 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_0063: 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_0049: 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_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_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_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_0083: 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_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_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: 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_00ec: 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_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_0104: 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_00e3: 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) RaycastHit val3 = default(RaycastHit); for (int i = 0; i < 2; i++) { for (int j = 0; j < 25; j++) { Vector3 val = ((i == 0 && Valid(desired)) ? desired : fallback); Vector3 val2 = ((j == 0) ? Vector3.zero : (Quaternion.Euler(0f, (float)j * 137.5f, 0f) * Vector3.forward * (1f + (float)j / 8f))); if (Physics.Raycast(val + val2 + Vector3.up * 8f, Vector3.down, ref val3, 30f, LayerMask.op_Implicit(GameManager.LayerSettings.PlayerGroundableMask), (QueryTriggerInteraction)1) && !(((RaycastHit)(ref val3)).normal.y < 0.65f)) { Vector3 val4 = ((RaycastHit)(ref val3)).point + Vector3.up * 0.15f; if ((!SingletonBehaviour<BoundsManager>.HasInstance || BoundsManager.IsPointInLevelBoundsImmediate(val4)) && !Physics.OverlapCapsule(val4 + Vector3.up * 0.5f, val4 + Vector3.up * 1.4f, 0.32f, -1, (QueryTriggerInteraction)1).Any(delegate(Collider x) { PlayerInfo componentInParent = ((Component)x).GetComponentInParent<PlayerInfo>(); return componentInParent == null || ((NetworkBehaviour)componentInParent).netId != victim; })) { return val4; } } } } return fallback + Vector3.up * 0.2f; } private unsafe void Release(Capture c, Vector3 desired, string reason) { //IL_0013: 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_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_003b: 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_00f3: 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) captures.Remove(c.Carrier); Vector3 position = SafeRelease(desired, c.Fallback, c.Victim); ApplyCapturePlayer(c.Victim, position, visible: true); BroadcastCapturePlayer(c.Victim, position, visible: true); PlayerInfo val = Player(c.Carrier); if ((Object)(object)val != (Object)null && c.Slot < val.Inventory.slots.Count && Registry.Get(val.Inventory.slots[c.Slot].itemType)?.Id == "capture_ball") { Consume(val.Inventory, c.Slot); } if ((Object)(object)c.Visual != (Object)null) { Object.Destroy((Object)(object)c.Visual); } Registry.Assets.Pulse(position, new Color(0.2f, 1f, 0.7f)); Notify("CAPTURE RELEASED (" + reason + ")"); log("Capture release carrier=" + c.Carrier + " victim=" + c.Victim + " at=" + ((object)(*(Vector3*)(&position))/*cast due to .constrained prefix*/).ToString()); SendState(); } private void FinishMiss(Capture c) { //IL_00b4: 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_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) captures.Remove(c.Carrier); PlayerInfo val = Player(c.Carrier); if ((Object)(object)val != (Object)null && c.Slot < val.Inventory.slots.Count && Registry.Get(val.Inventory.slots[c.Slot].itemType)?.Id == "capture_ball") { Consume(val.Inventory, c.Slot); } if ((Object)(object)c.Visual != (Object)null) { Object.Destroy((Object)(object)c.Visual); } Registry.Assets.Pulse(c.Position, new Color(0.8f, 0.9f, 1f)); log("Capture Ball missed/expired"); } private void KillCaptured(Capture c) { //IL_0032: 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_006e: Unknown result type (might be due to invalid IL or missing references) PlayerInfo val = Player(c.Victim); PlayerInfo val2 = Player(c.Carrier); captures.Remove(c.Carrier); ApplyCapturePlayer(c.Victim, c.Fallback, visible: true); BroadcastCapturePlayer(c.Victim, c.Fallback, visible: true); if ((Object)(object)val != (Object)null) { if ((Object)(object)val2 != (Object)null) { val.AsGolfer.ServerSetPotentialEliminationReason(val2.AsGolfer, ItemUseId.Invalid, (EliminationReason)5); } val.AsGolfer.ServerEliminate((EliminationReason)5); } if ((Object)(object)val2 != (Object)null && c.Slot < val2.Inventory.slots.Count) { Consume(val2.Inventory, c.Slot); } if ((Object)(object)c.Visual != (Object)null) { Object.Destroy((Object)(object)c.Visual); } Notify("CAPTURE BALL — OUT OF BOUNDS KILL"); log("Capture environmental kill carrier=" + c.Carrier + " victim=" + c.Victim); SendState(); } private void CleanupCapture(string reason) { //IL_0048: 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_00a9: Unknown result type (might be due to invalid IL or missing references) Capture[] array = captures.Values.ToArray(); foreach (Capture capture in array) { if (NetworkServer.active && capture.Victim != 0) { Release(capture, capture.Fallback, reason); continue; } if (capture.Victim != 0) { ApplyCapturePlayer(capture.Victim, capture.Fallback, visible: true); } if ((Object)(object)capture.Visual != (Object)null) { Object.Destroy((Object)(object)capture.Visual); } } captures.Clear(); KeyValuePair<uint, CapturedPlayer>[] array2 = hiddenPlayers.ToArray(); for (int i = 0; i < array2.Length; i++) { KeyValuePair<uint, CapturedPlayer> keyValuePair = array2[i]; ApplyCapturePlayer(keyValuePair.Key, keyValuePair.Value.Position, visible: true); } immunity.Clear(); } private void WriteCapture(BinaryWriter w) { //IL_0052: 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_006a: Unknown result type (might be due to invalid IL or missing references) w.Write(captures.Count); foreach (Capture value in captures.Values) { w.Write(value.Carrier); w.Write(value.Victim); w.Write(value.Slot); Vector(w, value.Position); Vector(w, value.Velocity); Vector(w, value.Fallback); w.Write(value.Until); w.Write(value.Flying); } } private void ReadCapture(BinaryReader r) { //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_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_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_0131: Unknown result type (might be due to invalid IL or missing references) int num = Count(r); HashSet<uint> ids = new HashSet<uint>(); for (int i = 0; i < num; i++) { uint num2 = r.ReadUInt32(); ids.Add(num2); if (!captures.TryGetValue(num2, out var value)) { Dictionary<uint, Capture> dictionary = captures; Capture obj = new Capture { Carrier = num2 }; value = obj; dictionary[num2] = obj; } value.Victim = r.ReadUInt32(); value.Slot = r.ReadInt32(); value.Position = Vector(r); value.Velocity = Vector(r); value.Fallback = Vector(r); value.Until = r.ReadDouble(); value.Flying = r.ReadBoolean(); } Capture[] array = captures.Values.Where((Capture c) => !ids.Contains(c.Carrier)).ToArray(); foreach (Capture capture in array) { if (capture.Victim != 0 && hiddenPlayers.ContainsKey(capture.Victim)) { ApplyCapturePlayer(capture.Victim, capture.Fallback, visible: true); } if ((Object)(object)capture.Visual != (Object)null) { Object.Destroy((Object)(object)capture.Visual); } captures.Remove(capture.Carrier); } } internal CustomItemRuntime(ConfigFile config, Harmony harmony, SharedGravity gravity, Func<bool> compatible, Func<int, bool> peerReady, Func<bool> clientReady, Func<float> itemQuality, Action<string> log, Action<string> notice) { //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_01c0: Expected O, but got Unknown //IL_03c0: Unknown result type (might be due to invalid IL or missing references) //IL_03c6: Expected I4, but got Unknown this.itemQuality = itemQuality; itemConfig = config; Registry = new CustomItemRegistry(config); Gravity = gravity; this.compatible = compatible; this.peerReady = peerReady; this.clientReady = clientReady; this.log = log; this.notice = notice; itemHarmony = harmony; Current = this; ConfigureGravity(config); ConfigureCapture(config); ConfigureBlower(config); ConfigureGreen(config); ConfigureNativeWeights(harmony); ConfigureGreenReflection(harmony); ConfigureRangeWeights(harmony); harmony.Patch((MethodBase)AccessTools.Method(typeof(ItemPool), "GetWeightedRandomItem", (Type[])null, (Type[])null), new HarmonyMethod(typeof(CustomItemRuntime), "SelectCustomItem", (Type[])null) { priority = 800 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Hook(harmony, typeof(PlayerInventory), "TryUseItem", "Use"); Hook(harmony, typeof(PlayerInventory), "TrySelectItemSlot", "Select"); Hook(harmony, typeof(PlayerInventory), "TryDeselectItem", "Deselect"); Hook(harmony, typeof(PlayerInventory), "DropItem", "Drop"); Hook(harmony, typeof(ItemData), "get_Name", "Name"); Hook(harmony, typeof(ItemCollection), "TryGetItemData", "Lookup"); Hook(harmony, typeof(ItemCollection), "GetItemIcon", "Icon"); Hook(harmony, typeof(PlayerMovement), "FixedUpdate", "Move"); Hook(harmony, typeof(PlayerMovement), "LocalPlayerUpdateVisibility", "Move"); Hook(harmony, typeof(PlayerMovement), "UpdateOutOfBounds", "Move"); Hook(harmony, typeof(Hittable), "HitWithItem", "Target"); Hook(harmony, typeof(PlayerGolfer), "CanMove", "CanMove"); Hook(harmony, typeof(PlayerGolfer), "CanAimSwing", "CanMove"); Hook(harmony, typeof(PlayerGolfer), "TryStartChargingSwing", "CanMove"); Hook(harmony, typeof(PlayerMovement), "TryTriggerJump", "MotionAction"); Hook(harmony, typeof(PlayerMovement), "TryDive", "MotionAction"); Hook(harmony, typeof(PlayerGolfer), "CancelAllActions", null); BNetworkManager.WillChangeScene += BeforeSceneChange; CustomItemDefinition[] items = Registry.Items; foreach (CustomItemDefinition customItemDefinition in items) { log("Registered " + customItemDefinition.Id + " stableId=" + (int)customItemDefinition.Type + " weight=" + Setting<int>(customItemDefinition.Weight)); } } private static void Hook(Harmony h, Type type, string method, string prefix) { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Expected O, but got Unknown MethodInfo methodInfo = AccessTools.DeclaredMethod(type, method, (Type[])null, (Type[])null); if (methodInfo == null) { throw new MissingMethodException(type.Name + "." + method); } if (prefix != null) { h.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(CustomItemRuntime), prefix, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } private static bool Lookup(ItemType itemType, ref ItemData itemData, ref bool __result) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) CustomItemDefinition customItemDefinition = Current?.Registry.Get(itemType); if (customItemDefinition == null) { return true; } Current.Registry.EnsureRegistered(); itemData = customItemDefinition.Data; __result = itemData != null; return false; } private static bool Icon(ItemType itemType, ref Sprite __result) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) CustomItemDefinition customItemDefinition = Current?.Registry.Get(itemType); if (customItemDefinition == null) { return true; } Current.Registry.EnsureRegistered(); __result = customItemDefinition.Data.Icon; return false; } private static bool Name(ItemData __instance, ref string __result) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) CustomItemDefinition customItemDefinition = Current?.Registry.Get(__instance.Type); if (customItemDefinition == null) { return true; } __result = customItemDefinition.Name; return false; } private static bool Use(PlayerInventory __instance, bool isAirhornReaction, ref bool shouldEatInput, ref bool __result) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) CustomItemRuntime current = Current; if (current == null) { return true; } if (current.IsCaptured(((NetworkBehaviour)__instance.PlayerInfo).netId)) { shouldEatInput = true; __result = false; return false; } if (current.Registry.Get(__instance.GetEffectivelyEquippedItem(false)) == null) { return true; } shouldEatInput = true; __result = false; if (!isAirhornReaction && current.Enabled && current.Playing && Eligible(__instance.PlayerInfo)) { current.SendUse(__instance.EquippedItemIndex); __result = true; } return false; } private static bool Select(PlayerInventory __instance, int index, ref bool __result) { CustomItemRuntime current = Current; if (current == null) { return true; } if (current.IsCaptured(((NetworkBehaviour)__instance.PlayerInfo).netId) || (current.CarrierSlot(((NetworkBehaviour)__instance.PlayerInfo).netId, out var slot) && slot != index)) { __result = false; return false; } return true; } private static bool Deselect(PlayerInventory __instance, ref bool __result) { CustomItemRuntime current = Current; if (current != null && (current.IsCaptured(((NetworkBehaviour)__instance.PlayerInfo).netId) || current.CarrierSlot(((NetworkBehaviour)__instance.PlayerInfo).netId, out var _))) { __result = false; return false; } return true; } private static bool Drop(PlayerInventory __instance) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) CustomItemRuntime current = Current; if (current == null) { return true; } if (current.IsCaptured(((NetworkBehaviour)__instance.PlayerInfo).netId) || current.Registry.Get(__instance.GetEffectivelyEquippedItem(false)) != null) { return false; } return true; } private static bool Move(PlayerMovement __instance) { if (Current != null) { return !Current.IsCaptured(((NetworkBehaviour)__instance.PlayerInfo).netId); } return true; } private static bool MotionAction(PlayerMovement __instance, ref bool __result) { if (Current == null || !Current.IsCaptured(((NetworkBehaviour)__instance.PlayerInfo).netId)) { return true; } __result = false; return false; } private static bool Target(Hittable __instance) { if (Current != null && !((Object)(object)__instance.AsEntity == (Object)null) && __instance.AsEntity.IsPlayer) { return !Current.IsCaptured(((NetworkBehaviour)__instance.AsEntity.PlayerInfo).netId); } return true; } private static bool CanMove(PlayerGolfer __instance, ref bool __result) { if (Current == null || !Current.IsCaptured(((NetworkBehaviour)__instance.PlayerInfo).netId)) { return true; } __result = false; return false; } internal static bool Eligible(PlayerInfo p) { //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_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Invalid comparison between Unknown and I4 if ((Object)(object)p != (Object)null && !p.AsGolfer.IsMatchResolved && !p.AsSpectator.IsSpectating && p.Movement.IsVisible && !p.Movement.IsRespawningOrDrowning && !p.Movement.IsKnockedOutOrRecovering) { GolfCartSeat activeGolfCartSeat = p.ActiveGolfCartSeat; if (!((GolfCartSeat)(ref activeGolfCartSeat)).IsValid()) { return (int)p.AsHittable.FrozenState != 2; } } return false; } internal static PlayerInfo Player(uint id) { if (!(NetworkServer.active ? NetworkServer.spawned : NetworkClient.spawned).TryGetValue(id, out var value)) { return null; } return ((Component)value).GetComponent<PlayerInfo>(); } internal static IEnumerable<PlayerInfo> Players() { return from x in (NetworkServer.active ? NetworkServer.spawned : NetworkClient.spawned).Values select ((Component)x).GetComponent<PlayerInfo>() into x where (Object)(object)x != (Object)null select x; } internal bool TrySelect(ItemPool pool, ref ItemType result, float quality) { //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_00bf: 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_00de: Expected I4, but got Unknown //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Expected I4, but got Unknown //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Expected I4, but got Unknown if (!HostEnabled || !Playing) { return false; } Registry.EnsureRegistered(); CustomItemDefinition[] array = Registry.Items.Where((CustomItemDefinition d) => Setting<bool>(d.Enabled) && Setting<int>(d.Weight) > 0).ToArray(); if (array.Length == 0) { return false; } ItemSpawnChance[] array2 = pool.SpawnChances.Where((ItemSpawnChance x) => (int)x.item != 0 && Registry.Get(x.item) == null).ToArray(); double num = random.NextDouble() * (double)(((IEnumerable<ItemSpawnChance>)array2).Sum((Func<ItemSpawnChance, float>)NativeWeight) + (float)array.Sum((CustomItemDefinition x) => Setting<int>(x.Weight))); ItemSpawnChance[] array3 = array2; foreach (ItemSpawnChance val in array3) { num -= (double)NativeWeight(val); if (num < 0.0) { result = (ItemType)(int)val.item; return true; } } CustomItemDefinition[] array4 = array; foreach (CustomItemDefinition customItemDefinition in array4) { num -= (double)Setting<int>(customItemDefinition.Weight); if (num < 0.0) { result = (ItemType)(int)customItemDefinition.Type; log("Native pickup selected " + customItemDefinition.Id); return true; } } result = (ItemType)(int)array[^1].Type; return true; float NativeWeight(ItemSpawnChance x) { //IL_0005: 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_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Invalid comparison between Unknown and I4 //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_0021: Invalid comparison between Unknown and I4 //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_002b: Invalid comparison between Unknown and I4 //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) //IL_0035: Invalid comparison between Unknown and I4 //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_003e: Invalid comparison between Unknown and I4 //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_0048: Invalid comparison between Unknown and I4 return Mathf.Max(0f, x.spawnChanceWeight) * (((int)x.item == 7 || (int)x.item == 10 || (int)x.item == 16 || (int)x.item == 15 || (int)x.item == 3 || (int)x.item == 17) ? quality : 1f); } } private static bool SelectCustomItem(ItemPool __instance, ref ItemType __result) { CustomItemRuntime current = Current; if (current != null) { return !current.TrySelect(__instance, ref __result, current.itemQuality()); } return true; } internal void Tick() { //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_001d: Unknown result type (might be due to invalid IL or missing references) if (Faulted) { return; } TickDiagnostics(); PollHost(); Scene activeScene = SceneManager.GetActiveScene(); int num = SceneHandle.op_Implicit(((Scene)(ref activeScene)).handle); if (scene != num || hole != CourseManager.CurrentHoleCourseIndex) { Cleanup("scene/hole changed"); scene = num; hole = CourseManager.CurrentHoleCourseIndex; } bool flag = Enabled && Playing; if (flag != lastEnabled) { if (!flag) { Cleanup("disabled or hole ended"); } log("Master gameplay " + (flag ? "ON (host authority)" : "OFF")); lastEnabled = flag; if (NetworkServer.active) { SendState(); } } Gravity.Apply(); if (flag) { Registry.EnsureRegistered(); TickCapture(); TickGravity(); TickGreen(); TickBlowerInput(); if (NetworkServer.active && NetworkTime.time >= nextState) { nextState = NetworkTime.time + 0.1; SendState(); } if (NetworkTime.time >= nextVisualScan) { nextVisualScan = NetworkTime.time + 0.1; RefreshHeld(); } AnimateVisuals(); } } internal void FixedTick() { if (Enabled && Playing && NetworkServer.active) { TickBlowerForces(); TickProjectiles(); } } private void RefreshHeld() { //IL_0024: 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_0131: Unknown result type (might be due to invalid IL or missing references) foreach (PlayerInfo item in Players()) { CustomItemDefinition customItemDefinition = Registry.Get(item.Inventory.GetEffectivelyEquippedItem(false)); if (customItemDefinition == null || !item.Movement.IsVisible) { RemoveHeld(((NetworkBehaviour)item).netId); continue; } if (!held.TryGetValue(((NetworkBehaviour)item).netId, out var value) || (Object)(object)value == (Object)null || heldIds[((NetworkBehaviour)item).netId] != customItemDefinition.Id) { RemoveHeld(((NetworkBehaviour)item).netId); value = Registry.Assets.Create(customItemDefinition.Id); held[((NetworkBehaviour)item).netId] = value; heldIds[((NetworkBehaviour)item).netId] = customItemDefinition.Id; customItemDefinition.Mount(value.transform, ((Component)item.RightHandEquipmentSwitcher).transform); } Blower value2; bool flag = blowers.TryGetValue(((NetworkBehaviour)item).netId, out value2) && value2.Until > NetworkTime.time && customItemDefinition.Id == "leaf_blower"; value.GetComponent<HeldItemPose>().SetAim(flag ? value2.Direction : Vector3.zero); Registry.Assets.Animate(value, CarrierSlot(((NetworkBehaviour)item).netId, out var _), flag); } uint[] array = held.Keys.Where((uint id2) => (Object)(object)Player(id2) == (Object)null).ToArray(); foreach (uint id in array) { RemoveHeld(id); } } private void RemoveHeld(uint id) { if (held.TryGetValue(id, out var value) && (Object)(object)value != (Object)null) { Object.Destroy((Object)(object)value); } held.Remove(id); heldIds.Remove(id); } private void BeforeSceneChange() { Cleanup("before scene unload"); } private void AnimateVisuals() { AnimateGreen(); AnimateGravity(); } internal void Force(string id) { //IL_0060: Unknown result type (might be due to invalid IL or missing references) if (!HostEnabled) { throw new InvalidOperationException("Enable Custom Items in host setup first"); } Registry.EnsureRegistered(); CustomItemDefinition customItemDefinition = Registry.Get(id) ?? throw new ArgumentException("Unknown stable item id"); PlayerInfo localPlayerInfo = GameManager.LocalPlayerInfo; int num = default(int); if (!localPlayerInfo.Inventory.HasSpaceForItem(ref num)) { throw new InvalidOperationException("Inventory full"); } if (!localPlayerInfo.Inventory.ServerTryAddItem(customItemDefinition.Type, customItemDefinition.Uses)) { throw new InvalidOperationException("Native grant rejected"); } localPlayerInfo.Inventory.TrySelectItemSlot(num, false); log("Forced native grant " + id); } internal void Cleanup(string reason) { //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) diagnosticCheck = null; diagnosticUndo?.Invoke(); diagnosticUndo = null; CleanupCapture(reason); CleanupGreen(); CleanupGravity(); blowers.Clear(); uint[] array = held.Keys.ToArray(); foreach (uint id in array) { RemoveHeld(id); } if (NetworkServer.active) { foreach (PlayerInfo item in Players()) { for (int j = 0; j < item.Inventory.slots.Count; j++) { if (Registry.Get(item.Inventory.slots[j].itemType) != null) { Consume(item.Inventory, j); } } } } if (NetworkServer.active && serverRegistered) { SendState(); } } internal void Consume(PlayerInventory inventory, int slot) { AccessTools.DeclaredMethod(typeof(PlayerInventory), "RemoveItemAt", (Type[])null, (Type[])null).Invoke(inventory, new object[3] { slot, false, true }); } internal void Notify(string text) { notice(text); log(text); } public void Dispose() { BNetworkManager.WillChangeScene -= BeforeSceneChange; try { Cleanup("plugin shutdown"); } finally { ClearNativeWeights(); StopNetworking(); Registry.Dispose(); itemHarmony.UnpatchSelf(); if (Current == this) { Current = null; } } } internal void PreserveSettingsUntilNextCourse() { if (resetSettings == null) { resetSettings = new ResetSettingsSnapshot(itemConfig, (string s) => s == "CustomItems" || s.StartsWith("CustomItems.")); } } internal void UseNextCourseSettings() { resetSettings = null; } private T Setting<T>(ConfigEntry<T> entry) { if (resetSettings == null) { return entry.Value; } return resetSettings.Read<T>(entry); } private void TickDiagnostics() { if (diagnosticCheck == null || NetworkTime.time < diagnosticAt) { return; } Action action = diagnosticCheck; diagnosticCheck = null; try { action(); } catch (Exception ex) { log("DIAGNOSTIC FAILED: " + ex.Message); } finally { diagnosticUndo?.Invoke(); diagnosticUndo = null; } } internal void Inspect() { //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_0162: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: 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_0285: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_02a6: Unknown result type (might be due to invalid IL or missing references) log("Enabled=" + Enabled + " scene=" + scene + " held=" + held.Count + " captures=" + captures.Count + " hidden=" + hiddenPlayers.Count + " green=" + greenId + " collider=" + ((Object)(object)greenColliders != (Object)null)); foreach (PlayerInfo item in Players()) { log("Player id=" + ((NetworkBehaviour)item).netId + " position=" + ((object)((Component)item).transform.position/*cast due to .constrained prefix*/).ToString() + " eligible=" + Eligible(item) + " equipped=" + ((object)item.Inventory.GetEffectivelyEquippedItem(false)/*cast due to .constrained prefix*/).ToString() + " handActive=" + ((Component)item.RightHandEquipmentSwitcher).gameObject.activeInHierarchy + " handScale=" + ((object)((Component)item.RightHandEquipmentSwitcher).transform.lossyScale/*cast due to .constrained prefix*/).ToString()); } foreach (KeyValuePair<uint, GameObject> item2 in held) { if ((Object)(object)item2.Value != (Object)null) { Renderer componentInChildren = item2.Value.GetComponentInChildren<Renderer>(); log("Held id=" + item2.Key + " active=" + item2.Value.activeInHierarchy + " scale=" + ((object)item2.Value.transform.lossyScale/*cast due to .constrained prefix*/).ToString() + " bounds=" + ((object)componentInChildren.bounds/*cast due to .constrained prefix*/).ToString() + " shader=" + ((Object)componentInChildren.sharedMaterial.shader).name + " visible=" + componentInChildren.isVisible); } } log(Gravity.Inspect()); } internal unsafe void Test(string action, PlayerInfo dummy) { //IL_0e55: 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_007b: Expected O, but got Unknown //IL_03f3: Unknown result type (might be due to invalid IL or missing references) //IL_03f8: Unknown result type (might be due to invalid IL or missing references) //IL_0409: Unknown result type (might be due to invalid IL or missing references) //IL_040e: Unknown result type (might be due to invalid IL or missing references) //IL_0413: Unknown result type (might be due to invalid IL or missing references) //IL_041d: Unknown result type (might be due to invalid IL or missing references) //IL_0422: Unknown result type (might be due to invalid IL or missing references) //IL_043a: Unknown result type (might be due to invalid IL or missing references) //IL_044b: Unknown result type (might be due to invalid IL or missing references) //IL_0455: Unknown result type (might be due to invalid IL or missing references) //IL_047d: Unknown result type (might be due to invalid IL or missing references) //IL_0482: Unknown result type (might be due to invalid IL or missing references) //IL_0667: Unknown result type (might be due to invalid IL or missing references) //IL_066c: Unknown result type (might be due to invalid IL or missing references) //IL_067d: Unknown result type (might be due to invalid IL or missing references) //IL_0682: Unknown result type (might be due to invalid IL or missing references) //IL_0687: Unknown result type (might be due to invalid IL or missing references) //IL_068c: Unknown result type (might be due to invalid IL or missing references) //IL_069c: Unknown result type (might be due to invalid IL or missing references) //IL_06b7: Unknown result type (might be due to invalid IL or missing references) //IL_06c1: 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_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_0726: Unknown result type (might be due to invalid IL or missing references) //IL_0736: Unknown result type (might be due to invalid IL or missing references) //IL_0740: Unknown result type (might be due to invalid IL or missing references) //IL_0745: Unknown result type (might be due to invalid IL or missing references) //IL_0757: Unknown result type (might be due to invalid IL or missing references) //IL_0763: Unknown result type (might be due to invalid IL or missing references) //IL_0795: Unknown result type (might be due to invalid IL or missing references) //IL_079a: Unknown result type (might be due to invalid IL or missing references) //IL_079f: Unknown result type (might be due to invalid IL or missing references) //IL_07af: Unknown result type (might be due to invalid IL or missing references) //IL_07b4: Unknown result type (might be due to invalid IL or missing references) //IL_07b9: Unknown result type (might be due to invalid IL or missing references) //IL_07c3: Unknown result type (might be due to invalid IL or missing references) //IL_07c8: Unknown result type (might be due to invalid IL or missing references) //IL_07cd: Unknown result type (might be due to invalid IL or missing references) //IL_07d1: Unknown result type (might be due to invalid IL or missing references) //IL_0572: Unknown result type (might be due to invalid IL or missing references) //IL_0577: Unknown result type (might be due to invalid IL or missing references) //IL_058d: Unknown result type (might be due to invalid IL or missing references) //IL_0592: Unknown result type (might be due to invalid IL or missing references) //IL_05b4: Unknown result type (might be due to invalid IL or missing references) //IL_05ca: Unknown result type (might be due to invalid IL or missing references) //IL_05d4: Unknown result type (might be due to invalid IL or missing references) //IL_0523: Unknown result type (might be due to invalid IL or missing references) //IL_0528: Unknown result type (might be due to invalid IL or missing references) //IL_0323: Unknown result type (might be due to invalid IL or missing references) //IL_0328: Unknown result type (might be due to invalid IL or missing references) //IL_0332: 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_034d: Unknown result type (might be due to invalid IL or missing references) //IL_08b7: Unknown result type (might be due to invalid IL or missing references) //IL_08bc: Unknown result type (might be due to invalid IL or missing references) //IL_0901: Unknown result type (might be due to invalid IL or missing references) //IL_0906: Unknown result type (might be due to invalid IL or missing references) //IL_0923: Unknown result type (might be due to invalid IL or missing references) //IL_092a: Unknown result type (might be due to invalid IL or missing references) //IL_0a74: Unknown result type (might be due to invalid IL or missing references) //IL_0a79: Unknown result type (might be due to invalid IL or missing references) //IL_0a7c: Unknown result type (might be due to invalid IL or missing references) //IL_0a81: Unknown result type (might be due to invalid IL or missing references) //IL_0a8b: Unknown result type (might be due to invalid IL or missing references) //IL_0a90: Unknown result type (might be due to invalid IL or missing references) //IL_0a95: Unknown result type (might be due to invalid IL or missing references) //IL_0a96: Unknown result type (might be due to invalid IL or missing references) //IL_0aa4: Unknown result type (might be due to invalid IL or missing references) //IL_0aa9: Unknown result type (might be due to invalid IL or missing references) //IL_0ab3: Unknown result type (might be due to invalid IL or missing references) //IL_0ab5: Unknown result type (might be due to invalid IL or missing references) //IL_094c: Unknown result type (might be due to invalid IL or missing references) //IL_0951: Unknown result type (might be due to invalid IL or missing references) //IL_0956: Unknown result type (might be due to invalid IL or missing references) //IL_0960: Unknown result type (might be due to invalid IL or missing references) //IL_0965: Unknown result type (might be due to invalid IL or missing references) //IL_0982: Unknown result type (might be due to invalid IL or missing references) //IL_0993: Unknown result type (might be due to invalid IL or missing references) //IL_09de: Unknown result type (might be due to invalid IL or missing references) //IL_09f1: Unknown result type (might be due to invalid IL or missing references) //IL_09f6: Unknown result type (might be due to invalid IL or missing references) //IL_0cd2: Unknown result type (might be due to invalid IL or missing references) //IL_0cd7: Unknown result type (might be due to invalid IL or missing references) //IL_0cdb: Unknown result type (might be due to invalid IL or missing references) //IL_0d06: Unknown result type (might be due to invalid IL or missing references) //IL_0d0b: Unknown result type (might be due to invalid IL or missing references) //IL_0d16: Unknown result type (might be due to invalid IL or missing references) //IL_0d1b: Unknown result type (might be due to invalid IL or missing references) //IL_0af3: Unknown result type (might be due to invalid IL or missing references) //IL_0b01: Unknown result type (might be due to invalid IL or missing references) //IL_0b06: Unknown result type (might be due to invalid IL or missing references) //IL_0b10: Unknown result type (might be due to invalid IL or missing references) //IL_0db9: Unknown result type (might be due to invalid IL or missing references) //IL_0b59: Unknown result type (might be due to invalid IL or missing references) //IL_0b5e: Unknown result type (might be due to invalid IL or missing references) //IL_0b65: Unknown result type (might be due to invalid IL or missing references) //IL_0b6a: Unknown result type (might be due to invalid IL or missing references) //IL_0b6f: Unknown result type (might be due to invalid IL or missing references) //IL_0b70: Unknown result type (might be due to invalid IL or missing references) //IL_0b7a: Unknown result type (might be due to invalid IL or missing references) //IL_0b7f: Unknown result type (might be due to invalid IL or missing references) //IL_0b89: Unknown result type (might be due to invalid IL or missing references) //IL_102a: Unknown result type (might be due to invalid IL or missing references) //IL_102f: Unknown result type (might be due to invalid IL or missing references) //IL_1039: Unknown result type (might be due to invalid IL or missing references) //IL_103e: Unknown result type (might be due to invalid IL or missing references) //IL_1043: Unknown result type (might be due to invalid IL or missing references) //IL_0bc2: Unknown result type (might be due to invalid IL or missing references) //IL_0bcc: Unknown result type (might be due to invalid IL or missing references) //IL_0bd1: Unknown result type (might be due to invalid IL or missing references) //IL_0bdb: Unknown result type (might be due to invalid IL or missing references) PlayerInfo host = GameManager.LocalPlayerInfo; Vector3 val4; if (action == "pool") { ItemSpawner val = Object.FindObjectsByType<ItemSpawner>((FindObjectsInactive)0, (FindObjectsSortMode)0).FirstOrDefault(); if ((Object)(object)val == (Object)null) { throw new InvalidOperationException("No item dispenser"); } ItemSpawnerSettings val2 = (ItemSpawnerSettings)AccessTools.Field(typeof(ItemSpawner), "settings").GetValue(val); Dictionary<string, int> counts = Registry.Items.ToDictionary((CustomItemDefinition x) => x.Id, (CustomItemDefinition x) => 0); for (int num = 0; num < 1000; num++) { ItemType randomItemFor = val2.GetRandomItemFor(host); CustomItemDefinition customItemDefinition = Registry.Get(randomItemFor); if (customItemDefinition != null) { counts[customItemDefinition.Id]++; } } if (HostEnabled && Registry.Items.Any((CustomItemDefinition d) => d.Enabled.Value && d.Weight.Value > 0 && counts[d.Id] == 0)) { throw new InvalidOperationException("Item not drawn"); } if (!HostEnabled && counts.Values.Any((int x) => x != 0)) { throw new InvalidOperationException("Custom item drawn while OFF"); } log("Native pool draws " + string.Join(", ", counts.Select((KeyValuePair<string, int> x) => x.Key + "=" + x.Value))); } else if (action == "pickup") { if (diagnosticCheck != null) { throw new InvalidOperationException("Diagnostic running"); } int num2 = default(int); if (!HostEnabled || !host.Inventory.HasSpaceForItem(ref num2)) { throw new InvalidOperationException("Enable items and empty inventory first"); } ItemSpawner val3 = Object.FindObjectsByType<ItemSpawner>((FindObjectsInactive)0, (FindObjectsSortMode)0).OrderBy(delegate(ItemSpawner x) { //IL_0006: 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) Vector3 val14 = ((Component)x).transform.position - ((Component)host).transform.position; return ((Vector3)(ref val14)).sqrMagnitude; }).FirstOrDefault(); if ((Object)(object)val3 == (Object)null) { throw new InvalidOperationException("No native dispenser"); } int[] weights = Registry.Items.Select((CustomItemDefinition x) => x.Weight.Value).ToArray(); diagnosticUndo = delegate { for (int i = 0; i < weights.Length; i++) { Registry.Items[i].Weight.Value = weights[i]; } }; CustomItemDefinition[] items = Registry.Items; for (num2 = 0; num2 < items.Length; num2++) { items[num2].Weight.Value = 1000; } host.Movement.Teleport(((Component)val3).transform.position + Vector3.up * 0.2f, ((Component)host).transform.rotation, true); diagnosticAt = NetworkTime.time + 6.0; diagnosticCheck = delegate { //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_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_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) InventorySlot val14 = ((IEnumerable<InventorySlot>)host.Inventory.slots).FirstOrDefault((Func<InventorySlot, bool>)((InventorySlot x) => Registry.Get(x.itemType) != null)); if (Registry.Get(val14.itemType) == null) { throw new InvalidOperationException("No custom pickup received (native draw can miss; retry)"); } log("DIAGNOSTIC PASS actual native dispenser pickup " + Registry.Get(val14.itemType).Id + " uses=" + val14.remainingUses); }; } else if (action == "green_ball") { if ((Object)(object)greenColliders == (Object)null) { throw new InvalidOperationException("Wait for barrier activation"); } GolfBall ownBall = host.AsGolfer.OwnBall; if ((Object)(object)ownBall == (Object)null) { throw new InvalidOperationException("Spawn native ball first"); } ownBall.AsEntity.InformWillTeleport(); ownBall.Rigidbody.position = greenCenter + Vector3.right * (greenSize + 3f) + Vector3.up * 2f; ((Component)ownBall).transform.position = ownBall.Rigidbody.position; ownBall.Rigidbody.linearVelocity = Vector3.left * 15f; ownBall.AsEntity.InformTeleported(); Action<string> action2 = log; val4 = ownBall.Rigidbody.linearVelocity; action2("Barrier approach native ball velocity=" + ((object)(*(Vector3*)(&val4))/*cast due to .constrained prefix*/).ToString()); } else if (action == "green_roof_ball") { if ((Object)(object)greenColliders == (Object)null || diagnosticCheck != null) { throw new InvalidOperationException("Wait for dome/no pending test"); } GolfBall ball = host.AsGolfer.OwnBall ?? host.AsGolfer.ServerSpawnBall(((Component)host).transform.position, Quaternion.identity); host.AsGolfer.NetworkownBall = ball; ball.AsEntity.InformWillTeleport(); ball.Rigidbody.position = greenCenter + Vector3.up * (ItemAssets.DomeHeight(greenSize) + 2f); ((Component)ball).transform.position = ball.Rigidbody.position; ball.Rigidbody.linearVelocity = Vector3.down * 8f; ball.Rigidbody.WakeUp(); ball.AsEntity.InformTeleported(); diagnosticAt = NetworkTime.time + 0.5; diagnosticCheck = delegate { //IL_0019: 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) if ((Object)(object)ball == (Object)null || ball.Rigidbody.linearVelocity.y <= 0f) { throw new InvalidOperationException("Native ball did not bounce from dome roof"); } log("DIAGNOSTIC PASS native ball roof bounce velocity=" + ((object)ball.Rigidbody.linearVelocity/*cast due to .constrained prefix*/).ToString()); }; } else if (action == "green_player") { if ((Object)(object)greenColliders == (Object)null) { throw new InvalidOperationException("Wait for barrier activation"); } host.Movement.Teleport(greenCenter + Vector3.right * (greenSize + 2f) + Vector3.up, ((Component)host).transform.rotation, true); host.AsEntity.Rigidbody.linearVelocity = Vector3.left * 10f; } else if (action == "capture_setup") { if ((Object)(object)dummy == (Object)null) { throw new InvalidOperationException("Spawn training golfer first"); } host.Inventory.TryDeselectItem(false, true); Rigidbody rigidbody = dummy.AsEntity.Rigidbody; rigidbody.position = ((Component)host).transform.position + ((Component)host).transform.forward * 4f; ((Component)dummy).transform.position = rigidbody.position; rigidbody.linearVelocity = Vector3.zero; Force("capture_ball"); PlayerInfo p = host; int equippedItemIndex = host.Inventory.EquippedItemIndex; val4 = ((Component)dummy).transform.position + Vector3.up - ((Component)host).transform.position - Vector3.up * 1.2f; Activate(p, equippedItemIndex, ((Vector3)(ref val4)).normalized); } else if (action == "blower_player" || action == "blower_player_far" || action == "blower_ball") { if (diagnosticCheck != null) { throw new InvalidOperationException("Diagnostic still running"); } Rigidbody body; if (action != "blower_ball") { if ((Object)(object)dummy == (Object)null) { throw new InvalidOperationException("Spawn training golfer first"); } body = dummy.AsEntity.Rigidbody; } else { GolfBall val5 = host.AsGolfer.OwnBall ?? host.AsGolfer.ServerSpawnBall(((Component)host).transform.position, Quaternion.identity); host.AsGolfer.NetworkownBall = val5; body = val5.Rigidbody; } Vector3 direction = ((Component)host).transform.forward; body.position = ((Component)host).transform.position + direction * (float)((action == "blower_player_far") ? 8 : 3) + Vector3.up * 0.6f; ((Component)body).transform.position = body.position; body.linearVelocity = Vector3.zero; body.WakeUp(); Physics.SyncTransforms(); Force("leaf_blower"); StartBlower(host, host.Inventory.EquippedItemIndex, direction); Vector3 start = body.position; diagnosticAt = NetworkTime.time + 0.3; diagnosticCheck = delegate { //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_0017: 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_002e: Unknown result type (might be due to invalid IL or missing references) float num8 = Vector3.Dot(body.position - start, direction); float num9 = Vector3.Dot(body.linearVelocity, direction); if (num8 < 0.01f && num9 < 0.1f) { throw new InvalidOperationException(action + " no forward response: " + num8 + " / " + num9 + " kinematic=" + body.isKinematic); } log("DIAGNOSTIC PASS " + action + " travel=" + num8 + " velocity=" + num9); }; } else if (action == "green_geometry") { if ((Object)(object)greenColliders == (Object)null) { throw new InvalidOperationException("Wait for field"); } if ((Object)(object)greenColliders.GetComponent<MeshCollider>() == (Object)null) { throw new InvalidOperationException("Missing dome collider"); } Vector3 right = Vector3.right; Vector3 val6 = greenCenter + Vector3.up * 2f; RaycastHit val7 = default(RaycastHit); if (!Physics.SphereCast(val6 + right * (greenSize + 2f), 0.2f, -right, ref val7, 4f, -1, (QueryTriggerInteraction)1) || !((Component)((RaycastHit)(ref val7)).collider).transform.IsChildOf(greenColliders.transform)) { throw new InvalidOperationException("Outside approach missed field"); } RaycastHit val8 = default(RaycastHit); if (!Physics.SphereCast(val6 + right * (greenSize - 2f), 0.2f, right, ref val8, 4f, -1, (QueryTriggerInteraction)1) || !((Component)((RaycastHit)(ref val8)).collider).transform.IsChildOf(greenColliders.transform)) { throw new InvalidOperationException("Inside approach missed field"); } float num3 = ItemAssets.DomeHeight(greenSize); Vector3 val9 = greenCenter + Vector3.up * num3; RaycastHit val10 = default(RaycastHit); if (!Physics.SphereCast(val9 + Vector3.up * 2f, 0.2f, Vector3.down, ref val10, 4f, -1, (QueryTriggerInteraction)1) || (Object)(object)((Component)((RaycastHit)(ref val10)).collider).gameObject != (Object)(object)greenColliders) { throw new InvalidOperationException("Outside roof missed dome"); } RaycastHit val11 = default(RaycastHit); if (!Physics.SphereCast(val9 - Vector3.up * 2f, 0.2f, Vector3.up, ref val11, 4f, -1, (QueryTriggerInteraction)1) || (Object)(object)((Component)((RaycastHit)(ref val11)).collider).gameObject != (Object)(object)greenColliders) { throw new InvalidOperationException("Inside roof missed dome"); } string text = greenId; if (StartGreen() || greenId != text) { throw new InvalidOperationException("Stacking accepted"); } log("DIAGNOSTIC PASS two-way dome side/roof sweeps and stacking rejection; layer=" + ((Component)((RaycastHit)(ref val7)).collider).gameObject.layer); } else if (action == "gravity_consumers") { if (!Gravity.TotalOverride) { throw new InvalidOperationException("Wait for active TOTAL override"); } GolfBall ownBall2 = host.AsGolfer.OwnBall; if ((Object)(object)ownBall2 == (Object)null) { throw new InvalidOperationException("Spawn native ball first"); } Rigidbody rigidbody2 = ownBall2.Rigidbody; Vector3 linearVelocity = rigidbody2.linearVelocity; try { rigidbody2.linearVelocity = Vector3.zero; AccessTools.DeclaredMethod(typeof(GolfBall), "ApplyGravity", (Type[])null, (Type[])null).Invoke(ownBall2, null); val4 = rigidbody2.linearVelocity; float magnitude = ((Vector3)(ref val4)).magnitude; val4 = Physics.gravity; float num4 = ((Vector3)(ref val4)).magnitude * Time.fixedDeltaTime; if (Mathf.Abs(magnitude - num4) > 0.001f) { throw new InvalidOperationException("Native ball delta mismatch " + magnitude + " != " + num4); } float num5 = (float)AccessTools.DeclaredMethod(typeof(PlayerMovement), "GetBaseGravitySpeedDelta", (Type[])null, (Type[])null).Invoke(host.Movement, null); float num6 = (float)AccessTools.Field(typeof(PlayerMovement), "gravityFactor").GetValue(host.Movement); float num7 = Physics.gravity.y * GameManager.PlayerMovementSettings.BaseGravityFactor * num6 * Time.fixedDeltaTime; if (Mathf.Abs(num5 - num7) > 0.001f) { throw new InvalidOperationException("Native player delta mismatch"); } log("DIAGNOSTIC PASS native gravity consumers ball=" + magnitude + " player=" + num5 + " TOTAL=" + Gravity.Effective); } finally { rigidbody2.linearVelocity = linearVelocity; } } else if (action == "capture_timeout") { if (!captures.TryGetValue(((NetworkBehaviour)host).netId, out var value) || value.Victim == 0) { throw new InvalidOperationException("No occupied Capture Ball"); } value.Until = NetworkTime.time; } else if (action == "capture_controls") { if (!captures.TryGetValue(((NetworkBehaviour)host).netId, out var value2) || value2.Victim == 0) { throw new InvalidOperationException("No occupied Capture Ball"); } PlayerInfo val12 = Player(value2.Victim); if ((Object)(object)val12 == (Object)null) { throw new InvalidOperationException("Victim disconnected"); } if (val12.Movement.IsVisible || !val12.AsEntity.Rigidbody.isKinematic || val12.AsGolfer.CanMove() || val12.AsGolfer.TryStartChargingSwing() || val12.Movement.TryTriggerJump() || val12.Movement.TryDive() || val12.Inventory.TrySelectItemSlot(0, true) || (bool)AccessTools.DeclaredMethod(typeof(PlayerGolfer), "CanAimSwing", (Type[])null, (Type[])null).Invoke(val12.AsGolfer, null)) { throw new InvalidOperationException("Captured controls not suspended"); } log("DIAGNOSTIC PASS capture native visibility/kinematic/move/aim/swing/jump/dive/inventory guards"); } else if (action == "capture_kill") { if (!captures.TryGetValue(((NetworkBehaviour)host).netId, out var value3) || value3.Victim == 0) { throw new InvalidOperationException("No occupied Capture Ball"); } Bounds val13 = default(Bounds); if (!BoundsManager.TryGetLevelBounds(ref val13)) { throw new InvalidOperationException("No bounds"); } value3.Flying = true; value3.Position = ((Bounds)(ref val13)).max + Vector3.right * 100f; } else { if (!(action == "verify_clean")) { throw new ArgumentException("Unknown custom diagnostic"); } if (captures.Count != 0 || hiddenPlayers.Count != 0 || (Object)(object)greenColliders != (Object)null || (Object)(object)greenVisual != (Object)null || gravityEvents.Count != 0 || blowers.Count != 0 || held.Count != 0 || Object.FindObjectsByType<Collider>((FindObjectsInactive)0, (FindObjectsSortMode)0).Any((Collider c) => ((Object)c).name == "CustomItems.GreenProtector.Colliders" || ((Object)(object)((Component)c).transform.parent != (Object)null && ((Object)((Component)c).transform.parent).name == "CustomItems.GreenProtector.Colliders"))) { throw new InvalidOperationException("Custom item state leaked"); } log("Verified all custom effects/objects/captured states cleared"); } Inspect(); } private static void Write(NetworkWriter w, byte[] data) { if (data == null || data.Length > 32768) { throw new InvalidDataException(); } NetworkWriterExtensions.WriteInt(w, data.Length); w.WriteBytes(data, 0, data.Length); } private static byte[] Read(NetworkReader r) { int num = NetworkReaderExtensions.ReadInt(r); if (num < 0 || num > 32768 || num > r.Remaining) { throw new InvalidDataException(); } return NetworkReaderExtensions.ReadBytes(r, num); } private static void RegisterSerializers() { CheckMessage<CustomItemsClientMessage>(); CheckMessage<CustomItemsServerMessage>(); Writer<CustomItemsClientMessage>.write = delegate(NetworkWriter w, CustomItemsClientMessage m) { Write(w, m.Data); }; Reader<CustomItemsClientMessage>.read = (NetworkReader r) => new CustomItemsClientMessage { Data = Read(r) }; Writer<CustomItemsServerMessage>.write = delegate(NetworkWriter w, CustomItemsServerMessage m) { Write(w, m.Data); }; Reader<CustomItemsServerMessage>.read = (NetworkReader r) => new CustomItemsServerMessage { Data = Read(r) }; } private static void CheckMessage<T>() where T : struct, NetworkMessage { ushort id = NetworkMessages.GetId<T>(); if (NetworkMessages.Lookup.TryGetValue(id, out var value) && value != typeof(T)) { throw new InvalidOperationException("CustomItems Mirror ID collision"); } } internal void StartServer() { RegisterSerializers(); session = Guid.NewGuid().ToString("N"); revision = 0L; NetworkServer.RegisterHandler<CustomItemsClientMessage>((Action<NetworkConnectionToClient, CustomItemsClientMessage>)ReceiveClient, true); serverRegistered = true; } internal void StartClient() { RegisterSerializers(); remoteEnabled = false; acceptedRevision = 0L; sequence = 0L; remoteSession = ""; nextHello = 0.0; NetworkClient.RegisterHandler<CustomItemsServerMessage>((Action<CustomItemsServerMessage>)ReceiveServer, true); clientRegistered = true; } internal void StopNetworking() { UseNextCourseSettings(); if (serverRegistered) { NetworkServer.UnregisterHandler<CustomItemsClientMessage>(); } if (clientRegistered) { NetworkClient.UnregisterHandler<CustomItemsServerMessage>(); } serverRegistered = (clientRegistered = (remoteEnabled = false)); lastRequest.Clear(); lastSequence.Clear(); lastHello.Clear(); remoteSession = ""; } internal void PeerDisconnected(int id) { lastRequest.Remove(id); lastSequence.Remove(id); lastHello.Remove(id); } private static byte[] Packet(Action<BinaryWriter> action) { using MemoryStream memoryStream = new MemoryStream(); using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8, leaveOpen: true)) { binaryWriter.Write((byte)1); action(binaryWriter); } if (memoryStream.Length > 32768) { throw new InvalidDataException(); } return memoryStream.ToArray(); } private void Broadcast(byte[] bytes) { if (!serverRegistered) { return; } foreach (NetworkConnectionToClient value in NetworkServer.connections.Values) { if (((NetworkConnection)value).isAuthenticated && (object)value != NetworkServer.localConnection && peerReady(value.connectionId)) { ((NetworkConnection)value).Send<CustomItemsServerMessage>(new CustomItemsServerMessage { Data = bytes }, 0); } } } private void SendUse(int slot) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) if (NetworkServer.active) { Activate(GameManager.LocalPlayerInfo, slot, LocalDirection()); } else if (remoteEnabled && NetworkClient.isConnected && clientReady()) { NetworkClient.Send<CustomItemsClientMessage>(new CustomItemsClientMessage { Data = Packet(delegate(BinaryWriter w) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) w.Write((byte)1); w.Write(remoteSession); w.Write(++sequence); w.Write(slot); Vector(w, LocalDirection()); }) }, 0); } } private static Vector3 LocalDirection() { //IL_0027: 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) if (!((Object)(object)GameManager.Camera != (Object)null)) { return ((Component)GameManager.LocalPlayerInfo).transform.forward; } return ((Component)GameManager.Camera).transform.forward; } private void ReceiveClient(NetworkConnectionToClient c, CustomItemsClientMessage m) { //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_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: Unknown result type (might be due to invalid IL or missing references) if (Faulted || !peerReady(c.connectionId)) { return; } try { using MemoryStream memoryStream = new MemoryStream(m.Data); using BinaryReader binaryReader = new BinaryReader(memoryStream); if (binaryReader.ReadByte() != 1) { return; } switch (binaryReader.ReadByte()) { case 0: { if (!lastHello.TryGetValue(c.connectionId, out var value3) || NetworkTime.time - value3 > 1.0) { lastHello[c.connectionId] = NetworkTime.time; SendState(c); } break; } case 1: { if (!HostEnabled || !Playing || binaryReader.ReadString() != session) { break; } long num = binaryReader.ReadInt64(); int slot = binaryReader.ReadInt32(); Vector3 v = Vector(binaryReader); if (memoryStream.Position != memoryStream.Length || !Valid(v) || ((Vector3)(ref v)).sqrMagnitude < 0.5f || ((Vector3)(ref v)).sqrMagnitude > 1.5f || (lastSequence.TryGetValue(c.connectionId, out var value) && num <= value)) { break; } lastSequence[c.connectionId] = num; if (!lastRequest.TryGetValue(c.connectionId, out var value2) || !(NetworkTime.time - value2 < 0.07)) { lastRequest[c.connectionId] = NetworkTime.time; NetworkIdentity identity = ((NetworkConnection)c).identity; PlayerInfo val = ((identity != null) ? ((Component)identity).GetComponent<PlayerInfo>() : null); if (!((Object)(object)val == (Object)null)) { Activate(val, slot, ((Vector3)(ref v)).normalized); } } break; } } } catch (Exception ex) when (ex is IOException || ex is ArgumentException) { log("Rejected custom intent: " + ex.GetType().Name); } } private void Activate(PlayerInfo p, int slot, Vector3 direction) { //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_0075: 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_0092: 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_0118: Unknown result type (might be due to invalid IL or missing references) if (!HostEnabled || !Playing || !Eligible(p) || IsCaptured(((NetworkBehaviour)p).netId) || slot < 0 || slot >= p.Inventory.slots.Count || (((NetworkBehaviour)p).isLocalPlayer ? p.Inventory.EquippedItemIndex : p.NetworkedEquippedItemIndex) != slot) { return; } InventorySlot val = p.Inventory.slots[slot]; CustomItemDefinition customItemDefinition = Registry.Get(val.itemType); if (customItemDefinition == null || !Setting<bool>(customItemDefinition.Enabled) || val.remainingUses <= 0 || (CarrierSlot(((NetworkBehaviour)p).netId, out var slot2) && slot2 != slot)) { return; } if (customItemDefinition.Id == "leaf_blower") { StartBlower(p, slot, direction); return; } if (customItemDefinition.Id == "green_protector") { if (!StartGreen(p)) { return; } } else if (customItemDefinition.Id == "gravity_swapper") { StartGravity(); } else if (customItemDefinition.Id == "capture_ball") { if (ThrowCapture(p, slot, direction)) { SendState(); } return; } Consume(p.Inventory, slot); log("Activated " + customItemDefinition.Id + " owner=" + ((NetworkBehaviour)p).netId); SendState(); } private void SendState(NetworkConnectionToClient only = null) { byte[] array = Packet(delegate(BinaryWriter w) { w.Write((byte)0); w.Write(session); w.Write(++revision); w.Write(HostEnabled); CustomItemDefinition[] items = Registry.Items; foreach (CustomItemDefinition customItemDefinition in items) { w.Write(Setting<bool>(customItemDefinition.Enabled)); w.Write(Setting<int>(customItemDefinition.Weight)); } WriteGreen(w); WriteGravity(w); WriteCapture(w); WriteBlower(w); }); if (only != null) { ((NetworkConnection)only).Send<CustomItemsServerMessage>(new CustomItemsServerMessage { Data = array }, 0); } else { Broadcast(array); } } private void ReceiveServer(CustomItemsServerMessage m) { //IL_0143: 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_01aa: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Unknown result type (might be due to invalid IL or missing references) //IL_01bc: 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_0193: Unknown result type (might be due to invalid IL or missing references) if (Faulted || NetworkServer.active) { return; } try { using MemoryStream input = new MemoryStream(m.Data); using BinaryReader binaryReader = new BinaryReader(input); if (binaryReader.ReadByte() != 1) { return; } switch (binaryReader.ReadByte()) { case 0: { string text = binaryReader.ReadString(); long num = binaryReader.ReadInt64(); if (text.Length == 32 && (!(text == remoteSession) || num > acceptedRevision)) { if (text != remoteSession) { Cleanup("host session changed"); acceptedRevision = 0L; remoteSession = text; } acceptedRevision = num; bool flag = binaryReader.ReadBoolean(); if (!flag && remoteEnabled) { Cleanup("host disabled"); } remoteEnabled = flag; remoteSettings = new Tuple<bool, int>[Registry.Items.Length]; for (int i = 0; i < remoteSettings.Length; i++) { remoteSettings[i] = Tuple.Create(binaryReader.ReadBoolean(), binaryReader.ReadInt32()); } ReadGreen(binaryReader); ReadGravity(binaryReader); ReadCapture(binaryReader); ReadBlower(binaryReader); } break; } case 1: