3 using MoonSharp.Interpreter;
4 using MoonSharp.Interpreter.Interop;
5 using System.Runtime.CompilerServices;
7 using System.Threading;
8 using LuaCsCompatPatchFunc =
Barotrauma.LuaCsPatch;
9 using System.Diagnostics;
10 using MoonSharp.VsCodeDebugger;
12 using System.Runtime.Loader;
13 using System.Xml.Linq;
40 internal delegate
void LuaCsMessageLogger(
string message);
41 internal delegate
void LuaCsErrorHandler(Exception ex, LuaCsMessageOrigin origin);
42 internal delegate
void LuaCsExceptionHandler(Exception ex, LuaCsMessageOrigin origin);
44 partial class LuaCsSetup
59 private const string configFileName =
"LuaCsSetupConfig.xml";
74 return Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) == Directory.GetCurrentDirectory();
81 private static int executionNumber = 0;
84 public Script
Lua {
get;
private set; }
104 public MoonSharpVsCodeDebugServer
DebugServer {
get;
private set; }
107 private bool ShouldRunCs
133 [Obsolete(
"Use AssemblyManager::GetTypesByName()")]
134 public static Type
GetType(
string typeName,
bool throwOnError =
false,
bool ignoreCase =
false)
161 if (s.Name.StartsWith(
"LocalMods") || s.Name.StartsWith(
"Lua"))
163 return Environment.CurrentDirectory +
"/" + s.Name;
175 if (File.Exists(configFileName))
179 using (var file = File.Open(configFileName, FileMode.Open, FileAccess.Read))
181 XDocument document = XDocument.Load(file);
198 XDocument document =
new XDocument();
199 document.Add(
new XElement(
"LuaCsSetupConfig"));
206 document.Save(configFileName);
211 foreach (
ContentPackage package
in ContentPackageManager.EnabledPackages.All)
213 if (package.
UgcId.ValueEquals(
id))
221 foreach (
ContentPackage package
in ContentPackageManager.LocalPackages)
223 if (package.
UgcId.ValueEquals(
id))
229 foreach (
ContentPackage package
in ContentPackageManager.AllPackages)
231 if (package.
UgcId.ValueEquals(
id))
238 if (useBackup && ContentPackageManager.EnabledPackages.BackupPackages.Regular !=
null)
240 foreach (
ContentPackage package
in ContentPackageManager.EnabledPackages.BackupPackages.Regular.Value)
242 if (package.
UgcId.ValueEquals(
id))
252 private DynValue DoFile(
string file, Table globalContext =
null,
string codeStringFriendly =
null)
256 throw new ScriptRuntimeException($
"dofile: File access to {file} not allowed.");
259 if (!LuaCsFile.Exists(file))
261 throw new ScriptRuntimeException($
"dofile: File {file} not found.");
264 return Lua.DoFile(file, globalContext, codeStringFriendly);
267 private DynValue LoadFile(
string file, Table globalContext =
null,
string codeStringFriendly =
null)
269 if (!LuaCsFile.CanReadFromPath(file))
271 throw new ScriptRuntimeException($
"loadfile: File access to {file} not allowed.");
274 if (!LuaCsFile.Exists(file))
276 throw new ScriptRuntimeException($
"loadfile: File {file} not found.");
279 return Lua.LoadFile(file, globalContext, codeStringFriendly);
286 if (
Lua ==
null) {
return null; }
292 return Lua.Call(
function, args);
302 private void SetModulePaths(
string[] str)
313 Stopwatch luaSw =
new Stopwatch();
319 GameMain.PerformanceCounter.AddElapsedTicks(
"Think Hook", luaSw.ElapsedTicks);
329 acl => acl.AssembliesTypes.Select(kvp => kvp.Value)))
331 UserData.UnregisterType(type,
true);
334 if (
Lua?.Globals is not
null)
336 Lua.Globals.Remove(
"CsPackageManager");
337 Lua.Globals.Remove(
"AssemblyManager");
359 #pragma warning disable CS0618
361 #pragma warning restore CS0618
383 bool csActive = ShouldRunCs || forceEnableCs;
388 RegisterLuaConverters();
390 Lua =
new Script(CoreModules.Preset_SoftSandbox | CoreModules.Debug | CoreModules.IO | CoreModules.OS_System);
393 Lua.Options.CheckThreadAccess =
false;
394 Script.GlobalOptions.ShouldPCallCatchException = (Exception ex) => {
return true; };
412 UserData.RegisterType<LuaCsCompatPatchFunc>();
414 UserData.RegisterType<
LuaGame>();
421 UserData.RegisterType<IUserDataDescriptor>();
423 Lua.Globals[
"printerror"] = (DynValue o) => {
LuaCsLogger.
LogError(o.ToString(), LuaCsMessageOrigin.LuaMod); };
425 Lua.Globals[
"setmodulepaths"] = (Action<string[]>)SetModulePaths;
427 Lua.Globals[
"dofile"] = (Func<string, Table, string, DynValue>)DoFile;
428 Lua.Globals[
"loadfile"] = (Func<string, Table, string, DynValue>)LoadFile;
429 Lua.Globals[
"require"] = (Func<string, Table, DynValue>)require.
Require;
431 Lua.Globals[
"dostring"] = (Func<string, Table, string, DynValue>)
Lua.DoString;
432 Lua.Globals[
"load"] = (Func<string, Table, string, DynValue>)
Lua.LoadString;
435 Lua.Globals[
"LuaUserData"] = UserData.CreateStatic<
LuaUserData>();
440 Lua.Globals[
"File"] = UserData.CreateStatic<
LuaCsFile>();
446 Lua.Globals[
"ExecutionNumber"] = executionNumber;
447 Lua.Globals[
"CSActive"] = csActive;
470 Stopwatch taskTimer =
new();
475 if (state is AssemblyLoadingSuccessState.Success or AssemblyLoadingSuccessState.AlreadyLoaded)
483 state = AssemblyLoadingSuccessState.Success;
485 ModUtils.Logging.PrintMessage($
"{nameof(LuaCsSetup)}: Completed assembly loading. Total time {taskTimer.ElapsedMilliseconds}ms.");
492 if(state is not AssemblyLoadingSuccessState.Success)
494 ModUtils.Logging.PrintError($
"{nameof(LuaCsSetup)}: Error while loading Cs-Assembly Mods | Err: {state}");
500 ModUtils.Logging.PrintError($
"{nameof(LuaCsSetup)}::{nameof(Initialize)}() | Error while loading assemblies! Details: {e.Message} | {e.StackTrace}");
511 CallLuaFunction(
Lua.LoadFile(luaPath), Path.GetDirectoryName(Path.GetFullPath(luaPath)));
517 string luaPath = Path.Combine(Path.GetDirectoryName(luaPackage.
Path),
"Binary/Lua/LuaSetup.lua");
518 CallLuaFunction(
Lua.LoadFile(luaPath), Path.GetDirectoryName(Path.GetFullPath(luaPath)));
523 LuaCsLogger.
LogError(
"LuaSetup.lua not found! Lua/LuaSetup.lua, no Lua scripts will be executed or work.", LuaCsMessageOrigin.LuaMod);
528 if (luaPackage !=
null) { RunWorkshop(); }
535 else if (luaPackage !=
null) { RunWorkshop(); }
Provides functionality for the loading, unloading and management of plugins implementing IAssemblyPlu...
IEnumerable< Type > GetTypesByName(string typeName)
Allows iteration over all types, including interfaces, in all loaded assemblies in the AsmMgr who's n...
IEnumerable< LoadedACL > GetAllLoadedACLs()
Returns a list of all loaded ACLs. WARNING: References to these ACLs outside of the AssemblyManager s...
static List< ACsMod > LoadedMods
readonly Option< ContentPackageId > UgcId
static bool CanReadFromPath(string path)
object Call(string name, params object[] args)
static void LogError(string message, LuaCsMessageOrigin origin)
static void LogMessage(string message, Color? serverColor=null, Color? clientColor=null)
static bool HideUserNames
static void Log(string message, Color? color=null, ServerLog.MessageType messageType=ServerLog.MessageType.ServerMessage)
static void HandleException(Exception ex, LuaCsMessageOrigin origin)
bool TreatForcedModsAsNormal
bool DisableErrorGUIOverlay
bool PreferToUseWorkshopLuaSetup
LuaCsSetupConfig(LuaCsSetupConfig config)
static Type GetType(string typeName, bool throwOnError=false, bool ignoreCase=false)
void Initialize(bool forceEnableCs=false)
static AssemblyManager AssemblyManager
CsPackageManager PluginPackageManager
DynValue CallLuaFunction(object function, params object[] args)
LuaCsNetworking Networking
MoonSharpVsCodeDebugServer DebugServer
static ContentPackageId CsForBarotraumaId
void ToggleDebugger(int port=41912)
LuaCsPerformanceCounter PerformanceCounter
const string LuaSetupFile
static ContentPackage GetPackage(ContentPackageId id, bool fallbackToAll=true, bool useBackup=false)
static bool IsRunningInsideWorkshop
LuaScriptLoader LuaScriptLoader
DynValue Require(string moduleName, Table globalContext)
static IUserDataDescriptor RegisterType(string typeName)
void RunPluginsInit()
Executes instantiated plugins' Initialize() and OnLoadCompleted() methods.
void RunPluginsPreInit()
Executes instantiated plugins' PreInitPatching() method.
void InstantiatePlugins(bool force=false)
Initializes plugin types that are registered.
AssemblyLoadingSuccessState LoadAssemblyPackages()
Begins the loading process of scanning packages for scripts and binary assemblies,...
bool PluginsPreInit
Whether or not loaded plugins had their preloader run.
bool PluginsInitialized
Whether or not plugins' types have been instantiated.
bool PluginsLoaded
Whether or not plugins are fully loaded.
delegate void LuaCsAction(params object[] args)
delegate DynValue LuaCsPatchFunc(object instance, LuaCsHook.ParameterTable ptable)