diff --git a/Barotrauma/BarotraumaClient/ClientSource/DebugConsole.cs b/Barotrauma/BarotraumaClient/ClientSource/DebugConsole.cs index 664bce9b7..d82a9869c 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/DebugConsole.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/DebugConsole.cs @@ -3223,7 +3223,7 @@ namespace Barotrauma return; } - GameMain.Lua.DoString(string.Join(" ", args)); + GameMain.LuaCs.DoString(string.Join(" ", args)); })); commands.Add(new Command("cl_reloadlua", "reloads lua on the client", (string[] args) => @@ -3234,7 +3234,7 @@ namespace Barotrauma return; } - GameMain.Lua.Initialize(); + GameMain.LuaCs.Initialize(); })); commands.Add(new Command("cl_net", "lua_net: runs a script on the client", (string[] args) => @@ -3245,7 +3245,7 @@ namespace Barotrauma return; } - GameMain.Lua.DoString(string.Join(" ", args)); + GameMain.LuaCs.DoString(string.Join(" ", args)); })); commands.Add(new Command("cl_reloadnet", "reloads lua on the client", (string[] args) => @@ -3256,7 +3256,7 @@ namespace Barotrauma return; } - GameMain.Lua.Initialize(); + GameMain.LuaCs.Initialize(); })); } diff --git a/Barotrauma/BarotraumaClient/ClientSource/GameMain.cs b/Barotrauma/BarotraumaClient/ClientSource/GameMain.cs index 24b11096c..89fa222fc 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/GameMain.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/GameMain.cs @@ -20,8 +20,7 @@ namespace Barotrauma { class GameMain : Game { - public static LuaSetup Lua; - public static NetSetup Net; + public static LuaCsSetup LuaCs; public static bool ShowFPS = false; public static bool ShowPerf = false; @@ -227,9 +226,7 @@ namespace Barotrauma throw new Exception("Content folder not found. If you are trying to compile the game from the source code and own a legal copy of the game, you can copy the Content folder from the game's files to BarotraumaShared/Content."); } - Lua = new LuaSetup(); - Net = new NetSetup(); - Net.Execute(); + LuaCs = new LuaCsSetup(); GameSettings.Init(); @@ -925,9 +922,8 @@ namespace Barotrauma SoundManager?.Update(); - GameMain.Lua.Update(); - GameMain.Lua.hook.Call("think", new object[] { }); - GameMain.Net.Update(); + GameMain.LuaCs.Update(); + GameMain.LuaCs.hook.Call("think"); Timing.Accumulator -= Timing.Step; @@ -1093,8 +1089,7 @@ namespace Barotrauma MainMenuScreen.Select(); GameSession = null; - GameMain.Lua.Stop(); - GameMain.Net.Stop(); + GameMain.LuaCs.Stop(); } public void ShowCampaignDisclaimer(Action onContinue = null) diff --git a/Barotrauma/BarotraumaClient/ClientSource/Networking/GameClient.cs b/Barotrauma/BarotraumaClient/ClientSource/Networking/GameClient.cs index 3a5eb48ef..faa5195b5 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Networking/GameClient.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Networking/GameClient.cs @@ -690,7 +690,7 @@ namespace Barotrauma.Networking { ServerPacketHeader header = (ServerPacketHeader)inc.ReadByte(); - GameMain.Lua.networking.NetMessageReceived(inc, header); + GameMain.LuaCs.networking.NetMessageReceived(inc, header); if (roundInitStatus != RoundInitStatus.Started && roundInitStatus != RoundInitStatus.NotStarted && @@ -2704,8 +2704,7 @@ namespace Barotrauma.Networking public override void Disconnect() { - GameMain.Lua.Stop(); - GameMain.Net.Stop(); + GameMain.LuaCs.Stop(); allowReconnect = false; @@ -2831,7 +2830,7 @@ namespace Barotrauma.Networking public override void AddChatMessage(ChatMessage message) { - var should = new LuaResult(GameMain.Lua.hook.Call("chatMessage", new object[] { message.Text, message.SenderClient, message.Type, message })); + var should = new LuaResult(GameMain.LuaCs.hook.Call("chatMessage", message.Text, message.SenderClient, message.Type, message)); if (should.Bool()) return; diff --git a/Barotrauma/BarotraumaClient/ClientSource/PlayerInput.cs b/Barotrauma/BarotraumaClient/ClientSource/PlayerInput.cs index 9b1f07edc..b406f1514 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/PlayerInput.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/PlayerInput.cs @@ -562,7 +562,7 @@ namespace Barotrauma allowInput = true; } - GameMain.Lua.hook.Call("keyUpdate", new object[] { deltaTime }); + GameMain.LuaCs.hook.Call("keyUpdate", deltaTime); oldMouseState = mouseState; mouseState = latestMouseState; diff --git a/Barotrauma/BarotraumaClient/ClientSource/Screens/MainMenuScreen.cs b/Barotrauma/BarotraumaClient/ClientSource/Screens/MainMenuScreen.cs index b6eee982d..0502f00c0 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Screens/MainMenuScreen.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Screens/MainMenuScreen.cs @@ -386,11 +386,11 @@ namespace Barotrauma #endif new GUIButton(new RectTransform(new Point(300, 30), Frame.RectTransform, Anchor.TopLeft) { AbsoluteOffset = new Point(20, 50) }, - "Remove Client-Side Lua", style: "MainMenuGUIButton", color: GUIStyle.Red) + "Remove Client-Side LuaCs", style: "MainMenuGUIButton", color: GUIStyle.Red) { IgnoreLayoutGroups = true, UserData = Tab.Empty, - ToolTip = "Remove Client-Side Lua.", + ToolTip = "Remove Client-Side LuaCs.", OnClicked = (tb, userdata) => { if (!File.Exists("Barotrauma.dll.old")) @@ -407,7 +407,7 @@ namespace Barotrauma return false; } - var msg = new GUIMessageBox("Confirm", "Are you sure you want to remove Client-Side Lua?", new LocalizedString[2] { TextManager.Get("Yes"), TextManager.Get("Cancel") }); + var msg = new GUIMessageBox("Confirm", "Are you sure you want to remove Client-Side LuaCs?", new LocalizedString[2] { TextManager.Get("Yes"), TextManager.Get("Cancel") }); msg.Buttons[0].OnClicked = (GUIButton button, object obj) => { @@ -1118,7 +1118,7 @@ namespace Barotrauma } ((SinglePlayerCampaign)GameMain.GameSession.GameMode).LoadNewLevel(); - GameMain.Lua.Initialize(); + GameMain.LuaCs.Initialize(); } private void LoadGame(string saveFile) @@ -1138,7 +1138,7 @@ namespace Barotrauma //TODO //GameMain.LobbyScreen.Select(); - GameMain.Lua.Initialize(); + GameMain.LuaCs.Initialize(); } #region UI Methods diff --git a/Barotrauma/BarotraumaServer/ServerSource/Characters/Character.cs b/Barotrauma/BarotraumaServer/ServerSource/Characters/Character.cs index 711e42137..44a605fe8 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/Characters/Character.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/Characters/Character.cs @@ -25,7 +25,7 @@ namespace Barotrauma GameServer.Log(GameServer.CharacterLogName(this) + " has died (Cause of death: " + causeOfDeath + ")", ServerLog.MessageType.Attack); } } - GameMain.Lua.hook.Call("characterDeath", new object[] { this,causeOfDeathAffliction }); + GameMain.LuaCs.hook.Call("characterDeath", this,causeOfDeathAffliction); if (HasAbilityFlag(AbilityFlags.RetainExperienceForNewCharacter)) { @@ -43,7 +43,7 @@ namespace Barotrauma var owner = GameMain.Server.ConnectedClients.Find(c => c.Character == this); if (owner != null) { - if (!GameMain.Lua.game.overrideTraitors) + if (!GameMain.LuaCs.game.overrideTraitors) { GameMain.Server.SendDirectChatMessage(TextManager.FormatServerMessage("KilledByTraitorNotification"), owner, ChatMessageType.ServerMessageBoxInGame); } diff --git a/Barotrauma/BarotraumaServer/ServerSource/Characters/CharacterNetworking.cs b/Barotrauma/BarotraumaServer/ServerSource/Characters/CharacterNetworking.cs index b4ed5bbda..b9f3e2c33 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/Characters/CharacterNetworking.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/Characters/CharacterNetworking.cs @@ -700,7 +700,7 @@ namespace Barotrauma var tempBuffer = new ReadWriteMessage(); WriteStatus(tempBuffer); - if (msgLengthBeforeStatus + tempBuffer.LengthBytes >= 255 && restrictMessageSize && GameMain.Lua.networking.restrictMessageSize) + if (msgLengthBeforeStatus + tempBuffer.LengthBytes >= 255 && restrictMessageSize && GameMain.LuaCs.networking.restrictMessageSize) { msg.Write(false); if (msgLengthBeforeStatus < 255) diff --git a/Barotrauma/BarotraumaServer/ServerSource/DebugConsole.cs b/Barotrauma/BarotraumaServer/ServerSource/DebugConsole.cs index 5b06d6307..112a503d2 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/DebugConsole.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/DebugConsole.cs @@ -1243,17 +1243,17 @@ namespace Barotrauma commands.Add(new Command("lua", "lua: runs a string", (string[] args) => { - GameMain.Lua.DoString(string.Join(" ", args)); + GameMain.LuaCs.DoString(string.Join(" ", args)); })); commands.Add(new Command("reloadlua", "reloads lua", (string[] args) => { - GameMain.Lua.Initialize(); + GameMain.LuaCs.Initialize(); })); commands.Add(new Command("install_cl_lua", "Installs client-Side Lua into your client.", (string[] args) => { - ContentPackage luaPackage = LuaSetup.GetPackage(); + ContentPackage luaPackage = LuaCsSetup.GetLuaPackage(); if (luaPackage == null) { @@ -1293,7 +1293,7 @@ namespace Barotrauma } catch (Exception e) { - GameMain.Lua.HandleLuaException(e); + GameMain.LuaCs.HandleLuaException(e); return; } diff --git a/Barotrauma/BarotraumaServer/ServerSource/GameMain.cs b/Barotrauma/BarotraumaServer/ServerSource/GameMain.cs index de1edcb6f..fca11ec4f 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/GameMain.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/GameMain.cs @@ -34,8 +34,7 @@ namespace Barotrauma set { world = value; } } - public static LuaSetup Lua; - public static NetSetup Net; + public static LuaCsSetup LuaCs; public static GameServer Server; public static NetworkMember NetworkMember @@ -121,9 +120,7 @@ namespace Barotrauma CheckContentPackage(); - Lua = new LuaSetup(); - Net = new NetSetup(); - Net.Execute(); + LuaCs = new LuaCsSetup(); } @@ -350,9 +347,8 @@ namespace Barotrauma TaskPool.Update(); CoroutineManager.Update((float)Timing.Step, (float)Timing.Step); - GameMain.Lua.Update(); - GameMain.Lua.hook.Call("think", new object[] { }); - GameMain.Net.Update(); + GameMain.LuaCs.Update(); + GameMain.LuaCs.hook.Call("think", new object[] { }); performanceCounterTimer.Stop(); LuaTimer.LastUpdateTime = performanceCounterTimer.ElapsedMilliseconds; performanceCounterTimer.Reset(); @@ -437,7 +433,7 @@ namespace Barotrauma public void Exit() { ShouldRun = false; - GameMain.Net.Stop(); + GameMain.LuaCs.Stop(); } } } diff --git a/Barotrauma/BarotraumaServer/ServerSource/Networking/ChatMessage.cs b/Barotrauma/BarotraumaServer/ServerSource/Networking/ChatMessage.cs index 40b628a11..715457b15 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/Networking/ChatMessage.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/Networking/ChatMessage.cs @@ -104,7 +104,7 @@ namespace Barotrauma.Networking bool isOwner = GameMain.Server.OwnerConnection != null && c.Connection == GameMain.Server.OwnerConnection; - if (similarity + c.ChatSpamSpeed > 5.0f && !isOwner && !GameMain.Lua.game.disableSpamFilter) + if (similarity + c.ChatSpamSpeed > 5.0f && !isOwner && !GameMain.LuaCs.game.disableSpamFilter) { GameMain.Server.KarmaManager.OnSpamFilterTriggered(c); @@ -125,7 +125,7 @@ namespace Barotrauma.Networking c.ChatSpamSpeed += similarity + 0.5f; - if (c.ChatSpamTimer > 0.0f && !isOwner && !GameMain.Lua.game.disableSpamFilter) + if (c.ChatSpamTimer > 0.0f && !isOwner && !GameMain.LuaCs.game.disableSpamFilter) { ChatMessage denyMsg = Create("", TextManager.Get("SpamFilterBlocked").Value, ChatMessageType.Server, null); c.ChatSpamTimer = 10.0f; @@ -133,8 +133,7 @@ namespace Barotrauma.Networking return; } - var should = new LuaResult(GameMain.Lua.hook.Call("chatMessage", new object[] { txt, c, type })); - + var should = new LuaResult(GameMain.LuaCs.hook.Call("chatMessage", txt, c, type)); if (should.Bool()) { diff --git a/Barotrauma/BarotraumaServer/ServerSource/Networking/GameServer.cs b/Barotrauma/BarotraumaServer/ServerSource/Networking/GameServer.cs index f7f02b1d8..265edaa96 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/Networking/GameServer.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/Networking/GameServer.cs @@ -202,7 +202,7 @@ namespace Barotrauma.Networking #endif } - GameMain.Lua.Initialize(); + GameMain.LuaCs.Initialize(); TickRate = serverSettings.TickRate; @@ -290,8 +290,8 @@ namespace Barotrauma.Networking SendConsoleMessage("Granted all permissions to " + newClient.Name + ".", newClient); } - GameMain.Lua.hook.Call("clientConnected", new object[] { newClient }); - + GameMain.LuaCs.hook.Call("clientConnected", newClient); + SendChatMessage($"ServerMessage.JoinedServer~[client]={clName}", ChatMessageType.Server, null, changeType: PlayerConnectionChangeType.Joined); serverSettings.ServerDetailsChanged = true; @@ -378,7 +378,7 @@ namespace Barotrauma.Networking Character character = Character.CharacterList[i]; if (character.IsDead || !character.ClientDisconnected) { continue; } - if (!GameMain.Lua.game.disableDisconnectCharacter) + if (!GameMain.LuaCs.game.disableDisconnectCharacter) { character.KillDisconnectedTimer += deltaTime; character.SetStun(1.0f); @@ -700,7 +700,7 @@ namespace Barotrauma.Networking ClientPacketHeader header = (ClientPacketHeader)inc.ReadByte(); - GameMain.Lua.networking.NetMessageReceived(inc, header, connectedClient); + GameMain.LuaCs.networking.NetMessageReceived(inc, header, connectedClient); switch (header) { @@ -1804,7 +1804,7 @@ namespace Barotrauma.Networking outmsg.Write((byte)ServerNetObject.CLIENT_LIST); outmsg.Write(LastClientListUpdateID); - GameMain.Lua.hook.Call("writeClientList", c, outmsg); + GameMain.LuaCs.hook.Call("writeClientList", c, outmsg); outmsg.Write((byte)connectedClients.Count); foreach (Client client in connectedClients) @@ -2251,7 +2251,7 @@ namespace Barotrauma.Networking AssignJobs(teamClients); - var result = new LuaResult(GameMain.Lua.hook.Call("jobsAssigned")); + var result = new LuaResult(GameMain.LuaCs.hook.Call("jobsAssigned")); List characterInfos = new List(); foreach (Client client in teamClients) @@ -2429,7 +2429,7 @@ namespace Barotrauma.Networking { if (!(GameMain.GameSession?.GameMode is CampaignMode)) { - if (!GameMain.Lua.game.overrideTraitors) + if (!GameMain.LuaCs.game.overrideTraitors) { TraitorManager = new TraitorManager(); TraitorManager.Start(this); @@ -2455,7 +2455,7 @@ namespace Barotrauma.Networking roundStartTime = DateTime.Now; - GameMain.Lua.hook.Call("roundStart", new object[] { }); + GameMain.LuaCs.hook.Call("roundStart"); startGameCoroutine = null; yield return CoroutineStatus.Success; @@ -2586,7 +2586,7 @@ namespace Barotrauma.Networking Log("Ending the round...", ServerLog.MessageType.ServerMessage); } - GameMain.Lua.hook.Call("roundEnd", new object[] { }); + GameMain.LuaCs.hook.Call("roundEnd"); string endMessage = TextManager.FormatServerMessage("RoundSummaryRoundHasEnded"); @@ -2697,7 +2697,7 @@ namespace Barotrauma.Networking newName = Client.SanitizeName(newName); if (newName == c.Name && newJob == c.PreferredJob && newTeam == c.PreferredTeam) { return false; } - var result = new LuaResult(GameMain.Lua.hook.Call("tryChangeClientName", c, newName, newJob, newTeam)); + var result = new LuaResult(GameMain.LuaCs.hook.Call("tryChangeClientName", c, newName, newJob, newTeam)); if (!result.IsNull()) { @@ -2892,7 +2892,7 @@ namespace Barotrauma.Networking { if (client == null) return; - GameMain.Lua.hook.Call("clientDisconnected", new object[] { client }); + GameMain.LuaCs.hook.Call("clientDisconnected", client); if (gameStarted && client.Character != null) { @@ -3133,7 +3133,7 @@ namespace Barotrauma.Networking senderName = null; senderCharacter = null; } - else if (type == ChatMessageType.Radio && !GameMain.Lua.game.overrideSignalRadio) + else if (type == ChatMessageType.Radio && !GameMain.LuaCs.game.overrideSignalRadio) { //send to chat-linked wifi components Signal s = new Signal(message, sender: senderCharacter, source: senderRadio.Item); @@ -3142,7 +3142,7 @@ namespace Barotrauma.Networking var hookChatMsg = ChatMessage.Create(senderName, message, (ChatMessageType)type, senderCharacter, senderClient, changeType); - var should = new LuaResult(GameMain.Lua.hook.Call("modifyChatMessage", new object[] { hookChatMsg, senderRadio })); + var should = new LuaResult(GameMain.LuaCs.hook.Call("modifyChatMessage", hookChatMsg, senderRadio)); if (should.Bool()) return; @@ -3874,8 +3874,7 @@ namespace Barotrauma.Networking { if (GameMain.Server == null || !GameMain.Server.ServerSettings.SaveServerLogs) { return; } - if(GameMain.Lua.hook != null) - GameMain.Lua.hook.Call("serverLog", new object[] { line, messageType }); + GameMain.LuaCs?.hook?.Call("serverLog", line, messageType); GameMain.Server.ServerSettings.ServerLog.WriteLine(line, messageType); diff --git a/Barotrauma/BarotraumaServer/ServerSource/Networking/Primitives/Peers/Server/LidgrenServerPeer.cs b/Barotrauma/BarotraumaServer/ServerSource/Networking/Primitives/Peers/Server/LidgrenServerPeer.cs index 58aecd282..75a9ac7d6 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/Networking/Primitives/Peers/Server/LidgrenServerPeer.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/Networking/Primitives/Peers/Server/LidgrenServerPeer.cs @@ -182,21 +182,21 @@ namespace Barotrauma.Networking { if (netServer == null) { return; } - var result = new LuaResult(GameMain.Lua.hook.Call("lidgren.handleConnection", inc)); - if (!result.IsNull()) - if (result.Bool()) - goto ignore; - else - return; + var skipDeny = false; + { + var result = new LuaResult(GameMain.LuaCs.hook.Call("lidgren.handleConnection", inc)); + if (!result.IsNull()) { + if (result.Bool()) skipDeny = true; + else return; + } + } - if (connectedClients.Count >= serverSettings.MaxPlayers) + if (!skipDeny && connectedClients.Count >= serverSettings.MaxPlayers) { inc.SenderConnection.Deny(DisconnectReason.ServerFull.ToString()); return; } - ignore: - if (serverSettings.BanList.IsBanned(inc.SenderConnection.RemoteEndPoint.Address, 0, 0, out string banReason)) { //IP banned: deny immediately diff --git a/Barotrauma/BarotraumaServer/ServerSource/Networking/Primitives/Peers/Server/ServerPeer.cs b/Barotrauma/BarotraumaServer/ServerSource/Networking/Primitives/Peers/Server/ServerPeer.cs index 4ecb00f1a..9b1f66b55 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/Networking/Primitives/Peers/Server/ServerPeer.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/Networking/Primitives/Peers/Server/ServerPeer.cs @@ -206,7 +206,7 @@ namespace Barotrauma.Networking protected void UpdatePendingClient(PendingClient pendingClient) { - var result = new LuaResult(GameMain.Lua.hook.Call("handlePendingClient", pendingClient)); + var result = new LuaResult(GameMain.LuaCs.hook.Call("handlePendingClient", pendingClient)); if (result.Bool()) goto ignore; diff --git a/Barotrauma/BarotraumaServer/ServerSource/Networking/RespawnManager.cs b/Barotrauma/BarotraumaServer/ServerSource/Networking/RespawnManager.cs index 0dedc8f57..7e607d936 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/Networking/RespawnManager.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/Networking/RespawnManager.cs @@ -25,7 +25,7 @@ namespace Barotrauma.Networking MultiPlayerCampaign campaign = GameMain.GameSession.GameMode as MultiPlayerCampaign; foreach (Client c in networkMember.ConnectedClients) { - if (GameMain.Lua.game.overrideRespawnSub) + if (GameMain.LuaCs.game.overrideRespawnSub) continue; if (!c.InGame) { continue; } @@ -125,7 +125,7 @@ namespace Barotrauma.Networking private bool ShouldStartRespawnCountdown(int characterToRespawnCount) { - if (GameMain.Lua.game.overrideRespawnSub) + if (GameMain.LuaCs.game.overrideRespawnSub) { characterToRespawnCount = 0; } @@ -136,7 +136,7 @@ namespace Barotrauma.Networking { if (RespawnShuttle != null) { - if (!GameMain.Lua.game.overrideRespawnSub) + if (!GameMain.LuaCs.game.overrideRespawnSub) { RespawnShuttle.Velocity = Vector2.Zero; } @@ -185,7 +185,7 @@ namespace Barotrauma.Networking { if (RespawnShuttle != null) { - if (GameMain.Lua.game.overrideRespawnSub) + if (GameMain.LuaCs.game.overrideRespawnSub) { CurrentState = State.Waiting; } @@ -206,7 +206,7 @@ namespace Barotrauma.Networking Vector2 spawnPos = FindSpawnPos(); - if (!GameMain.Lua.game.overrideRespawnSub) + if (!GameMain.LuaCs.game.overrideRespawnSub) { RespawnCharacters(spawnPos); } diff --git a/Barotrauma/BarotraumaServer/ServerSource/Networking/Voip/VoipServer.cs b/Barotrauma/BarotraumaServer/ServerSource/Networking/Voip/VoipServer.cs index c2f3aec6d..e6def7658 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/Networking/Voip/VoipServer.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/Networking/Voip/VoipServer.cs @@ -94,7 +94,7 @@ namespace Barotrauma.Networking ChatMessage.CanUseRadio(sender.Character, out WifiComponent senderRadio) && ChatMessage.CanUseRadio(recipient.Character, out WifiComponent recipientRadio)) { - var should = new LuaResult(GameMain.Lua.hook.Call("canUseVoiceRadio", new object[] { sender, recipient })); + var should = new LuaResult(GameMain.LuaCs.hook.Call("canUseVoiceRadio", new object[] { sender, recipient })); if (!should.IsNull()) return should.Bool(); @@ -102,7 +102,7 @@ namespace Barotrauma.Networking if (recipientRadio.CanReceive(senderRadio)) { return true; } } - var should2 = new LuaResult(GameMain.Lua.hook.Call("changeLocalVoiceRange", new object[] { sender, recipient })); + var should2 = new LuaResult(GameMain.LuaCs.hook.Call("changeLocalVoiceRange", new object[] { sender, recipient })); float range = 1.0f; if (!should2.IsNull()) diff --git a/Barotrauma/BarotraumaServer/ServerSource/Traitors/TraitorMission.cs b/Barotrauma/BarotraumaServer/ServerSource/Traitors/TraitorMission.cs index 48086c33e..ffb5a2aac 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/Traitors/TraitorMission.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/Traitors/TraitorMission.cs @@ -92,7 +92,7 @@ namespace Barotrauma var traitorCandidates = new List>(); foreach (Client c in server.ConnectedClients) { - var result = new LuaResult(GameMain.Lua.hook.Call("traitor.findTraitorCandidate", new object[] { c, team })); + var result = new LuaResult(GameMain.LuaCs.hook.Call("traitor.findTraitorCandidate", new object[] { c, team })); if (result.Bool()) { traitorCandidates.Add(Tuple.Create(c, c.Character)); @@ -234,7 +234,7 @@ namespace Barotrauma foreach (var traitor in Traitors.Values) { traitor.Greet(server, CodeWords, CodeResponse, message => pendingMessages[traitor].Add(message)); - GameMain.Lua.hook.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.SendChatMessageBox(message, Identifier))); diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveManager.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveManager.cs index a4888a6f7..067371328 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveManager.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveManager.cs @@ -80,7 +80,7 @@ namespace Barotrauma public void AddObjective(T objective) where T : AIObjective { - var result = new LuaResult(GameMain.Lua.hook.Call("AI.AddObjective", this, objective)); + var result = new LuaResult(GameMain.LuaCs.hook.Call("AI.AddObjective", this, objective)); if (result.Bool()) return; diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/Animation/HumanoidAnimController.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/Animation/HumanoidAnimController.cs index fa8cb41e3..d1312c280 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/Animation/HumanoidAnimController.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/Animation/HumanoidAnimController.cs @@ -1440,11 +1440,11 @@ namespace Barotrauma // -> 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); - GameMain.Lua.hook.Call("human.CPRSuccess", this); - } + GameMain.LuaCs.hook.Call("human.CPRSuccess", this); + } else { - GameMain.Lua.hook.Call("human.CPRFailed", this); + GameMain.LuaCs.hook.Call("human.CPRFailed", this); } } } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/Animation/Ragdoll.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/Animation/Ragdoll.cs index 65fdb62b8..56eed8f70 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/Animation/Ragdoll.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/Animation/Ragdoll.cs @@ -745,9 +745,9 @@ namespace Barotrauma float impactDamage = Math.Min((impact - ImpactTolerance) * ImpactDamageMultiplayer, character.MaxVitality * MaxImpactDamage); - var should = new LuaResult(GameMain.Lua.hook.Call("changeFallDamage", new object[] { impactDamage, character, impactPos, velocity })); + var should = new LuaResult(GameMain.LuaCs.hook.Call("changeFallDamage", new object[] { impactDamage, character, impactPos, velocity })); - if (!should.IsNull()) + if (!should.IsNull()) { impactDamage = should.Float(); } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/Character.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/Character.cs index b92032931..cc4f9979c 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/Character.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/Character.cs @@ -1043,7 +1043,7 @@ namespace Barotrauma } #endif - GameMain.Lua.hook.Call("characterCreated", new object[] { newCharacter }); + GameMain.LuaCs.hook.Call("characterCreated", new object[] { newCharacter }); return newCharacter; } @@ -2723,13 +2723,13 @@ namespace Barotrauma { for (int i = 0; i < CharacterList.Count; i++) { - if (GameMain.Lua.game.updatePriorityCharacters.Contains(CharacterList[i])) continue; + if (GameMain.LuaCs.game.updatePriorityCharacters.Contains(CharacterList[i])) continue; CharacterList[i].Update(deltaTime * CharacterUpdateInterval, cam); } } - foreach (Character character in GameMain.Lua.game.updatePriorityCharacters) + foreach (Character character in GameMain.LuaCs.game.updatePriorityCharacters) { if (character.Removed) continue; diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/Health/Afflictions/Affliction.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/Health/Afflictions/Affliction.cs index 6b38e2e7a..ac261a2ec 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/Health/Afflictions/Affliction.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/Health/Afflictions/Affliction.cs @@ -388,7 +388,7 @@ namespace Barotrauma AdditionStrength -= amount; } #if SERVER - GameMain.Lua.hook.Call("afflictionUpdate", new object[] { this, characterHealth, targetLimb, deltaTime }); + GameMain.LuaCs.hook.Call("afflictionUpdate", new object[] { this, characterHealth, targetLimb, deltaTime }); #endif } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/Health/Afflictions/AfflictionHusk.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/Health/Afflictions/AfflictionHusk.cs index 10aa28888..8faa09785 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/Health/Afflictions/AfflictionHusk.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/Health/Afflictions/AfflictionHusk.cs @@ -302,13 +302,13 @@ namespace Barotrauma if (Prefab is AfflictionPrefabHusk huskPrefab) { - if (huskPrefab.ControlHusk || GameMain.Lua.game.enableControlHusk) + if (huskPrefab.ControlHusk || GameMain.LuaCs.game.enableControlHusk) { #if SERVER if (client != null) { GameMain.Server.SetClientCharacter(client, husk); - GameMain.Lua.hook.Call("husk.clientControlHusk", new object[] { client, husk }); + GameMain.LuaCs.hook.Call("husk.clientControlHusk", new object[] { client, husk }); } #else if (!character.IsRemotelyControlled && character == Character.Controlled) diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/Health/CharacterHealth.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/Health/CharacterHealth.cs index c8758c2d3..70542fb17 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/Health/CharacterHealth.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/Health/CharacterHealth.cs @@ -541,7 +541,7 @@ namespace Barotrauma return; } - var should = new LuaResult(GameMain.Lua.hook.Call("character.applyDamage", new object[] { this, attackResult, hitLimb, allowStacking })); + var should = new LuaResult(GameMain.LuaCs.hook.Call("character.applyDamage", new object[] { this, attackResult, hitLimb, allowStacking })); if (should.Bool()) return; @@ -674,7 +674,7 @@ namespace Barotrauma } } - var should = new LuaResult(GameMain.Lua.hook.Call("character.applyAffliction", new object[] { this, limbHealth, newAffliction, allowStacking })); + var should = new LuaResult(GameMain.LuaCs.hook.Call("character.applyAffliction", new object[] { this, limbHealth, newAffliction, allowStacking })); if (should.Bool()) return; diff --git a/Barotrauma/BarotraumaShared/SharedSource/GameSession/GameSession.cs b/Barotrauma/BarotraumaShared/SharedSource/GameSession/GameSession.cs index 420448fa7..ef998a8f7 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/GameSession/GameSession.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/GameSession/GameSession.cs @@ -526,7 +526,7 @@ namespace Barotrauma HintManager.OnRoundStarted(); - GameMain.Lua.hook.Call("roundStart"); + GameMain.LuaCs.hook.Call("roundStart"); #endif } @@ -781,7 +781,7 @@ namespace Barotrauma RoundEnding = true; #if CLIENT - GameMain.Lua.hook.Call("roundEnd"); + GameMain.LuaCs.hook.Call("roundEnd"); #endif //Clear the grids to allow for garbage collection Powered.Grids.Clear(); diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Holdable/MeleeWeapon.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Holdable/MeleeWeapon.cs index d897f9125..95f76db14 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Holdable/MeleeWeapon.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Holdable/MeleeWeapon.cs @@ -387,7 +387,7 @@ namespace Barotrauma.Items.Components Limb targetLimb = target.UserData as Limb; Character targetCharacter = targetLimb?.character ?? target.UserData as Character; - GameMain.Lua.hook.Call("meleeWeapon.handleImpact", this, target); + GameMain.LuaCs.hook.Call("meleeWeapon.handleImpact", this, target); if (Attack != null) { Attack.SetUser(User); diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/Connection.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/Connection.cs index f2c20f148..cc899a070 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/Connection.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/Connection.cs @@ -325,8 +325,8 @@ namespace Barotrauma.Items.Components Connection connection = recipient; object[] obj = new object[] { signal, connection }; - GameMain.Lua.hook.Call("signalReceived", obj); - GameMain.Lua.hook.Call("signalReceived." + recipient.item.Prefab.Identifier, obj); + GameMain.LuaCs.hook.Call("signalReceived", obj); + GameMain.LuaCs.hook.Call("signalReceived." + recipient.item.Prefab.Identifier, obj); foreach (ItemComponent ic in recipient.item.Components) { diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/WifiComponent.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/WifiComponent.cs index 266716c0f..d2beb3877 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/WifiComponent.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/WifiComponent.cs @@ -74,7 +74,7 @@ namespace Barotrauma.Items.Components #if SERVER get { - if(GameMain.Lua.game.allowWifiChat) return true; + if(GameMain.LuaCs.game.allowWifiChat) return true; return linkToChat; } @@ -205,7 +205,7 @@ namespace Barotrauma.Items.Components public void TransmitSignal(Signal signal, bool sentFromChat) { - var should = new LuaResult(GameMain.Lua.hook.Call("wifiSignalTransmitted", new object[] { this, signal, sentFromChat })); + var should = new LuaResult(GameMain.LuaCs.hook.Call("wifiSignalTransmitted", new object[] { this, signal, sentFromChat })); if (should.Bool()) return; diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Inventory.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Inventory.cs index 50d504c7b..a44bc7ed0 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Inventory.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Inventory.cs @@ -540,7 +540,7 @@ namespace Barotrauma return; } - var should = new LuaResult(GameMain.Lua.hook.Call("inventoryPutItem", new object[] { this, item, user, i, removeItem })); + var should = new LuaResult(GameMain.LuaCs.hook.Call("inventoryPutItem", new object[] { this, item, user, i, removeItem })); if (should.Bool()) return; @@ -648,7 +648,7 @@ namespace Barotrauma if (slots[index].Items.Any(it => !it.IsInteractable(user))) { return false; } if (!AllowSwappingContainedItems) { return false; } - var should = new LuaResult(GameMain.Lua.hook.Call("inventoryItemSwap", new object[] { this, item, user, index, swapWholeStack })); + var should = new LuaResult(GameMain.LuaCs.hook.Call("inventoryItemSwap", new object[] { this, item, user, index, swapWholeStack })); if (!should.IsNull()) return should.Bool(); diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Item.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Item.cs index 8f4ea6f8e..3fa54b557 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Item.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Item.cs @@ -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 (HasTag("logic")) { isLogic = true; } - GameMain.Lua.hook.Call("item.created", this); + GameMain.LuaCs.hook.Call("item.created", this); ApplyStatusEffects(ActionType.OnSpawn, 1.0f); Components.ForEach(c => c.ApplyStatusEffects(ActionType.OnSpawn, 1.0f)); @@ -2469,7 +2469,7 @@ namespace Barotrauma if (condition == 0.0f) { return; } - var should = new LuaResult(GameMain.Lua.hook.Call("item.use", new object[] { this, character, targetLimb })); + var should = new LuaResult(GameMain.LuaCs.hook.Call("item.use", new object[] { this, character, targetLimb })); if (should.Bool()) return; @@ -2507,7 +2507,7 @@ namespace Barotrauma { if (condition == 0.0f) { return; } - var should = new LuaResult(GameMain.Lua.hook.Call("item.secondaryUse", new object[] { this, character})); + var should = new LuaResult(GameMain.LuaCs.hook.Call("item.secondaryUse", new object[] { this, character})); if (should.Bool()) return; @@ -2851,7 +2851,7 @@ namespace Barotrauma } } - var result = new LuaResult(GameMain.Lua.hook.Call("item.readPropertyChange", this, property, parentObject, allowEditing)); + var result = new LuaResult(GameMain.LuaCs.hook.Call("item.readPropertyChange", this, property, parentObject, allowEditing)); if (result.Bool()) return; @@ -3343,7 +3343,7 @@ namespace Barotrauma body = null; } - GameMain.Lua.hook.Call("item.removed", this); + GameMain.LuaCs.hook.Call("item.removed", this); } public override void Remove() @@ -3427,7 +3427,7 @@ namespace Barotrauma RemoveProjSpecific(); - GameMain.Lua.hook.Call("item.removed", this); + GameMain.LuaCs.hook.Call("item.removed", this); } partial void RemoveProjSpecific(); diff --git a/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaClasses/LuaClasses.cs b/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaClasses/LuaClasses.cs index 399f979de..5c345de02 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaClasses/LuaClasses.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaClasses/LuaClasses.cs @@ -31,7 +31,7 @@ namespace Barotrauma public void Wait(object function, int millisecondDelay) { - GameMain.Lua.hook.EnqueueTimedFunction((float)Timing.TotalTime + (millisecondDelay / 1000f), function); + GameMain.LuaCs.hook.EnqueueTimedFunction((float)Timing.TotalTime + (millisecondDelay / 1000f), function); } public static double GetTime() @@ -122,14 +122,14 @@ namespace Barotrauma if (CanWriteToPath(path)) return true; else - GameMain.Lua.HandleLuaException(new Exception("File access to \"" + path + "\" not allowed.")); + GameMain.LuaCs.HandleLuaException(new Exception("File access to \"" + path + "\" not allowed.")); } else { if (CanReadFromPath(path)) return true; else - GameMain.Lua.HandleLuaException(new Exception("File access to \"" + path + "\" not allowed.")); + GameMain.LuaCs.HandleLuaException(new Exception("File access to \"" + path + "\" not allowed.")); } return false; @@ -239,29 +239,29 @@ namespace Barotrauma { string netMessageName = netMessage.ReadString(); if (LuaNetReceives[netMessageName] is Closure) - GameMain.Lua.CallFunction(LuaNetReceives[netMessageName], new object[] { netMessage, client }); + GameMain.LuaCs.CallFunction(LuaNetReceives[netMessageName], new object[] { netMessage, client }); } else { - GameMain.Lua.hook.Call("netMessageReceived", netMessage, header, client); + GameMain.LuaCs.hook.Call("netMessageReceived", netMessage, header, client); } } #else - [MoonSharpHidden] - public void NetMessageReceived(IReadMessage netMessage, ServerPacketHeader header, Client client = null) + [MoonSharpHidden] + public void NetMessageReceived(IReadMessage netMessage, ServerPacketHeader header, Client client = null) + { + if (header == ServerPacketHeader.LUA_NET_MESSAGE) { - if (header == ServerPacketHeader.LUA_NET_MESSAGE) - { - string netMessageName = netMessage.ReadString(); - if (LuaNetReceives[netMessageName] is Closure) - GameMain.Lua.lua.Call(LuaNetReceives[netMessageName], new object[] { netMessage, client }); - } - else - { - GameMain.Lua.hook.Call("netMessageReceived", netMessage, header, client); - } + string netMessageName = netMessage.ReadString(); + if (LuaNetReceives[netMessageName] is Closure) + GameMain.LuaCs.lua.Call(LuaNetReceives[netMessageName], new object[] { netMessage, client }); } + else + { + GameMain.LuaCs.hook.Call("netMessageReceived", netMessage, header, client); + } + } #endif public void Receive(string netMessageName, object callback) @@ -327,18 +327,18 @@ namespace Barotrauma { var httpResponse = httpWebRequest.EndGetResponse(result); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) - GameMain.Lua.hook.EnqueueFunction(callback, streamReader.ReadToEnd()); + GameMain.LuaCs.hook.EnqueueFunction(callback, streamReader.ReadToEnd()); } catch (Exception e) { - GameMain.Lua.hook.EnqueueFunction(callback, e.ToString()); + GameMain.LuaCs.hook.EnqueueFunction(callback, e.ToString()); } }), null); } catch (Exception e) { - GameMain.Lua.hook.EnqueueFunction(callback, e.ToString()); + GameMain.LuaCs.hook.EnqueueFunction(callback, e.ToString()); } } @@ -354,17 +354,17 @@ namespace Barotrauma { var httpResponse = httpWebRequest.EndGetResponse(result); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) - GameMain.Lua.hook.EnqueueFunction(callback, streamReader.ReadToEnd()); + GameMain.LuaCs.hook.EnqueueFunction(callback, streamReader.ReadToEnd()); } catch (Exception e) { - GameMain.Lua.hook.EnqueueFunction(callback, e.ToString()); + GameMain.LuaCs.hook.EnqueueFunction(callback, e.ToString()); } }), null); } catch (Exception e) { - GameMain.Lua.hook.EnqueueFunction(callback, e.ToString()); + GameMain.LuaCs.hook.EnqueueFunction(callback, e.ToString()); } } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaClasses/LuaGame.cs b/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaClasses/LuaGame.cs index 60c46a5e3..576523ac0 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaClasses/LuaGame.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaClasses/LuaGame.cs @@ -326,11 +326,11 @@ namespace Barotrauma public void AddCommand(string name, string help, object onExecute, object getValidArgs = null, bool isCheat = false) { - var cmd = new DebugConsole.Command(name, help, (string[] arg1) => { GameMain.Lua.CallFunction(onExecute, new object[] { arg1 }); }, + var cmd = new DebugConsole.Command(name, help, (string[] arg1) => { GameMain.LuaCs.CallFunction(onExecute, new object[] { arg1 }); }, () => { if (getValidArgs == null) return null; - var result = new LuaResult(GameMain.Lua.CallFunction(getValidArgs, new object[] { })); + var result = new LuaResult(GameMain.LuaCs.CallFunction(getValidArgs, new object[] { })); var obj = result.Object(); if (obj is string[][]) return (string[][])obj; return null; @@ -357,7 +357,7 @@ namespace Barotrauma public List Commands => DebugConsole.Commands; - public void AssignOnExecute(string names, object onExecute) => DebugConsole.AssignOnExecute(names, (string[] a) => { GameMain.Lua.CallFunction(onExecute, new object[] { a }); }); + public void AssignOnExecute(string names, object onExecute) => DebugConsole.AssignOnExecute(names, (string[] a) => { GameMain.LuaCs.CallFunction(onExecute, new object[] { a }); }); #if SERVER @@ -412,7 +412,7 @@ namespace Barotrauma GameMain.Server.EndGame(); } - public void AssignOnClientRequestExecute(string names, object onExecute) => DebugConsole.AssignOnClientRequestExecute(names, (Client a, Vector2 b, string[] c) => { GameMain.Lua.CallFunction(onExecute, new object[] { a, b, c }); }); + public void AssignOnClientRequestExecute(string names, object onExecute) => DebugConsole.AssignOnClientRequestExecute(names, (Client a, Vector2 b, string[] c) => { GameMain.LuaCs.CallFunction(onExecute, new object[] { a, b, c }); }); #endif diff --git a/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaClasses/LuaHook.cs b/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaClasses/LuaHook.cs deleted file mode 100644 index ced9ef980..000000000 --- a/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaClasses/LuaHook.cs +++ /dev/null @@ -1,364 +0,0 @@ -using System; -using System.Linq; -using System.Reflection; -using MoonSharp.Interpreter; -using HarmonyLib; -using System.Collections.Generic; -using System.Text; - -namespace Barotrauma -{ - partial class LuaHook - { - public LuaHook() - { - _hookPrefixMethods = new Dictionary>>(); - _hookPostfixMethods = new Dictionary>>(); - } - - public class HookFunction - { - public string name; - public string hookName; - public object function; - - public HookFunction(string n, string hn, object func) - { - name = n; - hookName = hn; - function = func; - } - } - - private Dictionary> hookFunctions = new Dictionary>(); - - private static Dictionary>> _hookPrefixMethods; - private static Dictionary>> _hookPostfixMethods; - - private Queue> queuedFunctionCalls = new Queue>(); - - public enum HookMethodType - { - Before, After - } - - 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> methodSet = null; - switch (hookMethodType) - { - case HookMethodType.Before: - _hookPrefixMethods.TryGetValue(funcAddr, out methodSet); - break; - case HookMethodType.After: - _hookPostfixMethods.TryGetValue(funcAddr, out methodSet); - break; - default: - break; - } - - if (methodSet != null) - { - var @params = __originalMethod.GetParameters(); - var ptable = new Dictionary(); - for (int i = 0; i < @params.Length; i++) - { - ptable.Add(@params[i].Name, __args[i]); - } - - foreach (var tuple in methodSet) - { - result = new LuaResult(GameMain.Lua.lua.Call(tuple.Item2, __instance, ptable)); - } - } - } - catch (Exception ex) - { - GameMain.Lua.HandleLuaException(ex); - } - } - - static bool HookLuaPatchPrefix(MethodBase __originalMethod, object[] __args, object __instance) - { - _hookLuaPatch(__originalMethod, __args, __instance, out LuaResult result, HookMethodType.Before); - - return result.IsNull(); - } - - 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 (__originalMethod is MethodInfo mi) - { - __result = result.DynValue().ToObject(mi.ReturnType); - } - else - { - __result = result.Object(); - } - - return false; - } - - return true; - } - - static void HookLuaPatchPostfix(MethodBase __originalMethod, object[] __args, object __instance) - { - _hookLuaPatch(__originalMethod, __args, __instance, out LuaResult result, HookMethodType.After); - } - - static void HookLuaPatchRetPostfix(MethodBase __originalMethod, object[] __args, ref object __result, object __instance) - { - _hookLuaPatch(__originalMethod, __args, __instance, out LuaResult result, HookMethodType.After); - - if (!result.IsNull()) - { - if (__originalMethod is MethodInfo mi) - { - __result = result.DynValue().ToObject(mi.ReturnType); - } - else - { - __result = result.Object(); - } - } - } - - private const BindingFlags DefaultBindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; - private static MethodInfo _miHookLuaPatchPrefix = typeof(LuaHook).GetMethod("HookLuaPatchPrefix", BindingFlags.NonPublic | BindingFlags.Static); - private static MethodInfo _miHookLuaPatchRetPrefix = typeof(LuaHook).GetMethod("HookLuaPatchRetPrefix", BindingFlags.NonPublic | BindingFlags.Static); - private static MethodInfo _miHookLuaPatchPostfix = typeof(LuaHook).GetMethod("HookLuaPatchPostfix", BindingFlags.NonPublic | BindingFlags.Static); - private static MethodInfo _miHookLuaPatchRetPostfix = typeof(LuaHook).GetMethod("HookLuaPatchRetPostfix", BindingFlags.NonPublic | BindingFlags.Static); - public void HookMethod(string identifier, string className, string methodName, string[] parameterNames, object hookMethod, HookMethodType hookMethodType = HookMethodType.Before) - { - var classType = LuaUserData.GetType(className); - - if (classType == null) - { - GameMain.Lua.HandleLuaException(new Exception($"Tried to use HookMethod with an invalid class name '{className}'.")); - return; - } - - MethodInfo methodInfo = null; - - if (parameterNames != null) - { - Type[] parameterTypes = parameterNames.Select(x => LuaUserData.GetType(x)).ToArray(); - methodInfo = classType.GetMethod(methodName, DefaultBindingFlags, null, parameterTypes, null); - } - else - { - methodInfo = classType.GetMethod(methodName, DefaultBindingFlags); - } - - if (methodInfo == null) - { - string parameterNamesStr = parameterNames == null ? "" : string.Join(", ", parameterNames == null); - GameMain.Lua.HandleLuaException(new Exception($"Method '{methodName}' with parameters '{parameterNamesStr}' not found in class '{className}'")); - 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.Lua.harmony.Patch(methodInfo, prefix: new HarmonyMethod(_miHookLuaPatchPrefix)); - } - } - else - { - if (patches == null || patches.Prefixes == null || patches.Prefixes.Find(patch => patch.PatchMethod == _miHookLuaPatchRetPrefix) == null) - { - GameMain.Lua.harmony.Patch(methodInfo, prefix: new HarmonyMethod(_miHookLuaPatchRetPrefix)); - } - } - - if (_hookPrefixMethods.TryGetValue(funcAddr, out HashSet> methodSet)) - { - if (identifier != "") - { - methodSet.RemoveWhere(tuple => tuple.Item1 == identifier); - } - if (hookMethod != null) - { - methodSet.Add(Tuple.Create(identifier, hookMethod)); - } - } - else if (hookMethod != null) - { - _hookPrefixMethods.Add(funcAddr, new HashSet>() { Tuple.Create(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.Lua.harmony.Patch(methodInfo, postfix: new HarmonyMethod(_miHookLuaPatchPostfix)); - } - } - else - { - if (patches == null || patches.Postfixes == null || patches.Postfixes.Find(patch => patch.PatchMethod == _miHookLuaPatchRetPostfix) == null) - { - GameMain.Lua.harmony.Patch(methodInfo, postfix: new HarmonyMethod(_miHookLuaPatchRetPostfix)); - } - } - - if (_hookPostfixMethods.TryGetValue(funcAddr, out HashSet> methodSet)) - { - if (identifier != "") - { - methodSet.RemoveWhere(tuple => tuple.Item1 == identifier); - } - if (hookMethod != null) - { - methodSet.Add(Tuple.Create(identifier, hookMethod)); - } - } - else if (hookMethod != null) - { - _hookPostfixMethods.Add(funcAddr, new HashSet>() { Tuple.Create(identifier, hookMethod) }); - } - - } - - } - - public void HookMethod(string className, string methodName, object hookMethod, HookMethodType hookMethodType = HookMethodType.Before) - { - HookMethod("", className, methodName, null, hookMethod, hookMethodType); - } - - public void HookMethod(string className, string methodName, string[] parameterNames, object hookMethod, HookMethodType hookMethodType = HookMethodType.Before) - { - HookMethod("", className, methodName, parameterNames, hookMethod, hookMethodType); - } - - public void HookMethod(string identifier, string className, string methodName, object hookMethod, HookMethodType hookMethodType = HookMethodType.Before) - { - HookMethod(identifier, className, methodName, null, hookMethod, hookMethodType); - } - - public void EnqueueFunction(object function, params object[] args) - { - queuedFunctionCalls.Enqueue(new Tuple(0, function, args)); - } - - public void EnqueueTimedFunction(float time, object function, params object[] args) - { - queuedFunctionCalls.Enqueue(new Tuple(time, function, args)); - } - - public void Add(string name, string hookName, object function) - { - if (name == null && hookName == null && function == null) return; - - name = name.ToLower(); - - if (!hookFunctions.ContainsKey(name)) - hookFunctions.Add(name, new Dictionary()); - - hookFunctions[name][hookName] = new HookFunction(name, hookName, function); - } - - public void Remove(string name, string hookName) - { - if (name == null && hookName == null) return; - - name = name.ToLower(); - - if (!hookFunctions.ContainsKey(name)) - return; - - if (hookFunctions[name].ContainsKey(hookName)) - hookFunctions[name].Remove(hookName); - } - - public void Update() - { - try - { - if (queuedFunctionCalls.TryPeek(out Tuple result)) - { - if (Timing.TotalTime >= result.Item1) - { - GameMain.Lua.CallFunction(result.Item2, result.Item3); - - queuedFunctionCalls.Dequeue(); - } - } - } - catch (Exception ex) - { - GameMain.Lua.HandleLuaException(ex, $"queuedFunctionCalls was {queuedFunctionCalls}"); - } - } - - public object Call(string name, params object[] args) - { -#if CLIENT - if (GameMain.GameSession?.IsRunning == false && GameMain.IsSingleplayer) - return null; -#endif - if (GameMain.Lua == null) return null; - if (name == null) return null; - if (args == null) { args = new object[] { }; } - - name = name.ToLower(); - - if (!hookFunctions.ContainsKey(name)) - return null; - - object lastResult = null; - - foreach (HookFunction hf in hookFunctions[name].Values) - { - try - { - if (hf.function is Closure) - { - var result = GameMain.Lua.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.Lua.HandleLuaException(e, $"Error in Hook '{name}'->'{hf.hookName}', with args '{argsSb}'"); - } - } - - return lastResult; - } - } -} \ No newline at end of file diff --git a/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaClasses/LuaUserData.cs b/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaClasses/LuaUserData.cs index 85a3da2a8..7449f5736 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaClasses/LuaUserData.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaClasses/LuaUserData.cs @@ -28,7 +28,7 @@ namespace Barotrauma if (type == null) { - GameMain.Lua.HandleLuaException(new Exception($"Tried to register a type that doesn't exist: {typeName}.")); + GameMain.LuaCs.HandleLuaException(new Exception($"Tried to register a type that doesn't exist: {typeName}.")); return null; } @@ -41,7 +41,7 @@ namespace Barotrauma if (type == null) { - GameMain.Lua.HandleLuaException(new Exception($"Tried to unregister a type that doesn't exist: {typeName}.")); + GameMain.LuaCs.HandleLuaException(new Exception($"Tried to unregister a type that doesn't exist: {typeName}.")); return; } @@ -79,7 +79,7 @@ namespace Barotrauma if (type == null) { - GameMain.Lua.HandleLuaException(new Exception($"Tried to create a static userdata of a type that doesn't exist: {typeName}.")); + GameMain.LuaCs.HandleLuaException(new Exception($"Tried to create a static userdata of a type that doesn't exist: {typeName}.")); return null; } @@ -94,7 +94,7 @@ namespace Barotrauma if (type == null) { - GameMain.Lua.HandleLuaException(new Exception($"Tried to create an enum table with a type that doesn't exist:: {typeName}.")); + GameMain.LuaCs.HandleLuaException(new Exception($"Tried to create an enum table with a type that doesn't exist:: {typeName}.")); return null; } @@ -126,7 +126,7 @@ namespace Barotrauma { if (IUUD == null) { - GameMain.Lua.HandleLuaException(new Exception($"Tried to use a UserDataDescriptor that is null to make {fieldName} accessible.")); + GameMain.LuaCs.HandleLuaException(new Exception($"Tried to use a UserDataDescriptor that is null to make {fieldName} accessible.")); return; } @@ -140,7 +140,7 @@ namespace Barotrauma if (field == null) { - GameMain.Lua.HandleLuaException(new Exception($"Tried to make field '{fieldName}' accessible, but the field doesn't exist.")); + GameMain.LuaCs.HandleLuaException(new Exception($"Tried to make field '{fieldName}' accessible, but the field doesn't exist.")); return; } @@ -164,7 +164,7 @@ namespace Barotrauma { if (IUUD == null) { - GameMain.Lua.HandleLuaException(new Exception($"Tried to use a UserDataDescriptor that is null to make {methodName} accessible.")); + GameMain.LuaCs.HandleLuaException(new Exception($"Tried to use a UserDataDescriptor that is null to make {methodName} accessible.")); return; } @@ -178,7 +178,7 @@ namespace Barotrauma if (method == null) { - GameMain.Lua.HandleLuaException(new Exception($"Tried to make method '{methodName}' accessible, but the method doesn't exist.")); + GameMain.LuaCs.HandleLuaException(new Exception($"Tried to make method '{methodName}' accessible, but the method doesn't exist.")); return; } @@ -190,7 +190,7 @@ namespace Barotrauma { if (IUUD == null) { - GameMain.Lua.HandleLuaException(new Exception($"Tried to use a UserDataDescriptor that is null to add method {methodName}.")); + GameMain.LuaCs.HandleLuaException(new Exception($"Tried to use a UserDataDescriptor that is null to add method {methodName}.")); return; } @@ -198,8 +198,8 @@ namespace Barotrauma descriptor.RemoveMember(methodName); descriptor.AddMember(methodName, new ObjectCallbackMemberDescriptor(methodName, (object arg1, ScriptExecutionContext arg2, CallbackArguments arg3) => { - if (GameMain.Lua != null) - return GameMain.Lua.CallFunction(function, arg3.GetArray()); + if (GameMain.LuaCs != null) + return GameMain.LuaCs.CallFunction(function, arg3.GetArray()); return null; })); } @@ -208,7 +208,7 @@ namespace Barotrauma { if (IUUD == null) { - GameMain.Lua.HandleLuaException(new Exception($"Tried to use a UserDataDescriptor that is null to remove the member {memberName}.")); + GameMain.LuaCs.HandleLuaException(new Exception($"Tried to use a UserDataDescriptor that is null to remove the member {memberName}.")); return; } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaCustomConverters.cs b/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaCustomConverters.cs index deb737a35..6ccd076d3 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaCustomConverters.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaCustomConverters.cs @@ -29,7 +29,7 @@ namespace Barotrauma RegisterAction(); { - object Call(object function, params object[] arguments) => GameMain.Lua.CallFunction(function, arguments); + object Call(object function, params object[] arguments) => GameMain.LuaCs.CallFunction(function, arguments); void RegisterHandler(Func converter) { Script.GlobalOptions.CustomConverters.SetScriptToClrCustomConversion(DataType.Function, typeof(T), v => converter(v.Function)); @@ -122,7 +122,7 @@ namespace Barotrauma Script.GlobalOptions.CustomConverters.SetScriptToClrCustomConversion(DataType.Function, typeof(Action), v => { var function = v.Function; - return (Action)(p => GameMain.Lua.CallFunction(function, p)); + return (Action)(p => GameMain.LuaCs.CallFunction(function, p)); }); } @@ -131,7 +131,7 @@ namespace Barotrauma Script.GlobalOptions.CustomConverters.SetScriptToClrCustomConversion(DataType.Function, typeof(Action), v => { var function = v.Function; - return (Action)((a1, a2) => GameMain.Lua.CallFunction(function, a1, a2)); + return (Action)((a1, a2) => GameMain.LuaCs.CallFunction(function, a1, a2)); }); } @@ -140,7 +140,7 @@ namespace Barotrauma Script.GlobalOptions.CustomConverters.SetScriptToClrCustomConversion(DataType.Function, typeof(Action), v => { var function = v.Function; - return (Action)(() => GameMain.Lua.CallFunction(function)); + return (Action)(() => GameMain.LuaCs.CallFunction(function)); }); } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaScriptLoader.cs b/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaScriptLoader.cs index dd49dd7b8..b75657617 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaScriptLoader.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaScriptLoader.cs @@ -8,7 +8,7 @@ using System.Linq; namespace Barotrauma { - partial class LuaSetup { + partial class LuaCsSetup { public class LuaScriptLoader : ScriptLoaderBase { diff --git a/Barotrauma/BarotraumaShared/SharedSource/LuaCs/LuaCsHook.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/LuaCsHook.cs new file mode 100644 index 000000000..5cdc4a28e --- /dev/null +++ b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/LuaCsHook.cs @@ -0,0 +1,448 @@ +using System; +using System.Linq; +using System.Reflection; +using MoonSharp.Interpreter; +using HarmonyLib; +using System.Collections.Generic; +using System.Text; + +namespace Barotrauma +{ + delegate object CsHookDelegate(params object[] args); + delegate object CsPatchDelegate(object self, params object[] args); + + partial class LuaCsHook + { + public LuaCsHook() + { + luaHookPrefixMethods = new Dictionary>(); + luaHookPostfixMethods = new Dictionary>(); + csHookPrefixMethods = new Dictionary>(); + csHookPostfixMethods = new Dictionary>(); + } + + public class LuaHookFunction + { + public string name; + public string hookName; + public object function; + + public LuaHookFunction(string n, string hn, object func) + { + name = n; + hookName = hn; + function = func; + } + } + + private Dictionary> luaHookFunctions = new Dictionary>(); + private Dictionary> csHookFunctions = new Dictionary>(); + + private static Dictionary> luaHookPrefixMethods; + private static Dictionary> luaHookPostfixMethods; + private static Dictionary> csHookPrefixMethods; + private static Dictionary> csHookPostfixMethods; + + private Queue> queuedFunctionCalls = new Queue>(); + + public enum HookMethodType + { + Before, After + } + + 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: + luaHookPrefixMethods.TryGetValue(funcAddr, out methodSet); + break; + case HookMethodType.After: + luaHookPostfixMethods.TryGetValue(funcAddr, out methodSet); + break; + default: + break; + } + + if (methodSet != null) + { + var @params = __originalMethod.GetParameters(); + var ptable = new Dictionary(); + for (int i = 0; i < @params.Length; i++) + { + ptable.Add(@params[i].Name, __args[i]); + } + + foreach (var tuple in methodSet) + { + result = new LuaResult(GameMain.LuaCs.lua.Call(tuple.Item2, __instance, ptable)); + } + } + } + catch (Exception ex) + { + GameMain.LuaCs.HandleLuaException(ex); + } + } + + private static bool HookLuaPatchPrefix(MethodBase __originalMethod, object[] __args, object __instance) + { + _hookLuaPatch(__originalMethod, __args, __instance, out LuaResult result, HookMethodType.Before); + + return result.IsNull(); + } + + 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 (__originalMethod is MethodInfo mi) + { + __result = result.DynValue().ToObject(mi.ReturnType); + } + else + { + __result = result.Object(); + } + + return false; + } + + return true; + } + + private static void HookLuaPatchPostfix(MethodBase __originalMethod, object[] __args, object __instance) + { + _hookLuaPatch(__originalMethod, __args, __instance, out LuaResult result, HookMethodType.After); + } + + private static void HookLuaPatchRetPostfix(MethodBase __originalMethod, object[] __args, ref object __result, object __instance) + { + _hookLuaPatch(__originalMethod, __args, __instance, out LuaResult result, HookMethodType.After); + + if (!result.IsNull()) + { + if (__originalMethod is MethodInfo mi) + { + __result = result.DynValue().ToObject(mi.ReturnType); + } + else + { + __result = result.Object(); + } + } + } + + 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 void HookMethod(string identifier, string className, string methodName, string[] parameterNames, object hookMethod, HookMethodType hookMethodType = HookMethodType.Before) + { + var classType = LuaUserData.GetType(className); + + if (classType == null) + { + GameMain.LuaCs.HandleLuaException(new Exception($"Tried to use HookMethod with an invalid class name '{className}'.")); + return; + } + + MethodInfo methodInfo = null; + + if (parameterNames != null) + { + Type[] parameterTypes = parameterNames.Select(x => LuaUserData.GetType(x)).ToArray(); + methodInfo = classType.GetMethod(methodName, DefaultBindingFlags, null, parameterTypes, null); + } + else + { + methodInfo = classType.GetMethod(methodName, DefaultBindingFlags); + } + + if (methodInfo == null) + { + string parameterNamesStr = parameterNames == null ? "" : string.Join(", ", parameterNames == null); + GameMain.LuaCs.HandleLuaException(new Exception($"Method '{methodName}' with parameters '{parameterNamesStr}' not found in class '{className}'")); + 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) }); + } + + } + + } + + private void HookMethod(string className, string methodName, object hookMethod, HookMethodType hookMethodType = HookMethodType.Before) + { + HookMethod("", className, methodName, null, hookMethod, hookMethodType); + } + + private void HookMethod(string className, string methodName, string[] parameterNames, object hookMethod, HookMethodType hookMethodType = HookMethodType.Before) + { + HookMethod("", className, methodName, parameterNames, hookMethod, hookMethodType); + } + + private void HookMethod(string identifier, string className, string methodName, object hookMethod, HookMethodType hookMethodType = HookMethodType.Before) + { + HookMethod(identifier, className, methodName, null, hookMethod, hookMethodType); + } + + public void HookMethod(IDisposable owner, MethodInfo methodInfo, CsPatchDelegate hookMethod, HookMethodType hookMethodType = HookMethodType.Before) + { + if (owner == null || methodInfo == null || hookMethod == null) throw new ArgumentNullException("All 'HookMethod' arguments must not be null."); + + var funcAddr = ((long)methodInfo.MethodHandle.GetFunctionPointer()); + var patches = Harmony.GetPatchInfo(methodInfo); + + if (hookMethodType == HookMethodType.Before) + { + if (patches == null || patches.Prefixes == null || patches.Prefixes.Find(patch => patch.PatchMethod == hookMethod.Method) == null) + { + GameMain.LuaCs.harmony.Patch(methodInfo, prefix: new HarmonyMethod(hookMethod.Method)); + } + + if (csHookPrefixMethods.TryGetValue(funcAddr, out HashSet<(IDisposable, CsPatchDelegate)> methodSet)) + { + methodSet.RemoveWhere(tuple => tuple.Item1 == owner); + if (hookMethod != null) + { + methodSet.Add((owner, hookMethod)); + } + } + else if (hookMethod != null) + { + csHookPrefixMethods.Add(funcAddr, new HashSet<(IDisposable, CsPatchDelegate)>() { (owner, hookMethod) }); + } + + } + else if (hookMethodType == HookMethodType.After) + { + if (patches == null || patches.Postfixes == null || patches.Postfixes.Find(patch => patch.PatchMethod == hookMethod.Method) == null) + { + GameMain.LuaCs.harmony.Patch(methodInfo, postfix: new HarmonyMethod(hookMethod.Method)); + } + + if (csHookPostfixMethods.TryGetValue(funcAddr, out HashSet<(IDisposable, CsPatchDelegate)> methodSet)) + { + methodSet.RemoveWhere(tuple => tuple.Item1 == owner); + if (hookMethod != null) + { + methodSet.Add((owner, hookMethod)); + } + } + else if (hookMethod != null) + { + csHookPostfixMethods.Add(funcAddr, new HashSet<(IDisposable, CsPatchDelegate)>() { (owner, hookMethod) }); + } + + } + + } + + + public void EnqueueFunction(object function, params object[] args) + { + queuedFunctionCalls.Enqueue(new Tuple(0, function, args)); + } + + public void EnqueueTimedFunction(float time, object function, params object[] args) + { + queuedFunctionCalls.Enqueue(new Tuple(time, function, args)); + } + + + public void Add(string name, string hookName, object function) + { + if (name == null || hookName == null || function == null) return; + + name = name.ToLower(); + + if (!luaHookFunctions.ContainsKey(name)) + luaHookFunctions.Add(name, new Dictionary()); + + luaHookFunctions[name][hookName] = new LuaHookFunction(name, hookName, function); + } + + public void Remove(string name, string hookName) + { + if (name == null || hookName == null) return; + + name = name.ToLower(); + + if (!luaHookFunctions.ContainsKey(name)) + return; + + if (luaHookFunctions[name].ContainsKey(hookName)) + luaHookFunctions[name].Remove(hookName); + } + + public void Add(string name, CsHookDelegate hook, IDisposable owner = null) + { + if (name == null || hook == null) throw new ArgumentNullException("Name and Hook must not be null"); + + if (!csHookFunctions.ContainsKey(name)) + csHookFunctions.Add(name, new Dictionary()); + + csHookFunctions[name][hook] = owner; + } + + public void Remove(string name, CsHookDelegate hook) + { + if (name == null || hook == null) throw new ArgumentNullException("All arguments must not be null"); + + if (!csHookFunctions.ContainsKey(name)) + return; + + if (csHookFunctions[name].ContainsKey(hook)) + csHookFunctions[name].Remove(hook); + } + + + public void Update() + { + try + { + if (queuedFunctionCalls.TryPeek(out Tuple result)) + { + if (Timing.TotalTime >= result.Item1) + { + GameMain.LuaCs.CallFunction(result.Item2, result.Item3); + + queuedFunctionCalls.Dequeue(); + } + } + } + catch (Exception ex) + { + GameMain.LuaCs.HandleLuaException(ex, $"queuedFunctionCalls was {queuedFunctionCalls}"); + } + } + + public object Call(string name, params object[] args) + { +#if CLIENT + if (GameMain.GameSession?.IsRunning == false && GameMain.IsSingleplayer) + return null; +#endif + if (GameMain.LuaCs == null) return null; + if (name == null) return null; + if (args == null) { args = new object[] { }; } + + name = name.ToLower(); + + if (!luaHookFunctions.ContainsKey(name)) + return null; + + object lastResult = null; + + 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.HandleLuaException(e, $"Error in Hook '{name}'->'{hf.hookName}', with args '{argsSb}'"); + } + } + + return lastResult; + } + } +} \ No newline at end of file diff --git a/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaSetup.cs b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/LuaCsSetup.cs similarity index 76% rename from Barotrauma/BarotraumaShared/SharedSource/Lua/LuaSetup.cs rename to Barotrauma/BarotraumaShared/SharedSource/LuaCs/LuaCsSetup.cs index ee3f8a685..be286db38 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Lua/LuaSetup.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/LuaCs/LuaCsSetup.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Text; using System.IO; @@ -8,22 +8,26 @@ using Microsoft.Xna.Framework; using MoonSharp.Interpreter.Interop; using System.IO.Compression; using HarmonyLib; +using static Barotrauma.LuaCsSetup; +using System.Runtime.CompilerServices; +[assembly: InternalsVisibleTo("NetScriptAssembly", AllInternalsVisible = true)] namespace Barotrauma { - partial class LuaSetup + partial class LuaCsSetup { public const string LUASETUP_FILE = "Lua/LuaSetup.lua"; public const string VERSION_FILE = "luacsversion.txt"; public Script lua; - public LuaHook hook; + public LuaCsHook hook; public LuaGame game; public LuaNetworking networking; public Harmony harmony; public LuaScriptLoader luaScriptLoader; + public NetScriptLoader netScriptLoader; public static ContentPackage GetPackage() { @@ -64,9 +68,9 @@ namespace Barotrauma } } - public void PrintError(object message) - { - if (message == null) { message = "nil"; } + private static void PrintErrorBase(string prefix, object message, string empty) + { + if (message == null) { message = empty; } string str = message.ToString(); for (int i = 0; i < str.Length; i += 1024) @@ -74,12 +78,7 @@ namespace Barotrauma string subStr = str.Substring(i, Math.Min(1024, str.Length - i)); string errorMsg = subStr; - if (i == 0) -#if SERVER - errorMsg = "[SV LUA ERROR] " + errorMsg; -#else - errorMsg = "[CL LUA ERROR] " + errorMsg; -#endif + if (i == 0) errorMsg = prefix + errorMsg; DebugConsole.ThrowError(errorMsg); @@ -97,9 +96,17 @@ namespace Barotrauma } } - public void PrintMessage(object message) - { - if (message == null) { message = "nil"; } +#if SERVER + private void PrintError(object message) => PrintErrorBase("[SV LUA ERROR] ", message, "nil"); + public static void PrintCsError(object message) => PrintErrorBase("[SV CS ERROR] ", message, "Null"); +#else + private void PrintError(object message) => PrintErrorBase("[CL LUA ERROR] ", message, "nil"); + public static void PrintCsError(object message) => PrintErrorBase("[CL CS ERROR] ", message, "Null"); +#endif + + private static void PrintMessageBase(string prefix, object message, string empty) + { + if (message == null) { message = empty; } string str = message.ToString(); for (int i = 0; i < str.Length; i += 1024) @@ -115,7 +122,7 @@ namespace Barotrauma GameMain.Server.SendDirectChatMessage(ChatMessage.Create("", subStr, ChatMessageType.Console, null, textColor: Color.MediumPurple), c); } - GameServer.Log("[LUA] " + subStr, ServerLog.MessageType.ServerMessage); + GameServer.Log(prefix + subStr, ServerLog.MessageType.ServerMessage); } #endif } @@ -126,6 +133,8 @@ namespace Barotrauma DebugConsole.NewMessage(message.ToString(), Color.Purple); #endif } + private void PrintMessage(object message) => PrintMessageBase("[LUA] ", message, "nil"); + public static void PrintCsMessage(object message) => PrintMessageBase("[CS] ", message, "Null"); public DynValue DoString(string code, Table globalContext = null, string codeStringFriendly = null) { @@ -242,25 +251,44 @@ namespace Barotrauma public void Stop() { - harmony?.UnpatchAll(); + ANetMod.LoadedMods.ForEach(m => m.Dispose()); + ANetMod.LoadedMods.Clear(); + hook?.Call("stop"); game?.Stop(); - hook?.Call("stop", new object[] { }); + harmony?.UnpatchAll(); - hook = new LuaHook(); + hook = new LuaCsHook(); game = new LuaGame(); networking = new LuaNetworking(); luaScriptLoader = null; } + private void InitCs() + { + netScriptLoader = new NetScriptLoader(this); + netScriptLoader.SearchFolders(); + if (netScriptLoader == null) throw new Exception("LuaCsSetup was not properly initialized."); + try + { + var modTypes = netScriptLoader.Compile(); + modTypes.ForEach(t => t.GetConstructor(new Type[] { }).Invoke(null)); + } + catch (Exception ex) + { + PrintMessage(ex); + } + } + public void Initialize() { Stop(); - PrintMessage("Lua! Version " + AssemblyInfo.GitRevision); + PrintMessage("LuaCs! Version " + AssemblyInfo.GitRevision); luaScriptLoader = new LuaScriptLoader(); luaScriptLoader.ModulePaths = new string[] { }; + InitCs(); LuaCustomConverters.RegisterAll(); @@ -271,11 +299,11 @@ namespace Barotrauma harmony = new Harmony("com.LuaForBarotrauma"); harmony.UnpatchAll(); - hook = new LuaHook(); + hook = new LuaCsHook(); game = new LuaGame(); networking = new LuaNetworking(); - UserData.RegisterType(); + UserData.RegisterType(); UserData.RegisterType(); UserData.RegisterType(); UserData.RegisterType(); @@ -333,7 +361,7 @@ namespace Barotrauma try { - string luaPath = Path.Combine(path, "Binary/Lua/LuaSetup.lua"); + string luaPath = Path.Combine(path, "Binary/LuaCs/LuaCsSetup.lua"); lua.Call(lua.LoadFile(luaPath), Path.GetDirectoryName(luaPath)); } catch (Exception e) @@ -343,13 +371,13 @@ namespace Barotrauma } else { - PrintError("Lua loader not found! Lua/LuaSetup.lua, no Lua scripts will be executed or work."); + PrintError("LuaCs loader not found! LuaCs/LuaCsSetup.lua, no LuaCs scripts will be executed or work."); } } - public LuaSetup() + public LuaCsSetup() { - hook = new LuaHook(); + hook = new LuaCsHook(); game = new LuaGame(); networking = new LuaNetworking(); } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Map/Gap.cs b/Barotrauma/BarotraumaShared/SharedSource/Map/Gap.cs index 9c074d472..4c2b6a060 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Map/Gap.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Map/Gap.cs @@ -660,7 +660,7 @@ namespace Barotrauma if (Math.Max(hull1.WorldSurface + hull1.WaveY[hull1.WaveY.Length - 1], hull2.WorldSurface + hull2.WaveY[0]) > WorldRect.Y) { return; } } - var should = new LuaResult(GameMain.Lua.hook.Call("gapOxygenUpdate", new object[] { this, hull1, hull2 })); + var should = new LuaResult(GameMain.LuaCs.hook.Call("gapOxygenUpdate", this, hull1, hull2)); if (should.Bool()) return; diff --git a/Barotrauma/BarotraumaShared/SharedSource/Map/MapEntity.cs b/Barotrauma/BarotraumaShared/SharedSource/Map/MapEntity.cs index 1f3865f60..a03be0e13 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Map/MapEntity.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Map/MapEntity.cs @@ -596,12 +596,12 @@ namespace Barotrauma Powered.UpdatePower(deltaTime * MapEntityUpdateInterval); foreach (Item item in Item.ItemList) { - if (GameMain.Lua.game.updatePriorityItems.Contains(item)) continue; + if (GameMain.LuaCs.game.updatePriorityItems.Contains(item)) continue; item.Update(deltaTime * MapEntityUpdateInterval, cam); } } - foreach (var item in GameMain.Lua.game.updatePriorityItems) + foreach (var item in GameMain.LuaCs.game.updatePriorityItems) { if (item.Removed) continue; diff --git a/Barotrauma/BarotraumaShared/SharedSource/Net/NetHook.cs b/Barotrauma/BarotraumaShared/SharedSource/Net/NetHook.cs deleted file mode 100644 index 76102723c..000000000 --- a/Barotrauma/BarotraumaShared/SharedSource/Net/NetHook.cs +++ /dev/null @@ -1,255 +0,0 @@ -using System; -using System.Linq; -using System.Reflection; -using MoonSharp.Interpreter; -using HarmonyLib; -using System.Collections.Generic; -using System.Text; - -namespace Barotrauma -{ - using NetHookMethod = Func; - using HookMethod = Func, object>; - - partial class NetHook - { - public NetHook() - { - _hookPrefixMethods = new Dictionary>>(); - _hookPostfixMethods = new Dictionary>>(); - } - - private Dictionary> hookFunctions = new Dictionary>(); - - private static Dictionary>> _hookPrefixMethods; - private static Dictionary>> _hookPostfixMethods; - - private Queue> queuedFunctionCalls = new Queue>(); - - public enum HookMethodType - { - Before, After - } - - static void _hookNetPatch(MethodBase __originalMethod, object[] __args, object __instance, out object result, HookMethodType hookMethodType) - { - result = null; - -#if CLIENT - if (GameMain.GameSession?.IsRunning == false && GameMain.IsSingleplayer) - return; -#endif - - try - { - var funcAddr = ((long)__originalMethod.MethodHandle.GetFunctionPointer()); - HashSet> methodSet = null; - switch (hookMethodType) - { - case HookMethodType.Before: - _hookPrefixMethods.TryGetValue(funcAddr, out methodSet); - break; - case HookMethodType.After: - _hookPostfixMethods.TryGetValue(funcAddr, out methodSet); - break; - default: - break; - } - - if (methodSet != null) - { - var @params = __originalMethod.GetParameters(); - var ptable = new Dictionary(); - for (int i = 0; i < @params.Length; i++) - { - ptable.Add(@params[i].Name, __args[i]); - } - - foreach (var tuple in methodSet) - { - result = tuple.Item2(__instance, ptable); - } - } - } - catch (Exception ex) - { - GameMain.Net.HandleException(ex, null); - } - } - - private const BindingFlags DefaultBindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; - public void HookMethod(string identifier, MethodInfo methodInfo, HookMethod hookMethod, HookMethodType hookMethodType = HookMethodType.Before) - { - if (identifier == null || methodInfo == null || methodInfo == null) throw new ArgumentNullException("All 'HookMethod' arguments must not be null."); - - 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 == hookMethod.Method) == null) - { - GameMain.Net.harmony.Patch(methodInfo, prefix: new HarmonyMethod(hookMethod.Method)); - } - } - else - { - if (patches == null || patches.Prefixes == null || patches.Prefixes.Find(patch => patch.PatchMethod == hookMethod.Method) == null) - { - GameMain.Net.harmony.Patch(methodInfo, prefix: new HarmonyMethod(hookMethod.Method)); - } - } - - if (_hookPrefixMethods.TryGetValue(funcAddr, out HashSet> methodSet)) - { - if (identifier != "") - { - methodSet.RemoveWhere(tuple => tuple.Item1 == identifier); - } - if (hookMethod != null) - { - methodSet.Add(Tuple.Create(identifier, hookMethod)); - } - } - else if (hookMethod != null) - { - _hookPrefixMethods.Add(funcAddr, new HashSet>() { Tuple.Create(identifier, hookMethod) }); - } - - } - else if (hookMethodType == HookMethodType.After) - { - if (methodInfo.ReturnType == typeof(void)) - { - if (patches == null || patches.Postfixes == null || patches.Postfixes.Find(patch => patch.PatchMethod == hookMethod.Method) == null) - { - GameMain.Net.harmony.Patch(methodInfo, postfix: new HarmonyMethod(hookMethod.Method)); - } - } - else - { - if (patches == null || patches.Postfixes == null || patches.Postfixes.Find(patch => patch.PatchMethod == hookMethod.Method) == null) - { - GameMain.Net.harmony.Patch(methodInfo, postfix: new HarmonyMethod(hookMethod.Method)); - } - } - - if (_hookPostfixMethods.TryGetValue(funcAddr, out HashSet> methodSet)) - { - if (identifier != "") - { - methodSet.RemoveWhere(tuple => tuple.Item1 == identifier); - } - if (hookMethod != null) - { - methodSet.Add(Tuple.Create(identifier, hookMethod)); - } - } - else if (hookMethod != null) - { - _hookPostfixMethods.Add(funcAddr, new HashSet>() { Tuple.Create(identifier, hookMethod) }); - } - - } - - } - - public void EnqueueFunction(NetHookMethod function, params object[] args) - { - queuedFunctionCalls.Enqueue(new Tuple(0, function, args)); - } - - public void EnqueueTimedFunction(float time, NetHookMethod function, params object[] args) - { - queuedFunctionCalls.Enqueue(new Tuple(time, function, args)); - } - - public void Add(string name, NetHookMethod hook) - { - if (name == null || hook == null) throw new ArgumentNullException("Name and Action cannot be null"); - - name = name.ToLower(); - - if (!hookFunctions.ContainsKey(name)) - hookFunctions.Add(name, new List()); - - hookFunctions[name].Add(hook); - } - - public void Remove(string name, NetHookMethod hook) - { - if (name == null || hook == null) throw new ArgumentNullException("Name and Action cannot be null"); - - name = name.ToLower(); - - if (!hookFunctions.ContainsKey(name)) - return; - - if (hookFunctions[name].Contains(hook)) - hookFunctions[name].Remove(hook); - } - - public void Update() - { - try - { - if (queuedFunctionCalls.TryPeek(out Tuple result)) - { - if (Timing.TotalTime >= result.Item1) - { - result.Item2(result.Item3); - - queuedFunctionCalls.Dequeue(); - } - } - } - catch (Exception ex) - { - GameMain.Net.HandleException(ex, $"queuedFunctionCalls was {queuedFunctionCalls}"); - } - } - - public object Call(string name, params object[] args) - { -#if CLIENT - if (GameMain.GameSession?.IsRunning == false && GameMain.IsSingleplayer) - return null; -#endif - if (GameMain.Net == null) return null; - if (name == null) return null; - if (args == null) { args = new object[] { }; } - - name = name.ToLower(); - - if (!hookFunctions.ContainsKey(name)) - return null; - - object lastResult = null; - - foreach (var hook in hookFunctions[name]) - { - try - { - var result = hook(args); - if (!(result == null)) - lastResult = result; - } - catch (Exception e) - { - StringBuilder argsSb = new StringBuilder(); - foreach (var arg in args) - { - argsSb.Append(arg + " "); - } - - GameMain.Net.HandleException(e, $"Error in Hook '{name}'->'{hook}', with args '{argsSb}'\n{Environment.StackTrace}"); - } - } - - return lastResult; - } - } -} \ No newline at end of file diff --git a/Barotrauma/BarotraumaShared/SharedSource/Net/NetScriptLoader.cs b/Barotrauma/BarotraumaShared/SharedSource/Net/NetScriptLoader.cs index c40758309..c4cc9c872 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Net/NetScriptLoader.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Net/NetScriptLoader.cs @@ -13,150 +13,147 @@ using static NetScript; namespace Barotrauma { - partial class NetSetup + + class NetScriptLoader : AssemblyLoadContext { + public LuaCsSetup setup; + private List defaultReferences; + private List syntaxTrees; + public Assembly Assembly { get; private set; } - public class NetScriptLoader : AssemblyLoadContext + public NetScriptLoader(LuaCsSetup setup) { - public NetSetup net; - private List defaultReferences; - private List syntaxTrees; - public Assembly Assembly { get; private set; } + this.setup = setup; - public NetScriptLoader(NetSetup net) - { - this.net = net; - - defaultReferences = AppDomain.CurrentDomain.GetAssemblies() - .Where(a => !(a.IsDynamic || string.IsNullOrEmpty(a.Location) || a.Location.Contains("xunit"))) - .Select(a => MetadataReference.CreateFromFile(a.Location) as MetadataReference) - .ToList(); - - syntaxTrees = new List(); - Assembly = null; - } - - public void SearchFolders() - { - foreach(ContentPackage cp in GameMain.Config.AllEnabledPackages) - { - var path = Path.GetDirectoryName(cp.Path); - RunFolder(path); - } - } - - public void RunFolder(string folder) - { - var scriptFiles = new List(); - foreach (var str in DirSearch(folder)) - { - var s = str.Replace("\\", "/"); - - if (s.EndsWith(".cs")) - { - NetSetup.PrintMessage(s); - scriptFiles.Add(s); - } - } - - try - { - 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 - foreach (var file in scriptFiles) - { - var tree = SyntaxFactory.ParseSyntaxTree(File.ReadAllText(file), CSharpParseOptions.Default, file); - var error = NetScriptFilter.FilterSyntaxTree(tree as CSharpSyntaxTree); - if (error != null) throw new Exception(error); - - syntaxTrees.Add(tree); - } - } - catch (CompilationErrorException ex) - { - string errStr = "Cmopilation Error in '" + folder + "':"; - foreach (var diag in ex.Diagnostics) - { - errStr += "\n" + diag.ToString(); - } - NetSetup.PrintMessage(errStr); - } - catch (Exception ex) - { - NetSetup.PrintMessage("Error loading '" + folder + "':\n" + ex.Message + "\n" + ex.StackTrace); - } - } - - public List Compile() - { - var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) - .WithMetadataImportOptions(MetadataImportOptions.All) - .WithOptimizationLevel(OptimizationLevel.Release) - .WithAllowUnsafe(false); - var compilation = CSharpCompilation.Create("NetScriptAssembly",syntaxTrees, defaultReferences, options); - - using (var mem = new MemoryStream()) - { - var result = compilation.Emit(mem); - if (!result.Success) - { - IEnumerable failures = result.Diagnostics.Where(d => d.IsWarningAsError || d.Severity == DiagnosticSeverity.Error); - - string errStr = "NET MODS NOT LOADED | Mod cmopilation errors:"; - foreach (Diagnostic diagnostic in failures) - errStr = $"\n{diagnostic}"; - NetSetup.PrintMessage(errStr); - } - else - { - mem.Seek(0, SeekOrigin.Begin); - var errStr = NetScriptFilter.FilterMetadata(new PEReader(mem).GetMetadataReader()); - if (errStr == null) - { - mem.Seek(0, SeekOrigin.Begin); - Assembly = LoadFromStream(mem); - } - else NetSetup.PrintMessage(errStr); - } - } - syntaxTrees.Clear(); - - if (Assembly != null) - return Assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(ANetMod))).ToList(); - else - throw new Exception("Unable to create net mods assembly."); - } - - static string[] DirSearch(string sDir) - { - List files = new List(); - - try - { - foreach (string f in Directory.GetFiles(sDir)) - { - files.Add(f); - } - - foreach (string d in Directory.GetDirectories(sDir)) - { - files.AddRange(DirSearch(d)); - } - } - catch (System.Exception excpt) - { - Console.WriteLine(excpt.Message); - } - - return files.ToArray(); - } + defaultReferences = AppDomain.CurrentDomain.GetAssemblies() + .Where(a => !(a.IsDynamic || string.IsNullOrEmpty(a.Location) || a.Location.Contains("xunit"))) + .Select(a => MetadataReference.CreateFromFile(a.Location) as MetadataReference) + .ToList(); + syntaxTrees = new List(); + Assembly = null; } + + public void SearchFolders() + { + foreach(ContentPackage cp in ContentPackageManager.EnabledPackages.All) + { + var path = Path.GetDirectoryName(cp.Path); + RunFolder(path); + } + } + + private void RunFolder(string folder) + { + var scriptFiles = new List(); + foreach (var str in DirSearch(folder)) + { + var s = str.Replace("\\", "/"); + + if (s.EndsWith(".cs")) + { + LuaCsSetup.PrintCsMessage(s); + scriptFiles.Add(s); + } + } + + try + { + 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 + foreach (var file in scriptFiles) + { + var tree = SyntaxFactory.ParseSyntaxTree(File.ReadAllText(file), CSharpParseOptions.Default, file); + var error = NetScriptFilter.FilterSyntaxTree(tree as CSharpSyntaxTree); + if (error != null) throw new Exception(error); + + syntaxTrees.Add(tree); + } + } + catch (CompilationErrorException ex) + { + string errStr = "Cmopilation Error in '" + folder + "':"; + foreach (var diag in ex.Diagnostics) + { + errStr += "\n" + diag.ToString(); + } + LuaCsSetup.PrintCsMessage(errStr); + } + catch (Exception ex) + { + LuaCsSetup.PrintCsMessage("Error loading '" + folder + "':\n" + ex.Message + "\n" + ex.StackTrace); + } + } + + public List Compile() + { + var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) + .WithMetadataImportOptions(MetadataImportOptions.All) + .WithOptimizationLevel(OptimizationLevel.Release) + .WithAllowUnsafe(false); + var compilation = CSharpCompilation.Create("NetScriptAssembly",syntaxTrees, defaultReferences, options); + + using (var mem = new MemoryStream()) + { + var result = compilation.Emit(mem); + if (!result.Success) + { + IEnumerable failures = result.Diagnostics.Where(d => d.IsWarningAsError || d.Severity == DiagnosticSeverity.Error); + + string errStr = "NET MODS NOT LOADED | Mod cmopilation errors:"; + foreach (Diagnostic diagnostic in failures) + errStr = $"\n{diagnostic}"; + LuaCsSetup.PrintCsMessage(errStr); + } + else + { + mem.Seek(0, SeekOrigin.Begin); + var errStr = NetScriptFilter.FilterMetadata(new PEReader(mem).GetMetadataReader()); + if (errStr == null) + { + mem.Seek(0, SeekOrigin.Begin); + Assembly = LoadFromStream(mem); + } + else LuaCsSetup.PrintCsMessage(errStr); + } + } + syntaxTrees.Clear(); + + if (Assembly != null) + return Assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(ANetMod))).ToList(); + else + throw new Exception("Unable to create net mods assembly."); + } + + private static string[] DirSearch(string sDir) + { + List files = new List(); + + try + { + foreach (string f in Directory.GetFiles(sDir)) + { + files.Add(f); + } + + foreach (string d in Directory.GetDirectories(sDir)) + { + files.AddRange(DirSearch(d)); + } + } + catch (System.Exception excpt) + { + Console.WriteLine(excpt.Message); + } + + return files.ToArray(); + } + } } \ No newline at end of file diff --git a/Barotrauma/BarotraumaShared/SharedSource/Net/NetSetup.cs b/Barotrauma/BarotraumaShared/SharedSource/Net/NetSetup.cs deleted file mode 100644 index 294bf31eb..000000000 --- a/Barotrauma/BarotraumaShared/SharedSource/Net/NetSetup.cs +++ /dev/null @@ -1,102 +0,0 @@ -using System; -using Barotrauma.Networking; -using Microsoft.Xna.Framework; -using HarmonyLib; -using System.Runtime.CompilerServices; -//using System.Linq; -//using System.Collections.Generic; -//using Microsoft.CodeAnalysis; -//using Microsoft.CodeAnalysis.CSharp; - -[assembly: InternalsVisibleTo("NetScriptAssembly", AllInternalsVisible = true)] - -namespace Barotrauma -{ - partial class NetSetup : IDisposable - { - public NetScriptLoader Loader { get; private set; } - public Harmony harmony; - public LuaHook hook; - public NetSetup() => Initialize(); - public void Dispose() => Stop(); - - public void Reload() - { - Stop(); - Initialize(); - Execute(); - } - public void Initialize() - { - hook = new LuaHook(); - Loader = new NetScriptLoader(this); - Loader.SearchFolders(); - } - public void Execute() - { - if (Loader == null) throw new Exception("NetSetup was not properly initialized."); - try - { - var modTypes = Loader.Compile(); - modTypes.ForEach(t => t.GetConstructor(new Type[] { }).Invoke(null)); - } - catch (Exception ex) - { - PrintMessage(ex); - } - } - public void Stop() - { - ANetMod.LoadedMods.ForEach(m => m.Dispose()); - ANetMod.LoadedMods.Clear(); - Loader.Unload(); - - harmony?.UnpatchAll(); - hook?.Call("stop", new object[] { }); - - hook = null; - Loader = null; - } - - public void Update() - { - hook?.Update(); - ANetMod.LoadedMods.ForEach(m => m.Update()); - } - - public static void PrintMessage(object message) - { - if (message == null) { message = "null"; } - string str = message.ToString(); - -#if SERVER - if (GameMain.Server != null) - { - for (int i = 0; i < str.Length; i += 1024) - { - string subStr = str.Substring(i, Math.Min(1024, str.Length - i)); - - - foreach (var c in GameMain.Server.ConnectedClients) - { - GameMain.Server.SendDirectChatMessage(ChatMessage.Create("", subStr, ChatMessageType.Console, null, textColor: Color.MediumPurple), c); - } - - GameServer.Log("[NET] " + subStr, ServerLog.MessageType.ServerMessage); - } - } - else - { - DebugConsole.NewMessage("[NET]" + message.ToString(), Color.MediumPurple); - } -#else - DebugConsole.NewMessage(message.ToString(), Color.Purple); -#endif - } - - public void HandleException(Exception ex, string? info) - { - throw new NotImplementedException(); - } - } -} \ No newline at end of file diff --git a/Barotrauma/BarotraumaShared/SharedSource/Networking/RespawnManager.cs b/Barotrauma/BarotraumaShared/SharedSource/Networking/RespawnManager.cs index 30796abf8..91db5ad38 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Networking/RespawnManager.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Networking/RespawnManager.cs @@ -117,7 +117,7 @@ namespace Barotrauma.Networking foreach (Wire wire in connection.Wires) { #if SERVER - if (GameMain.Lua.game.overrideRespawnSub == false) + if (GameMain.LuaCs.game.overrideRespawnSub == false) { if (wire != null) wire.Locked = true; } @@ -205,7 +205,7 @@ namespace Barotrauma.Networking { #if SERVER - if (GameMain.Lua.game.overrideRespawnSub) + if (GameMain.LuaCs.game.overrideRespawnSub) { yield return CoroutineStatus.Success; } diff --git a/Barotrauma/BarotraumaShared/SharedSource/StatusEffects/StatusEffect.cs b/Barotrauma/BarotraumaShared/SharedSource/StatusEffects/StatusEffect.cs index bf22d5577..f95c79ef3 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/StatusEffects/StatusEffect.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/StatusEffects/StatusEffect.cs @@ -1201,7 +1201,7 @@ namespace Barotrauma { if (entity is Item item) { - var result = new LuaResult(GameMain.Lua.hook.Call("statusEffect.apply." + item.Prefab.Identifier, this, deltaTime, entity, targets, worldPosition)); + var result = new LuaResult(GameMain.LuaCs.hook.Call("statusEffect.apply." + item.Prefab.Identifier, this, deltaTime, entity, targets, worldPosition)); if (result.Bool()) return; @@ -1209,7 +1209,7 @@ namespace Barotrauma if (entity is Character character) { - var result = new LuaResult(GameMain.Lua.hook.Call("statusEffect.apply." + character.SpeciesName, this, deltaTime, entity, targets, worldPosition)); + var result = new LuaResult(GameMain.LuaCs.hook.Call("statusEffect.apply." + character.SpeciesName, this, deltaTime, entity, targets, worldPosition)); if (result.Bool()) return; @@ -1218,7 +1218,7 @@ namespace Barotrauma foreach (string luaHooks in luaHook) { - var result = new LuaResult(GameMain.Lua.hook.Call(luaHooks, this, deltaTime, entity, targets, worldPosition)); + var result = new LuaResult(GameMain.LuaCs.hook.Call(luaHooks, this, deltaTime, entity, targets, worldPosition)); if (result.Bool()) return;