Skip to content

Commit

Permalink
GadgetCore v2.0.4.2
Browse files Browse the repository at this point in the history
  • Loading branch information
SuperKael committed Jul 14, 2021
1 parent 03c667f commit f85a80c
Show file tree
Hide file tree
Showing 14 changed files with 155 additions and 65 deletions.
31 changes: 28 additions & 3 deletions API/GadgetConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,19 @@ public string ReadString(string key, string defaultValue, string vanillaValue =
return ConfigData[key];
}

/// <summary>
/// Reads a <see cref="string"/> array value from the config.
/// </summary>
public string[] ReadStringArray(string key, string[] defaultValue, string[] vanillaValue = default, bool requiresRestart = false, string[][] allowed = null, params string[] comments)
{
List<string> commentList = new List<string>();
commentList.AddRange(comments);
GenerateMetaComments(commentList, defaultValue, vanillaValue, requiresRestart, allowed);
if (!ConfigData.ContainsKey(key)) ConfigData[key] = defaultValue.ToString();
ConfigData.GetKeyData(key).Comments = commentList;
return ConfigData[key].Split(',');
}

/// <summary>
/// Reads a <see cref="KeyCode"/> value from the config.
/// </summary>
Expand Down Expand Up @@ -276,6 +289,18 @@ public void WriteString(string key, string value, string defaultValue = default,
ConfigData.GetKeyData(key).Comments = commentList;
}

/// <summary>
/// Writes a <see cref="string"/> array value to the config.
/// </summary>
public void WriteStringArray(string key, string[] value, string[] defaultValue = default, string[] vanillaValue = default, bool requiresRestart = false, string[][] allowed = null, params string[] comments)
{
List<string> commentList = new List<string>();
commentList.AddRange(comments);
GenerateMetaComments(commentList, defaultValue, vanillaValue, requiresRestart, allowed);
ConfigData[key] = value.Concat(",");
ConfigData.GetKeyData(key).Comments = commentList;
}

/// <summary>
/// Writes a <see cref="KeyCode"/> value to the config.
/// </summary>
Expand Down Expand Up @@ -314,9 +339,9 @@ public void Write<T>(string key, T value, T defaultValue = default, T vanillaVal

private void GenerateMetaComments<T>(List<string> commentList, T defaultValue = default, T vanillaValue = default, bool requiresRestart = false, T[] allowed = null, params T[] range)
{
if (EqualityComparer<T>.Default.Equals(defaultValue, default) && defaultValue != null)
if (!EqualityComparer<T>.Default.Equals(defaultValue, default) && defaultValue != null)
{
if (EqualityComparer<T>.Default.Equals(vanillaValue, default) && vanillaValue != null)
if (!EqualityComparer<T>.Default.Equals(vanillaValue, default) && vanillaValue != null)
{
commentList.Add("[Default(s): " + defaultValue + " | Vanilla: " + vanillaValue + "]");
}
Expand All @@ -325,7 +350,7 @@ private void GenerateMetaComments<T>(List<string> commentList, T defaultValue =
commentList.Add("[Default(s): " + defaultValue + "]");
}
}
else if (EqualityComparer<T>.Default.Equals(vanillaValue, default) && vanillaValue != null)
else if (!EqualityComparer<T>.Default.Equals(vanillaValue, default) && vanillaValue != null)
{
commentList.Add("[Vanilla: " + vanillaValue + "]");
}
Expand Down
20 changes: 18 additions & 2 deletions API/GadgetConsole.cs
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ public static int BroadcastMessage(GadgetConsoleMessage message)
public static int BroadcastMessage(string text, string sender = null, MessageSeverity severity = MessageSeverity.RAW)
{
int ID = Print(text, sender, severity);
RPCHooks.Singleton.BroadcastConsoleMessage(text, sender, severity, GetMessage(ID).SendTime);
RPCHooks.Singleton.BroadcastConsoleMessage(ID, text, sender, severity, GetMessage(ID).SendTime);
return ID;
}

Expand Down Expand Up @@ -301,6 +301,22 @@ public static void RemoveMessage(float sendTime)
RemoveMessage(messages.FindLastIndex(x => x.SendTime == sendTime));
}

/// <summary>
/// Like <see cref="ReplaceMessage(int, GadgetConsoleMessage)"/>, but replaces a broadcast from every player's console.
/// </summary>
public static void ReplaceBroadcast(int index, GadgetConsoleMessage message)
{
ReplaceBroadcast(index, message.Text, message.Sender, message.Severity, message.SendTime);
}

/// <summary>
/// Like <see cref="ReplaceMessage(int, GadgetConsoleMessage)"/>, but replaces a broadcast from every player's console.
/// </summary>
public static void ReplaceBroadcast(int index, string text, string sender = null, MessageSeverity severity = MessageSeverity.RAW, float sendTime = -1)
{
RPCHooks.Singleton.ReplaceConsoleBroadcast(index, text, sender, severity, sendTime);
}

/// <summary>
/// Like <see cref="RemoveMessage(int)"/>, but removes a broadcast from every player's console.
/// </summary>
Expand Down Expand Up @@ -334,7 +350,7 @@ private static int AddMessage(GadgetConsoleMessage message)
if (messages[messages.IndexOf(message)]?.Component != null) Destroy(messages[messages.IndexOf(message)].Component.gameObject);
messages[messages.IndexOf(message)] = null;
}
for (int i = 0;i < 2;i++)
for (int i = 0; i < 2; i++)
{
message.SendTime = Time.realtimeSinceStartup;
Text textComponent = new GameObject("Message " + messages.IndexOf(message) + ", sent at time: " + message.SendTime, typeof(RectTransform), typeof(CanvasRenderer), typeof(Text)).GetComponent<Text>();
Expand Down
4 changes: 2 additions & 2 deletions API/GadgetCoreAPI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ public static class GadgetCoreAPI
/// <summary>
/// The version numbers for this version of Gadget Core. You generally shouldn't access this directly, instead use <see cref="GetRawVersion()"/>
/// </summary>
public const string RAW_VERSION = "2.0.4.1";
public const string RAW_VERSION = "2.0.4.2";
/// <summary>
/// A slightly more informative version. You generally shouldn't access this directly, instead use <see cref="GetFullVersion()"/>
/// </summary>
public const string FULL_VERSION = "2.0.4.1 - Power Commands Edition";
public const string FULL_VERSION = "2.0.4.2 - Power Commands Edition";
/// <summary>
/// Indicates whether this version of GadgetCore is a beta version. You generally shouldn't access this directly, instead use <see cref="GetIsBeta()"/>
/// </summary>
Expand Down
44 changes: 8 additions & 36 deletions API/GadgetNetwork.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,7 @@ public static float GetTimeSinceConnect()
/// </summary>
public static bool HostHasReg(Registry reg)
{
if (!MatrixReady)
{
GadgetCore.CoreLogger.LogWarning("Network ID conversion cannot be performed when the ID conversion matrix is not ready!", false);
return false;
}
if (!MatrixReady) throw new InvalidOperationException("Network ID conversion cannot be performed when the ID conversion matrix is not ready!");
return IDConversionMatrixToHost.ContainsKey(reg.GetRegistryName());
}

Expand All @@ -74,11 +70,7 @@ public static object ConvertIDToHost(this Registry reg, ref object ID)
{
if (Network.isServer) return ID;
int id = (int)ID;
if (!MatrixReady)
{
GadgetCore.CoreLogger.LogWarning("Network ID conversion cannot be performed when the ID conversion matrix is not ready!", false);
return ID;
}
if (!MatrixReady) throw new InvalidOperationException("Network ID conversion cannot be performed when the ID conversion matrix is not ready!");
if (reg == null) return ID;
if (IDConversionMatrixToHost.ContainsKey(reg.GetRegistryName()) && IDConversionMatrixToHost[reg.GetRegistryName()].TryGetValue(id, out id))
{
Expand All @@ -94,11 +86,7 @@ public static object ConvertIDToHost(this Registry reg, ref object ID)
public static int ConvertIDToHost(this Registry reg, ref int ID)
{
if (Network.isServer) return ID;
if (!MatrixReady)
{
GadgetCore.CoreLogger.LogWarning("Network ID conversion cannot be performed when the ID conversion matrix is not ready!", false);
return ID;
}
if (!MatrixReady) throw new InvalidOperationException("Network ID conversion cannot be performed when the ID conversion matrix is not ready!");
if (reg == null) return ID;
if (IDConversionMatrixToHost.ContainsKey(reg.GetRegistryName()) && IDConversionMatrixToHost[reg.GetRegistryName()].TryGetValue(ID, out int newID))
{
Expand All @@ -114,11 +102,7 @@ public static int ConvertIDToHost(this Registry reg, ref int ID)
public static int ConvertIDToHost(this Registry reg, int ID)
{
if (Network.isServer) return ID;
if (!MatrixReady)
{
GadgetCore.CoreLogger.LogWarning("Network ID conversion cannot be performed when the ID conversion matrix is not ready!", false);
return ID;
}
if (!MatrixReady) throw new InvalidOperationException("Network ID conversion cannot be performed when the ID conversion matrix is not ready!");
if (reg == null) return ID;
if (IDConversionMatrixToHost.ContainsKey(reg.GetRegistryName()) && IDConversionMatrixToHost[reg.GetRegistryName()].TryGetValue(ID, out int newID))
{
Expand All @@ -135,11 +119,7 @@ public static object ConvertIDToLocal(this Registry reg, ref object ID)
{
if (Network.isServer) return ID;
int id = (int)ID;
if (!MatrixReady)
{
GadgetCore.CoreLogger.LogWarning("Network ID conversion cannot be performed when the ID conversion matrix is not ready!", false);
return ID;
}
if (!MatrixReady) throw new InvalidOperationException("Network ID conversion cannot be performed when the ID conversion matrix is not ready!");
if (reg == null) return ID;
if (IDConversionMatrixToLocal.ContainsKey(reg.GetRegistryName()) && IDConversionMatrixToLocal[reg.GetRegistryName()].TryGetValue(id, out id))
{
Expand All @@ -155,11 +135,7 @@ public static object ConvertIDToLocal(this Registry reg, ref object ID)
public static int ConvertIDToLocal(this Registry reg, ref int ID)
{
if (Network.isServer) return ID;
if (!MatrixReady)
{
GadgetCore.CoreLogger.LogWarning("Network ID conversion cannot be performed when the ID conversion matrix is not ready!", false);
return ID;
}
if (!MatrixReady) throw new InvalidOperationException("Network ID conversion cannot be performed when the ID conversion matrix is not ready!");
if (reg == null) return ID;
if (IDConversionMatrixToLocal.ContainsKey(reg.GetRegistryName()) && IDConversionMatrixToLocal[reg.GetRegistryName()].TryGetValue(ID, out int newID))
{
Expand All @@ -175,11 +151,7 @@ public static int ConvertIDToLocal(this Registry reg, ref int ID)
public static int ConvertIDToLocal(this Registry reg, int ID)
{
if (Network.isServer) return ID;
if (!MatrixReady)
{
GadgetCore.CoreLogger.LogWarning("Network ID conversion cannot be performed when the ID conversion matrix is not ready!", false);
return ID;
}
if (!MatrixReady) throw new InvalidOperationException("Network ID conversion cannot be performed when the ID conversion matrix is not ready!");
if (reg == null) return ID;
if (IDConversionMatrixToLocal.ContainsKey(reg.GetRegistryName()) && IDConversionMatrixToLocal[reg.GetRegistryName()].TryGetValue(ID, out int newID))
{
Expand Down Expand Up @@ -241,14 +213,14 @@ internal static void ParseIDMatrixData(string packedData)
}
}
MatrixReady = true;
OnMatrixReady?.Invoke(true);
}
catch (Exception e)
{
GadgetCore.CoreLogger.LogError("Received bad host ID conversion data: " + packedData);
GadgetCore.CoreLogger.LogError("Exception that occured while parsing host ID conversion data:" + Environment.NewLine + e.ToString());
Network.Disconnect();
}
OnMatrixReady?.Invoke(true);
}

/// <summary>
Expand Down
3 changes: 1 addition & 2 deletions API/GadgetUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,9 @@ public static void SafeCopyTexture(Texture2D src, int srcElement, int srcMip, in
{
RenderTexture renderTex = RenderTexture.GetTemporary(src.width, src.height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.Linear);
Graphics.Blit(src, renderTex);
RenderTexture previous = RenderTexture.active;
RenderTexture.active = renderTex;
dst.ReadPixels(new Rect(srcX, srcY, srcWidth, srcHeight), dstX, dstY);
RenderTexture.active = previous;
RenderTexture.active = null;
RenderTexture.ReleaseTemporary(renderTex);
}
else
Expand Down
5 changes: 1 addition & 4 deletions GadgetCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,10 +134,7 @@ internal static void Initialize()
{
if (GadgetCoreConfig.MaxLogArchives > 0) BackupLogFiles();
}
catch (Exception e)
{
Debug.Log("Failed to backup old log files: " + e);
}
catch (Exception) { }
try
{
CoreLogger = new GadgetLogger("GadgetCore", "Core");
Expand Down
26 changes: 19 additions & 7 deletions GadgetLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,11 @@ public void LogConsole(object text, GadgetConsole.MessageSeverity severity = Gad
/// </summary>
public void Log(object text)
{
foreach (string line in (text?.ToString() ?? "null").Replace('\r', '\n').Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries))
streamWriter?.WriteLine("[" + DateTime.Now + "]" + (!string.IsNullOrEmpty(LoggerName) ? "[" + LoggerName + "]" : "") + "[Info] " + line);
lock (streamWriter)
{
foreach (string line in (text?.ToString() ?? "null").Replace('\r', '\n').Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries))
streamWriter?.WriteLine("[" + DateTime.Now + "]" + (!string.IsNullOrEmpty(LoggerName) ? "[" + LoggerName + "]" : "") + "[Info] " + line);
}
}

/// <summary>
Expand All @@ -101,8 +104,11 @@ public void Log(object text)
public void LogWarning(object text, bool includeConsole = true)
{
if (includeConsole) GadgetConsole.Print(text?.ToString() ?? "null", LoggerName, GadgetConsole.MessageSeverity.WARN);
foreach (string line in (text?.ToString() ?? "null").Replace('\r', '\n').Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries))
streamWriter?.WriteLine("[" + DateTime.Now + "]" + (!string.IsNullOrEmpty(LoggerName) ? "[" + LoggerName + "]" : "") + "[Warning] " + line);
lock (streamWriter)
{
foreach (string line in (text?.ToString() ?? "null").Replace('\r', '\n').Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries))
streamWriter?.WriteLine("[" + DateTime.Now + "]" + (!string.IsNullOrEmpty(LoggerName) ? "[" + LoggerName + "]" : "") + "[Warning] " + line);
}
}

/// <summary>
Expand All @@ -111,16 +117,22 @@ public void LogWarning(object text, bool includeConsole = true)
public void LogError(object text, bool includeConsole = true)
{
if (includeConsole) GadgetConsole.Print(text?.ToString() ?? "null", LoggerName, GadgetConsole.MessageSeverity.ERROR);
foreach (string line in (text?.ToString() ?? "null").Replace('\r', '\n').Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries))
streamWriter?.WriteLine("[" + DateTime.Now + "]" + (!string.IsNullOrEmpty(LoggerName) ? "[" + LoggerName + "]" : "") + "[Error] " + line);
lock (streamWriter)
{
foreach (string line in (text?.ToString() ?? "null").Replace('\r', '\n').Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries))
streamWriter?.WriteLine("[" + DateTime.Now + "]" + (!string.IsNullOrEmpty(LoggerName) ? "[" + LoggerName + "]" : "") + "[Error] " + line);
}
}

/// <summary>
/// Disposes the internal <see cref="StreamWriter"/> used by this logger.
/// </summary>
public void Dispose()
{
streamWriter?.Dispose();
lock (streamWriter)
{
streamWriter?.Dispose();
}
}
}
}
23 changes: 23 additions & 0 deletions Patches/Patch_GameScript_OnPlayerDisconnected.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using HarmonyLib;
using GadgetCore.API;
using UnityEngine;
using System.Collections;
using System.Linq;

namespace GadgetCore.Patches
{
[HarmonyPatch(typeof(GameScript))]
[HarmonyPatch("OnPlayerDisconnected")]
static class Patch_GameScript_OnPlayerDisconnected
{
[HarmonyPrefix]
public static void Prefix(GameScript __instance, NetworkPlayer pl)
{
string name = GadgetNetwork.GetNameByNetworkPlayer(pl);
if (!string.IsNullOrEmpty(name))
{
GadgetConsole.Print($"{name} has left the game.");
}
}
}
}
4 changes: 2 additions & 2 deletions Patches/Patch_Object_Instantiate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,13 @@ public static void Postfix(ref UnityEngine.Object __result, ref HideFlags __stat
if ((__state & HideFlags.HideInInspector) == HideFlags.HideInInspector)
{
__result.hideFlags &= ~(HideFlags.HideAndDontSave | HideFlags.HideInInspector);
if (__result is GameObject obj)
/*if (__result is GameObject obj)
{
foreach (Component comp in obj.GetComponents(typeof(Component)))
{
if (!(comp is Transform) && !(comp is Rigidbody)) obj.ReplaceComponent(comp.GetType(), comp.GetType());
}
}
}*/
(__result as GameObject)?.SetActive(true);
}
}
Expand Down
4 changes: 3 additions & 1 deletion Patches/Patch_PlayerScript_SetName.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ static class Patch_PlayerScript_SetName
public static void Prefix(PlayerScript __instance, ref string n)
{
PlayerScript existingPlayer = null;
if (n == Menuu.curName)
bool isSelf = n == Menuu.curName;
if (isSelf)
{
existingPlayer = GadgetCoreAPI.GetPlayerByName(n);
if (existingPlayer != null && existingPlayer != __instance)
Expand Down Expand Up @@ -70,6 +71,7 @@ public static void Prefix(PlayerScript __instance, ref string n)
GadgetNetwork.NetworkPlayersByName[n] = existingPlayer.GetComponent<NetworkView>().owner;
GadgetNetwork.NamesByNetworkPlayer[existingPlayer.GetComponent<NetworkView>().owner] = n;
if (__instance.GetComponent<NetworkView>().owner == RPCHooks.Singleton.GetComponent<NetworkView>().owner) GadgetNetwork.ServerPlayerName = n;
if (!isSelf) GadgetConsole.Print($"{n} has joined the game.");
}
}
}
Loading

0 comments on commit f85a80c

Please sign in to comment.