Decompiled source of OddsDump v1.3.0

OddsDump.dll

Decompiled 5 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using DunGen;
using DunGen.Graph;
using GameNetcodeStuff;
using HarmonyLib;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("OddsDump")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("OddsDump")]
[assembly: AssemblyTitle("OddsDump")]
[assembly: AssemblyMetadata("AI_Assisted_Creation", "Code generated with Anthropic Claude (Claude Opus 5.5 and other Claude models, via Claude Code); designed and tested by the author")]
[assembly: AssemblyMetadata("AI_Model_Vendor", "Anthropic")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace OddsDump;

internal static class AutoSurvey
{
	private enum Step
	{
		Off,
		Route,
		Travel,
		Pull,
		Landing,
		WaitLog,
		Linger,
		Leave,
		Orbit
	}

	private static Step _step = Step.Off;

	private static List<SelectableLevel> _plan = new List<SelectableLevel>();

	private static int _index;

	private static float _stepAt;

	private static float _stableSince = -1f;

	private static int _logSerialAtLanding;

	private static int _done;

	private static int _failed;

	private static StartMatchLever _lever;

	private static MethodInfo _chat;

	internal static bool Running => _step != Step.Off;

	private static float InStep => Time.time - _stepAt;

	internal static void Tick()
	{
		try
		{
			Keyboard current = Keyboard.current;
			if (current != null && ((ButtonControl)current.f10Key).wasPressedThisFrame && current.ctrlKey.isPressed && current.shiftKey.isPressed)
			{
				if (Running)
				{
					Stop("stopped by you");
				}
				else
				{
					Start();
				}
			}
			if (Running)
			{
				Step1();
			}
		}
		catch (Exception ex)
		{
			Stop("error: " + ex.Message);
			Plugin.Log.LogError((object)("AutoSurvey: " + ex));
		}
	}

	private static void Start()
	{
		StartOfRound instance = StartOfRound.Instance;
		NetworkManager singleton = NetworkManager.Singleton;
		if ((Object)(object)instance == (Object)null || (Object)(object)singleton == (Object)null || !singleton.IsServer)
		{
			Say("AutoSurvey: host a game first.");
			return;
		}
		if (!instance.inShipPhase)
		{
			Say("AutoSurvey: start it in orbit.");
			return;
		}
		HashSet<string> exclude = new HashSet<string>(from s in Plugin.SurveyExclude.Value.Split(',')
			select s.Trim() into s
			where s.Length > 0
			select s, StringComparer.OrdinalIgnoreCase);
		HashSet<string> only = new HashSet<string>(from s in Plugin.SurveyOnly.Value.Split(',')
			select s.Trim() into s
			where s.Length > 0
			select s, StringComparer.OrdinalIgnoreCase);
		List<SelectableLevel> list = instance.levels.Where((SelectableLevel l) => (Object)(object)l != (Object)null && l.levelID != 3 && l.planetHasTime && l.sceneName != "CompanyBuilding" && !Matches(exclude, l) && (only.Count == 0 || Matches(only, l))).ToList();
		if (list.Count == 0)
		{
			Say("AutoSurvey: no moons to visit (check SurveyOnly / SurveyExclude).");
			return;
		}
		_plan.Clear();
		for (int num = 0; num < Math.Max(1, Plugin.SurveyLandingsPerMoon.Value); num++)
		{
			_plan.AddRange(list);
		}
		_index = 0;
		_done = 0;
		_failed = 0;
		_lever = Object.FindObjectOfType<StartMatchLever>();
		if ((Object)(object)_lever == (Object)null)
		{
			Say("AutoSurvey: ship lever not found.");
			_plan.Clear();
			return;
		}
		Plugin.LogLandingsForced = true;
		Go(Step.Orbit);
		Plugin.Log.LogInfo((object)("AutoSurvey: started, " + list.Count + " moons x " + Plugin.SurveyLandingsPerMoon.Value + " = " + _plan.Count + " landings: " + string.Join(", ", list.Select((SelectableLevel m) => m.PlanetName))));
		Say("AutoSurvey: started, " + _plan.Count + " landings (" + list.Count + " moons). Ctrl+Shift+F10 stops it.");
	}

	private static bool Matches(HashSet<string> set, SelectableLevel l)
	{
		if (set.Contains(l.PlanetName ?? ""))
		{
			return true;
		}
		string text = l.PlanetName ?? "";
		int num = text.IndexOf(' ');
		if (num > 0)
		{
			return set.Contains(text.Substring(num + 1));
		}
		return false;
	}

	private static void Stop(string why)
	{
		if (Running)
		{
			_step = Step.Off;
			Plugin.LogLandingsForced = false;
			Plugin.Log.LogInfo((object)("AutoSurvey: " + why + ". " + _done + " landings logged, " + _failed + " skipped."));
			Say("AutoSurvey: " + why + ". " + _done + " landings logged, " + _failed + " skipped.");
		}
	}

	private static void Go(Step s)
	{
		_step = s;
		_stepAt = Time.time;
		_stableSince = -1f;
	}

	private static void Step1()
	{
		StartOfRound instance = StartOfRound.Instance;
		TimeOfDay instance2 = TimeOfDay.Instance;
		if ((Object)(object)instance == (Object)null)
		{
			Stop("left the game");
			return;
		}
		if ((Object)(object)_lever == (Object)null)
		{
			_lever = Object.FindObjectOfType<StartMatchLever>();
		}
		PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null);
		switch (_step)
		{
		case Step.Orbit:
			if (!instance.inShipPhase || instance.shipIsLeaving || instance.travellingToNewLevel || instance.newGameIsLoading || instance.firingPlayersCutsceneRunning || !((Object)(object)_lever != (Object)null) || !((Object)(object)_lever.triggerScript != (Object)null) || !_lever.triggerScript.interactable || !((Object)(object)val != (Object)null) || val.isPlayerDead)
			{
				_stableSince = -1f;
				if (InStep > 180f)
				{
					Stop("ship never got ready in orbit");
				}
				break;
			}
			if (_stableSince < 0f)
			{
				_stableSince = Time.time;
			}
			if (!(Time.time - _stableSince < 4f))
			{
				if (_index >= _plan.Count)
				{
					Stop("finished");
				}
				else
				{
					Go(Step.Route);
				}
			}
			break;
		case Step.Route:
		{
			SelectableLevel val2 = _plan[_index];
			Terminal val3 = Object.FindObjectOfType<Terminal>();
			int num = (((Object)(object)val3 != (Object)null) ? val3.groupCredits : 0);
			if (instance.currentLevelID != val2.levelID)
			{
				instance.ChangeLevelServerRpc(val2.levelID, num);
			}
			Plugin.Log.LogInfo((object)("AutoSurvey: " + (_index + 1) + "/" + _plan.Count + " routing to " + val2.PlanetName));
			Go(Step.Travel);
			break;
		}
		case Step.Travel:
			if (InStep < 1.5f)
			{
				break;
			}
			if (instance.travellingToNewLevel)
			{
				if (InStep > 60f)
				{
					Skip("routing never finished");
				}
			}
			else if (instance.currentLevelID != _plan[_index].levelID)
			{
				if (InStep > 10f)
				{
					Skip("route was refused");
				}
			}
			else if (!_lever.triggerScript.interactable)
			{
				if (InStep > 30f)
				{
					Skip("lever not usable after routing");
				}
			}
			else
			{
				Go(Step.Pull);
			}
			break;
		case Step.Pull:
			if (!(InStep < 1f))
			{
				_lever.LeverAnimation();
				_lever.PullLever();
				_logSerialAtLanding = LandingLog.Serial;
				Go(Step.Landing);
			}
			break;
		case Step.Landing:
			if (instance.shipHasLanded && !instance.inShipPhase)
			{
				Go(Step.WaitLog);
			}
			else if (InStep > 150f)
			{
				Stop("landing on " + _plan[_index].PlanetName + " took over 150 s; stopped so nothing breaks (check the log)");
			}
			break;
		case Step.WaitLog:
			if (LandingLog.Serial != _logSerialAtLanding)
			{
				_done++;
				Go(Step.Linger);
			}
			else if (instance.inShipPhase)
			{
				Skip("ship left before the landing was logged");
				Go(Step.Orbit);
			}
			else if (InStep > 30f)
			{
				_failed++;
				Plugin.Log.LogWarning((object)("AutoSurvey: no landing log on " + _plan[_index].PlanetName + " after 30 s; leaving anyway"));
				Go(Step.Linger);
			}
			break;
		case Step.Linger:
			if (!(InStep < Mathf.Max(0f, Plugin.SurveySecondsOnMoon.Value)))
			{
				if ((Object)(object)instance2 != (Object)null && instance2.quotaFulfilled < instance2.profitQuota)
				{
					instance2.quotaFulfilled = instance2.profitQuota;
					instance2.UpdateProfitQuotaCurrentTime();
				}
				if ((Object)(object)val == (Object)null || val.isPlayerDead || instance.inShipPhase || instance.shipIsLeaving)
				{
					Next();
					Go(Step.Orbit);
				}
				else if (_lever.triggerScript.interactable || !(InStep < 40f))
				{
					_lever.LeverAnimation();
					_lever.PullLever();
					Go(Step.Leave);
				}
			}
			break;
		case Step.Leave:
			if (instance.inShipPhase || instance.shipIsLeaving)
			{
				Next();
				Go(Step.Orbit);
			}
			else if (InStep > 20f)
			{
				Plugin.Log.LogWarning((object)"AutoSurvey: lever didn't start the takeoff; trying again");
				Go(Step.Linger);
			}
			break;
		}
	}

	private static void Next()
	{
		_index++;
		if (_index % 5 == 0 || _index == _plan.Count)
		{
			Say("AutoSurvey: " + _index + "/" + _plan.Count + " done (" + _done + " logged).");
		}
	}

	private static void Skip(string why)
	{
		_failed++;
		Plugin.Log.LogWarning((object)("AutoSurvey: skipping " + _plan[_index].PlanetName + ": " + why));
		_index++;
		Go(Step.Orbit);
	}

	private static void Say(string text)
	{
		try
		{
			HUDManager instance = HUDManager.Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				if (_chat == null)
				{
					_chat = AccessTools.Method(typeof(HUDManager), "AddChatMessage", (Type[])null, (Type[])null);
				}
				_chat.Invoke(instance, new object[4]
				{
					"<color=#c8a0ff>" + text + "</color>",
					"",
					-1,
					false
				});
			}
		}
		catch
		{
		}
	}
}
internal static class LandingLog
{
	internal static int Serial;

	private static bool _wasLanded;

	private static float _scanAt = -1f;

	private static bool _warned;

	private static readonly CultureInfo IC = CultureInfo.InvariantCulture;

	private static string J(string s)
	{
		if (s != null)
		{
			return "\"" + s.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", " ") + "\"";
		}
		return "null";
	}

	private static string F(float f)
	{
		if (!float.IsNaN(f) && !float.IsInfinity(f))
		{
			return f.ToString("R", IC);
		}
		return "null";
	}

	public static void Tick()
	{
		try
		{
			StartOfRound instance = StartOfRound.Instance;
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)instance == (Object)null || (Object)(object)singleton == (Object)null || !singleton.IsServer)
			{
				_wasLanded = false;
				_scanAt = -1f;
				return;
			}
			bool flag = instance.shipHasLanded && !instance.inShipPhase;
			if (flag && !_wasLanded)
			{
				_scanAt = Time.time + 8f;
			}
			_wasLanded = flag;
			if (_scanAt > 0f && Time.time >= _scanAt)
			{
				_scanAt = -1f;
				if (flag)
				{
					Write(instance);
				}
			}
		}
		catch (Exception ex)
		{
			if (!_warned)
			{
				_warned = true;
				Plugin.Log.LogWarning((object)("LandingLog: " + ex));
			}
		}
	}

	private static float BcmField(string name)
	{
		try
		{
			Type type = AccessTools.TypeByName("BrutalCompanyMinus.Minus.Manager");
			FieldInfo fieldInfo = ((type == null) ? null : AccessTools.Field(type, name));
			return (fieldInfo == null) ? float.NaN : Convert.ToSingle(fieldInfo.GetValue(null));
		}
		catch
		{
			return float.NaN;
		}
	}

	private static void Write(StartOfRound sor)
	{
		RoundManager instance = RoundManager.Instance;
		SelectableLevel val = (((Object)(object)instance != (Object)null) ? instance.currentLevel : sor.currentLevel);
		if ((Object)(object)val == (Object)null)
		{
			return;
		}
		string text = null;
		try
		{
			RuntimeDungeon dungeonGenerator = instance.dungeonGenerator;
			object obj;
			if (dungeonGenerator == null)
			{
				obj = null;
			}
			else
			{
				DungeonGenerator generator = dungeonGenerator.Generator;
				if (generator == null)
				{
					obj = null;
				}
				else
				{
					DungeonFlow dungeonFlow = generator.DungeonFlow;
					obj = ((dungeonFlow != null) ? ((Object)dungeonFlow).name : null);
				}
			}
			text = (string)obj;
		}
		catch
		{
		}
		string text2 = ((object)Unsafe.As<LevelWeatherType, LevelWeatherType>(ref val.currentWeather)/*cast due to .constrained prefix*/).ToString();
		try
		{
			object obj3 = AccessTools.Method(AccessTools.TypeByName("WeatherRegistry.WeatherManager"), "GetCurrentWeather", new Type[1] { typeof(SelectableLevel) }, (Type[])null)?.Invoke(null, new object[1] { val });
			if (obj3 != null)
			{
				text2 = (string)AccessTools.Property(obj3.GetType(), "Name").GetValue(obj3, null);
			}
		}
		catch
		{
		}
		Dictionary<string, (int, int, bool)> dictionary = new Dictionary<string, (int, int, bool)>();
		int num = 0;
		int num2 = 0;
		int num3 = 0;
		int num4 = 0;
		GrabbableObject[] array = Object.FindObjectsOfType<GrabbableObject>();
		foreach (GrabbableObject val2 in array)
		{
			if (!((Object)(object)val2 == (Object)null) && !((Object)(object)val2.itemProperties == (Object)null) && val2.itemProperties.isScrap && !val2.isInShipRoom && !val2.isInElevator && !val2.scrapPersistedThroughRounds && !val2.deactivated)
			{
				num++;
				num2 += val2.scrapValue;
				if (val2.isInFactory)
				{
					num3++;
					num4 += val2.scrapValue;
				}
				string key = val2.itemProperties.itemName ?? "?";
				dictionary.TryGetValue(key, out var value);
				dictionary[key] = (value.Item1 + 1, value.Item2 + val2.scrapValue, val2.isInFactory);
			}
		}
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.Append("{\"utc\":").Append(J(DateTime.UtcNow.ToString("o", IC)));
		stringBuilder.Append(",\"day\":").Append(sor.gameStats.daysSpent);
		stringBuilder.Append(",\"moon\":").Append(J(val.PlanetName)).Append(",\"levelID\":")
			.Append(val.levelID)
			.Append(",\"risk\":")
			.Append(J(val.riskLevel));
		stringBuilder.Append(",\"interior\":").Append(J(text)).Append(",\"dungeonType\":")
			.Append(((Object)(object)instance != (Object)null) ? instance.currentDungeonType : (-1));
		stringBuilder.Append(",\"weather\":").Append(J(text2));
		stringBuilder.Append(",\"rmValueMult\":").Append(F(((Object)(object)instance != (Object)null) ? instance.scrapValueMultiplier : float.NaN));
		stringBuilder.Append(",\"rmAmountMult\":").Append(F(((Object)(object)instance != (Object)null) ? instance.scrapAmountMultiplier : float.NaN));
		stringBuilder.Append(",\"bcmValueMult\":").Append(F(BcmField("scrapValueMultiplier")));
		stringBuilder.Append(",\"bcmAmountMult\":").Append(F(BcmField("scrapAmountMultiplier")));
		stringBuilder.Append(",\"bcmDifficulty\":").Append(F(BcmField("difficulty")));
		stringBuilder.Append(",\"minScrap\":").Append(val.minScrap).Append(",\"maxScrap\":")
			.Append(val.maxScrap);
		stringBuilder.Append(",\"count\":").Append(num).Append(",\"total\":")
			.Append(num2);
		stringBuilder.Append(",\"insideCount\":").Append(num3).Append(",\"insideTotal\":")
			.Append(num4);
		stringBuilder.Append(",\"items\":[");
		bool flag = true;
		foreach (KeyValuePair<string, (int, int, bool)> item in dictionary.OrderByDescending<KeyValuePair<string, (int, int, bool)>, int>((KeyValuePair<string, (int n, int sum, bool inside)> k) => k.Value.sum))
		{
			if (!flag)
			{
				stringBuilder.Append(',');
			}
			flag = false;
			stringBuilder.Append('[').Append(J(item.Key)).Append(',')
				.Append(item.Value.Item1)
				.Append(',')
				.Append(item.Value.Item2)
				.Append(',')
				.Append(item.Value.Item3 ? "true" : "false")
				.Append(']');
		}
		stringBuilder.Append("],\"pool\":[");
		flag = true;
		foreach (SpawnableItemWithRarity item2 in val.spawnableScrap ?? new List<SpawnableItemWithRarity>())
		{
			if (item2 != null && !((Object)(object)item2.spawnableItem == (Object)null))
			{
				if (!flag)
				{
					stringBuilder.Append(',');
				}
				flag = false;
				stringBuilder.Append('[').Append(J(item2.spawnableItem.itemName)).Append(',')
					.Append(item2.rarity)
					.Append(',')
					.Append(item2.spawnableItem.minValue)
					.Append(',')
					.Append(item2.spawnableItem.maxValue)
					.Append(']');
			}
		}
		stringBuilder.Append("]}");
		File.AppendAllText(Path.Combine(Paths.BepInExRootPath, "ScrapDays.jsonl"), stringBuilder.ToString() + "\n");
		Serial++;
		Plugin.Log.LogInfo((object)("LandingLog: " + val.PlanetName + " / " + text + " / " + text2 + ": " + num + " scrap worth " + num2 + " on the moon (inside " + num3 + " worth " + num4 + ") -> ScrapDays.jsonl"));
	}
}
[BepInPlugin("jacob.oddsdump", "OddsDump", "1.3.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class Plugin : BaseUnityPlugin
{
	internal static ManualLogSource Log;

	internal static ConfigEntry<bool> DumpInOrbit;

	internal static ConfigEntry<bool> LogLandings;

	internal static ConfigEntry<int> SurveyLandingsPerMoon;

	internal static ConfigEntry<float> SurveySecondsOnMoon;

	internal static ConfigEntry<string> SurveyExclude;

	internal static ConfigEntry<string> SurveyOnly;

	internal static bool LogLandingsForced;

	private void Awake()
	{
		//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ef: Expected O, but got Unknown
		Log = ((BaseUnityPlugin)this).Logger;
		DumpInOrbit = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "DumpInOrbit", false, "Write OddsDump.json and ScrapDump.json once per launch, 10 s after you're hosting in orbit (about a second of work). Off by default; turn on only for odds/scrap checks.");
		LogLandings = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "LogLandings", false, "Append the scrap actually spawned on each landing to ScrapDays.jsonl (host). Costs a ~0.3 s hitch 8 s after landing, so off by default; turn on for scrap-value runs. Read live.");
		SurveyLandingsPerMoon = ((BaseUnityPlugin)this).Config.Bind<int>("AutoSurvey", "LandingsPerMoon", 3, "AutoSurvey (Ctrl+Shift+F10, host, in orbit): how many times to land on each moon. Moons are visited in rounds.");
		SurveySecondsOnMoon = ((BaseUnityPlugin)this).Config.Bind<float>("AutoSurvey", "SecondsOnMoon", 3f, "Seconds to stay after the landing has been logged (the log itself is written 8 s after landing).");
		SurveyExclude = ((BaseUnityPlugin)this).Config.Bind<string>("AutoSurvey", "ExcludeMoons", "Liquidation", "Comma-separated moons AutoSurvey skips (name with or without the number). The Company is always skipped.");
		SurveyOnly = ((BaseUnityPlugin)this).Config.Bind<string>("AutoSurvey", "OnlyMoons", "", "Comma-separated moons to visit; empty = every moon.");
		GameObject val = new GameObject("OddsDumpRunner")
		{
			hideFlags = (HideFlags)61
		};
		Object.DontDestroyOnLoad((Object)val);
		val.AddComponent<Runner>();
		((BaseUnityPlugin)this).Logger.LogInfo((object)("OddsDump 1.3.0 loaded. AutoSurvey: Ctrl+Shift+F10 in orbit. DumpInOrbit=" + DumpInOrbit.Value + ", LogLandings=" + LogLandings.Value + ((DumpInOrbit.Value || LogLandings.Value) ? "" : " (idle; turn either on in its config for odds/scrap checks)")));
	}
}
internal class Runner : MonoBehaviour
{
	private bool _done;

	private float _readyAt = -1f;

	private void Update()
	{
		AutoSurvey.Tick();
		if (Plugin.LogLandings.Value || Plugin.LogLandingsForced)
		{
			LandingLog.Tick();
		}
		if (_done || !Plugin.DumpInOrbit.Value)
		{
			return;
		}
		StartOfRound instance = StartOfRound.Instance;
		NetworkManager singleton = NetworkManager.Singleton;
		if ((Object)(object)instance == (Object)null || (Object)(object)singleton == (Object)null || !singleton.IsServer || !instance.inShipPhase)
		{
			_readyAt = -1f;
		}
		else if (_readyAt < 0f)
		{
			_readyAt = Time.time + 10f;
		}
		else if (!(Time.time < _readyAt))
		{
			_done = true;
			try
			{
				Dump();
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("OddsDump failed: " + ex));
			}
			try
			{
				ScrapDump.Write();
			}
			catch (Exception ex2)
			{
				Plugin.Log.LogError((object)("ScrapDump failed: " + ex2));
			}
		}
	}

	private static string J(string s)
	{
		return "\"" + (s ?? "").Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
	}

	private unsafe void Dump()
	{
		//IL_0652: Unknown result type (might be due to invalid IL or missing references)
		//IL_0654: Unknown result type (might be due to invalid IL or missing references)
		//IL_085a: Unknown result type (might be due to invalid IL or missing references)
		//IL_085c: Unknown result type (might be due to invalid IL or missing references)
		//IL_057d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0582: Unknown result type (might be due to invalid IL or missing references)
		//IL_06c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_06c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_0586: Unknown result type (might be due to invalid IL or missing references)
		//IL_0588: Unknown result type (might be due to invalid IL or missing references)
		//IL_06c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_06cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_033a: Unknown result type (might be due to invalid IL or missing references)
		//IL_033f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0398: Unknown result type (might be due to invalid IL or missing references)
		//IL_05d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_06fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_021b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0222: Expected O, but got Unknown
		//IL_04a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_04a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_04ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_04b8: Unknown result type (might be due to invalid IL or missing references)
		StringBuilder stringBuilder = new StringBuilder();
		Type type = AccessTools.TypeByName("WeatherRegistry.WeatherManager");
		MethodInfo getWeather = AccessTools.Method(type, "GetWeather", new Type[1] { typeof(LevelWeatherType) }, (Type[])null);
		Type type2 = AccessTools.TypeByName("WeatherTweaks.Variables");
		MethodInfo wtList = ((type2 == null) ? null : AccessTools.Method(type2, "GetPlanetWeightedList", new Type[2]
		{
			typeof(SelectableLevel),
			typeof(float)
		}, (Type[])null));
		Type type3 = AccessTools.TypeByName("WeatherRegistry.Weather");
		MethodInfo nameProp = AccessTools.PropertyGetter(type3, "Name");
		Type type4 = AccessTools.TypeByName("LethalLevelLoader.DungeonManager");
		MethodInfo methodInfo = ((type4 == null) ? null : AccessTools.Method(type4, "GetValidExtendedDungeonFlows", (Type[])null, (Type[])null));
		Type type5 = AccessTools.TypeByName("LethalLevelLoader.LevelManager");
		MethodInfo methodInfo2 = ((type5 == null) ? null : AccessTools.Method(type5, "GetExtendedLevel", new Type[1] { typeof(SelectableLevel) }, (Type[])null));
		Type type6 = AccessTools.TypeByName("LethalLevelLoader.ExtendedDungeonFlowWithRarity");
		FieldInfo fieldInfo = ((type6 == null) ? null : AccessTools.Field(type6, "extendedDungeonFlow"));
		FieldInfo fieldInfo2 = ((type6 == null) ? null : AccessTools.Field(type6, "rarity"));
		MethodInfo methodInfo3 = AccessTools.PropertyGetter(AccessTools.TypeByName("LethalLevelLoader.ExtendedDungeonFlow"), "DungeonName");
		float item = 0.8f;
		try
		{
			item = ((ConfigEntry<float>)AccessTools.Property(AccessTools.TypeByName("WeatherTweaks.ConfigManager"), "MaxMultiplier").GetValue(null)).Value;
		}
		catch
		{
		}
		MethodInfo methodInfo4 = AccessTools.Method(AccessTools.TypeByName("Dawn.DungeonRegistrationHandler"), "UpdateDungeonWeightOnLevel", (Type[])null, (Type[])null);
		if (methodInfo4 == null)
		{
			Plugin.Log.LogWarning((object)"DawnLib UpdateDungeonWeightOnLevel not found; dawnInteriors will show current weights only");
		}
		Dictionary<Object, string> dictionary = new Dictionary<Object, string>();
		try
		{
			Type type7 = AccessTools.TypeByName("LethalLevelLoader.PatchedContent");
			Type type8 = AccessTools.TypeByName("LethalLevelLoader.ExtendedDungeonFlow");
			foreach (object item3 in (IEnumerable)AccessTools.PropertyGetter(type7, "ExtendedDungeonFlows").Invoke(null, null))
			{
				Object val = (Object)AccessTools.PropertyGetter(type8, "DungeonFlow").Invoke(item3, null);
				if (val != (Object)null)
				{
					dictionary[val] = (string)AccessTools.PropertyGetter(type8, "DungeonName").Invoke(item3, null);
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("LLL dungeon names: " + ex.Message));
		}
		StartOfRound instance = StartOfRound.Instance;
		stringBuilder.Append("{\"days\":" + instance.gameStats.daysSpent + ",\"quotas\":" + TimeOfDay.Instance.timesFulfilledQuota + ",\"maxDifficulty\":" + item.ToString(CultureInfo.InvariantCulture) + ",\"levels\":[");
		bool flag = true;
		SelectableLevel[] levels = instance.levels;
		foreach (SelectableLevel val2 in levels)
		{
			if ((Object)(object)val2 == (Object)null)
			{
				continue;
			}
			if (!flag)
			{
				stringBuilder.Append(",");
			}
			flag = false;
			LevelWeatherType currentWeather = val2.currentWeather;
			stringBuilder.Append("{\"name\":" + J(val2.PlanetName) + ",\"id\":" + val2.levelID + ",\"scene\":" + J(val2.sceneName) + ",\"current\":" + J(TypeName(currentWeather)));
			List<LevelWeatherType> list = new List<LevelWeatherType> { (LevelWeatherType)(-1) };
			if (val2.randomWeathers != null)
			{
				list.AddRange(val2.randomWeathers.Select((RandomWeatherWithVariables r) => r.weatherType));
			}
			list = list.Distinct().ToList();
			stringBuilder.Append(",\"possible\":[" + string.Join(",", list.Select((LevelWeatherType p) => J(TypeName(p)))) + "]");
			stringBuilder.Append(",\"byPrev\":{");
			bool flag2 = true;
			List<LevelWeatherType> list2 = new List<LevelWeatherType>(list);
			try
			{
				foreach (object item4 in (IEnumerable)AccessTools.PropertyGetter(type, "Weathers").Invoke(null, null))
				{
					LevelWeatherType item2 = (LevelWeatherType)AccessTools.PropertyGetter(type3, "VanillaWeatherType").Invoke(item4, null);
					if (!list2.Contains(item2))
					{
						list2.Add(item2);
					}
				}
			}
			catch
			{
			}
			int daysSpent = instance.gameStats.daysSpent;
			(string, float)[] array = new(string, float)[3]
			{
				("byPrev", 0.02f),
				("byPrevMid", 0.27f),
				("byPrevMax", item)
			};
			for (int num = 0; num < array.Length; num++)
			{
				if (num > 0)
				{
					stringBuilder.Append(",\"" + array[num].Item1 + "\":{");
				}
				flag2 = true;
				foreach (LevelWeatherType item5 in list2)
				{
					try
					{
						val2.currentWeather = item5;
						if (instance.gameStats.daysSpent < 1)
						{
							instance.gameStats.daysSpent = 1;
						}
						List<(string, int)> l = Weighted(val2, array[num].Item2);
						if (!flag2)
						{
							stringBuilder.Append(",");
						}
						flag2 = false;
						stringBuilder.Append(J(TypeName(item5)) + ":" + WList(l));
					}
					catch (Exception ex2)
					{
						Plugin.Log.LogWarning((object)("weights " + val2.PlanetName + " prev " + ((object)(*(LevelWeatherType*)(&item5))/*cast due to .constrained prefix*/).ToString() + ": " + ex2.Message));
					}
					finally
					{
						val2.currentWeather = currentWeather;
						instance.gameStats.daysSpent = daysSpent;
					}
				}
				stringBuilder.Append("}");
			}
			stringBuilder.Append(",\"dawnInteriors\":{");
			bool flag3 = true;
			foreach (LevelWeatherType item6 in list)
			{
				try
				{
					val2.currentWeather = item6;
					methodInfo4?.Invoke(null, new object[1] { val2 });
					if (!flag3)
					{
						stringBuilder.Append(",");
					}
					flag3 = false;
					stringBuilder.Append(J(TypeName(item6)) + ":[");
					bool flag4 = true;
					IntWithRarity[] array2 = (IntWithRarity[])(((object)val2.dungeonFlowTypes) ?? ((object)new IntWithRarity[0]));
					foreach (IntWithRarity val3 in array2)
					{
						string s = "#" + val3.id;
						try
						{
							DungeonFlow dungeonFlow = RoundManager.Instance.dungeonFlowTypes[val3.id].dungeonFlow;
							s = (dictionary.TryGetValue((Object)(object)dungeonFlow, out var value) ? value : ((Object)dungeonFlow).name);
						}
						catch
						{
						}
						if (!flag4)
						{
							stringBuilder.Append(",");
						}
						flag4 = false;
						stringBuilder.Append("[" + J(s) + "," + val3.rarity + "]");
					}
					stringBuilder.Append("]");
				}
				catch (Exception ex3)
				{
					Plugin.Log.LogWarning((object)("dawn interiors " + val2.PlanetName + " " + ((object)(*(LevelWeatherType*)(&item6))/*cast due to .constrained prefix*/).ToString() + ": " + ex3.Message));
				}
				finally
				{
					val2.currentWeather = currentWeather;
				}
			}
			try
			{
				methodInfo4?.Invoke(null, new object[1] { val2 });
			}
			catch
			{
			}
			stringBuilder.Append("}");
			stringBuilder.Append(",\"interiors\":[");
			try
			{
				object obj5 = methodInfo2?.Invoke(null, new object[1] { val2 });
				if (obj5 != null && methodInfo != null)
				{
					IList obj6 = (IList)methodInfo.Invoke(null, new object[2] { obj5, false });
					bool flag5 = true;
					foreach (object item7 in obj6)
					{
						object value2 = fieldInfo.GetValue(item7);
						if (!flag5)
						{
							stringBuilder.Append(",");
						}
						flag5 = false;
						stringBuilder.Append("[" + J((string)methodInfo3.Invoke(value2, null)) + "," + (int)fieldInfo2.GetValue(item7) + "]");
					}
				}
			}
			catch (Exception ex4)
			{
				Plugin.Log.LogWarning((object)("interiors " + val2.PlanetName + ": " + ex4.Message));
			}
			stringBuilder.Append("]}");
		}
		stringBuilder.Append("]}");
		string text = Path.Combine(Paths.BepInExRootPath, "OddsDump.json");
		File.WriteAllText(text, stringBuilder.ToString());
		Plugin.Log.LogInfo((object)("OddsDump written: " + text + " (" + stringBuilder.Length + " chars)"));
		unsafe string TypeName(LevelWeatherType t)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				object obj7 = getWeather.Invoke(null, new object[1] { t });
				return (obj7 == null) ? ((object)(*(LevelWeatherType*)(&t))/*cast due to .constrained prefix*/).ToString() : WName(obj7);
			}
			catch
			{
				return ((object)(*(LevelWeatherType*)(&t))/*cast due to .constrained prefix*/).ToString();
			}
		}
		static string WList(List<(string, int)> source)
		{
			return "[" + string.Join(",", source.Select(((string, int) x) => "[" + J(x.Item1) + "," + x.Item2 + "]")) + "]";
		}
		string WName(object w)
		{
			try
			{
				return (string)nameProp.Invoke(w, null);
			}
			catch
			{
				return w?.ToString();
			}
		}
		List<(string, int)> Weighted(SelectableLevel lvl, float diff)
		{
			List<(string, int)> list3 = new List<(string, int)>();
			if (wtList == null)
			{
				return list3;
			}
			object obj7 = wtList.Invoke(null, new object[2] { lvl, diff });
			IList obj8 = (IList)AccessTools.PropertyGetter(obj7.GetType(), "Keys").Invoke(obj7, null);
			MethodInfo methodInfo5 = AccessTools.Method(obj7.GetType(), "Get", (Type[])null, (Type[])null);
			foreach (object item8 in obj8)
			{
				list3.Add((WName(item8), (int)methodInfo5.Invoke(obj7, new object[1] { item8 })));
			}
			return list3;
		}
	}
}
internal static class ScrapDump
{
	private sealed class Jw
	{
		private readonly StringBuilder _sb = new StringBuilder(1048576);

		private readonly Stack<bool> _need = new Stack<bool>();

		private bool _afterKey;

		public override string ToString()
		{
			return _sb.ToString();
		}

		private void Pre()
		{
			if (_afterKey)
			{
				_afterKey = false;
			}
			else if (_need.Count > 0)
			{
				if (_need.Peek())
				{
					_sb.Append(',');
				}
				_need.Pop();
				_need.Push(item: true);
			}
		}

		private void Str(string s)
		{
			_sb.Append('"');
			string text = s ?? "";
			foreach (char c in text)
			{
				switch (c)
				{
				case '"':
					_sb.Append("\\\"");
					continue;
				case '\\':
					_sb.Append("\\\\");
					continue;
				case '\n':
					_sb.Append("\\n");
					continue;
				case '\r':
					_sb.Append("\\r");
					continue;
				case '\t':
					_sb.Append("\\t");
					continue;
				}
				if (c < ' ')
				{
					StringBuilder sb = _sb;
					int num = c;
					sb.Append("\\u" + num.ToString("x4"));
				}
				else
				{
					_sb.Append(c);
				}
			}
			_sb.Append('"');
		}

		public Jw Obj()
		{
			Pre();
			_sb.Append('{');
			_need.Push(item: false);
			return this;
		}

		public Jw EndObj()
		{
			_need.Pop();
			_sb.Append('}');
			return this;
		}

		public Jw Arr()
		{
			Pre();
			_sb.Append('[');
			_need.Push(item: false);
			return this;
		}

		public Jw EndArr()
		{
			_need.Pop();
			_sb.Append(']');
			return this;
		}

		public Jw Key(string k)
		{
			Pre();
			Str(k);
			_sb.Append(':');
			_afterKey = true;
			return this;
		}

		private Jw Raw(string raw)
		{
			Pre();
			_sb.Append(raw);
			return this;
		}

		public Jw RawVal(string json)
		{
			return Raw(json);
		}

		public Jw S(string v)
		{
			if (v == null)
			{
				return Raw("null");
			}
			Pre();
			Str(v);
			return this;
		}

		public Jw I(int? v)
		{
			return Raw(v.HasValue ? v.Value.ToString(IC) : "null");
		}

		public Jw F(float? v)
		{
			return Raw((!v.HasValue || float.IsNaN(v.Value) || float.IsInfinity(v.Value)) ? "null" : v.Value.ToString("R", IC));
		}

		public Jw B(bool? v)
		{
			return Raw((!v.HasValue) ? "null" : (v.Value ? "true" : "false"));
		}

		public Jw KS(string k, string v)
		{
			return Key(k).S(v);
		}

		public Jw KI(string k, int? v)
		{
			return Key(k).I(v);
		}

		public Jw KF(string k, float? v)
		{
			return Key(k).F(v);
		}

		public Jw KB(string k, bool? v)
		{
			return Key(k).B(v);
		}

		public Jw KObj(string k)
		{
			return Key(k).Obj();
		}

		public Jw KArr(string k)
		{
			return Key(k).Arr();
		}
	}

	private static readonly CultureInfo IC = CultureInfo.InvariantCulture;

	private static readonly HashSet<string> Warned = new HashSet<string>();

	private static Type _lllLM;

	private static Type _lllEL;

	private static Type _lllEDF;

	private static Type _lllPC;

	private static Type _lllTag;

	private static MethodInfo _getExt;

	private static Type _wrWM;

	private static Type _wrW;

	private static Type _bcmMgr;

	private static Type _bcmNet;

	private static Type _bcmWeather;

	private static MethodInfo _dawnItems;

	private static MethodInfo _dawnEnemies;

	private static readonly Dictionary<Object, object> FlowToEdf = new Dictionary<Object, object>();

	private static void Warn(string key, Exception e)
	{
		if (Warned.Add(key))
		{
			Plugin.Log.LogWarning((object)("ScrapDump: " + key + ": " + ((e == null) ? "not found" : (e.GetType().Name + " " + e.Message))));
		}
	}

	private static void Resolve()
	{
		_lllLM = AccessTools.TypeByName("LethalLevelLoader.LevelManager");
		_lllEL = AccessTools.TypeByName("LethalLevelLoader.ExtendedLevel");
		_lllEDF = AccessTools.TypeByName("LethalLevelLoader.ExtendedDungeonFlow");
		_lllPC = AccessTools.TypeByName("LethalLevelLoader.PatchedContent");
		_lllTag = AccessTools.TypeByName("LethalLevelLoader.ContentTag");
		_getExt = ((_lllLM == null) ? null : AccessTools.Method(_lllLM, "GetExtendedLevel", new Type[1] { typeof(SelectableLevel) }, (Type[])null));
		if (_getExt == null)
		{
			Warn("LLL LevelManager.GetExtendedLevel", null);
		}
		_wrWM = AccessTools.TypeByName("WeatherRegistry.WeatherManager");
		_wrW = AccessTools.TypeByName("WeatherRegistry.Weather");
		_bcmMgr = AccessTools.TypeByName("BrutalCompanyMinus.Minus.Manager");
		_bcmNet = AccessTools.TypeByName("BrutalCompanyMinus.Net");
		_bcmWeather = AccessTools.TypeByName("BrutalCompanyMinus.Minus.Weather");
		_dawnItems = AccessTools.Method(AccessTools.TypeByName("Dawn.ItemRegistrationHandler"), "UpdateItemWeightsOnLevel", new Type[1] { typeof(SelectableLevel) }, (Type[])null);
		_dawnEnemies = AccessTools.Method(AccessTools.TypeByName("Dawn.EnemyRegistrationHandler"), "UpdateEnemyWeightsOnLevel", new Type[1] { typeof(SelectableLevel) }, (Type[])null);
		if (_dawnItems == null)
		{
			Warn("Dawn ItemRegistrationHandler.UpdateItemWeightsOnLevel", null);
		}
	}

	private static object Prop(object o, string name)
	{
		if (o == null)
		{
			return null;
		}
		Type type = (o as Type) ?? o.GetType();
		object obj = ((o is Type) ? null : o);
		PropertyInfo propertyInfo = AccessTools.Property(type, name);
		if (propertyInfo != null)
		{
			return propertyInfo.GetValue(obj, null);
		}
		FieldInfo fieldInfo = AccessTools.Field(type, name);
		if (fieldInfo != null)
		{
			return fieldInfo.GetValue(obj);
		}
		throw new MissingMemberException(type.FullName, name);
	}

	private static T TryGet<T>(Func<T> f, string warnKey, T fallback = default(T))
	{
		try
		{
			return f();
		}
		catch (Exception e)
		{
			Warn(warnKey, e);
			return fallback;
		}
	}

	public static void Write()
	{
		Resolve();
		StartOfRound sor = StartOfRound.Instance;
		RoundManager instance = RoundManager.Instance;
		Jw jw = new Jw();
		jw.Obj();
		jw.KS("tool", "OddsDump ScrapDump 1.2.0");
		jw.KS("utc", DateTime.UtcNow.ToString("o", IC));
		jw.KI("days", TryGet(() => sor.gameStats.daysSpent, "daysSpent", 0));
		jw.KI("quotasMet", TryGet(() => TimeOfDay.Instance.timesFulfilledQuota, "quotas", 0));
		WriteGlobals(jw, instance);
		WriteFormula(jw);
		Dictionary<int, (string, float, float)> wr = WriteWeathers(jw);
		WriteItems(jw, sor);
		WriteInteriors(jw, instance);
		WriteLevels(jw, sor, wr);
		jw.EndObj();
		string text = Path.Combine(Paths.BepInExRootPath, "ScrapDump.json");
		string text2 = jw.ToString();
		File.WriteAllText(text, text2);
		Plugin.Log.LogInfo((object)("ScrapDump written: " + text + " (" + text2.Length + " chars, " + sor.levels.Length + " levels)"));
	}

	private static void WriteGlobals(Jw w, RoundManager rm)
	{
		w.KObj("globals");
		w.KF("scrapValueMultiplier", TryGet((Func<float?>)(() => rm.scrapValueMultiplier), "rm.scrapValueMultiplier", (float?)null));
		w.KF("scrapAmountMultiplier", TryGet((Func<float?>)(() => rm.scrapAmountMultiplier), "rm.scrapAmountMultiplier", (float?)null));
		w.KI("increasedScrapSpawnRateIndex", TryGet((Func<int?>)(() => rm.increasedScrapSpawnRateIndex), "rm.increasedScrapSpawnRateIndex", (int?)null));
		w.KF("mapSizeMultiplier", TryGet((Func<float?>)(() => rm.mapSizeMultiplier), "rm.mapSizeMultiplier", (float?)null));
		w.KB("weatherRegistryScrapMultipliers", TryGet(delegate
		{
			Type type = AccessTools.TypeByName("WeatherRegistry.Settings");
			return (!(type == null)) ? new bool?((bool)Prop(type, "ScrapMultipliers")) : ((bool?)null);
		}, "WeatherRegistry.Settings.ScrapMultipliers"));
		w.KObj("brutalCompanyMinus");
		if (_bcmMgr == null)
		{
			w.KB("present", false);
		}
		else
		{
			w.KB("present", true);
			string[] array = new string[8] { "difficulty", "daysDifficulty", "scrapInShipDifficulty", "moonGradeDifficulty", "weatherDifficulty", "quotaDifficulty", "scrapValueMultiplier", "scrapAmountMultiplier" };
			foreach (string text in array)
			{
				string name = text;
				w.KF(name, TryGet((Func<float?>)(() => (float)AccessTools.Field(_bcmMgr, name).GetValue(null)), "BCM Manager." + name, (float?)null));
			}
			w.KArr("weatherMultipliers");
			try
			{
				object obj = Prop(_bcmNet, "Instance");
				IEnumerable enumerable = ((obj == null) ? null : (AccessTools.Field(_bcmNet, "currentWeatherMultipliers").GetValue(obj) as IEnumerable));
				if (enumerable != null)
				{
					FieldInfo fieldInfo = AccessTools.Field(_bcmWeather, "weatherType");
					FieldInfo fieldInfo2 = AccessTools.Field(_bcmWeather, "scrapValueMultiplier");
					FieldInfo fieldInfo3 = AccessTools.Field(_bcmWeather, "scrapAmountMultiplier");
					foreach (object item in enumerable)
					{
						w.Obj();
						w.KS("weather", fieldInfo.GetValue(item).ToString());
						w.KF("value", (float)fieldInfo2.GetValue(item));
						w.KF("amount", (float)fieldInfo3.GetValue(item));
						w.EndObj();
					}
				}
			}
			catch (Exception e)
			{
				Warn("BCM weather multipliers", e);
			}
			w.EndArr();
		}
		w.EndObj();
		w.EndObj();
	}

	private static void WriteFormula(Jw w)
	{
		w.KObj("formula");
		w.KS("count", "n = (int)(Random.Next(minScrap, maxScrap) * scrapAmountMultiplier)  [Next max is exclusive]; +6 if currentDungeonType == 4 (vanilla Mineshaft)");
		w.KS("pick", "each item: weighted by spawnableScrap rarity; one entry (increasedScrapSpawnRateIndex) can be forced to weight 100");
		w.KS("value", "each item: (int)(Random.Next(item.minValue, item.maxValue) * scrapValueMultiplier)  [Next max exclusive]");
		w.KS("singleItemDay", "21/500 chance: every item is the same entry (prefers rarity>=5 and one-handed; 60% abort if no such entry in 2 tries); value then clamped 50..170");
		w.KS("minTotalScrapValue", "only logged in v81; not used to top up or cap the total. maxTotalScrapValue is not read at all");
		w.KS("scrapValueMultiplier", "vanilla scene value 0.4. WeatherRegistry prefix (priority 0) sets it to weather.ScrapValueMultiplier * 0.4 and scrapAmountMultiplier = weather.ScrapAmountMultiplier, overwriting anything set before");
		w.KS("brutalCompanyMinus", "after spawn (waitForScrapToSpawnToSync) BCM multiplies every value by Manager.scrapValueMultiplier and adds (Manager.scrapAmountMultiplier - 1) * n extra items. Manager multipliers = BCM weather table * level properties * difficulty scale * events");
		w.KS("unplaced", "items whose spawnPositionTypes have no matching RandomScrapSpawn in the interior are skipped, so the real count can be lower");
		w.EndObj();
	}

	private static Dictionary<int, (string name, float val, float amt)> WriteWeathers(Jw w)
	{
		Dictionary<int, (string, float, float)> dictionary = new Dictionary<int, (string, float, float)>();
		w.KArr("weathers");
		try
		{
			if (_wrWM != null && _wrW != null)
			{
				IEnumerable enumerable = Prop(_wrWM, "Weathers") as IEnumerable;
				foreach (object o in enumerable ?? new object[0])
				{
					string text = TryGet(() => (string)Prop(o, "Name"), "WR Weather.Name", "?");
					int num = TryGet(() => Convert.ToInt32(Prop(o, "VanillaWeatherType")), "WR Weather.VanillaWeatherType", -99);
					float num2 = TryGet(() => (float)Prop(o, "ScrapValueMultiplier"), "WR Weather.ScrapValueMultiplier", float.NaN);
					float num3 = TryGet(() => (float)Prop(o, "ScrapAmountMultiplier"), "WR Weather.ScrapAmountMultiplier", float.NaN);
					string v = TryGet(() => Prop(o, "Type")?.ToString(), "WR Weather.Type");
					w.Obj().KS("name", text).KI("type", num)
						.KS("kind", v)
						.KF("scrapValueMultiplier", num2)
						.KF("scrapAmountMultiplier", num3)
						.EndObj();
					if (num != -99 && !dictionary.ContainsKey(num))
					{
						dictionary[num] = (text, num2, num3);
					}
				}
			}
			else
			{
				Warn("WeatherRegistry types", null);
			}
		}
		catch (Exception e)
		{
			Warn("WeatherRegistry weathers", e);
		}
		w.EndArr();
		return dictionary;
	}

	private static void WriteItems(Jw w, StartOfRound sor)
	{
		w.KArr("items");
		try
		{
			foreach (Item items in sor.allItemsList.itemsList)
			{
				if (!((Object)(object)items == (Object)null))
				{
					w.Obj().KS("name", items.itemName).KS("asset", ((Object)items).name)
						.KB("isScrap", items.isScrap)
						.KI("minValue", items.minValue)
						.KI("maxValue", items.maxValue)
						.KB("twoHanded", items.twoHanded)
						.KF("weight", items.weight)
						.KI("creditsWorth", items.creditsWorth)
						.EndObj();
				}
			}
		}
		catch (Exception e)
		{
			Warn("allItemsList", e);
		}
		w.EndArr();
	}

	private static void WriteInteriors(Jw w, RoundManager rm)
	{
		FlowToEdf.Clear();
		try
		{
			IEnumerable enumerable = Prop(_lllPC, "ExtendedDungeonFlows") as IEnumerable;
			foreach (object item in enumerable ?? new object[0])
			{
				object obj = Prop(item, "DungeonFlow");
				Object val = (Object)((obj is Object) ? obj : null);
				if (val != (Object)null && !FlowToEdf.ContainsKey(val))
				{
					FlowToEdf[val] = item;
				}
			}
		}
		catch (Exception e)
		{
			Warn("LLL ExtendedDungeonFlows", e);
		}
		w.KArr("interiors");
		try
		{
			for (int i = 0; i < rm.dungeonFlowTypes.Length; i++)
			{
				IndoorMapType val2 = rm.dungeonFlowTypes[i];
				w.Obj().KI("index", i);
				DungeonFlow flow = val2?.dungeonFlow;
				object edf = null;
				if ((Object)(object)flow != (Object)null)
				{
					FlowToEdf.TryGetValue((Object)(object)flow, out edf);
				}
				w.KS("flow", ((Object)(object)flow != (Object)null) ? ((Object)flow).name : null);
				object v;
				if (edf == null)
				{
					DungeonFlow obj2 = flow;
					v = ((obj2 != null) ? ((Object)obj2).name : null);
				}
				else
				{
					v = TryGet(() => (string)Prop(edf, "DungeonName"), "LLL DungeonName");
				}
				w.KS("name", (string)v);
				w.KF("mapTileSize", val2?.MapTileSize);
				w.KI("lengthMin", TryGet((Func<int?>)(() => flow.Length.Min), "flow.Length", (int?)null));
				w.KI("lengthMax", TryGet((Func<int?>)(() => flow.Length.Max), "flow.Length", (int?)null));
				if (edf != null)
				{
					w.KB("dynamicSizeRestriction", TryGet((Func<bool?>)(() => (bool)Prop(edf, "IsDynamicDungeonSizeRestrictionEnabled")), "LLL IsDynamicDungeonSizeRestrictionEnabled", (bool?)null));
					w.KF("dynamicSizeMin", TryGet((Func<float?>)(() => (float)Prop(edf, "DynamicDungeonSizeMin")), "LLL DynamicDungeonSizeMin", (float?)null));
					w.KF("dynamicSizeMax", TryGet((Func<float?>)(() => (float)Prop(edf, "DynamicDungeonSizeMax")), "LLL DynamicDungeonSizeMax", (float?)null));
					w.KF("dynamicSizeLerp", TryGet((Func<float?>)(() => (float)Prop(edf, "DynamicDungeonSizeLerpRate")), "LLL DynamicDungeonSizeLerpRate", (float?)null));
					w.KS("mod", TryGet(() => (string)Prop(edf, "ModName"), "LLL edf ModName"));
				}
				w.EndObj();
			}
		}
		catch (Exception e2)
		{
			Warn("interiors", e2);
		}
		w.EndArr();
		w.KArr("dawnDungeons");
		try
		{
			Type type = AccessTools.TypeByName("Dawn.LethalContent");
			object obj3 = ((type == null) ? null : AccessTools.Field(type, "Dungeons")?.GetValue(null));
			IEnumerable enumerable = ((obj3 == null) ? null : (Prop(obj3, "Values") as IEnumerable));
			foreach (object di in enumerable ?? new object[0])
			{
				Object val3 = TryGet(delegate
				{
					object obj4 = Prop(di, "DungeonFlow");
					return (Object)((obj4 is Object) ? obj4 : null);
				}, "Dawn DungeonFlow");
				object edf2 = null;
				if (val3 != (Object)null)
				{
					FlowToEdf.TryGetValue(val3, out edf2);
				}
				w.Obj();
				w.KS("key", TryGet(() => Prop(di, "Key")?.ToString(), "Dawn Key"));
				w.KS("flow", (val3 != (Object)null) ? val3.name : null);
				w.KS("name", (edf2 != null) ? TryGet(() => (string)Prop(edf2, "DungeonName"), "LLL DungeonName") : null);
				w.KI("extraScrapGeneration", TryGet((Func<int?>)(() => (int)Prop(di, "ExtraScrapGeneration")), "Dawn ExtraScrapGeneration", (int?)null));
				w.KF("mapTileSize", TryGet((Func<float?>)(() => (float)Prop(di, "MapTileSize")), "Dawn MapTileSize", (float?)null));
				object clamp = TryGet(() => Prop(di, "DungeonClampRange"), "Dawn DungeonClampRange");
				w.KF("clampMin", (clamp == null) ? ((float?)null) : TryGet((Func<float?>)(() => Convert.ToSingle(Prop(clamp, "Min"))), "Dawn BoundedRange.Min", (float?)null));
				w.KF("clampMax", (clamp == null) ? ((float?)null) : TryGet((Func<float?>)(() => Convert.ToSingle(Prop(clamp, "Max"))), "Dawn BoundedRange.Max", (float?)null));
				w.EndObj();
			}
		}
		catch (Exception e3)
		{
			Warn("Dawn dungeons", e3);
		}
		w.EndArr();
	}

	private static int? TerminalRoutePrice(SelectableLevel lvl)
	{
		Terminal val = Object.FindObjectOfType<Terminal>();
		if ((Object)(object)val == (Object)null || (Object)(object)val.terminalNodes == (Object)null)
		{
			return null;
		}
		TerminalKeyword val2 = ((IEnumerable<TerminalKeyword>)val.terminalNodes.allKeywords).FirstOrDefault((Func<TerminalKeyword, bool>)((TerminalKeyword k) => (Object)(object)k != (Object)null && k.word == "route"));
		if (val2?.compatibleNouns == null)
		{
			return null;
		}
		CompatibleNoun[] compatibleNouns = val2.compatibleNouns;
		for (int num = 0; num < compatibleNouns.Length; num++)
		{
			TerminalNode val3 = compatibleNouns[num]?.result;
			if ((Object)(object)val3 == (Object)null)
			{
				continue;
			}
			if (val3.terminalOptions != null)
			{
				CompatibleNoun[] terminalOptions = val3.terminalOptions;
				foreach (CompatibleNoun val4 in terminalOptions)
				{
					if ((Object)(object)val4?.result != (Object)null && val4.result.buyRerouteToMoon == lvl.levelID)
					{
						return val4.result.itemCost;
					}
				}
			}
			if (val3.displayPlanetInfo == lvl.levelID)
			{
				return val3.itemCost;
			}
		}
		return null;
	}

	private static void Enemies(Jw w, string key, List<SpawnableEnemyWithRarity> list)
	{
		w.KArr(key);
		if (list != null)
		{
			foreach (SpawnableEnemyWithRarity item in list)
			{
				if (item != null)
				{
					EnemyType enemyType = item.enemyType;
					w.Obj().KS("name", ((Object)(object)enemyType != (Object)null) ? enemyType.enemyName : null).KI("rarity", item.rarity)
						.KF("power", ((Object)(object)enemyType != (Object)null) ? new float?(enemyType.PowerLevel) : ((float?)null))
						.KI("maxCount", ((Object)(object)enemyType != (Object)null) ? new int?(enemyType.MaxCount) : ((int?)null))
						.EndObj();
				}
			}
		}
		w.EndArr();
	}

	private static void WriteLevels(Jw w, StartOfRound sor, Dictionary<int, (string name, float val, float amt)> wr)
	{
		//IL_0a40: Unknown result type (might be due to invalid IL or missing references)
		//IL_0a42: Unknown result type (might be due to invalid IL or missing references)
		//IL_0863: 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_074a: Expected I4, but got Unknown
		//IL_07ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_083d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0842: Unknown result type (might be due to invalid IL or missing references)
		//IL_0750: Unknown result type (might be due to invalid IL or missing references)
		//IL_075a: Expected I4, but got Unknown
		//IL_08b9: Unknown result type (might be due to invalid IL or missing references)
		w.KArr("levels");
		for (int i = 0; i < sor.levels.Length; i++)
		{
			SelectableLevel lvl = sor.levels[i];
			if ((Object)(object)lvl == (Object)null)
			{
				continue;
			}
			Jw jw = w;
			w = new Jw();
			try
			{
				w.Obj();
				w.KI("index", i).KS("name", lvl.PlanetName).KI("levelID", lvl.levelID)
					.KS("scene", lvl.sceneName)
					.KS("riskLevel", lvl.riskLevel)
					.KB("spawnEnemiesAndScrap", lvl.spawnEnemiesAndScrap)
					.KB("planetHasTime", lvl.planetHasTime)
					.KF("daySpeedMultiplier", lvl.DaySpeedMultiplier);
				object ext = null;
				try
				{
					ext = _getExt?.Invoke(null, new object[1] { lvl });
				}
				catch (Exception e)
				{
					Warn("GetExtendedLevel", e);
				}
				w.KB("hasExtendedLevel", ext != null);
				int? num = ((ext == null) ? ((int?)null) : TryGet((Func<int?>)(() => (int)Prop(ext, "RoutePrice")), "LLL RoutePrice", (int?)null));
				int? num2 = TryGet(() => TerminalRoutePrice(lvl), "terminal route price");
				w.KI("routePrice", num ?? num2).KS("routePriceSource", num.HasValue ? "LLL ExtendedLevel.RoutePrice" : (num2.HasValue ? "terminal route confirm node itemCost" : null)).KI("routePriceTerminal", num2);
				if (ext != null)
				{
					w.KS("numberlessName", TryGet(() => (string)Prop(ext, "NumberlessPlanetName"), "LLL NumberlessPlanetName"));
					w.KS("mod", TryGet(() => (string)Prop(ext, "ModName"), "LLL ModName"));
					w.KS("author", TryGet(() => (string)Prop(ext, "AuthorName"), "LLL AuthorName"));
					w.KS("contentType", TryGet(() => Prop(ext, "ContentType")?.ToString(), "LLL ContentType"));
					w.KI("calculatedDifficultyRating", TryGet((Func<int?>)(() => (int)Prop(ext, "CalculatedDifficultyRating")), "LLL CalculatedDifficultyRating", (int?)null));
					w.KB("isHidden", TryGet((Func<bool?>)(() => (bool)Prop(ext, "IsRouteHidden")), "LLL IsRouteHidden", (bool?)null));
					w.KB("isLocked", TryGet((Func<bool?>)(() => (bool)Prop(ext, "IsRouteLocked")), "LLL IsRouteLocked", (bool?)null));
					w.KB("isRemoved", TryGet((Func<bool?>)(() => (bool)Prop(ext, "IsRouteRemoved")), "LLL IsRouteRemoved", (bool?)null));
					w.KArr("tags");
					try
					{
						IEnumerable enumerable = Prop(ext, "ContentTags") as IEnumerable;
						foreach (object item in enumerable ?? new object[0])
						{
							if (item != null)
							{
								w.S((string)AccessTools.Field(_lllTag, "contentTagName").GetValue(item));
							}
						}
					}
					catch (Exception e2)
					{
						Warn("LLL ContentTags", e2);
					}
					w.EndArr();
					w.KArr("levelTags");
					try
					{
						IEnumerable<string> enumerable2 = AccessTools.Field(_lllEL, "levelTags")?.GetValue(ext) as IEnumerable<string>;
						foreach (string item2 in enumerable2 ?? new string[0])
						{
							w.S(item2);
						}
					}
					catch (Exception e3)
					{
						Warn("LLL levelTags", e3);
					}
					w.EndArr();
				}
				else
				{
					w.KS("numberlessName", TryGet(() => new string(lvl.PlanetName.SkipWhile((char c) => char.IsDigit(c) || c == ' ').ToArray()), "numberless"));
				}
				w.KI("minScrap", lvl.minScrap).KI("maxScrap", lvl.maxScrap).KI("minTotalScrapValue", lvl.minTotalScrapValue)
					.KI("maxTotalScrapValue", lvl.maxTotalScrapValue)
					.KF("factorySizeMultiplier", lvl.factorySizeMultiplier);
				w.KI("maxEnemyPowerCount", lvl.maxEnemyPowerCount).KI("maxOutsideEnemyPowerCount", lvl.maxOutsideEnemyPowerCount).KI("maxDaytimeEnemyPowerCount", lvl.maxDaytimeEnemyPowerCount);
				Enemies(w, "enemies", lvl.Enemies);
				Enemies(w, "outsideEnemies", lvl.OutsideEnemies);
				Enemies(w, "daytimeEnemies", lvl.DaytimeEnemies);
				w.KArr("spawnableScrap");
				if (lvl.spawnableScrap != null)
				{
					foreach (SpawnableItemWithRarity item3 in lvl.spawnableScrap)
					{
						if (item3 != null)
						{
							Item spawnableItem = item3.spawnableItem;
							w.Obj().KS("name", ((Object)(object)spawnableItem != (Object)null) ? spawnableItem.itemName : null).KI("rarity", item3.rarity);
							if ((Object)(object)spawnableItem != (Object)null)
							{
								w.KI("minValue", spawnableItem.minValue).KI("maxValue", spawnableItem.maxValue).KB("isScrap", spawnableItem.isScrap)
									.KB("twoHanded", spawnableItem.twoHanded)
									.KF("weight", spawnableItem.weight);
							}
							w.EndObj();
						}
					}
				}
				w.EndArr();
				w.KArr("randomWeathers");
				List<int> list = new List<int> { -1 };
				if (lvl.randomWeathers != null)
				{
					RandomWeatherWithVariables[] randomWeathers = lvl.randomWeathers;
					foreach (RandomWeatherWithVariables val in randomWeathers)
					{
						if (val != null && !list.Contains((int)val.weatherType))
						{
							list.Add((int)val.weatherType);
						}
					}
				}
				foreach (int item4 in list)
				{
					w.Obj().KI("type", item4);
					if (wr.TryGetValue(item4, out (string, float, float) value))
					{
						w.KS("name", value.Item1).KF("scrapValueMultiplier", value.Item2).KF("scrapAmountMultiplier", value.Item3);
					}
					else
					{
						w.KS("name", ((object)(LevelWeatherType)item4/*cast due to .constrained prefix*/).ToString());
					}
					w.EndObj();
				}
				w.EndArr();
				w.KObj("byWeather");
				LevelWeatherType currentWeather = lvl.currentWeather;
				foreach (int item5 in list)
				{
					try
					{
						lvl.currentWeather = (LevelWeatherType)item5;
						_dawnItems?.Invoke(null, new object[1] { lvl });
						_dawnEnemies?.Invoke(null, new object[1] { lvl });
						Jw jw2 = w;
						string? k;
						if (wr.TryGetValue(item5, out (string, float, float) value2))
						{
							(k, _, _) = value2;
						}
						else
						{
							k = ((object)(LevelWeatherType)item5/*cast due to .constrained prefix*/).ToString();
						}
						jw2.KObj(k);
						w.KArr("scrap");
						foreach (SpawnableItemWithRarity item6 in lvl.spawnableScrap ?? new List<SpawnableItemWithRarity>())
						{
							if (item6 != null)
							{
								w.Arr().S(((Object)(object)item6.spawnableItem != (Object)null) ? item6.spawnableItem.itemName : null).I(item6.rarity)
									.EndArr();
							}
						}
						w.EndArr();
						w.KArr("enemies");
						foreach (SpawnableEnemyWithRarity item7 in lvl.Enemies ?? new List<SpawnableEnemyWithRarity>())
						{
							if (item7 != null)
							{
								w.Arr().S(((Object)(object)item7.enemyType != (Object)null) ? item7.enemyType.enemyName : null).I(item7.rarity)
									.EndArr();
							}
						}
						w.EndArr();
						w.EndObj();
					}
					catch (Exception e4)
					{
						Warn("Dawn weights " + lvl.PlanetName + " " + item5, e4);
					}
					finally
					{
						lvl.currentWeather = currentWeather;
					}
				}
				try
				{
					_dawnItems?.Invoke(null, new object[1] { lvl });
					_dawnEnemies?.Invoke(null, new object[1] { lvl });
				}
				catch (Exception e5)
				{
					Warn("Dawn restore", e5);
				}
				w.EndObj();
				w.KArr("dungeonFlowTypes");
				if (lvl.dungeonFlowTypes != null)
				{
					IntWithRarity[] dungeonFlowTypes = lvl.dungeonFlowTypes;
					foreach (IntWithRarity val2 in dungeonFlowTypes)
					{
						w.Obj().KI("id", val2.id).KI("rarity", val2.rarity)
							.EndObj();
					}
				}
				w.EndArr();
				w.EndObj();
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("ScrapDump level " + lvl.PlanetName + ": " + ex));
				w = null;
			}
			string text = w?.ToString();
			w = jw;
			if (text != null)
			{
				w.RawVal(text);
			}
			else
			{
				w.Obj().KI("index", i).KS("name", lvl.PlanetName)
					.KS("error", "see LogOutput.log")
					.EndObj();
			}
		}
		w.EndArr();
	}
}