Decompiled source of Pennywise Enhanced v1.6.0

EmpressPennywise.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
namespace Empress.Pennywise;

public class DeadlightsEffect : MonoBehaviour
{
	internal static DeadlightsEffect Instance;

	private float _total;

	private float _left;

	private AudioListener _listener;

	private AudioLowPassFilter _lowPass;

	private void Awake()
	{
		Instance = this;
	}

	internal void Trigger(float duration)
	{
		_total = Mathf.Max(1f, duration);
		_left = _total;
		try
		{
			if ((Object)(object)PlayerController.instance != (Object)null)
			{
				PlayerController.instance.InputDisable(_total);
			}
		}
		catch (Exception ex)
		{
			PennywisePlugin.Log.LogWarning((object)("Deadlights: InputDisable failed: " + ex.Message));
		}
		try
		{
			if ((Object)(object)GameDirector.instance != (Object)null && (Object)(object)GameDirector.instance.CameraShake != (Object)null)
			{
				GameDirector.instance.CameraShake.Shake(2f, _total);
			}
		}
		catch (Exception ex2)
		{
			PennywisePlugin.Log.LogWarning((object)("Deadlights: CameraShake failed: " + ex2.Message));
		}
		PennywisePlugin.Log.LogInfo((object)$"Deadlights started for local player ({_total:F1}s).");
	}

	private float Envelope()
	{
		return Mathf.Clamp01(Mathf.Min((_total - _left) / 0.5f, _left / 0.8f));
	}

	private void Update()
	{
		if (_left > 0f)
		{
			_left -= Time.deltaTime;
			if ((Object)(object)_listener == (Object)null)
			{
				_listener = Object.FindObjectOfType<AudioListener>();
			}
			if (!((Object)(object)_listener != (Object)null))
			{
				return;
			}
			if ((Object)(object)_lowPass == (Object)null)
			{
				_lowPass = ((Component)_listener).GetComponent<AudioLowPassFilter>();
				if ((Object)(object)_lowPass == (Object)null)
				{
					_lowPass = ((Component)_listener).gameObject.AddComponent<AudioLowPassFilter>();
				}
			}
			((Behaviour)_lowPass).enabled = true;
			_lowPass.cutoffFrequency = Mathf.Lerp(22000f, 450f, Envelope());
		}
		else if ((Object)(object)_lowPass != (Object)null && ((Behaviour)_lowPass).enabled)
		{
			((Behaviour)_lowPass).enabled = false;
		}
	}

	private void OnGUI()
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0018: Invalid comparison between Unknown and I4
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
		if (!(_left <= 0f) && (int)Event.current.type == 7 && PennywiseConfig.DeadlightsScreenTint.Value)
		{
			float num = 0.5f + 0.5f * Mathf.Sin(Time.time * 6f);
			float num2 = Envelope();
			GUI.depth = -1000;
			GUI.color = new Color(1f, 0.55f + 0.1f * num, 0.1f, num2 * (0.3f + 0.15f * num));
			GUI.DrawTexture(new Rect(0f, 0f, (float)Screen.width, (float)Screen.height), (Texture)(object)Texture2D.whiteTexture);
			GUI.color = Color.white;
		}
	}
}
public class PennywiseAnimator : MonoBehaviour
{
	private Transform _head;

	private Transform _armL;

	private Transform _armR;

	private Transform _teeth;

	private Transform _face;

	private Quaternion _headQ;

	private Quaternion _armLQ;

	private Quaternion _armRQ;

	private Vector3 _teethS;

	private Vector3 _faceS;

	private Vector3 _rootS;

	private bool _monster;

	private bool _deadlights;

	private Transform _jaw;

	private Quaternion _jawQ;

	private DeadlightsOrbs _orbs;

	private float _k;

	private float _seed;

	private float _twitchTimer;

	private float _twitchLeft;

	private Vector3 _twitch;

	private static Transform Find(Transform root, string n)
	{
		Transform[] componentsInChildren = ((Component)root).GetComponentsInChildren<Transform>(true);
		foreach (Transform val in componentsInChildren)
		{
			if (((Object)val).name == n)
			{
				return val;
			}
		}
		return null;
	}

	private void Awake()
	{
		//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_00a8: 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)
		//IL_00c6: 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)
		//IL_00e4: 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_0102: Unknown result type (might be due to invalid IL or missing references)
		//IL_0107: Unknown result type (might be due to invalid IL or missing references)
		//IL_0120: Unknown result type (might be due to invalid IL or missing references)
		//IL_0125: Unknown result type (might be due to invalid IL or missing references)
		//IL_0154: Unknown result type (might be due to invalid IL or missing references)
		//IL_0159: Unknown result type (might be due to invalid IL or missing references)
		_seed = Random.Range(0f, 100f);
		_rootS = ((Component)this).transform.localScale;
		_head = Find(((Component)this).transform, "Bone.004");
		_armL = Find(((Component)this).transform, "Bone.005");
		_armR = Find(((Component)this).transform, "Bone.026");
		_teeth = Find(((Component)this).transform, "FINAL Teeth");
		_face = Find(((Component)this).transform, "FINAL Head");
		if (Object.op_Implicit((Object)(object)_head))
		{
			_headQ = _head.localRotation;
		}
		if (Object.op_Implicit((Object)(object)_armL))
		{
			_armLQ = _armL.localRotation;
		}
		if (Object.op_Implicit((Object)(object)_armR))
		{
			_armRQ = _armR.localRotation;
		}
		if (Object.op_Implicit((Object)(object)_teeth))
		{
			_teethS = _teeth.localScale;
		}
		if (Object.op_Implicit((Object)(object)_face))
		{
			_faceS = _face.localScale;
		}
		_jaw = Find(((Component)this).transform, "Bone.003");
		if (Object.op_Implicit((Object)(object)_jaw))
		{
			_jawQ = _jaw.localRotation;
		}
		_orbs = ((Component)this).gameObject.AddComponent<DeadlightsOrbs>();
		_orbs.Initialize(((Component)this).transform);
		if (!Object.op_Implicit((Object)(object)_head))
		{
			PennywisePlugin.Log.LogWarning((object)"PennywiseAnimator: bone 'Bone.004' (head) not found.");
		}
		_twitchTimer = Random.Range(1f, 3f);
	}

	public void SetMonster(bool on)
	{
		_monster = on;
	}

	public void SetDeadlights(bool on)
	{
		_deadlights = on;
		if (Object.op_Implicit((Object)(object)_orbs))
		{
			_orbs.SetActive(on);
		}
	}

	private static Vector3 Noise(float t, float seed)
	{
		//IL_0033: 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)
		return new Vector3(Mathf.PerlinNoise(t, seed) - 0.5f, Mathf.PerlinNoise(t + 17.3f, seed) - 0.5f, Mathf.PerlinNoise(t + 41.7f, seed) - 0.5f) * 2f;
	}

	private void LateUpdate()
	{
		//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_010b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0125: Unknown result type (might be due to invalid IL or missing references)
		//IL_012a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0188: Unknown result type (might be due to invalid IL or missing references)
		//IL_0195: Unknown result type (might be due to invalid IL or missing references)
		//IL_019b: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_014c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0151: Unknown result type (might be due to invalid IL or missing references)
		//IL_0152: Unknown result type (might be due to invalid IL or missing references)
		//IL_0157: Unknown result type (might be due to invalid IL or missing references)
		//IL_0138: Unknown result type (might be due to invalid IL or missing references)
		//IL_013a: Unknown result type (might be due to invalid IL or missing references)
		//IL_013f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0144: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01db: 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_01fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_0246: Unknown result type (might be due to invalid IL or missing references)
		//IL_024b: 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_030a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0321: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ab: Unknown result type (might be due to invalid IL or missing references)
		_k = Mathf.MoveTowards(_k, _monster ? 1f : 0f, Time.deltaTime * 1.5f);
		float num = Time.time + _seed;
		float num2 = Mathf.Lerp(0.7f, 2.4f, _k);
		_twitchTimer -= Time.deltaTime;
		if (_twitchTimer <= 0f)
		{
			_twitch = new Vector3(Random.Range(-40f, 40f), Random.Range(-60f, 60f), Random.Range(-40f, 40f));
			_twitchLeft = 0.12f;
			_twitchTimer = Mathf.Lerp(Random.Range(1.5f, 4f), Random.Range(0.4f, 1.2f), _k);
		}
		_twitchLeft -= Time.deltaTime;
		if (Object.op_Implicit((Object)(object)_head))
		{
			Vector3 val = Noise(num * num2, 1.1f) * Mathf.Lerp(12f, 55f, _k);
			if (_twitchLeft > 0f)
			{
				val += _twitch;
			}
			_head.localRotation = _headQ * Quaternion.Euler(val);
		}
		float num3 = 8f + 40f * _k;
		if (Object.op_Implicit((Object)(object)_armL))
		{
			_armL.localRotation = _armLQ * Quaternion.Euler(Noise(num * num2, 7.7f) * num3);
		}
		if (Object.op_Implicit((Object)(object)_armR))
		{
			_armR.localRotation = _armRQ * Quaternion.Euler(Noise(num * num2, 13.3f) * num3);
		}
		if (Object.op_Implicit((Object)(object)_teeth))
		{
			_teeth.localScale = Vector3.Scale(_teethS, new Vector3(1f, 1f + 0.5f * _k + 0.15f * _k * Mathf.Sin(num * 18f), 1f + 0.4f * _k));
		}
		if (Object.op_Implicit((Object)(object)_jaw))
		{
			_jaw.localRotation = _jawQ * Quaternion.Euler((_deadlights ? 25f : 0f) + 5f * _k * Mathf.Sin(num * 5f), 0f, 0f);
		}
		if (Object.op_Implicit((Object)(object)_face))
		{
			_face.localScale = _faceS * (1f + 0.12f * _k * (0.5f + 0.5f * Mathf.Sin(num * 9f)));
		}
		((Component)this).transform.localScale = _rootS * (1f + 0.3f * _k);
	}
}
internal sealed class DeadlightsOrbs : MonoBehaviour
{
	private readonly Transform[] _orbs = (Transform[])(object)new Transform[3];

	private readonly Light[] _lights = (Light[])(object)new Light[3];

	private readonly Material[] _materials = (Material[])(object)new Material[3];

	private Transform _root;

	private Transform _anchor;

	private Renderer _mouthRenderer;

	private Vector3 _mouthWorld;

	private Vector3 _mouthForward;

	private Vector3 _mouthRight;

	private Vector3 _mouthUp;

	private bool _active;

	private float _seed;

	internal void Initialize(Transform root)
	{
		//IL_0227: Unknown result type (might be due to invalid IL or missing references)
		//IL_0155: Unknown result type (might be due to invalid IL or missing references)
		//IL_015c: Expected O, but got Unknown
		//IL_018c: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01df: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
		_root = root;
		_seed = Random.Range(0f, 100f);
		_anchor = FindNamed(root, "FINAL Teeth") ?? FindNamed(root, "VTeethF") ?? FindNamed(root, "Pennywise Face") ?? FindNamed(root, "FINAL Head");
		if ((Object)(object)_anchor != (Object)null)
		{
			_mouthRenderer = ((Component)_anchor).GetComponentInChildren<Renderer>(true);
		}
		if ((Object)(object)_mouthRenderer == (Object)null)
		{
			Transform val = FindNamed(root, "FINAL Head") ?? FindNamed(root, "Pennywise Face");
			if ((Object)(object)val != (Object)null)
			{
				_mouthRenderer = ((Component)val).GetComponentInChildren<Renderer>(true);
			}
		}
		Shader val2 = Shader.Find("Unlit/Color") ?? Shader.Find("Sprites/Default") ?? Shader.Find("Standard");
		Color val5 = default(Color);
		for (int i = 0; i < 3; i++)
		{
			GameObject val3 = GameObject.CreatePrimitive((PrimitiveType)0);
			((Object)val3).name = "Pennywise_Deadlight_" + (i + 1);
			val3.transform.SetParent(root, true);
			Collider component = val3.GetComponent<Collider>();
			if ((Object)(object)component != (Object)null)
			{
				Object.Destroy((Object)(object)component);
			}
			SetWorldDiameter(val3.transform, 0.05f);
			Renderer component2 = val3.GetComponent<Renderer>();
			if ((Object)(object)val2 != (Object)null)
			{
				Material val4 = new Material(val2);
				((Color)(ref val5))..ctor(1f, 0.78f, 0.015f, 1f);
				if (val4.HasProperty("_Color"))
				{
					val4.SetColor("_Color", val5);
				}
				if (val4.HasProperty("_BaseColor"))
				{
					val4.SetColor("_BaseColor", val5);
				}
				if (val4.HasProperty("_EmissionColor"))
				{
					val4.EnableKeyword("_EMISSION");
					val4.SetColor("_EmissionColor", new Color(1f, 0.62f, 0.005f) * 1.15f);
				}
				component2.material = val4;
				_materials[i] = val4;
			}
			Light val6 = val3.AddComponent<Light>();
			val6.type = (LightType)2;
			val6.color = new Color(1f, 0.72f, 0.015f);
			val6.range = 3f;
			val6.intensity = 1.5f;
			_lights[i] = val6;
			_orbs[i] = val3.transform;
			val3.SetActive(false);
		}
		if ((Object)(object)_mouthRenderer == (Object)null)
		{
			PennywisePlugin.Log.LogWarning((object)"Deadlights: no face/teeth renderer found; using a conservative head-relative mouth position.");
		}
	}

	private static void SetWorldDiameter(Transform t, float diameter)
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: 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_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: 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_0067: Unknown result type (might be due to invalid IL or missing references)
		Vector3 val = (((Object)(object)t.parent != (Object)null) ? t.parent.lossyScale : Vector3.one);
		t.localScale = new Vector3(diameter / Mathf.Max(0.001f, Mathf.Abs(val.x)), diameter / Mathf.Max(0.001f, Mathf.Abs(val.y)), diameter / Mathf.Max(0.001f, Mathf.Abs(val.z)));
	}

	internal void SetActive(bool value)
	{
		_active = value;
		for (int i = 0; i < _orbs.Length; i++)
		{
			if ((Object)(object)_orbs[i] != (Object)null)
			{
				((Component)_orbs[i]).gameObject.SetActive(value);
			}
		}
	}

	private void LateUpdate()
	{
		//IL_0039: 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)
		//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_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: 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_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_008f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: 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_00a4: 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_00ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00de: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e3: 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_012d: Unknown result type (might be due to invalid IL or missing references)
		//IL_012f: 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_013d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0150: Unknown result type (might be due to invalid IL or missing references)
		if (!_active || (Object)(object)_root == (Object)null)
		{
			return;
		}
		Bounds bounds = default(Bounds);
		if ((Object)(object)_mouthRenderer != (Object)null)
		{
			bounds = _mouthRenderer.bounds;
		}
		else
		{
			Vector3 val = _root.position + _root.up * 1.45f;
			((Bounds)(ref bounds))..ctor(val, Vector3.one * 0.18f);
		}
		Transform obj = (((Object)(object)_anchor != (Object)null) ? _anchor : _root);
		Vector3 forward = obj.forward;
		Vector3 right = obj.right;
		Vector3 up = obj.up;
		Vector3 val2 = ((Bounds)(ref bounds)).center - up * (((Bounds)(ref bounds)).extents.y * 0.3f) + forward * (((Bounds)(ref bounds)).extents.z * 0.45f);
		float num = Mathf.Clamp(((Bounds)(ref bounds)).extents.x * 0.28f, 0.018f, 0.035f);
		for (int i = 0; i < 3; i++)
		{
			if (!((Object)(object)_orbs[i] == (Object)null))
			{
				_orbs[i].position = val2 + right * ((float)(i - 1) * num);
				_orbs[i].rotation = Quaternion.identity;
				float num2 = 0.82f + 0.18f * Mathf.Sin(Time.time * (5f + (float)i * 1.1f) + _seed + (float)i);
				SetWorldDiameter(_orbs[i], 0.045f + 0.01f * num2);
				if ((Object)(object)_lights[i] != (Object)null)
				{
					_lights[i].intensity = 1.2f + 0.5f * num2;
				}
			}
		}
	}

	private static Transform FindNamed(Transform root, string name)
	{
		Transform[] componentsInChildren = ((Component)root).GetComponentsInChildren<Transform>(true);
		foreach (Transform val in componentsInChildren)
		{
			if (((Object)val).name == name)
			{
				return val;
			}
		}
		return null;
	}

	private void OnDestroy()
	{
		for (int i = 0; i < _materials.Length; i++)
		{
			if ((Object)(object)_materials[i] != (Object)null)
			{
				Object.Destroy((Object)(object)_materials[i]);
			}
		}
	}
}
internal sealed class PennywiseAppearance : MonoBehaviour
{
	private static readonly int ColorId = Shader.PropertyToID("_Color");

	private static readonly int BaseColorId = Shader.PropertyToID("_BaseColor");

	private Renderer[] _renderers;

	private MaterialPropertyBlock _block;

	private void Awake()
	{
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0018: Expected O, but got Unknown
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
		_renderers = ((Component)this).GetComponentsInChildren<Renderer>(true);
		_block = new MaterialPropertyBlock();
		int num = 0;
		Renderer[] renderers = _renderers;
		foreach (Renderer val in renderers)
		{
			if (!((Object)(object)val == (Object)null))
			{
				string text = HierarchyPath(((Component)val).transform).ToLowerInvariant();
				if (text.Contains("hair") || text.Contains("sculpt hair"))
				{
					val.GetPropertyBlock(_block);
					_block.SetColor(ColorId, new Color(1f, 0.78f, 0.66f, 1f));
					_block.SetColor(BaseColorId, new Color(1f, 0.78f, 0.66f, 1f));
					val.SetPropertyBlock(_block);
					num++;
				}
			}
		}
		ManualLogSource log = PennywisePlugin.Log;
		if (log != null)
		{
			log.LogInfo((object)$"Appearance pass: {num} hair renderer(s) tinted; original mesh/textures preserved.");
		}
	}

	private static string HierarchyPath(Transform t)
	{
		string text = (((Object)(object)t != (Object)null) ? ((Object)t).name : string.Empty);
		while ((Object)(object)t != (Object)null && (Object)(object)t.parent != (Object)null)
		{
			t = t.parent;
			text = ((Object)t).name + "/" + text;
		}
		return text;
	}
}
internal static class PennywiseConfig
{
	internal static ConfigEntry<float> SpawnChance;

	internal static ConfigEntry<float> Volume;

	internal static ConfigEntry<bool> EnableBalloon;

	internal static ConfigEntry<float> BalloonSpawnChance;

	internal static ConfigEntry<float> StalkingDuration;

	internal static ConfigEntry<float> AttackSpeed;

	internal static ConfigEntry<float> BluffChance;

	internal static ConfigEntry<float> BalloonRelocateInterval;

	internal static ConfigEntry<float> DecoyBalloonInterval;

	internal static ConfigEntry<float> DecoyTrapChance;

	internal static ConfigEntry<float> DarkAppearanceChance;

	internal static ConfigEntry<bool> DeadlightsScreenTint;

	internal static ConfigEntry<bool> LethalAttacks;

	internal static ConfigEntry<float> JumpscareChance;

	internal static ConfigEntry<float> DifficultyMultiplier;

	internal static ConfigEntry<float> DeadlightsChance;

	internal static ConfigEntry<float> DeadlightsDuration;

	internal static ConfigEntry<float> TransformationChance;

	internal static ConfigEntry<float> CorridorAppearanceChance;

	internal static ConfigEntry<bool> EnableSeenDespawn;

	internal static ConfigEntry<bool> EnableVoiceProvocations;

	internal static ConfigEntry<float> ReattackDelayMinutes;

	internal static ConfigEntry<int> VoicesPerQuietPeriod;

	internal static ConfigEntry<float> MimicChance;

	internal static float Difficulty => Mathf.Clamp(DifficultyMultiplier.Value, 0.25f, 4f);

	private static AcceptableValueRange<float> Unit => new AcceptableValueRange<float>(0f, 1f);

	internal static void Bind(ConfigFile c)
	{
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Expected O, but got Unknown
		//IL_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_0061: Expected O, but got Unknown
		//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00aa: Expected O, but got Unknown
		//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e2: Expected O, but got Unknown
		//IL_0110: Unknown result type (might be due to invalid IL or missing references)
		//IL_011a: Expected O, but got Unknown
		//IL_013e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0148: Expected O, but got Unknown
		//IL_0176: Unknown result type (might be due to invalid IL or missing references)
		//IL_0180: Expected O, but got Unknown
		//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b8: Expected O, but got Unknown
		//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e6: Expected O, but got Unknown
		//IL_0225: Unknown result type (might be due to invalid IL or missing references)
		//IL_022f: Expected O, but got Unknown
		//IL_0253: Unknown result type (might be due to invalid IL or missing references)
		//IL_025d: Expected O, but got Unknown
		//IL_0281: Unknown result type (might be due to invalid IL or missing references)
		//IL_028b: Expected O, but got Unknown
		//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d4: Expected O, but got Unknown
		//IL_031d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0327: Expected O, but got Unknown
		//IL_034a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0354: Expected O, but got Unknown
		//IL_0378: Unknown result type (might be due to invalid IL or missing references)
		//IL_0382: Expected O, but got Unknown
		//IL_03cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_03d5: Expected O, but got Unknown
		//IL_03f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0403: Expected O, but got Unknown
		//IL_0427: Unknown result type (might be due to invalid IL or missing references)
		//IL_0431: Expected O, but got Unknown
		SpawnChance = c.Bind<float>("1. Spawn", "SpawnChance", 0.15f, new ConfigDescription("Шанс появления Пеннивайза на уровне [0..1]. 0 = мод выключен.", (AcceptableValueBase)(object)Unit, Array.Empty<object>()));
		DifficultyMultiplier = c.Bind<float>("1. Spawn", "DifficultyMultiplier", 1f, new ConfigDescription("Общая сложность: ускоряет атаку, сокращает задержку появления и число 'ложных' появлений до атаки. 1 = как в оригинале.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.25f, 4f), Array.Empty<object>()));
		EnableBalloon = c.Bind<bool>("2. Balloon", "EnableBalloon", true, "Включить красный шарик (стадия, на которой его можно лопнуть).");
		BalloonSpawnChance = c.Bind<float>("2. Balloon", "BalloonSpawnChance", 1f, new ConfigDescription("Шанс, что цепочка начнётся с шарика. Если не выпало — Пеннивайз сразу начинает преследование без шанса лопнуть шарик.", (AcceptableValueBase)(object)Unit, Array.Empty<object>()));
		BalloonRelocateInterval = c.Bind<float>("2. Balloon", "BalloonRelocateInterval", 30f, new ConfigDescription("Шарик периодически замирает и исчезает/появляется в другом месте. Это средний интервал смены поведения (сек). 0 = шарик просто всё время летит за игроком.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 120f), Array.Empty<object>()));
		DecoyBalloonInterval = c.Bind<float>("2. Balloon", "DecoyBalloonInterval", 90f, new ConfigDescription("Средний интервал (сек), с которым вне встречи с Пеннивайзом появляются одиночные шарики-приманки. Они стоят на месте 25-50 секунд и исчезают. 0 = выключено.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 600f), Array.Empty<object>()));
		DecoyTrapChance = c.Bind<float>("2. Balloon", "DecoyTrapChance", 0.25f, new ConfigDescription("Шанс, что шарик-приманка окажется ловушкой: если его лопнуть, рядом мгновенно появится Пеннивайз и атакует (смертельно, если включено LethalAttacks).", (AcceptableValueBase)(object)Unit, Array.Empty<object>()));
		StalkingDuration = c.Bind<float>("3. Behaviour", "StalkingDuration", 2f, new ConfigDescription("Сколько секунд Пеннивайз стоит и наблюдает при каждом появлении вдали.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 15f), Array.Empty<object>()));
		AttackSpeed = c.Bind<float>("3. Behaviour", "AttackSpeed", 9f, new ConfigDescription("Скорость рывка во время атаки (оригинал: 9).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 30f), Array.Empty<object>()));
		BluffChance = c.Bind<float>("3. Behaviour", "BluffChance", 0.5f, new ConfigDescription("Шанс обманной атаки: подбегает, останавливается в нескольких метрах и исчезает (оригинал: 0.5).", (AcceptableValueBase)(object)Unit, Array.Empty<object>()));
		LethalAttacks = c.Bind<bool>("3. Behaviour", "LethalAttacks", true, "Если выключить, Пеннивайз никогда не убивает (только пугает): урон-коллайдер модели отключён. Решение хоста.");
		JumpscareChance = c.Bind<float>("3. Behaviour", "JumpscareChance", 0.1f, new ConfigDescription("Шанс, что появление на стадии преследования будет внезапным: за спиной игрока, 4-8 м.", (AcceptableValueBase)(object)Unit, Array.Empty<object>()));
		CorridorAppearanceChance = c.Bind<float>("3. Behaviour", "CorridorAppearanceChance", 0.25f, new ConfigDescription("Шанс, что Пеннивайз появится в зоне прямой видимости вдали (конец коридора, 15-35 м).", (AcceptableValueBase)(object)Unit, Array.Empty<object>()));
		DarkAppearanceChance = c.Bind<float>("3. Behaviour", "DarkAppearanceChance", 0.2f, new ConfigDescription("Шанс, что Пеннивайз появится в тёмной зоне (рядом нет включённых источников света), 8-30 м от цели.", (AcceptableValueBase)(object)Unit, Array.Empty<object>()));
		EnableSeenDespawn = c.Bind<bool>("3. Behaviour", "EnableSeenDespawn", true, "Пеннивайз исчезает, если игрок смотрел прямо на него около секунды.");
		Volume = c.Bind<float>("4. Audio", "Volume", 1f, new ConfigDescription("Громкость звуков Пеннивайза [0..1].", (AcceptableValueBase)(object)Unit, Array.Empty<object>()));
		EnableVoiceProvocations = c.Bind<bool>("4. Audio", "EnableVoiceProvocations", true, "Голосовые провокации между встречами (шёпот, смех, детские голоса) рядом с целью. Файлы: whisper*.ogg, child*.ogg, laugh*.ogg рядом с DLL; если их нет, смех берётся из penny*.ogg с изменённой тональностью.");
		ReattackDelayMinutes = c.Bind<float>("3. Behaviour", "ReattackDelayMinutes", 10f, new ConfigDescription("Через сколько минут после окончания встречи (например, после обманной атаки) Пеннивайз попробует снова. Охота прекращается, если кого-то убили или игрок лопнул шарик.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 60f), Array.Empty<object>()));
		VoicesPerQuietPeriod = c.Bind<int>("4. Audio", "VoicesPerQuietPeriod", 3, new ConfigDescription("Сколько звуков (шёпот, смех, детские голоса) прозвучит между встречами. Они чаще ближе к следующей атаке. 0 = без звуков.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10), Array.Empty<object>()));
		DeadlightsChance = c.Bind<float>("5. Special", "DeadlightsChance", 0.1f, new ConfigDescription("Шанс, что вместо обычной атаки произойдёт Deadlights: три объёмных огонька в области пасти, приглушение звука, цель теряет управление. 0 = выключено.", (AcceptableValueBase)(object)Unit, Array.Empty<object>()));
		DeadlightsScreenTint = c.Bind<bool>("5. Special", "DeadlightsScreenTint", true, "Оранжевое свечение экрана у цели во время Deadlights.");
		DeadlightsDuration = c.Bind<float>("5. Special", "DeadlightsDuration", 4f, new ConfigDescription("Длительность Deadlights (сек). Если рядом (до 12 м) есть другой живой игрок, цель выживает.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1.5f, 10f), Array.Empty<object>()));
		TransformationChance = c.Bind<float>("5. Special", "TransformationChance", 0.35f, new ConfigDescription("Шанс монструозной трансформации во время атаки (увеличение, пасть, неестественные движения). 0 = выключено.", (AcceptableValueBase)(object)Unit, Array.Empty<object>()));
		MimicChance = c.Bind<float>("6. Reserved", "MimicChance", 0.1f, new ConfigDescription("Имитация игрока. Механика пока НЕ реализована.", (AcceptableValueBase)(object)Unit, Array.Empty<object>()));
	}
}
[RequireComponent(typeof(NavMeshAgent))]
public class PennywiseController : MonoBehaviour
{
	public enum EnemyType
	{
		Balloon,
		Stalker,
		Clown,
		Decoy
	}

	public EnemyType Type;

	private NavMeshAgent _agent;

	private PlayerAvatar _targetPlayer;

	private int _targetViewId;

	private int _stalkCount;

	private int _mode;

	private float _spawnTime;

	private Animator _anim;

	private PennywiseAnimator _procAnim;

	private AudioSource _audioSrc;

	private bool _charging;

	private bool _balloonFollowing;

	private float _balloonFollowTimer;

	private float _netSendTimer;

	private bool _hasNet;

	private Vector3 _netPos;

	private float _netYaw;

	private bool _wasHost;

	private float _bTimer;

	private bool _bIdle;

	private bool _trap;

	private bool _decoyPopped;

	private float _decoyLifetime;

	private Vector3 _basePos;

	public void Setup(int targetViewID, EnemyType type, int stalkCount, int mode)
	{
		_targetViewId = targetViewID;
		Type = type;
		_stalkCount = stalkCount;
		_mode = mode;
		RefreshTargetRef();
	}

	public void SetupDecoy(bool trap)
	{
		Type = EnemyType.Decoy;
		_trap = trap;
	}

	public void ReceiveTransform(Vector3 pos, float yaw)
	{
		//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)
		_netPos = pos;
		_netYaw = yaw;
		_hasNet = true;
	}

	private void Awake()
	{
		_spawnTime = Time.time;
		_agent = ((Component)this).GetComponent<NavMeshAgent>();
		_anim = ((Component)this).GetComponent<Animator>();
		_audioSrc = ((Component)this).GetComponent<AudioSource>();
		if (!Object.op_Implicit((Object)(object)_audioSrc))
		{
			_audioSrc = ((Component)this).gameObject.AddComponent<AudioSource>();
			_audioSrc.spatialBlend = 1f;
			_audioSrc.minDistance = 2f;
			_audioSrc.maxDistance = 25f;
		}
		_audioSrc.volume = PennywiseConfig.Volume.Value;
		SetKillEnabled(on: false);
	}

	private void Start()
	{
		//IL_0018: 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_01b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
		RefreshTargetRef();
		_wasHost = PennywisePlugin.IsHost();
		_netPos = ((Component)this).transform.position;
		_bTimer = Random.Range(0.5f, 1f) * PennywiseConfig.BalloonRelocateInterval.Value;
		if (Object.op_Implicit((Object)(object)_targetPlayer))
		{
			PennywisePlugin.Log.LogInfo((object)$"Spawned {Type} (mode {_mode}). Target: {((Object)_targetPlayer).name} (ViewID {_targetViewId})");
		}
		if (Object.op_Implicit((Object)(object)_agent))
		{
			_agent.updateRotation = false;
		}
		if (Type == EnemyType.Stalker || Type == EnemyType.Clown)
		{
			_procAnim = ((Component)this).gameObject.AddComponent<PennywiseAnimator>();
		}
		switch (Type)
		{
		case EnemyType.Balloon:
			if (Object.op_Implicit((Object)(object)_agent) && PennywisePlugin.IsHost() && _agent.isOnNavMesh)
			{
				((Behaviour)_agent).enabled = true;
				_agent.speed = PennywisePlugin.BalloonSpeed;
				_agent.stoppingDistance = 2f;
				_agent.baseOffset = 0.6f;
				_agent.updateRotation = true;
			}
			else if (PennywisePlugin.IsHost())
			{
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
			else if (Object.op_Implicit((Object)(object)_agent))
			{
				((Behaviour)_agent).enabled = false;
			}
			break;
		case EnemyType.Decoy:
			if (Object.op_Implicit((Object)(object)_agent))
			{
				((Behaviour)_agent).enabled = false;
			}
			_basePos = ((Component)this).transform.position;
			_decoyLifetime = Random.Range(25f, 50f);
			break;
		case EnemyType.Stalker:
			if (PennywisePlugin.StalkClips.Count > 0)
			{
				_audioSrc.PlayOneShot(PennywisePlugin.StalkClips[_stalkCount % PennywisePlugin.StalkClips.Count]);
			}
			if (Object.op_Implicit((Object)(object)_agent))
			{
				((Behaviour)_agent).enabled = true;
				_agent.speed = 0f;
				_agent.baseOffset = 0f;
			}
			if (_mode == 1)
			{
				GlowEyes();
				if (Object.op_Implicit((Object)(object)_procAnim))
				{
					_procAnim.SetDeadlights(on: true);
				}
			}
			if (PennywisePlugin.IsHost())
			{
				((MonoBehaviour)this).StartCoroutine(StalkLifeCycle());
			}
			break;
		case EnemyType.Clown:
			if (Object.op_Implicit((Object)(object)_agent))
			{
				((Behaviour)_agent).enabled = PennywisePlugin.IsHost();
				_agent.baseOffset = 0f;
				if (((Behaviour)_agent).enabled)
				{
					_agent.speed = 0f;
				}
			}
			((MonoBehaviour)this).StartCoroutine(AttackSequence());
			break;
		}
	}

	private void Update()
	{
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f3: 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_00ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0104: 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_0194: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
		bool flag = PennywisePlugin.IsHost();
		if (flag && !_wasHost)
		{
			_wasHost = true;
		}
		if (Type == EnemyType.Decoy)
		{
			DecoyUpdate(flag);
			return;
		}
		if (!Object.op_Implicit((Object)(object)_targetPlayer))
		{
			RefreshTargetRef();
		}
		if (!Object.op_Implicit((Object)(object)_targetPlayer) && flag && Type != EnemyType.Clown)
		{
			PickNewTarget();
			if (!Object.op_Implicit((Object)(object)_targetPlayer))
			{
				PennywiseEventRouter.BroadcastDespawn();
				return;
			}
		}
		if (Type != EnemyType.Balloon && Time.time - _spawnTime > 90f)
		{
			Object.Destroy((Object)(object)((Component)this).gameObject);
			return;
		}
		Vector3 val;
		if (Object.op_Implicit((Object)(object)_targetPlayer) && (Type == EnemyType.Stalker || (Type == EnemyType.Clown && !_charging) || (Type == EnemyType.Balloon && flag)))
		{
			Vector3 position = ((Component)_targetPlayer).transform.position;
			position.y = ((Component)this).transform.position.y;
			val = position - ((Component)this).transform.position;
			if (((Vector3)(ref val)).sqrMagnitude > 0.01f)
			{
				((Component)this).transform.LookAt(position);
			}
		}
		if (Type == EnemyType.Balloon && flag)
		{
			BalloonLogic();
		}
		if (flag && Type == EnemyType.Clown && _charging && Object.op_Implicit((Object)(object)_agent) && ((Behaviour)_agent).enabled && _agent.isOnNavMesh && Object.op_Implicit((Object)(object)_targetPlayer))
		{
			_agent.SetDestination(((Component)_targetPlayer).transform.position);
			val = _agent.velocity;
			if (((Vector3)(ref val)).sqrMagnitude > 0.1f)
			{
				((Component)this).transform.rotation = Quaternion.LookRotation(_agent.velocity);
			}
		}
		if (Type != EnemyType.Stalker)
		{
			SyncTransform(flag);
		}
	}

	private void DecoyUpdate(bool host)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		((Component)this).transform.position = _basePos + Vector3.up * (Mathf.Sin(Time.time * 1.3f + _spawnTime) * 0.15f);
		((Component)this).transform.Rotate(0f, 20f * Time.deltaTime, 0f);
		if (host && !_decoyPopped && Time.time - _spawnTime > _decoyLifetime)
		{
			_decoyPopped = true;
			PennywiseEventRouter.BroadcastDecoyDespawn(popped: false, ((Component)this).transform.position);
		}
	}

	private void PopDecoy()
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		if (!_decoyPopped)
		{
			_decoyPopped = true;
			Vector3 position = ((Component)this).transform.position;
			bool trap = _trap;
			PennywiseEventRouter.BroadcastDecoyDespawn(popped: true, position);
			if (trap)
			{
				PennywisePlugin.TriggerAmbush(position);
			}
		}
	}

	private void SyncTransform(bool host)
	{
		//IL_0062: 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_0072: 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_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f9: 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)
		if (host)
		{
			_netSendTimer += Time.deltaTime;
			if (_netSendTimer >= 0.1f)
			{
				_netSendTimer = 0f;
				PennywiseEventRouter.BroadcastTransform(((Component)this).transform.position, ((Component)this).transform.eulerAngles.y);
			}
		}
		else if (_hasNet)
		{
			Vector3 val = ((Component)this).transform.position - _netPos;
			if (((Vector3)(ref val)).sqrMagnitude > 36f)
			{
				((Component)this).transform.position = _netPos;
			}
			((Component)this).transform.position = Vector3.Lerp(((Component)this).transform.position, _netPos, Mathf.Clamp01(12f * Time.deltaTime));
			((Component)this).transform.rotation = Quaternion.Slerp(((Component)this).transform.rotation, Quaternion.Euler(0f, _netYaw, 0f), Mathf.Clamp01(10f * Time.deltaTime));
		}
	}

	private void OnCollisionEnter(Collision collision)
	{
		if (PennywisePlugin.IsHost() && Type == EnemyType.Decoy && Time.time >= _spawnTime + 2f && IsValidPopObject(collision.gameObject))
		{
			PopDecoy();
		}
		if (PennywisePlugin.IsHost() && Type == EnemyType.Balloon && Time.time >= _spawnTime + 5f && IsValidPopObject(collision.gameObject))
		{
			PopBalloon();
		}
	}

	private void OnTriggerEnter(Collider other)
	{
		if (PennywisePlugin.IsHost() && Type == EnemyType.Decoy && Time.time >= _spawnTime + 2f && IsValidPopObject(((Component)other).gameObject))
		{
			PopDecoy();
		}
		if (PennywisePlugin.IsHost() && Type == EnemyType.Balloon && Time.time >= _spawnTime + 5f && IsValidPopObject(((Component)other).gameObject))
		{
			PopBalloon();
		}
	}

	private bool IsValidPopObject(GameObject obj)
	{
		if (!((Object)(object)obj.GetComponentInParent<Item>() != (Object)null))
		{
			return (Object)(object)obj.GetComponentInParent<ValuableObject>() != (Object)null;
		}
		return true;
	}

	private void PopBalloon()
	{
		PlayPopSound();
		PennywiseEventRouter.BroadcastDespawn();
		Object.Destroy((Object)(object)((Component)this).gameObject);
	}

	private void BalloonLogic()
	{
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0093: Unknown result type (might be due to invalid IL or missing references)
		if (!Object.op_Implicit((Object)(object)_agent) || !((Behaviour)_agent).enabled || !_agent.isOnNavMesh || !Object.op_Implicit((Object)(object)_targetPlayer))
		{
			return;
		}
		BalloonMovement();
		if (_balloonFollowing)
		{
			_balloonFollowTimer += Time.deltaTime;
			if (_balloonFollowTimer > 5f)
			{
				PlayPopSound();
				SpawnNextPhase(isAttack: false);
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
		}
		else if (Vector3.Distance(((Component)this).transform.position, ((Component)_targetPlayer).transform.position) < 3f)
		{
			_balloonFollowing = true;
			_balloonFollowTimer = 0f;
		}
		if (Time.time - _spawnTime > PennywisePlugin.SwitchTargetTime)
		{
			PickNewTarget();
			_spawnTime = Time.time;
		}
	}

	private void FollowTarget()
	{
		//IL_0011: 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_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		_agent.SetDestination(((Component)_targetPlayer).transform.position + ((Component)_targetPlayer).transform.right * 1.5f);
	}

	private void BalloonMovement()
	{
		float value = PennywiseConfig.BalloonRelocateInterval.Value;
		if (_balloonFollowing || value <= 0f)
		{
			FollowTarget();
			return;
		}
		_bTimer -= Time.deltaTime;
		if (_bTimer <= 0f)
		{
			_bIdle = !_bIdle;
			_bTimer = Random.Range(0.5f, 1f) * value;
			if (_bIdle && Random.value < 0.6f)
			{
				RelocateBalloon();
			}
		}
		if (_bIdle)
		{
			if (_agent.hasPath)
			{
				_agent.ResetPath();
			}
		}
		else
		{
			FollowTarget();
		}
	}

	private void RelocateBalloon()
	{
		//IL_002a: 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_005d: Unknown result type (might be due to invalid IL or missing references)
		Vector3? val = PennywisePlugin.GetSightPoint(_targetPlayer, 10f, 25f) ?? PennywisePlugin.GetValidFarPoint(((Component)_targetPlayer).transform.position, 10f, 25f);
		if (val.HasValue && _agent.Warp(val.Value + Vector3.zero))
		{
			PennywisePlugin.Log.LogInfo((object)"Balloon relocated.");
		}
	}

	private void PlayPopSound()
	{
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)PennywisePlugin.BalloonPopClip != (Object)null)
		{
			AudioSource.PlayClipAtPoint(PennywisePlugin.BalloonPopClip, ((Component)this).transform.position, PennywiseConfig.Volume.Value);
		}
	}

	private void GlowEyes()
	{
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0074: Unknown result type (might be due to invalid IL or missing references)
		Renderer[] componentsInChildren = ((Component)this).GetComponentsInChildren<Renderer>(true);
		foreach (Renderer val in componentsInChildren)
		{
			if (((Object)val).name != "FINAL Eyes")
			{
				continue;
			}
			try
			{
				Material material = val.material;
				material.color = new Color(1f, 0.55f, 0.05f);
				if (material.HasProperty("_EmissionColor"))
				{
					material.EnableKeyword("_EMISSION");
					material.SetColor("_EmissionColor", new Color(3f, 1.5f, 0.2f));
				}
			}
			catch (Exception ex)
			{
				PennywisePlugin.Log.LogWarning((object)("GlowEyes failed: " + ex.Message));
			}
		}
	}

	private bool IsSeenByTarget()
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: 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_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: 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_0077: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0098: Unknown result type (might be due to invalid IL or missing references)
		//IL_009d: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
		if (!Object.op_Implicit((Object)(object)_targetPlayer))
		{
			return false;
		}
		Vector3 val = ((Component)_targetPlayer).transform.position + Vector3.up * 1.5f;
		Vector3 val2 = ((Component)this).transform.position + Vector3.up * 1.2f;
		Vector3 val3 = val2 - val;
		if (((Vector3)(ref val3)).magnitude > 45f)
		{
			return false;
		}
		if (Vector3.Angle(((Component)_targetPlayer).transform.forward, val3) > 30f)
		{
			return false;
		}
		RaycastHit val4 = default(RaycastHit);
		if (Physics.Linecast(val + ((Vector3)(ref val3)).normalized * 0.4f, val2, ref val4, -1, (QueryTriggerInteraction)1))
		{
			return ((RaycastHit)(ref val4)).transform.IsChildOf(((Component)this).transform);
		}
		return true;
	}

	private IEnumerator StalkLifeCycle()
	{
		if (_mode == 1)
		{
			yield return DeadlightsLifeCycle();
			yield break;
		}
		float t = 0f;
		float seen = 0f;
		float dur = PennywiseConfig.StalkingDuration.Value;
		while (t < dur)
		{
			t += Time.deltaTime;
			seen = ((!PennywiseConfig.EnableSeenDespawn.Value || !IsSeenByTarget()) ? Mathf.Max(0f, seen - Time.deltaTime) : (seen + Time.deltaTime));
			if (seen > 1.2f)
			{
				PennywisePlugin.Log.LogInfo((object)"Pennywise vanished: seen by target.");
				break;
			}
			yield return null;
		}
		_stalkCount++;
		SpawnNextPhase(_stalkCount >= PennywisePlugin.StalksBeforeAttack);
		Object.Destroy((Object)(object)((Component)this).gameObject);
	}

	private IEnumerator DeadlightsLifeCycle()
	{
		float value = PennywiseConfig.DeadlightsDuration.Value;
		PennywiseEventRouter.BroadcastDeadlights(_targetViewId, value);
		yield return (object)new WaitForSeconds(value);
		if (Object.op_Implicit((Object)(object)_targetPlayer) && PennywisePlugin.HasAllyNear(_targetPlayer, 12f))
		{
			PennywisePlugin.Log.LogInfo((object)"Deadlights ended: target survived (ally nearby).");
			PennywiseEventRouter.BroadcastDespawn();
		}
		else
		{
			PennywisePlugin.Log.LogInfo((object)"Deadlights ended: attack.");
			SpawnNextPhase(isAttack: true, forceMonster: true);
			Object.Destroy((Object)(object)((Component)this).gameObject);
		}
	}

	private IEnumerator AttackSequence()
	{
		if ((_mode & 4) == 0)
		{
			yield return (object)new WaitForSeconds(2f);
		}
		if ((Object)(object)PennywisePlugin.AttackClip != (Object)null)
		{
			_audioSrc.PlayOneShot(PennywisePlugin.AttackClip);
		}
		_charging = true;
		if (Object.op_Implicit((Object)(object)_anim))
		{
			_anim.SetBool("attack", true);
		}
		bool willKill = (_mode & 2) != 0;
		if ((_mode & 1) != 0 && Object.op_Implicit((Object)(object)_procAnim))
		{
			_procAnim.SetMonster(on: true);
		}
		if (willKill)
		{
			SetKillEnabled(on: true);
		}
		bool num = PennywisePlugin.IsHost();
		if (num)
		{
			if (Object.op_Implicit((Object)(object)_agent) && ((Behaviour)_agent).enabled && _agent.isOnNavMesh)
			{
				_agent.isStopped = false;
				_agent.speed = PennywisePlugin.AttackSpeedValue;
				_agent.acceleration = 200f;
				_agent.angularSpeed = 720f;
				_agent.stoppingDistance = 0f;
				_agent.autoBraking = false;
				_agent.updateRotation = false;
			}
			else if (Object.op_Implicit((Object)(object)_targetPlayer))
			{
				((Component)this).transform.position = ((Component)_targetPlayer).transform.position;
			}
		}
		if (willKill)
		{
			PennywisePlugin.MarkKillAchieved();
		}
		if (num)
		{
			float timer = 0f;
			float stopDst = (willKill ? 1.5f : 4f);
			while (timer < 10f && Object.op_Implicit((Object)(object)_targetPlayer) && !(Vector3.Distance(((Component)this).transform.position, ((Component)_targetPlayer).transform.position) < stopDst))
			{
				timer += Time.deltaTime;
				yield return null;
			}
			if (!willKill)
			{
				StopChase();
			}
			yield return (object)new WaitForSeconds(1f);
			PennywiseEventRouter.BroadcastDespawn();
		}
	}

	private void StopChase()
	{
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		_charging = false;
		SetKillEnabled(on: false);
		if (Object.op_Implicit((Object)(object)_agent) && ((Behaviour)_agent).enabled && _agent.isOnNavMesh)
		{
			_agent.isStopped = true;
			_agent.ResetPath();
			_agent.velocity = Vector3.zero;
		}
		PennywisePlugin.Log.LogInfo((object)"Attack ended as a bluff: Pennywise stopped, kill collider off.");
	}

	private void SetKillEnabled(bool on)
	{
		HurtCollider[] componentsInChildren = ((Component)this).GetComponentsInChildren<HurtCollider>(true);
		foreach (HurtCollider obj in componentsInChildren)
		{
			((Behaviour)obj).enabled = on;
			Collider[] components = ((Component)obj).GetComponents<Collider>();
			for (int j = 0; j < components.Length; j++)
			{
				components[j].enabled = on;
			}
		}
	}

	private void SpawnNextPhase(bool isAttack, bool forceMonster = false)
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: 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_01a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_01af: 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)
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e8: 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_00ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Unknown result type (might be due to invalid IL or missing references)
		if (!Object.op_Implicit((Object)(object)_targetPlayer))
		{
			return;
		}
		Vector3 position = ((Component)_targetPlayer).transform.position;
		if (isAttack)
		{
			if (!forceMonster && Random.value < PennywiseConfig.DeadlightsChance.Value)
			{
				Vector3? val = PennywisePlugin.GetSightPoint(_targetPlayer, 5f, 10f) ?? PennywisePlugin.GetValidFarPoint(position, 5f, 12f);
				if (val.HasValue)
				{
					PennywiseEventRouter.BroadcastStalk(val.Value, Quaternion.identity, _targetViewId, _stalkCount, 1);
					return;
				}
			}
			Vector3? validFarPoint = PennywisePlugin.GetValidFarPoint(position, 8f, 999f);
			int num = ((forceMonster || Random.value < PennywiseConfig.TransformationChance.Value) ? 1 : 0);
			if (PennywiseConfig.LethalAttacks.Value && Random.value > PennywiseConfig.BluffChance.Value)
			{
				num |= 2;
			}
			PennywiseEventRouter.BroadcastAttack(validFarPoint ?? position, Quaternion.identity, _targetViewId, num);
			return;
		}
		Vector3? val2 = null;
		float value = Random.value;
		float value2 = PennywiseConfig.JumpscareChance.Value;
		if (value < value2)
		{
			val2 = PennywisePlugin.GetBehindPoint(_targetPlayer, 4f, 8f);
		}
		else if (value < value2 + PennywiseConfig.CorridorAppearanceChance.Value)
		{
			val2 = PennywisePlugin.GetSightPoint(_targetPlayer, 15f, 35f);
		}
		else if (value < value2 + PennywiseConfig.CorridorAppearanceChance.Value + PennywiseConfig.DarkAppearanceChance.Value)
		{
			val2 = PennywisePlugin.GetDarkPoint(_targetPlayer, 8f, 30f);
		}
		if (!val2.HasValue)
		{
			val2 = PennywisePlugin.GetValidFarPoint(position, 15f, 999f);
		}
		PennywiseEventRouter.BroadcastStalk(val2 ?? position, Quaternion.identity, _targetViewId, _stalkCount);
	}

	private void PickNewTarget()
	{
		List<PlayerAvatar> list = (from p in PennywisePlugin.GetPlayers()
			where (Object)(object)p != (Object)(object)_targetPlayer
			select p).ToList();
		if (list.Count != 0)
		{
			_targetPlayer = list[Random.Range(0, list.Count)];
			_targetViewId = _targetPlayer.photonView.ViewID;
			PhotonView component = ((Component)this).GetComponent<PhotonView>();
			PennywiseEventRouter.BroadcastNewTarget(Object.op_Implicit((Object)(object)component) ? component.ViewID : 0, _targetViewId);
		}
	}

	public void SetNewTargetClient(int newTargetID)
	{
		_targetViewId = newTargetID;
		RefreshTargetRef();
	}

	private void RefreshTargetRef()
	{
		_targetPlayer = ((IEnumerable<PlayerAvatar>)PennywisePlugin.GetPlayers()).FirstOrDefault((Func<PlayerAvatar, bool>)((PlayerAvatar p) => p.photonView.ViewID == _targetViewId));
	}
}
public class PennywiseEventRouter : MonoBehaviourPunCallbacks, IOnEventCallback
{
	internal const byte EvSpawnBalloon = 60;

	internal const byte EvAttack = 61;

	internal const byte EvDespawn = 62;

	internal const byte EvNewTarget = 63;

	internal const byte EvStalk = 64;

	internal const byte EvTransform = 65;

	internal const byte EvDeadlights = 66;

	internal const byte EvVoice = 67;

	internal const byte EvDecoy = 68;

	internal const byte EvDecoyDespawn = 69;

	private static bool _callbackHooked;

	private static GameObject _activeEnemy;

	private static GameObject _decoy;

	internal static bool HasActiveEnemy => (Object)(object)_activeEnemy != (Object)null;

	internal static bool HasActiveDecoy => (Object)(object)_decoy != (Object)null;

	private void OnEnable()
	{
		SceneManager.sceneLoaded += OnSceneLoaded;
	}

	private void OnDisable()
	{
		SceneManager.sceneLoaded -= OnSceneLoaded;
		if (_callbackHooked)
		{
			PhotonNetwork.RemoveCallbackTarget((object)this);
		}
		_callbackHooked = false;
	}

	public override void OnJoinedRoom()
	{
		EnsureCallbackHooked();
	}

	public override void OnMasterClientSwitched(Player newMasterClient)
	{
		if (Object.op_Implicit((Object)(object)_activeEnemy))
		{
			Object.Destroy((Object)(object)_activeEnemy);
		}
		if (Object.op_Implicit((Object)(object)_decoy))
		{
			Object.Destroy((Object)(object)_decoy);
		}
		PennywisePlugin.Log.LogInfo((object)"Master client switched: active Pennywise removed.");
	}

	public override void OnLeftRoom()
	{
		if (_callbackHooked)
		{
			PhotonNetwork.RemoveCallbackTarget((object)this);
			_callbackHooked = false;
		}
		if (Object.op_Implicit((Object)(object)_activeEnemy))
		{
			Object.Destroy((Object)(object)_activeEnemy);
		}
		if (Object.op_Implicit((Object)(object)_decoy))
		{
			Object.Destroy((Object)(object)_decoy);
		}
	}

	private void OnSceneLoaded(Scene s, LoadSceneMode m)
	{
		if (Object.op_Implicit((Object)(object)_activeEnemy))
		{
			Object.Destroy((Object)(object)_activeEnemy);
		}
		if (Object.op_Implicit((Object)(object)_decoy))
		{
			Object.Destroy((Object)(object)_decoy);
		}
		if (PhotonNetwork.InRoom)
		{
			EnsureCallbackHooked();
		}
	}

	private void EnsureCallbackHooked()
	{
		if (!_callbackHooked)
		{
			PhotonNetwork.AddCallbackTarget((object)this);
			_callbackHooked = true;
		}
	}

	private static void Raise(byte code, object data, bool reliable = true)
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: 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_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_002a: Expected O, but got Unknown
		if (PhotonNetwork.InRoom)
		{
			PhotonNetwork.RaiseEvent(code, data, new RaiseEventOptions
			{
				Receivers = (ReceiverGroup)0
			}, reliable ? SendOptions.SendReliable : SendOptions.SendUnreliable);
		}
	}

	internal static void BroadcastSpawnBalloon(Vector3 pos, Quaternion rot, int targetID)
	{
		//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_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		CreateLocal(pos, rot, targetID, PennywiseController.EnemyType.Balloon, 0, 0);
		Raise(60, new object[3] { pos, rot, targetID });
	}

	internal static void BroadcastStalk(Vector3 pos, Quaternion rot, int targetID, int count, int mode = 0)
	{
		//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_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		CreateLocal(pos, rot, targetID, PennywiseController.EnemyType.Stalker, count, mode);
		Raise(64, new object[5] { pos, rot, targetID, count, mode });
	}

	internal static void BroadcastAttack(Vector3 pos, Quaternion rot, int targetID, int mode = 0)
	{
		//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_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		CreateLocal(pos, rot, targetID, PennywiseController.EnemyType.Clown, 0, mode);
		Raise(61, new object[4] { pos, rot, targetID, mode });
	}

	internal static void BroadcastDecoySpawn(Vector3 pos, bool trap)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		CreateDecoyLocal(pos, trap);
		Raise(68, new object[1] { pos });
	}

	internal static void BroadcastDecoyDespawn(bool popped, Vector3 pos)
	{
		//IL_0001: 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)
		HandleDecoyDespawn(popped, pos);
		Raise(69, new object[2] { popped, pos });
	}

	internal static void ClearDecoy()
	{
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		if (Object.op_Implicit((Object)(object)_decoy))
		{
			BroadcastDecoyDespawn(popped: false, _decoy.transform.position);
		}
	}

	private static void HandleDecoyDespawn(bool popped, Vector3 pos)
	{
		//IL_0003: Unknown result type (might be due to invalid IL or missing references)
		if (popped)
		{
			PennywisePlugin.PlayPopAt(pos);
		}
		if (Object.op_Implicit((Object)(object)_decoy))
		{
			Object.Destroy((Object)(object)_decoy);
		}
	}

	private static void CreateDecoyLocal(Vector3 pos, bool trap)
	{
		//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)
		if (Object.op_Implicit((Object)(object)_decoy))
		{
			Object.Destroy((Object)(object)_decoy);
		}
		if (!Object.op_Implicit((Object)(object)PennywisePlugin.BalloonPrefab))
		{
			PennywisePlugin.Log.LogWarning((object)"CreateDecoyLocal: balloon prefab missing.");
			return;
		}
		_decoy = Object.Instantiate<GameObject>(PennywisePlugin.BalloonPrefab, pos, Quaternion.identity);
		PennywiseController component = _decoy.GetComponent<PennywiseController>();
		if (Object.op_Implicit((Object)(object)component))
		{
			component.SetupDecoy(trap);
		}
	}

	internal static void BroadcastTransform(Vector3 pos, float yaw)
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		Raise(65, new object[2] { pos, yaw }, reliable: false);
	}

	internal static void BroadcastDeadlights(int targetViewId, float duration)
	{
		HandleDeadlights(targetViewId, duration);
		Raise(66, new object[2] { targetViewId, duration });
	}

	internal static void BroadcastVoice(int targetViewId, int cat, int idx, float pitch)
	{
		PennywiseVoice.PlayLocal(targetViewId, cat, idx, pitch);
		Raise(67, new object[4] { targetViewId, cat, idx, pitch });
	}

	private static void HandleDeadlights(int targetViewId, float duration)
	{
		PlayerAvatar val = ((IEnumerable<PlayerAvatar>)PennywisePlugin.GetPlayers()).FirstOrDefault((Func<PlayerAvatar, bool>)((PlayerAvatar x) => x.photonView.ViewID == targetViewId));
		if ((Object)(object)val != (Object)null && val.photonView.IsMine && (Object)(object)DeadlightsEffect.Instance != (Object)null)
		{
			DeadlightsEffect.Instance.Trigger(duration);
		}
	}

	internal static void BroadcastDespawn()
	{
		if (Object.op_Implicit((Object)(object)_activeEnemy))
		{
			Object.Destroy((Object)(object)_activeEnemy);
		}
		Raise(62, null);
	}

	internal static void BroadcastNewTarget(int enemyPhotonID, int newTargetID)
	{
		if (Object.op_Implicit((Object)(object)_activeEnemy))
		{
			_activeEnemy.GetComponent<PennywiseController>()?.SetNewTargetClient(newTargetID);
		}
		Raise(63, new object[2] { enemyPhotonID, newTargetID });
	}

	private static void CreateLocal(Vector3 pos, Quaternion rot, int targetID, PennywiseController.EnemyType type, int stalkCount, int mode)
	{
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ac: 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)
		//IL_00a4: 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_00da: 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_0116: 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_0125: Unknown result type (might be due to invalid IL or missing references)
		//IL_012a: Unknown result type (might be due to invalid IL or missing references)
		//IL_012e: 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_0146: Unknown result type (might be due to invalid IL or missing references)
		if (Object.op_Implicit((Object)(object)_activeEnemy))
		{
			Object.Destroy((Object)(object)_activeEnemy);
		}
		Scene activeScene = SceneManager.GetActiveScene();
		string text = ((Scene)(ref activeScene)).name.ToLower();
		if (text.Contains("menu") || text.Contains("loader") || text.Contains("intro"))
		{
			return;
		}
		GameObject val = ((type == PennywiseController.EnemyType.Balloon) ? PennywisePlugin.BalloonPrefab : PennywisePlugin.PennywisePrefab);
		if (!Object.op_Implicit((Object)(object)val))
		{
			PennywisePlugin.Log.LogWarning((object)$"CreateLocal({type}): prefab missing.");
			return;
		}
		NavMeshHit val2 = default(NavMeshHit);
		if (NavMesh.SamplePosition(pos, ref val2, 5f, -1))
		{
			pos = ((NavMeshHit)(ref val2)).position;
		}
		_activeEnemy = Object.Instantiate<GameObject>(val, pos, rot);
		NavMeshAgent component = _activeEnemy.GetComponent<NavMeshAgent>();
		if (Object.op_Implicit((Object)(object)component))
		{
			((Behaviour)component).enabled = true;
			if (!component.Warp(pos))
			{
				PlayerAvatar val3 = ((IEnumerable<PlayerAvatar>)PennywisePlugin.GetPlayers()).FirstOrDefault((Func<PlayerAvatar, bool>)((PlayerAvatar p) => p.photonView.ViewID == targetID));
				if (Object.op_Implicit((Object)(object)val3))
				{
					Vector3 val4 = ((Component)val3).transform.position - ((Component)val3).transform.forward * 3f;
					NavMeshHit val5 = default(NavMeshHit);
					component.Warp(NavMesh.SamplePosition(val4, ref val5, 5f, -1) ? ((NavMeshHit)(ref val5)).position : ((Component)val3).transform.position);
				}
			}
		}
		PennywiseController component2 = _activeEnemy.GetComponent<PennywiseController>();
		if (Object.op_Implicit((Object)(object)component2))
		{
			component2.Setup(targetID, type, stalkCount, mode);
		}
	}

	public void OnEvent(EventData e)
	{
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cd: 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_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01da: Unknown result type (might be due to invalid IL or missing references)
		//IL_012a: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			switch (e.Code)
			{
			case 60:
			{
				object[] array3 = (object[])e.CustomData;
				CreateLocal((Vector3)array3[0], (Quaternion)array3[1], (int)array3[2], PennywiseController.EnemyType.Balloon, 0, 0);
				break;
			}
			case 64:
			{
				object[] array2 = (object[])e.CustomData;
				CreateLocal((Vector3)array2[0], (Quaternion)array2[1], (int)array2[2], PennywiseController.EnemyType.Stalker, (int)array2[3], (array2.Length > 4) ? ((int)array2[4]) : 0);
				break;
			}
			case 61:
			{
				object[] array4 = (object[])e.CustomData;
				CreateLocal((Vector3)array4[0], (Quaternion)array4[1], (int)array4[2], PennywiseController.EnemyType.Clown, 0, (array4.Length > 3) ? ((int)array4[3]) : 0);
				break;
			}
			case 65:
			{
				object[] array8 = (object[])e.CustomData;
				if (Object.op_Implicit((Object)(object)_activeEnemy))
				{
					_activeEnemy.GetComponent<PennywiseController>()?.ReceiveTransform((Vector3)array8[0], (float)array8[1]);
				}
				break;
			}
			case 66:
			{
				object[] array7 = (object[])e.CustomData;
				HandleDeadlights((int)array7[0], (float)array7[1]);
				break;
			}
			case 67:
			{
				object[] array6 = (object[])e.CustomData;
				PennywiseVoice.PlayLocal((int)array6[0], (int)array6[1], (int)array6[2], (float)array6[3]);
				break;
			}
			case 68:
				CreateDecoyLocal((Vector3)((object[])e.CustomData)[0], trap: false);
				break;
			case 69:
			{
				object[] array5 = (object[])e.CustomData;
				HandleDecoyDespawn((bool)array5[0], (Vector3)array5[1]);
				break;
			}
			case 62:
				if (Object.op_Implicit((Object)(object)_activeEnemy))
				{
					Object.Destroy((Object)(object)_activeEnemy);
				}
				break;
			case 63:
			{
				object[] array = (object[])e.CustomData;
				if (Object.op_Implicit((Object)(object)_activeEnemy))
				{
					_activeEnemy.GetComponent<PennywiseController>()?.SetNewTargetClient((int)array[1]);
				}
				break;
			}
			}
		}
		catch (Exception arg)
		{
			PennywisePlugin.Log.LogError((object)$"OnEvent({e.Code}) failed: {arg}");
		}
	}
}
[BepInPlugin("enhanced.repo.pennywise", "Pennywise Enhanced", "1.6.0")]
public class PennywisePlugin : BaseUnityPlugin
{
	public const string PluginGuid = "enhanced.repo.pennywise";

	public const string PluginName = "Pennywise Enhanced";

	public const string PluginVersion = "1.6.0";

	internal static ManualLogSource Log;

	internal static PennywisePlugin Instance;

	private Harmony _harmony;

	private static AssetBundle _bundle;

	internal static GameObject BalloonPrefab;

	internal static GameObject PennywisePrefab;

	internal static List<AudioClip> StalkClips = new List<AudioClip>();

	internal static AudioClip AttackClip;

	internal static AudioClip BalloonPopClip;

	public static float BalloonSpeed = 3f;

	public static float SwitchTargetTime = 180f;

	private bool _spawnRoutineRunning;

	private static bool _hauntCancelled;

	private static bool _hasKilledThisLevel;

	private static readonly FieldInfo DeadSetField = AccessTools.Field(typeof(PlayerAvatar), "deadSet");

	private static List<Light> _lightCache;

	private static float _lightCacheTime = -999f;

	internal static int StalksBeforeAttack => Mathf.Max(1, Mathf.RoundToInt(3f / PennywiseConfig.Difficulty));

	internal static float AttackSpeedValue => PennywiseConfig.AttackSpeed.Value * PennywiseConfig.Difficulty;

	internal static bool KilledThisLevel => _hasKilledThisLevel;

	private void Awake()
	{
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Expected O, but got Unknown
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Expected O, but got Unknown
		//IL_008d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		((Component)this).transform.parent = null;
		((Object)((Component)this).gameObject).hideFlags = (HideFlags)61;
		Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
		Log = ((BaseUnityPlugin)this).Logger;
		Instance = this;
		PennywiseConfig.Bind(((BaseUnityPlugin)this).Config);
		_harmony = new Harmony("enhanced.repo.pennywise");
		_harmony.PatchAll(typeof(PennywisePlugin).Assembly);
		LoadBundle();
		((MonoBehaviour)this).StartCoroutine(LoadCustomAudio());
		GameObject val = new GameObject("Pennywise_RouterHost");
		Object.DontDestroyOnLoad((Object)val);
		((Object)val).hideFlags = (HideFlags)13;
		val.AddComponent<PennywiseEventRouter>();
		val.AddComponent<DeadlightsEffect>();
		SceneManager.sceneLoaded += OnSceneLoaded;
		Log.LogInfo((object)string.Format("{0} {1} loaded. SpawnChance={2}, Difficulty={3}", "Pennywise Enhanced", "1.6.0", PennywiseConfig.SpawnChance.Value, PennywiseConfig.Difficulty));
	}

	private IEnumerator LoadClip(string path, Action<AudioClip> onLoaded)
	{
		UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip("file://" + path, (AudioType)14);
		try
		{
			yield return www.SendWebRequest();
			if ((int)www.result == 1)
			{
				AudioClip content = DownloadHandlerAudioClip.GetContent(www);
				((Object)content).name = Path.GetFileName(path);
				onLoaded(content);
			}
			else
			{
				Log.LogWarning((object)("Failed to load audio '" + path + "': " + www.error));
			}
		}
		finally
		{
			if (www != null)
			{
				www.Dispose();
			}
		}
	}

	private IEnumerator LoadCustomAudio()
	{
		string dir = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
		if (string.IsNullOrEmpty(dir))
		{
			dir = Paths.PluginPath;
		}
		string path = Path.Combine(dir, "attack.ogg");
		if (File.Exists(path))
		{
			yield return LoadClip(path, delegate(AudioClip c)
			{
				AttackClip = c;
				Log.LogInfo((object)"Loaded attack.ogg");
			});
		}
		else
		{
			Log.LogWarning((object)"attack.ogg not found");
		}
		string path2 = Path.Combine(dir, "balloon.ogg");
		if (File.Exists(path2))
		{
			yield return LoadClip(path2, delegate(AudioClip c)
			{
				BalloonPopClip = c;
				Log.LogInfo((object)"Loaded balloon.ogg");
			});
		}
		else
		{
			Log.LogWarning((object)"balloon.ogg not found");
		}
		foreach (string item in from x in Directory.GetFiles(dir, "penny*.ogg")
			orderby x
			select x)
		{
			yield return LoadClip(item, delegate(AudioClip c)
			{
				StalkClips.Add(c);
			});
		}
		foreach (string item2 in from x in Directory.GetFiles(dir, "whisper*.ogg")
			orderby x
			select x)
		{
			yield return LoadClip(item2, delegate(AudioClip c)
			{
				PennywiseVoice.WhisperClips.Add(c);
			});
		}
		foreach (string item3 in from x in Directory.GetFiles(dir, "child*.ogg")
			orderby x
			select x)
		{
			yield return LoadClip(item3, delegate(AudioClip c)
			{
				PennywiseVoice.ChildClips.Add(c);
			});
		}
		foreach (string item4 in from x in Directory.GetFiles(dir, "laugh*.ogg")
			orderby x
			select x)
		{
			yield return LoadClip(item4, delegate(AudioClip c)
			{
				PennywiseVoice.LaughClips.Add(c);
			});
		}
		Log.LogInfo((object)$"Loaded {StalkClips.Count} stalk sounds, voice clips: whisper={PennywiseVoice.WhisperClips.Count}, child={PennywiseVoice.ChildClips.Count}, laugh={PennywiseVoice.LaughClips.Count}.");
	}

	private void OnDestroy()
	{
		SceneManager.sceneLoaded -= OnSceneLoaded;
		Harmony harmony = _harmony;
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
	}

	private void OnSceneLoaded(Scene s, LoadSceneMode m)
	{
		_spawnRoutineRunning = false;
		_hasKilledThisLevel = false;
		_hauntCancelled = false;
		((MonoBehaviour)this).StopAllCoroutines();
		if (PhotonNetwork.InRoom || !PhotonNetwork.IsConnected)
		{
			((MonoBehaviour)this).StartCoroutine(WaitLevelThenSpawn());
		}
	}

	private static bool BlockedMenuOrHub()
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			Scene activeScene = SceneManager.GetActiveScene();
			string text = SafeLower(((Scene)(ref activeScene)).name);
			if (text.Contains("menu") || text.Contains("loader") || text.Contains("intro"))
			{
				return true;
			}
			if ((Object)(object)RunManager.instance != (Object)null && (Object)(object)RunManager.instance.levelCurrent != (Object)null)
			{
				string text2 = SafeLower(RunManager.instance.levelCurrent.NarrativeName);
				if (text2.Contains("lobby") || text2.Contains("menu"))
				{
					return true;
				}
			}
			return false;
		}
		catch
		{
			return true;
		}
	}

	private static string SafeLower(string s)
	{
		return (s ?? string.Empty).Trim().ToLowerInvariant();
	}

	private static bool NavMeshReady()
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			return NavMesh.CalculateTriangulation().vertices.Length != 0;
		}
		catch
		{
			return false;
		}
	}

	private IEnumerator WaitLevelThenSpawn()
	{
		if (_spawnRoutineRunning || _hasKilledThisLevel)
		{
			yield break;
		}
		_spawnRoutineRunning = true;
		float t = 0f;
		while (BlockedMenuOrHub() || (Object)(object)LevelGenerator.Instance == (Object)null || !LevelGenerator.Instance.Generated || !NavMeshReady())
		{
			if (t >= 30f)
			{
				_spawnRoutineRunning = false;
				yield break;
			}
			t += Time.unscaledDeltaTime;
			yield return null;
		}
		if (!IsHost())
		{
			_spawnRoutineRunning = false;
		}
		else if ((Object)(object)BalloonPrefab == (Object)null || (Object)(object)PennywisePrefab == (Object)null)
		{
			Log.LogWarning((object)"Prefabs missing (bundle 'scary' not loaded) - Pennywise disabled this level.");
			_spawnRoutineRunning = false;
		}
		else if (Random.value > Mathf.Clamp01(PennywiseConfig.SpawnChance.Value))
		{
			_spawnRoutineRunning = false;
		}
		else
		{
			Log.LogInfo((object)"Pennywise chosen for this level.");
			((MonoBehaviour)this).StartCoroutine(HauntLoop());
		}
	}

	private bool TrySpawnEncounter()
	{
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_007f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0089: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0093: Unknown result type (might be due to invalid IL or missing references)
		List<PlayerAvatar> players = GetPlayers();
		if (players.Count == 0)
		{
			return false;
		}
		PlayerAvatar obj = players[Random.Range(0, players.Count)];
		int viewID = obj.photonView.ViewID;
		Vector3? validFarPoint = GetValidFarPoint(((Component)obj).transform.position, 15f, 999f);
		if (!validFarPoint.HasValue)
		{
			return false;
		}
		if (PennywiseConfig.EnableBalloon.Value && Random.value <= PennywiseConfig.BalloonSpawnChance.Value)
		{
			PennywiseEventRouter.BroadcastSpawnBalloon(validFarPoint.Value + Vector3.up * 0.6f, Quaternion.identity, viewID);
		}
		else
		{
			PennywiseEventRouter.BroadcastStalk(validFarPoint.Value, Quaternion.identity, viewID, 0);
		}
		return true;
	}

	private IEnumerator HauntLoop()
	{
		((MonoBehaviour)this).StartCoroutine(DecoyLoop());
		yield return (object)new WaitForSeconds(Random.Range(20f, 120f) / PennywiseConfig.Difficulty);
		int failed = 0;
		int encounter = 0;
		while (!_hasKilledThisLevel && !_hauntCancelled)
		{
			PennywiseEventRouter.ClearDecoy();
			if (!TrySpawnEncounter())
			{
				int num = failed + 1;
				failed = num;
				if (num > 20)
				{
					break;
				}
				yield return (object)new WaitForSeconds(30f);
				continue;
			}
			failed = 0;
			encounter++;
			Log.LogInfo((object)$"Haunt: encounter #{encounter} started.");
			float elapsed = 0f;
			float gone = 0f;
			while (elapsed < 900f)
			{
				elapsed += Time.deltaTime;
				if (PennywiseEventRouter.HasActiveEnemy)
				{
					gone = 0f;
				}
				else
				{
					gone += Time.deltaTime;
					if (gone > 1.5f)
					{
						break;
					}
				}
				yield return null;
			}
			if (_hasKilledThisLevel || _hauntCancelled)
			{
				break;
			}
			float num2 = Mathf.Max(30f, PennywiseConfig.ReattackDelayMinutes.Value * 60f * Random.Range(0.8f, 1.2f) / PennywiseConfig.Difficulty);
			Log.LogInfo((object)$"Haunt: encounter #{encounter} ended, next attempt in {num2 / 60f:F1} min.");
			yield return QuietPhase(num2);
		}
		Log.LogInfo((object)"Haunt: finished for this level.");
		_spawnRoutineRunning = false;
	}

	private IEnumerator DecoyLoop()
	{
		float interval = PennywiseConfig.DecoyBalloonInterval.Value;
		if (interval <= 0f)
		{
			yield break;
		}
		while (!_hasKilledThisLevel)
		{
			yield return (object)new WaitForSeconds(Random.Range(0.5f, 1.5f) * interval / PennywiseConfig.Difficulty);
			if (_hasKilledThisLevel)
			{
				break;
			}
			if (PennywiseEventRouter.HasActiveEnemy || PennywiseEventRouter.HasActiveDecoy)
			{
				continue;
			}
			List<PlayerAvatar> players = GetPlayers();
			if (players.Count != 0)
			{
				PlayerAvatar val = players[Random.Range(0, players.Count)];
				Vector3? val2 = GetSightPoint(val, 8f, 20f) ?? GetValidFarPoint(((Component)val).transform.position, 8f, 20f);
				if (val2.HasValue)
				{
					bool flag = Random.value < PennywiseConfig.DecoyTrapChance.Value;
					Log.LogInfo((object)$"Decoy balloon spawned (trap={flag}).");
					PennywiseEventRouter.BroadcastDecoySpawn(val2.Value + Vector3.up * 1f, flag);
				}
			}
		}
	}

	internal static void TriggerAmbush(Vector3 balloonPos)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_00cc: Unknown result type (might be due to invalid IL or missing references)
		PlayerAvatar val = (from p in GetPlayers()
			orderby Vector3.Distance(((Component)p).transform.position, balloonPos)
			select p).FirstOrDefault();
		if (!((Object)(object)val == (Object)null))
		{
			? pos = ((??)GetBehindPoint(val, 1.8f, 2.6f)) ?? (((Component)val).transform.position + ((Component)val).transform.forward * 2f);
			int num = 4;
			if (PennywiseConfig.LethalAttacks.Value)
			{
				num |= 2;
			}
			if (Random.value < PennywiseConfig.TransformationChance.Value)
			{
				num |= 1;
			}
			Log.LogInfo((object)$"Trap balloon popped: ambush on ViewID {val.photonView.ViewID} (mode {num}).");
			PennywiseEventRouter.BroadcastAttack((Vector3)pos, Quaternion.identity, val.photonView.ViewID, num);
		}
	}

	internal static void PlayPopAt(Vector3 pos)
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)BalloonPopClip != (Object)null)
		{
			AudioSource.PlayClipAtPoint(BalloonPopClip, pos, PennywiseConfig.Volume.Value);
		}
	}

	private IEnumerator QuietPhase(float duration)
	{
		int num = (PennywiseConfig.EnableVoiceProvocations.Value ? PennywiseConfig.VoicesPerQuietPeriod.Value : 0);
		List<float> list = (from _ in Enumerable.Range(0, Mathf.Max(0, num))
			select duration * 0.95f * Mathf.Sqrt(Random.value) into x
			orderby x
			select x).ToList();
		for (int num2 = 1; num2 < list.Count; num2++)
		{
			list[num2] = Mathf.Max(list[num2], list[num2 - 1] + 20f);
		}
		float passed = 0f;
		foreach (float tm in list)
		{
			if (tm >= duration)
			{
				break;
			}
			yield return (object)new WaitForSeconds(Mathf.Max(0f, tm - passed));
			passed = Mathf.Max(passed, tm);
			if (!_hasKilledThisLevel && !_hauntCancelled)
			{
				PennywiseVoice.HostPlayOne();
				continue;
			}
			yield break;
		}
		yield return (object)new WaitForSeconds(Mathf.Max(0f, duration - passed));
	}

	public static Vector3? GetValidFarPoint(Vector3 center, float minDst, float maxDst)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_012e: 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)
		LevelGenerator instance = LevelGenerator.Instance;
		if ((Object)(object)instance == (Object)null || !instance.Generated || instance.LevelPathPoints == null)
		{
			return null;
		}
		List<Transform> list = (from p in instance.LevelPathPoints
			where (Object)(object)p != (Object)null
			select ((Component)p).transform).Where(delegate(Transform t)
		{
			//IL_0001: 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)
			float num2 = Vector3.Distance(t.position, center);
			return num2 >= minDst && num2 <= maxDst;
		}).ToList();
		if (list.Count == 0)
		{
			list = (from p in instance.LevelPathPoints
				where (Object)(object)p != (Object)null
				select ((Component)p).transform).ToList();
			if (list.Count == 0)
			{
				return null;
			}
		}
		NavMeshHit val = default(NavMeshHit);
		for (int num = 0; num < 10; num++)
		{
			if (NavMesh.SamplePosition(list[Random.Range(0, list.Count)].position, ref val, 5f, -1))
			{
				return ((NavMeshHit)(ref val)).position;
			}
		}
		return null;
	}

	internal static Vector3? GetBehindPoint(PlayerAvatar p, float minDst, float maxDst)
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: 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_0061: 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_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_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: 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)
		if ((Object)(object)p == (Object)null)
		{
			return null;
		}
		Vector3 val = -((Component)p).transform.forward;
		val.y = 0f;
		if (((Vector3)(ref val)).sqrMagnitude < 0.01f)
		{
			val = Vector3.back;
		}
		NavMeshHit val3 = default(NavMeshHit);
		for (int i = 0; i < 10; i++)
		{
			Vector3 val2 = Quaternion.Euler(0f, Random.Range(-40f, 40f), 0f) * ((Vector3)(ref val)).normalized;
			if (NavMesh.SamplePosition(((Component)p).transform.position + val2 * Random.Range(minDst, maxDst), ref val3, 2.5f, -1))
			{
				return ((NavMeshHit)(ref val3)).position;
			}
		}
		return null;
	}

	internal static Vector3? GetSightPoint(PlayerAvatar p, float minDst, float maxDst)
	{
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: 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_0077: Unknown result type (might be due to invalid IL or missing references)
		//IL_0103: 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)
		LevelGenerator instance = LevelGenerator.Instance;
		if ((Object)(object)p == (Object)null || (Object)(object)instance == (Object)null || !instance.Generated || instance.LevelPathPoints == null)
		{
			return null;
		}
		Vector3 eye = ((Component)p).transform.position + Vector3.up * 1.5f;
		Vector3 fwd = ((Component)p).transform.forward;
		fwd.y = 0f;
		List<Vector3> list = (from x in instance.LevelPathPoints
			where (Object)(object)x != (Object)null
			select ((Component)x).transform.position).Where(delegate(Vector3 pos)
		{
			//IL_0000: 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_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: 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_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: 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_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val2 = pos - eye;
			float magnitude = ((Vector3)(ref val2)).magnitude;
			if (magnitude < minDst || magnitude > maxDst)
			{
				return false;
			}
			val2.y = 0f;
			return !(Vector3.Angle(fwd, val2) > 55f) && !Physics.Linecast(eye + ((Vector3)(ref fwd)).normalized * 0.4f, pos + Vector3.up * 1.2f, -1, (QueryTriggerInteraction)1);
		}).ToList();
		NavMeshHit val = default(NavMeshHit);
		for (int num = 0; num < 8; num++)
		{
			if (list.Count <= 0)
			{
				break;
			}
			if (NavMesh.SamplePosition(list[Random.Range(0, list.Count)], ref val, 3f, -1))
			{
				return ((NavMeshHit)(ref val)).position;
			}
		}
		return null;
	}

	private static bool IsDark(Vector3 pos, Vector3 ignoreNear)
	{
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Unknown result type (might be due to invalid IL or missing references)
		//IL_0088: 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_008f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		if (_lightCache == null || Time.time - _lightCacheTime > 20f)
		{
			_lightCache = (from l in Object.FindObjectsOfType<Light>()
				where (Object)(object)l != (Object)null && ((Behaviour)l).enabled && (int)l.type != 1 && l.intensity > 0.2f
				select l).ToList();
			_lightCacheTime = Time.time;
		}
		foreach (Light item in _lightCache)
		{
			if ((Object)(object)item == (Object)null || !((Behaviour)item).isActiveAndEnabled)
			{
				continue;
			}
			Vector3 position = ((Component)item).transform.position;
			Vector3 val = position - ignoreNear;
			if (!(((Vector3)(ref val)).sqrMagnitude < 4f))
			{
				float num = Mathf.Min(item.range, 12f);
				val = position - pos;
				if (((Vector3)(ref val)).sqrMagnitude < num * num)
				{
					return false;
				}
			}
		}
		return true;
	}

	internal static Vector3? GetDarkPoint(PlayerAvatar p, float minDst, float maxDst)
	{
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
		LevelGenerator instance = LevelGenerator.Instance;
		if ((Object)(object)p == (Object)null || (Object)(object)instance == (Object)null || !instance.Generated || instance.LevelPathPoints == null)
		{
			return null;
		}
		Vector3 origin = ((Component)p).transform.position;
		List<Vector3> list = (from x in instance.LevelPathPoints
			where (Object)(object)x != (Object)null
			select ((Component)x).transform.position).Where(delegate(Vector3 pos)
		{
			//IL_0000: 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_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_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_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			float num2 = Vector3.Distance(pos, origin);
			return num2 >= minDst && num2 <= maxDst && IsDark(pos + Vector3.up * 1.5f, origin + Vector3.up * 1.5f);
		}).ToList();
		NavMeshHit val = default(NavMeshHit);
		for (int num = 0; num < 8; num++)
		{
			if (list.Count <= 0)
			{
				break;
			}
			if (NavMesh.SamplePosition(list[Random.Range(0, list.Count)], ref val, 3f, -1))
			{
				return ((NavMeshHit)(ref val)).position;
			}
		}
		return null;
	}

	internal static bool HasAllyNear(PlayerAvatar target, float radius)
	{
		if ((Object)(object)target == (Object)null)
		{
			return false;
		}
		return GetPlayers().Any((PlayerAvatar p) => (Object)(object)p != (Object)(object)target && Vector3.Distance(((Component)p).transform.position, ((Component)target).transform.position) <= radius);
	}

	private void LoadBundle()
	{
		if ((Object)(object)_bundle != (Object)null)
		{
			return;
		}
		try
		{
			string text = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
			if (string.IsNullOrEmpty(text))
			{
				text = Paths.PluginPath;
			}
			string text2 = Directory.GetFiles(text, "scary", SearchOption.AllDirectories).FirstOrDefault();
			if (string.IsNullOrEmpty(text2))
			{
				Log.LogError((object)"AssetBundle 'scary' not found next to the plugin DLL.");
				return;
			}
			_bundle = AssetBundle.LoadFromFile(text2);
			if ((Object)(object)_bundle == (Object)null)
			{
				Log.LogError((object)"AssetBundle.LoadFromFile returned null.");
				return;
			}
			BalloonPrefab = _bundle.LoadAsset<GameObject>("Balloon");
			PennywisePrefab = _bundle.LoadAsset<GameObject>("Pennywise");
			if ((Object)(object)BalloonPrefab == (Object)null)
			{
				Log.LogError((object)"Prefab 'Balloon' not found in bundle.");
			}
			if ((Object)(object)PennywisePrefab == (Object)null)
			{
				Log.LogError((object)"Prefab 'Pennywise' not found in bundle.");
			}
			SetupPrefab(BalloonPrefab);
			SetupPrefab(PennywisePrefab);
			if ((Object)(object)PennywisePrefab != (Object)null && (Object)(object)PennywisePrefab.GetComponent<PennywiseAppearance>() == (Object)null)
			{
				PennywisePrefab.AddComponent<PennywiseAppearance>();
			}
			Log.LogInfo((object)"Loaded 'scary' bundle.");
		}
		catch (Exception arg)
		{
			Log.LogError((object)$"LoadBundle failed: {arg}");
		}
	}

	internal static void CancelHaunt()
	{
		_hauntCancelled = true;
	}

	public static void MarkKillAchieved()
	{
		_hasKilledThisLevel = true;
	}

	public static bool IsHost()
	{
		if (PhotonNetwork.InRoom)
		{
			return PhotonNetwork.IsMasterClient;
		}
		return true;
	}

	public static bool IsDead(PlayerAvatar p)
	{
		if ((Object)(object)p == (Object)null)
		{
			return true;
		}
		object obj = DeadSetField?.GetValue(p);
		if (obj != null)
		{
			return (