Decompiled source of Pre Roll Shop v1.5.6

Mods/WoodStudios.PreRollShop.dll

Decompiled 31 minutes 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.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using FybCommon;
using HarmonyLib;
using HoldTheFort;
using Il2CppFishNet;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppScheduleOne;
using Il2CppScheduleOne.AvatarFramework;
using Il2CppScheduleOne.AvatarFramework.Animation;
using Il2CppScheduleOne.Building;
using Il2CppScheduleOne.Core.Items.Framework;
using Il2CppScheduleOne.DevUtilities;
using Il2CppScheduleOne.Economy;
using Il2CppScheduleOne.Effects.MixMaps;
using Il2CppScheduleOne.Employees;
using Il2CppScheduleOne.EntityFramework;
using Il2CppScheduleOne.Equipping;
using Il2CppScheduleOne.Instancing;
using Il2CppScheduleOne.ItemFramework;
using Il2CppScheduleOne.Map;
using Il2CppScheduleOne.Messaging;
using Il2CppScheduleOne.NPCs;
using Il2CppScheduleOne.NPCs.Relation;
using Il2CppScheduleOne.Networking;
using Il2CppScheduleOne.ObjectScripts;
using Il2CppScheduleOne.Packaging;
using Il2CppScheduleOne.Persistence;
using Il2CppScheduleOne.PlayerScripts;
using Il2CppScheduleOne.Product;
using Il2CppScheduleOne.Product.Packaging;
using Il2CppScheduleOne.Property;
using Il2CppScheduleOne.Quests;
using Il2CppScheduleOne.Storage;
using Il2CppScheduleOne.Tiles;
using Il2CppScheduleOne.UI;
using Il2CppScheduleOne.UI.Phone;
using Il2CppScheduleOne.UI.Phone.ProductManagerApp;
using Il2CppScheduleOne.UI.Relations;
using Il2CppScheduleOne.UI.Shop;
using Il2CppScheduleOne.Weather;
using Il2CppSteamworks;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Reflection;
using MelonLoader;
using MelonLoader.Preferences;
using MelonLoader.Utils;
using Microsoft.CodeAnalysis;
using PreRollShopMod;
using S1API.DeadDrops;
using S1API.Economy;
using S1API.Entities;
using S1API.Entities.Customer;
using S1API.Entities.Relation;
using S1API.Entities.Schedule;
using S1API.Entities.Supplier;
using S1API.GameTime;
using S1API.Items;
using S1API.Items.Storable;
using S1API.Lifecycle;
using S1API.Map;
using S1API.Messaging;
using S1API.Money;
using S1API.Products;
using S1API.Properties;
using S1API.Properties.Interfaces;
using S1API.Rendering;
using S1API.Shops;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
using UnityEngine.UI;
using WoodKit;
using WoodLabs;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(PreRollCore), "Pre-Roll Shop", "1.5.6", "Wood Studios", null)]
[assembly: MelonGame("TVGS", "Schedule I")]
[assembly: MelonOptionalDependencies(new string[] { "HoldTheFort" })]
[assembly: AssemblyCompany("WoodStudios.PreRollShop")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0")]
[assembly: AssemblyProduct("WoodStudios.PreRollShop")]
[assembly: AssemblyTitle("WoodStudios.PreRollShop")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.5.6.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[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 WoodLabs
{
	internal static class AnyListed
	{
		private struct Option
		{
			public Tuple<ProductDefinition, int> E;

			public float Appeal;
		}

		private const string HarmonyId = "WoodStudios.AnyListed";

		private const float MinAppeal = 0.05f;

		private static MelonPreferences_Entry<bool> _on;

		private static bool _mine;

		private static IntPtr _choosing;

		private static int _choosingFrame = -1;

		private static int _prefixed;

		private static int _replaced;

		private static readonly List<Option> Sorted = new List<Option>();

		private static readonly List<Option> Ok = new List<Option>();

		private static readonly Dictionary<IntPtr, float> Appeals = new Dictionary<IntPtr, float>();

		private static bool _warned;

		private static float _surveyAt = -1f;

		private static int _surveyStep;

		private static readonly List<string> Listed = new List<string>();

		public static bool On => _on?.Value ?? true;

		public static void Init(string by)
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Expected O, but got Unknown
			//IL_00ae: Expected O, but got Unknown
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Expected O, but got Unknown
			try
			{
				MelonPreferences_Category val = MelonPreferences.GetCategory("WoodStudiosOrders") ?? MelonPreferences.CreateCategory("WoodStudiosOrders", "Wood Studios: customer orders");
				_on = val.GetEntry<bool>("OrderAnyListed") ?? val.CreateEntry<bool>("OrderAnyListed", true, "Customers order anything you list", "On: customers can ask for any product you list that they'd buy, still mostly what they like best. Off: the game's own way (each customer only ever orders one of their top 4).", false, false, (ValueValidator)null, (string)null);
				if (!Harmony.HasAnyPatches("WoodStudios.AnyListed"))
				{
					Harmony val2 = new Harmony("WoodStudios.AnyListed");
					val2.Patch((MethodBase)AccessTools.Method(typeof(Customer), "TryGenerateContract", (Type[])null, (Type[])null), new HarmonyMethod(typeof(AnyListed), "ContractPrefix", (Type[])null), new HarmonyMethod(typeof(AnyListed), "ContractPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					val2.Patch((MethodBase)AccessTools.Method(typeof(Customer), "GetOrderableProductsWithQuantities", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(AnyListed), "OrderablePostfix", (Type[])null)
					{
						priority = 0
					}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					_mine = true;
					Instance log = Kit.Log;
					if (log != null)
					{
						log.Msg("Customers order anything you list (set up by " + by + (On ? "" : "; switched off in [WoodStudiosOrders]") + ").");
					}
				}
			}
			catch (Exception ex)
			{
				Instance log2 = Kit.Log;
				if (log2 != null)
				{
					log2.Warning("Customer orders: " + ex.Message);
				}
			}
		}

		private static void ContractPrefix(Customer __instance)
		{
			_prefixed++;
			_choosing = (((Object)(object)__instance != (Object)null) ? ((Il2CppObjectBase)__instance).Pointer : IntPtr.Zero);
			_choosingFrame = Time.frameCount;
		}

		private static void ContractPostfix()
		{
			_choosing = IntPtr.Zero;
		}

		private static float AppealOf(Customer c, ProductDefinition p)
		{
			if (Appeals.TryGetValue(((Il2CppObjectBase)p).Pointer, out var value))
			{
				return value;
			}
			float marketValue = p.MarketValue;
			float price = p.Price;
			float num = ((marketValue > 0f) ? Mathf.Clamp01(price / marketValue * 0.5f) : ((price > 0f) ? 1f : 0f));
			value = c.GetProductEnjoyment(p) + 1f - 2f * num;
			Appeals[((Il2CppObjectBase)p).Pointer] = value;
			return value;
		}

		private static void OrderablePostfix(Customer __instance, ref List<Tuple<ProductDefinition, int>> __result)
		{
			try
			{
				if ((Object)(object)__instance == (Object)null || _choosing == IntPtr.Zero || ((Il2CppObjectBase)__instance).Pointer != _choosing || Time.frameCount != _choosingFrame)
				{
					return;
				}
				_choosing = IntPtr.Zero;
				if (On && __result != null && __result.Count > 4)
				{
					int rank;
					int buyable;
					Tuple<ProductDefinition, int> val = Choose(__instance, __result, out rank, out buyable);
					if (val != null)
					{
						List<Tuple<ProductDefinition, int>> val2 = new List<Tuple<ProductDefinition, int>>();
						val2.Add(val);
						__result = val2;
						_replaced++;
					}
				}
			}
			catch (Exception ex)
			{
				if (!_warned)
				{
					_warned = true;
					Instance log = Kit.Log;
					if (log != null)
					{
						log.Warning("Customer orders: " + ex.Message + "; using the game's own choice.");
					}
				}
			}
		}

		private static Tuple<ProductDefinition, int> Choose(Customer c, List<Tuple<ProductDefinition, int>> list, out int rank, out int buyable)
		{
			rank = -1;
			buyable = 0;
			Sorted.Clear();
			Appeals.Clear();
			for (int i = 0; i < list.Count; i++)
			{
				Tuple<ProductDefinition, int> val = list[i];
				if (!((Object)(object)val?.Item1 == (Object)null))
				{
					Option item = new Option
					{
						E = val,
						Appeal = AppealOf(c, val.Item1)
					};
					int num = Sorted.Count;
					while (num > 0 && Sorted[num - 1].Appeal < item.Appeal)
					{
						num--;
					}
					Sorted.Insert(num, item);
				}
			}
			if (Sorted.Count <= 4)
			{
				return null;
			}
			float num2 = Random.Range(0f, 1f);
			int index = ((!(num2 <= 0.5f)) ? ((num2 <= 0.75f) ? 1 : ((num2 <= 0.875f) ? 2 : 3)) : 0);
			if (Sorted[index].Appeal < 0.05f)
			{
				return Sorted[index].E;
			}
			Ok.Clear();
			foreach (Option item2 in Sorted)
			{
				if (item2.Appeal >= 0.05f)
				{
					Ok.Add(item2);
				}
			}
			buyable = Ok.Count;
			float num3 = 0f;
			for (int j = 0; j < Ok.Count; j++)
			{
				num3 += 1f / (float)(j + 1);
			}
			float num4 = Random.Range(0f, num3);
			for (int k = 0; k < Ok.Count; k++)
			{
				num4 -= 1f / (float)(k + 1);
				if (num4 <= 0f)
				{
					rank = k;
					return Ok[k].E;
				}
			}
			rank = Ok.Count - 1;
			return Ok[Ok.Count - 1].E;
		}

		public static void Loaded()
		{
			_surveyAt = Time.unscaledTime + 30f;
			_surveyStep = 0;
		}

		public static void Update()
		{
			if (!_mine || _surveyAt < 0f || Time.unscaledTime < _surveyAt || !FortifyApi.InGame)
			{
				return;
			}
			if (!FortifyApi.DevKeys)
			{
				_surveyAt = -1f;
				return;
			}
			try
			{
				ProductManager instance = NetworkSingleton<ProductManager>.Instance;
				if (_surveyStep == 0)
				{
					Listed.Clear();
					int num = ProductManager.ListedProducts?.Count ?? 0;
					List<ProductDefinition> discoveredProducts = ProductManager.DiscoveredProducts;
					int num2 = 0;
					while (discoveredProducts != null && num2 < discoveredProducts.Count && num < 12)
					{
						ProductDefinition val = discoveredProducts[num2];
						if (!((Object)(object)val == (Object)null) && !ProductManager.ListedProducts.Contains(val))
						{
							instance.SetProductListed(((BaseItemDefinition)val).ID, true);
							Listed.Add(((BaseItemDefinition)val).ID);
							num++;
						}
						num2++;
					}
					_surveyStep = 1;
					_surveyAt = Time.unscaledTime + 4f;
					return;
				}
				if (instance.TimeSinceProductListingChanged < 3.3f && _surveyStep < 30)
				{
					_surveyStep++;
					_surveyAt = Time.unscaledTime + 2f;
					return;
				}
				_surveyAt = -1f;
				List<ProductDefinition> listedProducts = ProductManager.ListedProducts;
				StringBuilder stringBuilder = new StringBuilder($"Survey: {listedProducts?.Count ?? 0} listed ({Listed.Count} listed just for this), accepting orders {ProductManager.IsAcceptingOrders}, listing changed {instance.TimeSinceProductListingChanged:0.0} ago.");
				List<Customer> unlockedCustomers = Customer.UnlockedCustomers;
				int num3 = 0;
				Customer val2 = ((unlockedCustomers != null && unlockedCustomers.Count > 0) ? unlockedCustomers[0] : null);
				if ((Object)(object)val2 != (Object)null)
				{
					float value = default(float);
					int value2 = default(int);
					ProductDefinition weightedRandomProduct = val2.GetWeightedRandomProduct((Dealer)null, ref value, ref value2);
					_choosing = ((Il2CppObjectBase)val2).Pointer;
					_choosingFrame = Time.frameCount;
					int replaced = _replaced;
					float value3 = default(float);
					int value4 = default(int);
					ProductDefinition weightedRandomProduct2 = val2.GetWeightedRandomProduct((Dealer)null, ref value3, ref value4);
					StringBuilder stringBuilder2 = stringBuilder;
					StringBuilder stringBuilder3 = stringBuilder2;
					StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(61, 7, stringBuilder2);
					handler.AppendLiteral("\n  step by step: game's pick ");
					handler.AppendFormatted((weightedRandomProduct != null) ? ((BaseItemDefinition)weightedRandomProduct).ID : null);
					handler.AppendLiteral(" (");
					handler.AppendFormatted(value, "0.00");
					handler.AppendLiteral(", ");
					handler.AppendFormatted(value2);
					handler.AppendLiteral("); ours ");
					handler.AppendFormatted((weightedRandomProduct2 != null) ? ((BaseItemDefinition)weightedRandomProduct2).ID : null);
					handler.AppendLiteral(" (");
					handler.AppendFormatted(value3, "0.00");
					handler.AppendLiteral(", ");
					handler.AppendFormatted(value4);
					handler.AppendLiteral(", list swapped ");
					handler.AppendFormatted(_replaced - replaced);
					handler.AppendLiteral(")");
					stringBuilder3.Append(ref handler);
					bool dEBUG = val2.DEBUG;
					val2.DEBUG = true;
					int prefixed = _prefixed;
					ContractInfo val3 = val2.TryGenerateContract((Dealer)null);
					val2.DEBUG = dEBUG;
					stringBuilder2 = stringBuilder;
					StringBuilder stringBuilder4 = stringBuilder2;
					handler = new StringBuilder.AppendInterpolatedStringHandler(26, 2, stringBuilder2);
					handler.AppendLiteral("; an order: ");
					object value5;
					if (val3 != null)
					{
						ProductList products = val3.Products;
						value5 = ((products != null) ? products.GetCommaSeperatedString() : null);
					}
					else
					{
						value5 = "none";
					}
					handler.AppendFormatted((string?)value5);
					handler.AppendLiteral(" (prefix ran ");
					handler.AppendFormatted(_prefixed - prefixed);
					handler.AppendLiteral(")");
					stringBuilder4.Append(ref handler);
				}
				int num4 = 0;
				while (unlockedCustomers != null && num4 < unlockedCustomers.Count && num3 < 4)
				{
					Customer val4 = unlockedCustomers[num4];
					if (!((Object)(object)val4 == (Object)null))
					{
						Dictionary<string, int> dictionary = new Dictionary<string, int>();
						int num5 = 0;
						for (int i = 0; i < 200; i++)
						{
							ContractInfo obj = val4.TryGenerateContract((Dealer)null);
							object obj2;
							if (obj == null)
							{
								obj2 = null;
							}
							else
							{
								ProductList products2 = obj.Products;
								obj2 = ((products2 != null) ? products2.entries : null);
							}
							List<Entry> val5 = (List<Entry>)obj2;
							if (val5 == null || val5.Count == 0)
							{
								num5++;
								continue;
							}
							string key = val5[0].ProductID ?? "?";
							dictionary.TryGetValue(key, out var value6);
							dictionary[key] = value6 + 1;
						}
						string value7 = "";
						try
						{
							value7 = (((Object)(object)val4.NPC != (Object)null) ? val4.NPC.FullName : "");
						}
						catch
						{
						}
						List<KeyValuePair<string, int>> list = new List<KeyValuePair<string, int>>(dictionary);
						list.Sort((KeyValuePair<string, int> x, KeyValuePair<string, int> y) => y.Value.CompareTo(x.Value));
						List<string> list2 = new List<string>();
						foreach (KeyValuePair<string, int> item in list)
						{
							list2.Add($"{item.Key} {item.Value}");
						}
						StringBuilder stringBuilder5 = stringBuilder;
						StringBuilder.AppendInterpolatedStringHandler handler2 = new StringBuilder.AppendInterpolatedStringHandler(32, 4, stringBuilder5);
						handler2.AppendLiteral("\n  ");
						handler2.AppendFormatted(value7);
						handler2.AppendLiteral(": ");
						handler2.AppendFormatted(dictionary.Count);
						handler2.AppendLiteral(" different, no order ");
						handler2.AppendFormatted(num5);
						handler2.AppendLiteral("/200: ");
						handler2.AppendFormatted(string.Join(", ", list2));
						stringBuilder5.Append(ref handler2);
						num3++;
					}
					num4++;
				}
				Instance log = Kit.Log;
				if (log != null)
				{
					log.Msg(stringBuilder.ToString());
				}
				foreach (string item2 in Listed)
				{
					instance.SetProductListed(item2, false);
				}
				Listed.Clear();
			}
			catch (Exception ex)
			{
				_surveyAt = -1f;
				Instance log2 = Kit.Log;
				if (log2 != null)
				{
					log2.Warning("Survey: " + ex.Message);
				}
			}
		}
	}
	internal static class DeadDrops
	{
		private static readonly (string Name, string Guid)[] All = new(string, string)[25]
		{
			("BehindSupermarket", "fe1782b0-64e5-4ae6-a3f9-56af509af104"),
			("BehindMotelOffice", "d66b3fd6-7b7f-4e98-b000-6d5a197f7437"),
			("SkatePark", "eda8c6a4-07be-4d8f-97f4-ddd6dfca19df"),
			("BehindGasMart", "64d10032-64a9-4cd9-8750-8048d71c5029"),
			("UnderWestBridge", "0fd91cf3-ac6a-41ce-968f-1f356f996a83"),
			("BehindCasino", "f5614c42-2c74-42d5-bee2-025e84718792"),
			("TacoTicklersExteriorWall", "79200bb6-7d39-44d9-ab22-c63f136d8cdf"),
			("TownHallFountain", "d28c727e-5175-4989-8c33-2a36c159c817"),
			("PawnShopWestWall", "fde97bca-d21a-476c-bf03-b00768a45030"),
			("BehindSlopShop", "58ec86b5-647e-456d-9266-4cd77413e9c3"),
			("Gazebo", "94eef741-d688-4380-ac64-cf190e812b10"),
			("BehindRandysBaitAndTackle", "baf08ceb-a0e7-4e4a-baa8-6b4cc992cb15"),
			("BehindBank", "e5399b56-22a5-4a2c-a254-cc81e3ab2f75"),
			("BehindCrimsonCanary", "51e8f8ec-adcb-4800-8020-55cc24f9ba40"),
			("BehindThompsonConstruction", "766389cd-b2e3-44ec-84fe-9c59eccfcdd7"),
			("CentralCanal", "4ac50ff1-ad3c-415b-aa77-c80249dfa473"),
			("NorthArcadeWall", "dd3d22f1-da56-4673-9203-640eeaf915fc"),
			("BrownApartmentBlock", "b77ed1a0-c729-41d5-b8a2-81b480ca971f"),
			("BehindMedicalPractice", "683fa5b9-c55d-4b3f-8026-6f29857d09d1"),
			("BehindLaundromat", "555e565d-2f65-4882-9edb-7167168b2e00"),
			("BehindAutoShop", "aaea12a7-ee38-47ba-aeb8-fb0d45a03957"),
			("GreyDocksBuilding", "eff8fff2-0f89-4936-aef5-c4d383ea4f50"),
			("BehindGroceryStore", "5aeef10c-955d-4fdb-9061-38f4ad7a6289"),
			("BehindFireStation", "86835825-f5f8-454d-9c74-c31e257f9cc2"),
			("BehindTopTattoo", "3ed706ba-458d-44b5-95cd-d65e4a699043")
		};

		public static string Names => string.Join(", ", All.Select(((string Name, string Guid) d) => d.Name));

		private static string Key(string s)
		{
			return new string((s ?? "").Where(char.IsLetterOrDigit).ToArray()).ToLowerInvariant();
		}

		public static string FirstFree(IEnumerable<string> taken, string after)
		{
			HashSet<string> hashSet = new HashSet<string>(taken ?? Array.Empty<string>(), StringComparer.OrdinalIgnoreCase);
			int val = Array.FindIndex(All, ((string Name, string Guid) d) => string.Equals(d.Guid, after, StringComparison.OrdinalIgnoreCase));
			for (int num = 1; num <= All.Length; num++)
			{
				(string, string) tuple = All[(Math.Max(val, 0) + num) % All.Length];
				if (!hashSet.Contains(tuple.Item2) && !string.Equals(tuple.Item2, after, StringComparison.OrdinalIgnoreCase))
				{
					return tuple.Item2;
				}
			}
			return null;
		}

		public static string Guid(string name)
		{
			string text = Key(name);
			(string, string)[] all = All;
			for (int i = 0; i < all.Length; i++)
			{
				(string, string) tuple = all[i];
				if (Key(tuple.Item1) == text || string.Equals(tuple.Item2, (name ?? "").Trim(), StringComparison.OrdinalIgnoreCase))
				{
					return tuple.Item2;
				}
			}
			return null;
		}

		public static string NameOf(string guid)
		{
			(string, string)[] all = All;
			for (int i = 0; i < all.Length; i++)
			{
				(string, string) tuple = all[i];
				if (string.Equals(tuple.Item2, guid, StringComparison.OrdinalIgnoreCase))
				{
					return tuple.Item1;
				}
			}
			return guid ?? "";
		}
	}
	internal sealed class InputSpec
	{
		public string Item;

		public string Product;

		public bool AnyOfType;

		public DrugType? Type;

		public int Qty = 1;

		public string Label;
	}
	internal sealed class ItemDef
	{
		public string Id;

		public string Name;

		public string Description;

		public string Model;

		public float Price;

		public int Stack = 20;

		public Color Color = Color.gray;

		public Color? Tint;

		public float Scale = 1f;

		public Vector3? IconTilt;

		public int IconCopies = 1;
	}
	public abstract class LabCustomerNpc : NPC
	{
		public override bool IsPhysical => true;

		public override bool IsCustomer => true;

		protected abstract int Index { get; }

		protected override void ConfigurePrefab(NPCPrefabBuilder b)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			LabDef d = LabHost.Def;
			PersonSpec p = d.Customers[Index];
			Vector3[] spots = LabNpcs.Spots(d.Region, Index);
			List<string> others = new List<string>();
			PersonSpec[] customers = d.Customers;
			foreach (PersonSpec personSpec in customers)
			{
				if (personSpec != p)
				{
					others.Add(personSpec.Id);
				}
			}
			b.WithIdentity(p.Id, p.First, p.Last).WithAppearanceDefaults((Action<AvatarDefaultsBuilder>)delegate(AvatarDefaultsBuilder av)
			{
				LabNpcs.Dress(av, p);
			}).WithSpawnPosition(spots[0])
				.WithRegion(d.Region)
				.EnsureCustomer()
				.WithCustomerDefaults((Action<CustomerDataBuilder>)delegate(CustomerDataBuilder cd)
				{
					//IL_003d: Unknown result type (might be due to invalid IL or missing references)
					//IL_005d: Unknown result type (might be due to invalid IL or missing references)
					//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
					cd.WithSpending(p.MinSpend, p.MaxSpend).WithOrdersPerWeek(p.MinOrders, p.MaxOrders).WithPreferredOrderDay(p.OrderDay)
						.WithOrderTime(p.OrderTime)
						.WithStandards(p.Standards)
						.AllowDirectApproach(true)
						.GuaranteeFirstSample(true)
						.WithMutualRelationRequirement(2f, 3.5f)
						.WithCallPoliceChance(0.08f)
						.WithDependence(0.15f, 1.1f)
						.WithAffinities((IEnumerable<ValueTuple<DrugType, float>>)new(DrugType, float)[1] { (d.Compat, p.Affinity) });
					if (p.Likes != null && p.Likes.Length != 0)
					{
						cd.WithPreferredProperties(p.Likes);
					}
				})
				.WithRelationshipDefaults((Action<NPCRelationshipDataBuilder>)delegate(NPCRelationshipDataBuilder r)
				{
					r.WithDelta(1f).SetUnlocked(false).SetUnlockType((UnlockType)1)
						.WithConnectionsById((IEnumerable<string>)others);
				})
				.WithSchedule((Action<PrefabScheduleBuilder>)delegate(PrefabScheduleBuilder plan)
				{
					//IL_000d: 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_005b: 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)
					plan.EnsureDealSignal().WalkTo(spots[0], 700, true, 1f, false, (Vector3?)null, (string)null).WalkTo(spots[1], 1130, true, 1f, false, (Vector3?)null, (string)null)
						.WalkTo(spots[2], 1600, true, 1f, false, (Vector3?)null, (string)null)
						.WalkTo(spots[0], 2030, true, 1f, false, (Vector3?)null, (string)null);
				});
		}

		protected override void OnCreated()
		{
			((NPC)this).OnCreated();
			try
			{
				((NPC)this).Appearance.Build();
			}
			catch
			{
			}
			try
			{
				((NPC)this).Schedule.Enable();
			}
			catch
			{
			}
			LabNpcs.Customers.Add(this);
		}
	}
	internal sealed class LabDef
	{
		public string Title;

		public string Folder;

		public string Prefix;

		public string Ns;

		public string Short;

		public string KindName;

		public Color Accent = new Color(0.2f, 0.75f, 0.8f);

		public DrugType Compat;

		public DrugType InputType;

		public string InputName = "weed";

		public string Template;

		public Region Region = (Region)1;

		public ProductSpec[] Products = Array.Empty<ProductSpec>();

		public ItemDef[] Items = Array.Empty<ItemDef>();

		public StationSpec[] Stations = Array.Empty<StationSpec>();

		public PackSpec Pack;

		public PersonSpec Supplier;

		public string SupplierIntro;

		public string SupplierHint;

		public string StashDrop;

		public string OldStashDrop;

		public string StashText;

		public PersonSpec[] Customers = Array.Empty<PersonSpec>();

		public float PriceMultiplier = 1f;

		public KeyCode DevKey = (KeyCode)44;

		public int DevRow;

		public Action<ProductSpec, GameObject> Decorate;

		public ProductSpec Product(string key)
		{
			ProductSpec[] products = Products;
			foreach (ProductSpec productSpec in products)
			{
				if (string.Equals(productSpec.Key, key, StringComparison.OrdinalIgnoreCase))
				{
					return productSpec;
				}
			}
			return null;
		}

		public ItemDef Item(string id)
		{
			ItemDef[] items = Items;
			foreach (ItemDef itemDef in items)
			{
				if (string.Equals(itemDef.Id, id, StringComparison.OrdinalIgnoreCase))
				{
					return itemDef;
				}
			}
			return null;
		}

		public StationSpec Station(string id)
		{
			StationSpec[] stations = Stations;
			foreach (StationSpec stationSpec in stations)
			{
				if (string.Equals(stationSpec.Id, id, StringComparison.OrdinalIgnoreCase))
				{
					return stationSpec;
				}
			}
			return null;
		}

		public bool IsOurs(string productId)
		{
			if (string.IsNullOrEmpty(productId))
			{
				return false;
			}
			ProductSpec[] products = Products;
			for (int i = 0; i < products.Length; i++)
			{
				if (string.Equals(products[i].Id, productId, StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
			}
			return false;
		}
	}
	internal static class LabHost
	{
		public static LabDef Def;

		private static MelonPreferences_Entry<float> _price;

		private static MelonPreferences_Entry<float> _time;

		private static MelonPreferences_Entry<bool> _walk;

		private static MelonPreferences_Entry<string> _stash;

		private static float _warnedAt = -100f;

		private static float _ctrlAt = -10f;

		private static bool _guiWarned;

		private static AudioClip _start;

		private static AudioClip _done;

		internal static string Rerouted;

		private static int _devOpen;

		public static float TimeMult => _time?.Value ?? 1f;

		public static bool WorkersWalk => _walk?.Value ?? true;

		public static string StashDrop
		{
			get
			{
				if (!string.IsNullOrEmpty(Rerouted))
				{
					return Rerouted;
				}
				string text = (_stash?.Value ?? "").Trim();
				if (text.Length > 0)
				{
					string text2 = DeadDrops.Guid(text);
					if (text2 != null)
					{
						return text2;
					}
					Instance log = Kit.Log;
					if (log != null)
					{
						log.Warning($"{Def.Title}: there's no dead drop called '{text}' (try one of: {DeadDrops.Names}). Using the usual one.");
					}
				}
				return Def.StashDrop;
			}
		}

		public static void Init(MelonMod mod, LabDef def, Harmony harmony)
		{
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e1: Unknown result type (might be due to invalid IL or missing references)
			Def = def;
			LabQuality.AddHeavenly(def);
			Host.Init(mod, def.Folder, def.Title, def.Prefix, null, Loaded, Unloaded);
			StashRoute.Hook(harmony);
			MelonPreferences_Category obj = MelonPreferences.GetCategory(def.Folder) ?? MelonPreferences.CreateCategory(def.Folder, def.Title);
			_price = obj.CreateEntry<float>("PriceMultiplier", 1f, "Price multiplier", "Multiplies the supplier's prices for the lab gear and supplies (1 = normal, 0 = free). Applies after a game restart.", false, false, (ValueValidator)null, (string)null);
			_time = obj.CreateEntry<float>("TimeMultiplier", 1f, "Time multiplier", "Multiplies how long each batch takes in game time (1 = normal, 0.5 = twice as fast).", false, false, (ValueValidator)null, (string)null);
			_walk = obj.CreateEntry<bool>("WorkersWalk", true, "Workers walk over", "Workers walk to a station before loading or unloading it (off: they do it from wherever they are).", false, false, (ValueValidator)null, (string)null);
			_stash = obj.CreateEntry<string>("SupplierStash", "", "Supplier stash", "Which dead drop the supplier's stash is at, if you want a different one (for example if another mod's supplier uses the same spot). Blank = " + DeadDrops.NameOf(def.StashDrop) + ". One of: " + DeadDrops.Names + ". Applies after a game restart.", false, false, (ValueValidator)null, (string)null);
			Kit.PriceMultiplier = () => _price?.Value ?? 1f;
			Kit.Stores = Array.Empty<string>();
			FortifyApi.SetNotifyIcon((def.Stations.Length != 0) ? def.Stations[0].Id : null);
			StationSpec[] stations = def.Stations;
			foreach (StationSpec stationSpec in stations)
			{
				StationSpec spec = stationSpec;
				Catalog.Add(new ItemSpec
				{
					Id = stationSpec.Id,
					Name = stationSpec.Name,
					Kind = PlaceKind.Ground,
					Price = stationSpec.Price,
					RotateStep = 90f,
					StackLimit = 2,
					NotSold = true,
					IconColor = def.Accent,
					BuildModel = () => LabModels.Station(spec),
					FitLift = 0.15f,
					Description = stationSpec.Description
				});
				Kit.Use[stationSpec.Id] = LabStations.TryUse;
			}
			ItemDef[] items = def.Items;
			foreach (ItemDef itemDef in items)
			{
				ItemDef item = itemDef;
				Catalog.Add(new ItemSpec
				{
					Id = itemDef.Id,
					Name = itemDef.Name,
					Kind = PlaceKind.Ground,
					Price = itemDef.Price,
					RotateStep = 0f,
					StackLimit = itemDef.Stack,
					NotSold = true,
					IconColor = itemDef.Color,
					BuildModel = () => LabModels.Item(item),
					Description = itemDef.Description,
					IconModel = ((itemDef.IconTilt.HasValue || itemDef.IconCopies > 1) ? ((Func<GameObject>)delegate
					{
						//IL_001a: Unknown result type (might be due to invalid IL or missing references)
						//IL_0020: Expected O, but got Unknown
						//IL_0085: Unknown result type (might be due to invalid IL or missing references)
						//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
						//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
						//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
						GameObject val = new GameObject(Kit.Prefix + "Icon_" + item.Id);
						int num2 = Math.Max(1, item.IconCopies);
						for (int i = 0; i < num2; i++)
						{
							GameObject obj2 = LabModels.Item(item);
							obj2.transform.SetParent(val.transform, false);
							obj2.transform.localPosition = new Vector3(((float)i - (float)(num2 - 1) * 0.5f) * 0.028f, 0f, (i % 2 == 0) ? 0f : 0.02f);
							obj2.transform.localRotation = Quaternion.Euler((Vector3)(((??)item.IconTilt) ?? Vector3.zero));
						}
						return val;
					}) : null)
				});
				Kit.CustomPlace[itemDef.Id] = Holding;
			}
			Kit.Created += LabStations.OnCreated;
			Kit.Removed += LabStations.OnRemoved;
			Kit.CanPickUp = (Placement.Placed p) => LabStations.CanPickUp(p);
			LabNet.Init();
			Kit.Busy = () => LabScreen.Open;
			LabProducts.Init();
			LabProducts.Patch(harmony);
			LabPack.Patch(harmony);
			LabOrderList.Patch(harmony);
			AnyListed.Init(def.Title);
			SenderFix.Init(def.Title);
			Host.Ok = true;
		}

		private static void Loaded()
		{
			LabPmPictures.Loaded();
			AnyListed.Loaded();
		}

		private static void Unloaded()
		{
			if (LabScreen.Open)
			{
				LabScreen.Close();
			}
			LabStations.Reset();
			LabWorkers.Reset();
			LabNpcs.Reset();
			LabProducts.Reset();
		}

		private static bool Holding(ItemSpec s, Camera cam, Player pl, out string hint)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			hint = null;
			if (Placement.Aim(cam, 3.5f, pl, out var best))
			{
				Placement.Placed placed = Placement.FindPlaced(((RaycastHit)(ref best)).collider);
				if (placed != null && Def.Station(placed.Spec.Id) != null && LabStations.TryUse(placed, best, out hint))
				{
					return true;
				}
			}
			string text = null;
			StationSpec[] stations = Def.Stations;
			foreach (StationSpec stationSpec in stations)
			{
				RecipeSpec[] recipes = stationSpec.Recipes;
				for (int j = 0; j < recipes.Length; j++)
				{
					InputSpec[] inputs = recipes[j].Inputs;
					for (int k = 0; k < inputs.Length; k++)
					{
						if (inputs[k].Item == s.Id)
						{
							text = stationSpec.Name;
							break;
						}
					}
				}
			}
			hint = ((text != null) ? $"{s.Name}: load it at a {text} (look at it and press {FortifyApi.UseKey})." : s.Name);
			return true;
		}

		public static void Update()
		{
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				LabPack.TryMake();
			}
			catch
			{
			}
			if (!Host.Update())
			{
				return;
			}
			try
			{
				WoodKit.Ui.Capture();
			}
			catch
			{
			}
			try
			{
				LabPack.Update();
				LabProducts.Update();
				LabPmPictures.Update();
				LabStations.Update();
				LabWorkers.Update();
				LabScreen.Update();
				LabNpcs.Update();
				AnyListed.Update();
				if (FortifyApi.KeyHeld((KeyCode)306) || FortifyApi.KeyHeld((KeyCode)305) || FortifyApi.KeyDown((KeyCode)306) || FortifyApi.KeyDown((KeyCode)305))
				{
					_ctrlAt = Time.unscaledTime;
				}
				if (FortifyApi.DevKeys && Time.unscaledTime - _ctrlAt < 0.3f && FortifyApi.KeyDown(Def.DevKey))
				{
					if (LabStations.All.Count == 0)
					{
						DevPlace();
						DevGive();
					}
					else
					{
						DevOpen();
					}
				}
				LabNpcs.DevDump();
				StashRoute.DevTestOnce();
			}
			catch (Exception ex)
			{
				if (Time.unscaledTime - _warnedAt > 30f)
				{
					_warnedAt = Time.unscaledTime;
					Instance log = Kit.Log;
					if (log != null)
					{
						log.Warning(Def.Title + ": " + ex.Message);
					}
				}
			}
		}

		public static void OnGUI()
		{
			if (!Host.Ok || !FortifyApi.InGame)
			{
				return;
			}
			try
			{
				if (LabScreen.Open)
				{
					LabScreen.Draw();
					return;
				}
			}
			catch (Exception value)
			{
				if (!_guiWarned)
				{
					_guiWarned = true;
					Instance log = Kit.Log;
					if (log != null)
					{
						log.Warning($"{Def.Title}: the station screen ({value}).");
					}
				}
			}
			Host.DrawHint();
		}

		public static void Sound(Placement.Placed p, bool start)
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!((Object)(object)p?.Go == (Object)null))
				{
					AudioSource.PlayClipAtPoint(start ? (_start ?? (_start = Tone("lab_start", new float[2] { 523f, 659f }, 0.16f))) : (_done ?? (_done = Tone("lab_done", new float[3] { 784f, 659f, 988f }, 0.14f))), p.Go.transform.position + Vector3.up, 0.45f);
				}
			}
			catch
			{
			}
		}

		public static void Done(LabStations.Station st)
		{
			Sound(st.P, start: false);
			if (st.Current != null && (st.Job == null || string.IsNullOrEmpty(st.Job.Worker)))
			{
				FortifyApi.Notify(Def.Title, $"The {st.Spec.Name} is done: {st.ReadyCount} ready to take.");
			}
		}

		private static AudioClip Tone(string name, float[] notes, float each)
		{
			int num = (int)(44100f * each);
			int num2 = num * notes.Length + 8820;
			float[] array = new float[num2];
			for (int i = 0; i < notes.Length; i++)
			{
				for (int j = 0; j < num + 8820 && i * num + j < num2; j++)
				{
					float num3 = (float)j / 44100f;
					float num4 = Mathf.Clamp01(num3 / 0.01f) * Mathf.Exp((0f - num3) * 9f);
					array[i * num + j] += (Mathf.Sin((float)Math.PI * 2f * notes[i] * num3) * 0.6f + Mathf.Sin((float)Math.PI * 4f * notes[i] * num3) * 0.15f) * num4 * 0.5f;
				}
			}
			AudioClip obj = AudioClip.Create(Kit.Prefix + name, num2, 1, 44100, false);
			obj.SetData(new Il2CppStructArray<float>(array), 0);
			((Object)obj).hideFlags = (HideFlags)32;
			return obj;
		}

		public static void DevGive()
		{
			//IL_0111: 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)
			try
			{
				StationSpec[] stations = Def.Stations;
				foreach (StationSpec stationSpec in stations)
				{
					if (stationSpec.Recipes.Length == 0)
					{
						continue;
					}
					RecipeSpec[] recipes = stationSpec.Recipes;
					foreach (RecipeSpec recipeSpec in recipes)
					{
						if (recipeSpec != stationSpec.Recipes[0] && !Array.Exists(recipeSpec.Inputs, (InputSpec x) => x.Type.HasValue))
						{
							continue;
						}
						InputSpec[] inputs = recipeSpec.Inputs;
						foreach (InputSpec inputSpec in inputs)
						{
							int n = inputSpec.Qty * 2;
							if (inputSpec.Item != null)
							{
								LabInv.Give(inputSpec.Item, -1, n);
							}
							else if (inputSpec.Product != null)
							{
								LabInv.Give(Def.Product(inputSpec.Product)?.Id, 3, n);
							}
							else if (inputSpec.AnyOfType)
							{
								LabInv.Give(LabInv.AnyOfTypeId((DrugType)(((??)inputSpec.Type) ?? Def.InputType)) ?? "ogkush", 3, n);
							}
						}
					}
				}
				PackagingDefinition item = Registry.GetItem<PackagingDefinition>("baggie");
				ProductDefinition val = ((Def.Products.Length != 0) ? Registry.GetItem<ProductDefinition>(Def.Products[Def.Products.Length - 1].Id) : null);
				if ((Object)(object)val != (Object)null)
				{
					if ((Object)(object)LabPack.Def != (Object)null)
					{
						LabInv.GiveProduct(val, 3, 2, LabPack.Def);
					}
					if ((Object)(object)item != (Object)null)
					{
						LabInv.GiveProduct(val, 3, 3, item);
					}
				}
				Instance log = Kit.Log;
				if (log != null)
				{
					log.Msg("Dev: " + Def.Title + " supplies.");
				}
			}
			catch (Exception ex)
			{
				Instance log2 = Kit.Log;
				if (log2 != null)
				{
					log2.Warning("Dev give: " + ex.Message);
				}
			}
		}

		public static void DevGiveAll()
		{
			ItemDef[] items = Def.Items;
			foreach (ItemDef itemDef in items)
			{
				LabInv.Give(itemDef.Id, -1, Math.Min(itemDef.Stack, 5));
			}
			if ((Object)(object)LabPack.Def != (Object)null)
			{
				LabInv.GiveItem((ItemDefinition)(object)LabPack.Def, 5);
			}
		}

		public static void DevPlace()
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: 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_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Player local = Player.Local;
				Camera main = Camera.main;
				if ((Object)(object)local == (Object)null || (Object)(object)main == (Object)null)
				{
					return;
				}
				Vector3 forward = ((Component)main).transform.forward;
				forward.y = 0f;
				if (((Vector3)(ref forward)).sqrMagnitude < 0.01f)
				{
					forward = Vector3.forward;
				}
				((Vector3)(ref forward)).Normalize();
				Vector3 val = Vector3.Cross(Vector3.up, forward);
				int num = Def.Stations.Length;
				RaycastHit val3 = default(RaycastHit);
				for (int i = 0; i < num; i++)
				{
					ItemSpec spec = Catalog.Get(Def.Stations[i].Id);
					Vector3 val2 = ((Component)local).transform.position + forward * (2.4f + (float)Def.DevRow * 2.3f) + val * (((float)i - (float)(num - 1) * 0.5f) * 1.9f);
					if (Physics.Raycast(val2 + Vector3.up * 2f, Vector3.down, ref val3, 6f, -1, (QueryTriggerInteraction)1))
					{
						val2 = ((RaycastHit)(ref val3)).point;
					}
					Placement.PlaceFree(spec, val2, Quaternion.LookRotation(forward, Vector3.up));
				}
				Instance log = Kit.Log;
				if (log != null)
				{
					log.Msg($"Dev: {num} {Def.Title} stations placed.");
				}
			}
			catch (Exception ex)
			{
				Instance log2 = Kit.Log;
				if (log2 != null)
				{
					log2.Warning("Dev place: " + ex.Message);
				}
			}
		}

		public static void DevOpen()
		{
			List<LabStations.Station> list = LabStations.All.FindAll((LabStations.Station st) => (Object)(object)st.P?.Go != (Object)null);
			if (list.Count != 0)
			{
				LabScreen.Show(list[_devOpen++ % list.Count]);
			}
		}
	}
	internal static class LabIcons
	{
		private static int _saved;

		private static string _lastError;

		private static string Dir => Path.Combine(MelonEnvironment.UserDataDirectory, "WoodStudios", "IconCache");

		private static string PathFor(ProductSpec p)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			string[] obj = new string[7] { p.Id, p.Model, null, null, null, null, null };
			ref Color? tint = ref p.Tint;
			obj[2] = (tint.HasValue ? ((object)tint.GetValueOrDefault()/*cast due to .constrained prefix*/).ToString() : null) ?? "-";
			obj[3] = ((object)Unsafe.As<Vector3, Vector3>(ref p.IconEuler)/*cast due to .constrained prefix*/).ToString();
			obj[4] = p.Scale.ToString();
			obj[5] = typeof(LabIcons).Assembly.GetName().Version?.ToString() ?? "0";
			obj[6] = ModelStamp(p.Model);
			string s = string.Join("|", obj);
			using SHA1 sHA = SHA1.Create();
			string text = BitConverter.ToString(sHA.ComputeHash(Encoding.UTF8.GetBytes(s))).Replace("-", "").Substring(0, 16);
			return Path.Combine(Dir, p.Id.Replace(':', '_').Replace('/', '_') + "_" + text + ".png");
		}

		private static string ModelStamp(string model)
		{
			try
			{
				using Stream stream = typeof(LabIcons).Assembly.GetManifestResourceStream(Kit.ModelResourcePrefix + model);
				return stream?.Length.ToString() ?? "0";
			}
			catch
			{
				return "0";
			}
		}

		public static Sprite Load(ProductSpec p)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				string path = PathFor(p);
				if (!File.Exists(path))
				{
					return null;
				}
				byte[] array = File.ReadAllBytes(path);
				Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
				if (!ImageConversion.LoadImage(val, new Il2CppStructArray<byte>(array)))
				{
					return null;
				}
				((Object)val).name = Kit.Prefix + "Icon_" + p.Key;
				((Object)val).hideFlags = (HideFlags)32;
				Sprite obj = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
				((Object)obj).name = ((Object)val).name;
				((Object)obj).hideFlags = (HideFlags)32;
				return obj;
			}
			catch
			{
				return null;
			}
		}

		public static void SaveWhenReady(ProductSpec[] products)
		{
			Instance log = Kit.Log;
			if (log != null)
			{
				log.Msg("Icon cache: checking " + ((products != null) ? products.Length : 0) + " product icon(s).");
			}
			MelonCoroutines.Start(SaveLoop(products));
		}

		private static IEnumerator SaveLoop(ProductSpec[] products)
		{
			for (int round = 0; round < 60; round++)
			{
				yield return (object)new WaitForSecondsRealtime(3f);
				bool flag = false;
				foreach (ProductSpec productSpec in products)
				{
					try
					{
						if (productSpec == null || productSpec.Id == null || File.Exists(PathFor(productSpec)))
						{
							continue;
						}
						ItemDefinition item = Registry.GetItem(productSpec.Id);
						ProductDefinition obj = ((item != null) ? ((Il2CppObjectBase)item).TryCast<ProductDefinition>() : null);
						Sprite val = ((obj != null) ? ((BaseItemDefinition)obj).Icon : null);
						if ((Object)(object)val == (Object)null || (Object)(object)val.texture == (Object)null || ((Object)val.texture).name != "S1API_ProductIcon_" + productSpec.Id)
						{
							flag = true;
							string[] obj2 = new string[5] { "waiting on ", productSpec.Id, " (icon '", null, null };
							object obj3;
							if (val == null)
							{
								obj3 = null;
							}
							else
							{
								Texture2D texture = val.texture;
								obj3 = ((texture != null) ? ((Object)texture).name : null);
							}
							if (obj3 == null)
							{
								obj3 = "none";
							}
							obj2[3] = (string)obj3;
							obj2[4] = "')";
							_lastError = string.Concat(obj2);
						}
						else
						{
							Save(productSpec, val);
						}
					}
					catch
					{
					}
				}
				if (!flag)
				{
					Instance log = Kit.Log;
					if (log != null)
					{
						log.Msg("Icons cached: " + _saved + " (next load skips rendering them).");
					}
					yield break;
				}
			}
			Instance log2 = Kit.Log;
			if (log2 != null)
			{
				log2.Msg("Icon cache: " + _saved + " saved, some icons never finished rendering" + ((_lastError != null) ? (" (" + _lastError + ")") : "") + ".");
			}
		}

		public static void Save(ProductSpec p, Sprite icon)
		{
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Expected O, but got Unknown
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if ((Object)(object)icon == (Object)null || (Object)(object)icon.texture == (Object)null)
				{
					return;
				}
				string path = PathFor(p);
				if (File.Exists(path))
				{
					return;
				}
				Texture2D texture = icon.texture;
				if (((Object)texture).name != "S1API_ProductIcon_" + p.Id)
				{
					return;
				}
				Texture2D val = texture;
				if (!((Texture)texture).isReadable)
				{
					RenderTexture temporary = RenderTexture.GetTemporary(((Texture)texture).width, ((Texture)texture).height, 0, (RenderTextureFormat)0);
					Graphics.Blit((Texture)(object)texture, temporary);
					RenderTexture active = RenderTexture.active;
					RenderTexture.active = temporary;
					val = new Texture2D(((Texture)texture).width, ((Texture)texture).height, (TextureFormat)4, false);
					val.ReadPixels(new Rect(0f, 0f, (float)((Texture)texture).width, (float)((Texture)texture).height), 0, 0);
					val.Apply();
					RenderTexture.active = active;
					RenderTexture.ReleaseTemporary(temporary);
				}
				Il2CppStructArray<byte> val2 = ImageConversion.EncodeToPNG(val);
				if (val2 != null && ((Il2CppArrayBase<byte>)(object)val2).Length >= 100)
				{
					Directory.CreateDirectory(Dir);
					File.WriteAllBytes(path, Il2CppArrayBase<byte>.op_Implicit((Il2CppArrayBase<byte>)(object)val2));
					_saved++;
					if ((Object)(object)val != (Object)(object)texture)
					{
						Object.Destroy((Object)(object)val);
					}
				}
			}
			catch (Exception ex)
			{
				_lastError = ex.GetType().Name + ": " + ex.Message;
			}
		}
	}
	internal static class LabInv
	{
		private static readonly Dictionary<int, Sprite> AnyIcons = new Dictionary<int, Sprite>();

		private static readonly Dictionary<int, string> TypeIds = new Dictionary<int, string>();

		public static PlayerInventory Inv
		{
			get
			{
				try
				{
					return PlayerSingleton<PlayerInventory>.Instance;
				}
				catch
				{
					return null;
				}
			}
		}

		public static string NameOf(InputSpec i)
		{
			if (i.Label != null)
			{
				return i.Label;
			}
			if (i.Item != null)
			{
				return ItemName(i.Item);
			}
			if (i.Product != null)
			{
				return LabHost.Def.Product(i.Product)?.Name ?? i.Product;
			}
			return "Product";
		}

		public static string ItemName(string id)
		{
			try
			{
				ItemDefinition item = Registry.GetItem(id);
				if ((Object)(object)item != (Object)null)
				{
					return ((BaseItemDefinition)item).Name;
				}
			}
			catch
			{
			}
			return LabHost.Def.Item(id)?.Name ?? id;
		}

		public static Sprite IconOf(InputSpec i)
		{
			//IL_006c: 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)
			try
			{
				if (i.Item != null)
				{
					ItemDefinition item = Registry.GetItem(i.Item);
					return (item != null) ? ((BaseItemDefinition)item).Icon : null;
				}
				if (i.Product != null)
				{
					ProductDefinition obj = LabProducts.Native(LabHost.Def.Product(i.Product));
					return (obj != null) ? ((BaseItemDefinition)obj).Icon : null;
				}
				return AnyOfTypeIcon((DrugType)(((??)i.Type) ?? LabHost.Def.InputType));
			}
			catch
			{
				return null;
			}
		}

		private static Sprite AnyOfTypeIcon(DrugType type)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected I4, but got Unknown
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected I4, but got Unknown
			if (AnyIcons.TryGetValue((int)type, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			Sprite val = null;
			try
			{
				string text = AnyOfTypeId(type);
				if (text != null)
				{
					ItemDefinition item = Registry.GetItem(text);
					val = ((item != null) ? ((BaseItemDefinition)item).Icon : null);
				}
			}
			catch
			{
			}
			if ((Object)(object)val != (Object)null)
			{
				AnyIcons[(int)type] = val;
			}
			return val;
		}

		public static string AnyOfTypeId(DrugType type)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected I4, but got Unknown
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected I4, but got Unknown
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Expected I4, but got Unknown
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			switch ((int)type)
			{
			case 0:
				return "ogkush";
			case 1:
				return "meth";
			case 2:
				return "cocaine";
			default:
			{
				if (TypeIds.TryGetValue((int)type, out var value))
				{
					return value;
				}
				string text = null;
				try
				{
					List<ItemDefinition> allItems = Singleton<Registry>.Instance.GetAllItems();
					int num = 0;
					while (text == null && allItems != null && num < allItems.Count)
					{
						ItemDefinition obj = allItems[num];
						ProductDefinition val = ((obj != null) ? ((Il2CppObjectBase)obj).TryCast<ProductDefinition>() : null);
						if (!((Object)(object)val == (Object)null) && !((BaseItemDefinition)val).ID.Contains(":") && val.DrugType == (EDrugType)type)
						{
							text = ((BaseItemDefinition)val).ID;
						}
						num++;
					}
				}
				catch
				{
				}
				if (text == null)
				{
					try
					{
						ProductManager instance = NetworkSingleton<ProductManager>.Instance;
						List<ProductDefinition>[] array = new List<ProductDefinition>[2]
						{
							(instance != null) ? instance.DefaultKnownProducts : null,
							(instance != null) ? instance.AllProducts : null
						};
						foreach (List<ProductDefinition> val2 in array)
						{
							int num2 = 0;
							while (text == null && val2 != null && num2 < val2.Count)
							{
								ProductDefinition val3 = val2[num2];
								if (!((Object)(object)val3 == (Object)null) && !((BaseItemDefinition)val3).ID.Contains(":") && val3.DrugType == (EDrugType)type)
								{
									text = ((BaseItemDefinition)val3).ID;
								}
								num2++;
							}
						}
					}
					catch
					{
					}
				}
				if (text != null)
				{
					TypeIds[(int)type] = text;
				}
				return text;
			}
			}
		}

		public static Sprite IconOfOutput(RecipeSpec r)
		{
			try
			{
				if (r.OutProduct != null)
				{
					ProductDefinition obj = LabProducts.Native(LabHost.Def.Product(r.OutProduct));
					return (obj != null) ? ((BaseItemDefinition)obj).Icon : null;
				}
				if (r.OutItem != null)
				{
					ItemDefinition item = Registry.GetItem(r.OutItem);
					return (item != null) ? ((BaseItemDefinition)item).Icon : null;
				}
			}
			catch
			{
			}
			return null;
		}

		internal static bool Matches(InputSpec i, ProductItemInstance p)
		{
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			if (p == null)
			{
				return false;
			}
			if (i.Product != null)
			{
				return string.Equals(((BaseItemInstance)p).ID, LabHost.Def.Product(i.Product)?.Id, StringComparison.OrdinalIgnoreCase);
			}
			if (!i.AnyOfType || LabHost.Def.IsOurs(((BaseItemInstance)p).ID) || ((BaseItemInstance)p).ID.Contains(":"))
			{
				return false;
			}
			ItemDefinition definition = ((ItemInstance)p).Definition;
			ProductDefinition val = ((definition != null) ? ((Il2CppObjectBase)definition).TryCast<ProductDefinition>() : null);
			if ((Object)(object)val != (Object)null)
			{
				return val.DrugType == (EDrugType)(((??)i.Type) ?? LabHost.Def.InputType);
			}
			return false;
		}

		internal static int Per(ProductItemInstance p)
		{
			try
			{
				PackagingDefinition appliedPackaging = p.AppliedPackaging;
				return (!((Object)(object)appliedPackaging != (Object)null)) ? 1 : Math.Max(1, appliedPackaging.Quantity);
			}
			catch
			{
				return 1;
			}
		}

		private static List<ItemSlot> Slots()
		{
			List<ItemSlot> list = new List<ItemSlot>();
			PlayerInventory inv = Inv;
			if ((Object)(object)inv == (Object)null)
			{
				return list;
			}
			try
			{
				HotbarSlot equippedSlot = inv.equippedSlot;
				if (equippedSlot != null)
				{
					list.Add((ItemSlot)(object)equippedSlot);
				}
				List<ItemSlot> allInventorySlots = inv.GetAllInventorySlots();
				int num = 0;
				while (allInventorySlots != null && num < allInventorySlots.Count)
				{
					ItemSlot val = allInventorySlots[num];
					if (val != null && (equippedSlot == null || !(((Il2CppObjectBase)val).Pointer == ((Il2CppObjectBase)equippedSlot).Pointer)))
					{
						list.Add(val);
					}
					num++;
				}
			}
			catch
			{
			}
			return list;
		}

		public static int Have(InputSpec i)
		{
			PlayerInventory inv = Inv;
			if ((Object)(object)inv == (Object)null)
			{
				return 0;
			}
			if (i.Item != null)
			{
				try
				{
					return (int)inv.GetAmountOfItem(i.Item);
				}
				catch
				{
					return 0;
				}
			}
			int num = 0;
			foreach (ItemSlot item in Slots())
			{
				ItemInstance itemInstance = item.ItemInstance;
				ProductItemInstance val = ((itemInstance != null) ? ((Il2CppObjectBase)itemInstance).TryCast<ProductItemInstance>() : null);
				if (Matches(i, val))
				{
					num += ((BaseItemInstance)val).Quantity * Per(val);
				}
			}
			return num;
		}

		public static bool Take(InputSpec i, int n, ref int qsum, ref int qn)
		{
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Expected I4, but got Unknown
			PlayerInventory inv = Inv;
			if ((Object)(object)inv == (Object)null || n <= 0)
			{
				return n <= 0;
			}
			if (i.Item != null)
			{
				if (Have(i) < n)
				{
					return false;
				}
				inv.RemoveAmountOfItem(i.Item, (uint)n);
				return true;
			}
			if (Have(i) < n)
			{
				return false;
			}
			int num = n;
			List<(ProductDefinition, int, int)> list = new List<(ProductDefinition, int, int)>();
			List<(ItemDefinition, int)> list2 = new List<(ItemDefinition, int)>();
			foreach (ItemSlot item in Slots())
			{
				if (num <= 0)
				{
					break;
				}
				ItemInstance itemInstance = item.ItemInstance;
				ProductItemInstance val = ((itemInstance != null) ? ((Il2CppObjectBase)itemInstance).TryCast<ProductItemInstance>() : null);
				if (!Matches(i, val))
				{
					continue;
				}
				int num2 = Per(val);
				int num3 = (int)((QualityItemInstance)val).Quality;
				ItemDefinition definition = ((ItemInstance)val).Definition;
				ProductDefinition val2 = ((definition != null) ? ((Il2CppObjectBase)definition).TryCast<ProductDefinition>() : null);
				PackagingDefinition appliedPackaging = val.AppliedPackaging;
				int num4 = Math.Min(((BaseItemInstance)val).Quantity, (num + num2 - 1) / num2);
				if (num4 > 0)
				{
					int num5 = num4 * num2;
					int num6 = Math.Min(num5, num);
					item.ChangeQuantity(-num4, false);
					num -= num6;
					qsum += num3 * num6;
					qn += num6;
					if (num5 > num6 && (Object)(object)val2 != (Object)null)
					{
						list.Add((val2, num3, num5 - num6));
					}
					if ((Object)(object)appliedPackaging != (Object)null)
					{
						list2.Add(((ItemDefinition)(object)appliedPackaging, num4));
					}
				}
			}
			foreach (var item2 in list)
			{
				GiveProduct(item2.Item1, item2.Item2, item2.Item3, null);
			}
			foreach (var item3 in list2)
			{
				GiveItem(item3.Item1, item3.Item2);
			}
			return num <= 0;
		}

		public static int GiveProduct(ProductDefinition def, int quality, int n, PackagingDefinition pack)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			PlayerInventory inv = Inv;
			if ((Object)(object)inv == (Object)null || (Object)(object)def == (Object)null || n <= 0)
			{
				return 0;
			}
			int val = Math.Max(1, ((BaseItemDefinition)def).StackLimit);
			int i;
			int num;
			for (i = 0; i < n; i += num)
			{
				num = Math.Min(val, n - i);
				ProductItemInstance val2 = new ProductItemInstance((ItemDefinition)(object)def, num, (EQuality)Mathf.Clamp(quality, 0, 4), pack);
				if (!inv.CanItemFitInInventory((ItemInstance)(object)val2, num))
				{
					break;
				}
				inv.AddItemToInventory((ItemInstance)(object)val2);
			}
			return i;
		}

		public static int GiveItem(ItemDefinition def, int n)
		{
			PlayerInventory inv = Inv;
			if ((Object)(object)inv == (Object)null || (Object)(object)def == (Object)null || n <= 0)
			{
				return 0;
			}
			int val = Math.Max(1, ((BaseItemDefinition)def).StackLimit);
			int i;
			int num;
			for (i = 0; i < n; i += num)
			{
				num = Math.Min(val, n - i);
				ItemInstance defaultInstance = def.GetDefaultInstance(num);
				if (defaultInstance == null || !inv.CanItemFitInInventory(defaultInstance, num))
				{
					break;
				}
				inv.AddItemToInventory(defaultInstance);
			}
			return i;
		}

		public static int Give(string id, int quality, int n)
		{
			try
			{
				ItemDefinition item = Registry.GetItem(id);
				if ((Object)(object)item == (Object)null)
				{
					return 0;
				}
				ProductDefinition val = ((Il2CppObjectBase)item).TryCast<ProductDefinition>();
				return ((Object)(object)val != (Object)null) ? GiveProduct(val, (quality < 0) ? 2 : quality, n, null) : GiveItem(item, n);
			}
			catch (Exception ex)
			{
				Instance log = Kit.Log;
				if (log != null)
				{
					log.Warning($"{LabHost.Def.Title}: giving {id} ({ex.Message}).");
				}
				return 0;
			}
		}

		public static string QualityName(int q)
		{
			return q switch
			{
				0 => "Trash", 
				1 => "Poor", 
				2 => "Standard", 
				3 => "Premium", 
				4 => "Heavenly", 
				_ => "", 
			};
		}

		public static Color QualityColor(int q)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			return (Color)(q switch
			{
				0 => new Color(0.55f, 0.45f, 0.4f), 
				1 => new Color(0.75f, 0.55f, 0.35f), 
				2 => new Color(0.75f, 0.78f, 0.82f), 
				3 => new Color(0.4f, 0.75f, 1f), 
				4 => new Color(1f, 0.82f, 0.3f), 
				_ => Color.white, 
			});
		}
	}
	internal static class LabMarks
	{
		private static float _next;

		private static float _circlesAt = -100f;

		private static float _reportAt = -1f;

		private static readonly Dictionary<IntPtr, List<RelationCircle>> Circles = new Dictionary<IntPtr, List<RelationCircle>>();

		private static readonly HashSet<IntPtr> Done = new HashSet<IntPtr>();

		private static bool _warned;

		private static int _reports;

		public static void Reset()
		{
			Circles.Clear();
			Done.Clear();
			_circlesAt = -100f;
			_next = 0f;
			_reportAt = -1f;
			_reports = 0;
		}

		public static void Update(IList<NPC> ours)
		{
			if (ours == null || ours.Count == 0 || Time.unscaledTime < _next)
			{
				return;
			}
			_next = Time.unscaledTime + 3f;
			if (_reportAt < 0f)
			{
				_reportAt = Time.unscaledTime + 25f;
			}
			try
			{
				if (Time.unscaledTime - _circlesAt > 30f)
				{
					FindCircles();
				}
				Done.Clear();
				foreach (NPC our in ours)
				{
					if ((Object)(object)our != (Object)null && Done.Add(((Il2CppObjectBase)our).Pointer))
					{
						Refresh(our, ours: true);
					}
				}
				foreach (NPC our2 in ours)
				{
					object obj;
					if ((Object)(object)our2 != (Object)null)
					{
						NPCRelationData relationData = our2.RelationData;
						obj = ((relationData != null) ? relationData.Connections : null);
					}
					else
					{
						obj = null;
					}
					List<NPC> val = (List<NPC>)obj;
					int num = 0;
					while (val != null && num < val.Count)
					{
						NPC val2 = val[num];
						if ((Object)(object)val2 != (Object)null && Done.Add(((Il2CppObjectBase)val2).Pointer))
						{
							Refresh(val2, ours: false);
						}
						num++;
					}
				}
				if (FortifyApi.DevKeys && Time.unscaledTime > _reportAt)
				{
					_reportAt = ((++_reports < 2) ? (Time.unscaledTime + 150f) : float.MaxValue);
					Report(ours);
				}
			}
			catch (Exception ex)
			{
				if (!_warned)
				{
					_warned = true;
					Instance log = Kit.Log;
					if (log != null)
					{
						log.Warning(LabHost.Def.Title + ": showing the customers on the map (" + ex.Message + ").");
					}
				}
			}
		}

		private static void Refresh(NPC n, bool ours)
		{
			try
			{
				Customer component = ((Component)n).GetComponent<Customer>();
				if ((Object)(object)component != (Object)null)
				{
					if (ours && (Object)(object)component._potentialCustomerPoI_k__BackingField == (Object)null && (Object)(object)component.NPC != (Object)null)
					{
						component.SetupPoI();
					}
					component.UpdatePotentialCustomerPoI();
				}
				if (!Circles.TryGetValue(((Il2CppObjectBase)n).Pointer, out var value))
				{
					return;
				}
				foreach (RelationCircle item in value)
				{
					if ((Object)(object)item != (Object)null)
					{
						item.UpdateBlackout();
					}
				}
			}
			catch (Exception ex)
			{
				if (!_warned)
				{
					_warned = true;
					Instance log = Kit.Log;
					if (log != null)
					{
						log.Warning($"{LabHost.Def.Title}: showing {((n != null) ? n.FirstName : null)} on the map ({ex.Message}).");
					}
				}
			}
		}

		private static void FindCircles()
		{
			_circlesAt = Time.unscaledTime;
			Circles.Clear();
			Il2CppArrayBase<RelationCircle> val = Object.FindObjectsOfType<RelationCircle>(true);
			int num = 0;
			while (val != null && num < val.Length)
			{
				RelationCircle val2 = val[num];
				NPC val3 = (((Object)(object)val2 != (Object)null) ? val2.AssignedNPC : null);
				if (!((Object)(object)val3 == (Object)null))
				{
					if (!Circles.TryGetValue(((Il2CppObjectBase)val3).Pointer, out var value))
					{
						List<RelationCircle> list = (Circles[((Il2CppObjectBase)val3).Pointer] = new List<RelationCircle>());
						value = list;
					}
					value.Add(val2);
				}
				num++;
			}
		}

		private static void Report(IList<NPC> ours)
		{
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			FindCircles();
			StringBuilder stringBuilder = new StringBuilder(LabHost.Def.Title + ": customers on the map and in Contacts:");
			foreach (NPC our in ours)
			{
				if ((Object)(object)our == (Object)null)
				{
					continue;
				}
				NPCRelationData relationData = our.RelationData;
				Customer component = ((Component)our).GetComponent<Customer>();
				NPCPoI val = (((Object)(object)component != (Object)null) ? component._potentialCustomerPoI_k__BackingField : null);
				List<RelationCircle> value2;
				int value = (Circles.TryGetValue(((Il2CppObjectBase)our).Pointer, out value2) ? value2.Count : 0);
				List<string> list = new List<string>();
				List<NPC> val2 = ((relationData != null) ? relationData.Connections : null);
				int num = 0;
				while (val2 != null && num < val2.Count)
				{
					NPC val3 = val2[num];
					if ((Object)(object)val3 != (Object)null && val3.RelationData != null && val3.RelationData.Unlocked)
					{
						list.Add(val3.FirstName);
					}
					num++;
				}
				string value3 = ((relationData == null) ? "?" : (relationData.Unlocked ? "a customer already" : ((list.Count > 0) ? ("knows " + string.Join(", ", list) + " (you know them)") : "knows nobody you know yet")));
				StringBuilder stringBuilder2 = stringBuilder;
				StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(38, 6, stringBuilder2);
				handler.AppendLiteral("\n  ");
				handler.AppendFormatted(our.FirstName);
				handler.AppendLiteral(" ");
				handler.AppendFormatted(our.LastName);
				handler.AppendLiteral(" [");
				handler.AppendFormatted<EMapRegion>(our.Region);
				handler.AppendLiteral("]: ");
				handler.AppendFormatted(value3);
				handler.AppendLiteral("; map marker ");
				handler.AppendFormatted(((Object)(object)val == (Object)null) ? "none" : (((Behaviour)val).enabled ? "SHOWN" : "hidden"));
				handler.AppendLiteral("; contact cards ");
				handler.AppendFormatted(value);
				stringBuilder2.Append(ref handler);
			}
			Instance log = Kit.Log;
			if (log != null)
			{
				log.Msg(stringBuilder.ToString());
			}
		}
	}
	internal static class LabMixing
	{
		private static string _ns;

		private static string _ownNs;

		private static EDrugType _own;

		private static EDrugType _borrowed;

		private static ProductDefinition _swapped;

		public static void Register(LabDef def, ProductKind kind)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected I4, but got Unknown
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: 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_004d: 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_00d1: 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_0111: Expected O, but got Unknown
			//IL_0138: 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)
			try
			{
				DrugType compat = def.Compat;
				ProductMixingMap val;
				switch ((int)compat)
				{
				case 0:
					val = (ProductMixingMap)0;
					break;
				case 1:
					val = (ProductMixingMap)1;
					break;
				case 2:
					val = (ProductMixingMap)2;
					break;
				case 4:
					val = (ProductMixingMap)3;
					break;
				case 3:
					val = (ProductMixingMap)1;
					Borrow(def, (EDrugType)1);
					break;
				case 5:
					val = (ProductMixingMap)2;
					Borrow(def, (EDrugType)2);
					break;
				default:
				{
					Instance log = Kit.Log;
					if (log != null)
					{
						log.Msg("Mixing isn't available for " + def.KindName + " yet (the mod API has no mixer for this drug type), so the mixing station won't take it.");
					}
					Block(def);
					return;
				}
				}
				if (ProductMixingProfiles.Get(kind) == null)
				{
					new Harmony(def.Ns + ".mixlook").Patch((MethodBase)AccessTools.Method(typeof(ProductManager), "RpcLogic___FinishAndNameMix_4237212381", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(LabMixing), "LookPostfix", (Type[])null)
					{
						priority = 0
					}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					GameLifecycle.OnLoadComplete += MixLooks.Watch;
					new ProductMixingProfileBuilder(kind).WithMixerMap(val).WithOutputFactory((Func<ProductMixingOutput, ProductMixingOutputDefinition>)((ProductMixingOutput o) => new ProductMixingOutputDefinition(string.IsNullOrWhiteSpace(o.MixName) ? ("Mixed " + def.KindName) : o.MixName, kind, Mathf.Clamp(Mathf.Round(o.SourcePrice * 1.15f), 1f, 999f)))).WithOutputFactoryCompatibility(def.Ns + ":mixing", 1)
						.Build();
				}
			}
			catch (Exception ex)
			{
				Instance log2 = Kit.Log;
				if (log2 != null)
				{
					log2.Warning("Mixing setup failed: " + ex.Message);
				}
			}
		}

		private static void Block(LabDef def)
		{
			//IL_0025: 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_005e: Expected O, but got Unknown
			try
			{
				_ns = def.Ns + ":";
				new Harmony(def.Ns + ".mixblock").Patch((MethodBase)AccessTools.Method(typeof(MixingStation), "CanStartMix", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(LabMixing), "BlockPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception ex)
			{
				Instance log = Kit.Log;
				if (log != null)
				{
					log.Warning("Mixing guard failed: " + ex.Message);
				}
			}
		}

		private static void BlockPostfix(MixingStation __instance, ref bool __result)
		{
			if (!__result || _ns == null)
			{
				return;
			}
			try
			{
				ProductDefinition product = __instance.GetProduct();
				string text = ((product != null) ? ((BaseItemDefinition)product).ID : null);
				if (text != null && text.StartsWith(_ns, StringComparison.OrdinalIgnoreCase))
				{
					__result = false;
				}
			}
			catch
			{
			}
		}

		private static void Borrow(LabDef def, EDrugType borrowed)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_0096: Expected O, but got Unknown
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Expected O, but got Unknown
			try
			{
				_ownNs = def.Ns + ":";
				_own = (EDrugType)def.Compat;
				_borrowed = borrowed;
				Harmony val = new Harmony(def.Ns + ".mixborrow");
				val.Patch((MethodBase)AccessTools.Method(typeof(ProductManager), "RpcLogic___FinishAndNameMix_4237212381", (Type[])null, (Type[])null), new HarmonyMethod(typeof(LabMixing), "MixPrefix", (Type[])null)
				{
					priority = 800
				}, new HarmonyMethod(typeof(LabMixing), "MixPostfix", (Type[])null)
				{
					priority = 0
				}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				val.Patch((MethodBase)AccessTools.Method(typeof(ProductManager), "GetMixerMap", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(LabMixing), "MapPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				GameLifecycle.OnLoadComplete += FixLoaded;
			}
			catch (Exception ex)
			{
				Instance log = Kit.Log;
				if (log != null)
				{
					log.Warning("Mixing setup failed: " + ex.Message);
				}
			}
		}

		private static bool Ours(string id)
		{
			if (id != null && _ownNs != null)
			{
				return id.StartsWith(_ownNs, StringComparison.OrdinalIgnoreCase);
			}
			return false;
		}

		private static void SetType(ProductDefinition d, EDrugType t)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			if (((d != null) ? d.DrugTypes : null) != null && d.DrugTypes.Count > 0 && d.DrugTypes[0] != null)
			{
				d.DrugTypes[0].DrugType = t;
			}
		}

		private static void MixPrefix(string productID)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			_swapped = null;
			try
			{
				if (Ours(productID))
				{
					ItemDefinition item = Registry.GetItem(productID);
					ProductDefinition val = (ProductDefinition)(object)((item is ProductDefinition) ? item : null);
					if (val != null && val.DrugType == _own)
					{
						SetType(val, _borrowed);
						_swapped = val;
					}
				}
			}
			catch
			{
			}
		}

		private static void MixPostfix(string mixID)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if ((Object)(object)_swapped != (Object)null)
				{
					SetType(_swapped, _own);
				}
				FixLoaded();
			}
			catch
			{
			}
			_swapped = null;
		}

		private static void FixLoaded()
		{
			//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_005c: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				ProductManager instance = NetworkSingleton<ProductManager>.Instance;
				if (((instance != null) ? instance.AllProducts : null) == null)
				{
					return;
				}
				Enumerator<ProductDefinition> enumerator = instance.AllProducts.GetEnumerator();
				while (enumerator.MoveNext())
				{
					ProductDefinition current = enumerator.Current;
					if ((Object)(object)current != (Object)null && Ours(((BaseItemDefinition)current).ID) && (Object)(object)current != (Object)(object)_swapped && current.DrugType == _borrowed)
					{
						SetType(current, _own);
					}
				}
			}
			catch
			{
			}
		}

		private static void MapPostfix(EDrugType type, ref MixerMap __result)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if ((Object)(object)__result == (Object)null && type == _own)
				{
					__result = NetworkSingleton<ProductManager>.Instance.GetMixerMap(_borrowed);
				}
			}
			catch
			{
			}
		}

		private static void LookPostfix(string productID, string mixID)
		{
			try
			{
				MixLooks.BindAll();
			}
			catch
			{
			}
		}
	}
	internal static class LabModels
	{
		private static readonly HashSet<int> Fixed = new HashSet<int>();

		private static readonly Dictionary<string, GameObject> Sources = new Dictionary<string, GameObject>();

		private static readonly Dictionary<string, Material> Tinted = new Dictionary<string, Material>();

		private static GameObject _sourceRoot;

		private static Transform SourceRoot
		{
			get
			{
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Expected O, but got Unknown
				//IL_003f: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)_sourceRoot == (Object)null)
				{
					_sourceRoot = new GameObject(Kit.Prefix + "Visuals");
					_sourceRoot.transform.position = new Vector3(0f, -900f, 0f);
					Object.DontDestroyOnLoad((Object)(object)_sourceRoot);
					((Object)_sourceRoot).hideFlags = (HideFlags)32;
				}
				return _sourceRoot.transform;
			}
		}

		public static GameObject Load(string name, string file, Color? tint = null)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//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_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name);
			((Object)GltfLoader.LoadEmbedded(file, val.transform)).name = "Model";
			foreach (Renderer componentsInChild in val.GetComponentsInChildren<Renderer>(true))
			{
				Il2CppReferenceArray<Material> sharedMaterials = componentsInChild.sharedMaterials;
				bool flag = false;
				for (int i = 0; i < ((Il2CppArrayBase<Material>)(object)sharedMaterials).Length; i++)
				{
					Material val2 = ((Il2CppArrayBase<Material>)(object)sharedMaterials)[i];
					if ((Object)(object)val2 == (Object)null)
					{
						continue;
					}
					if (Fixed.Add(((Object)val2).GetInstanceID()))
					{
						Color color = val2.color;
						Color val3 = (val2.color = ((Color)(ref color)).gamma);
						Color val4 = val3;
						if (val2.HasProperty("_BaseColor"))
						{
							val2.SetColor("_BaseColor", val4);
						}
						if (val2.HasProperty("_EmissionColor") && val2.IsKeywordEnabled("_EMISSION"))
						{
							val3 = val2.GetColor("_EmissionColor");
							val2.SetColor("_EmissionColor", ((Color)(ref val3)).gamma);
						}
					}
					if (tint.HasValue && ((Object)val2).name.Contains("tint"))
					{
						((Il2CppArrayBase<Material>)(object)sharedMaterials)[i] = TintOf(val2, tint.Value);
						flag = true;
					}
				}
				if (flag)
				{
					componentsInChild.sharedMaterials = sharedMaterials;
				}
			}
			return val;
		}

		private static Material TintOf(Material m, Color c)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			//IL_0055: 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_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			string key = ((Object)m).name + "|" + ColorUtility.ToHtmlStringRGB(c);
			if (Tinted.TryGetValue(key, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			Material val = new Material(m)
			{
				name = ((Object)m).name + "_" + ColorUtility.ToHtmlStringRGB(c)
			};
			val.color = c;
			if (val.HasProperty("_BaseColor"))
			{
				val.SetColor("_BaseColor", c);
			}
			if (val.HasProperty("_EmissionColor") && val.IsKeywordEnabled("_EMISSION"))
			{
				val.SetColor("_EmissionColor", c * 1.6f);
			}
			((Object)val).hideFlags = (HideFlags)32;
			Tinted[key] = val;
			return val;
		}

		public static void Box(Transform parent, Vector3 centre, Vector3 size)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(Kit.Prefix + "Collider");
			val.transform.SetParent(parent, false);
			val.transform.localPosition = centre;
			val.AddComponent<BoxCollider>().size = size;
		}

		public static GameObject Station(StationSpec s)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = Load(Kit.Prefix + s.Id, s.Model);
			Box(obj.transform, new Vector3(0f, s.Box.y * 0.5f, 0f), s.Box);
			return obj;
		}

		public static GameObject Item(ItemDef d)
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Load(Kit.Prefix + d.Id, d.Model, d.Tint);
			if (!Mathf.Approximately(d.Scale, 1f))
			{
				Transform child = val.transform.GetChild(0);
				child.localScale *= d.Scale;
			}
			return val;
		}

		public static GameObject ProductSource(ProductSpec p)
		{
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			string key = "p:" + p.Key;
			if (Sources.TryGetValue(key, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			GameObject val = Load(Kit.Prefix + "Product_" + p.Key, p.Model, p.Tint);
			try
			{
				LabHost.Def.Decorate?.Invoke(p, val);
			}
			catch (Exception ex)
			{
				Instance log = Kit.Log;
				if (log != null)
				{
					log.Warning($"{LabHost.Def.Title}: {p.Name}'s look ({ex.Message}).");
				}
			}
			val.transform.SetParent(SourceRoot, false);
			val.transform.localPosition = new Vector3((float)Sources.Count * 0.6f, 0f, 0f);
			foreach (Collider componentsInChild in val.GetComponentsInChildren<Collider>(true))
			{
				Object.Destroy((Object)(object)componentsInChild);
			}
			val.SetActive(true);
			((Object)val).hideFlags = (HideFlags)32;
			Sources[key] = val;
			return val;
		}

		public static GameObject PackSource(PackSpec p)
		{
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			string key = "k:" + p.Id;
			if (Sources.TryGetValue(key, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			GameObject val = Load(Kit.Prefix + "Pack_" + p.Id, p.Model);
			val.transform.SetParent(SourceRoot, false);
			val.transform.localPosition = new Vector3(-1f - (float)Sources.Count * 0.6f, 0f, 0f);
			foreach (Collider componentsInChild in val.GetComponentsInChildren<Collider>(true))
			{
				Object.Destroy((Object)(object)componentsInChild);
			}
			val.SetActive(true);
			((Object)val).hideFlags = (HideFlags)32;
			Sources[key] = val;
			return val;
		}

		public static Transform Find(Transform t, string name)
		{
			if ((Object)(object)t == (Object)null || string.IsNullOrEmpty(name))
			{
				return null;
			}
			if (((Object)t).name == name || ((Object)t).name.StartsWith(name + "_"))
			{
				return t;
			}
			for (int i = 0; i < t.childCount; i++)
			{
				Transform val = Find(t.GetChild(i), name);
				if ((Object)(object)val != (Object)null)
				{
					return val;
				}
			}
			return null;
		}

		public static Bounds LocalBounds(Transform root, bool includeInactive = true)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: 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_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			bool flag = false;
			Bounds result = default(Bounds);
			foreach (Renderer componentsInChild in ((Component)root).GetComponentsInChildren<Renderer>(includeInactive))
			{
				if ((Object)(object)componentsInChild == (Object)null || (Object)(object)((Il2CppObjectBase)componentsInChild).TryCast<ParticleSystemRenderer>() != (Object)null)
				{
					continue;
				}
				MeshFilter component = ((Component)componentsInChild).GetComponent<MeshFilter>();
				SkinnedMeshRenderer val = ((Il2CppObjectBase)componentsInChild).TryCast<SkinnedMeshRenderer>();
				Bounds bounds;
				if ((Object)(object)component != (Object)null && (Object)(object)component.sharedMesh != (Object)null)
				{
					bounds = component.sharedMesh.bounds;
				}
				else
				{
					if (!((Object)(object)val != (Object)null) || !((Object)(object)val.sharedMesh != (Object)null))
					{
						continue;
					}
					bounds = val.sharedMesh.bounds;
				}
				Matrix4x4 val2 = root.worldToLocalMatrix * ((Component)componentsInChild).transform.localToWorldMatrix;
				Vector3 center = ((Bounds)(ref bounds)).center;
				Vector3 extents = ((Bounds)(ref bounds)).extents;
				for (int i = 0; i < 8; i++)
				{
					Vector3 val3 = ((Matrix4x4)(ref val2)).MultiplyPoint3x4(center + new Vector3(((i & 1) == 0) ? (0f - extents.x) : extents.x, ((i & 2) == 0) ? (0f - extents.y) : extents.y, ((i & 4) == 0) ? (0f - extents.z) : extents.z));
					if (!flag)
					{
						result = new Bounds(val3, Vector3.zero);
						flag = true;
					}
					else
					{
						((Bounds)(ref result)).Encapsulate(val3);
					}
				}
			}
			return result;
		}
	}
	internal static class LabNet
	{
		public static void Init()
		{
			Placement.NetOps["load"] = HostLoad;
			Placement.NetOps["take"] = HostTake;
			Placement.NetGive = LabInv.Give;
			Kit.Reparse = LabStations.Reparse;
		}

		public static int GuestLoad(LabStations.Station st, int recipe, int n)
		{
			if (st == null || recipe < 0 || recipe >= st.Spec.Recipes.Length)
			{
				return 0;
			}
			if (st.Queue.Count > 0 && st.Recipe != recipe)
			{
				return 0;
			}
			string text = Placement.UidOf(st.P);
			if (text == null)
			{
				return 0;
			}
			RecipeSpec recipeSpec = st.Spec.Recipes[recipe];
			List<int> list = new List<int>();
			for (int i = 0; i < n; i++)
			{
				if (LabStations.CanMake(recipeSpec) < 1)
				{
					break;
				}
				int qsum = 0;
				int qn = 0;
				bool flag = true;
				InputSpec[] inputs = recipeSpec.Inputs;
				foreach (InputSpec obj in inputs)
				{
					if (!LabInv.Take(obj, obj.Qty, ref qsum, ref qn))
					{
						flag = false;
						break;
					}
				}
				if (!flag)
				{
					break;
				}
				list.Add((qn > 0) ? Mathf.Clamp(Mathf.RoundToInt((float)qsum / (float)qn) + recipeSpec.Boost, 0, 4) : recipeSpec.Quality);
			}
			if (list.Count > 0)
			{
				Placement.NetSend("load", text, recipe.ToString(CultureInfo.InvariantCulture), string.Join(",", list));
				LabHost.Sound(st.P, start: true);
			}
			return list.Count;
		}

		public static int GuestTake(LabStations.Station st)
		{
			int num = st?.ReadyCount ?? 0;
			string text = Placement.UidOf(st?.P);
			if (num > 0 && text != null)
			{
				Placement.NetSend("take", text);
			}
			return num;
		}

		private static void HostLoad(string session, string uid, string[] args)
		{
			if (args.Length < 2 || !int.TryParse(args[0], out var result))
			{
				return;
			}
			List<int> list = new List<int>();
			string[] array = args[1].Split(',');
			for (int i = 0; i < array.Length; i++)
			{
				if (int.TryParse(array[i], out var result2))
				{
					list.Add(Mathf.Clamp(result2, 0, 4));
				}
			}
			if (list.Count == 0)
			{
				return;
			}
			LabStations.Station station = Placement.FindByUid(uid)?.State as LabStations.Station;
			if (station == null || result < 0 || result >= station.Spec.Recipes.Length || (station.Queue.Count > 0 && station.Recipe != result))
			{
				Refund(session, station, result, list);
				return;
			}
			station.Recipe = result;
			if (station.Queue.Count == 0 || station.Start < 0.0)
			{
				station.Start = LabStations.Now;
			}
			station.Queue.AddRange(list);
			LabStations.Store(station);
			LabStations.Show(station);
			LabHost.Sound(station.P, start: true);
		}

		private static void Refund(string session, LabStations.Station st, int recipe, List<int> qualities)
		{
			RecipeSpec recipeSpec = ((st != null && recipe >= 0 && recipe < st.Spec.Recipes.Length) ? st.Spec.Recipes[recipe] : null);
			if (recipeSpec == null)
			{
				return;
			}
			foreach (int quality in qualities)
			{
				InputSpec[] inputs = recipeSpec.Inputs;
				foreach (InputSpec inputSpec in inputs)
				{
					if (inputSpec.Item != null)
					{
						Placement.NetGrant(session, inputSpec.Item, -1, inputSpec.Qty);
					}
					else if (inputSpec.Product != null)
					{
						string text = LabHost.Def.Product(inputSpec.Product)?.Id;
						if (text != null)
						{
							Placement.NetGrant(session, text, quality, inputSpec.Qty);
						}
					}
				}
			}
			Instance log = Kit.Log;
			if (log != null)
			{
				log.Msg("Co-op: a friend's batch didn't fit the station any more, so their ingredients went back to them.");
			}
		}

		private static void HostTake(string session, string uid, string[] args)
		{
			if (!(Placement.FindByUid(uid)?.State is LabStations.Station station) || station.Tray.Count == 0)
			{
				return;
			}
			foreach (LabStations.Ready item in station.Tray)
			{
				if (item.N > 0)
				{
					Placement.NetGrant(session, item.Id, item.Q, item.N);
				}
			}
			station.Tray.Clear();
			LabStations.Store(station);
			LabStations.Show(station);
		}
	}
	internal static class LabNpcs
	{
		internal static LabSupplierNpc SupplierNpc;

		internal static readonly List<LabCustomerNpc> Customers = new List<LabCustomerNpc>();

		private static float _introAt = -1f;

		private static float _next;

		private static bool _introDone;

		private static readonly Dictionary<Region, List<Vector3>> SpotCache = new Dictionary<Region, List<Vector3>>();

		private static readonly Dictionary<Region, Vector3[]> Known = new Dictionary<Region, Vector3[]>
		{
			[(Region)0] = (Vector3[])(object)new Vector3[9]
			{
				V(-79.2f, -3.9f, 131.8f),
				V(-47.3f, -5f, 164.3f),
				V(-25.6f, -4f, 158.6f),
				V(-22.5f, -3.9f, 145.9f),
				V(-3.5f, -4.01f, 118.9f),
				V(-30.8f, 0f, 112.7f),
				V(-55.8f, 0.1f, 104.3f),
				V(-35.2f, 0f, 84.7f),
				V(-45.1f, 0.1f, 74.2f)
			},
			[(Region)1] = (Vector3[])(object)new Vector3[9]
			{
				V(-75.2f, -2.5f, 40.5f),
				V(-136.8f, -5.3f, 19.9f),
				V(-136.8f, -3.9f, 41.5f),
				V(-110.4f, -4f, 54.9f),
				V(-62.2f, -2.5f, 41.9f),
				V(-143.4f, -3.9f, 114.3f),
				V(-142.2f, -3.3f, 106.2f),
				V(-177.3f, -3.8f, 92f),
				V(-85.1f, -5.4f, 66.7f)
			},
			[(Region)2] = (Vector3[])(object)new Vector3[7]
			{
				V(-10.1f, 0f, 88.5f),
				V(8.1f, 0.1f, 93f),
				V(46.7f, 0f, 101.5f),
				V(46f, 0.09f, 67.2f),
				V(-11.7f, 0.06f, 34.6f),
				V(0.9f, 0f, -5.3f),
				V(-32.7f, -2.4f, 16.8f)
			},
			[(Region)3] = (Vector3[])(object)new Vector3[5]
			{
				V(-73.3f, -2.4f, -49.6f),
				V(-97.3f, -2.5f, -37.2f),
				V(-54.6f, -2.4f, -85.2f),
				V(-10.4f, 0f, -115.6f),
				V(-11.3f, -4.46f, -2.3f)
			},
			[(Region)4] = (Vector3[])(object)new Vector3[7]
			{
				V(83.4f, 4f, -122.3f),
				V(80.3f, 0f, -21f),
				V(111.1f, 4f, -112.5f),
				V(19.6f, 0f, -83.4f),
				V(47.4f, 0f, -4.9f),
				V(75.7f, 4f, -77.9f),
				V(39.8f, 0f, -42.2f)
			},
			[(Region)5] = (Vector3[])(object)new Vector3[6]
			{
				V(80f, 0f, 36.6f),
				V(123.7f, 0.1f, 22.8f),
				V(108.4f, 0f, 69.5f),
				V(71.7f, 0.09f, 24.6f),
				V(81.2f, 0.09f, 67f),
				V(136.1f, 0f, 31.1f)
			}
		};

		private static bool _dumped;

		private static readonly List<NPC> _game = new List<NPC>();

		private static int _gameFor = -1;

		public static IEnumerable<string> SupplierItems()
		{
			LabDef d = LabHost.Def;
			StationSpec[] stations = d.Stations;
			StationSpec[] array = stations;
			foreach (StationSpec stationSpec in array)
			{
				yield return stationSpec.Id;
			}
			ItemDef[] items = d.Items;
			ItemDef[] array2 = items;
			foreach (ItemDef itemDef in array2)
			{
				yield return itemDef.Id;
			}
			if (d.Pack != null)
			{
				yield return d.Pack.Id;
			}
		}

		public static void Dress(AvatarDefaultsBuilder av, PersonSpec p)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: 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_00ce: 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_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: 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_0158: Unknown result type (might be due to invalid IL or missing references)
			av.Gender = p.Gender;
			av.Height = p.Height;
			av.Weight = p.Weight;
			av.SkinColor = p.Skin;
			av.LeftEyeLidColor = Color32.op_Implicit(p.Skin);
			av.RightEyeLidColor = Color32.op_Implicit(p.Skin);
			av.EyeBallTint = Color.white;
			av.PupilDilation = 0.7f;
			av.EyebrowScale = ((p.Gender > 0.5f) ? 0.85f : 1f);
			av.EyebrowThickness = ((p.Gender > 0.5f) ? 0.6f : 0.9f);
			av.HairPath = p.Hair ?? "";
			av.HairColor = p.HairCol;
			av.WithFaceLayer(p.Face, Color.black);
			av.WithBodyLayer(p.Top, p.TopCol);
			av.WithBodyLayer(p.Bottom, p.BottomCol);
			av.WithAccessoryLayer(p.Shoes, p.ShoeCol);
			if (p.Head != null)
			{
				av.WithAccessoryLayer(p.Head, p.HeadCol);
			}
			if (p.Chest != null)
			{
				av.WithAccessoryLayer(p.Chest, p.ChestCol);
			}
			if (p.Neck != null)
			{
				av.WithAccessoryLayer(p.Neck, p.NeckCol);
			}
		}

		private static Vector3 V(float x, float y, float z)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(x, y, z);
		}

		public static Vec

Mods/WoodStudios.MixLimitFix.dll

Decompiled 31 minutes ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppScheduleOne.Economy;
using Il2CppScheduleOne.NPCs;
using Il2CppScheduleOne.Product;
using Il2CppScheduleOne.Product.Packaging;
using Il2CppSystem.Collections.Generic;
using MelonLoader;
using Microsoft.CodeAnalysis;
using UnityEngine;
using WoodStudios.MixLimitFix;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(Main), "Mix Limit Fix", "1.2.0", "Wood Studios", null)]
[assembly: MelonGame("TVGS", "Schedule I")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[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 WoodStudios.MixLimitFix
{
	internal static class DealFix
	{
		private static float _sweepAt = -1f;

		private static int _added;

		private static Action<string> _log;

		public static void Apply(Harmony h, Action<string> log)
		{
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Expected O, but got Unknown
			_log = log;
			try
			{
				string[] array = new string[3] { "AdjustAffinity", "RpcLogic___AdjustAffinity_3036964899", "RpcWriter___Server_AdjustAffinity_3036964899" };
				foreach (string text in array)
				{
					MethodInfo methodInfo = AccessTools.Method(typeof(Customer), text, (Type[])null, (Type[])null);
					if (methodInfo != null)
					{
						Patches patchInfo = Harmony.GetPatchInfo((MethodBase)methodInfo);
						if (patchInfo != null && patchInfo.Prefixes?.Any((Patch p) => p.PatchMethod?.DeclaringType?.Name == "AffinityFix") == true)
						{
							log?.Invoke("Deal fix: already applied by Drug Pack.");
							return;
						}
					}
					if (methodInfo != null)
					{
						h.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(DealFix), "Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					}
				}
				log?.Invoke("Deal fix: customers accept every drug type the labs make (no more freeze after selling poppy or pill products).");
			}
			catch (Exception ex)
			{
				log?.Invoke("Deal fix couldn't start: " + ex.Message);
			}
		}

		private static void Prefix(Customer __instance, EDrugType drugType)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Ensure(__instance, drugType);
			}
			catch
			{
			}
		}

		public static bool Ensure(Customer c, EDrugType type)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			CustomerAffinityData obj = ((c != null) ? c.currentAffinityData : null);
			List<ProductTypeAffinity> val = ((obj != null) ? obj.ProductAffinities : null);
			if (val == null)
			{
				return false;
			}
			for (int i = 0; i < val.Count; i++)
			{
				ProductTypeAffinity val2 = val[i];
				if (val2 != null && val2.DrugType == type)
				{
					return false;
				}
			}
			ProductTypeAffinity val3 = new ProductTypeAffinity();
			val3.DrugType = type;
			val3.Affinity = 0f;
			val.Add(val3);
			_added++;
			return true;
		}

		public static void Update()
		{
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			if (Time.unscaledTime < _sweepAt)
			{
				return;
			}
			_sweepAt = Time.unscaledTime + 20f;
			try
			{
				Il2CppArrayBase<Customer> val = Object.FindObjectsOfType<Customer>();
				if (val == null || val.Length == 0)
				{
					return;
				}
				int added = _added;
				foreach (Customer item in val)
				{
					if ((Object)(object)item == (Object)null)
					{
						continue;
					}
					foreach (EDrugType value in Enum.GetValues(typeof(EDrugType)))
					{
						Ensure(item, value);
					}
				}
				if (_added > added)
				{
					_log?.Invoke("Deal fix: gave " + (_added - added) + " customer drug-type entries a neutral starting point.");
				}
			}
			catch
			{
			}
		}
	}
	public class Main : MelonMod
	{
		internal const int OldPayload = 65536;

		internal const int NewPayload = 2097152;

		internal const int OldCount = 256;

		internal const int NewCount = 1024;

		private static readonly (string Type, string Method, int Old, int New, int Expected)[] Targets = new(string, string, int, int, int)[5]
		{
			("S1API.Internal.Products.CustomProductManifestData", "Serialize", 65536, 2097152, 2),
			("S1API.Internal.Products.CustomProductManifestData", "TryDeserialize", 65536, 2097152, 2),
			("S1API.Internal.Products.CustomProductManifestData", "Create", 256, 1024, 1),
			("S1API.Internal.Products.CustomProductManifestData", "TryValidate", 256, 1024, 3),
			("S1API.Internal.Products.CustomProductSavePersistence", "RestoreBeforeBaseLoaders", 256, 1024, 1)
		};

		private static int _old;

		private static int _new;

		private static int _hits;

		public override void OnInitializeMelon()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Expected O, but got Unknown
			Harmony val = new Harmony("woodstudios.mixlimitfix");
			int num = 0;
			(string, string, int, int, int)[] targets = Targets;
			for (int i = 0; i < targets.Length; i++)
			{
				(string, string, int, int, int) tuple = targets[i];
				try
				{
					Type type = AccessTools.TypeByName(tuple.Item1);
					MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, tuple.Item2, (Type[])null, (Type[])null));
					if (methodInfo == null)
					{
						((MelonBase)this).LoggerInstance.Warning(tuple.Item1 + "." + tuple.Item2 + " not found; this S1API version may not need the fix.");
						continue;
					}
					Patches patchInfo = Harmony.GetPatchInfo((MethodBase)methodInfo);
					if (patchInfo != null && patchInfo.Transpilers?.Any((Patch p) => p.owner == "woodstudios.mixlimitfix") == true)
					{
						num++;
						continue;
					}
					_old = tuple.Item3;
					_new = tuple.Item4;
					val.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(Main), "Raise", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
					if (_hits != tuple.Item5)
					{
						((MelonBase)this).LoggerInstance.Warning($"{tuple.Item2}: changed {_hits} of {tuple.Item5} limits (S1API may have changed).");
					}
					_hits = 0;
					num++;
				}
				catch (Exception ex)
				{
					((MelonBase)this).LoggerInstance.Warning("Could not patch " + tuple.Item2 + ": " + ex.Message);
				}
			}
			((MelonBase)this).LoggerInstance.Msg($"Custom product limits raised ({num}/{Targets.Length}): up to {1024} products and {2048} KB.");
			if (AppDomain.CurrentDomain.GetAssemblies().Any((Assembly a) => a.GetName().Name == "WoodStudios.DrugPack"))
			{
				((MelonBase)this).LoggerInstance.Msg("Drug Pack is installed; it applies the deal and mixed-product save fixes itself.");
				return;
			}
			DealFix.Apply(val, delegate(string s)
			{
				((MelonBase)this).LoggerInstance.Msg(s);
			});
			MixSaveFix.Apply(val, delegate(string s)
			{
				((MelonBase)this).LoggerInstance.Msg(s);
			});
		}

		public override void OnUpdate()
		{
			DealFix.Update();
			SupplierFix.Update();
		}

		private static IEnumerable<CodeInstruction> Raise(IEnumerable<CodeInstruction> code)
		{
			foreach (CodeInstruction item in code)
			{
				if ((item.opcode == OpCodes.Ldc_I4 || item.opcode == OpCodes.Ldc_I4_S) && item.operand is int num && num == _old)
				{
					item.operand = _new;
					item.opcode = OpCodes.Ldc_I4;
					_hits++;
				}
				yield return item;
			}
		}
	}
	internal static class MixSaveFix
	{
		private static bool _done;

		public static void Apply(Harmony h, Action<string> log)
		{
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Expected O, but got Unknown
			if (_done)
			{
				return;
			}
			_done = true;
			try
			{
				Type type = AccessTools.TypeByName("S1API.Internal.Products.CustomProductSavePersistence");
				MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "RestoreFallback", (Type[])null, (Type[])null));
				if (methodInfo == null)
				{
					log?.Invoke("Mixed-product save fix: not needed with this S1API.");
					return;
				}
				Patches patchInfo = Harmony.GetPatchInfo((MethodBase)methodInfo);
				if (patchInfo != null && patchInfo.Transpilers?.Any((Patch p) => p.PatchMethod?.DeclaringType?.Name == "MixSaveFix") == true)
				{
					log?.Invoke("Mixed-product save fix: already applied by Drug Pack.");
					return;
				}
				h.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(MixSaveFix), "Transpile", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
				log?.Invoke("Mixed-product save fix applied: mixes of modded products now come back after reloading.");
			}
			catch (Exception ex)
			{
				log?.Invoke("Mixed-product save fix failed: " + ex.Message);
			}
		}

		private static IEnumerable<CodeInstruction> Transpile(IEnumerable<CodeInstruction> code)
		{
			foreach (CodeInstruction item in code)
			{
				if (item.opcode == OpCodes.Isinst && item.operand is Type type)
				{
					if (type == typeof(ProductDefinition))
					{
						item.opcode = OpCodes.Call;
						item.operand = AccessTools.Method(typeof(MixSaveFix), "AsProduct", (Type[])null, (Type[])null);
					}
					else if (type == typeof(PackagingDefinition))
					{
						item.opcode = OpCodes.Call;
						item.operand = AccessTools.Method(typeof(MixSaveFix), "AsPackaging", (Type[])null, (Type[])null);
					}
				}
				yield return item;
			}
		}

		public static ProductDefinition AsProduct(object o)
		{
			ProductDefinition val = (ProductDefinition)((o is ProductDefinition) ? o : null);
			if (val != null)
			{
				return val;
			}
			try
			{
				object obj = ((o is Il2CppObjectBase) ? o : null);
				return (obj != null) ? ((Il2CppObjectBase)obj).TryCast<ProductDefinition>() : null;
			}
			catch
			{
				return null;
			}
		}

		public static PackagingDefinition AsPackaging(object o)
		{
			PackagingDefinition val = (PackagingDefinition)((o is PackagingDefinition) ? o : null);
			if (val != null)
			{
				return val;
			}
			try
			{
				object obj = ((o is Il2CppObjectBase) ? o : null);
				return (obj != null) ? ((Il2CppObjectBase)obj).TryCast<PackagingDefinition>() : null;
			}
			catch
			{
				return null;
			}
		}
	}
	internal static class SupplierFix
	{
		private static readonly List<FieldInfo> Fields = new List<FieldInfo>();

		private static bool _found;

		private static float _next;

		private static void Find()
		{
			_found = true;
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				Type[] types;
				try
				{
					types = assembly.GetTypes();
				}
				catch (ReflectionTypeLoadException ex)
				{
					types = ex.Types;
				}
				catch
				{
					continue;
				}
				Type[] array = types;
				foreach (Type type in array)
				{
					if (!(type == null) && !(type.Name != "LabNpcs"))
					{
						FieldInfo field = type.GetField("SupplierNpc", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
						if (field != null && field.FieldType.Name == "LabSupplierNpc")
						{
							Fields.Add(field);
						}
					}
				}
			}
		}

		public static void Update()
		{
			if (Time.unscaledTime < _next)
			{
				return;
			}
			_next = Time.unscaledTime + 1f;
			if (!_found)
			{
				Find();
			}
			foreach (FieldInfo field in Fields)
			{
				try
				{
					object value = field.GetValue(null);
					if (value == null)
					{
						continue;
					}
					object? obj = value.GetType().GetProperty("gameObject")?.GetValue(value);
					GameObject val = (GameObject)((obj is GameObject) ? obj : null);
					if (!((Object)(object)val == (Object)null))
					{
						NPC component = val.GetComponent<NPC>();
						object obj2;
						if (component == null)
						{
							obj2 = null;
						}
						else
						{
							NPCMovement movement = component.Movement;
							obj2 = ((movement != null) ? movement._capsuleCollider : null);
						}
						CapsuleCollider val2 = (CapsuleCollider)obj2;
						if ((Object)(object)val2 != (Object)null && ((Collider)val2).enabled != component.isVisible)
						{
							((Collider)val2).enabled = component.isVisible;
						}
					}
				}
				catch
				{
				}
			}
		}
	}
}