Decompiled source of LooseEnds v1.2.0

LooseEnds.dll

Decompiled 3 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using HarmonyLib;
using Il2CppFishNet;
using Il2CppFishNet.Connection;
using Il2CppFishNet.Managing;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppScheduleOne.Combat;
using Il2CppScheduleOne.DevUtilities;
using Il2CppScheduleOne.Dragging;
using Il2CppScheduleOne.Employees;
using Il2CppScheduleOne.GameTime;
using Il2CppScheduleOne.Law;
using Il2CppScheduleOne.Map;
using Il2CppScheduleOne.NPCs;
using Il2CppScheduleOne.NPCs.Behaviour;
using Il2CppScheduleOne.Networking;
using Il2CppScheduleOne.PlayerScripts;
using Il2CppScheduleOne.Police;
using Il2CppScheduleOne.Vehicles;
using Il2CppScheduleOne.Vision;
using Il2CppScheduleOne.VoiceOver;
using Il2CppSystem.Collections.Generic;
using LooseEnds;
using LooseEnds.Config;
using LooseEnds.Detection;
using LooseEnds.Killer;
using LooseEnds.Networking;
using LooseEnds.Reaction;
using LooseEnds.Weight;
using MelonLoader;
using MelonLoader.Preferences;
using Microsoft.CodeAnalysis;
using S1API.Lifecycle;
using UnityEngine;
using UnityEngine.AI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(Core), "Loose Ends", "1.2.0", "DooDesch", "https://github.com/DooDesch-Mods/ScheduleOne-LooseEnds")]
[assembly: MelonGame("TVGS", "Schedule I")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("DooDesch")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © DooDesch")]
[assembly: AssemblyFileVersion("1.2.0.0")]
[assembly: AssemblyInformationalVersion("1.2.0+9e8c3eb6deac05ec7a2c0b0e65227b209e94aef1")]
[assembly: AssemblyProduct("LooseEnds")]
[assembly: AssemblyTitle("LooseEnds")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyMetadata("AI_Assisted_Creation", "This assembly was partially created with the assistance of Generative AI.")]
[assembly: AssemblyMetadata("AI_Model_Vendor", "Anthropic/OpenAI")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.2.0.0")]
[module: UnverifiableCode]
[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 DooDesch
{
	internal static class ModVersion
	{
		internal const string Current = "1.2.0";
	}
}
namespace LooseEnds
{
	public sealed class Core : MelonMod
	{
		private const float ScanIntervalSeconds = 0.4f;

		private const float ReconcileIntervalSeconds = 2f;

		private bool _inWorld;

		private float _scanAccum;

		private float _reconcileAccum;

		private int _activeLogState = -1;

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

		internal static string WitnessStatus = "init";

		public static Core Instance { get; private set; }

		public static Instance Log { get; private set; }

		[Conditional("DEBUG")]
		public static void LogDebug(string msg)
		{
			Instance log = Log;
			if (log != null)
			{
				log.Msg(msg);
			}
		}

		internal static void Caught(string where, Exception e)
		{
			if (_reported.Add(where))
			{
				Instance log = Log;
				if (log != null)
				{
					log.Warning("[Caught] " + where + ": " + e.GetType().Name + ": " + e.Message);
				}
			}
		}

		internal static void WarnOnce(string where, string message)
		{
			if (_reported.Add(where))
			{
				Instance log = Log;
				if (log != null)
				{
					log.Warning("[" + where + "] " + message);
				}
			}
		}

		internal static void Failed(string where, Exception e)
		{
			if (_reported.Add(where))
			{
				Instance log = Log;
				if (log != null)
				{
					log.Error("[Failed] " + where + ": " + e.GetType().Name + ": " + e.Message);
				}
			}
		}

		public override void OnInitializeMelon()
		{
			Instance = this;
			Log = ((MelonBase)this).LoggerInstance;
			Preferences.Initialize();
			GameLifecycle.OnSaveStart += ResetState;
			GameLifecycle.OnPreSceneChange += ResetState;
			Log.Msg("Loose Ends v1.2.0 loaded.");
		}

		private static void ResetState()
		{
			ReactionDispatcher.CancelAllCalls();
			SceneSearch.Clear();
			WitnessMemory.Clear();
			CorpseTracker.Clear();
			KillerRegistry.Clear();
			ArrestWatcher.Clear();
			CorpseWeight.RestoreAll();
			Instance log = Log;
			if (log != null)
			{
				log.Msg("[Core] State reset (save or scene change).");
			}
		}

		public override void OnSceneWasLoaded(int buildIndex, string sceneName)
		{
			_inWorld = sceneName == "Main";
		}

		public override void OnSceneWasUnloaded(int buildIndex, string sceneName)
		{
			if (!(sceneName != "Main"))
			{
				_inWorld = false;
				_activeLogState = -1;
				WitnessStatus = "[not in world]";
				ResetState();
			}
		}

		private bool WitnessActive()
		{
			if (!Preferences.Enabled)
			{
				WitnessStatus = "[OFF: disabled in settings]";
				if (_activeLogState != 0)
				{
					Log.Msg("[Core] Disabled via preferences - running vanilla.");
					_activeLogState = 0;
				}
				return false;
			}
			if (Net.IsCoop() && !Preferences.EnableInMultiplayer)
			{
				WitnessStatus = "[OFF: co-op - EnableInMultiplayer is off]";
				if (_activeLogState != 1)
				{
					Log.Msg("[Core] Co-op session - witness system off (EnableInMultiplayer = false).");
					_activeLogState = 1;
				}
				return false;
			}
			if (!Net.IsServer)
			{
				WitnessStatus = "[client - host runs detection]";
				if (_activeLogState != 2)
				{
					Log.Msg("[Core] Not the network authority - witness detection runs on the host.");
					_activeLogState = 2;
				}
				return false;
			}
			WitnessStatus = "[ACTIVE]";
			if (_activeLogState != 3)
			{
				Log.Msg("[Core] Witness system ACTIVE.");
				_activeLogState = 3;
			}
			return true;
		}

		public override void OnUpdate()
		{
			if (!_inWorld || !WitnessActive())
			{
				return;
			}
			ArrestWatcher.Tick();
			float deltaTime = Time.deltaTime;
			SceneSearch.Tick(deltaTime);
			WitnessMemory.Tick(deltaTime);
			_reconcileAccum += deltaTime;
			if (_reconcileAccum >= 2f)
			{
				_reconcileAccum = 0f;
				CorpseTracker.Reconcile();
			}
			if (CorpseTracker.Count == 0)
			{
				_scanAccum = 0f;
				return;
			}
			_scanAccum += deltaTime;
			if (!(_scanAccum < 0.4f))
			{
				_scanAccum = 0f;
				WitnessTick();
			}
		}

		private static void WitnessTick()
		{
			SightingScanner.Scan();
			float time = Time.time;
			float reactionDelaySeconds = Preferences.ReactionDelaySeconds;
			bool oncePerCorpse = Preferences.OncePerCorpse;
			float responseCooldownSeconds = Preferences.ResponseCooldownSeconds;
			foreach (CorpseRecord record in CorpseTracker.Records)
			{
				if (record.Calling)
				{
					ReactionDispatcher.UpdateCall(record, time);
				}
				else
				{
					if (!record.Discovered)
					{
						continue;
					}
					if (record.Dispatched)
					{
						if (!oncePerCorpse && !record.Settled && time - record.DispatchedTime >= responseCooldownSeconds)
						{
							record.Discovered = false;
							record.Dispatched = false;
							record.Discoverer = null;
						}
					}
					else if (!(time - record.FirstSeenTime < reactionDelaySeconds))
					{
						ReactionDispatcher.TryStartResponse(record);
					}
				}
			}
		}
	}
}
namespace LooseEnds.Weight
{
	internal static class CorpseWeight
	{
		private struct Saved
		{
			public Draggable D;

			public int NpcId;

			public float DragMult;

			public Rigidbody Rb;

			public float Drag;

			public float AngularDrag;

			public float Mass;
		}

		private static readonly Dictionary<int, Saved> _active = new Dictionary<int, Saved>();

		private static readonly List<int> _scratch = new List<int>();

		internal static int ActiveCount => _active.Count;

		internal static void OnStartDragging(Draggable d)
		{
			if (!Preferences.Enabled || (Object)(object)d == (Object)null)
			{
				return;
			}
			float corpseWeightMultiplier = Preferences.CorpseWeightMultiplier;
			if (corpseWeightMultiplier <= 1.0001f)
			{
				return;
			}
			int instanceID = ((Object)d).GetInstanceID();
			if (_active.ContainsKey(instanceID))
			{
				return;
			}
			NPC val = BodyOwner(d);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			Rigidbody rigidbody = d._rigidbody;
			if ((Object)(object)rigidbody == (Object)null)
			{
				Instance log = Core.Log;
				if (log != null)
				{
					log.Warning($"[Weight] body draggable id={instanceID} has no Rigidbody - left at vanilla weight.");
				}
			}
			else
			{
				Saved value = new Saved
				{
					D = d,
					NpcId = ((Object)val).GetInstanceID(),
					DragMult = d.DragForceMultiplier,
					Rb = rigidbody,
					Drag = rigidbody.drag,
					AngularDrag = rigidbody.angularDrag,
					Mass = rigidbody.mass
				};
				_active[instanceID] = value;
				d.DragForceMultiplier = Mathf.Max(0.05f, value.DragMult / corpseWeightMultiplier);
				rigidbody.drag = value.Drag + (corpseWeightMultiplier - 1f) * 2f;
				rigidbody.angularDrag = value.AngularDrag + (corpseWeightMultiplier - 1f) * 2f;
				rigidbody.mass = value.Mass * Mathf.Sqrt(corpseWeightMultiplier);
			}
		}

		internal static void OnStopDragging(Draggable d)
		{
			if (!((Object)(object)d == (Object)null))
			{
				int instanceID = ((Object)d).GetInstanceID();
				if (_active.TryGetValue(instanceID, out var value))
				{
					RestoreEntry(value);
					_active.Remove(instanceID);
				}
			}
		}

		private static void RestoreEntry(Saved s)
		{
			try
			{
				if ((Object)(object)s.D != (Object)null)
				{
					s.D.DragForceMultiplier = s.DragMult;
				}
			}
			catch (Exception e)
			{
				Core.Caught("weight: restore DragForceMultiplier (draggable destroyed)", e);
			}
			try
			{
				if ((Object)(object)s.Rb != (Object)null)
				{
					s.Rb.drag = s.Drag;
					s.Rb.angularDrag = s.AngularDrag;
					s.Rb.mass = s.Mass;
				}
			}
			catch (Exception e2)
			{
				Core.Caught("weight: restore Rigidbody (ragdoll destroyed)", e2);
			}
		}

		internal static void RestoreForNpcId(int npcId)
		{
			if (npcId == 0 || _active.Count == 0)
			{
				return;
			}
			_scratch.Clear();
			foreach (KeyValuePair<int, Saved> item in _active)
			{
				if (item.Value.NpcId == npcId)
				{
					RestoreEntry(item.Value);
					_scratch.Add(item.Key);
				}
			}
			for (int i = 0; i < _scratch.Count; i++)
			{
				_active.Remove(_scratch[i]);
			}
			if (_scratch.Count > 0)
			{
				Instance log = Core.Log;
				if (log != null)
				{
					log.Msg($"[Weight] restored the physics of a carried body whose NPC revived (npc={npcId}).");
				}
			}
		}

		internal static void RestoreAll()
		{
			foreach (KeyValuePair<int, Saved> item in _active)
			{
				RestoreEntry(item.Value);
			}
			_active.Clear();
		}

		private static NPC BodyOwner(Draggable d)
		{
			try
			{
				if ((Object)(object)((Il2CppObjectBase)d).TryCast<NPCRagdollDraggable>() == (Object)null)
				{
					return null;
				}
				int instanceID = ((Object)d).GetInstanceID();
				NPC val = ((Component)d).GetComponentInParent<NPC>();
				if ((Object)(object)val == (Object)null)
				{
					List<NPC> nPCRegistry = NPCManager.NPCRegistry;
					int num = nPCRegistry?.Count ?? 0;
					for (int i = 0; i < num; i++)
					{
						if (!((Object)(object)val == (Object)null))
						{
							break;
						}
						NPC val2 = nPCRegistry[i];
						Draggable val3 = (((Object)(object)val2 != (Object)null && (Object)(object)val2.Movement != (Object)null) ? val2.Movement._ragdollDraggable : null);
						if ((Object)(object)val3 != (Object)null && ((Object)val3).GetInstanceID() == instanceID)
						{
							val = val2;
						}
					}
				}
				if ((Object)(object)val == (Object)null)
				{
					Instance log = Core.Log;
					if (log != null)
					{
						log.Warning($"[Weight] ragdoll draggable id={instanceID} belongs to no known NPC - left at vanilla weight.");
					}
					return null;
				}
				NPCHealth health = val.Health;
				return ((Object)(object)health != (Object)null && (health.IsDead || health.IsKnockedOut)) ? val : null;
			}
			catch (Exception e)
			{
				Core.Caught("weight: identify the dragged body", e);
				return null;
			}
		}
	}
}
namespace LooseEnds.Reaction
{
	internal static class CitizenReaction
	{
		internal static void React(NPC discoverer, Vector3 bodyPos)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)discoverer == (Object)null)
			{
				return;
			}
			Alert(discoverer);
			bool flag;
			try
			{
				flag = (Object)(object)((Il2CppObjectBase)discoverer).TryCast<PoliceOfficer>() == (Object)null && (Object)(object)((Il2CppObjectBase)discoverer).TryCast<Employee>() == (Object)null;
			}
			catch (Exception e)
			{
				Core.Caught("reaction: witness role", e);
				return;
			}
			if (!flag)
			{
				return;
			}
			try
			{
				NPCMovement movement = discoverer.Movement;
				Vector3 val = bodyPos - ((Component)discoverer).transform.position;
				val.y = 0f;
				if ((Object)(object)movement != (Object)null && ((Vector3)(ref val)).sqrMagnitude > 0.0001f)
				{
					movement.FaceDirection(((Vector3)(ref val)).normalized, 0.5f);
				}
			}
			catch (Exception e2)
			{
				Core.Caught("reaction: witness faces the body", e2);
			}
		}

		internal static void Alert(NPC npc)
		{
			if ((Object)(object)npc == (Object)null)
			{
				return;
			}
			try
			{
				npc.PlayVO((EVOLineType)4, false);
			}
			catch (Exception e)
			{
				Core.Caught("reaction: alerted voice line", e);
			}
		}
	}
	internal static class ReactionDispatcher
	{
		private const float CallWindowSeconds = 4f;

		private const float CallTimeoutSeconds = 25f;

		private const float CallActivationGrace = 1.5f;

		private const float CallRetryBackoff = 2f;

		private static readonly Dictionary<int, CorpseRecord> _sceneOnlyCalls = new Dictionary<int, CorpseRecord>();

		internal static void TryStartResponse(CorpseRecord rec)
		{
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_029a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b0: 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)
			if (rec == null || rec.Dispatched || rec.Calling)
			{
				return;
			}
			float time = Time.time;
			Player val = ResolveKiller(rec);
			if ((Object)(object)val == (Object)null)
			{
				Instance log = Core.Log;
				if (log != null)
				{
					log.Msg($"[Reaction] corpse={rec.Id} seen, but nobody is to blame - no report.");
				}
				rec.Dispatched = true;
				rec.DispatchedTime = time;
				return;
			}
			if ((Object)(object)rec.Discoverer != (Object)null && !SafeConscious(rec.Discoverer))
			{
				Instance log2 = Core.Log;
				if (log2 != null)
				{
					log2.Msg($"[Reaction] corpse={rec.Id}: witness {SafeName(rec.Discoverer)} is down before reacting - body re-armed.");
				}
				rec.Discovered = false;
				rec.Discoverer = null;
				rec.WaitReason = null;
				return;
			}
			if (!rec.KillerSeen && WitnessSeesKiller(rec.Discoverer, val))
			{
				rec.KillerSeen = true;
				Instance log3 = Core.Log;
				if (log3 != null)
				{
					log3.Msg($"[Reaction] corpse={rec.Id}: witness {SafeName(rec.Discoverer)} now also sees {SafeCode(val)}.");
				}
			}
			if (Preferences.RequirePlayerAlsoSeen && !rec.KillerSeen)
			{
				Wait(rec, "the witness does not see the killer yet");
				return;
			}
			Vector3 val2 = (((Object)(object)rec.Npc != (Object)null) ? CorpseTracker.BodyPosition(rec.Npc) : Vector3.zero);
			if (Preferences.WitnessCallsPolice && !IsPolice(rec.Discoverer))
			{
				if (time < rec.CallRetryAfter)
				{
					Wait(rec, "the witness was fighting, retry shortly");
					return;
				}
				if (IsBusyCalling(rec.Discoverer))
				{
					Wait(rec, "the witness is already on the phone");
					return;
				}
				rec.WaitReason = null;
				if (StartCall(rec, val, val2, time))
				{
					return;
				}
				Instance log4 = Core.Log;
				if (log4 != null)
				{
					log4.Warning($"[Reaction] corpse={rec.Id}: the witness cannot phone - police alerted at once instead.");
				}
			}
			CitizenReaction.React(rec.Discoverer, val2);
			int officers = SceneSearch.CountReport();
			if (rec.KillerSeen)
			{
				DispatchToScene(rec, val, val2);
			}
			else
			{
				SceneSearch.Start(rec, val2, officers);
			}
			rec.Dispatched = true;
			rec.DispatchedTime = time;
		}

		internal static CorpseRecord SceneOnlyCall(CallPoliceBehaviour cpb)
		{
			if (_sceneOnlyCalls.Count == 0 || (Object)(object)cpb == (Object)null)
			{
				return null;
			}
			if (!_sceneOnlyCalls.TryGetValue(((Object)cpb).GetInstanceID(), out var value))
			{
				return null;
			}
			if (!value.Calling || value.ConnectedByMod)
			{
				return null;
			}
			return value;
		}

		internal static void EndSceneOnlyCall(CorpseRecord rec, CallPoliceBehaviour cpb)
		{
			_sceneOnlyCalls.Remove(((Object)cpb).GetInstanceID());
			rec.ConnectedByMod = true;
			rec.CallWasActive = true;
			try
			{
				((Behaviour)cpb).Disable_Networked((NetworkConnection)null);
			}
			catch (Exception e)
			{
				Core.Failed("reaction: hang up a scene-only call", e);
			}
		}

		private static void ForgetSceneOnlyCall(NPC witness)
		{
			if (_sceneOnlyCalls.Count == 0 || (Object)(object)witness == (Object)null)
			{
				return;
			}
			try
			{
				NPCBehaviour behaviour = witness.Behaviour;
				CallPoliceBehaviour val = ((behaviour != null) ? behaviour.CallPoliceBehaviour : null);
				if ((Object)(object)val != (Object)null)
				{
					_sceneOnlyCalls.Remove(((Object)val).GetInstanceID());
				}
			}
			catch (Exception e)
			{
				Core.Caught("reaction: forget a scene-only call", e);
			}
		}

		private static void Wait(CorpseRecord rec, string reason)
		{
			if (!(rec.WaitReason == reason))
			{
				rec.WaitReason = reason;
				Instance log = Core.Log;
				if (log != null)
				{
					log.Msg($"[Reaction] corpse={rec.Id} waits: {reason}.");
				}
			}
		}

		private static bool StartCall(CorpseRecord rec, Player killer, Vector3 bodyPos, float now)
		{
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			NPC discoverer = rec.Discoverer;
			if ((Object)(object)discoverer == (Object)null)
			{
				Instance log = Core.Log;
				if (log != null)
				{
					log.Warning($"[Reaction] corpse={rec.Id}: no witness to call.");
				}
				return false;
			}
			try
			{
				NPCBehaviour behaviour = discoverer.Behaviour;
				CallPoliceBehaviour val = (((Object)(object)behaviour != (Object)null) ? behaviour.CallPoliceBehaviour : null);
				if ((Object)(object)val == (Object)null)
				{
					Instance log2 = Core.Log;
					if (log2 != null)
					{
						log2.Warning("[Reaction] witness " + SafeName(discoverer) + " has no CallPoliceBehaviour.");
					}
					return false;
				}
				CitizenReaction.Alert(discoverer);
				val.ReportedCrime = (Crime)new DeadlyAssault();
				val.Target = killer;
				((Behaviour)val).Enable_Networked();
				rec.Calling = true;
				rec.CallStartTime = now;
				rec.CallWasActive = false;
				rec.ConnectedByMod = false;
				rec.CallKiller = killer;
				rec.ScenePos = bodyPos;
				if (!rec.KillerSeen)
				{
					_sceneOnlyCalls[((Object)val).GetInstanceID()] = rec;
				}
				Instance log3 = Core.Log;
				if (log3 != null)
				{
					log3.Msg($"[Reaction] witness {SafeName(discoverer)} CALLING police for corpse={rec.Id} - " + (rec.KillerSeen ? ("describes " + SafeCode(killer)) : "killer unknown, reports the body") + $" - {4f:F0}s window.");
				}
				return true;
			}
			catch (Exception e)
			{
				Core.Failed("reaction: start the witness call", e);
				return false;
			}
		}

		internal static void UpdateCall(CorpseRecord rec, float now)
		{
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			if (rec == null || !rec.Calling)
			{
				return;
			}
			float num = now - rec.CallStartTime;
			NPC discoverer = rec.Discoverer;
			CallPoliceBehaviour val = SafeCpb(discoverer);
			bool flag = SafeConscious(discoverer);
			bool flag2 = (Object)(object)val != (Object)null && SafeActive(val);
			bool flag3 = (Object)(object)val != (Object)null && SafeEnabled(val);
			if (flag2)
			{
				rec.CallWasActive = true;
			}
			if (rec.ConnectedByMod || (rec.CallWasActive && !flag3 && num >= 4f))
			{
				rec.Calling = false;
				rec.Dispatched = true;
				rec.DispatchedTime = now;
				int officers = SceneSearch.CountReport();
				if (rec.ConnectedByMod)
				{
					Instance log = Core.Log;
					if (log != null)
					{
						log.Msg($"[Reaction] call CONNECTED for corpse={rec.Id} - body reported, killer unknown.");
					}
					SceneSearch.Start(rec, rec.ScenePos, officers);
					return;
				}
				if (!rec.KillerSeen)
				{
					Instance log2 = Core.Log;
					if (log2 != null)
					{
						log2.Warning($"[Reaction] corpse={rec.Id}: the game finished a scene-only call - {SafeCode(rec.CallKiller)} was marked anyway.");
					}
				}
				ForgetSceneOnlyCall(discoverer);
				try
				{
					PlayerCrimeData val2 = (((Object)(object)rec.CallKiller != (Object)null) ? rec.CallKiller.CrimeData : null);
					if ((Object)(object)val2 != (Object)null)
					{
						val2.LastKnownPosition = rec.ScenePos;
					}
					else
					{
						Instance log3 = Core.Log;
						if (log3 != null)
						{
							log3.Warning($"[Reaction] corpse={rec.Id}: suspect has no CrimeData - officers go to the suspect, not the scene.");
						}
					}
				}
				catch (Exception e)
				{
					Core.Failed("reaction: point the patrol cars at the scene", e);
				}
				Instance log4 = Core.Log;
				if (log4 != null)
				{
					log4.Msg($"[Reaction] call CONNECTED for corpse={rec.Id} - {SafeCode(rec.CallKiller)} is the suspect (Investigating), scene ({rec.ScenePos.x:F1},{rec.ScenePos.y:F1},{rec.ScenePos.z:F1}).");
				}
				if (rec.KillerSeen)
				{
					WitnessMemory.Remember(discoverer, rec.CallKiller);
				}
			}
			else if (!flag)
			{
				CancelCall(discoverer);
				rec.Calling = false;
				rec.CallWasActive = false;
				rec.Discovered = false;
				rec.Discoverer = null;
				Instance log5 = Core.Log;
				if (log5 != null)
				{
					log5.Msg($"[Reaction] witness SILENCED before the call connected for corpse={rec.Id} - no police called.");
				}
			}
			else if (((!rec.CallWasActive && num > 1.5f) || (rec.CallWasActive && flag3 && !flag2)) && IsFighting(discoverer))
			{
				CancelCall(discoverer);
				rec.Calling = false;
				rec.CallWasActive = false;
				rec.CallRetryAfter = now + 2f;
				Instance log6 = Core.Log;
				if (log6 != null)
				{
					log6.Msg($"[Reaction] witness is fighting for corpse={rec.Id} - holding at SEEN, calls once combat ends.");
				}
			}
			else if (num > 25f)
			{
				CancelCall(discoverer);
				rec.Calling = false;
				rec.CallWasActive = false;
				rec.Discovered = false;
				rec.Discoverer = null;
				Instance log7 = Core.Log;
				if (log7 != null)
				{
					log7.Warning($"[Reaction] call for corpse={rec.Id} did not resolve within {25f:F0}s - re-armed.");
				}
			}
		}

		internal static void AbortCall(CorpseRecord rec, string reason)
		{
			if (rec != null && rec.Calling)
			{
				CancelCall(rec.Discoverer);
				rec.Calling = false;
				rec.CallWasActive = false;
				Instance log = Core.Log;
				if (log != null)
				{
					log.Msg($"[Reaction] call for corpse={rec.Id} aborted: {reason}.");
				}
			}
		}

		internal static void CancelAllCalls()
		{
			foreach (CorpseRecord record in CorpseTracker.Records)
			{
				if (record.Calling)
				{
					AbortCall(record, "state reset");
				}
			}
			_sceneOnlyCalls.Clear();
		}

		private static void CancelCall(NPC witness)
		{
			if ((Object)(object)witness == (Object)null)
			{
				return;
			}
			ForgetSceneOnlyCall(witness);
			try
			{
				NPCBehaviour behaviour = witness.Behaviour;
				CallPoliceBehaviour val = ((behaviour != null) ? behaviour.CallPoliceBehaviour : null);
				if ((Object)(object)val != (Object)null && ((Behaviour)val).Enabled)
				{
					((Behaviour)val).Disable_Networked((NetworkConnection)null);
				}
			}
			catch (Exception e)
			{
				Core.Caught("reaction: cancel the witness call", e);
			}
		}

		private static bool IsBusyCalling(NPC witness)
		{
			try
			{
				object obj;
				if (witness == null)
				{
					obj = null;
				}
				else
				{
					NPCBehaviour behaviour = witness.Behaviour;
					obj = ((behaviour != null) ? behaviour.CallPoliceBehaviour : null);
				}
				CallPoliceBehaviour val = (CallPoliceBehaviour)obj;
				return (Object)(object)val != (Object)null && ((Behaviour)val).Active;
			}
			catch (Exception e)
			{
				Core.Caught("reaction: read whether the witness is calling", e);
				return false;
			}
		}

		private static bool IsFighting(NPC witness)
		{
			try
			{
				NPCBehaviour val = (((Object)(object)witness != (Object)null) ? witness.Behaviour : null);
				if ((Object)(object)val == (Object)null)
				{
					return false;
				}
				Behaviour activeBehaviour = val.activeBehaviour;
				if ((Object)(object)activeBehaviour == (Object)null)
				{
					return false;
				}
				CombatBehaviour combatBehaviour = val.CombatBehaviour;
				return (Object)(object)combatBehaviour != (Object)null && ((Object)combatBehaviour).GetInstanceID() == ((Object)activeBehaviour).GetInstanceID();
			}
			catch (Exception e)
			{
				Core.Caught("reaction: read whether the witness is fighting", e);
				return false;
			}
		}

		private static CallPoliceBehaviour SafeCpb(NPC witness)
		{
			try
			{
				return ((Object)(object)witness != (Object)null && (Object)(object)witness.Behaviour != (Object)null) ? witness.Behaviour.CallPoliceBehaviour : null;
			}
			catch (Exception e)
			{
				Core.Caught("reaction: read CallPoliceBehaviour", e);
				return null;
			}
		}

		private static bool SafeActive(CallPoliceBehaviour cpb)
		{
			try
			{
				return ((Behaviour)cpb).Active;
			}
			catch (Exception e)
			{
				Core.Caught("reaction: read CallPoliceBehaviour.Active", e);
				return false;
			}
		}

		private static bool SafeEnabled(CallPoliceBehaviour cpb)
		{
			try
			{
				return ((Behaviour)cpb).Enabled;
			}
			catch (Exception e)
			{
				Core.Caught("reaction: read CallPoliceBehaviour.Enabled", e);
				return false;
			}
		}

		private static Player ResolveKiller(CorpseRecord rec)
		{
			if ((Object)(object)rec.Killer != (Object)null)
			{
				return rec.Killer;
			}
			if (Preferences.AttributeUnknownToLocalPlayer && !Net.IsCoop())
			{
				return Player.Local;
			}
			return null;
		}

		private static void DispatchToScene(CorpseRecord rec, Player killer, Vector3 bodyPos)
		{
			//IL_005b: 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_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Expected O, but got Unknown
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Expected I4, but got Unknown
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: 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_00b3: Expected O, but got Unknown
			PlayerCrimeData crimeData = killer.CrimeData;
			if ((Object)(object)crimeData == (Object)null)
			{
				Instance log = Core.Log;
				if (log != null)
				{
					log.Warning($"[Reaction] SCENE corpse={rec.Id} - suspect has no CrimeData; skipping dispatch.");
				}
				return;
			}
			EPursuitLevel val = (EPursuitLevel)Preferences.PursuitLevelInt;
			try
			{
				if (crimeData.CurrentPursuitLevel < val)
				{
					crimeData.SetPursuitLevel(val);
				}
			}
			catch (Exception e)
			{
				Core.Failed("dispatch: SetPursuitLevel", e);
			}
			try
			{
				crimeData.AddCrime((Crime)new DeadlyAssault(), 1);
			}
			catch (Exception e2)
			{
				Core.Failed("dispatch: AddCrime", e2);
			}
			try
			{
				if (Singleton<LawManager>.InstanceExists)
				{
					Singleton<LawManager>.Instance.PoliceCalled(killer, (Crime)new DeadlyAssault());
				}
				else
				{
					Instance log2 = Core.Log;
					if (log2 != null)
					{
						log2.Warning($"[Reaction] SCENE corpse={rec.Id} - no LawManager in the scene; no officers dispatched.");
					}
				}
			}
			catch (Exception e3)
			{
				Core.Failed("dispatch: LawManager.PoliceCalled", e3);
			}
			try
			{
				crimeData.LastKnownPosition = bodyPos;
			}
			catch (Exception e4)
			{
				Core.Failed("dispatch: redirect LastKnownPosition to the scene", e4);
			}
			Instance log3 = Core.Log;
			if (log3 != null)
			{
				log3.Msg($"[Reaction] SCENE corpse={rec.Id} suspect={SafeCode(killer)} pursuit={(int)val} body=({bodyPos.x:F1},{bodyPos.y:F1},{bodyPos.z:F1})");
			}
		}

		internal static bool WitnessSeesKiller(NPC discoverer, Player killer)
		{
			if ((Object)(object)discoverer == (Object)null || (Object)(object)killer == (Object)null)
			{
				return false;
			}
			try
			{
				NPCAwareness awareness = discoverer.Awareness;
				VisionCone val = (((Object)(object)awareness != (Object)null) ? awareness.VisionCone : null);
				return (Object)(object)val != (Object)null && val.IsPlayerVisible(killer);
			}
			catch (Exception e)
			{
				Core.Caught("reaction: VisionCone.IsPlayerVisible", e);
				return false;
			}
		}

		private static bool IsPolice(NPC npc)
		{
			try
			{
				return (Object)(object)npc != (Object)null && (Object)(object)((Il2CppObjectBase)npc).TryCast<PoliceOfficer>() != (Object)null;
			}
			catch (Exception e)
			{
				Core.Caught("reaction: cast witness to PoliceOfficer", e);
				return false;
			}
		}

		private static bool SafeConscious(NPC npc)
		{
			try
			{
				return (Object)(object)npc != (Object)null && npc.IsConscious;
			}
			catch (Exception e)
			{
				Core.Caught("reaction: read witness IsConscious (a destroyed witness reads as silenced)", e);
				return false;
			}
		}

		internal static string SafeCode(Player p)
		{
			if ((Object)(object)p == (Object)null)
			{
				return "nobody";
			}
			try
			{
				if ((Object)(object)Player.Local != (Object)null && ((Object)Player.Local).GetInstanceID() == ((Object)p).GetInstanceID())
				{
					return "you";
				}
				string playerName = p.PlayerName;
				return string.IsNullOrEmpty(playerName) ? p.PlayerCode : playerName;
			}
			catch (Exception e)
			{
				Core.Caught("log: player name", e);
				return "?";
			}
		}

		internal static string SafeName(NPC npc)
		{
			if ((Object)(object)npc == (Object)null)
			{
				return "nobody";
			}
			try
			{
				return npc.FullName;
			}
			catch (Exception e)
			{
				Core.Caught("log: NPC name", e);
				return ((Object)npc).GetInstanceID().ToString();
			}
		}
	}
	internal static class SceneSearch
	{
		private sealed class Search
		{
			public int CorpseId;

			public Player Killer;

			public Vector3 Center;

			public float StartTime;

			public float ArriveTime = -1f;

			public GameObject Root;

			public PatrolGroup Group;

			public int Officers;
		}

		private sealed class Waiting
		{
			public CorpseRecord Rec;

			public Vector3 Center;

			public int Officers;

			public float Since;

			public float NextTry;
		}

		private const float SearchSeconds = 120f;

		private const float TravelSeconds = 240f;

		private const float ArriveRadius = 10f;

		private const float SuspectRadius = 20f;

		private const float WaypointRadius = 6f;

		private const int WaypointCount = 4;

		private const int MaxOfficers = 3;

		private const float TickSeconds = 0.25f;

		private const float WaitForOfficerSeconds = 120f;

		private const float RetrySeconds = 5f;

		private static readonly List<Search> _active = new List<Search>();

		private static readonly List<Waiting> _waiting = new List<Waiting>();

		private static int _reportsDay = int.MinValue;

		private static int _reportsToday;

		private static float _tickAccum;

		internal static int ActiveCount => _active.Count;

		internal static int WaitingCount => _waiting.Count;

		internal static int ReportsToday => _reportsToday;

		internal static int CountReport()
		{
			int num = CurrentDay();
			if (num != _reportsDay)
			{
				_reportsDay = num;
				_reportsToday = 0;
			}
			_reportsToday++;
			return Math.Min(3, _reportsToday);
		}

		internal static void Start(CorpseRecord rec, Vector3 center, int officers)
		{
			//IL_0001: 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_0024: Unknown result type (might be due to invalid IL or missing references)
			if (!TryStart(rec, center, officers))
			{
				float time = Time.time;
				_waiting.Add(new Waiting
				{
					Rec = rec,
					Center = center,
					Officers = officers,
					Since = time,
					NextTry = time + 5f
				});
				Instance log = Core.Log;
				if (log != null)
				{
					log.Msg($"[Search] corpse={rec.Id}: every officer is busy - the report waits up to {120f:F0}s for one.");
				}
			}
		}

		internal static int FreeOfficers(Vector3 point)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				PoliceStation closestPoliceStation = PoliceStation.GetClosestPoliceStation(point);
				if ((Object)(object)closestPoliceStation == (Object)null || closestPoliceStation.OfficerPool == null)
				{
					return -1;
				}
				return closestPoliceStation.OfficerPool.Count;
			}
			catch (Exception e)
			{
				Core.Caught("search: read the station's officer pool", e);
				return -1;
			}
		}

		private static bool TryStart(CorpseRecord rec, Vector3 center, int officers)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Expected O, but got Unknown
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: 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_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: 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_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Expected O, but got Unknown
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_038b: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c7: Unknown result type (might be due to invalid IL or missing references)
			if (!Singleton<LawManager>.InstanceExists)
			{
				Instance log = Core.Log;
				if (log != null)
				{
					log.Warning($"[Search] corpse={rec.Id}: no LawManager in the scene - nobody searches the scene.");
				}
				return true;
			}
			int num = FreeOfficers(center);
			if (num < 0)
			{
				Instance log2 = Core.Log;
				if (log2 != null)
				{
					log2.Warning($"[Search] corpse={rec.Id}: no police station in the scene - nobody searches the scene.");
				}
				return true;
			}
			if (num == 0)
			{
				return false;
			}
			GameObject val = null;
			try
			{
				val = new GameObject($"LooseEnds_SceneSearch_{rec.Id}");
				val.transform.position = center;
				Il2CppReferenceArray<Transform> val2 = new Il2CppReferenceArray<Transform>(4L);
				NavMeshHit val4 = default(NavMeshHit);
				NavMeshHit val5 = default(NavMeshHit);
				for (int i = 0; i < 4; i++)
				{
					float num2 = (float)i * (float)Math.PI * 2f / 4f;
					Vector3 val3 = center + new Vector3(Mathf.Cos(num2), 0f, Mathf.Sin(num2)) * 6f;
					if (NavMesh.SamplePosition(val3, ref val4, 4f, -1))
					{
						val3 = ((NavMeshHit)(ref val4)).position;
					}
					else if (NavMesh.SamplePosition(center, ref val5, 4f, -1))
					{
						val3 = ((NavMeshHit)(ref val5)).position;
					}
					GameObject val6 = new GameObject($"wp{i}");
					val6.transform.SetParent(val.transform, false);
					val6.transform.position = val3;
					((Il2CppArrayBase<Transform>)(object)val2)[i] = val6.transform;
				}
				FootPatrolRoute val7 = val.AddComponent<FootPatrolRoute>();
				val7.RouteName = $"Loose Ends scene {rec.Id}";
				val7.Waypoints = val2;
				val7.StartWaypointIndex = 0;
				PatrolGroup val8 = Singleton<LawManager>.Instance.StartFootpatrol(val7, officers);
				if (val8 == null || val8.Members == null || val8.Members.Count == 0)
				{
					Object.Destroy((Object)(object)val);
					Instance log3 = Core.Log;
					if (log3 != null)
					{
						log3.Warning($"[Search] corpse={rec.Id}: the station had {num} free officer(s), but none joined the patrol.");
					}
					return false;
				}
				_active.Add(new Search
				{
					CorpseId = rec.Id,
					Killer = rec.Killer,
					Center = center,
					StartTime = Time.time,
					Root = val,
					Group = val8,
					Officers = val8.Members.Count
				});
				Instance log4 = Core.Log;
				if (log4 != null)
				{
					log4.Msg($"[Search] corpse={rec.Id}: {val8.Members.Count} of {officers} officer(s) walk to the scene ({center.x:F1},{center.y:F1},{center.z:F1}) - nobody is wanted yet.");
				}
				return true;
			}
			catch (Exception e)
			{
				Core.Failed("search: send officers to the scene", e);
				if ((Object)(object)val != (Object)null)
				{
					Object.Destroy((Object)(object)val);
				}
				return true;
			}
		}

		private static void TickWaiting(float now)
		{
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			for (int num = _waiting.Count - 1; num >= 0; num--)
			{
				Waiting waiting = _waiting[num];
				if (waiting.Rec.Settled)
				{
					_waiting.RemoveAt(num);
					Instance log = Core.Log;
					if (log != null)
					{
						log.Msg($"[Search] corpse={waiting.Rec.Id}: the waiting report was settled by an arrest.");
					}
				}
				else if (!(now < waiting.NextTry))
				{
					if (TryStart(waiting.Rec, waiting.Center, waiting.Officers))
					{
						_waiting.RemoveAt(num);
					}
					else if (now - waiting.Since >= 120f)
					{
						_waiting.RemoveAt(num);
						Instance log2 = Core.Log;
						if (log2 != null)
						{
							log2.Warning($"[Search] corpse={waiting.Rec.Id}: no officer came free within {120f:F0}s - nobody searches the scene.");
						}
					}
					else
					{
						waiting.NextTry = now + 5f;
					}
				}
			}
		}

		internal static void Tick(float dt)
		{
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			if (_active.Count == 0 && _waiting.Count == 0)
			{
				return;
			}
			_tickAccum += dt;
			if (_tickAccum < 0.25f)
			{
				return;
			}
			_tickAccum = 0f;
			float time = Time.time;
			if (_waiting.Count > 0)
			{
				TickWaiting(time);
			}
			for (int num = _active.Count - 1; num >= 0; num--)
			{
				Search search = _active[num];
				List<PoliceOfficer> list = Officers(search);
				if (list.Count == 0)
				{
					End(num, "every officer left the search");
					continue;
				}
				if (search.ArriveTime < 0f)
				{
					if (AnyWithin(list, search.Center, 10f))
					{
						search.ArriveTime = time;
						Instance log = Core.Log;
						if (log != null)
						{
							log.Msg($"[Search] corpse={search.CorpseId}: officers reached the scene after {time - search.StartTime:F0}s, searching for {120f:F0}s.");
						}
					}
					else if (time - search.StartTime > 240f)
					{
						End(num, $"no officer reached the scene within {240f:F0}s");
						continue;
					}
				}
				else if (time - search.ArriveTime > 120f)
				{
					End(num, "time is up, nobody seen near the body");
					continue;
				}
				if (TryFindSuspect(search, list, out var officer, out var suspect))
				{
					End(num, ReactionDispatcher.SafeName((NPC)(object)officer) + " saw " + ReactionDispatcher.SafeCode(suspect) + " near the body");
					Suspect(search, officer, suspect);
				}
			}
		}

		private static List<PoliceOfficer> Officers(Search s)
		{
			List<PoliceOfficer> list = new List<PoliceOfficer>();
			try
			{
				List<NPC> members = s.Group.Members;
				for (int i = 0; i < members.Count; i++)
				{
					NPC val = members[i];
					PoliceOfficer val2 = (((Object)(object)val != (Object)null) ? ((Il2CppObjectBase)val).TryCast<PoliceOfficer>() : null);
					if ((Object)(object)val2 != (Object)null && ((NPC)val2).IsConscious)
					{
						list.Add(val2);
					}
				}
			}
			catch (Exception e)
			{
				Core.Caught("search: read the patrol members", e);
			}
			return list;
		}

		private static bool AnyWithin(List<PoliceOfficer> officers, Vector3 center, float radius)
		{
			//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_0026: Unknown result type (might be due to invalid IL or missing references)
			float num = radius * radius;
			foreach (PoliceOfficer officer in officers)
			{
				try
				{
					Vector3 val = ((Component)officer).transform.position - center;
					if (((Vector3)(ref val)).sqrMagnitude <= num)
					{
						return true;
					}
				}
				catch (Exception e)
				{
					Core.Caught("search: read officer position", e);
				}
			}
			return false;
		}

		private static bool TryFindSuspect(Search s, List<PoliceOfficer> officers, out PoliceOfficer officer, out Player suspect)
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: 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)
			officer = null;
			suspect = null;
			List<Player> playerList = Player.PlayerList;
			if (playerList == null)
			{
				return false;
			}
			float num = 400f;
			for (int i = 0; i < playerList.Count; i++)
			{
				Player val = playerList[i];
				try
				{
					if ((Object)(object)val == (Object)null || val.IsArrested || (Object)(object)val.Health == (Object)null || !val.Health.IsAlive || (Object)(object)val.CrimeData == (Object)null || (int)val.CrimeData.CurrentPursuitLevel != 0)
					{
						continue;
					}
					Vector3 val2 = ((Component)val).transform.position - s.Center;
					if (((Vector3)(ref val2)).sqrMagnitude > num)
					{
						continue;
					}
					foreach (PoliceOfficer officer2 in officers)
					{
						VisionCone val3 = (((Object)(object)((NPC)officer2).Awareness != (Object)null) ? ((NPC)officer2).Awareness.VisionCone : null);
						if ((Object)(object)val3 != (Object)null && val3.IsPlayerVisible(val))
						{
							officer = officer2;
							suspect = val;
							return true;
						}
					}
				}
				catch (Exception e)
				{
					Core.Caught("search: look for a suspect near the body", e);
				}
			}
			return false;
		}

		private static void Suspect(Search s, PoliceOfficer officer, Player suspect)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			bool flag = (Object)(object)s.Killer != (Object)null && ((Object)s.Killer).GetInstanceID() == ((Object)suspect).GetInstanceID();
			try
			{
				PlayerCrimeData crimeData = suspect.CrimeData;
				crimeData.RecordLastKnownPosition(true);
				crimeData.SetPursuitLevel((EPursuitLevel)1);
				if (flag)
				{
					crimeData.AddCrime((Crime)new DeadlyAssault(), 1);
				}
				officer.BeginFootPursuit_Networked(suspect.PlayerCode, true);
				Instance log = Core.Log;
				if (log != null)
				{
					log.Msg($"[Search] corpse={s.CorpseId}: {ReactionDispatcher.SafeCode(suspect)} is the suspect - Investigating{(flag ? ", charged with the murder" : ", not the killer: questioned only")}.");
				}
			}
			catch (Exception e)
			{
				Core.Failed("search: make the player near the body the suspect", e);
			}
		}

		private static void End(int index, string reason)
		{
			Search search = _active[index];
			_active.RemoveAt(index);
			try
			{
				PatrolGroup obj = search.Group;
				if (obj != null)
				{
					obj.DisbandGroup();
				}
			}
			catch (Exception e)
			{
				Core.Caught("search: disband the patrol", e);
			}
			try
			{
				if ((Object)(object)search.Root != (Object)null)
				{
					Object.Destroy((Object)(object)search.Root);
				}
			}
			catch (Exception e2)
			{
				Core.Caught("search: remove the waypoints", e2);
			}
			Instance log = Core.Log;
			if (log != null)
			{
				log.Msg($"[Search] corpse={search.CorpseId}: search over - {reason}.");
			}
		}

		internal static void Clear()
		{
			for (int num = _active.Count - 1; num >= 0; num--)
			{
				End(num, "state reset");
			}
			_waiting.Clear();
			_reportsDay = int.MinValue;
			_reportsToday = 0;
		}

		internal static int CurrentDay()
		{
			try
			{
				return NetworkSingleton<TimeManager>.InstanceExists ? NetworkSingleton<TimeManager>.Instance.ElapsedDays : 0;
			}
			catch (Exception e)
			{
				Core.Caught("search: read the in-game day", e);
				return 0;
			}
		}
	}
	internal static class WitnessMemory
	{
		private sealed class Entry
		{
			public NPC Witness;

			public int WitnessId;

			public Player Killer;

			public int Day;

			public float LastCall = float.MinValue;

			public float PendingUntil = -1f;
		}

		private const float RecallCooldownSeconds = 30f;

		private const float CallResultSeconds = 10f;

		private const float TickSeconds = 0.5f;

		private static readonly List<Entry> _entries = new List<Entry>();

		private static float _tickAccum;

		internal static int Count => _entries.Count;

		internal static void Remember(NPC witness, Player killer)
		{
			if ((Object)(object)witness == (Object)null || (Object)(object)killer == (Object)null)
			{
				return;
			}
			int instanceID = ((Object)witness).GetInstanceID();
			int day = SceneSearch.CurrentDay();
			foreach (Entry entry in _entries)
			{
				if (entry.WitnessId == instanceID && (Object)(object)entry.Killer != (Object)null && ((Object)entry.Killer).GetInstanceID() == ((Object)killer).GetInstanceID())
				{
					entry.Day = day;
					return;
				}
			}
			_entries.Add(new Entry
			{
				Witness = witness,
				WitnessId = instanceID,
				Killer = killer,
				Day = day
			});
			Instance log = Core.Log;
			if (log != null)
			{
				log.Msg($"[Memory] {ReactionDispatcher.SafeName(witness)} will recognise {ReactionDispatcher.SafeCode(killer)} until tomorrow.");
			}
		}

		internal static int ForgetKiller(Player killer)
		{
			int id = ((Object)killer).GetInstanceID();
			return _entries.RemoveAll((Entry e) => (Object)(object)e.Killer == (Object)null || ((Object)e.Killer).GetInstanceID() == id);
		}

		internal static void Tick(float dt)
		{
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_025e: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
			if (_entries.Count == 0)
			{
				return;
			}
			_tickAccum += dt;
			if (_tickAccum < 0.5f)
			{
				return;
			}
			_tickAccum = 0f;
			float time = Time.time;
			int num = SceneSearch.CurrentDay();
			for (int num2 = _entries.Count - 1; num2 >= 0; num2--)
			{
				Entry entry = _entries[num2];
				if (entry.Day != num)
				{
					Instance log = Core.Log;
					if (log != null)
					{
						log.Msg($"[Memory] a new day: {ReactionDispatcher.SafeName(entry.Witness)} forgot {ReactionDispatcher.SafeCode(entry.Killer)}.");
					}
					_entries.RemoveAt(num2);
				}
				else if ((Object)(object)entry.Witness == (Object)null || (Object)(object)entry.Killer == (Object)null)
				{
					Instance log2 = Core.Log;
					if (log2 != null)
					{
						log2.Msg("[Memory] a witness or killer left the game - memory dropped.");
					}
					_entries.RemoveAt(num2);
				}
				else
				{
					bool flag;
					try
					{
						flag = (Object)(object)entry.Witness.Health != (Object)null && !entry.Witness.Health.IsDead;
					}
					catch (Exception e)
					{
						Core.Caught("memory: read witness health", e);
						flag = false;
					}
					if (!flag)
					{
						Instance log3 = Core.Log;
						if (log3 != null)
						{
							log3.Msg($"[Memory] {ReactionDispatcher.SafeName(entry.Witness)} is dead - memory of {ReactionDispatcher.SafeCode(entry.Killer)} dropped.");
						}
						_entries.RemoveAt(num2);
					}
					else if (entry.PendingUntil > 0f)
					{
						EPursuitLevel val = Level(entry.Killer);
						if ((int)val != 0)
						{
							Instance log4 = Core.Log;
							if (log4 != null)
							{
								log4.Msg($"[Memory] call by {ReactionDispatcher.SafeName(entry.Witness)} CONNECTED - {ReactionDispatcher.SafeCode(entry.Killer)} is {val}.");
							}
							entry.PendingUntil = -1f;
						}
						else if (time > entry.PendingUntil)
						{
							Instance log5 = Core.Log;
							if (log5 != null)
							{
								log5.Msg("[Memory] call by " + ReactionDispatcher.SafeName(entry.Witness) + " did not connect (silenced or interrupted).");
							}
							entry.PendingUntil = -1f;
						}
					}
					else if (!(time - entry.LastCall < 30f) && SafeConscious(entry.Witness) && !entry.Killer.IsArrested && (int)Level(entry.Killer) == 0 && ReactionDispatcher.WitnessSeesKiller(entry.Witness, entry.Killer))
					{
						Call(entry, time);
					}
				}
			}
		}

		private static void Call(Entry e, float now)
		{
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Expected O, but got Unknown
			e.LastCall = now;
			try
			{
				CallPoliceBehaviour val = (((Object)(object)e.Witness.Behaviour != (Object)null) ? e.Witness.Behaviour.CallPoliceBehaviour : null);
				if ((Object)(object)val == (Object)null)
				{
					Instance log = Core.Log;
					if (log != null)
					{
						log.Warning("[Memory] " + ReactionDispatcher.SafeName(e.Witness) + " has no CallPoliceBehaviour - cannot call.");
					}
					return;
				}
				if (((Behaviour)val).Enabled)
				{
					Instance log2 = Core.Log;
					if (log2 != null)
					{
						log2.Msg($"[Memory] {ReactionDispatcher.SafeName(e.Witness)} recognised {ReactionDispatcher.SafeCode(e.Killer)} but is already on the phone.");
					}
					return;
				}
				CitizenReaction.Alert(e.Witness);
				val.ReportedCrime = (Crime)new DeadlyAssault();
				val.Target = e.Killer;
				((Behaviour)val).Enable_Networked();
				e.PendingUntil = now + 10f;
				Instance log3 = Core.Log;
				if (log3 != null)
				{
					log3.Msg($"[Memory] {ReactionDispatcher.SafeName(e.Witness)} recognised {ReactionDispatcher.SafeCode(e.Killer)} - CALLING the police.");
				}
			}
			catch (Exception e2)
			{
				Core.Failed("memory: start the recognition call", e2);
			}
		}

		private static EPursuitLevel Level(Player p)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				return (EPursuitLevel)(((Object)(object)p.CrimeData != (Object)null) ? ((int)p.CrimeData.CurrentPursuitLevel) : 0);
			}
			catch (Exception e)
			{
				Core.Caught("memory: read pursuit level", e);
				return (EPursuitLevel)0;
			}
		}

		private static bool SafeConscious(NPC npc)
		{
			try
			{
				return npc.IsConscious;
			}
			catch (Exception e)
			{
				Core.Caught("memory: read witness IsConscious", e);
				return false;
			}
		}

		internal static void Clear()
		{
			_entries.Clear();
		}
	}
}
namespace LooseEnds.Patches
{
	[HarmonyPatch(typeof(CallPoliceBehaviour), "BehaviourUpdate")]
	internal static class CallPoliceBehaviour_BehaviourUpdate_Patch
	{
		private const float CallSeconds = 4f;

		private const int LookPriority = 2;

		private static bool Prefix(CallPoliceBehaviour __instance)
		{
			//IL_004e: 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_005d: 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)
			try
			{
				CorpseRecord corpseRecord = ReactionDispatcher.SceneOnlyCall(__instance);
				if (corpseRecord == null)
				{
					return true;
				}
				NPC npc = ((Behaviour)__instance).Npc;
				if ((Object)(object)npc != (Object)null && (Object)(object)npc.Avatar != (Object)null && (Object)(object)npc.Avatar.LookController != (Object)null)
				{
					npc.Avatar.LookController.OverrideLookTarget(corpseRecord.ScenePos + Vector3.up * 0.3f, 2, true);
				}
				if (__instance.currentCallTime + Time.deltaTime < 4f)
				{
					return true;
				}
				ReactionDispatcher.EndSceneOnlyCall(corpseRecord, __instance);
				return false;
			}
			catch (Exception e)
			{
				Core.Failed("call patch: end a scene-only call before the game marks the killer", e);
				return true;
			}
		}
	}
	[HarmonyPatch(typeof(Draggable), "StartDragging")]
	internal static class Draggable_StartDragging_Patch
	{
		private static void Postfix(Draggable __instance)
		{
			try
			{
				CorpseWeight.OnStartDragging(__instance);
			}
			catch (Exception e)
			{
				Core.Failed("patch Draggable.StartDragging (body weight)", e);
			}
		}
	}
	[HarmonyPatch(typeof(Draggable), "StopDragging")]
	internal static class Draggable_StopDragging_Patch
	{
		private static void Postfix(Draggable __instance)
		{
			try
			{
				CorpseWeight.OnStopDragging(__instance);
			}
			catch (Exception e)
			{
				Core.Failed("patch Draggable.StopDragging (restore body weight)", e);
			}
		}
	}
	[HarmonyPatch(typeof(NPCHealth), "NotifyAttackedByPlayer")]
	internal static class NPCHealth_NotifyAttackedByPlayer_Patch
	{
		private static void Postfix(NPCHealth __instance, Player player)
		{
			try
			{
				KillerRegistry.RecordAttacker(__instance._npc, player);
			}
			catch (Exception e)
			{
				Core.Failed("patch NPCHealth.NotifyAttackedByPlayer (attacker attribution)", e);
			}
		}
	}
	[HarmonyPatch(typeof(NPCHealth), "Die")]
	internal static class NPCHealth_Die_Patch
	{
		private static void Postfix(NPCHealth __instance)
		{
			try
			{
				NPC npc = __instance._npc;
				if ((Object)(object)npc == (Object)null)
				{
					Instance log = Core.Log;
					if (log != null)
					{
						log.Warning("[Killer] NPCHealth.Die on a health component without an NPC - body not tracked.");
					}
				}
				else if (__instance.IsDead)
				{
					Player val = KillerRegistry.RecordKill(npc);
					CorpseTracker.OnNpcDied(npc, val);
					Instance log2 = Core.Log;
					if (log2 != null)
					{
						log2.Msg($"[Killer] {ReactionDispatcher.SafeName(npc)} died, killer={ReactionDispatcher.SafeCode(val)}.");
					}
				}
			}
			catch (Exception e)
			{
				Core.Failed("patch NPCHealth.Die (track the body)", e);
			}
		}
	}
	[HarmonyPatch(typeof(NPCHealth), "KnockOut")]
	internal static class NPCHealth_KnockOut_Patch
	{
		private static void Postfix(NPCHealth __instance)
		{
			try
			{
				if (!Preferences.ReactToKnockedOut)
				{
					return;
				}
				NPC npc = __instance._npc;
				if (!((Object)(object)npc == (Object)null) && __instance.IsKnockedOut)
				{
					Player killer = KillerRegistry.GetKiller(npc);
					CorpseTracker.OnNpcDied(npc, killer);
					Instance log = Core.Log;
					if (log != null)
					{
						log.Msg($"[Killer] {ReactionDispatcher.SafeName(npc)} knocked out, attacker={ReactionDispatcher.SafeCode(killer)}.");
					}
				}
			}
			catch (Exception e)
			{
				Core.Failed("patch NPCHealth.KnockOut (track the body)", e);
			}
		}
	}
}
namespace LooseEnds.Networking
{
	internal static class Net
	{
		internal static bool IsServer
		{
			get
			{
				try
				{
					NetworkManager networkManager = InstanceFinder.NetworkManager;
					return (Object)(object)networkManager != (Object)null && networkManager.IsServer;
				}
				catch (Exception e)
				{
					Core.Caught("net: read NetworkManager.IsServer", e);
					return false;
				}
			}
		}

		internal static bool IsCoop()
		{
			try
			{
				Lobby instance = Singleton<Lobby>.Instance;
				return (Object)(object)instance != (Object)null && instance.IsInLobby && instance.PlayerCount > 1;
			}
			catch (Exception e)
			{
				Core.Caught("net: read the Steam lobby", e);
				return false;
			}
		}
	}
}
namespace LooseEnds.Killer
{
	internal static class ArrestWatcher
	{
		private static readonly Dictionary<int, int> _lastMins = new Dictionary<int, int>();

		internal static void Tick()
		{
			List<Player> playerList = Player.PlayerList;
			if (playerList == null)
			{
				return;
			}
			int count = playerList.Count;
			for (int i = 0; i < count; i++)
			{
				Player val = playerList[i];
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				int instanceID;
				int minsSinceLastArrested;
				try
				{
					PlayerCrimeData crimeData = val.CrimeData;
					if ((Object)(object)crimeData == (Object)null)
					{
						continue;
					}
					instanceID = ((Object)val).GetInstanceID();
					minsSinceLastArrested = crimeData.MinsSinceLastArrested;
					goto IL_005e;
				}
				catch (Exception e)
				{
					Core.Caught("arrest watcher: read player crime data", e);
				}
				continue;
				IL_005e:
				if (_lastMins.TryGetValue(instanceID, out var value) && minsSinceLastArrested < value)
				{
					OnArrested(val, instanceID, value, minsSinceLastArrested);
				}
				_lastMins[instanceID] = minsSinceLastArrested;
			}
		}

		private static void OnArrested(Player p, int id, int prevMins, int mins)
		{
			int value = KillerRegistry.ClearFor(p);
			int value2 = CorpseTracker.SettleFor(p);
			int value3 = WitnessMemory.ForgetKiller(p);
			Instance log = Core.Log;
			if (log != null)
			{
				log.Msg($"[Arrest] {ReactionDispatcher.SafeCode(p)} (player id={id}, mins since arrest {prevMins}->{mins}) arrested - settled {value2} bodies, cleared {value} attributions, {value3} witness memories.");
			}
		}

		internal static void Clear()
		{
			_lastMins.Clear();
		}
	}
	internal static class KillerRegistry
	{
		private struct Attack
		{
			public Player Player;

			public float Time;
		}

		private const float AttributionWindowSeconds = 120f;

		private static readonly Dictionary<int, Attack> _lastAttacker = new Dictionary<int, Attack>();

		private static readonly Dictionary<int, Player> _killer = new Dictionary<int, Player>();

		private static readonly List<int> _scratch = new List<int>();

		internal static void RecordAttacker(NPC npc, Player player)
		{
			if (!((Object)(object)npc == (Object)null) && !((Object)(object)player == (Object)null))
			{
				_lastAttacker[((Object)npc).GetInstanceID()] = new Attack
				{
					Player = player,
					Time = Time.time
				};
			}
		}

		internal static Player RecordKill(NPC npc)
		{
			if ((Object)(object)npc == (Object)null)
			{
				return null;
			}
			int instanceID = ((Object)npc).GetInstanceID();
			if (_lastAttacker.TryGetValue(instanceID, out var value) && (Object)(object)value.Player != (Object)null && Time.time - value.Time <= 120f)
			{
				_killer[instanceID] = value.Player;
				return value.Player;
			}
			return null;
		}

		internal static Player GetKiller(NPC npc)
		{
			if ((Object)(object)npc == (Object)null)
			{
				return null;
			}
			int instanceID = ((Object)npc).GetInstanceID();
			if (_killer.TryGetValue(instanceID, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			if (_lastAttacker.TryGetValue(instanceID, out var value2) && (Object)(object)value2.Player != (Object)null && Time.time - value2.Time <= 120f)
			{
				return value2.Player;
			}
			return null;
		}

		internal static void ForgetId(int id)
		{
			_lastAttacker.Remove(id);
			_killer.Remove(id);
		}

		internal static int ClearFor(Player player)
		{
			if ((Object)(object)player == (Object)null)
			{
				return 0;
			}
			int instanceID = ((Object)player).GetInstanceID();
			int num = 0;
			_scratch.Clear();
			foreach (KeyValuePair<int, Player> item in _killer)
			{
				if ((Object)(object)item.Value == (Object)null || ((Object)item.Value).GetInstanceID() == instanceID)
				{
					_scratch.Add(item.Key);
				}
			}
			for (int i = 0; i < _scratch.Count; i++)
			{
				_killer.Remove(_scratch[i]);
			}
			num += _scratch.Count;
			_scratch.Clear();
			foreach (KeyValuePair<int, Attack> item2 in _lastAttacker)
			{
				if ((Object)(object)item2.Value.Player == (Object)null || ((Object)item2.Value.Player).GetInstanceID() == instanceID)
				{
					_scratch.Add(item2.Key);
				}
			}
			for (int j = 0; j < _scratch.Count; j++)
			{
				_lastAttacker.Remove(_scratch[j]);
			}
			return num + _scratch.Count;
		}

		internal static void PruneStale()
		{
			if (_lastAttacker.Count == 0)
			{
				return;
			}
			float time = Time.time;
			_scratch.Clear();
			foreach (KeyValuePair<int, Attack> item in _lastAttacker)
			{
				if (time - item.Value.Time > 120f && !_killer.ContainsKey(item.Key))
				{
					_scratch.Add(item.Key);
				}
			}
			for (int i = 0; i < _scratch.Count; i++)
			{
				_lastAttacker.Remove(_scratch[i]);
			}
		}

		internal static void Clear()
		{
			_lastAttacker.Clear();
			_killer.Clear();
		}
	}
}
namespace LooseEnds.Detection
{
	internal sealed class CorpseRecord
	{
		public NPC Npc;

		public int Id;

		public Player Killer;

		public bool Discovered;

		public float FirstSeenTime;

		public NPC Discoverer;

		public bool KillerSeen;

		public bool Dispatched;

		public float DispatchedTime;

		public bool Settled;

		public string WaitReason;

		public bool Calling;

		public float CallStartTime;

		public bool CallWasActive;

		public float CallRetryAfter;

		public Player CallKiller;

		public Vector3 ScenePos;

		public bool ConnectedByMod;
	}
	internal static class CorpseTracker
	{
		private static readonly Dictionary<int, CorpseRecord> _corpses = new Dictionary<int, CorpseRecord>();

		private static readonly List<int> _toRemove = new List<int>();

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

		internal static int Count => _corpses.Count;

		internal static Dictionary<int, CorpseRecord>.ValueCollection Records => _corpses.Values;

		internal static void OnNpcDied(NPC npc, Player killer)
		{
			if (!((Object)(object)npc == (Object)null))
			{
				int instanceID = ((Object)npc).GetInstanceID();
				if (!_corpses.TryGetValue(instanceID, out var value))
				{
					value = new CorpseRecord
					{
						Npc = npc,
						Id = instanceID
					};
					_corpses[instanceID] = value;
				}
				if ((Object)(object)killer != (Object)null)
				{
					value.Killer = killer;
				}
			}
		}

		internal static Vector3 BodyPosition(NPC npc)
		{
			//IL_00c5: 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_003c: 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_004b: 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_0089: 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_00cb: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				NPCMovement movement = npc.Movement;
				Draggable val = (((Object)(object)movement != (Object)null) ? movement._ragdollDraggable : null);
				Rigidbody val2 = (((Object)(object)val != (Object)null) ? val._rigidbody : null);
				if ((Object)(object)val2 != (Object)null)
				{
					Vector3 position = val2.position;
					if (((Vector3)(ref position)).sqrMagnitude > 0.01f)
					{
						return position;
					}
					position = ((Component)val2).transform.position;
					if (((Vector3)(ref position)).sqrMagnitude > 0.01f)
					{
						Core.WarnOnce("corpse-rb-zero", "ragdoll Rigidbody of " + ReactionDispatcher.SafeName(npc) + " reports (0,0,0) - using its transform.");
						return position;
					}
					Core.WarnOnce("corpse-rb-transform-zero", "ragdoll of " + ReactionDispatcher.SafeName(npc) + " sits at (0,0,0) - using the NPC root.");
				}
			}
			catch (Exception e)
			{
				Core.Caught("corpse: ragdoll body position", e);
			}
			return ((Component)npc).transform.position;
		}

		internal static void Reconcile()
		{
			bool reactToKnockedOut = Preferences.ReactToKnockedOut;
			try
			{
				List<NPC> nPCRegistry = NPCManager.NPCRegistry;
				if (nPCRegistry != null)
				{
					int count = nPCRegistry.Count;
					for (int i = 0; i < count; i++)
					{
						NPC val = nPCRegistry[i];
						if ((Object)(object)val == (Object)null)
						{
							continue;
						}
						bool flag;
						try
						{
							NPCHealth health = val.Health;
							if ((Object)(object)health == (Object)null)
							{
								continue;
							}
							flag = health.IsDead || (reactToKnockedOut && health.IsKnockedOut);
							goto IL_0079;
						}
						catch (Exception e)
						{
							Core.Caught("reconcile: read NPC health", e);
						}
						continue;
						IL_0079:
						if (flag)
						{
							int instanceID = ((Object)val).GetInstanceID();
							if (!_corpses.ContainsKey(instanceID))
							{
								_corpses[instanceID] = new CorpseRecord
								{
									Npc = val,
									Id = instanceID,
									Killer = KillerRegistry.GetKiller(val)
								};
							}
						}
					}
				}
			}
			catch (Exception e2)
			{
				Core.Caught("reconcile: walk NPC registry", e2);
			}
			_toRemove.Clear();
			_removeReason.Clear();
			foreach (KeyValuePair<int, CorpseRecord> corpse in _corpses)
			{
				NPC npc = corpse.Value.Npc;
				string text = null;
				try
				{
					if ((Object)(object)npc == (Object)null)
					{
						text = "object gone";
					}
					else
					{
						NPCHealth health2 = npc.Health;
						if (!((Object)(object)health2 != (Object)null) || (!health2.IsDead && (!reactToKnockedOut || !health2.IsKnockedOut)))
						{
							text = "revived";
						}
					}
				}
				catch (Exception ex)
				{
					text = "object destroyed (" + ex.GetType().Name + ")";
				}
				if (text != null)
				{
					_toRemove.Add(corpse.Key);
					_removeReason.Add(text);
				}
			}
			for (int j = 0; j < _toRemove.Count; j++)
			{
				int num = _toRemove[j];
				CorpseWeight.RestoreForNpcId(num);
				_corpses.Remove(num);
				KillerRegistry.ForgetId(num);
				Instance log = Core.Log;
				if (log != null)
				{
					log.Msg($"[Corpse] untracked id={num}: {_removeReason[j]} (now {_corpses.Count})");
				}
			}
			KillerRegistry.PruneStale();
		}

		internal static void Clear()
		{
			_corpses.Clear();
		}

		internal static int SettleFor(Player arrested)
		{
			int num = 0;
			int instanceID = ((Object)arrested).GetInstanceID();
			foreach (CorpseRecord value in _corpses.Values)
			{
				if (value.Settled)
				{
					continue;
				}
				Player val = (value.Calling ? value.CallKiller : value.Killer);
				if (!((Object)(object)val != (Object)null) || ((Object)val).GetInstanceID() == instanceID)
				{
					if (value.Calling)
					{
						ReactionDispatcher.AbortCall(value, "killer arrested");
					}
					value.Discovered = true;
					value.Dispatched = true;
					value.Settled = true;
					num++;
				}
			}
			return num;
		}
	}
	internal static class SightingScanner
	{
		private const int MaxChecksPerScan = 64;

		private const float CullMargin = 2f;

		private const float BodyAimHeight = 0.5f;

		private const float EyeHeight = 1.6f;

		private const float NoticeExposureThreshold = 0.4f;

		private static int _observerCursor;

		internal static int LastChecks;

		internal static void Scan()
		{
			//IL_0092: 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_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: 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)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			List<NPC> nPCRegistry = NPCManager.NPCRegistry;
			if (nPCRegistry == null)
			{
				return;
			}
			int count;
			try
			{
				count = nPCRegistry.Count;
			}
			catch (Exception e)
			{
				Core.Caught("scan: NPC registry count", e);
				return;
			}
			if (count == 0)
			{
				return;
			}
			bool requireLineOfSight = Preferences.RequireLineOfSight;
			float bodySightRange = Preferences.BodySightRange;
			float noticeRadius = Preferences.NoticeRadius;
			float num = Mathf.Max(bodySightRange, noticeRadius) + 2f;
			float num2 = num * num;
			int num3 = 0;
			foreach (CorpseRecord record in CorpseTracker.Records)
			{
				if (record.Discovered)
				{
					continue;
				}
				NPC npc = record.Npc;
				if ((Object)(object)npc == (Object)null)
				{
					continue;
				}
				Vector3 val;
				try
				{
					val = CorpseTracker.BodyPosition(npc) + Vector3.up * 0.5f;
				}
				catch (Exception e2)
				{
					Core.Caught("scan: corpse position", e2);
					continue;
				}
				for (int i = 0; i < count; i++)
				{
					if (num3 >= 64)
					{
						AdvanceCursor(num3, count);
						return;
					}
					int num4 = (_observerCursor + i) % count;
					NPC val2 = nPCRegistry[num4];
					if ((Object)(object)val2 == (Object)null || ((Object)val2).GetInstanceID() == record.Id)
					{
						continue;
					}
					Vector3 position;
					try
					{
						NPCHealth health = val2.Health;
						if ((Object)(object)health == (Object)null || health.IsDead || health.IsKnockedOut || !RoleEnabled(val2))
						{
							continue;
						}
						position = ((Component)val2).transform.position;
						goto IL_016f;
					}
					catch (Exception e3)
					{
						Core.Caught("scan: read observer", e3);
					}
					continue;
					IL_016f:
					Vector3 val3 = position - val;
					float sqrMagnitude = ((Vector3)(ref val3)).sqrMagnitude;
					if (sqrMagnitude > num2)
					{
						continue;
					}
					num3++;
					if (CanSee(val2, npc, val, requireLineOfSight, bodySightRange, noticeRadius))
					{
						record.Discovered = true;
						record.FirstSeenTime = Time.time;
						record.Discoverer = val2;
						record.KillerSeen = ReactionDispatcher.WitnessSeesKiller(val2, record.Killer);
						Instance log = Core.Log;
						if (log != null)
						{
							log.Msg($"[Witness] corpse {record.Id} SEEN by {ReactionDispatcher.SafeName(val2)} ({Mathf.Sqrt(sqrMagnitude):F1}m, killer={ReactionDispatcher.SafeCode(record.Killer)}, killer seen={record.KillerSeen}).");
						}
						break;
					}
				}
			}
			AdvanceCursor(num3, count);
			LastChecks = num3;
		}

		private static void AdvanceCursor(int checksUsed, int regCount)
		{
			if (regCount > 0)
			{
				_observerCursor = (_observerCursor + Mathf.Max(1, checksUsed)) % regCount;
			}
		}

		private static bool CanSee(NPC observer, NPC corpse, Vector3 bodyPos, bool requireLos, float sightRange, float noticeRadius)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: 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_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_0091: 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_0069: Unknown result type (might be due to invalid IL or missing references)
			VisionCone val = null;
			try
			{
				NPCAwareness awareness = observer.Awareness;
				val = (((Object)(object)awareness != (Object)null) ? awareness.VisionCone : null);
			}
			catch (Exception e)
			{
				Core.Caught("sight: observer vision cone", e);
			}
			Vector3 val2 = EyeOf(observer, val);
			Vector3 val3 = val2 - bodyPos;
			float magnitude = ((Vector3)(ref val3)).magnitude;
			if (!requireLos)
			{
				return magnitude <= Mathf.Max(sightRange, noticeRadius);
			}
			if (magnitude <= sightRange && (Object)(object)val != (Object)null)
			{
				try
				{
					if (val.IsPointWithinSight(bodyPos, false, (LandVehicle)null))
					{
						return true;
					}
				}
				catch (Exception e2)
				{
					Core.Caught("sight: VisionCone.IsPointWithinSight", e2);
				}
			}
			if (magnitude <= noticeRadius)
			{
				return BodyExposedTo(corpse, observer, val2, noticeRadius, bodyPos, val);
			}
			return false;
		}

		private static bool BodyExposedTo(NPC corpse, NPC observer, Vector3 eye, float range, Vector3 bodyPos, VisionCone cone)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: 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)
			try
			{
				EntityVisibility visibility = corpse.Visibility;
				if ((Object)(object)visibility != (Object)null)
				{
					return visibility.CalculateExposureToPoint(eye, range + 3f, observer) >= 0.4f;
				}
			}
			catch (Exception e)
			{
				Core.Caught("sight: EntityVisibility.CalculateExposureToPoint (falls back to a ray)", e);
			}
			return HasClearPath(eye, bodyPos, cone);
		}

		private static Vector3 EyeOf(NPC observer, VisionCone cone)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if ((Object)(object)cone != (Object)null && (Object)(object)cone.VisionOrigin != (Object)null)
				{
					return cone.VisionOrigin.position;
				}
			}
			catch (Exception e)
			{
				Core.Caught("sight: VisionCone.VisionOrigin", e);
			}
			return ((Component)observer).transform.position + Vector3.up * 1.6f;
		}

		private static bool HasClearPath(Vector3 eye, Vector3 bodyPos, VisionCone cone)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: 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_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: 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_0044: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = bodyPos - eye;
			float magnitude = ((Vector3)(ref val)).magnitude;
			if (magnitude <= 0.6f)
			{
				return true;
			}
			val /= magnitude;
			float num = magnitude - 0.5f;
			try
			{
				if ((Object)(object)cone != (Object)null)
				{
					LayerMask visibilityBlockingLayers = cone.VisibilityBlockingLayers;
					if (((LayerMask)(ref visibilityBlockingLayers)).value != 0)
					{
						return !Physics.Raycast(eye, val, num, ((LayerMask)(ref visibilityBlockingLayers)).value);
					}
				}
			}
			catch (Exception e)
			{
				Core.Caught("sight: occlusion raycast", e);
			}
			return true;
		}

		private static bool RoleEnabled(NPC obs)
		{
			if ((Object)(object)((Il2CppObjectBase)obs).TryCast<PoliceOfficer>() != (Object)null)
			{
				return Preferences.ReactPolice;
			}
			if ((Object)(object)((Il2CppObjectBase)obs).TryCast<Employee>() != (Object)null)
			{
				return Preferences.ReactEmployees;
			}
			return Preferences.ReactCitizens;
		}
	}
}
namespace LooseEnds.Config
{
	internal static class Preferences
	{
		private const string CategoryId = "LooseEnds_01_Main";

		private static MelonPreferences_Category _category;

		private static MelonPreferences_Entry<bool> _enabled;

		private static MelonPreferences_Entry<bool> _enableInMp;

		private static MelonPreferences_Entry<bool> _reactCitizens;

		private static MelonPreferences_Entry<bool> _reactPolice;

		private static MelonPreferences_Entry<bool> _reactEmployees;

		private static MelonPreferences_Entry<bool> _requireLos;

		private static MelonPreferences_Entry<float> _bodySightRange;

		private static MelonPreferences_Entry<float> _noticeRadius;

		private static MelonPreferences_Entry<float> _reactionDelay;

		private static MelonPreferences_Entry<bool> _reactToKnockedOut;

		private static MelonPreferences_Entry<bool> _witnessCallsPolice;

		private static MelonPreferences_Entry<bool> _requirePlayerSeen;

		private static MelonPreferences_Entry<int> _pursuitLevel;

		private static MelonPreferences_Entry<bool> _oncePerCorpse;

		private static MelonPreferences_Entry<float> _responseCooldown;

		private static MelonPreferences_Entry<bool> _attributeUnknownToLocal;

		private static MelonPreferences_Entry<float> _weightMultiplier;

		internal static bool Enabled => _enabled?.Value ?? true;

		internal static bool EnableInMultiplayer => _enableInMp?.Value ?? false;

		internal static bool ReactCitizens => _reactCitizens?.Value ?? true;

		internal static bool ReactPolice => _reactPolice?.Value ?? true;

		internal static bool ReactEmployees => _reactEmployees?.Value ?? false;

		internal static bool RequireLineOfSight => _requireLos?.Value ?? true;

		internal static float BodySightRange => Mathf.Clamp(_bodySightRange?.Value ?? 12f, 4f, 30f);

		internal static float NoticeRadius => Mathf.Clamp(_noticeRadius?.Value ?? 6f, 2f, 15f);

		internal static float ReactionDelaySeconds => Mathf.Clamp(_reactionDelay?.Value ?? 3f, 0f, 30f);

		internal static bool ReactToKnockedOut => _reactToKnockedOut?.Value ?? false;

		internal static bool WitnessCallsPolice => _witnessCallsPolice?.Value ?? true;

		internal static bool RequirePlayerAlsoSeen => _requirePlayerSeen?.Value ?? false;

		internal static int PursuitLevelInt => Mathf.Clamp(_pursuitLevel?.Value ?? 1, 1, 4);

		internal static bool OncePerCorpse => _oncePerCorpse?.Value ?? true;

		internal static float ResponseCooldownSeconds => Mathf.Clamp(_responseCooldown?.Value ?? 60f, 5f, 600f);

		internal static bool AttributeUnknownToLocalPlayer => _attributeUnknownToLocal?.Value ?? true;

		internal static float CorpseWeightMultiplier => Mathf.Clamp(_weightMultiplier?.Value ?? 5f, 1f, 20f);

		internal static void Initialize()
		{
			if (_category == null)
			{
				_category = MelonPreferences.CreateCategory("LooseEnds_01_Main", "Loose Ends");
				_enabled = Create("Enabled", def: true, "Enabled", "Master switch. ON: NPCs who see a dead body react and dragged bodies are heavier. OFF: vanilla.");
				_enableInMp = Create("EnableInMultiplayer", def: true, "Enable in co-op", "Witnesses also react in a co-op lobby. The host runs detection for everyone; only the host's value counts.");
				_reactCitizens = Create("ReactCitizens", def: true, "Citizens react", "Civilian NPCs who see a body call the police.");
				_reactPolice = Create("ReactPolice", def: true, "Police react", "Police officers who see a body report it at once.");
				_reactEmployees = Create("ReactEmployees", def: false, "Employees react", "Your own employees call the police on a body they see.");
				_requireLos = Create("RequireLineOfSight", def: true, "Require line of sight", "ON: walls, dumpsters, buildings, water and cover hide a body. OFF: anyone within 'Body sight range' notices it, through walls too.");
				_bodySightRange = Create("BodySightRange", 12f, "Body sight range (m)", "How far an NPC notices a body lying in their field of view. 4-30.", (ValueValidator)(object)new ValueRange<float>(4f, 30f));
				_noticeRadius = Create("NoticeRadius", 6f, "Close-range notice radius (m)", "An NPC this close notices a body in any direction, not only in front of them. Cover still hides it. 2-15.", (ValueValidator)(object)new ValueRange<float>(2f, 15f));
				_reactionDelay = Create("ReactionDelaySeconds", 3f, "Reaction delay (s)", "Time between seeing a body and reacting to it. 0-30.", (ValueValidator)(object)new ValueRange<float>(0f, 30f));
				_reactToKnockedOut = Create("ReactToKnockedOut", def: false, "React to unconscious NPCs", "Witnesses also react to knocked-out NPCs, not only to dead ones.");
				_witnessCallsPolice = Create("WitnessCallsPolice", def: true, "Witness phones the police", "ON: a civilian witness calls the police over about 4 seconds; knock them out or kill them before the call connects to stop it. OFF: the police are alerted at once. Police officers always report at once.");
				_requirePlayerSeen = Create("RequirePlayerAlsoSeen", def: false, "Killer must also be seen", "ON: a witness reports only once they also see the killer. OFF: a witness who sees only the body reports it, and officers search the scene.");
				_pursuitLevel = Create("PursuitLevel", 1, "Pursuit level (1-4)", "Police status an instant report (police witness, or phone call off) gives a killer the witness saw: 1 Investigating, 2 Under arrest, 3 Wanted, 4 Wanted dead. A phoned report always gives Investigating.", (ValueValidator)(object)new ValueRange<int>(1, 4));
				_oncePerCorpse = Create("OncePerCorpse", def: true, "Report each body once", "ON: a body is reported at most once. OFF: it can be reported again after the cooldown below.");
				_responseCooldown = Create("ResponseCooldownSeconds", 60f, "Report cooldown (s)", "With 'Report each body once' OFF: time before the same body can be reported again. 5-600.", (ValueValidator)(object)new ValueRange<float>(5f, 600f));
				_attributeUnknownToLocal = Create("AttributeUnknownToLocalPlayer", def: true, "Blame you when the killer is unknown", "Single-player only: a body nobody killed (lightning, a fight between NPCs) is blamed on you.");
				_weightMultiplier = Create("CorpseWeightMultiplier", 5f, "Dragged body weight x", "How hard a dragged body (dead or knocked out) resists being pulled and thrown. 1 = vanilla. Your own speed does not change. 1-20.", (ValueValidator)(object)new ValueRange<float>(1f, 20f));
				Instance log = Core.Log;
				if (log != null)
				{
					log.Msg($"[Config] Loaded: Enabled={Enabled}, EnableInMultiplayer={EnableInMultiplayer}, LineOfSight={RequireLineOfSight}, BodySight={BodySightRange:F0}m, Notice={NoticeRadius:F0}m, Call={WitnessCallsPolice}, Pursuit={PursuitLevelInt}, Weight={CorpseWeightMultiplier:F1}x");
				}
			}
		}

		private static MelonPreferences_Entry<T> Create<T>(string id, T def, string name, string desc = null, ValueValidator validator = null)
		{
			if (validator != null)
			{
				return _category.CreateEntry<T>(id, def, name, desc, false, false, validator);
			}
			return _category.CreateEntry<T>(id, def, name, desc, false, false, (ValueValidator)null, (string)null);
		}
	}
}