Decompiled source of RandomValueMod v1.4.5

plugins/RandomValueMod.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Photon.Pun;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("RandomValueMod")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RandomValueMod")]
[assembly: AssemblyCopyright("Copyright ©  2026")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("94f4834c-4276-4ed1-92e7-92a919ab9c3b")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace RandomWeightAndValueMod;

[BepInPlugin("dyxc666.RandomWeightAndValueMod", "随机贵重物品的价格", "1.4.5")]
[BepInProcess("REPO.exe")]
[BepInDependency("nickklmao.repoconfig", "1.2.3")]
public class RandomValueMod : BaseUnityPlugin
{
	private readonly Harmony harmony = new Harmony("dyxc666.RandomValueMod");

	public static ConfigEntry<bool> EnableValueRandomization;

	public static ConfigEntry<float> MinValueMultiplier;

	public static ConfigEntry<float> MaxValueMultiplier;

	public static ConfigEntry<bool> ForceRefreshUI;

	public static ConfigEntry<bool> EnableVerboseLogging;

	public static ConfigEntry<string> BlacklistKeywords;

	public static ConfigEntry<string> WhitelistKeywords;

	public static ConfigEntry<bool> EnableWhitelistMode;

	public static ConfigEntry<bool> EnableBlacklistMode;

	public static ConfigEntry<bool> ExcludeHighValueItems;

	public static ConfigEntry<float> HighValueThreshold;

	public static ConfigEntry<bool> CashBagRandomizationToggle;

	public static ConfigEntry<bool> EnableNetworkSync;

	public static ConfigEntry<bool> EnableNetworkDebug;

	private static List<string> blacklistKeywordsList = new List<string>();

	private static List<string> whitelistKeywordsList = new List<string>();

	public static HashSet<int> modifiedItemIDs = new HashSet<int>();

	public static Dictionary<int, float> itemRandomizationCache = new Dictionary<int, float>();

	private static Dictionary<int, GrabEventListener> grabListeners = new Dictionary<int, GrabEventListener>();

	private static Dictionary<int, float> clientRequestedRandomizations = new Dictionary<int, float>();

	private static float networkSyncTimer = 0f;

	public static ManualLogSource StaticLogger { get; private set; }

	private void Awake()
	{
		StaticLogger = ((BaseUnityPlugin)this).Logger;
		((BaseUnityPlugin)this).Logger.LogInfo((object)"=========================================");
		((BaseUnityPlugin)this).Logger.LogInfo((object)"随机贵重物品的价格模组 v1.4.4 已加载");
		((BaseUnityPlugin)this).Logger.LogInfo((object)"作者: dyxc666");
		((BaseUnityPlugin)this).Logger.LogInfo((object)"功能: 抓取时随机化物品价格(多人游戏优化版)");
		((BaseUnityPlugin)this).Logger.LogInfo((object)"=========================================");
		CreateConfigEntries();
		BlacklistKeywords.SettingChanged += delegate
		{
			UpdateKeywordLists();
		};
		WhitelistKeywords.SettingChanged += delegate
		{
			UpdateKeywordLists();
		};
		MinValueMultiplier.SettingChanged += delegate
		{
			ValidateValueRange();
		};
		MaxValueMultiplier.SettingChanged += delegate
		{
			ValidateValueRange();
		};
		UpdateKeywordLists();
		try
		{
			ApplyHarmonyPatches();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"✅ 模组初始化成功");
			((BaseUnityPlugin)this).Logger.LogInfo((object)("\ud83d\udccb 黑名单关键词: " + string.Join(", ", blacklistKeywordsList)));
			((BaseUnityPlugin)this).Logger.LogInfo((object)("\ud83d\udccb 白名单关键词: " + string.Join(", ", whitelistKeywordsList)));
			((BaseUnityPlugin)this).Logger.LogInfo((object)"⚙\ufe0f 当前功能状态:");
			((BaseUnityPlugin)this).Logger.LogInfo((object)("   价格随机化: " + (EnableValueRandomization.Value ? "✅" : "❌")));
			((BaseUnityPlugin)this).Logger.LogInfo((object)"   随机化时机: 抓取时触发");
			((BaseUnityPlugin)this).Logger.LogInfo((object)("   现金袋保护: " + (CashBagRandomizationToggle.Value ? "❌ 已禁用" : "✅ 已启用")));
			((BaseUnityPlugin)this).Logger.LogInfo((object)("   网络同步: " + (EnableNetworkSync.Value ? "✅ 已启用" : "❌ 已禁用")));
			((BaseUnityPlugin)this).Logger.LogInfo((object)"\ud83d\udca1 提示: 配置选项可以在游戏设置菜单的Mods选项中修改");
			if (EnableNetworkSync.Value)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"\ud83c\udf10 网络同步功能已启用");
				((BaseUnityPlugin)this).Logger.LogInfo((object)"   支持主机与客户端双向同步");
				((BaseUnityPlugin)this).Logger.LogInfo((object)"   多人游戏优化: 延迟同步和重试机制");
			}
			CheckForModConflicts();
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("❌ 模组初始化失败: " + ex.Message));
			((BaseUnityPlugin)this).Logger.LogError((object)("详细错误: " + ex.StackTrace));
		}
	}

	private void Update()
	{
		networkSyncTimer += Time.deltaTime;
		if (networkSyncTimer >= 5f)
		{
			networkSyncTimer = 0f;
			CleanupExpiredRequests();
		}
	}

	private void CleanupExpiredRequests()
	{
		List<int> list = (from kvp in clientRequestedRandomizations
			where Time.realtimeSinceStartup - kvp.Value > 30f
			select kvp.Key).ToList();
		foreach (int item in list)
		{
			clientRequestedRandomizations.Remove(item);
		}
		if (list.Count > 0 && EnableNetworkDebug.Value)
		{
			StaticLogger.LogInfo((object)$"[网络清理] 清理了 {list.Count} 个过期请求");
		}
	}

	private void ApplyHarmonyPatches()
	{
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Expected O, but got Unknown
		//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f4: Expected O, but got Unknown
		try
		{
			MethodInfo methodInfo = AccessTools.Method(typeof(ValuableObject), "Awake", (Type[])null, (Type[])null);
			if (methodInfo != null)
			{
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(ValuableObjectPatch).GetMethod("Postfix_Awake")), (HarmonyMethod)null, (HarmonyMethod)null);
				((BaseUnityPlugin)this).Logger.LogInfo((object)"✅ 成功补丁 ValuableObject.Awake");
			}
			else
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"❌ 找不到 ValuableObject.Awake 方法");
			}
			string[] array = new string[3] { "GrabStarted", "GrabEnded", "GrabLink" };
			string[] array2 = array;
			foreach (string text in array2)
			{
				try
				{
					MethodInfo methodInfo2 = AccessTools.Method(typeof(PhysGrabObject), text, (Type[])null, (Type[])null);
					if (methodInfo2 != null)
					{
						harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(PhysGrabObjectPatch).GetMethod("Postfix_GrabMethod")), (HarmonyMethod)null, (HarmonyMethod)null);
						((BaseUnityPlugin)this).Logger.LogInfo((object)("✅ 成功补丁 PhysGrabObject." + text));
					}
				}
				catch (Exception ex)
				{
					((BaseUnityPlugin)this).Logger.LogDebug((object)("无法补丁 " + text + ": " + ex.Message));
				}
			}
		}
		catch (Exception ex2)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("❌ 应用Harmony补丁时出错: " + ex2.Message));
		}
	}

	private void CheckForModConflicts()
	{
		try
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)"\ud83d\udd0d 正在检查Mod兼容性...");
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				try
				{
					string fullName = assembly.FullName;
					if (fullName.Contains("Shared Upgrades") && fullName.Contains("2.1.3"))
					{
						((BaseUnityPlugin)this).Logger.LogWarning((object)"⚠\ufe0f 检测到可能冲突的Mod: Shared Upgrades 2.1.3");
						((BaseUnityPlugin)this).Logger.LogWarning((object)"  这个版本可能破坏Photon网络");
					}
				}
				catch
				{
				}
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"✅ Mod兼容性检查完成");
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("检查Mod冲突时出错: " + ex.Message));
		}
	}

	private void CreateConfigEntries()
	{
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Expected O, but got Unknown
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Expected O, but got Unknown
		//IL_0171: Unknown result type (might be due to invalid IL or missing references)
		//IL_017b: Expected O, but got Unknown
		EnableValueRandomization = ((BaseUnityPlugin)this).Config.Bind<bool>("基础设置", "随机化物品价格", true, "是否随机化贵重物品的价格");
		MinValueMultiplier = ((BaseUnityPlugin)this).Config.Bind<float>("价格设置", "最小价格倍率", 0.8f, new ConfigDescription("价格的最小倍率 (0.8 = 原价的80%)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 5f), Array.Empty<object>()));
		MaxValueMultiplier = ((BaseUnityPlugin)this).Config.Bind<float>("价格设置", "最大价格倍率", 2.5f, new ConfigDescription("价格的最大倍率 (2.5 = 原价的250%)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 10f), Array.Empty<object>()));
		EnableBlacklistMode = ((BaseUnityPlugin)this).Config.Bind<bool>("黑白名单", "启用黑名单模式", true, "启用黑名单,匹配的物品将不被随机化");
		BlacklistKeywords = ((BaseUnityPlugin)this).Config.Bind<string>("黑白名单", "黑名单关键词", "", "逗号分隔的关键词列表,匹配这些关键词的物品将不被随机化(留空表示无黑名单)");
		EnableWhitelistMode = ((BaseUnityPlugin)this).Config.Bind<bool>("黑白名单", "启用白名单模式", false, "启用白名单,只有匹配白名单的物品才会被随机化 (黑名单优先)");
		WhitelistKeywords = ((BaseUnityPlugin)this).Config.Bind<string>("黑白名单", "白名单关键词", "", "逗号分隔的关键词列表,只有匹配这些关键词的物品才会被随机化(留空表示所有物品)");
		ExcludeHighValueItems = ((BaseUnityPlugin)this).Config.Bind<bool>("特殊排除规则", "排除高价物品", false, "不随机化价格超过阈值的物品");
		HighValueThreshold = ((BaseUnityPlugin)this).Config.Bind<float>("特殊排除规则", "高价物品阈值", 50000f, new ConfigDescription("价格超过此值的物品不随机化 (如果启用排除高额物品)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1000f, 1000000f), Array.Empty<object>()));
		CashBagRandomizationToggle = ((BaseUnityPlugin)this).Config.Bind<bool>("特殊排除规则", "现金袋随机化", false, "如果为true,则现金袋也会被随机化");
		EnableNetworkSync = ((BaseUnityPlugin)this).Config.Bind<bool>("网络设置", "启用网络同步", true, "启用多人游戏网络同步 (需要所有玩家安装此模组)");
		EnableNetworkDebug = ((BaseUnityPlugin)this).Config.Bind<bool>("网络设置", "网络调试日志", false, "输出网络同步的详细日志");
		ForceRefreshUI = ((BaseUnityPlugin)this).Config.Bind<bool>("调试设置", "强制刷新UI", true, "尝试强制刷新UI显示");
		EnableVerboseLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("调试设置", "详细日志输出", false, "输出每个物品修改前后的具体数值");
	}

	private void UpdateKeywordLists()
	{
		try
		{
			if (!string.IsNullOrWhiteSpace(BlacklistKeywords.Value))
			{
				blacklistKeywordsList = (from k in BlacklistKeywords.Value.Split(new char[3] { ',', ';', '|' }, StringSplitOptions.RemoveEmptyEntries)
					select k.Trim().ToLower() into k
					where !string.IsNullOrEmpty(k)
					select k).ToList();
			}
			else
			{
				blacklistKeywordsList = new List<string>();
			}
			if (!string.IsNullOrWhiteSpace(WhitelistKeywords.Value))
			{
				whitelistKeywordsList = (from k in WhitelistKeywords.Value.Split(new char[3] { ',', ';', '|' }, StringSplitOptions.RemoveEmptyEntries)
					select k.Trim().ToLower() into k
					where !string.IsNullOrEmpty(k)
					select k).ToList();
			}
			else
			{
				whitelistKeywordsList = new List<string>();
			}
			if (EnableVerboseLogging.Value)
			{
				StaticLogger.LogInfo((object)("[RWVM] 黑名单关键词已更新: " + ((blacklistKeywordsList.Count > 0) ? string.Join(", ", blacklistKeywordsList) : "无")));
				StaticLogger.LogInfo((object)("[RWVM] 白名单关键词已更新: " + ((whitelistKeywordsList.Count > 0) ? string.Join(", ", whitelistKeywordsList) : "无")));
			}
		}
		catch (Exception ex)
		{
			StaticLogger.LogError((object)("[RWVM] 更新关键词列表时出错: " + ex.Message));
		}
	}

	private void ValidateValueRange()
	{
		if (MinValueMultiplier.Value < 0.1f)
		{
			MinValueMultiplier.Value = 0.1f;
		}
		if (MaxValueMultiplier.Value < MinValueMultiplier.Value + 0.1f)
		{
			MaxValueMultiplier.Value = MinValueMultiplier.Value + 0.1f;
		}
		if (MaxValueMultiplier.Value > 10f)
		{
			MaxValueMultiplier.Value = 10f;
		}
	}

	public static bool ShouldItemBeRandomized(GameObject obj, ValuableObject vo)
	{
		try
		{
			string itemName = ((Object)obj).name.ToLower();
			if (IsCashBag(itemName))
			{
				if (CashBagRandomizationToggle.Value)
				{
					return true;
				}
				return false;
			}
			if (CheckSpecialExclusionRules(obj, vo))
			{
				return false;
			}
			if (EnableBlacklistMode.Value && CheckBlacklist(itemName))
			{
				return false;
			}
			if (EnableWhitelistMode.Value && !CheckWhitelist(itemName))
			{
				return false;
			}
			if (!EnableValueRandomization.Value)
			{
				return false;
			}
			return true;
		}
		catch (Exception ex)
		{
			StaticLogger.LogError((object)("[RWVM] 检查物品时出错: " + ex.Message));
			return true;
		}
	}

	private static bool IsCashBag(string itemName)
	{
		return itemName.Contains("surplus");
	}

	private static bool CheckSpecialExclusionRules(GameObject obj, ValuableObject vo)
	{
		string text = ((Object)obj).name.ToLower();
		if (ExcludeHighValueItems.Value)
		{
			float itemPrice = GetItemPrice(vo);
			if (itemPrice >= HighValueThreshold.Value)
			{
				if (EnableVerboseLogging.Value)
				{
					StaticLogger.LogInfo((object)$"[RWVM] \ud83d\udc8e 排除高额物品: {((Object)obj).name} (价格: {itemPrice:F0})");
				}
				return true;
			}
		}
		return false;
	}

	private static bool CheckBlacklist(string itemName)
	{
		if (blacklistKeywordsList.Count == 0)
		{
			return false;
		}
		foreach (string blacklistKeywords in blacklistKeywordsList)
		{
			if (itemName.Contains(blacklistKeywords))
			{
				return true;
			}
		}
		return false;
	}

	private static bool CheckWhitelist(string itemName)
	{
		if (whitelistKeywordsList.Count == 0)
		{
			return true;
		}
		foreach (string whitelistKeywords in whitelistKeywordsList)
		{
			if (itemName.Contains(whitelistKeywords))
			{
				return true;
			}
		}
		return false;
	}

	private static float GetItemPrice(ValuableObject vo)
	{
		try
		{
			FieldInfo field = typeof(ValuableObject).GetField("dollarValueCurrent", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (field != null)
			{
				return (float)field.GetValue(vo);
			}
		}
		catch (Exception ex)
		{
			StaticLogger.LogError((object)("[DEBUG] 获取物品价格时出错: " + ex.Message));
		}
		return 0f;
	}

	public static float GetDeterministicRandomPrice(int instanceID, float originalPrice)
	{
		if (itemRandomizationCache.TryGetValue(instanceID, out var value))
		{
			return value;
		}
		float num = Mathf.Max(0.1f, MinValueMultiplier.Value);
		float num2 = Mathf.Max(num + 0.1f, MaxValueMultiplier.Value);
		Random random = new Random(instanceID);
		float num3 = originalPrice;
		if (originalPrice > 0f && EnableValueRandomization.Value)
		{
			float num4 = (float)(random.NextDouble() * (double)(num2 - num) + (double)num);
			num3 = originalPrice * num4;
			num3 = Mathf.Clamp(num3, 1f, 1000000f);
		}
		itemRandomizationCache[instanceID] = num3;
		return num3;
	}

	public static void ForceRandomizeItem(PhysGrabObject pgo, ValuableObject vo)
	{
		try
		{
			int instanceID = ((Object)((Component)pgo).gameObject).GetInstanceID();
			if (modifiedItemIDs.Contains(instanceID) || !ShouldItemBeRandomized(((Component)pgo).gameObject, vo))
			{
				return;
			}
			float itemPrice = ItemModifier.GetItemPrice(vo);
			if (!(itemPrice <= 0f))
			{
				float deterministicRandomPrice = GetDeterministicRandomPrice(instanceID, itemPrice);
				if (ItemModifier.ModifyItemAttributes(pgo, vo, deterministicRandomPrice))
				{
					modifiedItemIDs.Add(instanceID);
					float num = deterministicRandomPrice / itemPrice;
					string text = ((num > 1f) ? $"+{num:F1}倍" : $"{num:F1}倍");
					StaticLogger.LogInfo((object)$"[提示] 抓取时随机化: {((Object)((Component)pgo).gameObject).name} ${itemPrice:F0} → ${deterministicRandomPrice:F0} ({text})");
				}
			}
		}
		catch (Exception ex)
		{
			StaticLogger.LogError((object)("[RWVM] 监听器随机化出错: " + ex.Message));
		}
	}

	public static void RecordClientRandomizationRequest(int instanceID)
	{
		clientRequestedRandomizations[instanceID] = Time.realtimeSinceStartup;
	}

	public static bool HasClientRandomizationRequest(int instanceID)
	{
		return clientRequestedRandomizations.ContainsKey(instanceID);
	}

	public static void ClearClientRandomizationRequest(int instanceID)
	{
		if (clientRequestedRandomizations.ContainsKey(instanceID))
		{
			clientRequestedRandomizations.Remove(instanceID);
		}
	}
}
public static class ItemModifier
{
	public static bool ModifyItemAttributes(PhysGrabObject pgo, ValuableObject vo, float newPrice)
	{
		try
		{
			float itemPrice = GetItemPrice(vo);
			bool result = true;
			if (RandomValueMod.EnableValueRandomization.Value && itemPrice > 0f)
			{
				ModifyItemPrice(vo, newPrice);
				if (RandomValueMod.ForceRefreshUI.Value)
				{
					TryRefreshUIDisplay(vo);
				}
			}
			if (RandomValueMod.EnableVerboseLogging.Value)
			{
				string text = "[RWVM] " + ((Object)((Component)pgo).gameObject).name + ": ";
				if (RandomValueMod.EnableValueRandomization.Value && itemPrice > 0f)
				{
					float num = newPrice / itemPrice;
					text += $"价格 ${itemPrice:F0}→${newPrice:F0}(x{num:F2})";
					if (num > 2f)
					{
						text += " \ud83d\udcb0";
					}
					else if (num > 1.5f)
					{
						text += " \ud83d\udcc8";
					}
					else if (num < 0.9f)
					{
						text += " \ud83d\udcc9";
					}
					else if (num < 1f)
					{
						text += " \ud83d\udd3b";
					}
				}
				else if (itemPrice > 0f)
				{
					text += $"价格 ${itemPrice:F0} (保持不变)";
				}
				RandomValueMod.StaticLogger.LogInfo((object)text);
			}
			return result;
		}
		catch (Exception ex)
		{
			RandomValueMod.StaticLogger.LogError((object)("[RWVM] 修改物品属性时出错: " + ex.Message + "\n" + ex.StackTrace));
			return false;
		}
	}

	private static void ModifyItemPrice(ValuableObject vo, float newPrice)
	{
		try
		{
			FieldInfo field = typeof(ValuableObject).GetField("dollarValueCurrent", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (field != null)
			{
				field.SetValue(vo, newPrice);
			}
			FieldInfo field2 = typeof(ValuableObject).GetField("dollarValueOriginal", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (field2 != null)
			{
				field2.SetValue(vo, newPrice);
			}
		}
		catch (Exception ex)
		{
			RandomValueMod.StaticLogger.LogError((object)("[RWVM] 修改物品价格失败: " + ex.Message));
		}
	}

	private static void TryRefreshUIDisplay(ValuableObject valuableItem)
	{
		try
		{
			((Component)valuableItem).BroadcastMessage("OnValueChanged", (SendMessageOptions)1);
		}
		catch
		{
		}
	}

	public static float GetItemPrice(ValuableObject vo)
	{
		try
		{
			FieldInfo field = typeof(ValuableObject).GetField("dollarValueCurrent", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (field != null)
			{
				return (float)field.GetValue(vo);
			}
		}
		catch (Exception ex)
		{
			RandomValueMod.StaticLogger.LogError((object)("[DEBUG] 获取物品价格时出错: " + ex.Message));
		}
		return 0f;
	}
}
public static class ValuableObjectPatch
{
	[HarmonyPostfix]
	[HarmonyPatch(typeof(ValuableObject), "Awake")]
	public static void Postfix_Awake(ValuableObject __instance)
	{
		try
		{
			PhysGrabObject component = ((Component)__instance).GetComponent<PhysGrabObject>();
			if (!((Object)(object)component == (Object)null))
			{
				int instanceID = ((Object)((Component)__instance).gameObject).GetInstanceID();
				if (!RandomValueMod.modifiedItemIDs.Contains(instanceID))
				{
					GrabEventListener grabEventListener = ((Component)component).gameObject.AddComponent<GrabEventListener>();
					grabEventListener.valuableObject = __instance;
					grabEventListener.physGrabObject = component;
				}
			}
		}
		catch (Exception ex)
		{
			RandomValueMod.StaticLogger.LogError((object)("[RWVM] 在ValuableObject.Awake补丁中出错: " + ex.Message));
		}
	}
}
public static class PhysGrabObjectPatch
{
	[HarmonyPostfix]
	public static void Postfix_GrabMethod(PhysGrabObject __instance)
	{
		try
		{
			ValuableObject component = ((Component)__instance).GetComponent<ValuableObject>();
			if ((Object)(object)component == (Object)null)
			{
				return;
			}
			int instanceID = ((Object)((Component)__instance).gameObject).GetInstanceID();
			if (RandomValueMod.modifiedItemIDs.Contains(instanceID) || !RandomValueMod.ShouldItemBeRandomized(((Component)__instance).gameObject, component))
			{
				return;
			}
			float itemPrice = ItemModifier.GetItemPrice(component);
			if (itemPrice <= 0f)
			{
				return;
			}
			float deterministicRandomPrice = RandomValueMod.GetDeterministicRandomPrice(instanceID, itemPrice);
			if (RandomValueMod.EnableNetworkSync.Value && PhotonNetwork.IsConnected)
			{
				ItemRandomizationNetworkSync.EnsureNetworkComponent(((Component)__instance).gameObject);
				ItemRandomizationNetworkSync itemRandomizationNetworkSync = default(ItemRandomizationNetworkSync);
				if (((Component)__instance).TryGetComponent<ItemRandomizationNetworkSync>(ref itemRandomizationNetworkSync))
				{
					if (!PhotonNetwork.IsMasterClient)
					{
						RandomValueMod.RecordClientRandomizationRequest(instanceID);
						itemRandomizationNetworkSync.ClientRequestRandomization();
						return;
					}
					itemRandomizationNetworkSync.BroadcastRandomization(deterministicRandomPrice);
				}
			}
			if (ItemModifier.ModifyItemAttributes(__instance, component, deterministicRandomPrice))
			{
				RandomValueMod.modifiedItemIDs.Add(instanceID);
				float num = deterministicRandomPrice / itemPrice;
				string text = ((num > 1f) ? $"+{num:F1}倍" : $"{num:F1}倍");
				RandomValueMod.StaticLogger.LogInfo((object)$"[提示] 抓取时随机化: {((Object)((Component)__instance).gameObject).name} ${itemPrice:F0} → ${deterministicRandomPrice:F0} ({text})");
			}
		}
		catch (Exception)
		{
		}
	}
}
public class GrabEventListener : MonoBehaviour
{
	[CompilerGenerated]
	private sealed class <DelayedRandomization>d__8 : IEnumerator<object>, IDisposable, IEnumerator
	{
		private int <>1__state;

		private object <>2__current;

		public GrabEventListener <>4__this;

		private Exception <ex>5__1;

		object IEnumerator<object>.Current
		{
			[DebuggerHidden]
			get
			{
				return <>2__current;
			}
		}

		object IEnumerator.Current
		{
			[DebuggerHidden]
			get
			{
				return <>2__current;
			}
		}

		[DebuggerHidden]
		public <DelayedRandomization>d__8(int <>1__state)
		{
			this.<>1__state = <>1__state;
		}

		[DebuggerHidden]
		void IDisposable.Dispose()
		{
			<ex>5__1 = null;
			<>1__state = -2;
		}

		private bool MoveNext()
		{
			switch (<>1__state)
			{
			default:
				return false;
			case 0:
				<>1__state = -1;
				<>2__current = null;
				<>1__state = 1;
				return true;
			case 1:
				<>1__state = -1;
				try
				{
					if ((Object)(object)<>4__this.valuableObject != (Object)null && (Object)(object)<>4__this.physGrabObject != (Object)null && !<>4__this.isRandomized)
					{
						RandomValueMod.ForceRandomizeItem(<>4__this.physGrabObject, <>4__this.valuableObject);
						<>4__this.isRandomized = true;
					}
				}
				catch (Exception ex)
				{
					<ex>5__1 = ex;
				}
				return false;
			}
		}

		bool IEnumerator.MoveNext()
		{
			//ILSpy generated this explicit interface implementation from .override directive in MoveNext
			return this.MoveNext();
		}

		[DebuggerHidden]
		void IEnumerator.Reset()
		{
			throw new NotSupportedException();
		}
	}

	public ValuableObject valuableObject;

	public PhysGrabObject physGrabObject;

	private bool wasGrabbed = false;

	private int instanceID = 0;

	private float checkTimer = 0f;

	private bool isRandomized = false;

	private void Start()
	{
		if ((Object)(object)valuableObject == (Object)null)
		{
			valuableObject = ((Component)this).GetComponent<ValuableObject>();
		}
		if ((Object)(object)physGrabObject == (Object)null)
		{
			physGrabObject = ((Component)this).GetComponent<PhysGrabObject>();
		}
		if ((Object)(object)valuableObject == (Object)null || (Object)(object)physGrabObject == (Object)null)
		{
			Object.Destroy((Object)(object)this);
		}
		else
		{
			instanceID = ((Object)((Component)this).gameObject).GetInstanceID();
		}
	}

	private void Update()
	{
		if (isRandomized || (Object)(object)valuableObject == (Object)null || (Object)(object)physGrabObject == (Object)null)
		{
			return;
		}
		checkTimer += Time.deltaTime;
		if (checkTimer < 0.5f)
		{
			return;
		}
		checkTimer = 0f;
		try
		{
			bool flag = false;
			FieldInfo field = typeof(PhysGrabObject).GetField("grabbed", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (field != null)
			{
				flag = (bool)field.GetValue(physGrabObject);
			}
			else
			{
				FieldInfo field2 = typeof(PhysGrabObject).GetField("isGrabbed", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (field2 != null)
				{
					flag = (bool)field2.GetValue(physGrabObject);
				}
			}
			if (flag && !wasGrabbed && !isRandomized)
			{
				((MonoBehaviour)this).StartCoroutine(DelayedRandomization());
			}
			wasGrabbed = flag;
			if (isRandomized && RandomValueMod.modifiedItemIDs.Contains(instanceID))
			{
				Object.Destroy((Object)(object)this);
			}
		}
		catch (Exception)
		{
		}
	}

	[IteratorStateMachine(typeof(<DelayedRandomization>d__8))]
	private IEnumerator DelayedRandomization()
	{
		//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
		return new <DelayedRandomization>d__8(0)
		{
			<>4__this = this
		};
	}
}
public class ItemRandomizationNetworkSync : MonoBehaviourPun
{
	[CompilerGenerated]
	private sealed class <RetryBroadcast>d__13 : IEnumerator<object>, IDisposable, IEnumerator
	{
		private int <>1__state;

		private object <>2__current;

		public float price;

		public bool isClientInitiated;

		public ItemRandomizationNetworkSync <>4__this;

		object IEnumerator<object>.Current
		{
			[DebuggerHidden]
			get
			{
				return <>2__current;
			}
		}

		object IEnumerator.Current
		{
			[DebuggerHidden]
			get
			{
				return <>2__current;
			}
		}

		[DebuggerHidden]
		public <RetryBroadcast>d__13(int <>1__state)
		{
			this.<>1__state = <>1__state;
		}

		[DebuggerHidden]
		void IDisposable.Dispose()
		{
			<>1__state = -2;
		}

		private bool MoveNext()
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			switch (<>1__state)
			{
			default:
				return false;
			case 0:
				<>1__state = -1;
				<>2__current = (object)new WaitForSeconds(1f);
				<>1__state = 1;
				return true;
			case 1:
				<>1__state = -1;
				if (RandomValueMod.EnableNetworkDebug.Value)
				{
					RandomValueMod.StaticLogger.LogInfo((object)$"[重试] 第{<>4__this.syncRetryCount}次重试: {((Object)((Component)<>4__this).gameObject).name}");
				}
				<>4__this.BroadcastRandomization(price, isClientInitiated);
				return false;
			}
		}

		bool IEnumerator.MoveNext()
		{
			//ILSpy generated this explicit interface implementation from .override directive in MoveNext
			return this.MoveNext();
		}

		[DebuggerHidden]
		void IEnumerator.Reset()
		{
			throw new NotSupportedException();
		}
	}

	private bool hasBeenSynced = false;

	private float syncedPrice = -1f;

	private int itemInstanceID = 0;

	private int syncRetryCount = 0;

	private float lastSyncTime = 0f;

	private ValuableObject vo;

	private PhysGrabObject pgo;

	private void Awake()
	{
		vo = ((Component)this).GetComponent<ValuableObject>();
		pgo = ((Component)this).GetComponent<PhysGrabObject>();
		itemInstanceID = ((Object)((Component)this).gameObject).GetInstanceID();
		if (RandomValueMod.EnableNetworkDebug.Value)
		{
			RandomValueMod.StaticLogger.LogInfo((object)$"[网络组件] 初始化: {((Object)((Component)this).gameObject).name}, ID: {itemInstanceID}");
		}
	}

	private bool CheckPhotonStatus()
	{
		try
		{
			if (!PhotonNetwork.IsConnected)
			{
				return false;
			}
			if ((Object)(object)((MonoBehaviourPun)this).photonView == (Object)null)
			{
				return false;
			}
			return true;
		}
		catch
		{
			return false;
		}
	}

	[PunRPC]
	public void SyncItemRandomization(int viewID, float price, int requestPlayerID = -1)
	{
		try
		{
			if (RandomValueMod.EnableNetworkDebug.Value)
			{
				RandomValueMod.StaticLogger.LogInfo((object)$"[RPC] 收到同步请求: 物品={((Object)((Component)this).gameObject).name}, 价格={price}, 请求者={requestPlayerID}");
			}
			if (viewID == ((MonoBehaviourPun)this).photonView.ViewID && !hasBeenSynced)
			{
				syncedPrice = price;
				hasBeenSynced = true;
				lastSyncTime = Time.realtimeSinceStartup;
				ApplySyncedRandomization();
				if (!PhotonNetwork.IsMasterClient && requestPlayerID == PhotonNetwork.LocalPlayer.ActorNumber)
				{
					BroadcastToAllPlayers(price);
				}
				if (RandomValueMod.EnableNetworkDebug.Value)
				{
					RandomValueMod.StaticLogger.LogInfo((object)("[RPC] 同步成功: " + ((Object)((Component)this).gameObject).name));
				}
			}
		}
		catch (Exception ex)
		{
			RandomValueMod.StaticLogger.LogError((object)("[RPC] 处理RPC时出错: " + ex.Message));
		}
	}

	private void BroadcastToAllPlayers(float price)
	{
		if (!CheckPhotonStatus())
		{
			return;
		}
		try
		{
			if (RandomValueMod.EnableNetworkDebug.Value)
			{
				RandomValueMod.StaticLogger.LogInfo((object)$"[广播] 客户端广播: {((Object)((Component)this).gameObject).name}, 价格={price}");
			}
			((MonoBehaviourPun)this).photonView.RPC("SyncItemRandomization", (RpcTarget)0, new object[3]
			{
				((MonoBehaviourPun)this).photonView.ViewID,
				price,
				PhotonNetwork.LocalPlayer.ActorNumber
			});
		}
		catch (Exception ex)
		{
			RandomValueMod.StaticLogger.LogError((object)("[广播] 客户端广播失败: " + ex.Message));
		}
	}

	private void ApplySyncedRandomization()
	{
		if (!((Object)(object)vo == (Object)null) && !((Object)(object)pgo == (Object)null) && !RandomValueMod.modifiedItemIDs.Contains(itemInstanceID) && RandomValueMod.ShouldItemBeRandomized(((Component)this).gameObject, vo) && ItemModifier.ModifyItemAttributes(pgo, vo, syncedPrice))
		{
			RandomValueMod.modifiedItemIDs.Add(itemInstanceID);
			RandomValueMod.ClearClientRandomizationRequest(itemInstanceID);
			if (RandomValueMod.EnableNetworkDebug.Value)
			{
				RandomValueMod.StaticLogger.LogInfo((object)$"[网络] 客户端应用随机化: {((Object)((Component)this).gameObject).name}, 价格=${syncedPrice:F0}");
			}
		}
	}

	public void BroadcastRandomization(float price, bool isClientInitiated = false)
	{
		try
		{
			if (RandomValueMod.EnableNetworkDebug.Value)
			{
				RandomValueMod.StaticLogger.LogInfo((object)$"[广播] 开始广播: {((Object)((Component)this).gameObject).name}, 价格={price}, 客户端发起={isClientInitiated}");
			}
			if (!CheckPhotonStatus())
			{
				hasBeenSynced = true;
			}
			else
			{
				if (hasBeenSynced || !RandomValueMod.EnableNetworkSync.Value)
				{
					return;
				}
				if (PhotonNetwork.IsMasterClient)
				{
					try
					{
						((MonoBehaviourPun)this).photonView.RPC("SyncItemRandomization", (RpcTarget)1, new object[2]
						{
							((MonoBehaviourPun)this).photonView.ViewID,
							price
						});
						if (RandomValueMod.EnableNetworkDebug.Value)
						{
							RandomValueMod.StaticLogger.LogInfo((object)("[主机] RPC发送成功: " + ((Object)((Component)this).gameObject).name));
						}
					}
					catch (Exception ex)
					{
						RandomValueMod.StaticLogger.LogError((object)("[主机] RPC调用失败: " + ex.Message));
						if (syncRetryCount < 3)
						{
							syncRetryCount++;
							((MonoBehaviour)this).StartCoroutine(RetryBroadcast(price, isClientInitiated));
						}
					}
				}
				else if (isClientInitiated)
				{
					if (RandomValueMod.EnableNetworkDebug.Value)
					{
						RandomValueMod.StaticLogger.LogInfo((object)("[客户端] 发起同步: " + ((Object)((Component)this).gameObject).name));
					}
					syncedPrice = price;
					hasBeenSynced = true;
					ApplySyncedRandomization();
					BroadcastToAllPlayers(price);
				}
				hasBeenSynced = true;
			}
		}
		catch (Exception ex2)
		{
			RandomValueMod.StaticLogger.LogError((object)("[广播] 广播随机化时发生异常: " + ex2.Message));
		}
	}

	[IteratorStateMachine(typeof(<RetryBroadcast>d__13))]
	private IEnumerator RetryBroadcast(float price, bool isClientInitiated)
	{
		//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
		return new <RetryBroadcast>d__13(0)
		{
			<>4__this = this,
			price = price,
			isClientInitiated = isClientInitiated
		};
	}

	public void ClientRequestRandomization()
	{
		if (!CheckPhotonStatus())
		{
			return;
		}
		try
		{
			if (RandomValueMod.EnableNetworkDebug.Value)
			{
				RandomValueMod.StaticLogger.LogInfo((object)("[客户端请求] 请求随机化: " + ((Object)((Component)this).gameObject).name));
			}
			if (RandomValueMod.modifiedItemIDs.Contains(itemInstanceID) || !RandomValueMod.ShouldItemBeRandomized(((Component)this).gameObject, vo))
			{
				return;
			}
			float itemPrice = ItemModifier.GetItemPrice(vo);
			if (!(itemPrice <= 0f))
			{
				float deterministicRandomPrice = RandomValueMod.GetDeterministicRandomPrice(itemInstanceID, itemPrice);
				if (RandomValueMod.EnableNetworkDebug.Value)
				{
					RandomValueMod.StaticLogger.LogInfo((object)$"[客户端请求] 生成随机值: {((Object)((Component)this).gameObject).name}, 原始价格=${itemPrice:F0}, 随机价格=${deterministicRandomPrice:F0}");
				}
				BroadcastRandomization(deterministicRandomPrice, isClientInitiated: true);
			}
		}
		catch (Exception ex)
		{
			RandomValueMod.StaticLogger.LogError((object)("[客户端请求] 请求随机化时出错: " + ex.Message));
		}
	}

	public static void EnsureNetworkComponent(GameObject obj)
	{
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)obj == (Object)null || !PhotonNetwork.IsConnected || !RandomValueMod.EnableNetworkSync.Value)
		{
			return;
		}
		ValuableObject component = obj.GetComponent<ValuableObject>();
		ItemRandomizationNetworkSync itemRandomizationNetworkSync = default(ItemRandomizationNetworkSync);
		if (!((Object)(object)component == (Object)null) && RandomValueMod.ShouldItemBeRandomized(obj, component) && !obj.TryGetComponent<ItemRandomizationNetworkSync>(ref itemRandomizationNetworkSync))
		{
			PhotonView val = default(PhotonView);
			if (!obj.TryGetComponent<PhotonView>(ref val))
			{
				val = obj.AddComponent<PhotonView>();
				val.OwnershipTransfer = (OwnershipOption)1;
				val.Synchronization = (ViewSynchronization)3;
			}
			ItemRandomizationNetworkSync itemRandomizationNetworkSync2 = obj.AddComponent<ItemRandomizationNetworkSync>();
			if (RandomValueMod.EnableNetworkDebug.Value)
			{
				RandomValueMod.StaticLogger.LogInfo((object)("[网络组件] 添加同步组件: " + ((Object)obj).name));
			}
		}
	}
}