new hook call method + function to delegate conversion

This commit is contained in:
Oiltanker
2022-04-15 17:15:45 +03:00
parent 891efb4c4f
commit 3eba20ecb7
39 changed files with 470 additions and 676 deletions
@@ -923,7 +923,7 @@ namespace Barotrauma
SoundManager?.Update(); SoundManager?.Update();
GameMain.LuaCs.Update(); GameMain.LuaCs.Update();
GameMain.LuaCs.HookBase.Call("think"); GameMain.LuaCs.Hook.Call("think");
Timing.Accumulator -= Timing.Step; Timing.Accumulator -= Timing.Step;
@@ -2830,9 +2830,8 @@ namespace Barotrauma.Networking
public override void AddChatMessage(ChatMessage message) public override void AddChatMessage(ChatMessage message)
{ {
var should = new LuaResult(GameMain.LuaCs.HookBase.Call("chatMessage", message.Text, message.SenderClient, message.Type, message)); var should = GameMain.LuaCs.Hook.Call<bool?>("chatMessage", message.Text, message.SenderClient, message.Type, message);
if (should != null && should.Value) return;
if (should.Bool()) return;
base.AddChatMessage(message); base.AddChatMessage(message);
@@ -562,7 +562,7 @@ namespace Barotrauma
allowInput = true; allowInput = true;
} }
GameMain.LuaCs.HookBase.Call("keyUpdate", deltaTime); GameMain.LuaCs.Hook.Call("keyUpdate", deltaTime);
oldMouseState = mouseState; oldMouseState = mouseState;
mouseState = latestMouseState; mouseState = latestMouseState;
@@ -25,7 +25,7 @@ namespace Barotrauma
GameServer.Log(GameServer.CharacterLogName(this) + " has died (Cause of death: " + causeOfDeath + ")", ServerLog.MessageType.Attack); GameServer.Log(GameServer.CharacterLogName(this) + " has died (Cause of death: " + causeOfDeath + ")", ServerLog.MessageType.Attack);
} }
} }
GameMain.LuaCs.HookBase.Call("characterDeath", this,causeOfDeathAffliction); GameMain.LuaCs.Hook.Call("characterDeath", this,causeOfDeathAffliction);
if (HasAbilityFlag(AbilityFlags.RetainExperienceForNewCharacter)) if (HasAbilityFlag(AbilityFlags.RetainExperienceForNewCharacter))
{ {
@@ -348,9 +348,9 @@ namespace Barotrauma
CoroutineManager.Update((float)Timing.Step, (float)Timing.Step); CoroutineManager.Update((float)Timing.Step, (float)Timing.Step);
GameMain.LuaCs.Update(); GameMain.LuaCs.Update();
GameMain.LuaCs.HookBase.Call("think", new object[] { }); GameMain.LuaCs.Hook.Call("think", new object[] { });
performanceCounterTimer.Stop(); performanceCounterTimer.Stop();
LuaTimer.LastUpdateTime = performanceCounterTimer.ElapsedMilliseconds; LuaCsTimer.LastUpdateTime = performanceCounterTimer.ElapsedMilliseconds;
performanceCounterTimer.Reset(); performanceCounterTimer.Reset();
Timing.Accumulator -= Timing.Step; Timing.Accumulator -= Timing.Step;
@@ -133,9 +133,9 @@ namespace Barotrauma.Networking
return; return;
} }
var should = new LuaResult(GameMain.LuaCs.HookBase.Call("chatMessage", txt, c, type)); var should = GameMain.LuaCs.Hook.Call<bool?>("chatMessage", txt, c, type);
if (should.Bool()) if (should != null && should.Value)
{ {
return; return;
} }
@@ -290,7 +290,7 @@ namespace Barotrauma.Networking
SendConsoleMessage("Granted all permissions to " + newClient.Name + ".", newClient); SendConsoleMessage("Granted all permissions to " + newClient.Name + ".", newClient);
} }
GameMain.LuaCs.HookBase.Call("clientConnected", newClient); GameMain.LuaCs.Hook.Call("clientConnected", newClient);
SendChatMessage($"ServerMessage.JoinedServer~[client]={clName}", ChatMessageType.Server, null, changeType: PlayerConnectionChangeType.Joined); SendChatMessage($"ServerMessage.JoinedServer~[client]={clName}", ChatMessageType.Server, null, changeType: PlayerConnectionChangeType.Joined);
@@ -1804,7 +1804,7 @@ namespace Barotrauma.Networking
outmsg.Write((byte)ServerNetObject.CLIENT_LIST); outmsg.Write((byte)ServerNetObject.CLIENT_LIST);
outmsg.Write(LastClientListUpdateID); outmsg.Write(LastClientListUpdateID);
GameMain.LuaCs.HookBase.Call("writeClientList", c, outmsg); GameMain.LuaCs.Hook.Call("writeClientList", c, outmsg);
outmsg.Write((byte)connectedClients.Count); outmsg.Write((byte)connectedClients.Count);
foreach (Client client in connectedClients) foreach (Client client in connectedClients)
@@ -2251,7 +2251,7 @@ namespace Barotrauma.Networking
AssignJobs(teamClients); AssignJobs(teamClients);
var result = new LuaResult(GameMain.LuaCs.HookBase.Call("jobsAssigned")); GameMain.LuaCs.Hook.Call("jobsAssigned");
List<CharacterInfo> characterInfos = new List<CharacterInfo>(); List<CharacterInfo> characterInfos = new List<CharacterInfo>();
foreach (Client client in teamClients) foreach (Client client in teamClients)
@@ -2455,7 +2455,7 @@ namespace Barotrauma.Networking
roundStartTime = DateTime.Now; roundStartTime = DateTime.Now;
GameMain.LuaCs.HookBase.Call("roundStart"); GameMain.LuaCs.Hook.Call("roundStart");
startGameCoroutine = null; startGameCoroutine = null;
yield return CoroutineStatus.Success; yield return CoroutineStatus.Success;
@@ -2586,7 +2586,7 @@ namespace Barotrauma.Networking
Log("Ending the round...", ServerLog.MessageType.ServerMessage); Log("Ending the round...", ServerLog.MessageType.ServerMessage);
} }
GameMain.LuaCs.HookBase.Call("roundEnd"); GameMain.LuaCs.Hook.Call("roundEnd");
string endMessage = TextManager.FormatServerMessage("RoundSummaryRoundHasEnded"); string endMessage = TextManager.FormatServerMessage("RoundSummaryRoundHasEnded");
@@ -2697,12 +2697,12 @@ namespace Barotrauma.Networking
newName = Client.SanitizeName(newName); newName = Client.SanitizeName(newName);
if (newName == c.Name && newJob == c.PreferredJob && newTeam == c.PreferredTeam) { return false; } if (newName == c.Name && newJob == c.PreferredJob && newTeam == c.PreferredTeam) { return false; }
var result = new LuaResult(GameMain.LuaCs.HookBase.Call("tryChangeClientName", c, newName, newJob, newTeam)); var result = GameMain.LuaCs.Hook.Call<bool?>("tryChangeClientName", c, newName, newJob, newTeam);
if (!result.IsNull()) if (result != null)
{ {
LastClientListUpdateID++; LastClientListUpdateID++;
return result.Bool(); return result.Value;
} }
c.PreferredJob = newJob; c.PreferredJob = newJob;
@@ -2892,7 +2892,7 @@ namespace Barotrauma.Networking
{ {
if (client == null) return; if (client == null) return;
GameMain.LuaCs.HookBase.Call("clientDisconnected", client); GameMain.LuaCs.Hook.Call("clientDisconnected", client);
if (gameStarted && client.Character != null) if (gameStarted && client.Character != null)
{ {
@@ -3142,9 +3142,9 @@ namespace Barotrauma.Networking
var hookChatMsg = ChatMessage.Create(senderName, message, (ChatMessageType)type, senderCharacter, senderClient, changeType); var hookChatMsg = ChatMessage.Create(senderName, message, (ChatMessageType)type, senderCharacter, senderClient, changeType);
var should = new LuaResult(GameMain.LuaCs.HookBase.Call("modifyChatMessage", hookChatMsg, senderRadio)); var should = GameMain.LuaCs.Hook.Call<bool?>("modifyChatMessage", hookChatMsg, senderRadio);
if (should.Bool()) if (should != null && should.Value)
return; return;
@@ -3874,7 +3874,7 @@ namespace Barotrauma.Networking
{ {
if (GameMain.Server == null || !GameMain.Server.ServerSettings.SaveServerLogs) { return; } if (GameMain.Server == null || !GameMain.Server.ServerSettings.SaveServerLogs) { return; }
GameMain.LuaCs?.HookBase?.Call("serverLog", line, messageType); GameMain.LuaCs?.Hook?.Call("serverLog", line, messageType);
GameMain.Server.ServerSettings.ServerLog.WriteLine(line, messageType); GameMain.Server.ServerSettings.ServerLog.WriteLine(line, messageType);
@@ -184,9 +184,9 @@ namespace Barotrauma.Networking
var skipDeny = false; var skipDeny = false;
{ {
var result = new LuaResult(GameMain.LuaCs.HookBase.Call("lidgren.handleConnection", inc)); var result = GameMain.LuaCs.Hook.Call<bool?>("lidgren.handleConnection", inc);
if (!result.IsNull()) { if (result != null) {
if (result.Bool()) skipDeny = true; if (result.Value) skipDeny = true;
else return; else return;
} }
} }
@@ -206,18 +206,16 @@ namespace Barotrauma.Networking
protected void UpdatePendingClient(PendingClient pendingClient) protected void UpdatePendingClient(PendingClient pendingClient)
{ {
var result = new LuaResult(GameMain.LuaCs.HookBase.Call("handlePendingClient", pendingClient)); var skipRemove = false;
var result = GameMain.LuaCs.Hook.Call<bool?>("handlePendingClient", pendingClient);
if (result.Bool()) if (result != null) skipRemove = result.Value;
goto ignore;
if (connectedClients.Count >= serverSettings.MaxPlayers) if (!skipRemove && connectedClients.Count >= serverSettings.MaxPlayers)
{ {
RemovePendingClient(pendingClient, DisconnectReason.ServerFull, ""); RemovePendingClient(pendingClient, DisconnectReason.ServerFull, "");
} }
ignore:
if (IsPendingClientBanned(pendingClient, out string banReason)) if (IsPendingClientBanned(pendingClient, out string banReason))
{ {
RemovePendingClient(pendingClient, DisconnectReason.Banned, banReason); RemovePendingClient(pendingClient, DisconnectReason.Banned, banReason);
@@ -94,19 +94,19 @@ namespace Barotrauma.Networking
ChatMessage.CanUseRadio(sender.Character, out WifiComponent senderRadio) && ChatMessage.CanUseRadio(sender.Character, out WifiComponent senderRadio) &&
ChatMessage.CanUseRadio(recipient.Character, out WifiComponent recipientRadio)) ChatMessage.CanUseRadio(recipient.Character, out WifiComponent recipientRadio))
{ {
var should = new LuaResult(GameMain.LuaCs.HookBase.Call("canUseVoiceRadio", new object[] { sender, recipient })); var should = GameMain.LuaCs.Hook.Call<bool?>("canUseVoiceRadio", new object[] { sender, recipient });
if (!should.IsNull()) if (should != null)
return should.Bool(); return should.Value;
if (recipientRadio.CanReceive(senderRadio)) { return true; } if (recipientRadio.CanReceive(senderRadio)) { return true; }
} }
var should2 = new LuaResult(GameMain.LuaCs.HookBase.Call("changeLocalVoiceRange", new object[] { sender, recipient })); var should2 = GameMain.LuaCs.Hook.Call<float?>("changeLocalVoiceRange", sender, recipient);
float range = 1.0f; float range = 1.0f;
if (!should2.IsNull()) if (should2 != null)
range = should2.Float(); range = should2.Value;
//otherwise do a distance check //otherwise do a distance check
@@ -92,8 +92,8 @@ namespace Barotrauma
var traitorCandidates = new List<Tuple<Client, Character>>(); var traitorCandidates = new List<Tuple<Client, Character>>();
foreach (Client c in server.ConnectedClients) foreach (Client c in server.ConnectedClients)
{ {
var result = new LuaResult(GameMain.LuaCs.HookBase.Call("traitor.findTraitorCandidate", new object[] { c, team })); var result = GameMain.LuaCs.Hook.Call<bool?>("traitor.findTraitorCandidate", c, team);
if (result.Bool()) if (result != null && result.Value)
{ {
traitorCandidates.Add(Tuple.Create(c, c.Character)); traitorCandidates.Add(Tuple.Create(c, c.Character));
continue; continue;
@@ -234,7 +234,7 @@ namespace Barotrauma
foreach (var traitor in Traitors.Values) foreach (var traitor in Traitors.Values)
{ {
traitor.Greet(server, CodeWords, CodeResponse, message => pendingMessages[traitor].Add(message)); traitor.Greet(server, CodeWords, CodeResponse, message => pendingMessages[traitor].Add(message));
GameMain.LuaCs.HookBase.Call("traitor.traitorAssigned", new object[] { traitor }); GameMain.LuaCs.Hook.Call("traitor.traitorAssigned", new object[] { traitor });
} }
pendingMessages.ForEach(traitor => traitor.Value.ForEach(message => traitor.Key.SendChatMessage(message, Identifier))); pendingMessages.ForEach(traitor => traitor.Value.ForEach(message => traitor.Key.SendChatMessage(message, Identifier)));
pendingMessages.ForEach(traitor => traitor.Value.ForEach(message => traitor.Key.SendChatMessageBox(message, Identifier))); pendingMessages.ForEach(traitor => traitor.Value.ForEach(message => traitor.Key.SendChatMessageBox(message, Identifier)));
@@ -64,6 +64,8 @@
<Content Remove="..\BarotraumaShared\**\*.cs" /> <Content Remove="..\BarotraumaShared\**\*.cs" />
<Content Remove="..\BarotraumaShared\**\*.props" /> <Content Remove="..\BarotraumaShared\**\*.props" />
<Compile Include="..\BarotraumaShared\**\*.cs" /> <Compile Include="..\BarotraumaShared\**\*.cs" />
<Compile Remove="..\BarotraumaShared\SharedSource\Cs\CsHook.cs" />
<Compile Remove="..\BarotraumaShared\SharedSource\Lua\LuaClasses\LuaHook.cs" />
<Content Remove="DedicatedServer.exe" /> <Content Remove="DedicatedServer.exe" />
</ItemGroup> </ItemGroup>
@@ -80,9 +80,9 @@ namespace Barotrauma
public void AddObjective<T>(T objective) where T : AIObjective public void AddObjective<T>(T objective) where T : AIObjective
{ {
var result = new LuaResult(GameMain.LuaCs.HookBase.Call("AI.AddObjective", this, objective)); var result = GameMain.LuaCs.Hook.Call<bool?>("AI.AddObjective", this, objective);
if (result.Bool()) return; if (result != null && result.Value) return;
if (objective == null) if (objective == null)
{ {
@@ -1440,11 +1440,11 @@ namespace Barotrauma
// -> the character should be revived if there are no major afflictions in addition to lack of oxygen // -> the character should be revived if there are no major afflictions in addition to lack of oxygen
target.Oxygen = Math.Max(target.Oxygen + 10.0f, 10.0f); target.Oxygen = Math.Max(target.Oxygen + 10.0f, 10.0f);
GameMain.LuaCs.HookBase.Call("human.CPRSuccess", this); GameMain.LuaCs.Hook.Call("human.CPRSuccess", this);
} }
else else
{ {
GameMain.LuaCs.HookBase.Call("human.CPRFailed", this); GameMain.LuaCs.Hook.Call("human.CPRFailed", this);
} }
} }
} }
@@ -745,11 +745,11 @@ namespace Barotrauma
float impactDamage = Math.Min((impact - ImpactTolerance) * ImpactDamageMultiplayer, character.MaxVitality * MaxImpactDamage); float impactDamage = Math.Min((impact - ImpactTolerance) * ImpactDamageMultiplayer, character.MaxVitality * MaxImpactDamage);
var should = new LuaResult(GameMain.LuaCs.HookBase.Call("changeFallDamage", new object[] { impactDamage, character, impactPos, velocity })); var should = GameMain.LuaCs.Hook.Call<float?>("changeFallDamage", impactDamage, character, impactPos, velocity);
if (!should.IsNull()) if (should != null)
{ {
impactDamage = should.Float(); impactDamage = should.Value;
} }
character.LastDamageSource = null; character.LastDamageSource = null;
@@ -1043,7 +1043,7 @@ namespace Barotrauma
} }
#endif #endif
GameMain.LuaCs.HookBase.Call("characterCreated", new object[] { newCharacter }); GameMain.LuaCs.Hook.Call("characterCreated", new object[] { newCharacter });
return newCharacter; return newCharacter;
} }
@@ -388,7 +388,7 @@ namespace Barotrauma
AdditionStrength -= amount; AdditionStrength -= amount;
} }
#if SERVER #if SERVER
GameMain.LuaCs.HookBase.Call("afflictionUpdate", new object[] { this, characterHealth, targetLimb, deltaTime }); GameMain.LuaCs.Hook.Call("afflictionUpdate", new object[] { this, characterHealth, targetLimb, deltaTime });
#endif #endif
} }
@@ -308,7 +308,7 @@ namespace Barotrauma
if (client != null) if (client != null)
{ {
GameMain.Server.SetClientCharacter(client, husk); GameMain.Server.SetClientCharacter(client, husk);
GameMain.LuaCs.HookBase.Call("husk.clientControlHusk", new object[] { client, husk }); GameMain.LuaCs.Hook.Call("husk.clientControlHusk", new object[] { client, husk });
} }
#else #else
if (!character.IsRemotelyControlled && character == Character.Controlled) if (!character.IsRemotelyControlled && character == Character.Controlled)
@@ -541,9 +541,9 @@ namespace Barotrauma
return; return;
} }
var should = new LuaResult(GameMain.LuaCs.HookBase.Call("character.applyDamage", new object[] { this, attackResult, hitLimb, allowStacking })); var should = GameMain.LuaCs.Hook.Call<bool?>("character.applyDamage", this, attackResult, hitLimb, allowStacking);
if (should.Bool()) if (should != null && should.Value)
return; return;
foreach (Affliction newAffliction in attackResult.Afflictions) foreach (Affliction newAffliction in attackResult.Afflictions)
@@ -674,9 +674,9 @@ namespace Barotrauma
} }
} }
var should = new LuaResult(GameMain.LuaCs.HookBase.Call("character.applyAffliction", new object[] { this, limbHealth, newAffliction, allowStacking })); var should = GameMain.LuaCs.Hook.Call<bool?>("character.applyAffliction", this, limbHealth, newAffliction, allowStacking);
if (should.Bool()) if (should != null && should.Value)
return; return;
Affliction existingAffliction = null; Affliction existingAffliction = null;
@@ -9,12 +9,6 @@ namespace Barotrauma
private static List<ACsMod> mods = new List<ACsMod>(); private static List<ACsMod> mods = new List<ACsMod>();
public static List<ACsMod> LoadedMods { get => mods; } public static List<ACsMod> LoadedMods { get => mods; }
//public static ACsMod CreateInstance(Type type)
//{
// if (!type.IsSubclassOf(typeof(ACsMod))) throw new Exception("Type argument is not the subclass of ACsMod.");
// return type.GetConstructor(new Type[] { }).Invoke(new object[] { }) as ACsMod;
//}
public bool IsDisposed { get; private set; } public bool IsDisposed { get; private set; }
public ACsMod() public ACsMod()
@@ -1,27 +0,0 @@
using System;
using System.Reflection;
namespace Barotrauma
{
partial class LuaCsSetup
{
// CSharp wrapper for LuaCsHook
public class CsHook : LuaCsHookWrapper
{
public CsHook(LuaCsHook hook) : base(hook) { }
public void HookMethod(string identifier, MethodInfo method, CsPatchDelegate hook, HookMethodType hookType = HookMethodType.Before, ACsMod owner = null) =>
_hook.HookCsMethod(identifier, method, hook, hookType, owner);
public void UnhookMethod(string identifier, MethodInfo method, HookMethodType hookType = HookMethodType.Before) =>
_hook.RemovePatch(identifier, method, hookType);
public void Add(string name, string hookName, CsHookDelegate hook, ACsMod owner = null) =>
_hook.AddCsHook(name, hookName, hook, owner);
}
}
}
@@ -1,10 +1,8 @@
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Scripting;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Reflection.Metadata; using System.Reflection.Metadata;
@@ -28,7 +26,7 @@ namespace Barotrauma {
}; };
private static string[] typessProhibited = new string[] { private static string[] typessProhibited = new string[] {
//"System.Reflection", //"System.Reflection",
"System.IO.File", "System.IO",
}; };
public static bool IsTypeAllowed(string usingName) public static bool IsTypeAllowed(string usingName)
{ {
@@ -48,22 +48,13 @@ namespace Barotrauma
{ {
var s = str.Replace("\\", "/"); var s = str.Replace("\\", "/");
if (s.EndsWith(".cs")) if (s.EndsWith(".cs") && LuaCsFile.IsPathAllowedCsException(s)) scriptFiles.Add(s);
{
LuaCsSetup.PrintCsMessage(s);
scriptFiles.Add(s);
}
} }
try try
{ {
if (scriptFiles.Count <= 0) return; if (scriptFiles.Count <= 0) return;
var mainFile = scriptFiles.Find(s => s.EndsWith("Main.cs"));
if (mainFile == null) throw new Exception("Mod folder has no Main.cs file");
scriptFiles.Remove(mainFile);
scriptFiles.Add(mainFile);
// Check file content for prohibited stuff // Check file content for prohibited stuff
foreach (var file in scriptFiles) foreach (var file in scriptFiles)
{ {
@@ -526,7 +526,7 @@ namespace Barotrauma
HintManager.OnRoundStarted(); HintManager.OnRoundStarted();
GameMain.LuaCs.HookBase.Call("roundStart"); GameMain.LuaCs.Hook.Call("roundStart");
#endif #endif
} }
@@ -781,7 +781,7 @@ namespace Barotrauma
RoundEnding = true; RoundEnding = true;
#if CLIENT #if CLIENT
GameMain.LuaCs.HookBase.Call("roundEnd"); GameMain.LuaCs.Hook.Call("roundEnd");
#endif #endif
//Clear the grids to allow for garbage collection //Clear the grids to allow for garbage collection
Powered.Grids.Clear(); Powered.Grids.Clear();
@@ -387,7 +387,7 @@ namespace Barotrauma.Items.Components
Limb targetLimb = target.UserData as Limb; Limb targetLimb = target.UserData as Limb;
Character targetCharacter = targetLimb?.character ?? target.UserData as Character; Character targetCharacter = targetLimb?.character ?? target.UserData as Character;
GameMain.LuaCs.HookBase.Call("meleeWeapon.handleImpact", this, target); GameMain.LuaCs.Hook.Call("meleeWeapon.handleImpact", this, target);
if (Attack != null) if (Attack != null)
{ {
Attack.SetUser(User); Attack.SetUser(User);
@@ -325,8 +325,8 @@ namespace Barotrauma.Items.Components
Connection connection = recipient; Connection connection = recipient;
object[] obj = new object[] { signal, connection }; object[] obj = new object[] { signal, connection };
GameMain.LuaCs.HookBase.Call("signalReceived", obj); GameMain.LuaCs.Hook.Call("signalReceived", obj);
GameMain.LuaCs.HookBase.Call("signalReceived." + recipient.item.Prefab.Identifier, obj); GameMain.LuaCs.Hook.Call("signalReceived." + recipient.item.Prefab.Identifier, obj);
foreach (ItemComponent ic in recipient.item.Components) foreach (ItemComponent ic in recipient.item.Components)
{ {
@@ -205,9 +205,9 @@ namespace Barotrauma.Items.Components
public void TransmitSignal(Signal signal, bool sentFromChat) public void TransmitSignal(Signal signal, bool sentFromChat)
{ {
var should = new LuaResult(GameMain.LuaCs.HookBase.Call("wifiSignalTransmitted", new object[] { this, signal, sentFromChat })); var should = GameMain.LuaCs.Hook.Call<bool?>("wifiSignalTransmitted", this, signal, sentFromChat);
if (should.Bool()) if (should != null && should.Value)
return; return;
if (sentFromChat) if (sentFromChat)
@@ -540,9 +540,9 @@ namespace Barotrauma
return; return;
} }
var should = new LuaResult(GameMain.LuaCs.HookBase.Call("inventoryPutItem", new object[] { this, item, user, i, removeItem })); var should = GameMain.LuaCs.Hook.Call<bool?>("inventoryPutItem", this, item, user, i, removeItem);
if (should.Bool()) if (should != null && should.Value)
return; return;
if (Owner == null) { return; } if (Owner == null) { return; }
@@ -648,10 +648,10 @@ namespace Barotrauma
if (slots[index].Items.Any(it => !it.IsInteractable(user))) { return false; } if (slots[index].Items.Any(it => !it.IsInteractable(user))) { return false; }
if (!AllowSwappingContainedItems) { return false; } if (!AllowSwappingContainedItems) { return false; }
var should = new LuaResult(GameMain.LuaCs.HookBase.Call("inventoryItemSwap", new object[] { this, item, user, index, swapWholeStack })); var should = GameMain.LuaCs.Hook.Call<bool?>("inventoryItemSwap", this, item, user, index, swapWholeStack);
if (!should.IsNull()) if (should != null)
return should.Bool(); return should.Value;
//swap to InvSlotType.Any if possible //swap to InvSlotType.Any if possible
Inventory otherInventory = item.ParentInventory; Inventory otherInventory = item.ParentInventory;
@@ -999,7 +999,7 @@ namespace Barotrauma
if (Components.Any(ic => ic is Wire) && Components.All(ic => ic is Wire || ic is Holdable)) { isWire = true; } if (Components.Any(ic => ic is Wire) && Components.All(ic => ic is Wire || ic is Holdable)) { isWire = true; }
if (HasTag("logic")) { isLogic = true; } if (HasTag("logic")) { isLogic = true; }
GameMain.LuaCs.HookBase.Call("item.created", this); GameMain.LuaCs.Hook.Call("item.created", this);
ApplyStatusEffects(ActionType.OnSpawn, 1.0f); ApplyStatusEffects(ActionType.OnSpawn, 1.0f);
Components.ForEach(c => c.ApplyStatusEffects(ActionType.OnSpawn, 1.0f)); Components.ForEach(c => c.ApplyStatusEffects(ActionType.OnSpawn, 1.0f));
@@ -2469,9 +2469,9 @@ namespace Barotrauma
if (condition == 0.0f) { return; } if (condition == 0.0f) { return; }
var should = new LuaResult(GameMain.LuaCs.HookBase.Call("item.use", new object[] { this, character, targetLimb })); var should = GameMain.LuaCs.Hook.Call<bool?>("item.use", new object[] { this, character, targetLimb });
if (should.Bool()) if (should != null && should.Value)
return; return;
bool remove = false; bool remove = false;
@@ -2507,9 +2507,9 @@ namespace Barotrauma
{ {
if (condition == 0.0f) { return; } if (condition == 0.0f) { return; }
var should = new LuaResult(GameMain.LuaCs.HookBase.Call("item.secondaryUse", new object[] { this, character})); var should = GameMain.LuaCs.Hook.Call<bool?>("item.secondaryUse", this, character);
if (should.Bool()) if (should != null && should.Value)
return; return;
bool remove = false; bool remove = false;
@@ -2851,8 +2851,8 @@ namespace Barotrauma
} }
} }
var result = new LuaResult(GameMain.LuaCs.HookBase.Call("item.readPropertyChange", this, property, parentObject, allowEditing)); var result = GameMain.LuaCs.Hook.Call<bool?>("item.readPropertyChange", this, property, parentObject, allowEditing);
if (result.Bool()) if (result != null && result.Value)
return; return;
Type type = property.PropertyType; Type type = property.PropertyType;
@@ -3343,7 +3343,7 @@ namespace Barotrauma
body = null; body = null;
} }
GameMain.LuaCs.HookBase.Call("item.removed", this); GameMain.LuaCs.Hook.Call("item.removed", this);
} }
public override void Remove() public override void Remove()
@@ -3427,7 +3427,7 @@ namespace Barotrauma
RemoveProjSpecific(); RemoveProjSpecific();
GameMain.LuaCs.HookBase.Call("item.removed", this); GameMain.LuaCs.Hook.Call("item.removed", this);
} }
partial void RemoveProjSpecific(); partial void RemoveProjSpecific();
@@ -324,14 +324,14 @@ namespace Barotrauma
} }
} }
public void AddCommand(string name, string help, object onExecute, object getValidArgs = null, bool isCheat = false) public void AddCommand(string name, string help, CsAction onExecute, CsFunc getValidArgs = null, bool isCheat = false)
{ {
var cmd = new DebugConsole.Command(name, help, (string[] arg1) => { GameMain.LuaCs.CallLuaFunction(onExecute, new object[] { arg1 }); }, var cmd = new DebugConsole.Command(name, help, (string[] arg1) => { onExecute(arg1); },
() => () =>
{ {
if (getValidArgs == null) return null; if (getValidArgs == null) return null;
var result = new LuaResult(GameMain.LuaCs.CallLuaFunction(getValidArgs, new object[] { })); var obj = getValidArgs();
var obj = result.Object(); if (obj is LuaResult res) obj = res.Object();
if (obj is string[][]) return (string[][])obj; if (obj is string[][]) return (string[][])obj;
return null; return null;
}, isCheat); }, isCheat);
@@ -1,44 +0,0 @@
using System;
namespace Barotrauma
{
partial class LuaCsSetup
{
// CSharp wrapper for LuaCsHook
public class LuaHook : LuaCsHookWrapper
{
public LuaHook(LuaCsHook hook) : base(hook) { }
public class HookMethodTypeProxy
{
public HookMethodTypeProxy() { }
public const HookMethodType Before = Barotrauma.HookMethodType.Before;
public const HookMethodType After = Barotrauma.HookMethodType.After;
}
public static readonly HookMethodTypeProxy HookMethodType = new HookMethodTypeProxy();
public void HookMethod(string identifier, string className, string methodName, string[] parameterNames, object hookMethod, HookMethodType hookMethodType = Barotrauma.HookMethodType.Before) =>
_hook.HookLuaMethod(identifier, className, methodName, parameterNames, hookMethod, hookMethodType);
public void HookMethod(string identifier, string className, string methodName, object hookMethod, HookMethodType hookMethodType = Barotrauma.HookMethodType.Before) =>
_hook.HookLuaMethod(identifier, className, methodName, null, hookMethod, hookMethodType);
public void HookMethod(string className, string methodName, object hookMethod, HookMethodType hookMethodType = Barotrauma.HookMethodType.Before) =>
_hook.HookLuaMethod("", className, methodName, null, hookMethod, hookMethodType);
public void HookMethod(string className, string methodName, string[] parameterNames, object hookMethod, HookMethodType hookMethodType = Barotrauma.HookMethodType.Before) =>
_hook.HookLuaMethod("", className, methodName, parameterNames, hookMethod, hookMethodType);
public void Add(string name, string hookName, object function) =>
_hook.AddLuaHook(name, hookName, function);
public void EnqueueFunction(object function, params object[] args) =>
_hook.EnqueueLuaFunction(function, args);
public void EnqueueTimedFunction(float time, object function, params object[] args) =>
_hook.EnqueueTimedLuaFunction(time, function, args);
}
}
}
@@ -0,0 +1,111 @@
using System;
using System.Collections.Generic;
using System.Text;
using MoonSharp.Interpreter;
using Microsoft.Xna.Framework;
using Barotrauma.Networking;
using Barotrauma.Items.Components;
using System.IO;
using System.Net;
using System.Linq;
using System.Xml.Linq;
using FarseerPhysics.Dynamics;
using System.Reflection;
using HarmonyLib;
using MoonSharp.Interpreter.Interop;
using System.Diagnostics;
namespace Barotrauma
{
public class LuaResult
{
object result;
public LuaResult(object arg)
{
result = arg;
}
public bool IsNull()
{
if (result == null)
return true;
if (result is DynValue dynValue)
return dynValue.IsNil();
return false;
}
public bool Bool()
{
if (result is DynValue dynValue)
{
return dynValue.CastToBool();
}
return false;
}
public float Float()
{
if (result is DynValue dynValue)
{
var num = dynValue.CastToNumber();
if (num == null) { return 0f; }
return (float)num.Value;
}
return 0f;
}
public double Double()
{
if (result is DynValue dynValue)
{
var num = dynValue.CastToNumber();
if (num == null) { return 0f; }
return num.Value;
}
return 0f;
}
public string String()
{
if (result is DynValue dynValue)
{
var str = dynValue.CastToString();
if (str == null) { return ""; }
return str;
}
return "";
}
public object Object()
{
if (result is DynValue dynValue)
{
return dynValue.ToObject();
}
return null;
}
public DynValue DynValue()
{
if (result is DynValue dynValue)
{
return dynValue;
}
return null;
}
public static implicit operator bool(LuaResult res) => res.Bool();
public static implicit operator float(LuaResult res) => res.Float();
public static implicit operator string(LuaResult res) => res.String();
public static implicit operator double(LuaResult res) => res.Double();
public static implicit operator DynValue(LuaResult res) => res.DynValue();
}
}
@@ -23,6 +23,10 @@ namespace Barotrauma
var function = v.Function; var function = v.Function;
return (Func<Fixture, Vector2, Vector2, float, float>)((Fixture a, Vector2 b, Vector2 c, float d) => new LuaResult(function.Call(a, b, c, d)).Float()); return (Func<Fixture, Vector2, Vector2, float, float>)((Fixture a, Vector2 b, Vector2 c, float d) => new LuaResult(function.Call(a, b, c, d)).Float());
}); });
Script.GlobalOptions.CustomConverters.SetScriptToClrCustomConversion(DataType.Function, typeof(Closure), v => v.Function);
Script.GlobalOptions.CustomConverters.SetScriptToClrCustomConversion(DataType.Function, typeof(CsAction), v => (CsAction)( args => GameMain.LuaCs.CallLuaFunction(v.Function, args) ));
Script.GlobalOptions.CustomConverters.SetScriptToClrCustomConversion(DataType.Function, typeof(CsFunc), v => (CsFunc)( args => new LuaResult(GameMain.LuaCs.CallLuaFunction(v.Function, args)).Object() ));
Script.GlobalOptions.CustomConverters.SetScriptToClrCustomConversion(DataType.Function, typeof(CsPatch), v => (CsPatch)( (self, args) => new LuaResult(GameMain.LuaCs.CallLuaFunction(v.Function, self, args)).Object() ));
#if CLIENT #if CLIENT
RegisterAction<float>(); RegisterAction<float>();
@@ -13,14 +13,14 @@ namespace Barotrauma
public override object LoadFile(string file, Table globalContext) public override object LoadFile(string file, Table globalContext)
{ {
if (!LuaFile.IsPathAllowedLuaException(file, false)) return null; if (!LuaCsFile.IsPathAllowedLuaException(file, false)) return null;
return File.ReadAllText(file); return File.ReadAllText(file);
} }
public override bool ScriptFileExists(string file) public override bool ScriptFileExists(string file)
{ {
if (!LuaFile.IsPathAllowedLuaException(file, false)) return false; if (!LuaCsFile.IsPathAllowedLuaException(file, false)) return false;
return File.Exists(file); return File.Exists(file);
} }
@@ -5,39 +5,21 @@ using MoonSharp.Interpreter;
using HarmonyLib; using HarmonyLib;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using MoonSharp.Interpreter.Interop;
namespace Barotrauma namespace Barotrauma
{ {
public enum HookMethodType public delegate void CsAction(params object[] args);
{ public delegate object CsFunc(params object[] args);
Before, After public delegate object CsPatch(object self, params object[] args);
}
public delegate object CsHookDelegate(params object[] args);
public delegate object CsPatchDelegate(object self, params object[] args);
public abstract class LuaCsHookWrapper {
protected LuaCsHook _hook;
public LuaCsHookWrapper(LuaCsHook hook)
{
_hook = hook;
}
public void Remove(string name, string hookName) =>
_hook.RemoveHook(name, hookName);
public void Update() =>
_hook.Update();
public object Call(string name, params object[] args) =>
_hook.Call(name, args);
}
public class LuaCsHook public class LuaCsHook
{ {
public enum HookMethodType
{
Before, After
}
private class LuaHookFunction private class LuaHookFunction
{ {
public string name; public string name;
@@ -51,82 +33,41 @@ namespace Barotrauma
function = func; function = func;
} }
} }
private class LuaCsHookCallback
{
public string name;
public string hookName;
public CsFunc func;
private Dictionary<string, Dictionary<string, LuaHookFunction>> luaHookFunctions; public LuaCsHookCallback(string name, string hookName, CsFunc func)
private Dictionary<string, Dictionary<string, (CsHookDelegate, ACsMod)>> csHookFunctions; {
this.name = name;
this.hookName = hookName;
this.func = func;
}
}
private Dictionary<long, HashSet<(string, object)>> luaHookPrefixMethods; private Dictionary<string, Dictionary<string, (LuaCsHookCallback, ACsMod)>> hookFunctions;
private Dictionary<long, HashSet<(string, object)>> luaHookPostfixMethods;
private Dictionary<long, HashSet<(string, CsPatchDelegate, ACsMod)>> csHookPrefixMethods;
private Dictionary<long, HashSet<(string, CsPatchDelegate, ACsMod)>> csHookPostfixMethods;
private Queue<Tuple<float, object, object[]>> queuedFunctionCalls; private Dictionary<long, HashSet<(string, CsPatch, ACsMod)>> hookPrefixMethods;
private Dictionary<long, HashSet<(string, CsPatch, ACsMod)>> hookPostfixMethods;
private Queue<(float, CsAction, object[])> queuedFunctionCalls;
private LuaCsHook() { private LuaCsHook() {
luaHookFunctions = new Dictionary<string, Dictionary<string, LuaHookFunction>>(); hookFunctions = new Dictionary<string, Dictionary<string, (LuaCsHookCallback, ACsMod)>>();
csHookFunctions = new Dictionary<string, Dictionary<string, (CsHookDelegate, ACsMod)>>();
luaHookPrefixMethods = new Dictionary<long, HashSet<(string, object)>>(); hookPrefixMethods = new Dictionary<long, HashSet<(string, CsPatch, ACsMod)>>();
luaHookPostfixMethods = new Dictionary<long, HashSet<(string, object)>>(); hookPostfixMethods = new Dictionary<long, HashSet<(string, CsPatch, ACsMod)>>();
csHookPrefixMethods = new Dictionary<long, HashSet<(string, CsPatchDelegate, ACsMod)>>();
csHookPostfixMethods = new Dictionary<long, HashSet<(string, CsPatchDelegate, ACsMod)>>();
queuedFunctionCalls = new Queue<Tuple<float, object, object[]>>(); queuedFunctionCalls = new Queue<(float, CsAction, object[])>();
} }
private static LuaCsHook _inst; private static LuaCsHook _inst;
static LuaCsHook() => _inst = new LuaCsHook(); static LuaCsHook() => _inst = new LuaCsHook();
public static LuaCsHook Instance { get => _inst; } public static LuaCsHook Instance { get => _inst; }
private static void _hookLuaCsPatch(MethodBase __originalMethod, object[] __args, object __instance, ref object result, HookMethodType hookMethodType)
static void _hookLuaPatch(MethodBase __originalMethod, object[] __args, object __instance, out LuaResult result, HookMethodType hookMethodType)
{
result = new LuaResult(null);
#if CLIENT
if (GameMain.GameSession?.IsRunning == false && GameMain.IsSingleplayer)
return;
#endif
try
{
var funcAddr = ((long)__originalMethod.MethodHandle.GetFunctionPointer());
HashSet<(string, object)> methodSet = null;
switch (hookMethodType)
{
case HookMethodType.Before:
_inst.luaHookPrefixMethods.TryGetValue(funcAddr, out methodSet);
break;
case HookMethodType.After:
_inst.luaHookPostfixMethods.TryGetValue(funcAddr, out methodSet);
break;
default:
break;
}
if (methodSet != null)
{
var @params = __originalMethod.GetParameters();
var ptable = new Dictionary<string, object>();
for (int i = 0; i < @params.Length; i++)
{
ptable.Add(@params[i].Name, __args[i]);
}
foreach (var tuple in methodSet)
{
var luaResult = new LuaResult(GameMain.LuaCs.lua.Call(tuple.Item2, __instance, ptable));
if (!luaResult.IsNull()) result = luaResult;
}
}
}
catch (Exception ex)
{
GameMain.LuaCs.HandleException(ex);
}
}
static void _hookCsPatch(MethodBase __originalMethod, object[] __args, object __instance, ref object result, HookMethodType hookMethodType)
{ {
#if CLIENT #if CLIENT
if (GameMain.GameSession?.IsRunning == false && GameMain.IsSingleplayer) if (GameMain.GameSession?.IsRunning == false && GameMain.IsSingleplayer)
@@ -135,14 +76,14 @@ namespace Barotrauma
try try
{ {
var funcAddr = ((long)__originalMethod.MethodHandle.GetFunctionPointer()); var funcAddr = ((long)__originalMethod.MethodHandle.GetFunctionPointer());
HashSet<(string, CsPatchDelegate, ACsMod)> methodSet = null; HashSet<(string, CsPatch, ACsMod)> methodSet = null;
switch (hookMethodType) switch (hookMethodType)
{ {
case HookMethodType.Before: case HookMethodType.Before:
_inst.csHookPrefixMethods.TryGetValue(funcAddr, out methodSet); _inst.hookPrefixMethods.TryGetValue(funcAddr, out methodSet);
break; break;
case HookMethodType.After: case HookMethodType.After:
_inst.csHookPostfixMethods.TryGetValue(funcAddr, out methodSet); _inst.hookPostfixMethods.TryGetValue(funcAddr, out methodSet);
break; break;
default: default:
break; break;
@@ -157,94 +98,78 @@ namespace Barotrauma
args.Add(@params[i].Name, __args[i]); args.Add(@params[i].Name, __args[i]);
} }
var outOfSocpe = new HashSet<(string, CsPatchDelegate, ACsMod)>(); var outOfSocpe = new HashSet<(string, CsPatch, ACsMod)>();
foreach (var tuple in methodSet) foreach (var tuple in methodSet)
{ {
if (tuple.Item3 != null && tuple.Item3.IsDisposed) if (tuple.Item3 != null && tuple.Item3.IsDisposed)
outOfSocpe.Add(tuple); outOfSocpe.Add(tuple);
else else
result = tuple.Item2(__instance, args) ?? result; {
var _result = tuple.Item2(__instance, args);
if (_result is LuaResult res && !res.IsNull()) result = _result;
else if (_result != null) result = _result;
}
} }
foreach (var tuple in outOfSocpe) methodSet.Remove(tuple); foreach (var tuple in outOfSocpe) methodSet.Remove(tuple);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
GameMain.LuaCs.HandleException(ex, exceptionType: LuaCsSetup.ExceptionType.CSharp); GameMain.LuaCs.HandleException(ex, exceptionType: LuaCsSetup.ExceptionType.Both);
} }
} }
private static bool HookLuaPatchPrefix(MethodBase __originalMethod, object[] __args, object __instance) private static bool HookLuaCsPatchPrefix(MethodBase __originalMethod, object[] __args, object __instance)
{ {
_hookLuaPatch(__originalMethod, __args, __instance, out LuaResult result, HookMethodType.Before); object result = null;
_hookLuaCsPatch(__originalMethod, __args, __instance, ref result, HookMethodType.Before);
return result.IsNull(); if (result != null)
}
private static bool HookLuaPatchRetPrefix(MethodBase __originalMethod, object[] __args, ref object __result, object __instance)
{
_hookLuaPatch(__originalMethod, __args, __instance, out LuaResult result, HookMethodType.Before);
if (!result.IsNull())
{ {
if (result is LuaResult res) return res.IsNull();
if (__originalMethod is MethodInfo mi)
{
__result = result.DynValue().ToObject(mi.ReturnType);
}
else
{
__result = result.Object();
}
return false; return false;
} }
else return true;
return true;
} }
private static void HookLuaCsPatchPostfix(MethodBase __originalMethod, object[] __args, object __instance)
private static void HookLuaPatchPostfix(MethodBase __originalMethod, object[] __args, object __instance)
{ {
_hookLuaPatch(__originalMethod, __args, __instance, out LuaResult result, HookMethodType.After); object result = null;
_hookLuaCsPatch(__originalMethod, __args, __instance, ref result, HookMethodType.After);
} }
private static void HookLuaPatchRetPostfix(MethodBase __originalMethod, object[] __args, ref object __result, object __instance) private static bool HookLuaCsPatchRetPrefix(MethodBase __originalMethod, object[] __args, ref object __result, object __instance)
{ {
_hookLuaPatch(__originalMethod, __args, __instance, out LuaResult result, HookMethodType.After); _hookLuaCsPatch(__originalMethod, __args, __instance, ref __result, HookMethodType.Before);
if (__result != null)
if (!result.IsNull())
{ {
if (__originalMethod is MethodInfo mi) if (__result is LuaResult res)
{ {
__result = result.DynValue().ToObject(mi.ReturnType); if (!res.IsNull() && __originalMethod is MethodInfo mi) __result = res.DynValue().ToObject(mi.ReturnType);
else __result = res.Object();
} }
else return false;
}
else return true;
}
private static void HookLuaCsPatchRetPostfix(MethodBase __originalMethod, object[] __args, ref object __result, object __instance)
{
_hookLuaCsPatch(__originalMethod, __args, __instance, ref __result, HookMethodType.After);
if (__result != null)
{
if (__result is LuaResult res)
{ {
__result = result.Object(); if (!res.IsNull() && __originalMethod is MethodInfo mi) __result = res.DynValue().ToObject(mi.ReturnType);
else __result = res.Object();
} }
} }
} }
private static bool HookCsPatchPrefix(MethodBase __originalMethod, object[] __args, ref object __result, object __instance)
{
_hookCsPatch(__originalMethod, __args, __instance, ref __result, HookMethodType.Before);
if (__result != null) return false;
else return true;
}
private static void HookCsPatchPostfix(MethodBase __originalMethod, object[] __args, ref object __result, object __instance) =>
_hookCsPatch(__originalMethod, __args, __instance, ref __result, HookMethodType.After);
private const BindingFlags DefaultBindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; private const BindingFlags DefaultBindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
private static MethodInfo _miHookLuaPatchPrefix = typeof(LuaCsHook).GetMethod("HookLuaPatchPrefix", BindingFlags.NonPublic | BindingFlags.Static);
private static MethodInfo _miHookLuaPatchRetPrefix = typeof(LuaCsHook).GetMethod("HookLuaPatchRetPrefix", BindingFlags.NonPublic | BindingFlags.Static);
private static MethodInfo _miHookLuaPatchPostfix = typeof(LuaCsHook).GetMethod("HookLuaPatchPostfix", BindingFlags.NonPublic | BindingFlags.Static);
private static MethodInfo _miHookLuaPatchRetPostfix = typeof(LuaCsHook).GetMethod("HookLuaPatchRetPostfix", BindingFlags.NonPublic | BindingFlags.Static);
private static MethodInfo _miHookCsPatchRetPrefix = typeof(LuaCsHook).GetMethod("HookCsPatchPrefix", BindingFlags.NonPublic | BindingFlags.Static);
private static MethodInfo _miHookCsPatchRetPostfix = typeof(LuaCsHook).GetMethod("HookCsPatchPostfix", BindingFlags.NonPublic | BindingFlags.Static);
private static MethodInfo _miHookLuaCsPatchPrefix = typeof(LuaCsHook).GetMethod("HookLuaCsPatchPrefix", BindingFlags.NonPublic | BindingFlags.Static);
private static MethodInfo _miHookLuaCsPatchPostfix = typeof(LuaCsHook).GetMethod("HookLuaCsPatchPostfix", BindingFlags.NonPublic | BindingFlags.Static);
private static MethodInfo _miHookLuaCsPatchRetPrefix = typeof(LuaCsHook).GetMethod("HookLuaCsPatchRetPrefix", BindingFlags.NonPublic | BindingFlags.Static);
private static MethodInfo _miHookLuaCsPatchRetPostfix = typeof(LuaCsHook).GetMethod("HookLuaCsPatchRetPostfix", BindingFlags.NonPublic | BindingFlags.Static);
private static MethodInfo ResolveMethod(string where, string className, string methodName, string[] parameterNames) private static MethodInfo ResolveMethod(string where, string className, string methodName, string[] parameterNames)
{ {
@@ -277,216 +202,145 @@ namespace Barotrauma
return methodInfo; return methodInfo;
} }
public void HookLuaMethod(string identifier, string className, string methodName, string[] parameterNames, object hookMethod, HookMethodType hookMethodType = HookMethodType.Before) public void HookMethod(string identifier, MethodInfo method, CsPatch patch, HookMethodType hookType = HookMethodType.Before, ACsMod owner = null)
{ {
if (identifier == null || method == null || patch == null) throw new ArgumentNullException("Identifier, Method and Patch arguments must not be null.");
MethodInfo methodInfo = ResolveMethod("HookMethod", className, methodName, parameterNames);
if (methodInfo == null) return;
identifier = identifier.ToLower();
var funcAddr = ((long)methodInfo.MethodHandle.GetFunctionPointer());
var patches = Harmony.GetPatchInfo(methodInfo);
if (hookMethodType == HookMethodType.Before)
{
if (methodInfo.ReturnType == typeof(void))
{
if (patches == null || patches.Prefixes == null || patches.Prefixes.Find(patch => patch.PatchMethod == _miHookLuaPatchPrefix) == null)
{
GameMain.LuaCs.harmony.Patch(methodInfo, prefix: new HarmonyMethod(_miHookLuaPatchPrefix));
}
}
else
{
if (patches == null || patches.Prefixes == null || patches.Prefixes.Find(patch => patch.PatchMethod == _miHookLuaPatchRetPrefix) == null)
{
GameMain.LuaCs.harmony.Patch(methodInfo, prefix: new HarmonyMethod(_miHookLuaPatchRetPrefix));
}
}
if (luaHookPrefixMethods.TryGetValue(funcAddr, out HashSet<(string, object)> methodSet))
{
if (identifier != "")
{
methodSet.RemoveWhere(tuple => tuple.Item1 == identifier);
}
if (hookMethod != null)
{
methodSet.Add((identifier, hookMethod));
}
}
else if (hookMethod != null)
{
luaHookPrefixMethods.Add(funcAddr, new HashSet<(string, object)>() { (identifier, hookMethod) });
}
}
else if (hookMethodType == HookMethodType.After)
{
if (methodInfo.ReturnType == typeof(void))
{
if (patches == null || patches.Postfixes == null || patches.Postfixes.Find(patch => patch.PatchMethod == _miHookLuaPatchPostfix) == null)
{
GameMain.LuaCs.harmony.Patch(methodInfo, postfix: new HarmonyMethod(_miHookLuaPatchPostfix));
}
}
else
{
if (patches == null || patches.Postfixes == null || patches.Postfixes.Find(patch => patch.PatchMethod == _miHookLuaPatchRetPostfix) == null)
{
GameMain.LuaCs.harmony.Patch(methodInfo, postfix: new HarmonyMethod(_miHookLuaPatchRetPostfix));
}
}
if (luaHookPostfixMethods.TryGetValue(funcAddr, out HashSet<(string, object)> methodSet))
{
if (identifier != "")
{
methodSet.RemoveWhere(tuple => tuple.Item1 == identifier);
}
if (hookMethod != null)
{
methodSet.Add((identifier, hookMethod));
}
}
else if (hookMethod != null)
{
luaHookPostfixMethods.Add(funcAddr, new HashSet<(string, object)>() { (identifier, hookMethod) });
}
}
}
public void HookCsMethod(string identifier, MethodInfo method, CsPatchDelegate hook, HookMethodType hookType = HookMethodType.Before, ACsMod owner = null)
{
if (identifier == null || method == null || hook == null) throw new ArgumentNullException("Identifier, Method and Hook arguments must not be null.");
var funcAddr = ((long)method.MethodHandle.GetFunctionPointer()); var funcAddr = ((long)method.MethodHandle.GetFunctionPointer());
var patches = Harmony.GetPatchInfo(method); var patches = Harmony.GetPatchInfo(method);
if (hookType == HookMethodType.Before) if (hookType == HookMethodType.Before)
{ {
if (patches == null || patches.Prefixes == null || patches.Prefixes.Find(patch => patch.PatchMethod == _miHookCsPatchRetPrefix) == null) if (method.ReturnType != typeof(void))
{ {
GameMain.LuaCs.harmony.Patch(method, prefix: new HarmonyMethod(_miHookCsPatchRetPrefix)); if (patches == null || patches.Prefixes == null || patches.Prefixes.Find(patch => patch.PatchMethod == _miHookLuaCsPatchRetPrefix) == null)
{
GameMain.LuaCs.harmony.Patch(method, prefix: new HarmonyMethod(_miHookLuaCsPatchRetPrefix));
}
}
else
{
if (patches == null || patches.Prefixes == null || patches.Prefixes.Find(patch => patch.PatchMethod == _miHookLuaCsPatchPrefix) == null)
{
GameMain.LuaCs.harmony.Patch(method, prefix: new HarmonyMethod(_miHookLuaCsPatchPrefix));
}
} }
if (csHookPrefixMethods.TryGetValue(funcAddr, out HashSet<(string, CsPatchDelegate, ACsMod)> methodSet)) if (hookPrefixMethods.TryGetValue(funcAddr, out HashSet<(string, CsPatch, ACsMod)> methodSet))
{ {
methodSet.RemoveWhere(tuple => tuple.Item1 == identifier); methodSet.RemoveWhere(tuple => tuple.Item1 == identifier);
methodSet.Add((identifier, hook, owner)); methodSet.Add((identifier, patch, owner));
} }
else if (hook != null) else if (patch != null)
{ {
csHookPrefixMethods.Add(funcAddr, new HashSet<(string, CsPatchDelegate, ACsMod)>() { (identifier, hook, owner) }); hookPrefixMethods.Add(funcAddr, new HashSet<(string, CsPatch, ACsMod)>() { (identifier, patch, owner) });
} }
} }
else if (hookType == HookMethodType.After) else if (hookType == HookMethodType.After)
{ {
if (patches == null || patches.Postfixes == null || patches.Postfixes.Find(patch => patch.PatchMethod == _miHookCsPatchRetPrefix) == null) if (method.ReturnType != typeof(void))
{ {
GameMain.LuaCs.harmony.Patch(method, postfix: new HarmonyMethod(_miHookCsPatchRetPostfix)); if (patches == null || patches.Postfixes == null || patches.Postfixes.Find(patch => patch.PatchMethod == _miHookLuaCsPatchRetPostfix) == null)
{
GameMain.LuaCs.harmony.Patch(method, postfix: new HarmonyMethod(_miHookLuaCsPatchRetPostfix));
}
}
else
{
if (patches == null || patches.Postfixes == null || patches.Postfixes.Find(patch => patch.PatchMethod == _miHookLuaCsPatchPostfix) == null)
{
GameMain.LuaCs.harmony.Patch(method, postfix: new HarmonyMethod(_miHookLuaCsPatchPostfix));
}
} }
if (csHookPostfixMethods.TryGetValue(funcAddr, out HashSet<(string, CsPatchDelegate, ACsMod)> methodSet)) if (hookPostfixMethods.TryGetValue(funcAddr, out HashSet<(string, CsPatch, ACsMod)> methodSet))
{ {
methodSet.RemoveWhere(tuple => tuple.Item1 == identifier); methodSet.RemoveWhere(tuple => tuple.Item1 == identifier);
methodSet.Add((identifier, hook, owner)); methodSet.Add((identifier, patch, owner));
} }
else if (hook != null) else if (patch != null)
{ {
csHookPostfixMethods.Add(funcAddr, new HashSet<(string, CsPatchDelegate, ACsMod)>() { (identifier, hook, owner) }); hookPostfixMethods.Add(funcAddr, new HashSet<(string, CsPatch, ACsMod)>() { (identifier, patch, owner) });
} }
} }
} }
public void RemoveLuaPatch(string identifier, string className, string methodName, string[] parameterNames, HookMethodType hookType = HookMethodType.Before) protected void HookMethod(string identifier, string className, string methodName, string[] parameterNames, CsPatch patch, HookMethodType hookMethodType = HookMethodType.Before)
{ {
MethodInfo methodInfo = ResolveMethod("UnhookMathod", className, methodName, parameterNames);
MethodInfo methodInfo = ResolveMethod("HookMethod", className, methodName, parameterNames);
if (methodInfo == null) return; if (methodInfo == null) return;
RemovePatch(identifier, methodInfo, hookType); HookMethod(identifier, methodInfo, patch, hookMethodType);
} }
public void RemovePatch(string identifier, MethodInfo method, HookMethodType hookType = HookMethodType.Before) protected void HookMethod(string identifier, string className, string methodName, CsPatch patch, HookMethodType hookMethodType = HookMethodType.Before) =>
HookMethod(identifier, className, methodName, null, patch, hookMethodType);
protected void HookMethod(string className, string methodName, CsPatch patch, HookMethodType hookMethodType = HookMethodType.Before) =>
HookMethod("", className, methodName, null, patch, hookMethodType);
protected void HookMethod(string className, string methodName, string[] parameterNames, CsPatch patch, HookMethodType hookMethodType = HookMethodType.Before) =>
HookMethod("", className, methodName, parameterNames, patch, hookMethodType);
public void UnhookMethod(string identifier, MethodInfo method, HookMethodType hookType = HookMethodType.Before)
{ {
var funcAddr = ((long)method.MethodHandle.GetFunctionPointer()); var funcAddr = ((long)method.MethodHandle.GetFunctionPointer());
Dictionary<long, HashSet<(string, object)>> luaMethods; Dictionary<long, HashSet<(string, CsPatch, ACsMod)>> methods;
Dictionary<long, HashSet<(string, CsPatchDelegate, ACsMod)>> csMethods; if (hookType == HookMethodType.Before) methods = hookPrefixMethods;
if (hookType == HookMethodType.Before) else if (hookType == HookMethodType.After) methods = hookPostfixMethods;
{
luaMethods = luaHookPrefixMethods;
csMethods = csHookPrefixMethods;
}
else if (hookType == HookMethodType.After)
{
luaMethods = luaHookPostfixMethods;
csMethods = csHookPostfixMethods;
}
else throw null; else throw null;
if (luaMethods.ContainsKey(funcAddr)) luaMethods[funcAddr]?.RemoveWhere(t => t.Item1 == identifier); if (methods.ContainsKey(funcAddr)) methods[funcAddr]?.RemoveWhere(t => t.Item1 == identifier);
if (csMethods.ContainsKey(funcAddr)) csMethods[funcAddr]?.RemoveWhere(t => t.Item1 == identifier);
} }
protected void UnhookMethod(string identifier, string className, string methodName, string[] parameterNames, HookMethodType hookType = HookMethodType.Before)
public void EnqueueLuaFunction(object function, params object[] args)
{ {
queuedFunctionCalls.Enqueue(new Tuple<float, object, object[]>(0, function, args)); MethodInfo methodInfo = ResolveMethod("UnhookMathod", className, methodName, parameterNames);
if (methodInfo == null) return;
UnhookMethod(identifier, methodInfo, hookType);
} }
public void EnqueueTimedLuaFunction(float time, object function, params object[] args)
public void Enqueue(CsAction action, params object[] args)
{ {
queuedFunctionCalls.Enqueue(new Tuple<float, object, object[]>(time, function, args)); queuedFunctionCalls.Enqueue((0, action, args));
} }
public void EnqueueTimed(float time, CsAction action, params object[] args)
public void AddLuaHook(string name, string hookName, object function)
{ {
if (name == null || hookName == null || function == null) return; queuedFunctionCalls.Enqueue((time, action, args));
name = name.ToLower();
if (!luaHookFunctions.ContainsKey(name))
luaHookFunctions.Add(name, new Dictionary<string, LuaHookFunction>());
luaHookFunctions[name][hookName] = new LuaHookFunction(name, hookName, function);
} }
public void AddCsHook(string name, string hookName, CsHookDelegate hook, ACsMod owner = null) protected void EnqueueFunction(CsAction function, params object[] args) => Enqueue(function, args);
protected void EnqueueTimedFunction(float time, CsAction function, params object[] args) => EnqueueTimed(time, function, args);
public void Add(string name, string hookName, CsFunc hook, ACsMod owner = null)
{ {
if (name == null || hookName == null || hook == null) throw new ArgumentNullException("Names and Hook must not be null"); if (name == null || hookName == null || hook == null) throw new ArgumentNullException("Names and Hook must not be null");
if (!csHookFunctions.ContainsKey(name)) if (!hookFunctions.ContainsKey(name))
csHookFunctions.Add(name, new Dictionary<string, (CsHookDelegate, ACsMod)>()); hookFunctions.Add(name, new Dictionary<string, (LuaCsHookCallback, ACsMod)>());
csHookFunctions[name][hookName] = (hook, owner); hookFunctions[name][hookName] = (new LuaCsHookCallback(name, hookName, hook), owner);
} }
public void RemoveHook(string name, string hookName) public void Remove(string name, string hookName)
{ {
if (name == null || hookName == null) return; if (name == null || hookName == null) return;
name = name.ToLower(); name = name.ToLower();
if (luaHookFunctions.ContainsKey(name) && luaHookFunctions[name].ContainsKey(hookName)) if (hookFunctions.ContainsKey(name) && hookFunctions[name].ContainsKey(hookName))
luaHookFunctions[name].Remove(hookName); hookFunctions[name].Remove(hookName);
if (csHookFunctions.ContainsKey(name) && csHookFunctions[name].ContainsKey(hookName))
csHookFunctions[name].Remove(hookName);
} }
public void Clear() public void Clear()
{ {
luaHookFunctions.Clear(); hookFunctions.Clear();
csHookFunctions.Clear();
luaHookPrefixMethods.Clear(); hookPrefixMethods.Clear();
luaHookPostfixMethods.Clear(); hookPostfixMethods.Clear();
csHookPrefixMethods.Clear();
csHookPostfixMethods.Clear();
queuedFunctionCalls.Clear(); queuedFunctionCalls.Clear();
@@ -498,43 +352,53 @@ namespace Barotrauma
{ {
try try
{ {
if (queuedFunctionCalls.TryPeek(out Tuple<float, object, object[]> result)) if (queuedFunctionCalls.TryPeek(out (float, CsAction, object[]) result))
{ {
if (Timing.TotalTime >= result.Item1) if (Timing.TotalTime >= result.Item1)
{ {
GameMain.LuaCs.CallLuaFunction(result.Item2, result.Item3); result.Item2(result.Item3);
queuedFunctionCalls.Dequeue(); queuedFunctionCalls.Dequeue();
} }
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
GameMain.LuaCs.HandleException(ex, $"queuedFunctionCalls was {queuedFunctionCalls}"); GameMain.LuaCs.HandleException(ex, $"queuedFunctionCalls was {queuedFunctionCalls}", LuaCsSetup.ExceptionType.Both);
} }
} }
public object Call(string name, params object[] args) public T Call<T>(string name, params object[] args)
{ {
if (
typeof(T) != typeof(object) &&
!name.StartsWith("think") &&
!name.StartsWith("gapOxygenUpdate") &&
!name.StartsWith("statusEffect")
) Console.WriteLine($" --== '{name}'");
#if CLIENT #if CLIENT
if (GameMain.GameSession?.IsRunning == false && GameMain.IsSingleplayer) if (GameMain.GameSession?.IsRunning == false && GameMain.IsSingleplayer)
return null; //return null;
return default(T);
#endif #endif
if (GameMain.LuaCs == null) return null; //if (GameMain.LuaCs == null) return null;
if (name == null) return null; //if (name == null) return null;
if (GameMain.LuaCs == null) return default(T);
if (name == null) return default(T);
if (args == null) { args = new object[] { }; } if (args == null) { args = new object[] { }; }
name = name.ToLower(); name = name.ToLower();
if (!luaHookFunctions.ContainsKey(name)) if (!hookFunctions.ContainsKey(name))
return null; //return null;
return default(T);
object lastResult = null; //object lastResult = null;
T lastResult = default(T);
if (csHookFunctions.ContainsKey(name)) if (hookFunctions.ContainsKey(name))
{ {
var outOfScope = new List<string>(); var outOfScope = new List<string>();
foreach ((var key, var tuple) in csHookFunctions[name]) foreach ((var key, var tuple) in hookFunctions[name])
{ {
if (tuple.Item2 != null && tuple.Item2.IsDisposed) if (tuple.Item2 != null && tuple.Item2.IsDisposed)
outOfScope.Add(key); outOfScope.Add(key);
@@ -542,8 +406,9 @@ namespace Barotrauma
{ {
try try
{ {
var result = tuple.Item1(args); var result = tuple.Item1.func(args);
if (result != null) lastResult = result; if (result is LuaResult lRes && !lRes.IsNull()) lastResult = lRes.DynValue().ToObject<T>();
else if (result != null && result is T cRes) lastResult = cRes;
} }
catch (Exception e) catch (Exception e)
{ {
@@ -551,40 +416,15 @@ namespace Barotrauma
foreach (var arg in args) argsSb.Append(arg + " "); foreach (var arg in args) argsSb.Append(arg + " ");
GameMain.LuaCs.HandleException( GameMain.LuaCs.HandleException(
e, $"Error in Hook '{name}'->'{key}', with args '{argsSb}':\n{e}", e, $"Error in Hook '{name}'->'{key}', with args '{argsSb}':\n{e}",
LuaCsSetup.ExceptionType.CSharp); LuaCsSetup.ExceptionType.Both);
} }
} }
} }
foreach (var key in outOfScope) csHookFunctions[name].Remove(key); foreach (var key in outOfScope) hookFunctions[name].Remove(key);
}
if (luaHookFunctions.ContainsKey(name))
{
foreach (LuaHookFunction hf in luaHookFunctions[name].Values)
{
try
{
if (hf.function is Closure)
{
var result = GameMain.LuaCs.lua.Call(hf.function, args);
if (!result.IsNil())
lastResult = result;
}
}
catch (Exception e)
{
StringBuilder argsSb = new StringBuilder();
foreach (var arg in args)
{
argsSb.Append(arg + " ");
}
GameMain.LuaCs.HandleException(e, $"Error in Hook '{name}'->'{hf.hookName}', with args '{argsSb}'");
}
}
} }
return lastResult; return lastResult;
} }
public object Call(string name, params object[] args) => Call<object>(name, args);
} }
} }
@@ -9,6 +9,8 @@ using MoonSharp.Interpreter.Interop;
using System.IO.Compression; using System.IO.Compression;
using HarmonyLib; using HarmonyLib;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Linq;
using System.Reflection;
[assembly: InternalsVisibleTo("NetScriptAssembly", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("NetScriptAssembly", AllInternalsVisible = true)]
namespace Barotrauma namespace Barotrauma
@@ -20,12 +22,10 @@ namespace Barotrauma
public Script lua; public Script lua;
private LuaHook luaHook; internal LuaCsHook Hook { get; private set; }
public CsHook Hook { get; private set; }
internal LuaCsHook HookBase { get; private set; }
public LuaGame game; public LuaGame game;
public LuaNetworking networking; public LuaCsNetworking networking;
public Harmony harmony; public Harmony harmony;
public LuaScriptLoader luaScriptLoader; public LuaScriptLoader luaScriptLoader;
@@ -33,12 +33,10 @@ namespace Barotrauma
public LuaCsSetup() public LuaCsSetup()
{ {
HookBase = LuaCsHook.Instance; Hook = LuaCsHook.Instance;
Hook = new CsHook(HookBase);
luaHook = new LuaHook(HookBase);
game = new LuaGame(); game = new LuaGame();
networking = new LuaNetworking(); networking = new LuaCsNetworking();
} }
@@ -66,13 +64,15 @@ namespace Barotrauma
public enum ExceptionType public enum ExceptionType
{ {
Lua, Lua,
CSharp CSharp,
Both
} }
public void HandleException(Exception ex, string extra = "", ExceptionType exceptionType = ExceptionType.Lua) public void HandleException(Exception ex, string extra = "", ExceptionType exceptionType = ExceptionType.Lua)
{ {
if (!string.IsNullOrWhiteSpace(extra)) if (!string.IsNullOrWhiteSpace(extra))
if (exceptionType == ExceptionType.Lua) PrintError(extra); if (exceptionType == ExceptionType.Lua) PrintError(extra);
else PrintCsError(extra); else if (exceptionType == ExceptionType.CSharp) PrintCsError(extra);
else PrintBothError(extra);
if (ex is InterpreterException) if (ex is InterpreterException)
{ {
@@ -84,7 +84,8 @@ namespace Barotrauma
else else
{ {
if (exceptionType == ExceptionType.Lua) PrintError(ex); if (exceptionType == ExceptionType.Lua) PrintError(ex);
else PrintCsError(ex); else if (exceptionType == ExceptionType.CSharp) PrintCsError(ex);
else PrintBothError(ex);
} }
} }
@@ -119,9 +120,11 @@ namespace Barotrauma
#if SERVER #if SERVER
private void PrintError(object message) => PrintErrorBase("[SV LUA ERROR] ", message, "nil"); private void PrintError(object message) => PrintErrorBase("[SV LUA ERROR] ", message, "nil");
public static void PrintCsError(object message) => PrintErrorBase("[SV CS ERROR] ", message, "Null"); public static void PrintCsError(object message) => PrintErrorBase("[SV CS ERROR] ", message, "Null");
public static void PrintBothError(object message) => PrintErrorBase("[SV ERROR] ", message, "Null");
#else #else
private void PrintError(object message) => PrintErrorBase("[CL LUA ERROR] ", message, "nil"); private void PrintError(object message) => PrintErrorBase("[CL LUA ERROR] ", message, "nil");
public static void PrintCsError(object message) => PrintErrorBase("[CL CS ERROR] ", message, "Null"); public static void PrintCsError(object message) => PrintErrorBase("[CL CS ERROR] ", message, "Null");
public static void PrintBothError(object message) => PrintErrorBase("[CL ERROR] ", message, "Null");
#endif #endif
private static void PrintMessageBase(string prefix, object message, string empty) private static void PrintMessageBase(string prefix, object message, string empty)
@@ -172,8 +175,8 @@ namespace Barotrauma
public DynValue DoFile(string file, Table globalContext = null, string codeStringFriendly = null) public DynValue DoFile(string file, Table globalContext = null, string codeStringFriendly = null)
{ {
if (!LuaFile.IsPathAllowedLuaException(file, false)) return null; if (!LuaCsFile.IsPathAllowedLuaException(file, false)) return null;
if (!LuaFile.Exists(file)) if (!LuaCsFile.Exists(file))
{ {
HandleException(new Exception($"dofile: File {file} not found.")); HandleException(new Exception($"dofile: File {file} not found."));
return null; return null;
@@ -210,8 +213,8 @@ namespace Barotrauma
public DynValue LoadFile(string file, Table globalContext = null, string codeStringFriendly = null) public DynValue LoadFile(string file, Table globalContext = null, string codeStringFriendly = null)
{ {
if (!LuaFile.IsPathAllowedLuaException(file, false)) return null; if (!LuaCsFile.IsPathAllowedLuaException(file, false)) return null;
if (!LuaFile.Exists(file)) if (!LuaCsFile.Exists(file))
{ {
HandleException(new Exception($"loadfile: File {file} not found.")); HandleException(new Exception($"loadfile: File {file} not found."));
return null; return null;
@@ -266,22 +269,22 @@ namespace Barotrauma
public void Update() public void Update()
{ {
HookBase?.Update(); Hook?.Update();
} }
public void Stop() public void Stop()
{ {
foreach (var mod in ACsMod.LoadedMods.ToArray()) mod.Dispose(); foreach (var mod in ACsMod.LoadedMods.ToArray()) mod.Dispose();
ACsMod.LoadedMods.Clear(); ACsMod.LoadedMods.Clear();
HookBase?.Call("stop"); Hook?.Call("stop");
game?.Stop(); game?.Stop();
//harmony?.UnpatchAll(); //harmony?.UnpatchAll();
//HookBase = new LuaCsHook(); //Hook = new LuaCsHook();
HookBase.Clear(); Hook.Clear();
game = new LuaGame(); game = new LuaGame();
networking = new LuaNetworking(); networking = new LuaCsNetworking();
luaScriptLoader = null; luaScriptLoader = null;
} }
@@ -321,21 +324,34 @@ namespace Barotrauma
harmony = new Harmony("com.LuaForBarotrauma"); harmony = new Harmony("com.LuaForBarotrauma");
harmony.UnpatchAll(); harmony.UnpatchAll();
//HookBase = new LuaCsHook(); //Hook = new LuaCsHook();
game = new LuaGame(); game = new LuaGame();
networking = new LuaNetworking(); networking = new LuaCsNetworking();
//UserData.RegisterType<LuaCsHook>(); //UserData.RegisterType<LuaCsHook>();
UserData.RegisterType<LuaHook>();
UserData.RegisterType<LuaGame>(); UserData.RegisterType<LuaGame>();
UserData.RegisterType<LuaTimer>(); UserData.RegisterType<LuaCsTimer>();
UserData.RegisterType<LuaFile>(); UserData.RegisterType<LuaCsFile>();
UserData.RegisterType<LuaNetworking>(); UserData.RegisterType<LuaCsNetworking>();
UserData.RegisterType<LuaUserData>(); UserData.RegisterType<LuaUserData>();
UserData.RegisterType<IUserDataDescriptor>(); UserData.RegisterType<IUserDataDescriptor>();
lua.Globals["printerror"] = (Action<object>)PrintError; lua.Globals["printerror"] = (Action<object>)PrintError;
var hookType = UserData.RegisterType<LuaCsHook>();
var hookDesc = (StandardUserDataDescriptor)hookType;
typeof(LuaCsHook).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).ToList().ForEach(m => {
if (
m.Name.Contains("HookMethod") ||
m.Name.Contains("UnhookMethod") ||
m.Name.Contains("EnqueueFunction") ||
m.Name.Contains("EnqueueTimedFunction")
)
{
hookDesc.AddMember(m.Name, new MethodMemberDescriptor(m, InteropAccessMode.Default));
}
});
lua.Globals["setmodulepaths"] = (Action<string[]>)SetModulePaths; lua.Globals["setmodulepaths"] = (Action<string[]>)SetModulePaths;
lua.Globals["dofile"] = (Func<string, Table, string, DynValue>)DoFile; lua.Globals["dofile"] = (Func<string, Table, string, DynValue>)DoFile;
@@ -347,13 +363,12 @@ namespace Barotrauma
lua.Globals["LuaUserData"] = UserData.CreateStatic<LuaUserData>(); lua.Globals["LuaUserData"] = UserData.CreateStatic<LuaUserData>();
lua.Globals["Game"] = game; lua.Globals["Game"] = game;
//lua.Globals["Hook"] = HookBase; lua.Globals["Hook"] = Hook;
lua.Globals["Hook"] = luaHook; lua.Globals["Timer"] = new LuaCsTimer();
lua.Globals["Timer"] = new LuaTimer(); lua.Globals["File"] = UserData.CreateStatic<LuaCsFile>();
lua.Globals["File"] = UserData.CreateStatic<LuaFile>();
lua.Globals["Networking"] = networking; lua.Globals["Networking"] = networking;
bool isServer = true; bool isServer;
#if SERVER #if SERVER
isServer = true; isServer = true;
@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using MoonSharp.Interpreter; using MoonSharp.Interpreter;
@@ -17,7 +17,7 @@ using System.Diagnostics;
namespace Barotrauma namespace Barotrauma
{ {
public partial class LuaTimer public partial class LuaCsTimer
{ {
public static long LastUpdateTime = 0; public static long LastUpdateTime = 0;
@@ -29,9 +29,9 @@ namespace Barotrauma
} }
} }
public void Wait(object function, int millisecondDelay) public void Wait(CsAction action, int millisecondDelay)
{ {
GameMain.LuaCs.HookBase.EnqueueTimedLuaFunction((float)Timing.TotalTime + (millisecondDelay / 1000f), function); GameMain.LuaCs.Hook.EnqueueTimed((float)Timing.TotalTime + (millisecondDelay / 1000f), action);
} }
public static double GetTime() public static double GetTime()
@@ -49,7 +49,7 @@ namespace Barotrauma
} }
} }
partial class LuaFile partial class LuaCsFile
{ {
public static bool CanReadFromPath(string path) public static bool CanReadFromPath(string path)
{ {
@@ -115,7 +115,7 @@ namespace Barotrauma
return false; return false;
} }
public static bool IsPathAllowedLuaException(string path, bool write = true) public static bool IsPathAllowedException(string path, bool write = true, LuaCsSetup.ExceptionType exceptionType = LuaCsSetup.ExceptionType.Both)
{ {
if (write) if (write)
{ {
@@ -123,9 +123,9 @@ namespace Barotrauma
return true; return true;
else else
GameMain.LuaCs.HandleException(new Exception("File access to \"" + path + "\" not allowed.")); GameMain.LuaCs.HandleException(new Exception("File access to \"" + path + "\" not allowed."));
} }
else else
{ {
if (CanReadFromPath(path)) if (CanReadFromPath(path))
return true; return true;
else else
@@ -134,10 +134,14 @@ namespace Barotrauma
return false; return false;
} }
public static bool IsPathAllowedLuaException(string path, bool write = true) =>
IsPathAllowedException(path, write, LuaCsSetup.ExceptionType.Lua);
public static bool IsPathAllowedCsException(string path, bool write = true) =>
IsPathAllowedException(path, write, LuaCsSetup.ExceptionType.CSharp);
public static string Read(string path) public static string Read(string path)
{ {
if (!IsPathAllowedLuaException(path, false)) if (!IsPathAllowedException(path, false))
return ""; return "";
return File.ReadAllText(path); return File.ReadAllText(path);
@@ -145,7 +149,7 @@ namespace Barotrauma
public static void Write(string path, string text) public static void Write(string path, string text)
{ {
if (!IsPathAllowedLuaException(path)) if (!IsPathAllowedException(path))
return; return;
File.WriteAllText(path, text); File.WriteAllText(path, text);
@@ -153,7 +157,7 @@ namespace Barotrauma
public static bool Exists(string path) public static bool Exists(string path)
{ {
if (!IsPathAllowedLuaException(path, false)) if (!IsPathAllowedException(path, false))
return false; return false;
return File.Exists(path); return File.Exists(path);
@@ -161,7 +165,7 @@ namespace Barotrauma
public static bool CreateDirectory(string path) public static bool CreateDirectory(string path)
{ {
if (!IsPathAllowedLuaException(path)) if (!IsPathAllowedException(path))
return false; return false;
Directory.CreateDirectory(path); Directory.CreateDirectory(path);
@@ -171,7 +175,7 @@ namespace Barotrauma
public static bool DirectoryExists(string path) public static bool DirectoryExists(string path)
{ {
if (!IsPathAllowedLuaException(path, false)) if (!IsPathAllowedException(path, false))
return false; return false;
return Directory.Exists(path); return Directory.Exists(path);
@@ -179,7 +183,7 @@ namespace Barotrauma
public static string[] GetFiles(string path) public static string[] GetFiles(string path)
{ {
if (!IsPathAllowedLuaException(path, false)) if (!IsPathAllowedException(path, false))
return null; return null;
return Directory.GetFiles(path); return Directory.GetFiles(path);
@@ -187,7 +191,7 @@ namespace Barotrauma
public static string[] GetDirectories(string path) public static string[] GetDirectories(string path)
{ {
if (!IsPathAllowedLuaException(path, false)) if (!IsPathAllowedException(path, false))
return new string[] { }; return new string[] { };
return Directory.GetDirectories(path); return Directory.GetDirectories(path);
@@ -195,7 +199,7 @@ namespace Barotrauma
public static string[] DirSearch(string sDir) public static string[] DirSearch(string sDir)
{ {
if (!IsPathAllowedLuaException(sDir, false)) if (!IsPathAllowedException(sDir, false))
return new string[] { }; return new string[] { };
List<string> files = new List<string>(); List<string> files = new List<string>();
@@ -225,11 +229,10 @@ namespace Barotrauma
} }
} }
partial class LuaNetworking partial class LuaCsNetworking
{ {
public bool restrictMessageSize = true; public bool restrictMessageSize = true;
public Dictionary<string, CsAction> LuaCsNetReceives = new Dictionary<string, CsAction>();
public Dictionary<string, object> LuaNetReceives = new Dictionary<string, object>();
#if SERVER #if SERVER
[MoonSharpHidden] [MoonSharpHidden]
@@ -238,12 +241,11 @@ namespace Barotrauma
if (header == ClientPacketHeader.LUA_NET_MESSAGE) if (header == ClientPacketHeader.LUA_NET_MESSAGE)
{ {
string netMessageName = netMessage.ReadString(); string netMessageName = netMessage.ReadString();
if (LuaNetReceives[netMessageName] is Closure) if (LuaCsNetReceives.ContainsKey(netMessageName)) LuaCsNetReceives[netMessageName](netMessage, client);
GameMain.LuaCs.CallLuaFunction(LuaNetReceives[netMessageName], new object[] { netMessage, client });
} }
else else
{ {
GameMain.LuaCs.HookBase.Call("netMessageReceived", netMessage, header, client); GameMain.LuaCs.Hook.Call("netMessageReceived", netMessage, header, client);
} }
} }
@@ -254,19 +256,17 @@ namespace Barotrauma
if (header == ServerPacketHeader.LUA_NET_MESSAGE) if (header == ServerPacketHeader.LUA_NET_MESSAGE)
{ {
string netMessageName = netMessage.ReadString(); string netMessageName = netMessage.ReadString();
if (LuaNetReceives[netMessageName] is Closure) if (LuaCsNetReceives.ContainsKey(netMessageName)) LuaCsNetReceives[netMessageName](netMessage, client);
GameMain.LuaCs.lua.Call(LuaNetReceives[netMessageName], new object[] { netMessage, client });
} }
else else
{ {
GameMain.LuaCs.HookBase.Call("netMessageReceived", netMessage, header, client); GameMain.LuaCs.Hook.Call("netMessageReceived", netMessage, header, client);
} }
} }
#endif #endif
public void Receive(string netMessageName, CsAction callback)
public void Receive(string netMessageName, object callback)
{ {
LuaNetReceives[netMessageName] = callback; LuaCsNetReceives[netMessageName] = callback;
} }
public IWriteMessage Start(string netMessageName) public IWriteMessage Start(string netMessageName)
@@ -275,7 +275,7 @@ namespace Barotrauma
#if SERVER #if SERVER
message.Write((byte)ServerPacketHeader.LUA_NET_MESSAGE); message.Write((byte)ServerPacketHeader.LUA_NET_MESSAGE);
#else #else
message.Write((byte)ClientPacketHeader.LUA_NET_MESSAGE); message.Write((byte)ClientPacketHeader.LUA_NET_MESSAGE);
#endif #endif
message.Write(netMessageName); message.Write(netMessageName);
return ((IWriteMessage)message); return ((IWriteMessage)message);
@@ -304,13 +304,13 @@ namespace Barotrauma
} }
} }
#else #else
public void Send(IWriteMessage netMessage, DeliveryMethod deliveryMethod = DeliveryMethod.Reliable) public void Send(IWriteMessage netMessage, DeliveryMethod deliveryMethod = DeliveryMethod.Reliable)
{ {
GameMain.Client.ClientPeer.Send(netMessage, deliveryMethod); GameMain.Client.ClientPeer.Send(netMessage, deliveryMethod);
} }
#endif #endif
public void RequestPostHTTP(string url, object callback, string data, string contentType = "application/json") public void RequestPostHTTP(string url, CsAction callback, string data, string contentType = "application/json")
{ {
try try
{ {
@@ -327,22 +327,22 @@ namespace Barotrauma
{ {
var httpResponse = httpWebRequest.EndGetResponse(result); var httpResponse = httpWebRequest.EndGetResponse(result);
using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
GameMain.LuaCs.HookBase.EnqueueLuaFunction(callback, streamReader.ReadToEnd()); GameMain.LuaCs.Hook.Enqueue(callback, streamReader.ReadToEnd());
} }
catch (Exception e) catch (Exception e)
{ {
GameMain.LuaCs.HookBase.EnqueueLuaFunction(callback, e.ToString()); GameMain.LuaCs.Hook.Enqueue(callback, e.ToString());
} }
}), null); }), null);
} }
catch (Exception e) catch (Exception e)
{ {
GameMain.LuaCs.HookBase.EnqueueLuaFunction(callback, e.ToString()); GameMain.LuaCs.Hook.Enqueue(callback, e.ToString());
} }
} }
public void RequestGetHTTP(string url, object callback) public void RequestGetHTTP(string url, CsAction callback)
{ {
try try
{ {
@@ -354,17 +354,17 @@ namespace Barotrauma
{ {
var httpResponse = httpWebRequest.EndGetResponse(result); var httpResponse = httpWebRequest.EndGetResponse(result);
using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
GameMain.LuaCs.HookBase.EnqueueLuaFunction(callback, streamReader.ReadToEnd()); GameMain.LuaCs.Hook.Enqueue(callback, streamReader.ReadToEnd());
} }
catch (Exception e) catch (Exception e)
{ {
GameMain.LuaCs.HookBase.EnqueueLuaFunction(callback, e.ToString()); GameMain.LuaCs.Hook.Enqueue(callback, e.ToString());
} }
}), null); }), null);
} }
catch (Exception e) catch (Exception e)
{ {
GameMain.LuaCs.HookBase.EnqueueLuaFunction(callback, e.ToString()); GameMain.LuaCs.Hook.Enqueue(callback, e.ToString());
} }
} }
@@ -393,90 +393,4 @@ namespace Barotrauma
} }
} }
}
public class LuaResult
{
object result;
public LuaResult(object arg)
{
result = arg;
}
public bool IsNull()
{
if (result == null)
return true;
if (result is DynValue dynValue)
return dynValue.IsNil();
return false;
}
public bool Bool()
{
if (result is DynValue dynValue)
{
return dynValue.CastToBool();
}
return false;
}
public float Float()
{
if (result is DynValue dynValue)
{
var num = dynValue.CastToNumber();
if (num == null) { return 0f; }
return (float)num.Value;
}
return 0f;
}
public double Double()
{
if (result is DynValue dynValue)
{
var num = dynValue.CastToNumber();
if (num == null) { return 0f; }
return num.Value;
}
return 0f;
}
public string String()
{
if (result is DynValue dynValue)
{
var str = dynValue.CastToString();
if (str == null) { return ""; }
return str;
}
return "";
}
public object Object()
{
if (result is DynValue dynValue)
{
return dynValue.ToObject();
}
return null;
}
public DynValue DynValue()
{
if (result is DynValue dynValue)
{
return dynValue;
}
return null;
}
} }
@@ -660,10 +660,9 @@ namespace Barotrauma
if (Math.Max(hull1.WorldSurface + hull1.WaveY[hull1.WaveY.Length - 1], hull2.WorldSurface + hull2.WaveY[0]) > WorldRect.Y) { return; } if (Math.Max(hull1.WorldSurface + hull1.WaveY[hull1.WaveY.Length - 1], hull2.WorldSurface + hull2.WaveY[0]) > WorldRect.Y) { return; }
} }
var should = new LuaResult(GameMain.LuaCs.HookBase.Call("gapOxygenUpdate", this, hull1, hull2)); var should = GameMain.LuaCs.Hook.Call<bool?>("gapOxygenUpdate", this, hull1, hull2);
if (should.Bool()) if (should != null && should.Value) return;
return;
float totalOxygen = hull1.Oxygen + hull2.Oxygen; float totalOxygen = hull1.Oxygen + hull2.Oxygen;
float totalVolume = hull1.Volume + hull2.Volume; float totalVolume = hull1.Volume + hull2.Volume;
@@ -1201,26 +1201,26 @@ namespace Barotrauma
{ {
if (entity is Item item) if (entity is Item item)
{ {
var result = new LuaResult(GameMain.LuaCs.HookBase.Call("statusEffect.apply." + item.Prefab.Identifier, this, deltaTime, entity, targets, worldPosition)); var result = GameMain.LuaCs.Hook.Call<bool?>("statusEffect.apply." + item.Prefab.Identifier, this, deltaTime, entity, targets, worldPosition);
if (result.Bool()) if (result != null && result.Value)
return; return;
} }
if (entity is Character character) if (entity is Character character)
{ {
var result = new LuaResult(GameMain.LuaCs.HookBase.Call("statusEffect.apply." + character.SpeciesName, this, deltaTime, entity, targets, worldPosition)); var result = GameMain.LuaCs.Hook.Call<bool?>("statusEffect.apply." + character.SpeciesName, this, deltaTime, entity, targets, worldPosition);
if (result.Bool()) if (result != null && result.Value)
return; return;
} }
} }
foreach (string luaHooks in luaHook) foreach (string luaHooks in luaHook)
{ {
var result = new LuaResult(GameMain.LuaCs.HookBase.Call(luaHooks, this, deltaTime, entity, targets, worldPosition)); var result = GameMain.LuaCs.Hook.Call<bool?>(luaHooks, this, deltaTime, entity, targets, worldPosition);
if (result.Bool()) if (result != null && result.Value)
return; return;
} }