Skip to content

Commit

Permalink
refactor: improve code structure
Browse files Browse the repository at this point in the history
  • Loading branch information
Hypick122 committed Feb 24, 2024
1 parent dd5f80d commit cc60cad
Show file tree
Hide file tree
Showing 6 changed files with 75 additions and 47 deletions.
20 changes: 14 additions & 6 deletions ExplosivePresents/NetworkHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ public void CustomExplodeMineServerRpc(Vector3 explosionPosition)
if (networkManager == null || !networkManager.IsListening)
return;

if (__rpc_exec_stage != __RpcExecStage.Server && (networkManager.IsClient || networkManager.IsHost)) { }
if (__rpc_exec_stage != __RpcExecStage.Server && (networkManager.IsClient || networkManager.IsHost))
{
}

if (__rpc_exec_stage == __RpcExecStage.Server && (networkManager.IsServer || networkManager.IsHost))
{
Expand All @@ -31,15 +33,19 @@ public void CustomExplodeMineClientRpc(Vector3 explosionPosition)
if (networkManager == null || !networkManager.IsListening)
return;

if (__rpc_exec_stage != __RpcExecStage.Client && (networkManager.IsServer || networkManager.IsHost)) { }
if (__rpc_exec_stage != __RpcExecStage.Client && (networkManager.IsServer || networkManager.IsHost))
{
}

if (__rpc_exec_stage == __RpcExecStage.Client && (networkManager.IsClient || networkManager.IsHost))
{
base.StartCoroutine(DelayedExplosion(explosionPosition, true, Plugin.Config.KillRange, Plugin.Config.DamageRange, Plugin.Config.Delay));
base.StartCoroutine(DelayedExplosion(explosionPosition, true, Plugin.Config.KillRange,
Plugin.Config.DamageRange, Plugin.Config.Delay));
}
}

static IEnumerator DelayedExplosion(Vector3 explosionPosition, bool spawnExplosionEffect = false, float killRange = 1f, float damageRange = 1f, float Delay = 1)
private static IEnumerator DelayedExplosion(Vector3 explosionPosition, bool spawnExplosionEffect = false,
float killRange = 1f, float damageRange = 1f, float Delay = 1)
{
Landmine landmine = Resources.FindObjectsOfTypeAll<Landmine>()[0];

Expand All @@ -56,7 +62,8 @@ static IEnumerator DelayedExplosion(Vector3 explosionPosition, bool spawnExplosi
yield return new WaitForSeconds(Delay);

mineAudio.GetComponent<AudioSource>().PlayOneShot(landmine.mineDetonate, 1f);
Landmine.SpawnExplosion(explosionPosition + Vector3.up, spawnExplosionEffect: spawnExplosionEffect, killRange, damageRange);
Landmine.SpawnExplosion(explosionPosition + Vector3.up, spawnExplosionEffect: spawnExplosionEffect, killRange,
damageRange);
// }
}

Expand All @@ -67,6 +74,7 @@ public override void OnNetworkSpawn()

if (Instance == null)
Instance = this;

base.OnNetworkSpawn();
}
}
}
65 changes: 43 additions & 22 deletions ExplosivePresents/Patches/GiftBoxItemPatch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,13 @@ internal class GiftBoxItemPatch
{
[HarmonyPatch("OpenGiftBoxServerRpc")]
[HarmonyPrefix]
static bool OpenGiftBox(GiftBoxItem __instance)
public static bool OpenGiftBox(GiftBoxItem __instance)
{
if (Mathf.Clamp(Plugin.Config.SpawnChance, 0f, 100f) / 100f > Random.Range(0f, 0.99f))
{
NetworkHandler.Instance.CustomExplodeMineServerRpc(__instance.transform.position);
return OpenGiftBoxCustom(__instance, true);
}
return OpenGiftBoxCustom(__instance);
if (!(Mathf.Clamp(Plugin.Config.SpawnChance, 0f, 100f) / 100f > Random.Range(0f, 0.99f)))
return OpenGiftBoxCustom(__instance);

NetworkHandler.Instance.CustomExplodeMineServerRpc(__instance.transform.position);
return OpenGiftBoxCustom(__instance, true);
}

private static bool OpenGiftBoxCustom(GiftBoxItem __instance, bool explosive = false)
Expand All @@ -27,51 +26,59 @@ private static bool OpenGiftBoxCustom(GiftBoxItem __instance, bool explosive = f
if (networkManager == null || !networkManager.IsListening)
return false;

if ((RpcExecStage)__instance.GetType().GetField("__rpc_exec_stage", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(__instance) != RpcExecStage.Server && (networkManager.IsClient || networkManager.IsHost))
if (GetPrivateField<RpcExecStage>(__instance, "__rpc_exec_stage") != RpcExecStage.Server &&
(networkManager.IsClient || networkManager.IsHost))
{
ServerRpcParams serverRpcParams = new();
FastBufferWriter bufferWriter = (FastBufferWriter)__instance.GetType().GetMethod("__beginSendServerRpc", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(__instance, [2878544999u, serverRpcParams, RpcDelivery.Reliable]);
__instance.GetType().GetMethod("__endSendServerRpc", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(__instance, [bufferWriter, 2878544999u, serverRpcParams, RpcDelivery.Reliable]);

FastBufferWriter bufferWriter = (FastBufferWriter)GetPrivateMethod(__instance, "__beginSendServerRpc",
[2878544999u, serverRpcParams, RpcDelivery.Reliable]);
GetPrivateMethod(__instance, "__endSendServerRpc",
[bufferWriter, 2878544999u, serverRpcParams, RpcDelivery.Reliable]);
}
if ((RpcExecStage)__instance.GetType().GetField("__rpc_exec_stage", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(__instance) != RpcExecStage.Server || (!networkManager.IsClient && !networkManager.IsHost))

if (GetPrivateField<RpcExecStage>(__instance, "__rpc_exec_stage") != RpcExecStage.Server ||
(!networkManager.IsClient && !networkManager.IsHost))
return false;

if (explosive)
{
Plugin.Log.LogInfo("OPEN GIFTBOX WTTH BOMB AHAHAAHAAH");
Plugin.Log.LogInfo("Opening a gift with a bomb inside :)");
__instance.OpenGiftBoxNoPresentClientRpc();
return false;
}

Plugin.Log.LogInfo("OPEN GIFTBOX without bomb :(");
Plugin.Log.LogInfo("Opening a gift without a bomb :(");

GameObject gameObject = null;
int presentValue = 0;
var presentValue = 0;
Vector3 vector = Vector3.zero;
GameObject objectInPresent = (GameObject)__instance.GetType().GetField("objectInPresent", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(__instance);
GameObject objectInPresent = GetPrivateField<GameObject>(__instance, "objectInPresent");

if (objectInPresent == null)
Debug.LogError("Error: There is no object in gift box!");
else
{
Transform parent;
if (((__instance.playerHeldBy != null && __instance.playerHeldBy.isInElevator) || StartOfRound.Instance.inShipPhase) && RoundManager.Instance.spawnedScrapContainer != null)
if (((__instance.playerHeldBy != null && __instance.playerHeldBy.isInElevator) ||
StartOfRound.Instance.inShipPhase) && RoundManager.Instance.spawnedScrapContainer != null)
parent = RoundManager.Instance.spawnedScrapContainer;
else
parent = StartOfRound.Instance.elevatorTransform;

vector = __instance.transform.position + Vector3.up * 0.25f;
gameObject = Object.Instantiate(objectInPresent, vector, Quaternion.identity, parent);
GrabbableObject component = gameObject.GetComponent<GrabbableObject>();
PlayerControllerB previousPlayerHeldBy = (PlayerControllerB)__instance.GetType().GetField("previousPlayerHeldBy", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(__instance);
PlayerControllerB previousPlayerHeldBy =
GetPrivateField<PlayerControllerB>(__instance, "previousPlayerHeldBy");

component.startFallingPosition = vector;
__instance.StartCoroutine(__instance.SetObjectToHitGroundSFX(component));
component.targetFloorPosition = component.GetItemFloorPosition(__instance.transform.position);
if (previousPlayerHeldBy != null && previousPlayerHeldBy.isInHangarShipRoom)
previousPlayerHeldBy.SetItemInElevator(droppedInShipRoom: true, droppedInElevator: true, component);

presentValue = (int)__instance.GetType().GetField("objectInPresentValue", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(__instance);
presentValue = GetPrivateField<int>(__instance, "objectInPresent");
component.SetScrapValue(presentValue);
component.NetworkObject.Spawn();
}
Expand All @@ -85,8 +92,22 @@ private static bool OpenGiftBoxCustom(GiftBoxItem __instance, bool explosive = f

private enum RpcExecStage
{
None,
Server,
Client
Server
}

private static object GetPrivateMethod(object instance, string methodName, params object[] args)
{
const BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance;
MethodInfo field = instance.GetType().GetMethod(methodName, bindingFlags);

return field?.Invoke(instance, args);
}

private static T GetPrivateField<T>(object instance, string fieldName)
{
const BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance;
FieldInfo field = instance.GetType().GetField(fieldName, bindingFlags);

return (T)field?.GetValue(instance);
}
}
}
10 changes: 5 additions & 5 deletions ExplosivePresents/Patches/NetworkObjectManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@ public static void Init()

// var MainAssetBundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Assets/netcodemod"));
var path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Assets/netcodemod");
AssetBundle MainAssetBundle;
AssetBundle mainAssetBundle;
if (File.Exists(path))
MainAssetBundle = AssetBundle.LoadFromFile(path);
mainAssetBundle = AssetBundle.LoadFromFile(path);
else
MainAssetBundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "netcodemod"));
mainAssetBundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "netcodemod"));

Plugin.Log.LogInfo($"Loading NetworkManager Prefab: {MainAssetBundle}");
networkPrefab = (GameObject)MainAssetBundle.LoadAsset("Assets/Necode/NetwordManager.prefab");
Plugin.Log.LogInfo($"Loading NetworkManager Prefab: {mainAssetBundle}");
networkPrefab = (GameObject)mainAssetBundle.LoadAsset("Assets/Necode/NetwordManager.prefab");
networkPrefab.AddComponent<NetworkHandler>();

NetworkManager.Singleton.AddNetworkPrefab(networkPrefab);
Expand Down
10 changes: 4 additions & 6 deletions ExplosivePresents/Plugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ namespace Hypick;
[BepInIncompatibility("ExplodingPresents")]
public class Plugin : BaseUnityPlugin
{
public static Plugin Instance { get; set; }
private static Plugin Instance { get; set; }

public static ManualLogSource Log => Instance.Logger;

public static new PluginConfig Config;
public new static PluginConfig Config;

private readonly Harmony _harmony = new(PluginInfo.PLUGIN_GUID);

Expand Down Expand Up @@ -45,11 +45,9 @@ private static void NetcodePatcher()
foreach (var method in methods)
{
var attributes = method.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), false);
if (attributes.Length > 0)
{
if (attributes.Length > 0)
method.Invoke(null, null);
}
}
}
}
}
}
15 changes: 8 additions & 7 deletions ExplosivePresents/PluginConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,19 @@ public static class Categories

public class PluginConfig
{
public bool ImmediateExplosion;
public float SpawnChance;
public float KillRange;
public float DamageRange;
public float Delay;
public bool ImmediateExplosion { get; }
public float SpawnChance { get; }
public float KillRange { get; }
public float DamageRange { get; }
public float Delay { get; }

public PluginConfig(ConfigFile cfg)
{
ImmediateExplosion = cfg.Bind<bool>(Categories.Present, nameof(ImmediateExplosion), false, "").Value;
SpawnChance = cfg.Bind<float>(Categories.Present, nameof(SpawnChance), 10f, new ConfigDescription("Chance of the present exploding", new AcceptableValueRange<float>(0f, 100f))).Value;
SpawnChance = cfg.Bind<float>(Categories.Present, nameof(SpawnChance), 10f,
new ConfigDescription("Chance of the present exploding", new AcceptableValueRange<float>(0f, 100f))).Value;
KillRange = cfg.Bind<float>(Categories.Present, nameof(KillRange), 5.7f, "Explosion kill range").Value;
DamageRange = cfg.Bind<float>(Categories.Present, nameof(DamageRange), 6.4f, "Explosion damage range").Value;
Delay = cfg.Bind<float>(Categories.Present, nameof(Delay), 0.5f, "Delay before explosion. In seconds").Value;
}
}
}
2 changes: 1 addition & 1 deletion thunderstore.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ outdir = "build"

[[build.copy]]
source = "ExplosivePresents/bin/Hypick.ExplosivePresents.dll"
target = "ExplosivePresents.dll"
target = "BepInEx/plugins/ExplosivePresents.dll"

[[build.copy]]
source = "CHANGELOG.md"
Expand Down

0 comments on commit cc60cad

Please sign in to comment.