using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using KillItWithShovel.Patches;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("DisableTurretOnHit")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DisableTurretOnHit")]
[assembly: AssemblyCopyright("Copyright © 2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("7396d5a1-8737-4657-8c55-4f5741428920")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace KillItWithShovel
{
[Serializable]
public class Config : SyncedInstance<Config>
{
public static ConfigEntry<bool> configEnterBerserkMode;
public bool bMode;
public static ConfigEntry<bool> configWakenAfterWeapon;
public bool bWakenAfterWeapon;
public static ConfigEntry<float> configDisableDuration;
public float dDuration;
public static ConfigEntry<float> configDisableChance;
public float dChance;
public static ConfigEntry<int> configGuaranteedBMode;
public int BGuarantee;
public static ConfigEntry<bool> configIncreaseGBMOnFailure;
public bool GBMUpOnFailure;
public Config(ConfigFile cfg)
{
InitInstance(this);
configEnterBerserkMode = cfg.Bind<bool>("General", "Berserk Mode when being waked", true, "Turret will enter berserker mode if rudely woken by weapons.");
configWakenAfterWeapon = cfg.Bind<bool>("General", "Can be Waked only after deactivating to a weapon", true, "Turrets can be waken from deactivation only when they were deactivated by other weapon previously (not ship terminal).");
configDisableDuration = cfg.Bind<float>("General", "Disable Duration", 5f, "For how many seconds the turret will be deactivated on successful hit.");
configDisableChance = cfg.Bind<float>("General", "Deactivate Chance", 1f, "Chance that the turret will deactivate on a successful hit (0 to 1).\n-\nHow this works: 0.5 means 50% that turret will deactivate (same 50% that it fails to deactivate), it could be 0 (0%, turret will never deactivate), 1 (100%, turret always deactivates), and any other value like for example 0.34 (34%)");
configGuaranteedBMode = cfg.Bind<int>("General", "Guaranteed Berserk Mode", -1, "How many hits will trigger guaranteed berserk mode (-1 to disable this feature).\n-\nHow this works: every time you hit turret 0 value goes up, and when you hit it while value is equal to this config value, guaranteed berserk mode starts and value resets to 0. That's why -1 disables this function beacuse no matter how much you hit it will never be equal to negative number.");
configIncreaseGBMOnFailure = cfg.Bind<bool>("General", "Increase Guaranteed Berserk Mode Value on failure to deactivate the turret", false, "The guaranteed berserk mode counter will increase if player fails to deactivate turret with a shovel and turret enters Berserk mode.");
}
public static void BuildServerConfigSync()
{
SyncedInstance<Config>.Default.bMode = configEnterBerserkMode.Value;
SyncedInstance<Config>.Default.bWakenAfterWeapon = configWakenAfterWeapon.Value;
SyncedInstance<Config>.Default.dDuration = configDisableDuration.Value;
SyncedInstance<Config>.Default.dChance = configDisableChance.Value;
SyncedInstance<Config>.Default.BGuarantee = configGuaranteedBMode.Value;
SyncedInstance<Config>.Default.GBMUpOnFailure = configIncreaseGBMOnFailure.Value;
SyncedInstance<Config>.Instance.bMode = SyncedInstance<Config>.Default.bMode;
SyncedInstance<Config>.Instance.bWakenAfterWeapon = SyncedInstance<Config>.Default.bWakenAfterWeapon;
SyncedInstance<Config>.Instance.dDuration = SyncedInstance<Config>.Default.dDuration;
SyncedInstance<Config>.Instance.dChance = SyncedInstance<Config>.Default.dChance;
SyncedInstance<Config>.Instance.BGuarantee = SyncedInstance<Config>.Default.BGuarantee;
SyncedInstance<Config>.Instance.GBMUpOnFailure = SyncedInstance<Config>.Default.GBMUpOnFailure;
}
public static void RequestSync()
{
//IL_002a: Unknown result type (might be due to invalid IL or missing references)
if (!SyncedInstance<Config>.IsClient)
{
return;
}
FastBufferWriter val = default(FastBufferWriter);
((FastBufferWriter)(ref val))..ctor(SyncedInstance<Config>.IntSize, (Allocator)2, -1);
try
{
SyncedInstance<Config>.MessageManager.SendNamedMessage("DisableTurretOnHit_OnRequestConfigSync", 0uL, val, (NetworkDelivery)2);
}
finally
{
((FastBufferWriter)(ref val)).Dispose();
}
}
public static void OnRequestSync(ulong clientId, FastBufferReader _)
{
//IL_0053: 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_0077: Unknown result type (might be due to invalid IL or missing references)
if (!SyncedInstance<Config>.IsHost)
{
return;
}
SyncedInstance<Config>.mls2.LogInfo((object)$"Config sync request received from client: {clientId}");
byte[] array = SyncedInstance<Config>.SerializeToBytes(SyncedInstance<Config>.Instance);
int num = array.Length;
FastBufferWriter val = default(FastBufferWriter);
((FastBufferWriter)(ref val))..ctor(num + SyncedInstance<Config>.IntSize, (Allocator)2, -1);
try
{
((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives));
((FastBufferWriter)(ref val)).WriteBytesSafe(array, -1, 0);
SyncedInstance<Config>.MessageManager.SendNamedMessage("DisableTurretOnHit_OnReceiveConfigSync", clientId, val, (NetworkDelivery)2);
}
catch (Exception arg)
{
SyncedInstance<Config>.mls2.LogError((object)$"Error occurred syncing config with client: {clientId}\n{arg}");
}
finally
{
((FastBufferWriter)(ref val)).Dispose();
}
}
public static void OnReceiveSync(ulong _, FastBufferReader reader)
{
//IL_002d: 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)
if (!((FastBufferReader)(ref reader)).TryBeginRead(SyncedInstance<Config>.IntSize))
{
SyncedInstance<Config>.mls2.LogError((object)"Config sync error: Could not begin reading buffer.");
return;
}
int num = default(int);
((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
if (!((FastBufferReader)(ref reader)).TryBeginRead(num))
{
SyncedInstance<Config>.mls2.LogError((object)"Config sync error: Host could not sync.");
return;
}
byte[] data = new byte[num];
((FastBufferReader)(ref reader)).ReadBytesSafe(ref data, num, 0);
SyncedInstance<Config>.SyncInstance(data);
SyncedInstance<Config>.mls2.LogInfo((object)"Successfully synced config with host.");
}
[HarmonyPostfix]
[HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")]
public static void InitializeLocalPlayer()
{
//IL_0050: Unknown result type (might be due to invalid IL or missing references)
//IL_005a: Expected O, but got Unknown
//IL_0022: Unknown result type (might be due to invalid IL or missing references)
//IL_002c: Expected O, but got Unknown
if (SyncedInstance<Config>.IsHost)
{
BuildServerConfigSync();
SyncedInstance<Config>.MessageManager.RegisterNamedMessageHandler("DisableTurretOnHit_OnRequestConfigSync", new HandleNamedMessageDelegate(OnRequestSync));
SyncedInstance<Config>.Synced = true;
}
else
{
SyncedInstance<Config>.Synced = false;
SyncedInstance<Config>.MessageManager.RegisterNamedMessageHandler("DisableTurretOnHit_OnReceiveConfigSync", new HandleNamedMessageDelegate(OnReceiveSync));
RequestSync();
}
}
[HarmonyPostfix]
[HarmonyPatch(typeof(GameNetworkManager), "StartDisconnect")]
public static void PlayerLeave()
{
SyncedInstance<Config>.RevertSync();
}
}
[BepInPlugin("Great_Ramil.DisableTurretOnHit", "DisableTurretOnHit", "1.0.0")]
public class Plugin : BaseUnityPlugin
{
private const string modGUID = "Great_Ramil.DisableTurretOnHit";
private const string modName = "DisableTurretOnHit";
private const string modVersion = "1.0.0";
private readonly Harmony harmony = new Harmony("Great_Ramil.DisableTurretOnHit");
public static Plugin Instance;
internal ManualLogSource mls;
public static Config MyConfig { get; internal set; }
private void Awake()
{
if ((Object)(object)Instance == (Object)null)
{
Instance = this;
}
((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin Great_Ramil.DisableTurretOnHit is loaded!");
mls = Logger.CreateLogSource("Great_Ramil.DisableTurretOnHit");
harmony.PatchAll(typeof(Plugin));
harmony.PatchAll(typeof(TurretPatch));
harmony.PatchAll(typeof(Config));
MyConfig = new Config(((BaseUnityPlugin)this).Config);
}
}
public static class PluginInfo
{
public const string PLUGIN_GUID = "Great_Ramil.DisableTurretOnHit";
public const string PLUGIN_NAME = "DisableTurretOnHit";
public const string PLUGIN_VERSION = "2.0.0";
}
[Serializable]
public class SyncedInstance<T>
{
public static ManualLogSource mls2 = Logger.CreateLogSource("Great_Ramil.DisableTurretOnHit");
[NonSerialized]
protected static int IntSize = 4;
internal static CustomMessagingManager MessageManager => NetworkManager.Singleton.CustomMessagingManager;
internal static bool IsClient => NetworkManager.Singleton.IsClient;
internal static bool IsHost => NetworkManager.Singleton.IsHost;
public static T Default { get; private set; }
public static T Instance { get; private set; }
public static bool Synced { get; internal set; }
protected void InitInstance(T instance)
{
Default = instance;
Instance = instance;
IntSize = 4;
}
internal static void SyncInstance(byte[] data)
{
Instance = DeserializeFromBytes(data);
Synced = true;
}
internal static void RevertSync()
{
Instance = Default;
Synced = false;
}
public static byte[] SerializeToBytes(T val)
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
using MemoryStream memoryStream = new MemoryStream();
try
{
binaryFormatter.Serialize(memoryStream, val);
return memoryStream.ToArray();
}
catch (Exception arg)
{
mls2.LogError((object)$"Error serializing instance: {arg}");
return null;
}
}
public static T DeserializeFromBytes(byte[] data)
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
T result;
using (MemoryStream serializationStream = new MemoryStream(data))
{
try
{
result = (T)binaryFormatter.Deserialize(serializationStream);
return result;
}
catch (Exception arg)
{
mls2.LogError((object)$"Error deserializing instance: {arg}");
result = default(T);
}
}
return result;
}
}
}
namespace KillItWithShovel.Patches
{
[HarmonyPatch(typeof(EnemyAI))]
internal class EnemyAIPatch
{
[HarmonyPatch(typeof(EnemyAI), "HitEnemy")]
[HarmonyPrefix]
public static bool HitPushBackPatch(ref int force, ref PlayerControllerB playerWhoHit, ref EnemyAI __instance)
{
string enemyName = __instance.enemyType.enemyName;
string text = enemyName;
if (text == "SpringManAI" || text == "JesterAI")
{
PushBackHit(ref force, ref playerWhoHit, ref __instance);
}
return true;
}
private static void PushBackHit(ref int force, ref PlayerControllerB playerWhoHit, ref EnemyAI __instance)
{
//IL_000d: Unknown result type (might be due to invalid IL or missing references)
//IL_0012: 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_0024: Unknown result type (might be due to invalid IL or missing references)
//IL_0025: Unknown result type (might be due to invalid IL or missing references)
//IL_002b: Unknown result type (might be due to invalid IL or missing references)
//IL_0051: Unknown result type (might be due to invalid IL or missing references)
//IL_0052: 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_005b: 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_0074: 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_007b: Unknown result type (might be due to invalid IL or missing references)
Vector3 position = ((Component)__instance).gameObject.transform.position;
Vector3 position2 = ((Component)playerWhoHit).gameObject.transform.position;
float num = position2.y - position.y;
if (num > 40f)
{
__instance.KillEnemy(false);
return;
}
Vector3 val = Vector3.Normalize((position2 - position) * (float)force);
Transform transform = ((Component)__instance).gameObject.transform;
transform.position += val;
}
}
[HarmonyPatch(typeof(Turret))]
internal class TurretPatch
{
public class TurretHitPatchMB : MonoBehaviour
{
}
public class TurretHitStatus : MonoBehaviour
{
public int hitCount = 0;
public bool wasDeactivatedByWeapon = false;
}
private static readonly ManualLogSource logger = Logger.CreateLogSource("KillItWithShovel");
private static TurretHitPatchMB turretHitPatchMB;
[HarmonyPatch(typeof(Turret), "IHittable.Hit")]
[HarmonyPrefix]
public static bool HitDisablePatch(ref TurretMode ___turretMode, ref Turret __instance)
{
if ((Object)(object)turretHitPatchMB == (Object)null)
{
turretHitPatchMB = ((Component)__instance).gameObject.AddComponent<TurretHitPatchMB>();
}
TurretHitStatus turretHitStatus = ((Component)__instance).gameObject.GetComponent<TurretHitStatus>();
if ((Object)(object)turretHitStatus == (Object)null)
{
turretHitStatus = ((Component)__instance).gameObject.AddComponent<TurretHitStatus>();
}
int num = turretHitStatus.hitCount;
bool wasDeactivatedByWeapon = turretHitStatus.wasDeactivatedByWeapon;
bool turretActive = __instance.turretActive;
bool flag = false;
if ((int)___turretMode == 3)
{
flag = true;
}
bool result = true;
if (!flag)
{
if (turretActive)
{
bool flag2 = Random.value <= SyncedInstance<Config>.Instance.dChance;
if (SyncedInstance<Config>.Instance.dChance == 0f)
{
flag2 = false;
}
if (num >= SyncedInstance<Config>.Instance.BGuarantee && SyncedInstance<Config>.Instance.BGuarantee >= 0)
{
num = 0;
result = true;
}
else if (flag2)
{
num++;
((MonoBehaviour)turretHitPatchMB).StartCoroutine(TurnOffAndOnTurret(__instance, SyncedInstance<Config>.Instance.dDuration));
result = false;
}
else
{
if (SyncedInstance<Config>.Instance.GBMUpOnFailure)
{
num++;
}
result = true;
}
}
else
{
bool bMode = SyncedInstance<Config>.Instance.bMode;
bool bWakenAfterWeapon = SyncedInstance<Config>.Instance.bWakenAfterWeapon;
if (bMode && ((bWakenAfterWeapon && wasDeactivatedByWeapon) || !bWakenAfterWeapon))
{
__instance.ToggleTurretEnabled(true);
result = true;
}
else
{
result = false;
}
}
}
((Component)__instance).gameObject.GetComponent<TurretHitStatus>().hitCount = num;
return result;
}
public static IEnumerator TurnOffAndOnTurret(Turret _turret, float duration)
{
((Component)_turret).gameObject.GetComponent<TurretHitStatus>().wasDeactivatedByWeapon = true;
_turret.ToggleTurretEnabled(false);
yield return (object)new WaitForSeconds(duration);
((Component)_turret).gameObject.GetComponent<TurretHitStatus>().wasDeactivatedByWeapon = false;
_turret.ToggleTurretEnabled(true);
}
}
}