Decompiled source of Voyage v1.0.0

Voyage.dll

Decompiled 2 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;
using UnityEngine.UI;
using Voyage.CartDock;
using Voyage.CartUpgrade;
using Voyage.Config;
using Voyage.Localization;
using Voyage.Motor;
using Voyage.Overload;
using Voyage.Shared;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("Voyage")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Voyage")]
[assembly: AssemblyTitle("Voyage")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Voyage
{
	[BepInPlugin("MM94.Voyage", "Voyage", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public static ManualLogSource Log;

		public static Plugin Instance { get; private set; }

		private void Awake()
		{
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			LogBuildInfo();
			Lang.Init();
			VoyageConfig.Bind(((BaseUnityPlugin)this).Config);
			ApplyHarmonyPatchesIsolated();
			Log.LogInfo((object)"Voyage loaded.");
		}

		private void ApplyHarmonyPatchesIsolated()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			Harmony val = new Harmony("MM94.Voyage");
			int num = 0;
			int num2 = 0;
			foreach (Type item in from t in AccessTools.GetTypesFromAssembly(Assembly.GetExecutingAssembly())
				where t.GetCustomAttributes(typeof(HarmonyPatch), inherit: false).Length != 0
				select t)
			{
				try
				{
					val.CreateClassProcessor(item).Patch();
					num++;
				}
				catch (Exception arg)
				{
					num2++;
					Log.LogError((object)$"[Voyage:패치실패] '{item.FullName}' 패치 적용 실패 — 이 기능만 비활성화된 채로 나머지는 계속 진행됨. {arg}");
				}
			}
			Log.LogInfo((object)$"[Voyage:패치요약] 성공 {num}개 / 실패 {num2}개");
		}

		private void Update()
		{
			if (VoyageConfig.ModEnabled.Value)
			{
				SafeTick("CartDockTick", CartDockManager.Tick);
				SafeTick("CartUpgradeTick", CartUpgradeManager.Tick);
				SafeTick("MotorInputTick", MotorManager.TickInput);
				SafeTick("MotorHudTick", MotorShipHud.Tick);
			}
		}

		private static void SafeTick(string name, Action action)
		{
			try
			{
				action();
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"[Voyage:Tick실패] {name} — {arg}");
			}
		}

		private void LogBuildInfo()
		{
			try
			{
				string location = Assembly.GetExecutingAssembly().Location;
				DateTime lastWriteTime = File.GetLastWriteTime(location);
				string arg;
				using (MD5 mD = MD5.Create())
				{
					using FileStream inputStream = File.OpenRead(location);
					arg = BitConverter.ToString(mD.ComputeHash(inputStream), 0, 4).Replace("-", "");
				}
				((BaseUnityPlugin)this).Logger.LogInfo((object)$"[Voyage:빌드정보] dll 수정시각={lastWriteTime:yyyy-MM-dd HH:mm:ss}, md5앞8자리={arg}");
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("[Voyage:빌드정보] 확인 실패 — " + ex.Message));
			}
		}
	}
	internal static class BuildInfo
	{
		internal const string Timestamp = "2026-11-22 06:19:13";
	}
}
namespace Voyage.Shared
{
	internal static class VanillaAccess
	{
		private static readonly FieldRef<Vagon, Rigidbody> s_vagonBody = AccessTools.FieldRefAccess<Vagon, Rigidbody>("m_body");

		private static readonly FieldRef<Vagon, Rigidbody[]> s_vagonBodies = AccessTools.FieldRefAccess<Vagon, Rigidbody[]>("m_bodies");

		private static readonly FieldRef<Vagon, ConfigurableJoint> s_vagonAttachJoin = AccessTools.FieldRefAccess<Vagon, ConfigurableJoint>("m_attachJoin");

		private static readonly FieldRef<Player, GameObject> s_playerHovering = AccessTools.FieldRefAccess<Player, GameObject>("m_hovering");

		private static readonly FieldRef<Ship, Rigidbody> s_shipBody = AccessTools.FieldRefAccess<Ship, Rigidbody>("m_body");

		private static List<Vagon> s_vagonInstances;

		private static Func<Ship, bool> s_shipHaveControllingPlayer;

		internal static Rigidbody VagonBody(Vagon v)
		{
			return s_vagonBody.Invoke(v);
		}

		internal static Rigidbody[] VagonBodies(Vagon v)
		{
			return s_vagonBodies.Invoke(v);
		}

		internal static ConfigurableJoint VagonAttachJoin(Vagon v)
		{
			return s_vagonAttachJoin.Invoke(v);
		}

		internal static GameObject PlayerHovering(Player p)
		{
			return s_playerHovering.Invoke(p);
		}

		internal static Rigidbody ShipBody(Ship s)
		{
			return s_shipBody.Invoke(s);
		}

		internal static List<Vagon> VagonInstances()
		{
			if (s_vagonInstances == null)
			{
				s_vagonInstances = (List<Vagon>)AccessTools.Field(typeof(Vagon), "m_instances").GetValue(null);
			}
			return s_vagonInstances;
		}

		internal static bool ShipHaveControllingPlayer(Ship ship)
		{
			try
			{
				if (s_shipHaveControllingPlayer == null)
				{
					s_shipHaveControllingPlayer = AccessTools.MethodDelegate<Func<Ship, bool>>(AccessTools.Method(typeof(Ship), "HaveControllingPlayer", (Type[])null, (Type[])null), (object)null, true);
				}
				return s_shipHaveControllingPlayer(ship);
			}
			catch (Exception ex)
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("[Voyage:리플렉션실패] Ship.HaveControllingPlayer 호출 실패 — " + ex.Message));
				}
				return true;
			}
		}
	}
	internal static class ZdoKeys
	{
		internal const string CartDockedShip = "Voyage_DockedShip";

		internal const string CartDockOffsetPos = "Voyage_DockOffsetPos";

		internal const string CartDockOffsetRot = "Voyage_DockOffsetRot";

		internal const string MotorOn = "Voyage_MotorOn";

		internal const string MotorFuelItem = "Voyage_MotorFuelItem";

		internal const string MotorFuelRemain = "Voyage_MotorFuelRemain";
	}
}
namespace Voyage.Overload
{
	[HarmonyPatch(typeof(Ship), "Awake")]
	internal static class ShipAwakeOverloadPatch
	{
		private static void Postfix(Ship __instance)
		{
			if ((Object)(object)((Component)__instance).GetComponent<VoyageOverload>() == (Object)null)
			{
				((Component)__instance).gameObject.AddComponent<VoyageOverload>();
			}
		}
	}
	[HarmonyPatch(typeof(Ship), "CustomFixedUpdate")]
	internal static class ShipPaddleForceOverloadPatch
	{
		private static void Prefix(Ship __instance, out float __state)
		{
			__state = __instance.m_backwardForce;
			if (VoyageConfig.OverloadEnabled.Value)
			{
				VoyageOverload component = ((Component)__instance).GetComponent<VoyageOverload>();
				if (!((Object)(object)component == (Object)null))
				{
					__instance.m_backwardForce *= component.SpeedMultiplier;
				}
			}
		}

		private static void Postfix(Ship __instance, float __state)
		{
			__instance.m_backwardForce = __state;
		}
	}
	internal class VoyageOverload : MonoBehaviour
	{
		private Ship m_ship;

		private ZNetView m_nview;

		internal float CurrentWeight { get; private set; }

		internal float Capacity { get; private set; } = 2000f;

		internal float SpeedMultiplier { get; private set; } = 1f;

		private void Awake()
		{
			m_ship = ((Component)this).GetComponent<Ship>();
			m_nview = ((Component)this).GetComponent<ZNetView>();
			Capacity = LookupCapacity();
			((MonoBehaviour)this).InvokeRepeating("Recalculate", 0f, 1f);
		}

		private float LookupCapacity()
		{
			string text = ((Object)((Component)this).gameObject).name.Replace("(Clone)", string.Empty).Trim();
			foreach (KeyValuePair<string, float> item in ParseCapacityTable(VoyageConfig.ShipCapacityTable.Value))
			{
				if (item.Key == text)
				{
					return item.Value;
				}
			}
			return VoyageConfig.DefaultShipCapacity.Value;
		}

		private static IEnumerable<KeyValuePair<string, float>> ParseCapacityTable(string raw)
		{
			if (string.IsNullOrEmpty(raw))
			{
				yield break;
			}
			string[] array = raw.Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				string[] array2 = array[i].Split(new char[1] { ':' });
				if (array2.Length == 2 && float.TryParse(array2[1].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
				{
					yield return new KeyValuePair<string, float>(array2[0].Trim(), result);
				}
			}
		}

		private void Recalculate()
		{
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			if (!VoyageConfig.OverloadEnabled.Value)
			{
				SpeedMultiplier = 1f;
			}
			else
			{
				if ((Object)(object)m_nview == (Object)null || !m_nview.IsValid())
				{
					return;
				}
				float num = 0f;
				Container[] componentsInChildren = ((Component)this).GetComponentsInChildren<Container>();
				foreach (Container val in componentsInChildren)
				{
					if (!((Object)(object)val == (Object)null))
					{
						Inventory inventory = val.GetInventory();
						if (inventory != null)
						{
							num += inventory.GetTotalWeight();
						}
					}
				}
				foreach (Vagon item in CartDockManager.GetCartsDockedTo(m_nview.GetZDO().m_uid))
				{
					num += VoyageConfig.CartBaseWeight.Value;
					if ((Object)(object)item.m_container != (Object)null)
					{
						Inventory inventory2 = item.m_container.GetInventory();
						if (inventory2 != null)
						{
							num += inventory2.GetTotalWeight();
						}
					}
				}
				CurrentWeight = num;
				float num2 = ((Capacity > 0f) ? (num / Capacity) : 0f);
				if (num2 <= 1f)
				{
					SpeedMultiplier = 1f;
					return;
				}
				float num3 = Mathf.Max(VoyageConfig.OverdraftRatioForMinSpeed.Value, 1.01f);
				float num4 = Mathf.Clamp01((num2 - 1f) / (num3 - 1f));
				SpeedMultiplier = Mathf.Lerp(1f, VoyageConfig.MinSpeedMultiplier.Value, num4);
			}
		}

		internal float GetLoadRatio()
		{
			if (!(Capacity > 0f))
			{
				return 0f;
			}
			return CurrentWeight / Capacity;
		}
	}
}
namespace Voyage.Motor
{
	internal struct FuelDef
	{
		internal string Name;

		internal float Multiplier;

		internal float Duration;
	}
	internal static class MotorFuel
	{
		private static List<FuelDef> ParseTable()
		{
			List<FuelDef> list = new List<FuelDef>();
			string value = VoyageConfig.FuelTable.Value;
			if (string.IsNullOrEmpty(value))
			{
				return list;
			}
			string[] array = value.Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				string[] array2 = array[i].Split(new char[1] { ':' });
				if (array2.Length == 3 && float.TryParse(array2[1].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result) && float.TryParse(array2[2].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result2))
				{
					list.Add(new FuelDef
					{
						Name = array2[0].Trim(),
						Multiplier = result,
						Duration = result2
					});
				}
			}
			return list;
		}

		internal static float GetMultiplier(string fuelItemName)
		{
			if (string.IsNullOrEmpty(fuelItemName))
			{
				return 1f;
			}
			foreach (FuelDef item in ParseTable())
			{
				if (item.Name == fuelItemName)
				{
					return item.Multiplier;
				}
			}
			return 1f;
		}

		internal static bool IsKnownFuel(string fuelItemName)
		{
			if (string.IsNullOrEmpty(fuelItemName))
			{
				return false;
			}
			return ParseTable().Any((FuelDef d) => d.Name == fuelItemName);
		}

		internal static bool TryConsumeFuel(Ship ship, out string fuelItem, out float duration, string preferSameAs = null)
		{
			fuelItem = null;
			duration = 0f;
			if ((Object)(object)ship == (Object)null)
			{
				return false;
			}
			List<FuelDef> list = ParseTable();
			if (list.Count == 0)
			{
				return false;
			}
			List<(FuelDef, Container, ItemData)> list2 = new List<(FuelDef, Container, ItemData)>();
			Container[] componentsInChildren = ((Component)ship).GetComponentsInChildren<Container>();
			foreach (Container val in componentsInChildren)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				Inventory inventory = val.GetInventory();
				if (inventory == null)
				{
					continue;
				}
				foreach (ItemData allItem in inventory.GetAllItems())
				{
					if ((Object)(object)allItem?.m_dropPrefab == (Object)null)
					{
						continue;
					}
					string name = ((Object)allItem.m_dropPrefab).name;
					foreach (FuelDef item in list)
					{
						if (item.Name == name)
						{
							list2.Add((item, val, allItem));
							break;
						}
					}
				}
			}
			if (list2.Count == 0)
			{
				return false;
			}
			if (!string.IsNullOrEmpty(preferSameAs))
			{
				(FuelDef, Container, ItemData) tuple = list2.FirstOrDefault<(FuelDef, Container, ItemData)>(((FuelDef def, Container container, ItemData item) a) => a.def.Name == preferSameAs);
				if (tuple.Item3 != null)
				{
					return Consume(tuple.Item2, tuple.Item1, tuple.Item3, out fuelItem, out duration);
				}
			}
			(FuelDef, Container, ItemData) tuple2 = (VoyageConfig.PreferLowMultiplierFuel.Value ? list2.OrderBy<(FuelDef, Container, ItemData), float>(((FuelDef def, Container container, ItemData item) a) => a.def.Multiplier).ToList() : list2.OrderByDescending<(FuelDef, Container, ItemData), float>(((FuelDef def, Container container, ItemData item) a) => a.def.Multiplier).ToList())[0];
			return Consume(tuple2.Item2, tuple2.Item1, tuple2.Item3, out fuelItem, out duration);
		}

		internal static bool HasAnyContainer(Ship ship)
		{
			if ((Object)(object)ship == (Object)null)
			{
				return false;
			}
			Container[] componentsInChildren = ((Component)ship).GetComponentsInChildren<Container>();
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				if ((Object)(object)componentsInChildren[i] != (Object)null)
				{
					return true;
				}
			}
			return false;
		}

		private static bool Consume(Container container, FuelDef def, ItemData item, out string fuelItem, out float duration)
		{
			ZNetView component = ((Component)container).GetComponent<ZNetView>();
			if ((Object)(object)component != (Object)null && component.IsValid())
			{
				component.ClaimOwnership();
			}
			container.GetInventory().RemoveItem(item, 1);
			fuelItem = def.Name;
			duration = def.Duration;
			return true;
		}
	}
	internal static class MotorManager
	{
		internal static void TickInput()
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			if (!VoyageConfig.MotorEnabled.Value)
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return;
			}
			Ship controlledShip = localPlayer.GetControlledShip();
			if (!((Object)(object)controlledShip == (Object)null))
			{
				VoyageMotor component = ((Component)controlledShip).GetComponent<VoyageMotor>();
				if (!((Object)(object)component == (Object)null) && Input.GetKeyDown(VoyageConfig.MotorToggleKey.Value))
				{
					component.RequestToggle(localPlayer);
				}
			}
		}
	}
	[HarmonyPatch(typeof(Ship), "Awake")]
	internal static class ShipAwakeMotorPatch
	{
		private static void Postfix(Ship __instance)
		{
			if ((Object)(object)((Component)__instance).GetComponent<VoyageMotor>() == (Object)null)
			{
				((Component)__instance).gameObject.AddComponent<VoyageMotor>();
			}
		}
	}
	[HarmonyPatch(typeof(Ship), "GetSailForce")]
	internal static class ShipSailForceCompositePatch
	{
		private static void Postfix(Ship __instance, ref Vector3 __result)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			if (VoyageConfig.MotorEnabled.Value)
			{
				VoyageMotor component = ((Component)__instance).GetComponent<VoyageMotor>();
				if ((Object)(object)component != (Object)null && component.IsOn)
				{
					__result *= component.CurrentFuelMultiplier;
				}
			}
			if (VoyageConfig.OverloadEnabled.Value)
			{
				VoyageOverload component2 = ((Component)__instance).GetComponent<VoyageOverload>();
				if ((Object)(object)component2 != (Object)null)
				{
					__result *= component2.SpeedMultiplier;
				}
			}
		}
	}
	[HarmonyPatch(typeof(Ship), "CustomFixedUpdate")]
	internal static class ShipPaddleForceMotorPatch
	{
		private static void Prefix(Ship __instance, out float __state)
		{
			__state = __instance.m_backwardForce;
			if (VoyageConfig.MotorEnabled.Value)
			{
				VoyageMotor component = ((Component)__instance).GetComponent<VoyageMotor>();
				if (!((Object)(object)component == (Object)null) && component.IsOn)
				{
					__instance.m_backwardForce *= component.CurrentFuelMultiplier;
				}
			}
		}

		private static void Postfix(Ship __instance, float __state)
		{
			__instance.m_backwardForce = __state;
		}
	}
	internal static class MotorShipHud
	{
		private const float IconSize = 18f;

		private const float IconOffsetY = 0f;

		private const float TextOffsetY = -14f;

		private const float TextWidth = 60f;

		private const float TextHeight = 20f;

		private const int TextFontSize = 14;

		private const float SpeedOffsetY = -30f;

		private const float SpeedWidth = 70f;

		private const float SpeedHeight = 16f;

		private const int SpeedFontSize = 12;

		private static readonly Color SpeedOffColor = Color.white;

		private static readonly Color SpeedOnColor = new Color(1f, 0.85f, 0.25f);

		private static GameObject s_root;

		private static Image s_icon;

		private static Text s_text;

		private static Text s_speedText;

		private static string s_cachedFuelItem;

		private static bool s_loggedCenterOnce;

		private static readonly Dictionary<string, Sprite> s_iconCache = new Dictionary<string, Sprite>();

		internal static void Tick()
		{
			if ((Object)(object)Hud.instance == (Object)null || (Object)(object)Hud.instance.m_shipHudRoot == (Object)null)
			{
				return;
			}
			EnsureBuilt();
			Player localPlayer = Player.m_localPlayer;
			Ship val = (((Object)(object)localPlayer != (Object)null) ? localPlayer.GetControlledShip() : null);
			if ((Object)(object)val == (Object)null)
			{
				if (s_root.activeSelf)
				{
					s_root.SetActive(false);
				}
				return;
			}
			if (!s_root.activeSelf)
			{
				s_root.SetActive(true);
			}
			UpdateCenterPosition();
			VoyageMotor component = ((Component)val).GetComponent<VoyageMotor>();
			bool motorOn = (Object)(object)component != (Object)null && component.IsOn;
			UpdateFuelDisplay(component, motorOn);
			UpdateSpeedDisplay(val, motorOn);
		}

		private static void UpdateFuelDisplay(VoyageMotor motor, bool motorOn)
		{
			if (((Component)s_icon).gameObject.activeSelf != motorOn)
			{
				((Component)s_icon).gameObject.SetActive(motorOn);
			}
			if (((Component)s_text).gameObject.activeSelf != motorOn)
			{
				((Component)s_text).gameObject.SetActive(motorOn);
			}
			if (motorOn)
			{
				if (motor.FuelItem != s_cachedFuelItem)
				{
					s_cachedFuelItem = motor.FuelItem;
					s_icon.sprite = GetIconFor(motor.FuelItem);
					((Behaviour)s_icon).enabled = (Object)(object)s_icon.sprite != (Object)null;
				}
				s_text.text = Mathf.CeilToInt(motor.FuelRemain).ToString(CultureInfo.InvariantCulture);
			}
		}

		private static void UpdateSpeedDisplay(Ship ship, bool motorOn)
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			if (!VoyageConfig.SpeedDisplayEnabled.Value)
			{
				if (((Component)s_speedText).gameObject.activeSelf)
				{
					((Component)s_speedText).gameObject.SetActive(false);
				}
				return;
			}
			if (!((Component)s_speedText).gameObject.activeSelf)
			{
				((Component)s_speedText).gameObject.SetActive(true);
			}
			Rigidbody val = VanillaAccess.ShipBody(ship);
			float num = 0f;
			if ((Object)(object)val != (Object)null)
			{
				Vector3 linearVelocity = val.linearVelocity;
				linearVelocity.y = 0f;
				num = ((Vector3)(ref linearVelocity)).magnitude;
			}
			s_speedText.text = num.ToString("0.0", CultureInfo.InvariantCulture) + " m/s";
			((Graphic)s_speedText).color = (motorOn ? SpeedOnColor : SpeedOffColor);
		}

		private static void UpdateCenterPosition()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			RectTransform shipWindIndicatorRoot = Hud.instance.m_shipWindIndicatorRoot;
			if ((Object)(object)shipWindIndicatorRoot == (Object)null)
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogWarning((object)"[Voyage:모터HUD] m_shipWindIndicatorRoot가 없어 폴백 위치를 사용합니다.");
				}
				return;
			}
			Vector3 position = ((Transform)shipWindIndicatorRoot).position;
			s_root.transform.position = position;
			s_root.transform.rotation = Quaternion.identity;
			if (!s_loggedCenterOnce)
			{
				s_loggedCenterOnce = true;
				ManualLogSource log2 = Plugin.Log;
				if (log2 != null)
				{
					log2.LogInfo((object)$"[Voyage:모터HUD] 원형 게이지 중앙 좌표(월드): {position}");
				}
			}
		}

		private static void EnsureBuilt()
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0244: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)s_root != (Object)null))
			{
				s_root = new GameObject("VoyageMotorHud", new Type[1] { typeof(RectTransform) });
				s_root.transform.SetParent(Hud.instance.m_shipHudRoot.transform, false);
				RectTransform component = s_root.GetComponent<RectTransform>();
				Vector2 val = default(Vector2);
				((Vector2)(ref val))..ctor(0.5f, 0.5f);
				component.anchorMax = val;
				component.anchorMin = val;
				component.anchoredPosition = Vector2.zero;
				component.sizeDelta = new Vector2(60f, 60f);
				GameObject val2 = new GameObject("Icon", new Type[1] { typeof(RectTransform) });
				val2.transform.SetParent(s_root.transform, false);
				RectTransform component2 = val2.GetComponent<RectTransform>();
				((Vector2)(ref val))..ctor(0.5f, 0.5f);
				component2.anchorMax = val;
				component2.anchorMin = val;
				component2.anchoredPosition = new Vector2(0f, 0f);
				component2.sizeDelta = new Vector2(18f, 18f);
				s_icon = val2.AddComponent<Image>();
				s_icon.preserveAspect = true;
				GameObject val3 = new GameObject("Seconds", new Type[1] { typeof(RectTransform) });
				val3.transform.SetParent(s_root.transform, false);
				RectTransform component3 = val3.GetComponent<RectTransform>();
				((Vector2)(ref val))..ctor(0.5f, 0.5f);
				component3.anchorMax = val;
				component3.anchorMin = val;
				component3.anchoredPosition = new Vector2(0f, -14f);
				component3.sizeDelta = new Vector2(60f, 20f);
				s_text = val3.AddComponent<Text>();
				s_text.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
				s_text.fontSize = 14;
				s_text.alignment = (TextAnchor)4;
				((Graphic)s_text).color = Color.white;
				GameObject val4 = new GameObject("Speed", new Type[1] { typeof(RectTransform) });
				val4.transform.SetParent(s_root.transform, false);
				RectTransform component4 = val4.GetComponent<RectTransform>();
				((Vector2)(ref val))..ctor(0.5f, 0.5f);
				component4.anchorMax = val;
				component4.anchorMin = val;
				component4.anchoredPosition = new Vector2(0f, -30f);
				component4.sizeDelta = new Vector2(70f, 16f);
				s_speedText = val4.AddComponent<Text>();
				s_speedText.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
				s_speedText.fontSize = 12;
				s_speedText.alignment = (TextAnchor)4;
				((Graphic)s_speedText).color = SpeedOffColor;
				s_root.SetActive(false);
			}
		}

		private static Sprite GetIconFor(string fuelItemName)
		{
			if (string.IsNullOrEmpty(fuelItemName))
			{
				return null;
			}
			if (s_iconCache.TryGetValue(fuelItemName, out var value))
			{
				return value;
			}
			Sprite val = null;
			GameObject val2 = (((Object)(object)ObjectDB.instance != (Object)null) ? ObjectDB.instance.GetItemPrefab(fuelItemName) : null);
			ItemDrop val3 = (((Object)(object)val2 != (Object)null) ? val2.GetComponent<ItemDrop>() : null);
			if ((Object)(object)val3 != (Object)null && val3.m_itemData != null)
			{
				val = val3.m_itemData.GetIcon();
			}
			s_iconCache[fuelItemName] = val;
			return val;
		}
	}
	internal enum MotorMsg
	{
		OnOk,
		OffOk,
		NoFuel,
		NoContainer
	}
	internal class VoyageMotor : MonoBehaviour
	{
		private Ship m_ship;

		private ZNetView m_nview;

		internal bool IsOn { get; private set; }

		internal string FuelItem { get; private set; } = "";

		internal float FuelRemain { get; private set; }

		internal float CurrentFuelMultiplier { get; private set; } = 1f;

		private void Awake()
		{
			m_ship = ((Component)this).GetComponent<Ship>();
			m_nview = ((Component)this).GetComponent<ZNetView>();
			if (!((Object)(object)m_nview == (Object)null) && m_nview.IsValid())
			{
				m_nview.Register("Voyage_ToggleMotor", (Action<long>)RPC_ToggleMotor);
				m_nview.Register<int>("Voyage_MotorMessage", (Action<long, int>)RPC_MotorMessage);
			}
		}

		internal void RequestToggle(Player requester)
		{
			if (!((Object)(object)m_nview == (Object)null) && m_nview.IsValid())
			{
				m_nview.InvokeRPC("Voyage_ToggleMotor", Array.Empty<object>());
			}
		}

		private void RPC_ToggleMotor(long sender)
		{
			if ((Object)(object)m_nview == (Object)null || !m_nview.IsValid() || !m_nview.IsOwner())
			{
				return;
			}
			ZDO zDO = m_nview.GetZDO();
			if (zDO.GetBool("Voyage_MotorOn", false))
			{
				zDO.Set("Voyage_MotorOn", false);
				m_nview.InvokeRPC(sender, "Voyage_MotorMessage", new object[1] { 1 });
				return;
			}
			if (!MotorFuel.HasAnyContainer(m_ship))
			{
				m_nview.InvokeRPC(sender, "Voyage_MotorMessage", new object[1] { 3 });
				return;
			}
			string fuelItemName = zDO.GetString("Voyage_MotorFuelItem", "");
			string fuelItem;
			float duration;
			if (zDO.GetFloat("Voyage_MotorFuelRemain", 0f) > 0f && MotorFuel.IsKnownFuel(fuelItemName))
			{
				zDO.Set("Voyage_MotorOn", true);
				m_nview.InvokeRPC(sender, "Voyage_MotorMessage", new object[1] { 0 });
			}
			else if (MotorFuel.TryConsumeFuel(m_ship, out fuelItem, out duration))
			{
				zDO.Set("Voyage_MotorOn", true);
				zDO.Set("Voyage_MotorFuelItem", fuelItem);
				zDO.Set("Voyage_MotorFuelRemain", duration);
				m_nview.InvokeRPC(sender, "Voyage_MotorMessage", new object[1] { 0 });
			}
			else
			{
				m_nview.InvokeRPC(sender, "Voyage_MotorMessage", new object[1] { 2 });
			}
		}

		private void RPC_MotorMessage(long sender, int code)
		{
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null))
			{
				string text = (MotorMsg)code switch
				{
					MotorMsg.OnOk => Lang.T("모터 작동", "Motor engaged"), 
					MotorMsg.OffOk => Lang.T("모터 정지", "Motor stopped"), 
					MotorMsg.NoFuel => Lang.T("화물칸에 연료가 없습니다", "No fuel in the cargo hold"), 
					MotorMsg.NoContainer => Lang.T("이 배에는 화물칸이 없어 모터를 쓸 수 없습니다", "This ship has no cargo hold — motor unavailable"), 
					_ => null, 
				};
				if (text != null)
				{
					((Character)localPlayer).Message((MessageType)2, text, 0, (Sprite)null, false);
				}
			}
		}

		private void FixedUpdate()
		{
			if (!Object.op_Implicit((Object)(object)m_nview) || !m_nview.IsValid())
			{
				return;
			}
			ZDO zDO = m_nview.GetZDO();
			IsOn = zDO.GetBool("Voyage_MotorOn", false);
			FuelItem = zDO.GetString("Voyage_MotorFuelItem", "");
			FuelRemain = zDO.GetFloat("Voyage_MotorFuelRemain", 0f);
			CurrentFuelMultiplier = MotorFuel.GetMultiplier(FuelItem);
			if (!VoyageConfig.MotorEnabled.Value || !m_nview.IsOwner() || !IsOn)
			{
				return;
			}
			if ((Object)(object)m_ship != (Object)null && !VanillaAccess.ShipHaveControllingPlayer(m_ship))
			{
				zDO.Set("Voyage_MotorOn", false);
				return;
			}
			float num = FuelRemain - Time.fixedDeltaTime;
			if (num <= 0f)
			{
				if (VoyageConfig.AutoRefuelOnEmpty.Value && MotorFuel.TryConsumeFuel(m_ship, out var fuelItem, out var duration, FuelItem))
				{
					zDO.Set("Voyage_MotorFuelItem", fuelItem);
					zDO.Set("Voyage_MotorFuelRemain", duration);
				}
				else
				{
					zDO.Set("Voyage_MotorOn", false);
					zDO.Set("Voyage_MotorFuelRemain", 0f);
				}
			}
			else
			{
				zDO.Set("Voyage_MotorFuelRemain", num);
			}
		}
	}
}
namespace Voyage.Localization
{
	internal static class Lang
	{
		internal static bool IsKorean { get; private set; }

		internal static void Init()
		{
			IsKorean = PlayerPrefs.GetString("language", "English") == "Korean";
		}

		internal static string T(string ko, string en)
		{
			if (!IsKorean)
			{
				return en;
			}
			return ko;
		}
	}
}
namespace Voyage.Config
{
	internal static class VoyageConfig
	{
		internal static ConfigEntry<bool> ModEnabled;

		internal static ConfigEntry<KeyCode> DockKey;

		internal static ConfigEntry<KeyCode> MotorToggleKey;

		internal static ConfigEntry<KeyCode> UprightKey;

		internal static ConfigEntry<bool> DockingEnabled;

		internal static ConfigEntry<float> DockMaxDeckDistance;

		internal static ConfigEntry<float> DockDeckClearance;

		internal static ConfigEntry<bool> OverloadEnabled;

		internal static ConfigEntry<string> ShipCapacityTable;

		internal static ConfigEntry<float> DefaultShipCapacity;

		internal static ConfigEntry<float> CartBaseWeight;

		internal static ConfigEntry<float> MinSpeedMultiplier;

		internal static ConfigEntry<float> OverdraftRatioForMinSpeed;

		internal static ConfigEntry<bool> MotorEnabled;

		internal static ConfigEntry<string> FuelTable;

		internal static ConfigEntry<bool> AutoRefuelOnEmpty;

		internal static ConfigEntry<bool> PreferLowMultiplierFuel;

		internal static ConfigEntry<bool> SpeedDisplayEnabled;

		internal static ConfigEntry<bool> CartUpgradeEnabled;

		internal static ConfigEntry<float> CartBreakForce;

		internal static ConfigEntry<float> CartDetachToleranceMultiplier;

		internal static ConfigEntry<float> CartCenterOfMassYOffset;

		internal static ConfigEntry<float> CartAngularDragBonus;

		internal static ConfigEntry<float> CartUprightLiftHeight;

		internal static ConfigEntry<float> CartUprightRange;

		internal static void Bind(ConfigFile cfg)
		{
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Expected O, but got Unknown
			ModEnabled = cfg.Bind<bool>("General", "ModEnabled", true, "Voyage 모드 전체를 켜고 끕니다.");
			DockKey = cfg.Bind<KeyCode>("General", "DockKey", (KeyCode)103, "수레를 배 갑판에 고정/해제하는 키 (수레를 조준한 상태에서 사용).");
			MotorToggleKey = cfg.Bind<KeyCode>("General", "MotorToggleKey", (KeyCode)304, "배를 조타 중일 때 모터를 켜고 끄는 키.");
			UprightKey = cfg.Bind<KeyCode>("General", "UprightKey", (KeyCode)104, "뒤집힌 수레를 조준한 상태에서 바로 세우는 키.");
			DockingEnabled = cfg.Bind<bool>("Docking", "DockingEnabled", true, "수레를 배에 고정하는 기능을 켜고 끕니다.");
			DockMaxDeckDistance = cfg.Bind<float>("Docking", "DockMaxDeckDistance", 3f, "수레에서 아래로 레이캐스트해 배 갑판을 감지하는 최대 거리(m).");
			DockDeckClearance = cfg.Bind<float>("Docking", "DockDeckClearance", 0.05f, "고정 시 수레를 갑판 표면에서 살짝 띄우는 보정값(m) — 콜라이더가 겹쳐 배가 기우는 것을 방지.");
			OverloadEnabled = cfg.Bind<bool>("Overload", "OverloadEnabled", true, "배 과적(적재량 초과 시 속도 감소) 기능을 켜고 끕니다.");
			ShipCapacityTable = cfg.Bind<string>("Overload", "ShipCapacityTable", "Raft:500,Karve:1000,VikingShip:2500,VikingShip_Ashlands:4000", "배 프리팹이름:기준적재량(kg) 목록, 쉼표로 구분. 목록에 없는 배는 DefaultShipCapacity 사용. 아쉬랜드 드라카의 실제 프리팹명은 VikingShip_Ashlands로 확인됨.");
			DefaultShipCapacity = cfg.Bind<float>("Overload", "DefaultShipCapacity", 2000f, "ShipCapacityTable 목록에 없는 배의 기본 기준 적재량(kg).");
			CartBaseWeight = cfg.Bind<float>("Overload", "CartBaseWeight", 100f, "배에 고정된 수레 1대의 본체 무게(kg, 수레 보관함 내용물 무게는 별도로 합산됨).");
			MinSpeedMultiplier = cfg.Bind<float>("Overload", "MinSpeedMultiplier", 0.5f, new ConfigDescription("과적이 심할 때 떨어지는 속도 배율의 하한값(0.1~1.0).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 1f), Array.Empty<object>()));
			OverdraftRatioForMinSpeed = cfg.Bind<float>("Overload", "OverdraftRatioForMinSpeed", 2f, "기준 적재량의 몇 배에서 MinSpeedMultiplier(최저 배율)에 도달하는지(예: 2 = 기준×2).");
			MotorEnabled = cfg.Bind<bool>("Motor", "MotorEnabled", true, "연료를 소모해 배를 추진하는 모터 기능을 켜고 끕니다.");
			FuelTable = cfg.Bind<string>("Motor", "FuelTable", "SurtlingCore:1.8:120,BlackCore:2.75:180", "연료아이템프리팹이름:추진배율:지속초 목록, 쉼표로 구분. 자유롭게 추가 가능. 모터는 새 힘을 추가하지 않고 배의 기존 추진력(돛/노젓기)에 이 배율만 곱합니다 — 역풍 데드존 등 기존 추진력이 0이면 모터를 켜도 0입니다. 기본값은 실측 기준 체감 속도 약 1.5배(SurtlingCore)/2배(BlackCore)에 해당하는 배율입니다.");
			AutoRefuelOnEmpty = cfg.Bind<bool>("Motor", "AutoRefuelOnEmpty", true, "모터가 켜진 상태에서 연료가 바닥나면 배 화물칸의 같은 종류 연료를 자동으로 재충전합니다.");
			PreferLowMultiplierFuel = cfg.Bind<bool>("Motor", "PreferLowMultiplierFuel", true, "여러 종류의 연료를 보유했을 때 배율이 낮은 연료부터 소모합니다(false면 배율이 높은 연료 우선).");
			SpeedDisplayEnabled = cfg.Bind<bool>("Motor", "SpeedDisplayEnabled", true, "조타 중일 때 배의 현재 속도(m/s)를 원형 게이지 하단에 표시합니다.");
			CartUpgradeEnabled = cfg.Bind<bool>("Cart", "CartUpgradeEnabled", true, "수레 끌기 개선(안 벗겨짐/안 뒤집힘/바로 세우기) 기능을 켜고 끕니다.");
			CartBreakForce = cfg.Bind<float>("Cart", "CartBreakForce", 1E+09f, "플레이어-수레 연결이 끊어지는 힘 한계. 기본값(사실상 무한대)이면 직접 키를 눌러 놓기 전까지 끊어지지 않음.");
			CartDetachToleranceMultiplier = cfg.Bind<float>("Cart", "CartDetachToleranceMultiplier", 2f, "수레가 자동으로 분리되는 거리/각도 판정을 완화하는 배율(값이 클수록 잘 안 벗겨짐).");
			CartCenterOfMassYOffset = cfg.Bind<float>("Cart", "CartCenterOfMassYOffset", -0.5f, "수레 무게중심 Y 오프셋(음수일수록 안정적, 덜 뒤집힘).");
			CartAngularDragBonus = cfg.Bind<float>("Cart", "CartAngularDragBonus", 2f, "수레 회전 저항(angularDrag)에 추가로 더해지는 값(클수록 덜 흔들리고 덜 뒤집힘).");
			CartUprightLiftHeight = cfg.Bind<float>("Cart", "CartUprightLiftHeight", 0.5f, "복원 키 사용 시 수레를 들어올리는 높이(m).");
			CartUprightRange = cfg.Bind<float>("Cart", "CartUprightRange", 3f, "복원 키가 작동하는 최대 거리(m).");
		}
	}
}
namespace Voyage.CartUpgrade
{
	internal static class CartUpgradeManager
	{
		internal static void Tick()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: 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)
			if (!VoyageConfig.CartUpgradeEnabled.Value || !Input.GetKeyDown(VoyageConfig.UprightKey.Value))
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return;
			}
			GameObject val = VanillaAccess.PlayerHovering(localPlayer);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			Vagon componentInParent = val.GetComponentInParent<Vagon>();
			if ((Object)(object)componentInParent == (Object)null || Vector3.Distance(((Component)localPlayer).transform.position, ((Component)componentInParent).transform.position) > VoyageConfig.CartUprightRange.Value)
			{
				return;
			}
			CartDockComponent component = ((Component)componentInParent).GetComponent<CartDockComponent>();
			if ((Object)(object)component != (Object)null && component.IsDocked())
			{
				((Character)localPlayer).Message((MessageType)2, Lang.T("배에 고정된 수레는 바로 세울 필요가 없습니다.", "A docked cart doesn't need to be uprighted."), 0, (Sprite)null, false);
				return;
			}
			ZNetView component2 = ((Component)componentInParent).GetComponent<ZNetView>();
			if (!((Object)(object)component2 == (Object)null) && component2.IsValid())
			{
				component2.ClaimOwnership();
				Rigidbody val2 = VanillaAccess.VagonBody(componentInParent);
				if ((Object)(object)val2 != (Object)null)
				{
					Vector3 position = val2.position;
					position.y += VoyageConfig.CartUprightLiftHeight.Value;
					val2.position = position;
					Quaternion rotation = val2.rotation;
					Vector3 eulerAngles = ((Quaternion)(ref rotation)).eulerAngles;
					val2.rotation = Quaternion.Euler(0f, eulerAngles.y, 0f);
					val2.linearVelocity = Vector3.zero;
					val2.angularVelocity = Vector3.zero;
				}
				((Character)localPlayer).Message((MessageType)2, Lang.T("수레를 바로 세웠습니다.", "Cart uprighted."), 0, (Sprite)null, false);
			}
		}
	}
	[HarmonyPatch(typeof(Vagon), "Awake")]
	internal static class VagonAwakeUpgradePatch
	{
		private static void Postfix(Vagon __instance)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			if (!VoyageConfig.CartUpgradeEnabled.Value)
			{
				return;
			}
			__instance.m_detachDistance *= VoyageConfig.CartDetachToleranceMultiplier.Value;
			Rigidbody val = VanillaAccess.VagonBody(__instance);
			if ((Object)(object)val != (Object)null)
			{
				Vector3 centerOfMass = val.centerOfMass;
				centerOfMass.y += VoyageConfig.CartCenterOfMassYOffset.Value;
				val.centerOfMass = centerOfMass;
			}
			Rigidbody[] array = VanillaAccess.VagonBodies(__instance);
			if (array == null)
			{
				return;
			}
			Rigidbody[] array2 = array;
			foreach (Rigidbody val2 in array2)
			{
				if (!((Object)(object)val2 == (Object)null))
				{
					val2.angularDamping += VoyageConfig.CartAngularDragBonus.Value;
				}
			}
		}
	}
	[HarmonyPatch(typeof(Vagon), "AttachTo")]
	internal static class VagonAttachToUpgradePatch
	{
		private static void Postfix(Vagon __instance)
		{
			if (VoyageConfig.CartUpgradeEnabled.Value)
			{
				ConfigurableJoint val = VanillaAccess.VagonAttachJoin(__instance);
				if ((Object)(object)val != (Object)null)
				{
					((Joint)val).breakForce = VoyageConfig.CartBreakForce.Value;
				}
			}
		}
	}
}
namespace Voyage.CartDock
{
	internal class CartDockComponent : MonoBehaviour
	{
		private Vagon m_vagon;

		private ZNetView m_nview;

		private ZSyncTransform m_zsync;

		private Rigidbody m_body;

		private Collider[] m_cartColliders;

		private GameObject m_ignoredShipGO;

		private float m_destroyCheckTimer;

		private void Awake()
		{
			m_vagon = ((Component)this).GetComponent<Vagon>();
			m_nview = ((Component)this).GetComponent<ZNetView>();
			m_zsync = ((Component)this).GetComponent<ZSyncTransform>();
			m_body = (((Object)(object)m_vagon != (Object)null) ? VanillaAccess.VagonBody(m_vagon) : null);
			m_cartColliders = ((Component)this).GetComponentsInChildren<Collider>();
			if (IsDocked())
			{
				SetKinematic(kinematic: true);
				if ((Object)(object)m_zsync != (Object)null)
				{
					((Behaviour)m_zsync).enabled = false;
				}
			}
		}

		internal bool IsDocked()
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)m_nview) || !m_nview.IsValid())
			{
				return false;
			}
			ZDOID zDOID = m_nview.GetZDO().GetZDOID("Voyage_DockedShip");
			return !((ZDOID)(ref zDOID)).IsNone();
		}

		internal void DockTo(Ship ship)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: 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)
			if (Object.op_Implicit((Object)(object)m_nview) && m_nview.IsValid())
			{
				m_nview.ClaimOwnership();
				Transform transform = ((Component)ship).transform;
				Vector3 val = transform.InverseTransformPoint(((Component)this).transform.position);
				val.y += VoyageConfig.DockDeckClearance.Value;
				Quaternion val2 = Quaternion.Inverse(transform.rotation) * ((Component)this).transform.rotation;
				ZDO zDO = m_nview.GetZDO();
				zDO.Set("Voyage_DockedShip", ((Component)ship).GetComponent<ZNetView>().GetZDO().m_uid);
				zDO.Set("Voyage_DockOffsetPos", val);
				zDO.Set("Voyage_DockOffsetRot", val2);
				SetKinematic(kinematic: true);
				if ((Object)(object)m_zsync != (Object)null)
				{
					((Behaviour)m_zsync).enabled = false;
				}
			}
		}

		internal void Undock()
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)m_nview) && m_nview.IsValid())
			{
				m_nview.ClaimOwnership();
				m_nview.GetZDO().Set("Voyage_DockedShip", ZDOID.None);
				SetKinematic(kinematic: false);
				if ((Object)(object)m_zsync != (Object)null)
				{
					((Behaviour)m_zsync).enabled = true;
				}
				ApplyIgnoreCollision(m_ignoredShipGO, ignore: false);
				m_ignoredShipGO = null;
				if ((Object)(object)m_body != (Object)null)
				{
					m_body.WakeUp();
					m_body.AddForce(0f, 1f, 0f);
				}
			}
		}

		private void SetKinematic(bool kinematic)
		{
			if ((Object)(object)m_vagon == (Object)null)
			{
				return;
			}
			Rigidbody[] array = VanillaAccess.VagonBodies(m_vagon);
			if (array == null)
			{
				return;
			}
			Rigidbody[] array2 = array;
			foreach (Rigidbody val in array2)
			{
				if (!((Object)(object)val == (Object)null))
				{
					val.isKinematic = kinematic;
				}
			}
		}

		private void ApplyIgnoreCollision(GameObject shipGO, bool ignore)
		{
			if ((Object)(object)shipGO == (Object)null || m_cartColliders == null)
			{
				return;
			}
			Collider[] componentsInChildren = shipGO.GetComponentsInChildren<Collider>();
			Collider[] cartColliders = m_cartColliders;
			foreach (Collider val in cartColliders)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				Collider[] array = componentsInChildren;
				foreach (Collider val2 in array)
				{
					if (!((Object)(object)val2 == (Object)null))
					{
						Physics.IgnoreCollision(val, val2, ignore);
					}
				}
			}
		}

		private void FixedUpdate()
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)m_nview) || !m_nview.IsValid())
			{
				return;
			}
			ZDO zDO = m_nview.GetZDO();
			ZDOID zDOID = zDO.GetZDOID("Voyage_DockedShip");
			if (((ZDOID)(ref zDOID)).IsNone())
			{
				return;
			}
			m_destroyCheckTimer += Time.fixedDeltaTime;
			if (m_destroyCheckTimer > 1f)
			{
				m_destroyCheckTimer = 0f;
				if (ZDOMan.instance != null && ZDOMan.instance.GetZDO(zDOID) == null)
				{
					Undock();
					return;
				}
			}
			GameObject val = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.FindInstance(zDOID) : null);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			if ((Object)(object)val != (Object)(object)m_ignoredShipGO)
			{
				if ((Object)(object)m_ignoredShipGO != (Object)null)
				{
					ApplyIgnoreCollision(m_ignoredShipGO, ignore: false);
				}
				ApplyIgnoreCollision(val, ignore: true);
				m_ignoredShipGO = val;
			}
			Vector3 vec = zDO.GetVec3("Voyage_DockOffsetPos", Vector3.zero);
			Quaternion quaternion = zDO.GetQuaternion("Voyage_DockOffsetRot", Quaternion.identity);
			Transform transform = val.transform;
			Vector3 position = transform.TransformPoint(vec);
			Quaternion rotation = transform.rotation * quaternion;
			if ((Object)(object)m_body != (Object)null)
			{
				m_body.position = position;
				m_body.rotation = rotation;
				Rigidbody component = val.GetComponent<Rigidbody>();
				m_body.linearVelocity = (((Object)(object)component != (Object)null) ? component.linearVelocity : Vector3.zero);
			}
			((Component)this).transform.position = position;
			((Component)this).transform.rotation = rotation;
		}
	}
	internal static class CartDockManager
	{
		internal static void Tick()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (!VoyageConfig.DockingEnabled.Value || !Input.GetKeyDown(VoyageConfig.DockKey.Value))
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return;
			}
			GameObject val = VanillaAccess.PlayerHovering(localPlayer);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			Vagon componentInParent = val.GetComponentInParent<Vagon>();
			if ((Object)(object)componentInParent == (Object)null)
			{
				return;
			}
			CartDockComponent component = ((Component)componentInParent).GetComponent<CartDockComponent>();
			if ((Object)(object)component == (Object)null)
			{
				return;
			}
			if (component.IsDocked())
			{
				component.Undock();
				((Character)localPlayer).Message((MessageType)2, Lang.T("수레 고정을 해제했습니다.", "Cart undocked."), 0, (Sprite)null, false);
				return;
			}
			if (componentInParent.IsAttached())
			{
				((Character)localPlayer).Message((MessageType)2, Lang.T("끌고 있는 중에는 고정할 수 없습니다.", "Cannot dock the cart while pulling it."), 0, (Sprite)null, false);
				return;
			}
			Ship val2 = FindShipBelow(componentInParent);
			if ((Object)(object)val2 == (Object)null)
			{
				((Character)localPlayer).Message((MessageType)2, Lang.T("배 갑판 위에서만 고정할 수 있습니다.", "The cart must be on a ship's deck to dock."), 0, (Sprite)null, false);
				return;
			}
			component.DockTo(val2);
			((Character)localPlayer).Message((MessageType)2, Lang.T("수레를 배에 고정했습니다.", "Cart docked to the ship."), 0, (Sprite)null, false);
		}

		private static Ship FindShipBelow(Vagon vagon)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			float value = VoyageConfig.DockMaxDeckDistance.Value;
			RaycastHit[] array = Physics.RaycastAll(((Component)vagon).transform.position + Vector3.up * 0.5f, Vector3.down, value + 0.5f);
			Array.Sort(array, (RaycastHit a, RaycastHit b) => ((RaycastHit)(ref a)).distance.CompareTo(((RaycastHit)(ref b)).distance));
			RaycastHit[] array2 = array;
			for (int num = 0; num < array2.Length; num++)
			{
				RaycastHit val = array2[num];
				if (!((Component)((RaycastHit)(ref val)).collider).transform.IsChildOf(((Component)vagon).transform))
				{
					Ship componentInParent = ((Component)((RaycastHit)(ref val)).collider).GetComponentInParent<Ship>();
					if ((Object)(object)componentInParent != (Object)null)
					{
						return componentInParent;
					}
				}
			}
			return null;
		}

		internal static List<Vagon> GetCartsDockedTo(ZDOID shipId)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			List<Vagon> list = new List<Vagon>();
			foreach (Vagon item in VanillaAccess.VagonInstances())
			{
				if (!((Object)(object)item == (Object)null))
				{
					ZNetView component = ((Component)item).GetComponent<ZNetView>();
					if (!((Object)(object)component == (Object)null) && component.IsValid() && component.GetZDO().GetZDOID("Voyage_DockedShip") == shipId)
					{
						list.Add(item);
					}
				}
			}
			return list;
		}
	}
	[HarmonyPatch(typeof(Vagon), "Awake")]
	internal static class VagonAwakeDockPatch
	{
		private static void Postfix(Vagon __instance)
		{
			if ((Object)(object)((Component)__instance).GetComponent<CartDockComponent>() == (Object)null)
			{
				((Component)__instance).gameObject.AddComponent<CartDockComponent>();
			}
		}
	}
	[HarmonyPatch(typeof(Vagon), "Interact")]
	internal static class VagonInteractDockPatch
	{
		private static bool Prefix(Vagon __instance, Humanoid character, bool hold, ref bool __result)
		{
			if (hold)
			{
				return true;
			}
			CartDockComponent component = ((Component)__instance).GetComponent<CartDockComponent>();
			if ((Object)(object)component != (Object)null && component.IsDocked())
			{
				((Character)character).Message((MessageType)2, Lang.T("고정된 수레는 끌 수 없습니다.", "A docked cart cannot be pulled."), 0, (Sprite)null, false);
				__result = false;
				return false;
			}
			return true;
		}
	}
}