From bbf8c6c14f5a3a3952e1b72198640ada4739db74 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Wed, 7 Oct 2026 23:30:14 +0100 Subject: [PATCH 01/23] Fix addons --- .vscode/launch.json | 16 ++++++++-------- Game.Shared/GarrysMod/GarrysMod.cs | 4 ++-- Game.Shared/GarrysMod/LuaGamemode.cs | 4 ++-- Source.Common/GarrysMod/LegacyAddons.cs | 2 +- Source.Filesystem/GarrysMod/GamemodeSystem.cs | 4 ++-- Source.Filesystem/GarrysMod/LegacyAddonSystem.cs | 14 +++++++++++--- 6 files changed, 26 insertions(+), 18 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 5cf1298cb..932170ee1 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -6,8 +6,8 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build Source.Launcher", - "program": "${workspaceFolder}/Build/Source.Launcher.dll", - "cwd": "${workspaceFolder}/Build", + "program": "${workspaceFolder}/Build/Debug/Source.Launcher.dll", + "cwd": "${workspaceFolder}/Build/Debug", "stopAtEntry": false }, { @@ -15,8 +15,8 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build Source.Launcher", - "program": "${workspaceFolder}/Build/Source.Launcher.dll", - "cwd": "${workspaceFolder}/Build", + "program": "${workspaceFolder}/Build/Debug/Source.Launcher.dll", + "cwd": "${workspaceFolder}/Build/Debug", "stopAtEntry": false, "console": "externalTerminal" }, @@ -25,8 +25,8 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build Source.Dedicated", - "program": "${workspaceFolder}/Build/Source.Dedicated.dll", - "cwd": "${workspaceFolder}/Build", + "program": "${workspaceFolder}/Build/Debug (Dedicated)/Source.Dedicated.dll", + "cwd": "${workspaceFolder}/Build/Debug (Dedicated)", "args": ["-maxplayers", "2", "+map", "gm_flatgrass"], "stopAtEntry": false }, @@ -35,8 +35,8 @@ "type": "coreclr", "request": "launch", "preLaunchTask": "build Source.Dedicated", - "program": "${workspaceFolder}/Build/Source.Dedicated.dll", - "cwd": "${workspaceFolder}/Build", + "program": "${workspaceFolder}/Build/Debug (Dedicated)/Source.Dedicated.dll", + "cwd": "${workspaceFolder}/Build/Debug (Dedicated)", "args": ["-maxplayers", "2", "+map", "gm_flatgrass"], "stopAtEntry": false, "console": "externalTerminal" diff --git a/Game.Shared/GarrysMod/GarrysMod.cs b/Game.Shared/GarrysMod/GarrysMod.cs index 383851168..dcd2dd6fe 100644 --- a/Game.Shared/GarrysMod/GarrysMod.cs +++ b/Game.Shared/GarrysMod/GarrysMod.cs @@ -224,8 +224,8 @@ public static bool Create() { foreach (ILegacyAddons.Information addon in filesystem.LegacyAddons().GetList()) { if (!string.IsNullOrEmpty(addon.LuaPath)) get.LuaShared()!.MountLuaAdd(addon.LuaPath, LuaPathID); - if (!string.IsNullOrEmpty(addon.Placeholder4)) - get.LuaShared()!.MountLuaAdd(addon.Placeholder4, LuaPathID); + if (!string.IsNullOrEmpty(addon.GamemodesPath)) + get.LuaShared()!.MountLuaAdd(addon.GamemodesPath, LuaPathID); } get.LuaShared()!.MountLuaAdd("workshop/lua", LuaPathID); get.LuaShared()!.MountLuaAdd("workshop/gamemodes", LuaPathID); diff --git a/Game.Shared/GarrysMod/LuaGamemode.cs b/Game.Shared/GarrysMod/LuaGamemode.cs index 07bfe5577..369783a29 100644 --- a/Game.Shared/GarrysMod/LuaGamemode.cs +++ b/Game.Shared/GarrysMod/LuaGamemode.cs @@ -57,8 +57,8 @@ public void LoadGamemode(string name, bool reload) { FileServ.AddCSLuaFile(name + "/gamemode/" + "cl_init.lua", "!GM"); #endif foreach (ILegacyAddons.Information addon in filesystem.LegacyAddons().GetList()) { - string path = addon.Placeholder4 + "/" + folder + "/entities"; - if (!string.IsNullOrEmpty(addon.Placeholder4) && filesystem.IsDirectory(path, "MOD")) + string path = addon.GamemodesPath + "/" + folder + "/entities"; + if (!string.IsNullOrEmpty(addon.GamemodesPath) && filesystem.IsDirectory(path, "MOD")) get.LuaShared()!.MountLuaAdd(path, Game.Client.GarrysMod.GarrysMod.LuaPathID); } get.LuaShared()!.MountLuaAdd("workshop/" + folder + "/entities", Game.Client.GarrysMod.GarrysMod.LuaPathID); diff --git a/Source.Common/GarrysMod/LegacyAddons.cs b/Source.Common/GarrysMod/LegacyAddons.cs index cd8caf836..ddeef9d32 100644 --- a/Source.Common/GarrysMod/LegacyAddons.cs +++ b/Source.Common/GarrysMod/LegacyAddons.cs @@ -7,7 +7,7 @@ public struct Information public string Name; public string Path; public string LuaPath; - public string Placeholder4; + public string GamemodesPath; } } diff --git a/Source.Filesystem/GarrysMod/GamemodeSystem.cs b/Source.Filesystem/GarrysMod/GamemodeSystem.cs index 0d990209e..7c8b3afd1 100644 --- a/Source.Filesystem/GarrysMod/GamemodeSystem.cs +++ b/Source.Filesystem/GarrysMod/GamemodeSystem.cs @@ -124,8 +124,8 @@ void Mount(ReadOnlySpan name) { Span fullPath = stackalloc char[MAX_PATH]; foreach (ILegacyAddons.Information addon in g_FullFileSystem.LegacyAddons().GetList()) { - string path = addon.Placeholder4 + "/" + gm.Name + "/content"; - if (!string.IsNullOrEmpty(addon.Placeholder4) && g_FullFileSystem.IsDirectory(path, "MOD")) { + string path = addon.GamemodesPath + "/" + gm.Name + "/content"; + if (!string.IsNullOrEmpty(addon.GamemodesPath) && g_FullFileSystem.IsDirectory(path, "MOD")) { ReadOnlySpan full = g_FullFileSystem.RelativePathToFullPath(path, "MOD", fullPath); if (!full.IsEmpty) { g_FullFileSystem.AddSearchPath(full, "GAME", SearchPathAdd.ToTail, PathGroupName.GMContent); diff --git a/Source.Filesystem/GarrysMod/LegacyAddonSystem.cs b/Source.Filesystem/GarrysMod/LegacyAddonSystem.cs index d9b4152e2..7b03254b0 100644 --- a/Source.Filesystem/GarrysMod/LegacyAddonSystem.cs +++ b/Source.Filesystem/GarrysMod/LegacyAddonSystem.cs @@ -32,11 +32,19 @@ public void Refresh() { g_FullFileSystem.AddSearchPath(fullpath.SliceNullTerminatedString(), "GAME", groupName: Common.Filesystem.PathGroupName.AddonContent); g_FullFileSystem.AddSearchPath(fullpath.SliceNullTerminatedString(), "thirdparty", groupName: Common.Filesystem.PathGroupName.AddonContent); + string full = new(fullpath.SliceNullTerminatedString()); + string luaPath = ""; + string gamemodesPath = ""; + if (g_FullFileSystem.IsDirectory(full + "/lua", null)) + luaPath = path.ToString() + "/lua"; + if (g_FullFileSystem.IsDirectory(full + "/gamemodes", null)) + gamemodesPath = path.ToString() + "/gamemodes"; + ILegacyAddons.Information information; information.Name = new(filename.SliceNullTerminatedString()); - information.Path = new(fullpath.SliceNullTerminatedString()); - information.LuaPath = new(path); - information.Placeholder4 = ""; // ToDo: Find out. + information.Path = full; + information.LuaPath = luaPath; + information.GamemodesPath = gamemodesPath; Addons.Add(information); } From 02a5cc5854e9dbd99bcbadb7ee9c1b8dffc4cd23 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Wed, 7 Oct 2026 23:37:37 +0100 Subject: [PATCH 02/23] CompileString/ProtectedCall --- Game.Shared/GarrysMod/LuaGlobalFunctions.cs | 42 +++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs index a50b32975..e676b7a02 100644 --- a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs +++ b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs @@ -138,6 +138,48 @@ static int include(ILuaInterface lua) { return g_Lua.Top() - top; } + [LuaGlobal] + static int CompileString(ILuaInterface lua) { + string code = g_Lua!.CheckString(1); + string identifier = g_Lua.CheckStringOpt(2, "CompileString"); + if (g_Lua.GetType(3) == LuaType.Nil) { + if (!g_Lua.RunStringEx(identifier, "", code, false, true, true, true)) + return 0; + } + else { + bool handleError = g_Lua.GetBool(3); + if (!g_Lua.RunStringEx(identifier, "", code, false, handleError, handleError, true) && handleError) + return 0; + } + return 1; + } + + [LuaGlobal] + static int ProtectedCall(ILuaInterface lua) { + LuaObject func = new(1, LuaType.None); + if (!func.isFunction()) { + g_Lua!.TypeError("function", 1); + func.UnReference(); + return 0; + } + + int top = g_Lua!.Top(); + List args = []; + for (int i = 2; i <= top; i++) + args.Add(new LuaObject(i, LuaType.None)); + + func.Push(); + foreach (LuaObject arg in args) + arg.Push(); + foreach (LuaObject arg in args) + arg.UnReference(); + args.Clear(); + + g_Lua.PushBool(g_Lua.CallFunctionProtected(top - 1, 0, true)); + func.UnReference(); + return 1; + } + [LuaGlobal] static int DeriveGamemode(ILuaInterface lua) { string name = g_Lua!.CheckString(1); From 1a8a621d7d9287055485068e7781df5e94cfdc78 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Thu, 8 Oct 2026 04:41:17 +0100 Subject: [PATCH 03/23] Fix GetSteamInf --- .vscode/tasks.json | 2 ++ Source.Common/SteamAppInfo.cs | 6 ++---- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 7639d02d7..16ff963ee 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -7,6 +7,7 @@ "type": "process", "args": [ "build", + "--no-restore", "${workspaceFolder}/Source.Launcher/Source.Launcher.csproj", "-p:WarningLevel=0" ], @@ -18,6 +19,7 @@ "type": "process", "args": [ "build", + "--no-restore", "${workspaceFolder}/Source.Dedicated/Source.Dedicated.csproj", "-p:WarningLevel=0", "-c", diff --git a/Source.Common/SteamAppInfo.cs b/Source.Common/SteamAppInfo.cs index fce8906a3..6e33d0c86 100644 --- a/Source.Common/SteamAppInfo.cs +++ b/Source.Common/SteamAppInfo.cs @@ -39,12 +39,10 @@ public static SteamAppInfo GetSteamInf(IFileSystem fileSystem) { switch (split[0].ToLower()) { case "patchversion": inf.PatchVersion = split[1]; break; case "productname": inf.ProductName = split[1]; break; - case "clientversion": inf.ServerVersion = int.TryParse(split[1], out int i1) ? i1 : 0; break; - case "serverversion": inf.ClientVersion = int.TryParse(split[1], out int i2) ? i2 : 0; break; + case "clientversion": inf.ClientVersion = int.TryParse(split[1], out int i1) ? i1 : 0; break; + case "serverversion": inf.ServerVersion = int.TryParse(split[1], out int i2) ? i2 : 0; break; case "appid": inf.AppID = int.TryParse(split[1], out int i3) ? i3 : 0; break; } - - return inf; } return inf; } From 44ca3a4ea616026b0b5a9ae59e1f967158e82653 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Thu, 8 Oct 2026 06:04:44 +0100 Subject: [PATCH 04/23] More lua/workshop impl --- Game.Client/ClientRenderTargets.cs | 63 +++++++ Game.Client/GarrysMod/LuaMaterial.cs | 112 +++++++++++- Game.Client/GarrysMod/LuaRender.cs | 172 +++++++++++++++++- Game.Client/GarrysMod/LuaVGUI.cs | 17 +- Game.Client/HLClient.cs | 1 + Game.Client/RenderTexture.cs | 89 +++++++++ Game.Lua/LuaSharedImpl.cs | 8 +- Game.Server/World.cs | 30 ++- Game.Shared/GarrysMod/LuaGame.cs | 28 +++ Game.Shared/GarrysMod/LuaPlayer.cs | 7 + Game.Shared/GarrysMod/LuaUtil.cs | 13 ++ Source.Common/Filesystem/IFileSystem.cs | 2 +- Source.Filesystem/BaseFileSystem.cs | 69 +++++-- Source.Filesystem/DiskSearchPath.cs | 20 +- .../GarrysMod/AddonFileSystem.cs | 7 + Source.MaterialSystem/MaterialSystem.cs | 10 +- Source.MaterialSystem/Texture.cs | 2 + 17 files changed, 614 insertions(+), 36 deletions(-) create mode 100644 Game.Client/ClientRenderTargets.cs diff --git a/Game.Client/ClientRenderTargets.cs b/Game.Client/ClientRenderTargets.cs new file mode 100644 index 000000000..1aca752e3 --- /dev/null +++ b/Game.Client/ClientRenderTargets.cs @@ -0,0 +1,63 @@ +using Source.Common.Bitmap; +using Source.Common.Client; +using Source.Common.MaterialSystem; + +using TextureFlags = Source.Common.TextureFlags; + +namespace Game.Client; + +public class BaseClientRenderTargets : IClientRenderTargets +{ + protected readonly TextureReference WaterReflectionTexture = new(); + protected readonly TextureReference WaterRefractionTexture = new(); + protected readonly TextureReference CameraTexture = new(); + + protected static ITexture? CreateWaterReflectionTexture(IMaterialSystem materialSystem, int size) { + return materialSystem.CreateNamedRenderTargetTextureEx2("_rt_WaterReflection", size, size, RenderTargetSizeMode.Picmip, materialSystem.GetBackBufferFormat(), MaterialRenderTargetDepth.Shared, TextureFlags.ClampS | TextureFlags.ClampT, CreateRenderTargetFlags.HDR); + } + + protected static ITexture? CreateWaterRefractionTexture(IMaterialSystem materialSystem, int size) { + return materialSystem.CreateNamedRenderTargetTextureEx2("_rt_WaterRefraction", size, size, RenderTargetSizeMode.Picmip, ImageFormat.RGBA8888, MaterialRenderTargetDepth.Shared, TextureFlags.ClampS | TextureFlags.ClampT, CreateRenderTargetFlags.HDR); + } + + protected static ITexture? CreateCameraTexture(IMaterialSystem materialSystem, int size) { + return materialSystem.CreateNamedRenderTargetTextureEx2("_rt_Camera", size, size, RenderTargetSizeMode.Default, materialSystem.GetBackBufferFormat(), MaterialRenderTargetDepth.Shared, 0, CreateRenderTargetFlags.HDR); + } + + public virtual void InitClientRenderTargets(IMaterialSystem materialSystem, IMaterialSystemHardwareConfig hardwareConfig) => InitClientRenderTargets(materialSystem, hardwareConfig, 1024, 256); + + public void InitClientRenderTargets(IMaterialSystem materialSystem, IMaterialSystemHardwareConfig hardwareConfig, int waterTextureSize, int cameraTextureSize) { + // Water effects + WaterReflectionTexture.Init(CreateWaterReflectionTexture(materialSystem, waterTextureSize)); + WaterRefractionTexture.Init(CreateWaterRefractionTexture(materialSystem, waterTextureSize)); + + // Monitors + CameraTexture.Init(CreateCameraTexture(materialSystem, cameraTextureSize)); + } + + public virtual void ShutdownClientRenderTargets() { + // Water effects + WaterReflectionTexture.Shutdown(); + WaterRefractionTexture.Shutdown(); + + // Monitors + CameraTexture.Shutdown(); + } +} + +public class ClientRenderTargets : BaseClientRenderTargets +{ + public override void InitClientRenderTargets(IMaterialSystem materialSystem, IMaterialSystemHardwareConfig hardwareConfig) { + InitClientRenderTargets(materialSystem, hardwareConfig, 1024, 512); + materialSystem.CreateNamedRenderTargetTexture("_rt_spawnicon", 512, 512, RenderTargetSizeMode.Default, ImageFormat.ARGB8888, MaterialRenderTargetDepth.Separate, true, false); + + RenderTexture.GetMoBlurTex0(); + RenderTexture.GetMoBlurTex1(); + RenderTexture.GetBloomTex0(); + RenderTexture.GetBloomTex1(); + RenderTexture.GetMorphTex0(); + RenderTexture.GetMorphTex1(); + RenderTexture.GetSuperFPTex2(hardwareConfig); + RenderTexture.GetSuperFPTex(hardwareConfig); + } +} diff --git a/Game.Client/GarrysMod/LuaMaterial.cs b/Game.Client/GarrysMod/LuaMaterial.cs index 4995374ef..9c81dfea9 100644 --- a/Game.Client/GarrysMod/LuaMaterial.cs +++ b/Game.Client/GarrysMod/LuaMaterial.cs @@ -1,4 +1,5 @@ using Source; +using Source.Common.Formats.Keyvalues; using Source.Common.GarrysMod.Lua; using Source.Common.MaterialSystem; @@ -201,8 +202,6 @@ static int Material(ILuaInterface lua) { string parameters = lua.CheckStringOpt(2, ""); long start = Stopwatch.GetTimestamp(); - Console.WriteLine($"Lua loading material {name}"); // todo remove me - IMaterial? material = null; if (get.Resources() != null) material = get.Resources()!.FindMaterial(name, parameters, true, false, false); @@ -218,4 +217,113 @@ static int Material(ILuaInterface lua) { lua.PushNumber((Stopwatch.GetTimestamp() - start) / (double)Stopwatch.Frequency); return 2; } + + struct CreatedMaterial + { + public InlineArray260 Name; + public IMaterial? Material; + } + + static readonly List CreatedMaterials = []; + + public static void Push(IMaterial? material) { + material?.IncrementReferenceCount(); + LC_IMaterial.Push(material); + } + + public static void TableToKeyValues(ILuaObject? table, KeyValues kv, ILuaObject visited) { + if (table == null || !table.isTable()) + return; + + visited.Push(); + table.Push(); + g_Lua!.GetTable(-2); + LuaType type = g_Lua.GetType(-1); + g_Lua.Pop(2); + if (type == LuaType.Bool) { + visited.UnReference(); + g_Lua.Error("TableToKeyValues: attempt to serialize structure with cyclic reference"); + return; + } + + visited.Push(); + table.Push(); + g_Lua.PushBool(true); + g_Lua.SetTable(-3); + g_Lua.Pop(1); + + table.Push(); + g_Lua.PushNil(); + while (g_Lua.Next(-2)) { + g_Lua.Push(-2); + string? key = g_Lua.GetString(-1); + g_Lua.Pop(1); + if (g_Lua.GetType(-1) == LuaType.Table) { + KeyValues sub = kv.CreateNewKey(); + sub.SetName(key); + LuaObject subTable = new(); + subTable.SetFromStack(-1); + TableToKeyValues(subTable, sub, visited); + subTable.UnReference(); + } + else + kv.SetString(key, g_Lua.GetString(-1)); + g_Lua.Pop(1); + } + g_Lua.Pop(1); + + visited.Push(); + table.Push(); + g_Lua.PushNil(); + g_Lua.SetTable(-3); + g_Lua.Pop(1); + } + + [LuaGlobal] + static int CreateMaterial(ILuaInterface lua) { + string name = lua.CheckString(1); + string shader = lua.CheckString(2); + ILuaObject data = lua.GetObject(3); + if (!data.isNil() && !data.isTable()) { + lua.TypeError("table", 3); + return 0; + } + + foreach (CreatedMaterial created in CreatedMaterials) { + if (strncmp(((ReadOnlySpan)created.Name).SliceNullTerminatedString(), name, 260) == 0) { + Push(created.Material); + return 1; + } + } + + KeyValues kv = new(shader); + LuaTable visited = new(null, 0); + TableToKeyValues(data, kv, visited); + + string fileName = $"{name}.vmt"; + IMaterial? material = materials.FindMaterial("!" + name, "Other textures", false, null); + if (material == null || material.IsErrorMaterial()) { + material = materials.CreateMaterial(fileName, kv); + if (material == null) { + visited.UnReference(); + return 0; + } + material.DecrementReferenceCount(); + } + else { + // todo: IMaterial.SetShaderAndParams + // material.SetShaderAndParams(kv); + } + + CreatedMaterial entry = default; + strcpy(entry.Name, name); + entry.Material = material; + CreatedMaterials.Add(entry); + material.IncrementReferenceCount(); + material.Refresh(); + Push(material); + + visited.UnReference(); + return 1; + } } diff --git a/Game.Client/GarrysMod/LuaRender.cs b/Game.Client/GarrysMod/LuaRender.cs index 6c807e68c..29dfb9ad0 100644 --- a/Game.Client/GarrysMod/LuaRender.cs +++ b/Game.Client/GarrysMod/LuaRender.cs @@ -1,6 +1,10 @@ +using Source; +using Source.Common.Bitmap; using Source.Common.GarrysMod.Lua; using Source.Common.MaterialSystem; +using TextureFlags = Source.Common.TextureFlags; + using System.Numerics; namespace Game.Client.GarrysMod; @@ -12,6 +16,102 @@ public static partial class LuaRender static readonly IMaterialSystemHardwareConfig HardwareConfig = Singleton(); static readonly TextureReference RenderTextureReference = new(); + struct NamedRenderTarget + { + public InlineArray256 Name; + public ITexture? Texture; + } + + static readonly List NamedRenderTargets = []; + + static ITexture? CreateNamedRenderTarget(ReadOnlySpan name, int w, int h, RenderTargetSizeMode sizeMode, MaterialRenderTargetDepth depth, TextureFlags textureFlags, CreateRenderTargetFlags renderTargetFlags, bool unused, ImageFormat format) { + if (name.IsEmpty) + return null; + + int index = -1; + for (int i = 0; i < NamedRenderTargets.Count; i++) { + NamedRenderTarget rt = NamedRenderTargets[i]; + if (stricmp(((ReadOnlySpan)rt.Name).SliceNullTerminatedString(), name) == 0) { + if (rt.Texture == null || rt.Texture.IsError()) { + index = i; + break; + } + return rt.Texture; + } + } + + if (stricmp("_rt_ResolvedFullFrameDepth", name) == 0) { + Warning($"Warning! Creating an RT ({name}) with name of an existing texture!\n"); + return materials.FindTexture("_rt_ResolvedFullFrameDepth", MaterialDefines.TEXTURE_GROUP_RENDER_TARGET, true, 0); + } + + if ((textureFlags & TextureFlags.EnvMap) != 0) { + Warning($"Warning! Creating an RT ({name}) with TEXTUREFLAGS_ENVMAP! This will cause crashes! Bailing..\n"); + return null; + } + + if ((textureFlags & TextureFlags.Procedural) != 0) { + Warning($"Warning! Creating an RT ({name}) with TEXTUREFLAGS_PROCEDURAL! Not allowed.\n"); + return null; + } + + if (format == ImageFormat.Unknown) + format = materials.GetBackBufferFormat(); + + ITexture? texture = materials.CreateNamedRenderTargetTextureEx(name, w, h, sizeMode, format, depth, textureFlags, renderTargetFlags); + if (texture == null) { + Warning($"Warning! Failed to create render target {name}!\n"); + return null; + } + + NamedRenderTarget entry = default; + strcpy(entry.Name, name); + entry.Texture = texture; + if (index == -1) + NamedRenderTargets.Add(entry); + else + NamedRenderTargets[index] = entry; + return texture; + } + + [LuaGlobal] + static int GetRenderTarget(ILuaInterface lua) { + ITexture? texture = CreateNamedRenderTarget(lua.CheckString(1), (int)lua.CheckNumber(2), (int)lua.CheckNumber(3), RenderTargetSizeMode.NoChange, MaterialRenderTargetDepth.Separate, TextureFlags.Trilinear | TextureFlags.NoMip, 0, true, ImageFormat.Unknown); + if (texture != null && !texture.IsError()) { + LuaTexture.Push(texture); + return 1; + } + return 0; + } + + [LuaGlobal] + static int GetRenderTargetEx(ILuaInterface lua) { + float sizeMode = (int)lua.CheckNumber(4); + if (sizeMode <= 0) + sizeMode = 0; + if ((float)RenderTargetSizeMode.LiteralPicmip <= sizeMode) + sizeMode = (float)RenderTargetSizeMode.LiteralPicmip; + + float depth = (int)lua.CheckNumber(5); + if (depth <= 0) + depth = 0; + if ((float)MaterialRenderTargetDepth.Only <= depth) + depth = (float)MaterialRenderTargetDepth.Only; + + int format = (int)lua.CheckNumber(8); + if (format < (int)ImageFormat.Unknown || format >= (int)ImageFormat.Count) { + lua.Error("GetRenderTargetEx: Invalid image format\n"); + return 0; + } + + ITexture? texture = CreateNamedRenderTarget(lua.CheckString(1), (int)lua.CheckNumber(2), (int)lua.CheckNumber(3), (RenderTargetSizeMode)(uint)sizeMode, (MaterialRenderTargetDepth)(uint)depth, (TextureFlags)(int)lua.CheckNumber(6), (CreateRenderTargetFlags)(int)lua.CheckNumber(7), false, (ImageFormat)format); + if (texture != null && !texture.IsError()) { + LuaTexture.Push(texture); + return 1; + } + return 0; + } + // todo: DrawSprite // todo: DrawQuadEasy // todo: DrawQuad @@ -64,8 +164,36 @@ public static partial class LuaRender // todo: GetRenderTarget // todo: SetRenderTarget // todo: SetRenderTargetEx - // todo: PushRenderTarget - // todo: PopRenderTarget + static int RenderTargetStack; + + [LuaFunction] + static int PushRenderTarget(ILuaInterface lua) { + ITexture? texture = null; + if (lua.IsType(1, LuaType.Texture)) + texture = (ITexture?)LuaTexture.LC_ITexture.Get(1); + + using MatRenderContextPtr renderContext = new(materials); + if (lua.GetType(2) == LuaType.Number) + renderContext.PushRenderTargetAndViewport(texture, (int)lua.CheckNumber(2), (int)lua.CheckNumber(3), (int)lua.CheckNumber(4), (int)lua.CheckNumber(5)); + else + renderContext.PushRenderTargetAndViewport(texture); + + RenderTargetStack++; + return 0; + } + + [LuaFunction] + static int PopRenderTarget(ILuaInterface lua) { + if (RenderTargetStack > 0) { + RenderTargetStack--; + using MatRenderContextPtr renderContext = new(materials); + renderContext.PopRenderTargetAndViewport(); + return 0; + } + + lua.ErrorFromLua("render.PopRenderTarget underflow\n"); + return 0; + } [LuaFunction] static int GetScreenEffectTexture(ILuaInterface lua) { int index = 0; @@ -79,16 +207,44 @@ static int GetScreenEffectTexture(ILuaInterface lua) { } return 0; } - // todo: GetBloomTex0 - // todo: GetBloomTex1 - // todo: GetMoBlurTex0 - // todo: GetMoBlurTex1 + [LuaFunction] + static int GetBloomTex0(ILuaInterface lua) { + LuaTexture.Push(RenderTexture.GetBloomTex0()); + return 1; + } + + [LuaFunction] + static int GetBloomTex1(ILuaInterface lua) { + LuaTexture.Push(RenderTexture.GetBloomTex1()); + return 1; + } + + [LuaFunction] + static int GetMoBlurTex0(ILuaInterface lua) { + LuaTexture.Push(RenderTexture.GetMoBlurTex0()); + return 1; + } + + [LuaFunction] + static int GetMoBlurTex1(ILuaInterface lua) { + LuaTexture.Push(RenderTexture.GetMoBlurTex1()); + return 1; + } // todo: GetMorphTex0 // todo: GetMorphTex1 // todo: GetSmallTex0 // todo: GetSmallTex1 - // todo: GetSuperFPTex - // todo: GetSuperFPTex2 + [LuaFunction] + static int GetSuperFPTex(ILuaInterface lua) { + LuaTexture.Push(RenderTexture.GetSuperFPTex(null)); + return 1; + } + + [LuaFunction] + static int GetSuperFPTex2(ILuaInterface lua) { + LuaTexture.Push(RenderTexture.GetSuperFPTex2(null)); + return 1; + } // todo: SuppressEngineLighting // todo: SetLocalModelLights // todo: ResetModelLighting diff --git a/Game.Client/GarrysMod/LuaVGUI.cs b/Game.Client/GarrysMod/LuaVGUI.cs index f70f0f31d..c2aaf3255 100644 --- a/Game.Client/GarrysMod/LuaVGUI.cs +++ b/Game.Client/GarrysMod/LuaVGUI.cs @@ -16,7 +16,22 @@ public static partial class LuaVGUI // todo: CursorVisible // todo: IsHoveringWorld // todo: GetWorldPanel - // todo: FocusedHasParent + [LuaFunction] + static int FocusedHasParent(ILuaInterface lua) { + Panel? panel = Get_Panel(1); + if (panel == null) + return 0; + + IPanel? focus = vguiInput.GetFocus(); + if (focus != null && focus.HasParent(panel)) { + lua.PushBool(true); + return 1; + } + + lua.PushBool(false); + return 1; + } + [LuaFunction] static int GetKeyboardFocus(ILuaInterface lua) { IPanel? focus = vguiInput.GetFocus(); diff --git a/Game.Client/HLClient.cs b/Game.Client/HLClient.cs index 873fe9933..eef26a446 100644 --- a/Game.Client/HLClient.cs +++ b/Game.Client/HLClient.cs @@ -40,6 +40,7 @@ public class HLClient(IServiceProvider services, ClientGlobalVariables gpGlobals public static void DLLInit(IServiceCollection services) { services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(x => x.GetRequiredService()); services.AddSingleton(x => x.GetRequiredService()); diff --git a/Game.Client/RenderTexture.cs b/Game.Client/RenderTexture.cs index 20a934839..7c3f2f0fa 100644 --- a/Game.Client/RenderTexture.cs +++ b/Game.Client/RenderTexture.cs @@ -1,6 +1,9 @@ using Source; +using Source.Common.Bitmap; using Source.Common.MaterialSystem; +using TextureFlags = Source.Common.TextureFlags; + namespace Game.Client; /// @@ -182,6 +185,92 @@ static void AddReleaseFunc() { return TeenyTextures[which].Get(); } + static readonly TextureReference BloomTex0 = new(); + public static ITexture? GetBloomTex0() { + if (BloomTex0.IsValid()) + return BloomTex0.Get(); + + BloomTex0.Init(materials.CreateNamedRenderTargetTextureEx2("s_pBloomTex0", 256, 256, RenderTargetSizeMode.HDR, materials.GetBackBufferFormat(), MaterialRenderTargetDepth.Separate, TextureFlags.ClampS | TextureFlags.ClampT, CreateRenderTargetFlags.HDR)); + if (!BloomTex0.IsValid()) + Warning("Error Creating Render Target s_pBloomTex0!\n"); + return BloomTex0.Get(); + } + + static readonly TextureReference BloomTex1 = new(); + public static ITexture? GetBloomTex1() { + if (BloomTex1.IsValid()) + return BloomTex1.Get(); + + BloomTex1.Init(materials.CreateNamedRenderTargetTextureEx2("s_pBloomTex1", 256, 256, RenderTargetSizeMode.HDR, materials.GetBackBufferFormat(), MaterialRenderTargetDepth.Separate, TextureFlags.ClampS | TextureFlags.ClampT, CreateRenderTargetFlags.HDR)); + if (!BloomTex1.IsValid()) + Warning("Error Creating Render Target s_pBloomTex1!\n"); + return BloomTex1.Get(); + } + + static readonly TextureReference MoBlurTex0 = new(); + public static ITexture? GetMoBlurTex0() { + if (MoBlurTex0.IsValid()) + return MoBlurTex0.Get(); + + MoBlurTex0.Init(materials.CreateNamedRenderTargetTextureEx2("s_pMoBlurTex0", 256, 256, RenderTargetSizeMode.FullFrameBuffer, materials.GetBackBufferFormat(), MaterialRenderTargetDepth.Separate, TextureFlags.ClampS | TextureFlags.ClampT, CreateRenderTargetFlags.HDR)); + if (!MoBlurTex0.IsValid()) + Warning("Error Creating Render Target s_pMoBlurTex0!\n"); + return MoBlurTex0.Get(); + } + + static readonly TextureReference MoBlurTex1 = new(); + public static ITexture? GetMoBlurTex1() { + if (MoBlurTex1.IsValid()) + return MoBlurTex1.Get(); + + MoBlurTex1.Init(materials.CreateNamedRenderTargetTextureEx2("s_pMoBlurTex1", 256, 256, RenderTargetSizeMode.FullFrameBuffer, materials.GetBackBufferFormat(), MaterialRenderTargetDepth.Separate, TextureFlags.ClampS | TextureFlags.ClampT, CreateRenderTargetFlags.HDR)); + if (!MoBlurTex1.IsValid()) + Warning("Error Creating Render Target s_pMoBlurTex1!\n"); + return MoBlurTex1.Get(); + } + + static readonly TextureReference MorphTex0 = new(); + public static ITexture? GetMorphTex0() { + if (MorphTex0.IsValid()) + return MorphTex0.Get(); + + MorphTex0.Init(materials.CreateNamedRenderTargetTextureEx2("s_pMorphTexture0", 256, 256, RenderTargetSizeMode.FullFrameBuffer, materials.GetBackBufferFormat(), MaterialRenderTargetDepth.Separate, TextureFlags.ClampS | TextureFlags.ClampT, CreateRenderTargetFlags.HDR)); + if (!MorphTex0.IsValid()) + Warning("Error Creating Render Target s_pMorphTexture0!\n"); + return MorphTex0.Get(); + } + + static readonly TextureReference MorphTex1 = new(); + public static ITexture? GetMorphTex1() { + if (MorphTex1.IsValid()) + return MorphTex1.Get(); + + MorphTex1.Init(materials.CreateNamedRenderTargetTextureEx2("s_pMorphTexture1", 256, 256, RenderTargetSizeMode.FullFrameBuffer, materials.GetBackBufferFormat(), MaterialRenderTargetDepth.Separate, TextureFlags.ClampS | TextureFlags.ClampT, CreateRenderTargetFlags.HDR)); + if (!MorphTex1.IsValid()) + Warning("Error Creating Render Target s_pMorphTexture1!\n"); + return MorphTex1.Get(); + } + + static readonly TextureReference SuperFPTex = new(); + public static ITexture? GetSuperFPTex(IMaterialSystemHardwareConfig? hardwareConfig) { + if (!SuperFPTex.IsValid()) { + if (hardwareConfig != null && hardwareConfig.GetDXSupportLevel() >= 90) + SuperFPTex.InitRenderTarget(512, 512, RenderTargetSizeMode.FullFrameBuffer, ImageFormat.RGBA16161616F, MaterialRenderTargetDepth.Shared, true, "__rt_SuperTexture1"); + return SuperFPTex.Get(); + } + return SuperFPTex.Get(); + } + + static readonly TextureReference SuperFPTex2 = new(); + public static ITexture? GetSuperFPTex2(IMaterialSystemHardwareConfig? hardwareConfig) { + if (!SuperFPTex2.IsValid()) { + if (hardwareConfig != null && hardwareConfig.GetDXSupportLevel() >= 90) + SuperFPTex2.InitRenderTarget(512, 512, RenderTargetSizeMode.FullFrameBuffer, ImageFormat.RGBA16161616F, MaterialRenderTargetDepth.Shared, true, "__rt_SuperTexture2"); + return SuperFPTex2.Get(); + } + return SuperFPTex2.Get(); + } + public static void ReleaseRenderTargets() { PowerOfTwoFrameBufferTexture.Shutdown(); CameraTexture.Shutdown(); diff --git a/Game.Lua/LuaSharedImpl.cs b/Game.Lua/LuaSharedImpl.cs index 2e046e396..ac26e39d6 100644 --- a/Game.Lua/LuaSharedImpl.cs +++ b/Game.Lua/LuaSharedImpl.cs @@ -205,7 +205,8 @@ LuaFile CreateCache(ReadOnlySpan name, byte[] contents, int time) { public void MountLua(ReadOnlySpan pathId) { MountLuaAdd("lua", pathId); - MountLuaAdd("gamemodes", pathId); + if (stricmp(pathId, "LuaMenu") != 0) + MountLuaAdd("gamemodes", pathId); } public void MountLuaAdd(ReadOnlySpan path, ReadOnlySpan pathId) { @@ -214,17 +215,18 @@ public void MountLuaAdd(ReadOnlySpan path, ReadOnlySpan pathId) { } void AddSearchPath(ReadOnlySpan path, ReadOnlySpan pathId) { + bool workshop = strnicmp(path, "workshop", 8) == 0; Span fullPath = stackalloc char[MaxPath]; ReadOnlySpan full = filesystem.RelativePathToFullPath(path, "MOD", fullPath); if (!full.IsEmpty) { if (filesystem.IsDirectory(full, null)) - filesystem.AddSearchPath(full, pathId, SearchPathAdd.ToTail, PathGroupName.Lua); + filesystem.AddSearchPath(full, pathId, SearchPathAdd.ToTail, PathGroupName.Lua, workshop); else Warning($"Tried to add search path, but path isn't path(!?) ({path})\n"); return; } - filesystem.AddSearchPath($"{Get!.GameDir()}{CORRECT_PATH_SEPARATOR}{path}", pathId, SearchPathAdd.ToTail, PathGroupName.Lua); + filesystem.AddSearchPath($"{Get!.GameDir()}{CORRECT_PATH_SEPARATOR}{path}", pathId, SearchPathAdd.ToTail, PathGroupName.Lua, workshop); } public void UnMountLua(ReadOnlySpan pathId) => filesystem.RemoveSearchPaths(pathId); diff --git a/Game.Server/World.cs b/Game.Server/World.cs index da78fbf39..410079e84 100644 --- a/Game.Server/World.cs +++ b/Game.Server/World.cs @@ -4,6 +4,7 @@ using Source.Common; using Source.Common.Commands; +using Source.Common.Mathematics; using Source.Engine; using System.Numerics; @@ -48,6 +49,31 @@ public World() { ColdWorld = false; } + public override bool KeyValue(ReadOnlySpan keyName, ReadOnlySpan value) { + if (keyName.Equals("skyname", StringComparison.Ordinal)) { + ConVarRef skyname = new("sv_skyname"); + skyname.SetValue(value); + } + else if (keyName.Equals("newunit", StringComparison.Ordinal)) { + // if (atoi(value) != 0) + // Game_SetOneWayTransition(); + } + else if (keyName.Equals("world_mins", StringComparison.Ordinal)) { + Vector3 vec = default; + UTIL_StringToVector(vec.Base(), value); + WorldMins = vec; + } + else if (keyName.Equals("world_maxs", StringComparison.Ordinal)) { + Vector3 vec = default; + UTIL_StringToVector(vec.Base(), value); + WorldMaxs = vec; + } + else + return base.KeyValue(keyName, value); + + return true; + } + public override void Precache() { g_WorldEntity = this; g_fGameOver = false; @@ -85,7 +111,7 @@ public override void Precache() { g_pGameRules.Precache(); BaseTempEntity.PrecacheTempEnts(); - for (int i = 0; i < g_DefaultLightstyles.Length; i++) + for (int i = 0; i < g_DefaultLightstyles.Length; i++) engine.LightStyle(i, GetDefaultLightstyleString(i)); // styles 32-62 are assigned by the light program for switchable lights @@ -104,7 +130,7 @@ public override void Precache() { } public static ReadOnlySpan GetDefaultLightstyleString(int styleIndex) => styleIndex < g_DefaultLightstyles.Length ? g_DefaultLightstyles[styleIndex] : "m"; - static readonly string[] g_DefaultLightstyles = [ + static readonly string[] g_DefaultLightstyles = [ // 0 normal "m", // 1 FLICKER (first variety) diff --git a/Game.Shared/GarrysMod/LuaGame.cs b/Game.Shared/GarrysMod/LuaGame.cs index a0bbae5f6..15ed1abca 100644 --- a/Game.Shared/GarrysMod/LuaGame.cs +++ b/Game.Shared/GarrysMod/LuaGame.cs @@ -1,5 +1,6 @@ #if CLIENT_DLL || GAME_DLL using Source; +using Source.Common.GarrysMod; using Source.Common.GarrysMod.Lua; using Game.Shared; @@ -46,6 +47,33 @@ static int GetMap(ILuaInterface lua) { // todo: GetSkillLevel // todo: AddParticles // todo: IsDedicated + + [LuaFunction] + static int MountGMA(ILuaInterface lua) { + string path = g_Lua!.CheckString(1); + if (!GMOD.IsValidPath(path)) { + g_Lua.PushBool(false); + return 1; + } + + List files = []; + if (!filesystem.Addons().MountFile(path, files, 0, 0, 2)) { + g_Lua.PushBool(false); + return 1; + } + + g_Lua.PushBool(true); + g_Lua.CreateTable(); + for (int i = 0; i < files.Count; i++) { + g_Lua.PushNumber(i + 1); + g_Lua.PushString(files[i]); + g_Lua.SetTable(-3); + // todo: engine.GMOD_LoadModel + // if (Bootil.String.Test.EndsWith(files[i], ".mdl")) + // engine.GMOD_LoadModel(files[i]); + } + return 2; + } [LuaFunction] static int GetWorld(ILuaInterface lua) { #if CLIENT_DLL diff --git a/Game.Shared/GarrysMod/LuaPlayer.cs b/Game.Shared/GarrysMod/LuaPlayer.cs index 2c2b70970..9f7c966b3 100644 --- a/Game.Shared/GarrysMod/LuaPlayer.cs +++ b/Game.Shared/GarrysMod/LuaPlayer.cs @@ -93,6 +93,13 @@ static int Player__KeyDown(ILuaInterface lua) { return 1; } + [LuaMethod] + static int Player__Alive(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + g_Lua!.PushBool(player.IsAlive()); + return 1; + } + [LuaMethod] static int Player__GetActiveWeapon(ILuaInterface lua) { BasePlayer player = Get_Player(1, false)!; diff --git a/Game.Shared/GarrysMod/LuaUtil.cs b/Game.Shared/GarrysMod/LuaUtil.cs index 5059ccc1a..2b492ae52 100644 --- a/Game.Shared/GarrysMod/LuaUtil.cs +++ b/Game.Shared/GarrysMod/LuaUtil.cs @@ -6,6 +6,7 @@ using Source.Common.DataCache; using Source.Common.Engine; using Source.Common.Formats.BSP; +using Source.Common.Formats.Keyvalues; using Source.Common.GarrysMod.Lua; using Source.Common.Mathematics; using Source.Common.Physics; @@ -88,6 +89,18 @@ static int Base64Decode(ILuaInterface lua) { return 1; } + [LuaFunction] + static int KeyValuesToTable(ILuaInterface lua) { + LuaTable table = new(null, 0); + KeyValues kv = new("KeyValuesToTable"); + kv.UsesEscapeSequences(g_Lua!.GetBool(2)); + kv.LoadFromBuffer("util.KeyValuesToTable", g_Lua.CheckString(1)); + LuaHelper.KeyValuesToTable(kv, table, g_Lua.GetBool(3)); + table.Push(); + table.UnReference(); + return 1; + } + #if GAME_DLL [LuaFunction] static int AddNetworkString(string name) => NetworkString.Add(name); diff --git a/Source.Common/Filesystem/IFileSystem.cs b/Source.Common/Filesystem/IFileSystem.cs index 8d92f153d..7088afc52 100644 --- a/Source.Common/Filesystem/IFileSystem.cs +++ b/Source.Common/Filesystem/IFileSystem.cs @@ -245,7 +245,7 @@ public interface IFileSystem : IBaseFileSystem /// /// /// - public void AddSearchPath(ReadOnlySpan diskPath, ReadOnlySpan pathID, SearchPathAdd addType = SearchPathAdd.ToTail, PathGroupName groupName = PathGroupName.Default); + public void AddSearchPath(ReadOnlySpan diskPath, ReadOnlySpan pathID, SearchPathAdd addType = SearchPathAdd.ToTail, PathGroupName groupName = PathGroupName.Default, bool workshop = false); /// /// Add a search path. /// diff --git a/Source.Filesystem/BaseFileSystem.cs b/Source.Filesystem/BaseFileSystem.cs index 60dfe464d..8f1571421 100644 --- a/Source.Filesystem/BaseFileSystem.cs +++ b/Source.Filesystem/BaseFileSystem.cs @@ -128,7 +128,7 @@ private void AddPackFiles(ReadOnlySpan path, ReadOnlySpan pathID, Se private void AddSeparatorAndFixPath(ref string path) { // this sucks fix it later path = (path.TrimEnd('\\').TrimEnd('/') + "/").Replace("\\", "/"); } - private void AddSearchPathDiskInternal(ReadOnlySpan path, ReadOnlySpan pathID, SearchPathAdd addType, PathGroupName groupName, bool addPackFiles) { + private void AddSearchPathDiskInternal(ReadOnlySpan path, ReadOnlySpan pathID, SearchPathAdd addType, PathGroupName groupName, bool addPackFiles, bool workshop = false) { var ext = Path.GetExtension(path); switch (ext) { @@ -161,12 +161,12 @@ private void AddSearchPathDiskInternal(ReadOnlySpan path, ReadOnlySpan path, ReadOnlySpan pathID, SearchPathAdd addType = SearchPathAdd.ToTail, PathGroupName name = PathGroupName.Default) { - AddSearchPathDiskInternal(path, pathID, addType, name, true); + public void AddSearchPath(ReadOnlySpan path, ReadOnlySpan pathID, SearchPathAdd addType = SearchPathAdd.ToTail, PathGroupName name = PathGroupName.Default, bool workshop = false) { + AddSearchPathDiskInternal(path, pathID, addType, name, true, workshop); } public void AddSearchPath(ISearchPath path, ReadOnlySpan pathID, SearchPathAdd addType = SearchPathAdd.ToTail, PathGroupName groupName = PathGroupName.Default) { @@ -300,19 +300,28 @@ interface IFirstToThePostOp return loseDefault; } - readonly ref struct RelativePathToFullPath_Op() : IFirstToThePostOp - { - public bool Invoke(ISearchPath p, scoped ReadOnlySpan name) => p.Exists(name); - public bool Win(bool v) => v; - } - public ReadOnlySpan RelativePathToFullPath(ReadOnlySpan fileName, ReadOnlySpan pathID, Span dest, PathTypeFilter filter = PathTypeFilter.None) { + using Lock.Scope scope = SearchPathLock.EnterScope(); fileName = fileName.SliceNullTerminatedString(); - if (!FirstToThePost(fileName, pathID, new RelativePathToFullPath_Op(), false, out ISearchPath? winner)) - return null; - - Span concatBuffer = stackalloc char[MAX_PATH]; - return ISearchPath.Concat(winner, fileName, dest); + Span filenameNormalizedBuffer = stackalloc char[MAX_PATH]; + ReadOnlySpan filenameNormalized = ISearchPath.Normalize(fileName, filenameNormalizedBuffer); + CollectionIterator iterator = GetCollections(pathID.Hash()); + while (iterator.MoveNext()) { + ISearchPath path = iterator.Current; + if (path is DiskSearchPath disk) { + if (disk.ExistsOnDisk(filenameNormalized)) + return ISearchPath.Concat(path, fileName, dest); + + string resolved = g_AddonFileSystem.ResolveFile(disk.GetFullPath(filenameNormalized)); + if (resolved.Length != 0) { + int len = strcpy(dest, resolved); + return dest[..len]; + } + } + else if (path.Exists(filenameNormalized)) + return ISearchPath.Concat(path, fileName, dest); + } + return null; } public bool FullPathToRelativePath(ReadOnlySpan fullPath, Span relative) => FullPathToRelativePathEx(fullPath, null, relative); @@ -733,11 +742,41 @@ public void FullyLock(BaseFileSystem system, FileFindHandle_t lockedIdx, ReadOnl PathID = new UtlSymbol(pathID); #if GMOD_DLL + if (pathID.IsEmpty) { + foreach (SearchPathCollection collection in system.SearchPaths.Values) { + if (collection.RequestOnly) + continue; + FindInLooseAddonPaths(collection, wildcard); + } + } + else if (!pathID.Equals("BSP", StringComparison.Ordinal) && system.SearchPaths.TryGetValue(new string(pathID).Hash(), out SearchPathCollection? collection)) + FindInLooseAddonPaths(collection, wildcard); + if (!pathID.IsEmpty && !pathID.Equals("MOD", StringComparison.Ordinal) && !pathID.Equals("GAME", StringComparison.Ordinal) && !pathID.Equals("workshop", StringComparison.Ordinal)) g_AddonFileSystem.FindInAddon(new string(pathID), new string(wildcard), addonFiles!); #endif } +#if GMOD_DLL + readonly void FindInLooseAddonPaths(SearchPathCollection collection, ReadOnlySpan wildcard) { + for (int i = 0; ; i++) { + ISearchPath? searchPath = collection.AtSorted(i); + if (searchPath == null) + break; + if (searchPath is not DiskSearchPath) + continue; + + ReadOnlySpan path = searchPath.GetPathString(); + if (path.Equals("GAME", StringComparison.Ordinal)) + continue; + + string full = $"{path}{wildcard}"; + full = full.Replace('\\', '/'); + g_AddonFileSystem.FindFirst(full, addonFiles!, null); + } + } +#endif + public void Reset() { Wildcard = default; PathID = default; diff --git a/Source.Filesystem/DiskSearchPath.cs b/Source.Filesystem/DiskSearchPath.cs index cce022187..0658e47fc 100644 --- a/Source.Filesystem/DiskSearchPath.cs +++ b/Source.Filesystem/DiskSearchPath.cs @@ -50,6 +50,7 @@ static string ResolveDiskPath(string path) { #endif private IFileSystem parent; + public bool Workshop; public DiskSearchPath(IFileSystem filesystem, string absPath) { parent = filesystem; @@ -61,7 +62,15 @@ public DiskSearchPath(IFileSystem filesystem, string absPath) { private string GetAbsPath(ReadOnlySpan relPath) => ResolveDiskPath(Path.Combine(DiskPath!, new(relPath))); - public override bool Exists(ReadOnlySpan path) => Path.Exists(GetAbsPath(path)); + public override bool Exists(ReadOnlySpan path) { + string absPath = GetAbsPath(path); + if (Path.Exists(absPath)) + return true; + return Workshop && BaseFileSystem.g_AddonFileSystem.GetFileEntry(absPath) != null; + } + + public bool ExistsOnDisk(ReadOnlySpan path) => Path.Exists(GetAbsPath(path)); + public string GetFullPath(ReadOnlySpan path) => GetAbsPath(path).Replace('\\', '/'); public override bool IsDirectory(ReadOnlySpan path) => Directory.Exists(GetAbsPath(path)); public override bool IsFileWritable(ReadOnlySpan path) { @@ -76,7 +85,11 @@ public override bool IsFileWritable(ReadOnlySpan path) { FileOpenOptions operation = options.GetOperation(); // Scram early if the file doesn't even exist - if (!info.Exists && operation == FileOpenOptions.Read) return null; + if (!info.Exists && operation == FileOpenOptions.Read) { + if (Workshop) + return BaseFileSystem.g_AddonFileSystem.GetFileEntry(absPath); + return null; + } // Check file options for invalid access if (operation == FileOpenOptions.Write && info.IsReadOnly && info.Exists) @@ -153,7 +166,8 @@ public override long Size(ReadOnlySpan path) { public override DateTime Time(ReadOnlySpan path) { var absPath = GetAbsPath(path); var info = new FileInfo(absPath); - if (!info.Exists) return DateTime.UnixEpoch; + if (!info.Exists) + return BaseFileSystem.g_AddonFileSystem.GetFileSize(absPath) >= 0 ? DateTime.UnixEpoch.AddSeconds(1) : DateTime.UnixEpoch; return info.LastWriteTimeUtc; } diff --git a/Source.Filesystem/GarrysMod/AddonFileSystem.cs b/Source.Filesystem/GarrysMod/AddonFileSystem.cs index 9c728f994..cc3d7e960 100644 --- a/Source.Filesystem/GarrysMod/AddonFileSystem.cs +++ b/Source.Filesystem/GarrysMod/AddonFileSystem.cs @@ -1012,6 +1012,13 @@ public bool GetFile(string fileName, out AddonFileInfo info) { return new AddonFileHandle(in info, g_FullFileSystem.FindOrAddFileName(fileName)); } + public string ResolveFile(string fileName) { + if (!GetFile(fileName, out AddonFileInfo info)) + return ""; + + return ModPath + info.FolderName + info.FileName; + } + public int GetFileSize(string fileName) { if (Secrets) Msg($"Addon[GetFileSize]: [{fileName}]\n"); diff --git a/Source.MaterialSystem/MaterialSystem.cs b/Source.MaterialSystem/MaterialSystem.cs index b30f49c1d..c5aa1f797 100644 --- a/Source.MaterialSystem/MaterialSystem.cs +++ b/Source.MaterialSystem/MaterialSystem.cs @@ -1182,7 +1182,15 @@ public void CompactMemory() { } public ITexture? CreateNamedRenderTargetTexture(ReadOnlySpan rtName, int w, int h, RenderTargetSizeMode sizeMode, ImageFormat format, MaterialRenderTargetDepth depth = MaterialRenderTargetDepth.Shared, bool clampTexCoords = true, bool autoMipMap = false) { - throw new NotImplementedException("Incomplete port of IMaterialSystem"); + TextureFlags textureFlags = 0; + if (clampTexCoords) + textureFlags |= TextureFlags.ClampS | TextureFlags.ClampT; + + CreateRenderTargetFlags renderTargetFlags = 0; + if (autoMipMap) + renderTargetFlags |= CreateRenderTargetFlags.AutoMipmap; + + return CreateNamedRenderTargetTextureEx(rtName, w, h, sizeMode, format, depth, textureFlags, renderTargetFlags); } public ITexture? CreateNamedTextureFromBitsEx(ReadOnlySpan name, ReadOnlySpan textureGroupName, int w, int h, int mips, ImageFormat fmt, int srcBufferSize, Span srcBits, CreateTextureFlags flags) { diff --git a/Source.MaterialSystem/Texture.cs b/Source.MaterialSystem/Texture.cs index 8e7fe7ae3..04fce3fd1 100644 --- a/Source.MaterialSystem/Texture.cs +++ b/Source.MaterialSystem/Texture.cs @@ -1327,8 +1327,10 @@ private void ApplyRenderTargetSizeMode(ref int width, ref int height, ImageForma case RenderTargetSizeMode.Literal: break; case RenderTargetSizeMode.LiteralPicmip: break; default: +#if !GMOD_DLL Assert(RenderTargetSizeMode == RenderTargetSizeMode.NoChange); Assert(OriginalRenderTargetType == RenderTargetType.NoDepth); +#endif break; } } From 87544c28c0c5c47c1551d5bc11b35c066e5ef881 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Thu, 8 Oct 2026 06:39:04 +0100 Subject: [PATCH 05/23] LuaCam --- Game.Client/ClientModeShared.cs | 9 +- Game.Client/GarrysMod/LuaCam.cs | 299 ++++++++++++++++++++++ Game.Client/GarrysMod/LuaRender.cs | 204 +++++++++++++++ Game.Client/IViewRender.cs | 3 +- Game.Shared/GarrysMod/LuaVMatrix.cs | 71 +++++ Source.MaterialSystem/MatRenderContext.cs | 8 +- Source.ShaderAPI.Gl46/ShaderAPIGl46.cs | 46 +++- 7 files changed, 623 insertions(+), 17 deletions(-) create mode 100644 Game.Client/GarrysMod/LuaCam.cs create mode 100644 Game.Shared/GarrysMod/LuaVMatrix.cs diff --git a/Game.Client/ClientModeShared.cs b/Game.Client/ClientModeShared.cs index 2bca2dc8d..0beeaa866 100644 --- a/Game.Client/ClientModeShared.cs +++ b/Game.Client/ClientModeShared.cs @@ -37,7 +37,14 @@ public ClientModeShared() { strcpy(HostName, "Unset"); } - static void SetupVGuiMatrices(bool push, IMatRenderContext renderContext) { + public void SetupGModSurface(bool push) { + if (push) + surface.PushMakeCurrent(GarrysMod.GModBase.GetGModBasePanel(true)!, false); + else + surface.PopMakeCurrent(GarrysMod.GModBase.GetGModBasePanel(true)!); + } + + public static void SetupVGuiMatrices(bool push, IMatRenderContext renderContext) { if (!push) { renderContext.MatrixMode(MaterialMatrixMode.Projection); renderContext.PopMatrix(); diff --git a/Game.Client/GarrysMod/LuaCam.cs b/Game.Client/GarrysMod/LuaCam.cs new file mode 100644 index 000000000..ee1879f07 --- /dev/null +++ b/Game.Client/GarrysMod/LuaCam.cs @@ -0,0 +1,299 @@ +using Source; +using Source.Common; +using Source.Common.Engine; +using Source.Common.GarrysMod.Lua; +using Source.Common.GUI; +using Source.Common.Mathematics; +using Source.Common.MaterialSystem; +using Source.Engine; + +using System.Numerics; + +namespace Game.Client.GarrysMod; + +public static partial class LuaCam +{ + [LuaLibrary] + static readonly LuaLibrary LL_Factory_cam = new("cam"); + + static int Start2DCount; + static int Start3DCount; + static int OrthoViewCount; + + static ViewSetup StartView; + + public static bool InSurface3D; + public static void SetInSurface3D(bool value) => InSurface3D = value; + + public static bool FrameStateChecked; + public static void ResetFrameStateChecked() => FrameStateChecked = false; + + [LuaFunction] + static int Start(ILuaInterface lua) { + LuaTable data = new(null, 0); + data.SetFromStack(1); + if (!data.isTable()) { + lua.TypeError("table", 1); + data.UnReference(); + return 0; + } + + ResetFrameStateChecked(); + + if (data.GetMemberStr("type", "3D")![0] == '2') { + using MatRenderContextPtr renderContext = new(materials); + ClientModeShared.SetupVGuiMatrices(true, renderContext); + ((ClientModeShared)clientMode).SetupGModSurface(true); + renderContext.OverrideAlphaWriteEnable(true, true); + Start2DCount++; + data.UnReference(); + return 0; + } + + StartView = view.GetViewSetup(); + StartView.Origin = data.GetMemberVector("origin", StartView.Origin); + StartView.Angles = data.GetMemberAngle("angles", StartView.Angles); + StartView.FOV = data.GetMemberFloat("fov", StartView.FOV); + StartView.X = (int)data.GetMemberFloat("x", StartView.X); + StartView.Y = (int)data.GetMemberFloat("y", StartView.Y); + StartView.Width = (int)data.GetMemberFloat("w", StartView.Width); + StartView.Height = (int)data.GetMemberFloat("h", StartView.Height); + StartView.AspectRatio = data.GetMemberFloat("aspect", StartView.AspectRatio); + StartView.ZNear = data.GetMemberFloat("znear", StartView.ZNear); + StartView.ZFar = data.GetMemberFloat("zfar", StartView.ZFar); + + bool subrect = StartView.X != 0 || StartView.Y != 0 || StartView.Width != ScreenWidth() || StartView.Height != ScreenHeight(); + StartView.RenderToSubrectOfLargerScreen = subrect; + StartView.RenderToSubrectOfLargerScreen = data.GetMemberBool("subrect", subrect); + + LuaObject offCenter = new(); + data.GetMember("offcenter", offCenter); + if (offCenter.isTable()) { + StartView.OffCenter = true; + float invWidth = 1.0f / StartView.Width; + float invHeight = 1.0f / StartView.Height; + StartView.OffCenterLeft = offCenter.GetMemberFloat("left", StartView.OffCenterLeft) * invWidth; + StartView.OffCenterRight = offCenter.GetMemberFloat("right", StartView.OffCenterRight) * invWidth; + StartView.OffCenterTop = offCenter.GetMemberFloat("bottom", StartView.OffCenterTop) * invHeight; + StartView.OffCenterBottom = offCenter.GetMemberFloat("top", StartView.OffCenterBottom) * invHeight; + } + else + StartView.OffCenter = false; + + LuaObject ortho = new(); + data.GetMember("ortho", ortho); + if (ortho.isTable()) { + StartView.Ortho = true; + StartView.OrthoLeft = ortho.GetMemberFloat("left", StartView.OrthoLeft); + StartView.OrthoRight = ortho.GetMemberFloat("right", StartView.OrthoRight); + StartView.OrthoTop = ortho.GetMemberFloat("top", StartView.OrthoTop); + StartView.OrthoBottom = ortho.GetMemberFloat("bottom", StartView.OrthoBottom); + } + else + StartView.Ortho = false; + + StartView.DoBloomAndToneMapping = data.GetMemberBool("bloomtone", false); + + // todo: poster + + render.Push3DView(in StartView, 0, null, view.GetFrustum(), null); + Start3DCount++; + + ortho.UnReference(); + offCenter.UnReference(); + data.UnReference(); + return 0; + } + + [LuaFunction] + static int End(ILuaInterface lua) { + if (Start3DCount < 1) { + lua.ErrorFromLua("cam.End underflow\n"); + return 0; + } + + Start3DCount--; + render.PopView(view.GetFrustum()); + return 0; + } + + [LuaFunction] + static int End3D(ILuaInterface lua) { + if (Start3DCount < 1) { + lua.ErrorFromLua("cam.End3D underflow\n"); + return 0; + } + + Start3DCount--; + render.PopView(view.GetFrustum()); + return 0; + } + + [LuaFunction] + static int End2D(ILuaInterface lua) { + if (Start2DCount < 1) { + lua.ErrorFromLua("cam.End3D underflow\n"); + return 0; + } + + Start2DCount--; + using MatRenderContextPtr renderContext = new(materials); + renderContext.OverrideAlphaWriteEnable(false, false); + ((ClientModeShared)clientMode).SetupGModSurface(false); + ClientModeShared.SetupVGuiMatrices(false, renderContext); + return 0; + } + + [LuaFunction] + static int StartOrthoView(ILuaInterface lua) { + float left = (float)lua.CheckNumber(1); + float top = (float)lua.CheckNumber(2); + float right = (float)lua.CheckNumber(3); + float bottom = (float)lua.CheckNumber(4); + + using MatRenderContextPtr renderContext = new(materials); + renderContext.MatrixMode(MaterialMatrixMode.Projection); + renderContext.PushMatrix(); + renderContext.LoadIdentity(); + renderContext.Scale(1, -1, 1); + renderContext.Ortho(left, top, right, bottom, -99999.0, 99999.0); + OrthoViewCount++; + return 0; + } + + [LuaFunction] + static int EndOrthoView(ILuaInterface lua) { + if (OrthoViewCount > 0) { + OrthoViewCount--; + using MatRenderContextPtr renderContext = new(materials); + renderContext.MatrixMode(MaterialMatrixMode.Projection); + renderContext.PopMatrix(); + return 0; + } + + lua.ErrorFromLua("cam.EndOrthoView underflow\n"); + return 0; + } + + [LuaFunction] + static int IgnoreZ(ILuaInterface lua) { + using MatRenderContextPtr renderContext = new(materials); + if (lua.GetBool(1)) + renderContext.DepthRange(0, 0.01f); + else + renderContext.DepthRange(0, 1); + return 0; + } + + static int Start3D2DCount; + static int ModelMatrixCount; + + [LuaFunction] + static int Start3D2D(ILuaInterface lua) { + ref QAngle angles = ref LuaAngle.Get_Angle(2); + ref Vector3 origin = ref LuaVector.Get_Vector(1); + + Matrix4x4 matrix = default; + matrix.SetupMatrixOrgAngles(origin, angles); + float scale = (float)lua.CheckNumber(3); + MathLib.MatrixBuildScale(out Matrix4x4 scaleMatrix, scale, -scale, 1.0f); + MathLib.MatrixMultiply(matrix, scaleMatrix, out Matrix4x4 result); + + using MatRenderContextPtr renderContext = new(materials); + renderContext.MatrixMode(MaterialMatrixMode.Model); + renderContext.PushMatrix(); + renderContext.LoadMatrix(result); + renderContext.OverrideDepthEnable(true, false); + renderContext.GMOD_ForceFilterMode(true, 3); + renderContext.GMOD_ForceFilterMode(false, 3); + Start3D2DCount++; + return 0; + } + + [LuaFunction] + static int End3D2D(ILuaInterface lua) { + if (Start3D2DCount < 1) { + lua.ErrorFromLua("cam.End3D2D underflow\n"); + return 0; + } + + Start3D2DCount--; + using MatRenderContextPtr renderContext = new(materials); + renderContext.MatrixMode(MaterialMatrixMode.Model); + renderContext.PopMatrix(); + renderContext.OverrideDepthEnable(false, true); + renderContext.GMOD_ForceFilterMode(true, 0); + renderContext.GMOD_ForceFilterMode(false, 0); + return 0; + } + + [LuaFunction] + static int PushModelMatrix(ILuaInterface lua) { + ref Matrix4x4 matrix = ref LuaVMatrix.Get_VMatrix(1); + + using MatRenderContextPtr renderContext = new(materials); + Matrix4x4 result; + if (lua.GetType(2) != LuaType.Nil && lua.GetBool(2)) { + renderContext.GetMatrix(MaterialMatrixMode.Model, out Matrix4x4 current); + MathLib.MatrixMultiply(current, matrix, out result); + } + else + result = matrix; + + renderContext.MatrixMode(MaterialMatrixMode.Model); + renderContext.PushMatrix(); + renderContext.LoadMatrix(result); + ModelMatrixCount++; + return 0; + } + + [LuaFunction] + static int PopModelMatrix(ILuaInterface lua) { + if (ModelMatrixCount > 0) { + using MatRenderContextPtr renderContext = new(materials); + renderContext.MatrixMode(MaterialMatrixMode.Model); + renderContext.PopMatrix(); + ModelMatrixCount--; + return 0; + } + + Warning("cam.PopModelMatrix: Matrix stack is empty!\n"); + return 0; + } + + [LuaFunction] + static int GetModelMatrix(ILuaInterface lua) { + using MatRenderContextPtr renderContext = new(materials); + renderContext.GetMatrix(MaterialMatrixMode.Model, out Matrix4x4 matrix); + LuaVMatrix.Push_VMatrix(matrix); + return 1; + } + + [LuaFunction] + static int GetProjectionMatrix(ILuaInterface lua) { + using MatRenderContextPtr renderContext = new(materials); + renderContext.GetMatrix(MaterialMatrixMode.Projection, out Matrix4x4 matrix); + LuaVMatrix.Push_VMatrix(matrix); + return 1; + } + + [LuaFunction] + static int GetViewMatrix(ILuaInterface lua) { + using MatRenderContextPtr renderContext = new(materials); + renderContext.GetMatrix(MaterialMatrixMode.View, out Matrix4x4 matrix); + LuaVMatrix.Push_VMatrix(matrix); + return 1; + } + + [LuaFunction] + static int ApplyShake(ILuaInterface lua) { + Vector3 origin = LuaVector.Get_Vector(1); + QAngle angles = LuaAngle.Get_Angle(2); + float factor = (float)lua.CheckNumber(3); + vieweffects.CalcShake(); + vieweffects.ApplyShake(ref origin, ref angles, factor); + LuaVector.Push_Vector(origin); + LuaAngle.Push_Angle(angles); + return 2; + } +} diff --git a/Game.Client/GarrysMod/LuaRender.cs b/Game.Client/GarrysMod/LuaRender.cs index 29dfb9ad0..c171e9ba9 100644 --- a/Game.Client/GarrysMod/LuaRender.cs +++ b/Game.Client/GarrysMod/LuaRender.cs @@ -1,7 +1,11 @@ using Source; +using Source.Common; using Source.Common.Bitmap; +using Source.Common.Client; +using Source.Common.GUI; using Source.Common.GarrysMod.Lua; using Source.Common.MaterialSystem; +using Source.Engine; using TextureFlags = Source.Common.TextureFlags; @@ -173,6 +177,7 @@ static int PushRenderTarget(ILuaInterface lua) { texture = (ITexture?)LuaTexture.LC_ITexture.Get(1); using MatRenderContextPtr renderContext = new(materials); + renderContext.Flush(false); if (lua.GetType(2) == LuaType.Number) renderContext.PushRenderTargetAndViewport(texture, (int)lua.CheckNumber(2), (int)lua.CheckNumber(3), (int)lua.CheckNumber(4), (int)lua.CheckNumber(5)); else @@ -187,6 +192,7 @@ static int PopRenderTarget(ILuaInterface lua) { if (RenderTargetStack > 0) { RenderTargetStack--; using MatRenderContextPtr renderContext = new(materials); + renderContext.Flush(false); renderContext.PopRenderTargetAndViewport(); return 0; } @@ -268,6 +274,204 @@ static void SetColorModulation([LuaGet] float r, [LuaGet] float g, [LuaGet] floa [LuaFunction] static float GetBlend() => render.GetBlend(); + public static ViewID RenderViewID = ViewID.Illegal; + public static readonly List DrawViewerStack = []; + + static float UnscaleFOVByWidthRatio(float fovDegrees, float ratio) { + float halfAngleRadians = fovDegrees * (0.5f * MathF.PI / 180.0f); + float t = MathF.Tan(halfAngleRadians); + t /= ratio; + float retDegrees = (180.0f / MathF.PI) * MathF.Atan(t); + return retDegrees * 2.0f; + } + + [LuaFunction] + static int RenderView(ILuaInterface lua) { + ViewSetup setup = view.GetViewSetup(); + LuaTable data = new(null, 0); + data.SetFromStack(1); + + RenderViewInfo whatToDraw = data.GetMemberBool("drawhud", false) ? RenderViewInfo.DrawHUD : 0; + if (data.GetMemberBool("drawviewmodel", true)) + whatToDraw |= RenderViewInfo.DrawViewmodel; + if (!data.GetMemberBool("dopostprocess", false)) + whatToDraw |= RenderViewInfo.NoPostProcess; + if (!data.GetMemberBool("drawmonitors", false)) + whatToDraw |= RenderViewInfo.SuppressMonitorRendering; + bool drawViewer = data.GetMemberBool("drawviewer", false); + setup.DoBloomAndToneMapping = data.GetMemberBool("bloomtone", true); + setup.CacheFullSceneState = false; + + setup.X = (int)data.GetMemberFloat("x", setup.X); + setup.Y = (int)data.GetMemberFloat("y", setup.Y); + setup.Width = (int)data.GetMemberFloat("w", setup.Width); + setup.Height = (int)data.GetMemberFloat("h", setup.Height); + + LuaObject offCenter = new(); + data.GetMember("offcenter", offCenter); + if (offCenter.isTable()) { + setup.OffCenter = true; + float invWidth = 1.0f / setup.Width; + float invHeight = 1.0f / setup.Height; + setup.OffCenterLeft = offCenter.GetMemberFloat("left", setup.OffCenterLeft) * invWidth; + setup.OffCenterRight = offCenter.GetMemberFloat("right", setup.OffCenterRight) * invWidth; + setup.OffCenterTop = offCenter.GetMemberFloat("bottom", setup.OffCenterTop) * invHeight; + setup.OffCenterBottom = offCenter.GetMemberFloat("top", setup.OffCenterBottom) * invHeight; + } + else + setup.OffCenter = false; + + setup.Origin = data.GetMemberVector("origin", setup.Origin); + setup.Angles = data.GetMemberAngle("angles", setup.Angles); + setup.FOV = data.GetMemberFloat("fov", setup.FOV); + setup.FOVViewmodel = data.GetMemberFloat("viewmodelfov", setup.FOVViewmodel); + setup.ZNear = data.GetMemberFloat("znear", setup.ZNear); + setup.ZFar = data.GetMemberFloat("zfar", setup.ZFar); + setup.ZNearViewmodel = data.GetMemberFloat("znearviewmodel", setup.ZNearViewmodel); + setup.ZFarViewmodel = data.GetMemberFloat("zfarviewmodel", setup.ZFarViewmodel); + + LuaObject ortho = new(); + data.GetMember("ortho", ortho); + if (ortho.isTable()) { + setup.Ortho = true; + setup.OrthoLeft = ortho.GetMemberFloat("left", setup.OrthoLeft); + setup.OrthoRight = ortho.GetMemberFloat("right", setup.OrthoRight); + setup.OrthoTop = ortho.GetMemberFloat("top", setup.OrthoTop); + setup.OrthoBottom = ortho.GetMemberFloat("bottom", setup.OrthoBottom); + } + else if (ortho.isBool() && ortho.GetBool()) { + setup.Ortho = true; + setup.OrthoLeft = data.GetMemberFloat("ortholeft", setup.OrthoLeft); + setup.OrthoTop = data.GetMemberFloat("orthotop", setup.OrthoTop); + setup.OrthoRight = data.GetMemberFloat("orthoright", setup.OrthoRight); + setup.OrthoBottom = data.GetMemberFloat("orthobottom", setup.OrthoBottom); + } + else + setup.Ortho = false; + + setup.RenderToSubrectOfLargerScreen = setup.X != 0 || setup.Y != 0 || setup.Width != ScreenWidth() || setup.Height != ScreenHeight(); + + float aspect = engine.GetScreenAspectRatio(); + if (aspect <= 0.0f) + aspect = (float)setup.Width / setup.Height; + aspect = data.GetMemberFloat("aspect", aspect); + setup.AspectRatio = data.GetMemberFloat("aspectratio", aspect); + + if (drawViewer) + DrawViewerStack.Add(true); + + LuaCam.ResetFrameStateChecked(); + RenderViewID = (ViewID)Math.Clamp(data.GetMemberInt("viewid", 0), 0, 9); + view.RenderView(in setup, ClearFlags.ClearColor | ClearFlags.ClearDepth | ClearFlags.ClearStencil, whatToDraw); + RenderViewID = ViewID.Illegal; + + if (drawViewer) + DrawViewerStack.RemoveAt(DrawViewerStack.Count - 1); + + LuaCam.ResetFrameStateChecked(); + ortho.UnReference(); + offCenter.UnReference(); + data.UnReference(); + return 0; + } + + [LuaFunction] + static int GetViewSetup(ILuaInterface lua) { + ref ViewSetup setup = ref view.GetPlayerViewSetup(); + if (lua.GetType(1) != LuaType.Nil && lua.GetBool(1)) + setup = ref view.GetViewSetup(); + + LuaTable table = new(null, 0); + table.SetMemberAngle("angles", setup.Angles); + table.SetMemberVector("origin", setup.Origin); + table.SetMember("height", setup.Height); + table.SetMember("width", setup.Width); + table.SetMember("x", setup.X); + table.SetMember("y", setup.Y); + table.SetMember("znear", setup.ZNear); + table.SetMember("zfar", setup.ZFar); + table.SetMember("znearviewmodel", setup.ZNearViewmodel); + table.SetMember("zfarviewmodel", setup.ZFarViewmodel); + table.SetMember("fov", setup.FOV); + table.SetMember("fovviewmodel", setup.FOVViewmodel); + table.SetMember("fov_unscaled", UnscaleFOVByWidthRatio(setup.FOV, setup.AspectRatio / (4.0f / 3.0f))); + table.SetMember("fovviewmodel_unscaled", UnscaleFOVByWidthRatio(setup.FOVViewmodel, setup.AspectRatio / (4.0f / 3.0f))); + table.SetMember("bloomtone", setup.DoBloomAndToneMapping); + table.SetMember("subrect", setup.RenderToSubrectOfLargerScreen); + table.SetMember("aspect", setup.AspectRatio); + table.SetMember("viewid", (int)ViewRender.g_CurrentViewID); + + if (setup.Ortho) { + LuaTable ortho = new(null, 0); + ortho.SetMember("left", setup.OrthoLeft); + ortho.SetMember("right", setup.OrthoRight); + ortho.SetMember("top", setup.OrthoTop); + ortho.SetMember("bottom", setup.OrthoBottom); + table.SetMember("ortho", ortho); + ortho.UnReference(); + } + + if (setup.OffCenter) { + LuaTable offCenter = new(null, 0); + offCenter.SetMember("left", setup.OffCenterLeft); + offCenter.SetMember("right", setup.OffCenterRight); + offCenter.SetMember("top", setup.OffCenterTop); + offCenter.SetMember("bottom", setup.OffCenterBottom); + table.SetMember("offcenter", offCenter); + offCenter.UnReference(); + } + + table.Push(); + table.UnReference(); + return 1; + } + + [LuaFunction] + static int RenderHUD(ILuaInterface lua) { + int x = (int)lua.CheckNumber(1); + int y = (int)lua.CheckNumber(2); + int w = (int)lua.CheckNumber(3); + int h = (int)lua.CheckNumber(4); + + using MatRenderContextPtr renderContext = new(materials); + LuaCam.SetInSurface3D(true); + + ViewSetup hudView = default; + hudView.X = x; + hudView.Y = y; + hudView.Width = w; + hudView.Height = h; + hudView.Origin = vec3_origin; + hudView.Angles = default; + hudView.RenderToSubrectOfLargerScreen = false; + hudView.AspectRatio = 0; + hudView.OffCenter = false; + hudView.DoBloomAndToneMapping = true; + hudView.CacheFullSceneState = false; + hudView.ViewToProjectionOverride = false; + hudView.Ortho = false; + hudView.UnscaledHeight = 0; + render.Push2DView(hudView, 0, renderContext.GetRenderTarget(), view.GetFrustum()); + + IPanel? clientDll = enginevgui.GetPanel(VGuiPanelType.ClientDll); + if (clientDll != null) { + clientDll.SetPos(hudView.X, hudView.Y); + clientDll.SetSize(hudView.Width, hudView.Height); + } + + IPanel? clientDllTools = enginevgui.GetPanel(VGuiPanelType.ClientDllTools); + if (clientDllTools != null) { + clientDllTools.SetPos(hudView.X, hudView.Y); + clientDllTools.SetSize(hudView.Width, hudView.Height); + } + + render.VGui_Paint(PaintMode.InGamePanels); + renderContext.Flush(false); + render.PopView(view.GetFrustum()); + LuaCam.SetInSurface3D(false); + return 0; + } + // todo: SetViewPort // todo: Clear // todo: ClearDepth diff --git a/Game.Client/IViewRender.cs b/Game.Client/IViewRender.cs index 04afd211c..ad320a343 100644 --- a/Game.Client/IViewRender.cs +++ b/Game.Client/IViewRender.cs @@ -11,7 +11,8 @@ public enum RenderViewInfo Unspecified = 0, DrawViewmodel = 1 << 0, DrawHUD = 1 << 1, - SuppressMonitorRendering = 1 << 2 + SuppressMonitorRendering = 1 << 2, + NoPostProcess = 1 << 3 } [Flags] public enum DrawFlags diff --git a/Game.Shared/GarrysMod/LuaVMatrix.cs b/Game.Shared/GarrysMod/LuaVMatrix.cs new file mode 100644 index 000000000..7fbc447cb --- /dev/null +++ b/Game.Shared/GarrysMod/LuaVMatrix.cs @@ -0,0 +1,71 @@ +#if CLIENT_DLL || GAME_DLL +using Source.Common.GarrysMod.Lua; +using Source.Common.Mathematics; + +using System.Numerics; +using System.Runtime.InteropServices; + +#if CLIENT_DLL +namespace Game.Client.GarrysMod; +#else +namespace Game.Server.GarrysMod; +#endif + +public static partial class LuaVMatrix +{ + [LuaClass(typeof(Matrix4x4))] + public static readonly LuaClass LC_VMatrix = new("VMatrix", LuaType.Matrix, null, null); + + public static ref Matrix4x4 Get_VMatrix(int stackPos) => ref LC_VMatrix.GetValue(stackPos); + + public static void Push_VMatrix(in Matrix4x4 matrix) => g_Lua!.PushValueUserType(matrix, LuaType.Matrix); + + [LuaGlobal] + static int Matrix(ILuaInterface lua) { + Matrix4x4 matrix = default; + LuaType type = lua.GetType(1); + if (type == LuaType.Table) { + LuaObject table = new(1, LuaType.None); + LuaObject row = new(); + LuaObject element = new(); + Span elements = MemoryMarshal.CreateSpan(ref matrix.M11, 16); + for (int r = 1; r <= 4; r++) { + table.GetMember((float)r, row); + if (!row.isTable()) { + g_Lua!.Error($"bad row ({r}) from argument #1 of 'Matrix' (table expected, got {g_Lua.GetTypeName(row.GetType())})"); + element.UnReference(); + row.UnReference(); + table.UnReference(); + return 0; + } + + for (int c = 1; c <= 4; c++) { + row.GetMember((float)c, element); + if (!element.isNumber()) { + g_Lua!.Error($"bad element ({r}, {c}) from argument #1 of 'Matrix' (number expected, got {g_Lua.GetTypeName(element.GetType())})"); + element.UnReference(); + row.UnReference(); + table.UnReference(); + return 0; + } + elements[(r - 1) * 4 + (c - 1)] = element.GetFloat(); + } + } + element.UnReference(); + row.UnReference(); + table.UnReference(); + } + else if (type == LuaType.Nil) + MathLib.SetIdentityMatrix(out matrix); + else if (type == LuaType.Matrix) + matrix = Get_VMatrix(1); + else { + g_Lua!.Error($"bad argument #1 to 'Matrix' (table, VMatrix or nil expected, got {g_Lua.GetTypeName(type)})"); + return 0; + } + + Push_VMatrix(matrix); + return 1; + } +} +#endif diff --git a/Source.MaterialSystem/MatRenderContext.cs b/Source.MaterialSystem/MatRenderContext.cs index 4a2c98de1..a9fd29ce8 100644 --- a/Source.MaterialSystem/MatRenderContext.cs +++ b/Source.MaterialSystem/MatRenderContext.cs @@ -1011,9 +1011,7 @@ public int OcclusionQuery_GetNumPixelsRendered(OcclusionQueryObjectHandle_t hand throw new NotImplementedException("Incomplete port of IMatRenderContext"); } - public void OverrideAlphaWriteEnable(bool enable, bool alphaWriteEnable) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void OverrideAlphaWriteEnable(bool enable, bool alphaWriteEnable) => shaderAPI.OverrideAlphaWriteEnable(enable, alphaWriteEnable); public void OverrideBlend(bool unk1, bool unk2, int unk3, int unk4, int unk5) { throw new NotImplementedException("Incomplete port of IMatRenderContext"); @@ -1027,9 +1025,7 @@ public void OverrideColorWriteEnable(bool overrideEnable, bool colorWriteEnable) throw new NotImplementedException("Incomplete port of IMatRenderContext"); } - public void OverrideDepthEnable(bool enable, bool depthEnable) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void OverrideDepthEnable(bool enable, bool depthEnable) => shaderAPI.OverrideDepthEnable(enable, depthEnable); public void PerformFullScreenStencilOperation() { throw new NotImplementedException("Incomplete port of IMatRenderContext"); diff --git a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs index 2eb151583..4fa49e05e 100644 --- a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs +++ b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs @@ -2442,14 +2442,23 @@ public bool SetBoardState(in GraphicsBoardState state) { glBlendEquation(state.BlendOperation.GLEnum()); } - if (force || state.ColorWrite != last.ColorWrite || state.AlphaWrite != last.AlphaWrite) - glColorMask(state.ColorWrite, state.ColorWrite, state.ColorWrite, state.AlphaWrite); + bool alphaWrite = OverrideAlphaWrite ? OverriddenAlphaWriteValue : state.AlphaWrite; + if (force || state.ColorWrite != last.ColorWrite || alphaWrite != AppliedAlphaWrite) { + glColorMask(state.ColorWrite, state.ColorWrite, state.ColorWrite, alphaWrite); + AppliedAlphaWrite = alphaWrite; + } - if (force || state.DepthTest != last.DepthTest) - glToggle(GL_DEPTH_TEST, state.DepthTest); + bool depthTest = OverrideDepth || state.DepthTest; + if (force || depthTest != AppliedDepthTest) { + glToggle(GL_DEPTH_TEST, depthTest); + AppliedDepthTest = depthTest; + } - if (force || state.DepthWrite != last.DepthWrite) - glDepthMask(state.DepthWrite); + bool depthWrite = OverrideDepth ? OverriddenDepthWriteValue : state.DepthWrite; + if (force || depthWrite != AppliedDepthWrite) { + glDepthMask(depthWrite); + AppliedDepthWrite = depthWrite; + } if (force || state.DepthFunc != last.DepthFunc) glDepthFunc(state.DepthFunc.GLEnum()); @@ -3183,8 +3192,17 @@ public int OcclusionQuery_GetNumPixelsRendered(ShaderAPIOcclusionQuery_t query, throw new NotImplementedException("Incomplete port of IShaderAPI"); } + bool OverrideAlphaWrite; + bool OverriddenAlphaWriteValue; + bool AppliedAlphaWrite; + public void OverrideAlphaWriteEnable(bool enable, bool alphaWriteEnable) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + if (enable != OverrideAlphaWrite) { + FlushBufferedPrimitives(); + OverrideAlphaWrite = enable; + OverriddenAlphaWriteValue = alphaWriteEnable; + lastBoardUploadHash = 0; + } } public void OverrideBlend(bool overrideEnable, bool useSeparateAlpha, int srcBlend, int destBlend, int blendFunc) { @@ -3199,8 +3217,18 @@ public void OverrideColorWriteEnable(bool overrideEnable, bool colorWriteEnable) throw new NotImplementedException("Incomplete port of IShaderAPI"); } - public void OverrideDepthEnable(bool bEnable, bool bDepthEnable) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + bool OverrideDepth; + bool OverriddenDepthWriteValue; + bool AppliedDepthTest; + bool AppliedDepthWrite; + + public void OverrideDepthEnable(bool enable, bool depthEnable) { + if (enable != OverrideDepth) { + FlushBufferedPrimitives(); + OverrideDepth = enable; + OverriddenDepthWriteValue = depthEnable; + lastBoardUploadHash = 0; + } } public bool OwnGPUResources(bool bEnable) { From 9b017e3572e1c2de1ebba763c1cfcff58808c3b6 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Thu, 8 Oct 2026 07:01:06 +0100 Subject: [PATCH 06/23] Some render hooks --- Game.Client/C_BaseEntity.cs | 11 ++++++++ Game.Client/GarrysMod/IntroScreen.cs | 2 -- Game.Client/ViewRender.cs | 28 +++++++++++++++++++ Game.Shared/GarrysMod/LuaEntity.cs | 23 +++++++++++++++ Source.Common/Filesystem/IFileSystem.cs | 2 ++ Source.Common/GUI/ISurface.cs | 3 -- .../Surface/MatSystemSurface.cs | 26 ++++++++++++++--- 7 files changed, 86 insertions(+), 9 deletions(-) diff --git a/Game.Client/C_BaseEntity.cs b/Game.Client/C_BaseEntity.cs index 308ef6a1e..39fbd0e4c 100644 --- a/Game.Client/C_BaseEntity.cs +++ b/Game.Client/C_BaseEntity.cs @@ -2110,6 +2110,17 @@ public ref Matrix3x4 EntityToWorldTransform() { return ref CoordinateFrame; } + public virtual void GetVectors(out Vector3 forward, out Vector3 right, out Vector3 up) { + ref readonly Matrix3x4 entityToWorld = ref EntityToWorldTransform(); + + MathLib.MatrixGetColumn(entityToWorld, 0, out forward); + + MathLib.MatrixGetColumn(entityToWorld, 1, out right); + right *= -1.0f; + + MathLib.MatrixGetColumn(entityToWorld, 2, out up); + } + public ref Vector3 GetNetworkOrigin() => ref NetworkOrigin; public ref readonly Vector3 GetOldOrigin() => ref OldOrigin; public ref QAngle GetNetworkAngles() => ref NetworkAngles; diff --git a/Game.Client/GarrysMod/IntroScreen.cs b/Game.Client/GarrysMod/IntroScreen.cs index d04bcda7f..f351fc147 100644 --- a/Game.Client/GarrysMod/IntroScreen.cs +++ b/Game.Client/GarrysMod/IntroScreen.cs @@ -74,9 +74,7 @@ public void Update(ReadOnlySpan status, bool step) { renderContext.PushMatrix(); renderContext.LoadIdentity(); - surface.SetInDrawing(true); DoDraw(ref renderContext, status, width, height, progress); - surface.SetInDrawing(false); renderContext.MatrixMode(MaterialMatrixMode.Projection); renderContext.PopMatrix(); diff --git a/Game.Client/ViewRender.cs b/Game.Client/ViewRender.cs index 3a8c5ba9c..aefa79c68 100644 --- a/Game.Client/ViewRender.cs +++ b/Game.Client/ViewRender.cs @@ -312,6 +312,17 @@ protected void DrawOpaqueRenderables(RenderDepthMode depthMode) { render.SetBlend(1); + DrawFlags drawFlags = GetDrawFlags(); +#if GMOD_DLL + if (depthMode == RenderDepthMode.Normal && gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PreDrawOpaqueRenderables)) { + g_Lua!.PushBool(false); + g_Lua.PushBool((drawFlags & DrawFlags.DrawSkybox) != 0); + g_Lua.PushBool(SkyboxView.Rendering3DSkybox); + if (gGM.CallFinish(3)) + return; + } +#endif + // todo, this has more // First do the brush models @@ -322,6 +333,15 @@ protected void DrawOpaqueRenderables(RenderDepthMode depthMode) { DrawOpaqueRenderables_Range(RenderGroup.OpaqueEntityHuge + 2 * bucket, depthMode); DrawOpaqueRenderables_DrawStaticProps(RenderGroup.OpaqueStaticHuge + 2 * bucket, depthMode); } + +#if GMOD_DLL + if (depthMode == RenderDepthMode.Normal && gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PostDrawOpaqueRenderables)) { + g_Lua!.PushBool(false); + g_Lua.PushBool((drawFlags & DrawFlags.DrawSkybox) != 0); + g_Lua.PushBool(SkyboxView.Rendering3DSkybox); + gGM.CallNoReturns(3); + } +#endif } private void DrawOpaqueRenderable(IClientRenderable ent, bool twoPass, RenderDepthMode depthMode, StudioFlags defaultFlags = 0) { @@ -576,6 +596,7 @@ private DrawWorldListFlags BuildEngineDrawWorldListFlags(DrawFlags drawFlags) { public class SkyboxView : Rendering3dView { + public static bool Rendering3DSkybox; SafeFieldPointer Sky3dParams = new(); public SkyboxView(ViewRender mainView) : base(mainView) { @@ -624,6 +645,7 @@ private void DrawInternal(ViewID skyBoxViewID, bool invokePreAndPostRender, ITex if (sky3dParams.Scale > 0) setup.Origin *= 1f / sky3dParams.Scale; setup.Origin += sky3dParams.Origin; + Rendering3DSkybox = true; render.ViewSetupVisEx(false, new(ref sky3dParams.Origin), out _); render.Push3DView(in setup, ClearFlags, rtColor, GetFrustrum(), rtDepth); @@ -658,6 +680,12 @@ private void DrawInternal(ViewID skyBoxViewID, bool invokePreAndPostRender, ITex } render.PopView(GetFrustrum()); + +#if GMOD_DLL + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PostDrawSkyBox) && gGM.CallFinish(0)) + return; +#endif + Rendering3DSkybox = false; } private SafeFieldPointer PreRender3dSkyboxWorld(ref SkyboxVisibility skyboxVisible) { diff --git a/Game.Shared/GarrysMod/LuaEntity.cs b/Game.Shared/GarrysMod/LuaEntity.cs index 0bd94ffc1..45791dbe7 100644 --- a/Game.Shared/GarrysMod/LuaEntity.cs +++ b/Game.Shared/GarrysMod/LuaEntity.cs @@ -2,6 +2,7 @@ using Source.Common; using Source.Common.GarrysMod.Lua; +using System.Numerics; using System.Runtime.InteropServices; #if CLIENT_DLL @@ -187,6 +188,28 @@ static int Entity__IsValid(ILuaInterface lua) { return 1; } + [LuaMethod] + static int Entity__GetPos(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + LuaVector.Push_Vector(ent.GetAbsOrigin()); + return 1; + } + + [LuaMethod] + static int Entity__GetForward(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + ent.GetVectors(out Vector3 forward, out _, out _); + LuaVector.Push_Vector(forward); + return 1; + } + + [LuaMethod] + static int Entity__EyeAngles(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + LuaAngle.Push_Angle(ent.EyeAngles()); + return 1; + } + [LuaMethod] static int Entity__EyePos(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; diff --git a/Source.Common/Filesystem/IFileSystem.cs b/Source.Common/Filesystem/IFileSystem.cs index 7088afc52..bace02586 100644 --- a/Source.Common/Filesystem/IFileSystem.cs +++ b/Source.Common/Filesystem/IFileSystem.cs @@ -164,6 +164,8 @@ public static ReadOnlySpan Concat(ISearchPath searchPath, scoped ReadOnlyS fileName = fileName[1..]; fileName.ClampedCopyTo(target[writePtr..]); writePtr += fileName.Length; + if (writePtr < target.Length) + target[writePtr] = '\0'; return target[..writePtr]; } } diff --git a/Source.Common/GUI/ISurface.cs b/Source.Common/GUI/ISurface.cs index 0c3899924..3812c81f4 100644 --- a/Source.Common/GUI/ISurface.cs +++ b/Source.Common/GUI/ISurface.cs @@ -241,9 +241,6 @@ public interface IMatSystemSurface : ISurface int GetTextureNumFrames(in TextureID id); void DrawSetTextureFrame(in TextureID id, int frame, ref TokenCache frameCache); void DrawSetTextureMaterial(TextureID textureID, IMaterial material); -#if GMOD_DLL - void SetInDrawing(bool inDrawing); -#endif void SetFullscreenViewportAndRenderTarget(int x, int y, int w, int h, ITexture? renderTarget); void GetFullscreenViewport(out int x, out int y, out int w, out int h); void OnScreenSizeChanged(int oldWidth, int oldHeight); diff --git a/Source.MaterialSystem/Surface/MatSystemSurface.cs b/Source.MaterialSystem/Surface/MatSystemSurface.cs index d7065b8d9..9a2c6d35b 100644 --- a/Source.MaterialSystem/Surface/MatSystemSurface.cs +++ b/Source.MaterialSystem/Surface/MatSystemSurface.cs @@ -399,10 +399,6 @@ public void CreatePopup(IPanel panel, bool minimised, bool showTaskbarIcon = tru } } -#if GMOD_DLL - public void SetInDrawing(bool inDrawing) => InDrawing = inDrawing; -#endif - public void DestroyTextureID(in TextureID id) { TextureDictionary.DestroyTexture(id); } @@ -413,7 +409,9 @@ public bool DeleteTextureByID(in TextureID id) { } public void DrawFilledRect(int x0, int y0, int x1, int y1) { +#if !GMOD_DLL Assert(InDrawing); +#endif if (FullyTransparent) return; @@ -431,7 +429,9 @@ public void DrawFilledRect(int x0, int y0, int x1, int y1) { } public void DrawFilledRectArray(Span rects, int numRects) { +#if !GMOD_DLL Assert(InDrawing); +#endif if (FullyTransparent) return; @@ -518,7 +518,9 @@ public void DrawGetTextureSize(in TextureID id, out int wide, out int tall) { } public void DrawLine(int x0, int y0, int x1, int y1) { +#if !GMOD_DLL Assert(InDrawing); +#endif if (FullyTransparent) return; @@ -605,7 +607,9 @@ public void DrawOutlinedRect(int x0, int y0, int x1, int y1) { } public void DrawOutlinedCircle(int x, int y, int radius, int segments) { +#if !GMOD_DLL Assert(InDrawing); +#endif Assert(!In3DPaintMode); if (FullyTransparent) @@ -661,7 +665,9 @@ public void DrawPolyLine(Span points) { IFont? CurrentFont; public void DrawPrintText(ReadOnlySpan text, FontDrawType drawType = FontDrawType.Default) { +#if !GMOD_DLL Assert(InDrawing); +#endif if (text.IsEmpty) return; @@ -878,7 +884,9 @@ public void DrawUpdateRegionTextureRGBA(in TextureID id, int x, int y, nint rgba } public void DrawTexturedRect(int x0, int y0, int x1, int y1) { +#if !GMOD_DLL Assert(InDrawing); +#endif if (DrawColor.A == 0) return; @@ -900,7 +908,9 @@ public void DrawTexturedRect(int x0, int y0, int x1, int y1) { } public void DrawTexturedSubRect(int x0, int y0, int x1, int y1, float s0, float t0, float s1, float t1) { +#if !GMOD_DLL Assert(InDrawing); +#endif if (DrawColor.A == 0) return; @@ -1190,7 +1200,9 @@ private void FinishDrawing() { renderContext.MatrixMode(MaterialMatrixMode.View); renderContext.PopMatrix(); +#if !GMOD_DLL Assert(InDrawing); +#endif InDrawing = false; } @@ -1286,7 +1298,9 @@ void RemovePopup(IPanel panel) { public void DrawTexturedPolygon(Span vertices, bool clipVertices = true) { Assert(!In3DPaintMode); +#if !GMOD_DLL Assert(InDrawing); +#endif // Don't even bother drawing fully transparent junk if (vertices.IsEmpty || vertices.Length == 0 || DrawColor[3] == 0) @@ -1868,7 +1882,9 @@ public void DrawRenderCharFromInfo(CharRenderInfo info) { } private void DrawRenderCharInternal(CharRenderInfo info) { +#if !GMOD_DLL Assert(InDrawing); +#endif if (info.ShouldClip) { Span clip = [info.Verts[0], info.Verts[1]]; @@ -1887,7 +1903,9 @@ private void DrawRenderCharInternal(CharRenderInfo info) { public bool DrawGetCharRenderInfo(char ch, ref CharRenderInfo info) { +#if !GMOD_DLL Assert(InDrawing); +#endif info.Valid = false; if (CurrentFont == null) From e04fa60a55f2a7af0e6409849a1ff242fd7957ef Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Thu, 8 Oct 2026 14:15:18 +0100 Subject: [PATCH 07/23] LuaVMatrix --- Game.Client/GarrysMod/LuaMaterial.cs | 32 +++ Game.Client/GarrysMod/LuaTexture.cs | 3 + Game.Shared/GarrysMod/LuaVMatrix.cs | 387 ++++++++++++++++++++++++++- Source.Common/Mathematics/MathLib.cs | 153 ++++++++++- 4 files changed, 573 insertions(+), 2 deletions(-) diff --git a/Game.Client/GarrysMod/LuaMaterial.cs b/Game.Client/GarrysMod/LuaMaterial.cs index 9c81dfea9..f24998bd6 100644 --- a/Game.Client/GarrysMod/LuaMaterial.cs +++ b/Game.Client/GarrysMod/LuaMaterial.cs @@ -168,6 +168,38 @@ static int IMaterial__SetTexture(ILuaInterface lua) { return 0; } + [LuaMethod] + static int IMaterial__GetMatrix(ILuaInterface lua) { + IMaterial? material = (IMaterial?)LC_IMaterial.Get(1); + if (material == null) { + lua.Error("Tried to use a NULL IMaterial!"); + return 0; + } + + IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + if (var == null || !found) + return 0; + + LuaVMatrix.Push_VMatrix(var.GetMatrixValue()); + return 1; + } + + [LuaMethod] + static int IMaterial__SetMatrix(ILuaInterface lua) { + IMaterial? material = (IMaterial?)LC_IMaterial.Get(1); + if (material == null) { + lua.Error("Tried to use a NULL IMaterial!"); + return 0; + } + + IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + if (var == null || !found) + return 0; + + var.SetMatrixValue(LuaVMatrix.Get_VMatrix(3)); + return 0; + } + static bool IsAllowedMaterialPath(ReadOnlySpan name) { Span buffer = stackalloc char[MAX_PATH]; strcpy(buffer, name); diff --git a/Game.Client/GarrysMod/LuaTexture.cs b/Game.Client/GarrysMod/LuaTexture.cs index e7770fc35..1920b6dcc 100644 --- a/Game.Client/GarrysMod/LuaTexture.cs +++ b/Game.Client/GarrysMod/LuaTexture.cs @@ -18,4 +18,7 @@ public static void Push(ITexture? texture) { [LuaMethod] static int ITexture__Height(ITexture texture) => texture.GetActualHeight(); + + [LuaMethod] + static string ITexture__GetName(ITexture texture) => new(texture.GetName()); } diff --git a/Game.Shared/GarrysMod/LuaVMatrix.cs b/Game.Shared/GarrysMod/LuaVMatrix.cs index 7fbc447cb..4a66e25fc 100644 --- a/Game.Shared/GarrysMod/LuaVMatrix.cs +++ b/Game.Shared/GarrysMod/LuaVMatrix.cs @@ -16,10 +16,395 @@ public static partial class LuaVMatrix [LuaClass(typeof(Matrix4x4))] public static readonly LuaClass LC_VMatrix = new("VMatrix", LuaType.Matrix, null, null); - public static ref Matrix4x4 Get_VMatrix(int stackPos) => ref LC_VMatrix.GetValue(stackPos); + public static ref Matrix4x4 Get_VMatrix(int stackPos) { + ref Matrix4x4 matrix = ref LC_VMatrix.GetValue(stackPos); + nint ud = g_Lua!.GetUserdata(stackPos); + if (ud == 0 || Marshal.ReadIntPtr(ud) == 0) + g_Lua.Error("Tried to use a NULL VMatrix!"); + return ref matrix; + } public static void Push_VMatrix(in Matrix4x4 matrix) => g_Lua!.PushValueUserType(matrix, LuaType.Matrix); + static bool MatrixIsZero(in Matrix4x4 m) { + return m.M11 == 0 && m.M12 == 0 && m.M13 == 0 && m.M14 == 0 && + m.M21 == 0 && m.M22 == 0 && m.M23 == 0 && m.M24 == 0 && + m.M31 == 0 && m.M32 == 0 && m.M33 == 0 && m.M34 == 0 && + m.M41 == 0 && m.M42 == 0 && m.M43 == 0 && m.M44 == 0; + } + + [LuaMethod] + static int VMatrix____eq(ILuaInterface lua) { + ref Matrix4x4 a = ref Get_VMatrix(1); + ref Matrix4x4 b = ref Get_VMatrix(2); + lua.PushBool(a == b); + return 1; + } + + [LuaMethod] + static int VMatrix____add(ILuaInterface lua) { + ref Matrix4x4 a = ref Get_VMatrix(1); + ref Matrix4x4 b = ref Get_VMatrix(2); + Push_VMatrix(a + b); + return 1; + } + + [LuaMethod] + static int VMatrix____sub(ILuaInterface lua) { + ref Matrix4x4 a = ref Get_VMatrix(1); + ref Matrix4x4 b = ref Get_VMatrix(2); + Push_VMatrix(a - b); + return 1; + } + + [LuaMethod] + static int VMatrix____unm(ILuaInterface lua) { + ref Matrix4x4 a = ref Get_VMatrix(1); + Push_VMatrix(-a); + return 1; + } + + [LuaMethod] + static int VMatrix____mul(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + if (lua.GetType(2) == LuaType.Vector) { + MathLib.Vector3DMultiplyPosition(in m, in LuaVector.Get_Vector(2), out Vector3 ret); + LuaVector.Push_Vector(ret); + return 1; + } + if (lua.GetType(2) != LuaType.Matrix) { + lua.TypeError("Vector or Matrix", 2); + return 0; + } + MathLib.MatrixMultiply(in m, in Get_VMatrix(2), out Matrix4x4 product); + Push_VMatrix(product); + return 1; + } + + [LuaMethod] + static int VMatrix____tostring(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + lua.PushString(string.Create(System.Globalization.CultureInfo.InvariantCulture, $"[{m.M11:F5},\t{m.M12:F5},\t{m.M13:F5},\t{m.M14:F5}]\n[{m.M21:F5},\t{m.M22:F5},\t{m.M23:F5},\t{m.M24:F5}]\n[{m.M31:F5},\t{m.M32:F5},\t{m.M33:F5},\t{m.M34:F5}]\n[{m.M41:F5},\t{m.M42:F5},\t{m.M43:F5},\t{m.M44:F5}]")); + return 1; + } + + [LuaMethod] + static int VMatrix__Add(ILuaInterface lua) { + ref Matrix4x4 a = ref Get_VMatrix(1); + ref Matrix4x4 b = ref Get_VMatrix(2); + a += b; + return 0; + } + + [LuaMethod] + static int VMatrix__Sub(ILuaInterface lua) { + ref Matrix4x4 a = ref Get_VMatrix(1); + ref Matrix4x4 b = ref Get_VMatrix(2); + a -= b; + return 0; + } + + [LuaMethod] + static int VMatrix__Mul(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + MathLib.MatrixMultiply(in m, in Get_VMatrix(2), out Matrix4x4 product); + m = product; + return 0; + } + + [LuaMethod] + static int VMatrix__ToTable(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + Span s = MemoryMarshal.CreateSpan(ref m.M11, 16); + LuaTable table = new(null, 4); + for (int r = 0; r < 4; r++) { + LuaTable row = new(null, 4); + row.SetMemberDouble(1, s[r * 4 + 0]); + row.SetMemberDouble(2, s[r * 4 + 1]); + row.SetMemberDouble(3, s[r * 4 + 2]); + row.SetMemberDouble(4, s[r * 4 + 3]); + table.SetMember(r + 1, row); + row.UnReference(); + } + table.Push(); + table.UnReference(); + return 1; + } + + [LuaMethod] + static int VMatrix__Unpack(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + Span s = MemoryMarshal.CreateSpan(ref m.M11, 16); + for (int i = 0; i < 16; i++) + lua.PushNumber(s[i]); + return 16; + } + + [LuaMethod] + static int VMatrix__SetUnpacked(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + Span s = MemoryMarshal.CreateSpan(ref m.M11, 16); + for (int i = 2; i < 18; i++) + s[i - 2] = (float)lua.CheckNumber(i); + return 0; + } + + [LuaMethod] + static int VMatrix__Set(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + m = Get_VMatrix(2); + return 0; + } + + [LuaMethod] + static int VMatrix__Identity(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + MathLib.SetIdentityMatrix(out m); + return 0; + } + + [LuaMethod] + static int VMatrix__IsIdentity(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + lua.PushBool(m.M11 == 1.0f && m.M12 == 0 && m.M13 == 0 && m.M14 == 0 && + m.M21 == 0 && m.M22 == 1.0f && m.M23 == 0 && m.M24 == 0 && + m.M31 == 0 && m.M32 == 0 && m.M33 == 1.0f && m.M34 == 0 && + m.M41 == 0 && m.M42 == 0 && m.M43 == 0 && m.M44 == 1.0f); + return 1; + } + + [LuaMethod] + static int VMatrix__Zero(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + m = default; + return 0; + } + + [LuaMethod] + static int VMatrix__IsZero(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + lua.PushBool(MatrixIsZero(in m)); + return 1; + } + + [LuaMethod] + static int VMatrix__IsRotationMatrix(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + lua.PushBool(m.IsRotationMatrix()); + return 1; + } + + [LuaMethod] + static int VMatrix__Invert(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + lua.PushBool(MathLib.MatrixInverseGeneral(in m, out m)); + return 1; + } + + [LuaMethod] + static int VMatrix__GetInverse(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + if (!MathLib.MatrixInverseGeneral(in m, out Matrix4x4 inverse)) + return 0; + Push_VMatrix(inverse); + return 1; + } + + [LuaMethod] + static int VMatrix__InvertTR(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + MathLib.MatrixInverseTR(in m, out Matrix4x4 inverse); + m = inverse; + return 0; + } + + [LuaMethod] + static int VMatrix__GetInverseTR(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + MathLib.MatrixInverseTR(in m, out Matrix4x4 inverse); + Push_VMatrix(inverse); + return 1; + } + + [LuaMethod] + static int VMatrix__SetForward(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + ref Vector3 v = ref LuaVector.Get_Vector(2); + m[0, 0] = v.X; + m[1, 0] = v.Y; + m[2, 0] = v.Z; + return 0; + } + + [LuaMethod] + static int VMatrix__SetRight(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + ref Vector3 v = ref LuaVector.Get_Vector(2); + m[0, 1] = -v.X; + m[1, 1] = -v.Y; + m[2, 1] = -v.Z; + return 0; + } + + [LuaMethod] + static int VMatrix__SetUp(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + ref Vector3 v = ref LuaVector.Get_Vector(2); + m[0, 2] = v.X; + m[1, 2] = v.Y; + m[2, 2] = v.Z; + return 0; + } + + [LuaMethod] + static int VMatrix__GetForward(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + LuaVector.Push_Vector(new(m[0, 0], m[1, 0], m[2, 0])); + return 1; + } + + [LuaMethod] + static int VMatrix__GetRight(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + LuaVector.Push_Vector(new(-m[0, 1], -m[1, 1], -m[2, 1])); + return 1; + } + + [LuaMethod] + static int VMatrix__GetUp(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + LuaVector.Push_Vector(new(m[0, 2], m[1, 2], m[2, 2])); + return 1; + } + + [LuaMethod] + static int VMatrix__GetField(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + int row = (int)lua.CheckNumber(2); + int column = (int)lua.CheckNumber(3); + if ((uint)(row - 1) >= 4 || (uint)(column - 1) >= 4) + return 0; + lua.PushNumber(m[row - 1, column - 1]); + return 1; + } + + [LuaMethod] + static int VMatrix__SetField(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + int row = (int)lua.CheckNumber(2); + int column = (int)lua.CheckNumber(3); + double value = lua.CheckNumber(4); + if ((uint)(row - 1) < 4 && (uint)(column - 1) < 4) + m[row - 1, column - 1] = (float)value; + return 0; + } + + [LuaMethod] + static int VMatrix__Translate(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + MathLib.MatrixMultiply(in m, MathLib.SetupMatrixTranslation(in LuaVector.Get_Vector(2)), out Matrix4x4 product); + m = product; + return 0; + } + + [LuaMethod] + static int VMatrix__Rotate(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + MathLib.MatrixMultiply(in m, MathLib.SetupMatrixAngles(in LuaAngle.Get_Angle(2)), out Matrix4x4 product); + m = product; + return 0; + } + + [LuaMethod] + static int VMatrix__Scale(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + MathLib.MatrixMultiply(in m, MathLib.SetupMatrixScale(in LuaVector.Get_Vector(2)), out Matrix4x4 product); + m = product; + return 0; + } + + [LuaMethod] + static int VMatrix__GetTranslation(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + LuaVector.Push_Vector(new(m[0, 3], m[1, 3], m[2, 3])); + return 1; + } + + [LuaMethod] + static int VMatrix__GetAngles(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + Matrix4x4 normalized = m.NormalizeBasisVectors(); + MathLib.MatrixToAngles(in normalized, out QAngle angles); + LuaAngle.Push_Angle(angles); + return 1; + } + + [LuaMethod] + static int VMatrix__GetScale(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + LuaVector.Push_Vector(m.GetScale()); + return 1; + } + + [LuaMethod] + static int VMatrix__SetTranslation(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + ref Vector3 v = ref LuaVector.Get_Vector(2); + m[0, 3] = v.X; + m[1, 3] = v.Y; + m[2, 3] = v.Z; + return 0; + } + + [LuaMethod] + static int VMatrix__SetAngles(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + QAngle angles = LuaAngle.Get_Angle(2); + Vector3 scale = m.GetScale(); + Matrix4x4 rotation = default; + rotation.SetupMatrixOrgAngles(vec3_origin, in angles); + m[0, 0] = rotation[0, 0] * scale.X; + m[0, 1] = rotation[0, 1] * scale.X; + m[0, 2] = rotation[0, 2] * scale.X; + m[1, 0] = rotation[1, 0] * scale.Y; + m[1, 1] = rotation[1, 1] * scale.Y; + m[1, 2] = rotation[1, 2] * scale.Y; + m[2, 0] = rotation[2, 0] * scale.Z; + m[2, 1] = rotation[2, 1] * scale.Z; + m[2, 2] = rotation[2, 2] * scale.Z; + return 0; + } + + [LuaMethod] + static int VMatrix__SetScale(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + ref Vector3 scale = ref LuaVector.Get_Vector(2); + m.GetBasisVectors(out Vector3 forward, out Vector3 left, out Vector3 up); + MathLib.VectorNormalizeFast(ref forward); + MathLib.VectorNormalizeFast(ref left); + MathLib.VectorNormalizeFast(ref up); + m.SetBasisVectors(forward * scale.X, left * scale.Y, up * scale.Z); + return 0; + } + + [LuaMethod] + static int VMatrix__ScaleTranslation(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + float scale = (float)lua.CheckNumber(2); + m[0, 3] *= scale; + m[1, 3] *= scale; + m[2, 3] *= scale; + return 0; + } + + [LuaMethod] + static int VMatrix__GetTransposed(ILuaInterface lua) { + ref Matrix4x4 m = ref Get_VMatrix(1); + MathLib.MatrixTranspose(in m, out Matrix4x4 transposed); + Push_VMatrix(transposed); + return 1; + } + [LuaGlobal] static int Matrix(ILuaInterface lua) { Matrix4x4 matrix = default; diff --git a/Source.Common/Mathematics/MathLib.cs b/Source.Common/Mathematics/MathLib.cs index b834ff6fb..bdedc1762 100644 --- a/Source.Common/Mathematics/MathLib.cs +++ b/Source.Common/Mathematics/MathLib.cs @@ -1537,7 +1537,83 @@ public static unsafe bool IsValid(this ref RadianEuler R) { return !Vector3.AnyWhereAllBitsSet(Vector3.IsNaN(*(Vector3*)pR)); } - public static void MatrixInverseGeneral(in Matrix4x4 src, out Matrix4x4 dst) => Matrix4x4.Invert(src, out dst); + public static bool MatrixInverseGeneral(in Matrix4x4 src, out Matrix4x4 dst) { + int iRow, i, j, iTemp, iTest; + float mul, fTest, fLargest; + Span mat = stackalloc float[4 * 8]; + Span rowMap = stackalloc int[4]; + int iLargest; + + Matrix4x4 srcCopy = src; + ReadOnlySpan pIn = MemoryMarshal.CreateReadOnlySpan(ref srcCopy.M11, 16); + + for (i = 0; i < 4; i++) { + Span pOut = mat.Slice(i * 8, 8); + + for (j = 0; j < 4; j++) + pOut[j] = pIn[i * 4 + j]; + + pOut[4] = 0.0f; + pOut[5] = 0.0f; + pOut[6] = 0.0f; + pOut[7] = 0.0f; + pOut[i + 4] = 1.0f; + + rowMap[i] = i; + } + + for (iRow = 0; iRow < 4; iRow++) { + fLargest = 0.00001f; + iLargest = -1; + for (iTest = iRow; iTest < 4; iTest++) { + fTest = MathF.Abs(mat[rowMap[iTest] * 8 + iRow]); + if (fTest > fLargest) { + iLargest = iTest; + fLargest = fTest; + } + } + + if (iLargest == -1) { + dst = srcCopy; + return false; + } + + iTemp = rowMap[iLargest]; + rowMap[iLargest] = rowMap[iRow]; + rowMap[iRow] = iTemp; + + Span pRow = mat.Slice(rowMap[iRow] * 8, 8); + + mul = 1.0f / pRow[iRow]; + for (j = 0; j < 8; j++) + pRow[j] *= mul; + + pRow[iRow] = 1.0f; + + for (i = 0; i < 4; i++) { + if (i == iRow) + continue; + + Span pScaleRow = mat.Slice(rowMap[i] * 8, 8); + + mul = -pScaleRow[iRow]; + for (j = 0; j < 8; j++) + pScaleRow[j] += pRow[j] * mul; + + pScaleRow[iRow] = 0.0f; + } + } + + dst = default; + Span dstOut = MemoryMarshal.CreateSpan(ref dst.M11, 16); + for (i = 0; i < 4; i++) { + ReadOnlySpan pRowIn = mat.Slice(rowMap[i] * 8 + 4, 4); + for (j = 0; j < 4; j++) + dstOut[i * 4 + j] = pRowIn[j]; + } + + return true; + } public static void V3Mul(this in Matrix4x4 m, in Vector3 vIn, out Vector3 vOut) { float rw = 1.0f / (m[3, 0] * vIn.X + m[3, 1] * vIn.Y + m[3, 2] * vIn.Z + m[3, 3]); @@ -2976,6 +3052,81 @@ public static void SetTranslation(ref this Matrix4x4 m, in Vector3 trans) { m[2, 3] = trans.Z; } + public static Vector3 GetScale(this in Matrix4x4 m) { + m.GetBasisVectors(out Vector3 v0, out Vector3 v1, out Vector3 v2); + return new(v0.Length(), v1.Length(), v2.Length()); + } + + public static Matrix4x4 NormalizeBasisVectors(this in Matrix4x4 m) { + Matrix4x4 ret = default; + m.GetBasisVectors(out Vector3 v0, out Vector3 v1, out Vector3 v2); + + VectorNormalize(ref v0); + VectorNormalize(ref v1); + VectorNormalize(ref v2); + + ret.SetBasisVectors(in v0, in v1, in v2); + + ret[3, 0] = ret[3, 1] = ret[3, 2] = 0.0f; + ret[3, 3] = 1.0f; + + return ret; + } + + public static bool IsRotationMatrix(this in Matrix4x4 m) { + Vector3 v1 = new(m[0, 0], m[0, 1], m[0, 2]); + Vector3 v2 = new(m[1, 0], m[1, 1], m[1, 2]); + Vector3 v3 = new(m[2, 0], m[2, 1], m[2, 2]); + + return + MathF.Abs(1 - v1.Length()) < 0.01f && + MathF.Abs(1 - v2.Length()) < 0.01f && + MathF.Abs(1 - v3.Length()) < 0.01f && + MathF.Abs(Vector3.Dot(v1, v2)) < 0.01f && + MathF.Abs(Vector3.Dot(v1, v3)) < 0.01f && + MathF.Abs(Vector3.Dot(v2, v3)) < 0.01f; + } + + public static Matrix4x4 SetupMatrixTranslation(in Vector3 translation) { + Matrix4x4 ret = default; + ret.Init( + 1.0f, 0.0f, 0.0f, translation.X, + 0.0f, 1.0f, 0.0f, translation.Y, + 0.0f, 0.0f, 1.0f, translation.Z, + 0.0f, 0.0f, 0.0f, 1.0f + ); + return ret; + } + + public static Matrix4x4 SetupMatrixScale(in Vector3 scale) { + Matrix4x4 ret = default; + ret.Init( + scale.X, 0.0f, 0.0f, 0.0f, + 0.0f, scale.Y, 0.0f, 0.0f, + 0.0f, 0.0f, scale.Z, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + ); + return ret; + } + + public static void SetupMatrixAngles(ref this Matrix4x4 m, in QAngle angles) { + SetupMatrixAnglesInternal(ref m, angles); + + m[0, 3] = 0.0f; + m[1, 3] = 0.0f; + m[2, 3] = 0.0f; + m[3, 0] = 0.0f; + m[3, 1] = 0.0f; + m[3, 2] = 0.0f; + m[3, 3] = 1.0f; + } + + public static Matrix4x4 SetupMatrixAngles(in QAngle angles) { + Matrix4x4 ret = default; + ret.SetupMatrixAngles(in angles); + return ret; + } + public static void MatrixTranspose(in Matrix4x4 src, out Matrix4x4 dst) { dst = default; dst[0, 0] = src[0, 0]; dst[0, 1] = src[1, 0]; dst[0, 2] = src[2, 0]; dst[0, 3] = src[3, 0]; From b495021431a3fdbf713cdc79d6ff48eacd58e9b7 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Thu, 8 Oct 2026 14:17:14 +0100 Subject: [PATCH 08/23] Finish LuaMaterial --- Game.Client/GarrysMod/LuaMaterial.cs | 261 +++++++++++++++++++++++++++ 1 file changed, 261 insertions(+) diff --git a/Game.Client/GarrysMod/LuaMaterial.cs b/Game.Client/GarrysMod/LuaMaterial.cs index f24998bd6..5c5119767 100644 --- a/Game.Client/GarrysMod/LuaMaterial.cs +++ b/Game.Client/GarrysMod/LuaMaterial.cs @@ -4,6 +4,8 @@ using Source.Common.MaterialSystem; using System.Diagnostics; +using System.Numerics; +using System.Runtime.InteropServices; namespace Game.Client.GarrysMod; @@ -200,6 +202,265 @@ static int IMaterial__SetMatrix(ILuaInterface lua) { return 0; } + [LuaMethod] + static int IMaterial__GetInt(ILuaInterface lua) { + IMaterial? material = (IMaterial?)LC_IMaterial.Get(1); + if (material == null) { + lua.Error("Tried to use a NULL IMaterial!"); + return 0; + } + + IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + if (var == null || !found) + return 0; + + lua.PushNumber(var.GetIntValue()); + return 1; + } + + [LuaMethod] + static int IMaterial__SetInt(ILuaInterface lua) { + IMaterial? material = (IMaterial?)LC_IMaterial.Get(1); + if (material == null) { + lua.Error("Tried to use a NULL IMaterial!"); + return 0; + } + + IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + if (var == null || !found) + return 0; + + int value = (int)lua.CheckNumber(3); + if (value != var.GetIntValue()) { + var.SetIntValue(value); + material.RecomputeStateSnapshots(); + } + return 0; + } + + [LuaMethod] + static int IMaterial__GetFloat(ILuaInterface lua) { + IMaterial? material = (IMaterial?)LC_IMaterial.Get(1); + if (material == null) { + lua.Error("Tried to use a NULL IMaterial!"); + return 0; + } + + IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + if (var == null || !found) + return 0; + + lua.PushNumber(var.GetFloatValue()); + return 1; + } + + [LuaMethod] + static int IMaterial__SetFloat(ILuaInterface lua) { + IMaterial? material = (IMaterial?)LC_IMaterial.Get(1); + if (material == null) { + lua.Error("Tried to use a NULL IMaterial!"); + return 0; + } + + IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + if (var == null || !found) + return 0; + + var.SetFloatValue((float)lua.CheckNumber(3)); + return 0; + } + + [LuaMethod] + static int IMaterial__SetUndefined(ILuaInterface lua) { + IMaterial? material = (IMaterial?)LC_IMaterial.Get(1); + if (material == null) { + lua.Error("Tried to use a NULL IMaterial!"); + return 0; + } + + IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + if (var == null || !found) + return 0; + + var.SetUndefined(); + return 0; + } + + [LuaMethod] + static int IMaterial__SetVector(ILuaInterface lua) { + IMaterial? material = (IMaterial?)LC_IMaterial.Get(1); + if (material == null) { + lua.Error("Tried to use a NULL IMaterial!"); + return 0; + } + + IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + if (var == null || !found) + return 0; + + ref Vector3 vec = ref LuaVector.Get_Vector(3); + var.SetVecValue(vec.X, vec.Y, vec.Z); + return 0; + } + + [LuaMethod] + static int IMaterial__GetVector(ILuaInterface lua) { + IMaterial? material = (IMaterial?)LC_IMaterial.Get(1); + if (material == null) { + lua.Error("Tried to use a NULL IMaterial!"); + return 0; + } + + IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + if (var == null || !found) + return 0; + + Vector3 vec = default; + var.GetVecValue(MemoryMarshal.CreateSpan(ref vec.X, 3)); + LuaVector.Push_Vector(vec); + return 1; + } + + [LuaMethod] + static int IMaterial__SetVector4D(ILuaInterface lua) { + IMaterial? material = (IMaterial?)LC_IMaterial.Get(1); + if (material == null) { + lua.Error("Tried to use a NULL IMaterial!"); + return 0; + } + + IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + if (var == null || !found) + return 0; + + float x = (float)lua.CheckNumber(3); + float y = (float)lua.CheckNumber(4); + float z = (float)lua.CheckNumber(5); + float w = (float)lua.CheckNumber(6); + var.SetVecValue(x, y, z, w); + return 0; + } + + [LuaMethod] + static int IMaterial__GetVector4D(ILuaInterface lua) { + IMaterial? material = (IMaterial?)LC_IMaterial.Get(1); + if (material == null) { + lua.Error("Tried to use a NULL IMaterial!"); + return 0; + } + + IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + if (var == null || !found) + return 0; + + Span vec = stackalloc float[4]; + var.GetVecValue(vec); + lua.PushNumber(vec[0]); + lua.PushNumber(vec[1]); + lua.PushNumber(vec[2]); + lua.PushNumber(vec[3]); + return 4; + } + + [LuaMethod] + static int IMaterial__GetVectorLinear(ILuaInterface lua) { + IMaterial? material = (IMaterial?)LC_IMaterial.Get(1); + if (material == null) { + lua.Error("Tried to use a NULL IMaterial!"); + return 0; + } + + IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + if (var == null || !found) + return 0; + + Vector3 vec = default; + var.GetLinearVecValue(MemoryMarshal.CreateSpan(ref vec.X, 3), 3); + LuaVector.Push_Vector(vec); + return 1; + } + + [LuaMethod] + static int IMaterial__SetString(ILuaInterface lua) { + IMaterial? material = (IMaterial?)LC_IMaterial.Get(1); + if (material == null) { + lua.Error("Tried to use a NULL IMaterial!"); + return 0; + } + + IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + if (var == null || !found) + return 0; + + var.SetStringValue(lua.CheckString(3)); + return 0; + } + + [LuaMethod] + static int IMaterial__SetShader(ILuaInterface lua) => 0; + + [LuaMethod] + static int IMaterial__Recompute(ILuaInterface lua) { + IMaterial? material = (IMaterial?)LC_IMaterial.Get(1); + if (material == null) { + lua.Error("Tried to use a NULL IMaterial!"); + return 0; + } + + material.RecomputeStateSnapshots(); + return 0; + } + + [LuaMethod] + static int IMaterial__GetKeyValues(ILuaInterface lua) { + IMaterial? material = (IMaterial?)LC_IMaterial.Get(1); + if (material == null) { + lua.Error("Tried to use a NULL IMaterial!"); + return 0; + } + + int count = material.ShaderParamCount(); + IMaterialVar[] vars = material.GetShaderParams()!; + lua.CreateTable(); + for (int i = 0; i < count; i++) { + IMaterialVar var = vars[i]; + lua.PushString(var.GetName()); + switch (var.GetVarType()) { + case MaterialVarType.Float: + lua.PushNumber(var.GetFloatValue()); + break; + default: + lua.PushString(var.GetStringValue()); + break; + case MaterialVarType.Vector: { + Vector3 vec = default; + var.GetLinearVecValue(MemoryMarshal.CreateSpan(ref vec.X, 3), 3); + LuaVector.Push_Vector(vec); + break; + } + case MaterialVarType.Texture: { + ITexture? texture = var.GetTextureValue(); + if (texture == null) + lua.PushNil(); + else + LuaTexture.LC_ITexture.Push(texture); + break; + } + case MaterialVarType.Int: + lua.PushNumber(var.GetIntValue()); + break; + case MaterialVarType.Undefined: + lua.PushNil(); + break; + case MaterialVarType.Matrix: + LuaVMatrix.Push_VMatrix(var.GetMatrixValue()); + break; + } + lua.SetTable(-3); + } + return 1; + } + static bool IsAllowedMaterialPath(ReadOnlySpan name) { Span buffer = stackalloc char[MAX_PATH]; strcpy(buffer, name); From 82c3b70a8cf6e2a3e0888555e1cb8626a8f597c7 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Thu, 8 Oct 2026 14:24:52 +0100 Subject: [PATCH 09/23] Finish LuaInput --- Game.Client/GarrysMod/LuaInput.cs | 178 ++++++++++++++++++++-- Game.Client/SourceDllMain.cs | 2 + Source.Common/Input/IInputSystem.cs | 1 + Source.SDLInputSystem/SDL3_InputSystem.cs | 2 + 4 files changed, 167 insertions(+), 16 deletions(-) diff --git a/Game.Client/GarrysMod/LuaInput.cs b/Game.Client/GarrysMod/LuaInput.cs index 5f7a798c6..320fe501f 100644 --- a/Game.Client/GarrysMod/LuaInput.cs +++ b/Game.Client/GarrysMod/LuaInput.cs @@ -8,8 +8,28 @@ public static partial class LuaInput [LuaLibrary] static readonly LuaLibrary LL_Factory_input = new("input"); - // todo: IsButtonDown - // todo: GetAnalogValue + [LuaFunction] + static int IsButtonDown(ILuaInterface lua) { + int code = (int)lua.CheckNumber(1); + if ((uint)code < 1042) { + lua.PushBool(inputsystem.IsButtonDown((ButtonCode)code)); + return 1; + } + lua.PushBool(false); + return 1; + } + + [LuaFunction] + static int GetAnalogValue(ILuaInterface lua) { + int code = (int)lua.CheckNumber(1); + if ((uint)code < 28) { + lua.PushNumber(inputsystem.GetAnalogValue((AnalogCode)code)); + return 1; + } + lua.PushNumber(0); + return 1; + } + [LuaFunction] static int IsMouseDown(ILuaInterface lua) { ButtonCode code = (ButtonCode)(int)lua.CheckNumber(1); @@ -48,11 +68,61 @@ static int GetCursorPos(ILuaInterface lua) { return 2; } - // todo: WasMousePressed - // todo: WasMouseReleased - // todo: WasMouseDoublePressed - // todo: WasKeyPressed - // todo: IsKeyDown + [LuaFunction] + static int WasMousePressed(ILuaInterface lua) { + int code = (int)lua.CheckNumber(1); + if ((uint)(code - 107) < 7) { + lua.PushBool(vguiInput.WasMousePressed((ButtonCode)code)); + return 1; + } + lua.PushBool(false); + return 1; + } + + [LuaFunction] + static int WasMouseReleased(ILuaInterface lua) { + int code = (int)lua.CheckNumber(1); + if ((uint)(code - 107) < 7) { + lua.PushBool(vguiInput.WasMouseReleased((ButtonCode)code)); + return 1; + } + lua.PushBool(false); + return 1; + } + + [LuaFunction] + static int WasMouseDoublePressed(ILuaInterface lua) { + int code = (int)lua.CheckNumber(1); + if ((uint)(code - 107) < 7) { + lua.PushBool(vguiInput.WasMouseDoublePressed((ButtonCode)code)); + return 1; + } + lua.PushBool(false); + return 1; + } + + [LuaFunction] + static int WasKeyPressed(ILuaInterface lua) { + int code = (int)lua.CheckNumber(1); + if ((uint)code < 107) { + lua.PushBool(vguiInput.WasKeyPressed((ButtonCode)code)); + return 1; + } + lua.PushBool(false); + return 1; + } + + [LuaFunction] + static int IsKeyDown(ILuaInterface lua) { + int code = (int)lua.CheckNumber(1); + if ((uint)code < 107) { + lua.PushBool(vguiInput.IsKeyDown((ButtonCode)code)); + return 1; + } + lua.PushBool(false); + return 1; + } + [LuaFunction] static int IsShiftDown(ILuaInterface lua) { lua.PushBool(vguiInput.IsKeyDown(ButtonCode.KeyLShift) || vguiInput.IsKeyDown(ButtonCode.KeyRShift)); @@ -63,13 +133,52 @@ static int IsControlDown(ILuaInterface lua) { lua.PushBool(vguiInput.IsKeyDown(ButtonCode.KeyLControl) || vguiInput.IsKeyDown(ButtonCode.KeyRControl)); return 1; } - // todo: WasKeyTyped - // todo: WasKeyReleased - // todo: GetKeyName - // todo: GetKeyCode + [LuaFunction] + static int WasKeyTyped(ILuaInterface lua) { + int code = (int)lua.CheckNumber(1); + if ((uint)code < 107) { + lua.PushBool(vguiInput.WasKeyTyped((ButtonCode)code)); + return 1; + } + lua.PushBool(false); + return 1; + } + + [LuaFunction] + static int WasKeyReleased(ILuaInterface lua) { + int code = (int)lua.CheckNumber(1); + if ((uint)code < 107) { + lua.PushBool(vguiInput.WasKeyReleased((ButtonCode)code)); + return 1; + } + lua.PushBool(false); + return 1; + } + + [LuaFunction] + static int GetKeyName(ILuaInterface lua) { + int code = (int)lua.CheckNumber(1); + if ((uint)(code - 1) < 1041) { + lua.PushString(inputsystem.ButtonCodeToString((ButtonCode)code)); + return 1; + } + return 0; + } + + [LuaFunction] + static int GetKeyCode(ILuaInterface lua) { + lua.PushNumber((int)inputsystem.StringToButtonCode(lua.CheckString(1))); + return 1; + } + static bool KeyTrapping; - // todo: StartKeyTrapping + [LuaFunction] + static int StartKeyTrapping(ILuaInterface lua) { + engine.StartKeyTrapMode(); + KeyTrapping = true; + return 0; + } [LuaFunction] static int IsKeyTrapping(ILuaInterface lua) { @@ -77,7 +186,16 @@ static int IsKeyTrapping(ILuaInterface lua) { return 1; } - // todo: CheckKeyTrapping + [LuaFunction] + static int CheckKeyTrapping(ILuaInterface lua) { + if (engine.CheckDoneKeyTrapping(out ButtonCode code)) { + lua.PushNumber((int)code); + KeyTrapping = false; + return 1; + } + return 0; + } + [LuaFunction] static int LookupBinding(ILuaInterface lua) { string binding = lua.CheckString(1); @@ -92,7 +210,35 @@ static int LookupBinding(ILuaInterface lua) { lua.PushString(key); return 1; } - // todo: LookupKeyBinding - // todo: TranslateAlias - // todo: SelectWeapon + [LuaFunction] + static int LookupKeyBinding(ILuaInterface lua) { + ReadOnlySpan binding = engine.Key_BindingForKey((ButtonCode)(int)lua.CheckNumber(1)); + if (binding.IsEmpty) + return 0; + lua.PushString(binding); + return 1; + } + + [LuaFunction] + static int TranslateAlias(ILuaInterface lua) { + ReadOnlySpan alias = engine.GMOD_TranslateAlias(lua.CheckString(1)); + if (alias.IsEmpty) + return 0; + lua.PushString(alias); + return 1; + } + + static void SelectWeapon(BaseEntity? ent) { + if (ent == null || !ent.IsBaseCombatWeapon()) { + g_Lua!.Error("Weapon is NULL/Not a Weapon"); + ent = null; + } + input.MakeWeaponSelection((BaseCombatWeapon?)ent); + } + + [LuaFunction] + static int SelectWeapon(ILuaInterface lua) { + SelectWeapon(LuaEntity.Get_Entity(1, false)); + return 0; + } } diff --git a/Game.Client/SourceDllMain.cs b/Game.Client/SourceDllMain.cs index 0cffda1b6..952e0aa4e 100644 --- a/Game.Client/SourceDllMain.cs +++ b/Game.Client/SourceDllMain.cs @@ -10,6 +10,7 @@ using Source.Common.DataCache; using Source.Common.Engine; using Source.Common.Filesystem; +using Source.Common.Input; using Source.Common.GameUI; using Source.Common.GUI; using Source.Common.MaterialSystem; @@ -88,6 +89,7 @@ public static void Link(IServiceCollection services) { [Dependency] public static IVGui VGui { get; private set; } = null!; [Dependency] public static ILocalize Localize { get; private set; } = null!; [Dependency] public static IVGuiInput vguiInput { get; private set; } = null!; + [Dependency] public static IInputSystem inputsystem { get; private set; } = null!; [Dependency] public static ISceneFileCache scenefilecache { get; private set; } = null!; #if GMOD_DLL [Dependency] public static Source.Common.GarrysMod.IGet get { get; private set; } = null!; diff --git a/Source.Common/Input/IInputSystem.cs b/Source.Common/Input/IInputSystem.cs index 727c29bf6..f2b909bee 100644 --- a/Source.Common/Input/IInputSystem.cs +++ b/Source.Common/Input/IInputSystem.cs @@ -13,6 +13,7 @@ public interface IInputSystem public void PollInputState(); public int GetPollTick(); public bool IsButtonDown(ButtonCode code); + public int GetAnalogValue(AnalogCode code); public int GetButtonPressedTick(ButtonCode code); public int GetButtonReleasedTick(ButtonCode code); public long GetEventCount(); diff --git a/Source.SDLInputSystem/SDL3_InputSystem.cs b/Source.SDLInputSystem/SDL3_InputSystem.cs index 7f6b3d58c..48dcb9121 100644 --- a/Source.SDLInputSystem/SDL3_InputSystem.cs +++ b/Source.SDLInputSystem/SDL3_InputSystem.cs @@ -102,6 +102,8 @@ public bool IsButtonDown(ButtonCode code) { return InputState.ButtonState.IsBitSet((int)code); } + public int GetAnalogValue(AnalogCode code) => InputState.AnalogValue[(int)code]; + public void ClearInputState() { foreach (var state in InputStates) { state.Events.Clear(); From 716264ba2027db73ccc28a9d4c7e4a0aa81bd10c Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Thu, 8 Oct 2026 15:28:52 +0100 Subject: [PATCH 10/23] SetVerticalScrollbarEnabled --- Game.Client/GarrysMod/LuaPanel.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Game.Client/GarrysMod/LuaPanel.cs b/Game.Client/GarrysMod/LuaPanel.cs index e70b4d674..4e4873ba4 100644 --- a/Game.Client/GarrysMod/LuaPanel.cs +++ b/Game.Client/GarrysMod/LuaPanel.cs @@ -938,6 +938,14 @@ static int Panel__SetExpensiveShadow(ILuaInterface lua) { [LuaMethod] static void Panel__SetPaintBackgroundEnabled(Panel panel, [LuaGet] bool state) => panel.SetPaintBackgroundEnabled(state); + [LuaMethod] + static void Panel__SetVerticalScrollbarEnabled(Panel panel) { + if (panel is RichText richText) + richText.SetVerticalScrollbar(g_Lua!.GetBool(2)); + if (panel is TextEntry textEntry) + textEntry.SetVerticalScrollbar(g_Lua!.GetBool(2)); + } + [LuaMethod] static void Panel__MoveToFront(Panel panel) => panel.MoveToFront(); From 26314f59546a2d122d16671b419635b3b5db434b Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Fri, 9 Oct 2026 04:41:36 +0100 Subject: [PATCH 11/23] Let DownloadFile cycle without notify for now --- Source.Filesystem/GarrysMod/AddonTasks.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Source.Filesystem/GarrysMod/AddonTasks.cs b/Source.Filesystem/GarrysMod/AddonTasks.cs index 721c349f3..3c9b53e2c 100644 --- a/Source.Filesystem/GarrysMod/AddonTasks.cs +++ b/Source.Filesystem/GarrysMod/AddonTasks.cs @@ -242,8 +242,8 @@ void OnItemDownloaded(DownloadItemResult_t result) { public override void Cycle() { IAddonDownloadNotification? notify = AddonSystem.Notify(); - if (notify == null) - return; + // if (notify == null) // TODO, add this back once implemented + // return; if (Thread != null) { if (!Thread.IsDone()) @@ -276,7 +276,7 @@ public override void Cycle() { if (Extracting) { if (!Extractor!.IsDone()) { - notify.ExtractProgress(Info.WorkshopID, Info.HContentPreview, Info.Title, (uint)(Extractor.GetProgress() * Percent)); + notify?.ExtractProgress(Info.WorkshopID, Info.HContentPreview, Info.Title, (uint)(Extractor.GetProgress() * Percent)); return; } @@ -308,7 +308,7 @@ public override void Cycle() { BaseFileSystem.get.RunSteamCallbacks(); if (SteamUGC.GetItemDownloadInfo(new PublishedFileId_t(Info.WorkshopID), out ulong downloadedBytes, out ulong totalBytes) && totalBytes != 0) { - notify.DownloadProgress(Info.WorkshopID, Info.HContentPreview, Info.Title, (uint)downloadedBytes, (uint)totalBytes); + notify?.DownloadProgress(Info.WorkshopID, Info.HContentPreview, Info.Title, (uint)downloadedBytes, (uint)totalBytes); BytesTransferred += (int)downloadedBytes - PrevDownloadedBytes; PrevDownloadedBytes = (int)downloadedBytes; } From f3e9b9cd1d5705fc3d9cb26a73bfe5a5ab1a202c Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Fri, 9 Oct 2026 13:56:27 +0100 Subject: [PATCH 12/23] Update steamworks submodule --- Dependencies/Steamworks.NET | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dependencies/Steamworks.NET b/Dependencies/Steamworks.NET index 6907d66cf..5fa039c69 160000 --- a/Dependencies/Steamworks.NET +++ b/Dependencies/Steamworks.NET @@ -1 +1 @@ -Subproject commit 6907d66cfd0b926dd72804766efe2df8202bfb28 +Subproject commit 5fa039c69f1a98d59f828266d77d28fb3164b5ec From 871ac3774dab000383cc221d5ecbbf04bf5cfe7c Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Sat, 10 Oct 2026 10:55:24 +0100 Subject: [PATCH 13/23] More lua impl --- Game.Client/C_BaseEntity.cs | 2 +- Game.Client/C_PropJeep.cs | 2 + Game.Client/C_RagdollProp.cs | 2 + Game.Client/HL2MP/C_HL2MP_Player.cs | 2 + Game.Server/HL2/PropVehiclePrisonerPod.cs | 2 + Game.Server/PropCrane.cs | 2 + Game.Server/PropJeep.cs | 2 + Game.Server/PropVehicleDriveable.cs | 2 + Game.Server/RagdollProp.cs | 2 + Game.Server/World.cs | 29 +--- Game.Shared/GarrysMod/BaseEntityLua.cs | 3 + Game.Shared/GarrysMod/LuaEntity.cs | 188 ++++++++++++++++++++++ Game.Shared/GarrysMod/LuaEnts.cs | 54 ++++++- Game.Shared/GarrysMod/LuaPlayer.cs | 18 +++ Game.Shared/GarrysMod/LuaUtil.cs | 73 ++++++++- 15 files changed, 353 insertions(+), 30 deletions(-) diff --git a/Game.Client/C_BaseEntity.cs b/Game.Client/C_BaseEntity.cs index 45449124d..02f774afe 100644 --- a/Game.Client/C_BaseEntity.cs +++ b/Game.Client/C_BaseEntity.cs @@ -1074,7 +1074,7 @@ public virtual bool GetSoundSpatialization(ref SpatializationInfo info) { public virtual void ValidateModelIndex() { SetModelByIndex(ModelIndex); } - void SetModelPointer(Model? model) { + public void SetModelPointer(Model? model) { if (model != Model) { DestroyModelInstance(); Model = model; diff --git a/Game.Client/C_PropJeep.cs b/Game.Client/C_PropJeep.cs index e2a945208..f70b0ad01 100644 --- a/Game.Client/C_PropJeep.cs +++ b/Game.Client/C_PropJeep.cs @@ -18,6 +18,8 @@ public class C_PropJeep : C_PropVehicleDriveable [NetworkName("m_bHeadlightIsOn")] public bool HeadlightIsOn; + + public override bool IsJeep() => true; } [NetworkName("CPropJeepEpisodic")] diff --git a/Game.Client/C_RagdollProp.cs b/Game.Client/C_RagdollProp.cs index 7dddf7124..3b6b19345 100644 --- a/Game.Client/C_RagdollProp.cs +++ b/Game.Client/C_RagdollProp.cs @@ -28,4 +28,6 @@ .. Enumerable.Range(0, RAGDOLL_MAX_ELEMENTS).Select(i => RecvPropQAngles(FIELD.O public float BlendWeight; [NetworkName("m_nOverlaySequence")] public int OverlaySequence; + + public override bool IsRagdollProp() => true; } diff --git a/Game.Client/HL2MP/C_HL2MP_Player.cs b/Game.Client/HL2MP/C_HL2MP_Player.cs index 2401654a5..9b6651bbf 100644 --- a/Game.Client/HL2MP/C_HL2MP_Player.cs +++ b/Game.Client/HL2MP/C_HL2MP_Player.cs @@ -136,4 +136,6 @@ public class C_HL2MPRagdoll : C_BaseAnimatingOverlay public EHANDLE Player = new(); [NetworkName("m_vecRagdollVelocity")] public Vector3 RagdollVelocity; + + public override bool IsRagdollProp() => true; } diff --git a/Game.Server/HL2/PropVehiclePrisonerPod.cs b/Game.Server/HL2/PropVehiclePrisonerPod.cs index 738b8f849..a46db4fd4 100644 --- a/Game.Server/HL2/PropVehiclePrisonerPod.cs +++ b/Game.Server/HL2/PropVehiclePrisonerPod.cs @@ -33,4 +33,6 @@ public class PropVehiclePrisonerPod : PhysicsProp public bool LimitView = new(); [NetworkName("m_bLocked")] public bool Locked; + + public override bool IsVehicle() => true; } diff --git a/Game.Server/PropCrane.cs b/Game.Server/PropCrane.cs index b3fe225da..5e0465305 100644 --- a/Game.Server/PropCrane.cs +++ b/Game.Server/PropCrane.cs @@ -27,4 +27,6 @@ public class PropCrane : BaseAnimating public bool ExitAnimOn; [NetworkName("m_vecEyeExitEndpoint")] public Vector3 EyeExitEndpoint; + + public override bool IsVehicle() => true; } diff --git a/Game.Server/PropJeep.cs b/Game.Server/PropJeep.cs index e5aada4ab..d35cfd522 100644 --- a/Game.Server/PropJeep.cs +++ b/Game.Server/PropJeep.cs @@ -18,6 +18,8 @@ public class PropJeep : PropVehicleDriveable [NetworkName("m_bHeadlightIsOn")] public bool HeadlightIsOn; + + public override bool IsJeep() => true; } [LinkEntityToClass("prop_vehicle_jeep")] diff --git a/Game.Server/PropVehicleDriveable.cs b/Game.Server/PropVehicleDriveable.cs index 5a95adb70..fa9216ee4 100644 --- a/Game.Server/PropVehicleDriveable.cs +++ b/Game.Server/PropVehicleDriveable.cs @@ -56,4 +56,6 @@ public class PropVehicleDriveable : BaseAnimating public Vector3 GunCrosshair; [NetworkName("m_bLocked")] public bool Locked; + + public override bool IsVehicle() => true; } diff --git a/Game.Server/RagdollProp.cs b/Game.Server/RagdollProp.cs index a98fe65ad..8a82537b2 100644 --- a/Game.Server/RagdollProp.cs +++ b/Game.Server/RagdollProp.cs @@ -40,4 +40,6 @@ .. Enumerable.Range(0, RAGDOLL_MAX_ELEMENTS).Select(i => SendPropQAngles(FIELD.O public static bool Ragdoll_IsPropRagdoll(BaseEntity entity) => entity is RagdollProp; public static Ragdoll? Ragdoll_GetRagdoll(BaseEntity entity) => (entity as RagdollProp)?.GetRagdoll(); + + public override bool IsRagdollProp() => true; } diff --git a/Game.Server/World.cs b/Game.Server/World.cs index d02441e90..8bdefced2 100644 --- a/Game.Server/World.cs +++ b/Game.Server/World.cs @@ -49,31 +49,6 @@ public World() { ColdWorld = false; } - public override bool KeyValue(ReadOnlySpan keyName, ReadOnlySpan value) { - if (keyName.Equals("skyname", StringComparison.Ordinal)) { - ConVarRef skyname = new("sv_skyname"); - skyname.SetValue(value); - } - else if (keyName.Equals("newunit", StringComparison.Ordinal)) { - // if (atoi(value) != 0) - // Game_SetOneWayTransition(); - } - else if (keyName.Equals("world_mins", StringComparison.Ordinal)) { - Vector3 vec = default; - UTIL_StringToVector(vec.Base(), value); - WorldMins = vec; - } - else if (keyName.Equals("world_maxs", StringComparison.Ordinal)) { - Vector3 vec = default; - UTIL_StringToVector(vec.Base(), value); - WorldMaxs = vec; - } - else - return base.KeyValue(keyName, value); - - return true; - } - public override void Precache() { g_WorldEntity = this; g_fGameOver = false; @@ -134,6 +109,10 @@ public override bool KeyValue(ReadOnlySpan keyName, ReadOnlySpan val ConVarRef skyname = new("sv_skyname"); skyname.SetValue(value); } + else if (FStrEq(keyName, "newunit")) { + // if (atoi(value) != 0) + // Game_SetOneWayTransition(); + } else if (FStrEq(keyName, "world_mins")) { Vector3 vec = default; UTIL_StringToVector(vec.Base(), value); diff --git a/Game.Shared/GarrysMod/BaseEntityLua.cs b/Game.Shared/GarrysMod/BaseEntityLua.cs index 4ba7df4fc..62ab75680 100644 --- a/Game.Shared/GarrysMod/BaseEntityLua.cs +++ b/Game.Shared/GarrysMod/BaseEntityLua.cs @@ -24,6 +24,9 @@ public partial class public virtual bool IsWeapon() => false; public virtual bool IsVehicle() => false; + public virtual bool IsRagdollProp() => false; + public virtual bool IsJeep() => false; + public virtual void PostLuaSpawn() { } public virtual LuaClass Lua_GetLuaClass() => LuaEntity.LC_Entity; public virtual void PushEntity() { diff --git a/Game.Shared/GarrysMod/LuaEntity.cs b/Game.Shared/GarrysMod/LuaEntity.cs index 45791dbe7..b27b8a366 100644 --- a/Game.Shared/GarrysMod/LuaEntity.cs +++ b/Game.Shared/GarrysMod/LuaEntity.cs @@ -1,6 +1,12 @@ #if CLIENT_DLL || GAME_DLL +using Game.Shared; + +using Source; using Source.Common; +using Source.Common.Engine; using Source.Common.GarrysMod.Lua; +using Source.Common.Mathematics; +using Source.Common.Physics; using System.Numerics; using System.Runtime.InteropServices; @@ -188,6 +194,174 @@ static int Entity__IsValid(ILuaInterface lua) { return 1; } + // todo: populate from Entity:Remove + public static readonly List RemovedEntities = []; + + public static bool IsEntityRemoving(BaseEntity ent, bool ignoreRemoved) { + if (!ignoreRemoved) { + foreach (EHANDLE handle in RemovedEntities) { + if (handle.Get() == ent) + return true; + } + } + return ent.IsMarkedForDeletion(); + } + + [LuaMethod] + static int Entity__SetBodyGroups(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating == null || IsEntityRemoving(ent, false)) + return 0; + + string? groups = lua.CheckString(2); + if (groups == null) + return 0; + + for (int i = 0; i < groups.Length; i++) { + char c = groups[i]; + int value = -1; + if (c >= '0' && c <= '9') + value = c - '0'; + if (c >= 'a' && c <= 'z') + value = c - 'a' + 10; + if (c >= 'A' && c <= 'Z') + value = c - 'A' + 10; + if (value >= 0) + animating.SetBodygroup(i, value); + } + return 0; + } + + [LuaMethod] + static int Entity__NearestPoint(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + ref Vector3 point = ref LuaVector.Get_Vector(2); + ent.CollisionProp().CalcNearestPoint(point, out Vector3 nearest); + LuaVector.Push_Vector(nearest); + return 1; + } + + [LuaMethod] + static int Entity__Spawn(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + if (IsEntityRemoving(ent, false)) + return 0; + if (!ent.IsPlayer() && LuaEnts.IsProtectedEntity(ent)) + return 0; + + Handle handle = ent.GetRefEHandle(); +#if CLIENT_DLL + ent.Spawn(); +#else + Util.DispatchSpawn(ent); +#endif + if (handle.Get() != null) + ent.PostLuaSpawn(); + return 0; + } + + [LuaMethod] + static int Entity__Activate(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + if (!IsEntityRemoving(ent, false)) + ent.Activate(); + return 0; + } + + [LuaMethod] + static int Entity__SetPos(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + ref Vector3 pos = ref LuaVector.Get_Vector(2); + float max = MAX_COORD_FLOAT * 8; + if (!(-max < pos.X && pos.X < max && -max < pos.Y && pos.Y < max && -max < pos.Z && pos.Z < max)) { + Warning($"{ent.GetClassname()}[{ent.EntIndex()}]:SetPos( {pos.X:F6} {pos.Y:F6} {pos.Z:F6} ): Ignoring unreasonable position.\n"); + return 0; + } + + ent.SetAbsOrigin(pos); + if (ent.GetMoveType() == MoveType.None || ent.VPhysicsGetObject() == null || ent.IsRagdollProp() || ent.IsJeep()) + return 0; +#if CLIENT_DLL + IPhysicsObject phys = ent.VPhysicsGetObject()!; + phys.GetPosition(out _, out QAngle angles); + phys.SetPosition(pos, angles, true); +#else + ent.Teleport(pos, null, null); +#endif + return 0; + } + + [LuaMethod] + static int Entity__SetAngles(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + ref QAngle angles = ref LuaAngle.Get_Angle(2); + float max = 360000f * 360000f; + if (!(-max < angles.X && angles.X < max && -max < angles.Y && angles.Y < max && -max < angles.Z && angles.Z < max)) { + Warning($"{ent.GetClassname()}[{ent.EntIndex()}]:SetAngles( {angles.X:F6} {angles.Y:F6} {angles.Z:F6} ): Ignoring unreasonable angles.\n"); + return 0; + } + + ent.SetAbsAngles(angles); +#if GAME_DLL + if (ent.IsJeep()) + ent.Teleport(null, angles, null); +#endif + if (ent.GetMoveType() == MoveType.None || ent.VPhysicsGetObject() == null || ent.IsRagdollProp() || ent.IsJeep()) + return 0; + IPhysicsObject phys = ent.VPhysicsGetObject()!; + phys.GetPosition(out Vector3 pos, out _); + phys.SetPosition(pos, angles, true); + return 0; + } + + [LuaMethod] + static int Entity__SetSkin(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating == null || IsEntityRemoving(ent, false)) + return 0; + + int skin = (int)lua.CheckNumber(2); + if (animating.Skin != skin) + animating.Skin = skin; + return 0; + } + + [LuaMethod] + static int Entity__SetModel(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + string? modelName = lua.CheckString(2); + if (string.IsNullOrEmpty(modelName) || (modelName[0] & 0xDF) == 0 || modelName.Length < 2) + return 0; + if (!stristr(modelName, ".bsp").IsEmpty) + return 0; + if (stristr(modelName, ".mdl").IsEmpty && modelName[0] != '*') + return 0; + +#if CLIENT_DLL + engine.LoadModel(modelName, true); + Model? model = modelinfo.FindOrLoadModel(modelName); + ent.SetModel(modelName); + Vector3 mins = vec3_origin, maxs = vec3_origin; + if (model != null) { + ent.SetModelPointer(model); + ent.ModelName = modelName; + modelinfo.GetModelBounds(model, out mins, out maxs); + } + ent.SetCollisionBounds(mins, maxs); +#else + Util.SetModel(ent, modelName); + ent.SetModel(modelName); +#endif + + MDLHandle_t handle = mdlcache.FindMDL(ent.GetModelName()); + if (handle == MDLHANDLE_INVALID || mdlcache.IsErrorModel(handle)) + Warning($"Model missing: {modelName}\n"); + mdlcache.Release(handle); + return 0; + } + [LuaMethod] static int Entity__GetPos(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; @@ -217,6 +391,20 @@ static int Entity__EyePos(ILuaInterface lua) { return 1; } + [LuaMethod] + static int Entity__GetClass(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + ReadOnlySpan classname = ent.GetClassname(); + if (strcmp(classname, "prop_vehicle_jeep_old") == 0) { + lua.PushString("prop_vehicle_jeep"); + return 1; + } + if (classname.Length >= 3 && classname[0] == 'a' && classname[1] == 'i' && classname[2] == '_') + classname = classname[3..]; + lua.PushString(new string(classname)); + return 1; + } + [LuaMethod] static int Entity__EntIndex(ILuaInterface lua) { LuaType type = lua.GetType(1); diff --git a/Game.Shared/GarrysMod/LuaEnts.cs b/Game.Shared/GarrysMod/LuaEnts.cs index 441285057..4ebb39f9f 100644 --- a/Game.Shared/GarrysMod/LuaEnts.cs +++ b/Game.Shared/GarrysMod/LuaEnts.cs @@ -22,12 +22,64 @@ public static partial class LuaEnts #endif } + static readonly string[] ProtectedClasses = [ + "worldspawn", + "player", + "gm_bot", + "gmod_gamerules", + "soundent", + "ai_ally_speech_manager", + "ai_network_build_helper", + "scene_manager", + "ai_network", + "player_manager", + "instanced_scripted_scene", + "npc_barnacle_tongue_tip", + ]; + + public static bool IsProtectedClass(ReadOnlySpan className) { + foreach (string name in ProtectedClasses) { + if (stricmp(className, name) == 0) + return true; + } + return false; + } + + public static bool IsProtectedEntity(BaseEntity ent) { +#if CLIENT_DLL + if (ent.IsPlayer() || ent == C_World.GetClientWorldEntity()) +#else + if (ent.IsPlayer() || ent == GetWorldEntity()) +#endif + return true; + return IsProtectedClass(ent.GetClassname()); + } + #if CLIENT_DLL // todo: CreateClientProp // todo: CreateClientRope // todo: CreateClientside #else - // todo: Create + // todo: render depth counter + static bool IsRendering() => false; + + [LuaFunction] + static int Create(ILuaInterface lua) { + if (IsRendering()) { + lua.ErrorNoHalt("ents.Create cannot be called while rendering\n"); + return 0; + } + + string? className = lua.CheckString(1); + if (className == null || IsProtectedClass(className)) + return 0; + + if (GetWorldEntity() == null) + Warning($"Trying to create entities too early! ({className})\n"); + + LuaEntity.Push_Entity(CreateEntityByName(className, -1)); + return 1; + } [LuaFunction] static int GetEdictCount() => gEntList.NumberOfEdicts(); diff --git a/Game.Shared/GarrysMod/LuaPlayer.cs b/Game.Shared/GarrysMod/LuaPlayer.cs index 9f7c966b3..0077914f5 100644 --- a/Game.Shared/GarrysMod/LuaPlayer.cs +++ b/Game.Shared/GarrysMod/LuaPlayer.cs @@ -177,6 +177,24 @@ static int Player__GetAimVector(ILuaInterface lua) { return 1; } + [LuaMethod] + static int Player__GetVehicle(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; +#if CLIENT_DLL + LuaEntity.Push_Entity(player.GetVehicle()?.GetVehicleEnt()); +#else + LuaEntity.Push_Entity(player.IsInAVehicle() ? player.GetVehicleEntity() : null); +#endif + return 1; + } + + [LuaMethod] + static int Player__GetShootPos(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + LuaVector.Push_Vector(player.Weapon_ShootPosition()); + return 1; + } + [LuaFunction] static int GetByID(ILuaInterface lua) { BasePlayer? player = Util.PlayerByIndex((int)g_Lua!.CheckNumber(1)); diff --git a/Game.Shared/GarrysMod/LuaUtil.cs b/Game.Shared/GarrysMod/LuaUtil.cs index 6804cd56e..68560c9b4 100644 --- a/Game.Shared/GarrysMod/LuaUtil.cs +++ b/Game.Shared/GarrysMod/LuaUtil.cs @@ -31,16 +31,18 @@ public static partial class LuaUtil public static bool UTIL_IsValidModel(ReadOnlySpan name) { if (name.IsEmpty || name[0] <= ' ' || name.Length <= 3) return false; - if (name.Contains(".bsp", StringComparison.OrdinalIgnoreCase)) + if (!stristr(name, ".bsp").IsEmpty) return false; if (stricmp(name[^4..], ".mdl") != 0) return false; -#if GAME_DLL +#if CLIENT_DLL + int index = UTIL_GetModelIndex(name); +#else if (!engine.IsModelPrecached(name) && !filesystem.FileExists(name, "GAME")) return false; -#endif int index = BaseEntity.PrecacheModel(name); +#endif if (index == -1) return false; @@ -61,6 +63,60 @@ public static bool UTIL_IsValidModel(ReadOnlySpan name) { return !error; } + public static int UTIL_GetModelIndex(ReadOnlySpan name) { + if (name.Contains('*')) + return -1; + if (name.IsEmpty || (name[0] & 0xDF) == 0) + return -1; + return modelinfo.GetModelIndex(name); + } + + public static bool UTIL_IsValidPropModel(ReadOnlySpan name) { + if (!UTIL_IsValidModel(name)) + return false; + if (!stristr(name, "coreball.mdl").IsEmpty) + return false; +#if CLIENT_DLL + VCollide? collide = modelinfo.GetVCollide(UTIL_GetModelIndex(name)); +#else + VCollide? collide = modelinfo.GetVCollide(BaseEntity.PrecacheModel(name)); +#endif + return collide != null && collide.SolidCount == 1; + } + + public static bool UTIL_IsValidRagdollModel(ReadOnlySpan name) { + if (!UTIL_IsValidModel(name)) + return false; +#if CLIENT_DLL + VCollide? collide = modelinfo.GetVCollide(UTIL_GetModelIndex(name)); +#else + VCollide? collide = modelinfo.GetVCollide(BaseEntity.PrecacheModel(name)); +#endif + return collide != null && collide.SolidCount > 1; + } + + [LuaFunction] + static int IsValidRagdoll(ILuaInterface lua) { + string? name = lua.CheckString(1); + if (!string.IsNullOrEmpty(name) && ' ' < name[0]) { + lua.PushBool(UTIL_IsValidRagdollModel(name)); + return 1; + } + lua.PushBool(false); + return 0; + } + + [LuaFunction] + static int IsValidProp(ILuaInterface lua) { + string? name = lua.CheckString(1); + if (!string.IsNullOrEmpty(name) && ' ' < name[0]) { + lua.PushBool(UTIL_IsValidPropModel(name)); + return 1; + } + lua.PushBool(false); + return 0; + } + [LuaFunction] static int PrecacheModel(ILuaInterface lua) { if (UTIL_IsValidModel(g_Lua!.CheckString(1))) @@ -68,6 +124,17 @@ static int PrecacheModel(ILuaInterface lua) { return 0; } + [LuaFunction] + static int IsValidModel(ILuaInterface lua) { + string? name = lua.CheckString(1); + if (!string.IsNullOrEmpty(name) && ' ' < name[0]) { + lua.PushBool(UTIL_IsValidModel(name)); + return 1; + } + lua.PushBool(false); + return 0; + } + [LuaFunction] static int PrecacheSound(ILuaInterface lua) { BaseEntity.PrecacheScriptSound(g_Lua!.CheckString(1)); From 6270c1238efe0d5a167a50b9921bc1c0a7c6236d Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Sat, 10 Oct 2026 11:36:23 +0100 Subject: [PATCH 14/23] Render spawnicons --- Game.Client/ClientEntityList.cs | 3 +- Game.Client/GarrysMod/SpawnIcon.cs | 529 +++++++++++++++++++++- Game.Client/SourceDllMain.cs | 1 + Game.Client/View.cs | 14 +- Game.Shared/GarrysMod/LuaEntity.cs | 76 ++++ Source.Common/Engine/IModelRender.cs | 1 + Source.Common/GarrysMod/IResources.cs | 2 +- Source.Common/Mathematics/LightDesc.cs | 68 +++ Source.Common/Mathematics/MathLib.cs | 51 +++ Source.Engine/GarrysMod/Resources.cs | 46 +- Source.Engine/ImplStudio.cs | 6 +- Source.Engine/ModelInfo.cs | 6 +- Source.MaterialSystem/MatRenderContext.cs | 28 +- Source.ShaderAPI.Gl46/ShaderAPIGl46.cs | 74 ++- 14 files changed, 842 insertions(+), 63 deletions(-) diff --git a/Game.Client/ClientEntityList.cs b/Game.Client/ClientEntityList.cs index 6101a9a2b..32360004e 100644 --- a/Game.Client/ClientEntityList.cs +++ b/Game.Client/ClientEntityList.cs @@ -33,7 +33,8 @@ public class ClientEntityList : BaseEntityList, IClientEntityList public IClientUnknown? GetListedEntity(int entNum) => (IClientUnknown?)LookupEntityByNetworkIndex(entNum); public IClientEntity? GetClientEntityFromHandle(in BaseHandle ent) { - throw new NotImplementedException(); + IClientUnknown? pEnt = GetClientUnknownFromHandle(ent); + return pEnt == null ? null : pEnt.GetIClientEntity(); } public IClientNetworkable? GetClientNetworkable(int entnNum) { diff --git a/Game.Client/GarrysMod/SpawnIcon.cs b/Game.Client/GarrysMod/SpawnIcon.cs index 62373b0b4..5a3f01b58 100644 --- a/Game.Client/GarrysMod/SpawnIcon.cs +++ b/Game.Client/GarrysMod/SpawnIcon.cs @@ -1,20 +1,453 @@ +using Game.Shared.GarrysMod; + +using Source; +using Source.Common; +using Source.Common.Bitmap; +using Source.Common.Commands; +using Source.Common.Engine; +using Source.Common.GarrysMod.Lua; using Source.Common.GUI; using Source.Common.MaterialSystem; +using Source.Common.Mathematics; using Source.GUI.Controls; +using System.Numerics; + namespace Game.Client.GarrysMod; public class SpawnIconRenderer { + const float DefaultCamYaw = 190.0f; + const float DefaultCamFOV = 20.0f; + const float ZNear = 0.1f; + const float ZFar = 16192.0f; + const float AmbientLight = 0.3f; + const float SharpenAmount = 0.25f; + const int MaxLights = 4; + const int LightboxSides = 6; + const int IntRenderParm = 10; + const int DefaultLightType = 1; + const float DefaultAngularFalloff = 5.0f; + const float DefaultConeAngle = 45.0f; + const float DefaultFiftyPercentDistance = 64.0f; + const float DefaultZeroPercentDistance = 128.0f; + + static readonly ConVar spawnicon_sharpen = new("spawnicon_sharpen", "4", 0); + static readonly IMaterialSystemHardwareConfig HardwareConfig = Singleton(); + + static readonly List Renderers = []; + static readonly Vector3[] DefaultLightbox = [ + new(1.3f, 1.3f, 1.3f), + new(0.2f, 0.2f, 0.2f), + new(0.2f, 0.2f, 0.2f), + new(0.2f, 0.2f, 0.2f), + new(2.3f, 2.3f, 2.3f), + new(0.1f, 0.1f, 0.1f), + ]; + static readonly Vector3 White = new(1, 1, 1); + static ITexture? Cubemap; + + public string ModelName = ""; + public string BodyGroups = ""; + public string MaterialPath = ""; + public int Skin; + public int Wide; + public int Tall; public bool Finished; public bool Abort; + public Vector3 CamPos; + public QAngle CamAng; + public Vector3 CustomPos; + public QAngle CustomAng; + public float CustomFOV; + public bool CustomCamera; + public BaseHandle Entity; + public int LightCount; + public InlineArray4 Lights; + public bool UseLightbox; + public InlineArray6 Lightbox; + + public SpawnIconRenderer(string modelName, string spawnIconPath, int skin, string bodyGroups, int wide, int tall, LuaObject? camera) { + Wide = (int)BitOperations.RoundUpToPowerOf2((uint)wide); + Tall = (int)BitOperations.RoundUpToPowerOf2((uint)tall); + ModelName = modelName; + MaterialPath = "materials\\" + spawnIconPath; + Skin = skin; + BodyGroups = bodyGroups; + + Renderers.Add(this); + + CustomCamera = false; + CamPos = default; + CamAng = new(0, DefaultCamYaw, 0); + Entity = new(Constants.INVALID_EHANDLE_INDEX); + UseLightbox = false; + LightCount = 0; + + if (camera == null) + return; + + CustomCamera = true; + C_BaseEntity? ent = (C_BaseEntity?)camera.GetMemberEntity("ent", null); + Entity = ent == null ? new(Constants.INVALID_EHANDLE_INDEX) : ent.GetRefEHandle(); + CustomAng = camera.GetMemberAngle("cam_ang", CamAng); + CustomPos = camera.GetMemberVector("cam_pos", CamPos); + CustomFOV = camera.GetMemberFloat("cam_fov", DefaultCamFOV); + + C_BaseEntity? handleEnt = GetEntity(); + if (handleEnt != null) { + CamAng = handleEnt.GetAbsAngles(); + CamPos = handleEnt.GetAbsOrigin(); + } + + LuaObject lights = new(); + camera.GetMember("lights", lights); + if (lights.isTable()) { + for (int i = 1; i < MaxLights + 1; i++) { + LuaObject light = new(); + lights.GetMember(i, light); + if (!light.isTable()) { + light.UnReference(); + break; + } + + ParseLight(ref Lights[i - 1], light); + LightCount++; + light.UnReference(); + } + } + + LuaObject lightbox = new(); + camera.GetMember("lightbox", lightbox); + if (lightbox.isTable()) { + UseLightbox = true; + for (int i = 1; i < LightboxSides + 1; i++) { + LuaObject side = new(); + lightbox.GetMember(i, side); + Lightbox[i - 1] = side.isVector() ? side.GetVector() : default; + side.UnReference(); + } + } + + lightbox.UnReference(); + lights.UnReference(); + } + + static void ParseLight(ref LightDesc desc, LuaObject light) { + desc.Type = (LightType)Math.Clamp(light.GetMemberInt("type", DefaultLightType), 0, 3); + desc.Color = light.GetMemberVector("color", vec3_origin); + desc.Position = light.GetMemberVector("pos", vec3_origin); + desc.Direction = light.GetMemberVector("dir", vec3_origin); + desc.Range = light.GetMemberFloat("range", 0); + desc.Falloff = light.GetMemberFloat("angularFalloff", DefaultAngularFalloff); + desc.Theta = (float)(light.GetMemberFloat("innerAngle", DefaultConeAngle) * (Math.PI / 180.0)); + desc.Phi = (float)(light.GetMemberFloat("outerAngle", DefaultConeAngle) * (Math.PI / 180.0)); + + if (!light.MemberIsNil("fiftyPercentDistance") && !light.MemberIsNil("zeroPercentDistance")) + desc.SetupNewStyleAttenuation(light.GetMemberFloat("fiftyPercentDistance", DefaultFiftyPercentDistance), light.GetMemberFloat("zeroPercentDistance", DefaultZeroPercentDistance)); + else + desc.SetupOldStyleAttenuation(light.GetMemberFloat("quadraticFalloff", 0), light.GetMemberFloat("linearFalloff", 0), light.GetMemberFloat("constantFalloff", 1.0f)); + + desc.RecalculateDerivedValues(); + } + + public void Remove() => Renderers.Remove(this); + + C_BaseEntity? GetEntity() => (C_BaseEntity?)cl_entitylist.GetClientEntityFromHandle(Entity); + + public static void RenderQueued() { + SpawnIcon.ResetQueueTime(); + if (Renderers.Count == 0) + return; + + Cubemap = materials.FindTexture(HardwareConfig.GetHDREnabled() ? "editor/cubemap.hdr" : "editor/cubemap", null, true); + + SpawnIconRenderer[] queued = [.. Renderers]; + if (queued.Length != 0) { + queued[0].Render(); + Renderers.Remove(queued[0]); + } + + Cubemap = null; + } + + C_BaseFlex? CreateEntity() { + C_BaseFlex ent = new(); + + if (LuaUtil.UTIL_GetModelIndex(ModelName) < 1) { + if (ent.InitializeAsClientEntity(null, RenderGroup.TranslucentEntity)) { + Model? model = modelinfo.FindOrLoadModel(ModelName); + ent.SetModelPointer(model); + + StudioHeader? hdr = modelinfo.GetStudiomodel(model); + if (hdr == null || ((strcmp(hdr.GetName(), "error.mdl") != 0 || ModelName == "models/error.mdl") && hdr.NumBodyParts >= 1)) + return SetupEntity(ent); + } + } + else if (ent.InitializeAsClientEntity(ModelName, RenderGroup.TranslucentEntity)) + return SetupEntity(ent); + + ent.Release(); + return null; + } + + C_BaseFlex SetupEntity(C_BaseFlex ent) { + for (int i = 0; i < BodyGroups.Length; i++) { + char c = BodyGroups[i]; + int value = -1; + if ((uint)(c - '0') < 10) + value = c - '0'; + if ((uint)(c - 'a') < 26) + value = c - 'a' + 10; + if ((uint)(c - 'A') < 26) + value = c - 'A' + 10; + if (value >= 0) + ent.SetBodygroup(i, value); + } + + ent.Skin = Skin; + ent.Spawn(); + return ent; + } + + void PositionSpawnIcon(C_BaseEntity ent, ref ViewSetup view) { + C_BasePlayer.GetLocalPlayer()!.EyeVectors(out _); + ent.SetAbsAngles(CamAng); + ent.SetAbsOrigin(CamPos); + + if (!CustomCamera) { + if (g_Lua != null && g_Lua.Global() != null) { + LuaObject func = new(); + g_Lua.Global().GetMember("PositionSpawnIcon", func); + if (func.isFunction()) { + func.Push(); + LuaEntity.Push_Entity(ent); + g_Lua.PushVector(CamPos); + + LuaObject ret = new(); + if (g_Lua.CallInternalGet(2, ret) && ret.isTable()) { + view.FOV = ret.GetMemberFloat("fov", view.FOV); + view.Origin = ret.GetMemberVector("origin", view.Origin); + view.Angles = ret.GetMemberAngle("angles", view.Angles); + } + ret.UnReference(); + } + func.UnReference(); + } + + if (!CustomCamera) + return; + } + + view.Origin = CustomPos; + view.Angles = CustomAng; + view.FOV = CustomFOV; + } + + void Render() { + C_BaseEntity? ent = GetEntity(); + if (ent == null) { + C_BaseFlex? flex = CreateEntity(); + if (flex == null) { + Finished = true; + return; + } + + flex.AddEffects(EntityEffects.NoDraw | EntityEffects.NoInterp); + + C_BaseAnimating? animating = flex.GetBaseAnimating(); + if (animating != null) { + int sequence = animating.LookupSequence("WalkUnarmed_all"); + if (sequence > 0 || (sequence = animating.LookupSequence("walk_all_moderate")) > 0) + animating.SetSequence(sequence); + + animating.InvalidateBoneCache(); + animating.FrameAdvance(0); + animating.StudioFrameAdvance(); + + if (!stristr(ModelName, "\\spy.mdl").IsEmpty && Skin >= 4) + animating.SetBodygroup(1, 1); + } + + ent = flex; + } + else { + StudioHeader? hdr = modelinfo.GetStudiomodel(ent.GetModel()); + if (hdr != null && strcmp(hdr.GetName(), "error.mdl") == 0 && ModelName != "models/error.mdl") { + Finished = true; + return; + } + } + + ViewSetup viewSetup = view.GetViewSetup(); + PositionSpawnIcon(ent, ref viewSetup); + + viewSetup.X = 0; + viewSetup.Y = 0; + viewSetup.Width = Math.Min(Wide * 2, ScreenWidth()); + viewSetup.Height = Math.Min(Tall * 2, ScreenHeight()); + viewSetup.RenderToSubrectOfLargerScreen = true; + viewSetup.OffCenter = false; + viewSetup.Ortho = false; + viewSetup.DoBloomAndToneMapping = false; + viewSetup.CacheFullSceneState = false; + viewSetup.AspectRatio = (float)viewSetup.Width / viewSetup.Height; + viewSetup.ZNear = ZNear; + viewSetup.ZFar = ZFar; + + C_BaseAnimating? entAnimating = ent.GetBaseAnimating(); + if (entAnimating != null) + entAnimating.OverrideViewTarget = viewSetup.Origin; + + Frustum frustum = new(); + using MatRenderContextPtr renderContext = new(materials); + + render.Push3DView(viewSetup, 0, null, frustum, null); + modelrender.SuppressEngineLighting(false); + renderContext.BindLocalCubemap(Cubemap); + renderContext.SetLightingOrigin(vec3_origin); + renderContext.SetAmbientLight(AmbientLight, AmbientLight, AmbientLight); + modelrender.SuppressEngineLighting(true); + render.SetColorModulation(White); + render.SetBlend(1.0f); + + Span lightbox = stackalloc Vector3[LightboxSides]; + if (UseLightbox) + ((ReadOnlySpan)Lightbox).CopyTo(lightbox); + else + DefaultLightbox.CopyTo(lightbox); + studiorender.SetAmbientLightColors(lightbox); + + if (LightCount < 1) + studiorender.SetLocalLights(0, null); + else + studiorender.SetLocalLights(LightCount, ((ReadOnlySpan)Lights)[..LightCount]); + + renderContext.SetIntRenderingParameter(IntRenderParm, 0); + renderContext.DepthRange(0.0f, 1.0f); + + int size = viewSetup.Width * viewSetup.Height * 4; + byte[] red = new byte[size]; + byte[] green = new byte[size]; + byte[] blue = new byte[size]; + + renderContext.ClearColor4ub(255, 0, 0, 0); + renderContext.ClearBuffers(true, true); + RenderPass(red, ent, renderContext, viewSetup.Width, viewSetup.Height); + + renderContext.ClearColor4ub(0, 255, 0, 0); + renderContext.ClearBuffers(true, true); + RenderPass(green, ent, renderContext, viewSetup.Width, viewSetup.Height); + + renderContext.ClearColor4ub(0, 0, 255, 0); + renderContext.ClearBuffers(true, true); + RenderPass(blue, ent, renderContext, viewSetup.Width, viewSetup.Height); + + CombinePasses(red, green, blue, viewSetup.Width, viewSetup.Height); + + string dir = MaterialPath; + Bootil.String.File.StripFilename(ref dir); + filesystem.CreateDirHierarchy(dir, "DEFAULT_WRITE_PATH"); + + get.Resources()!.SavePNG(viewSetup.Width, viewSetup.Height, red, MaterialPath, Wide, Tall); + + modelrender.SuppressEngineLighting(false); + renderContext.BindLocalCubemap(null); + render.PopView(frustum); + + if (ent != GetEntity()) + ent.Release(); + + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.SpawniconGenerated)) { + g_Lua!.PushString(ModelName); + g_Lua.PushString(MaterialPath); + g_Lua.PushNumber(Renderers.Count); + gGM.CallNoReturns(3); + } + + Finished = true; + if (Abort) + Remove(); + } + + void RenderPass(Span pixels, C_BaseEntity ent, IMatRenderContext renderContext, int width, int height) { + C_BaseEntity? handleEnt = GetEntity(); + if (handleEnt != null) + ent = handleEnt; + + if (ent.UsesPowerOfTwoFrameBufferTexture() || ent.UsesFullFrameBufferTexture()) + UpdateRefractTexture(0, 0, width, height, true); + + ent.DrawModel(StudioFlags.Render); + renderContext.ReadPixels(0, 0, width, height, pixels, ImageFormat.BGRA8888); + } + + static int Clamp255(int value) => value < 0 ? 0 : value > 255 ? 255 : value; + + static void CombinePasses(Span red, Span green, Span blue, int width, int height) { + const float Inv255 = 1.0f / 255.0f; + const float Inv510 = 1.0f / 510.0f; + const float Half = 127.5f; + + for (int i = 0; i < width * height * 4; i += 4) { + int rB = red[i], rG = red[i + 1], rR = red[i + 2]; + int gB = green[i], gG = green[i + 1], gR = green[i + 2]; + int bB = blue[i], bG = blue[i + 1], bR = blue[i + 2]; + + float alphaR = Math.Clamp(rR * Inv255 - (bR + gR) * Inv510, 0.0f, 1.0f); + float alphaG = Math.Clamp(gG * Inv255 - (bG + rG) * Inv510, 0.0f, 1.0f); + float alphaB = Math.Clamp(bB * Inv255 - (rB + gB) * Inv510, 0.0f, 1.0f); + float background = alphaG * alphaR * alphaB; + float add = background * Half; + + byte r = (byte)Clamp255((int)((gR + bR) / 2 + add)); + byte g = (byte)Clamp255((int)((bG + rG) / 2 + add)); + byte b = (byte)Clamp255((int)(((rB + gB) >> 1) + add)); + byte a = (byte)Clamp255((int)((1.0f - background) * 255.0f)); + + red[i] = green[i] = b; + red[i + 1] = green[i + 1] = g; + red[i + 2] = green[i + 2] = r; + red[i + 3] = green[i + 3] = a; + } + + float sharpen = spawnicon_sharpen.GetFloat(); + if (sharpen == 0.0f) + return; + + int pitch = width * 4; + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + int i = y * pitch + x * 4; + if (x != 0 && y != 0 && x < width - 1 && y < height - 1) { + for (int c = 0; c < 4; c++) + red[i + c] = (byte)Sharpen(green, pitch, x, y, c, red[i + c], sharpen); + } + } + } + } + + static int Sharpen(ReadOnlySpan src, int pitch, int x, int y, int channel, int value, float amount) { + int left = src[y * pitch + (x - 1) * 4 + channel]; + int right = src[y * pitch + (x + 1) * 4 + channel]; + int up = src[(y - 1) * pitch + x * 4 + channel]; + int down = src[(y + 1) * pitch + x * 4 + channel]; + + int sum = (int)((int)((int)((up - value) * amount) + (int)((int)((left - value) * amount) - (int)((right - value) * amount))) - (int)((down - value) * amount)); + return Clamp255((int)(sum * SharpenAmount + value)); + } } public class SpawnIcon : Panel { + const double QueueBudget = 0.1; + + static readonly ConVar spawnicon_queue = new("spawnicon_queue", "0", 0, "Enables experimental spawnicon loading queue, which prevents the game from freezing when opening large spawnlists."); + static TextureID GeneratingTexture = -1; static TextureID BrokenTexture = -1; static TextureID MaterialTexture = -1; + static double QueueTime; string SpawnIconPath = ""; string BodyGroups = ""; @@ -24,6 +457,8 @@ public class SpawnIcon : Panel bool Failed; IMaterial? Material; + public static void ResetQueueTime() => QueueTime = 0; + public SpawnIcon(Panel? parent, ReadOnlySpan name) : base(parent, name) { SetSize(64, 64); @@ -46,6 +481,20 @@ public SpawnIcon(Panel? parent, ReadOnlySpan name) : base(parent, name) { SetPaintBorderEnabled(false); } + public override void Dispose() { + if (Renderer != null) { + Renderer.Remove(); + Renderer = null; + } + + if (Material != null) { + Material.DecrementReferenceCount(); + Material = null; + } + + base.Dispose(); + } + public override void OnSizeChanged(int newWide, int newTall) { base.OnSizeChanged(newWide, newTall); if (ModelName.Length != 0 && !Failed) @@ -53,23 +502,14 @@ public override void OnSizeChanged(int newWide, int newTall) { } public override void Paint() { - if (Failed) { - surface.DrawSetTexture(BrokenTexture); - surface.DrawSetColor(255, 255, 255, 255); - surface.DrawTexturedRect(0, 0, GetWide(), GetTall()); - return; - } - - if (Material != null && Renderer == null) { + if (!Failed && Material != null && Renderer == null) { if (MaterialTexture == -1) MaterialTexture = surface.CreateNewTextureID(false); surface.DrawSetTextureMaterial(MaterialTexture, Material); - surface.DrawSetColor(255, 255, 255, 255); - surface.DrawTexturedRect(0, 0, GetWide(), GetTall()); - return; } + else + surface.DrawSetTexture(Failed ? BrokenTexture : GeneratingTexture); - surface.DrawSetTexture(GeneratingTexture); surface.DrawSetColor(255, 255, 255, 255); surface.DrawTexturedRect(0, 0, GetWide(), GetTall()); } @@ -77,20 +517,53 @@ public override void Paint() { public override void OnThink() { base.OnThink(); - if (Material == null) { - if (Failed) - return; - if (Renderer == null && SpawnIconPath.Length != 0) - ThinkRender(); + if ((Material != null && Renderer == null) || Failed) + return; + + if (Material == null && Renderer == null && SpawnIconPath.Length != 0) { + if (spawnicon_queue.GetInt() == 0) + StartRender(); + else if (gpGlobals.AbsoluteFrameTime + QueueTime < QueueBudget || QueueTime == 0.0) { + double start = Platform.Time; + StartRender(); + QueueTime += Platform.Time - start; + } } - else if (Renderer == null || Failed) + + if (Renderer == null || !Renderer.Finished) + return; + + Renderer.Remove(); + Renderer = null; + + if (Material == null) { + Material = get.Resources()!.FindMaterial(SpawnIconPath, "", true, false, false); + if (Material != null) + Material.IncrementReferenceCount(); + else + Failed = true; return; + } - if (Renderer != null) - ThinkRender(); + string path = SpawnIconPath; + Bootil.String.File.ExtractFilename(ref path); + Bootil.String.File.StripExtension(ref path); + string cmd = "mat_reloadmaterial " + path + "\n"; + if (!cmd.Contains(';')) + engine.ClientCmd(cmd); } - void ThinkRender() { } // TODO + void StartRender() { + Material = get.Resources()!.FindMaterial(SpawnIconPath, "", true, false, false); + if (Material != null) { + Material.IncrementReferenceCount(); + return; + } + + RebuildSpawnIcon(); + if (Renderer == null) + Failed = true; + } public virtual void SetModel(string modelName, int skin, string bodyGroups) { Skin = skin; @@ -174,7 +647,17 @@ public virtual void SetSpawnIcon(string path) { SpawnIconPath = ""; } - public virtual void RebuildSpawnIcon() => throw new NotImplementedException(); + public virtual void RebuildSpawnIcon() { + if (Renderer == null && ModelName.Length != 0) { + Renderer = new SpawnIconRenderer(ModelName, SpawnIconPath, Skin, BodyGroups, GetWide(), GetTall(), null); + Failed = false; + } + } - public virtual void RebuildSpawnIconEx() => throw new NotImplementedException(); + public virtual void RebuildSpawnIconEx(LuaObject camera) { + if (Renderer == null && ModelName.Length != 0) { + Renderer = new SpawnIconRenderer(ModelName, SpawnIconPath, Skin, BodyGroups, GetWide(), GetTall(), camera); + Failed = false; + } + } } diff --git a/Game.Client/SourceDllMain.cs b/Game.Client/SourceDllMain.cs index 952e0aa4e..836bd36f1 100644 --- a/Game.Client/SourceDllMain.cs +++ b/Game.Client/SourceDllMain.cs @@ -74,6 +74,7 @@ public static void Link(IServiceCollection services) { [Dependency] public static IMaterialSystem materials { get; private set; } = null!; [Dependency] public static IInput input { get; private set; } = null!; [Dependency] public static IModelRender modelrender { get; private set; } = null!; + [Dependency] public static IStudioRender studiorender { get; private set; } = null!; [Dependency] public static IVEfx effects { get; private set; } = null!; [Dependency] public static IFileSystem filesystem { get; private set; } = null!; [Dependency] public static ISchemeManager vguiSchemeManager { get; private set; } = null!; diff --git a/Game.Client/View.cs b/Game.Client/View.cs index 6f1c6ff0b..d96770301 100644 --- a/Game.Client/View.cs +++ b/Game.Client/View.cs @@ -1,6 +1,9 @@ global using static Game.Client.ViewConVars; global using static Game.Client.ViewAccessors; +#if GMOD_DLL +using Game.Client.GarrysMod; +#endif using Game.Shared; using Microsoft.Extensions.DependencyInjection; @@ -97,7 +100,7 @@ public class ViewRender : IViewRender static ConVar r_nearz = new(VIEW_NEARZ.ToString(), FCvar.Cheat, "Override the near clipping plane."); static ConVar r_farz = new("-1", FCvar.Cheat, "Override the far clipping plane. -1 means to use the value in env_fog_controller."); - public ViewSetup? CurrentView; + public ViewSetup CurrentView; bool ForceNoVis; DrawFlags BaseDrawFlags; Frustum Frustum; @@ -144,7 +147,7 @@ public void GetScreenFadeDistances(out float min, out float max) { } public ref ViewSetup GetViewSetup() { - throw new NotImplementedException(); + return ref CurrentView; } public void GetWaterLODParams(ref float cheapWaterStartDistance, ref float cheapWaterEndDistance) { @@ -330,6 +333,11 @@ public void Render(ViewRects rect) { throw new NotImplementedException("Stereo-eye not yet implemented"); } +#if GMOD_DLL + if (LuaRender.RenderViewID == ViewID.Illegal) + SpawnIconRenderer.RenderQueued(); +#endif + ClearFlags clearFlags = ClearFlags.ClearColor | ClearFlags.ClearDepth | ClearFlags.ClearStencil; bool drawViewModel = true; // todo @@ -380,6 +388,8 @@ public void Render(ViewRects rect) { IEngineVGui enginevgui => _enginevgui ??= Singleton(); public void RenderView(in ViewSetup viewRender, ClearFlags clearFlags, RenderViewInfo whatToDraw) { + CurrentView = viewRender; + using C_BaseAnimating.AutoAllowBoneAccess boneaccess = new(true, true); MatRenderContextPtr renderContext; diff --git a/Game.Shared/GarrysMod/LuaEntity.cs b/Game.Shared/GarrysMod/LuaEntity.cs index b27b8a366..93026c82c 100644 --- a/Game.Shared/GarrysMod/LuaEntity.cs +++ b/Game.Shared/GarrysMod/LuaEntity.cs @@ -233,6 +233,82 @@ static int Entity__SetBodyGroups(ILuaInterface lua) { return 0; } + [LuaMethod] + static int Entity__LookupAttachment(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating != null && !ent.IsMarkedForDeletion()) { + lua.PushNumber(animating.LookupAttachment(lua.CheckString(2))); + return 1; + } + lua.PushNumber(0); + return 1; + } + + [LuaMethod] + static int Entity__SelectWeightedSequence(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating == null || IsEntityRemoving(ent, false)) + return 0; + + if ((uint)(int)lua.CheckNumber(2) > int.MaxValue) + lua.ArgError(2, "invalid act"); + + lua.PushNumber(animating.SelectWeightedSequence((Activity)(int)lua.CheckNumber(2))); + return 1; + } + + [LuaMethod] + static int Entity__GetModel(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + if (ent.IsWeapon() && ent is BaseCombatWeapon weapon) { + string worldModel = new string(weapon.GetWorldModel()).ToLowerInvariant(); + lua.PushString(worldModel); + return 1; + } + +#if CLIENT_DLL + ReadOnlySpan name = ent.GetModelName(); + if (name.IsEmpty) { + Model? model = ent.GetModel(); + if (model != null) + name = modelinfo.GetModelName(model); + } + + if (name.IsEmpty) { + C_BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating != null && !ent.IsMarkedForDeletion()) { + StudioHdr? hdr = animating.GetModelPtr(); + if (hdr != null) { + string path = $"models/{hdr.Name()}".Replace('\\', '/'); + name = path; + } + } + } + + if (name.IsEmpty) + return 0; +#else + ReadOnlySpan name = ent.GetModelName(); + if (name.IsEmpty) + return 0; +#endif + lua.PushString(new string(name).ToLowerInvariant()); + return 1; + } + +#if CLIENT_DLL + [LuaMethod] + static int Entity__GetRenderBounds(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + ent.GetRenderBounds(out Vector3 mins, out Vector3 maxs); + LuaVector.Push_Vector(mins); + LuaVector.Push_Vector(maxs); + return 2; + } +#endif + [LuaMethod] static int Entity__NearestPoint(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; diff --git a/Source.Common/Engine/IModelRender.cs b/Source.Common/Engine/IModelRender.cs index af2086857..b57acfdd4 100644 --- a/Source.Common/Engine/IModelRender.cs +++ b/Source.Common/Engine/IModelRender.cs @@ -64,4 +64,5 @@ public interface IModelRender ref Matrix4x4 SetupModelState(IClientRenderable renderable); bool DrawModelShadowSetup(IClientRenderable renderable, int body, int skin, ref Source.Common.DrawModelInfo info, Span customBoneToWorld, out Span boneToWorldOut); void DrawModelShadow(IClientRenderable renderable, in Source.Common.DrawModelInfo info, Span boneToWorld); + void SuppressEngineLighting(bool suppress); } diff --git a/Source.Common/GarrysMod/IResources.cs b/Source.Common/GarrysMod/IResources.cs index ca009f92a..e1bc3110e 100644 --- a/Source.Common/GarrysMod/IResources.cs +++ b/Source.Common/GarrysMod/IResources.cs @@ -44,7 +44,7 @@ public interface IResources IVideoHolly? CreateMovie(); IMaterial? FindMaterial(ReadOnlySpan unk1, ReadOnlySpan unk2, bool unk3, bool unk4, bool unk5); Color GetTextureColour(ITexture unk1, int unk2, int unk3); - void SavePNG(int unk1, int unk2, Span unk3, ReadOnlySpan unk4, int unk5, int unk6); + void SavePNG(int unk1, int unk2, Span unk3, ReadOnlySpan unk4, int unk5, int unk6); void SaveJPG(int unk1, int unk2, int unk3, Span unk4, ReadOnlySpan unk5, int unk6, int unk7, Stream unk8); bool ShouldRecordSound(); void AudioSamples(Span unk1, uint unk2 /* probably size of unk1*/, byte unk3, byte unk4); diff --git a/Source.Common/Mathematics/LightDesc.cs b/Source.Common/Mathematics/LightDesc.cs index c9e0ecebd..81acce578 100644 --- a/Source.Common/Mathematics/LightDesc.cs +++ b/Source.Common/Mathematics/LightDesc.cs @@ -39,4 +39,72 @@ public struct LightDesc public uint Flags; private float OneOver_ThetaDot_Minus_PhiDot; private float RangeSquared; + + public void RecalculateDerivedValues() { + Flags = (uint)LightTypeOptimizationFlags.DerivedValuesCalced; + if (Attenuation0 != 0) + Flags |= (uint)LightTypeOptimizationFlags.HasAttenuation0; + if (Attenuation1 != 0) + Flags |= (uint)LightTypeOptimizationFlags.HasAttenuation1; + if (Attenuation2 != 0) + Flags |= (uint)LightTypeOptimizationFlags.HasAttenuation2; + + if (Type == LightType.Spot) { + ThetaDot = MathF.Cos(Theta); + PhiDot = MathF.Cos(Phi); + float spread = ThetaDot - PhiDot; + if (spread > 1.0e-10f) + OneOver_ThetaDot_Minus_PhiDot = 1.0f / spread; + else + OneOver_ThetaDot_Minus_PhiDot = 1.0f; + } + if (Type == LightType.Directional) { + Position = Direction; + Position *= 2.0e6f; + } + + RangeSquared = Range * Range; + } + + public void SetupOldStyleAttenuation(float quadraticAttn, float linearAttn, float constantAttn) { + if (quadraticAttn < EQUAL_EPSILON) + quadraticAttn = 0; + + if (linearAttn < EQUAL_EPSILON) + linearAttn = 0; + + if (constantAttn < EQUAL_EPSILON) + constantAttn = 0; + + if ((constantAttn < EQUAL_EPSILON) && (linearAttn < EQUAL_EPSILON) && (quadraticAttn < EQUAL_EPSILON)) + constantAttn = 1; + + Attenuation2 = quadraticAttn; + Attenuation1 = linearAttn; + Attenuation0 = constantAttn; + float scaleFactor = quadraticAttn * 10000 + linearAttn * 100 + constantAttn; + + if (scaleFactor > 0) + Color *= scaleFactor; + } + + public void SetupNewStyleAttenuation(float fiftyPercentDistance, float zeroPercentDistance) { + float d50 = fiftyPercentDistance; + float d0 = zeroPercentDistance; + if (d0 < d50) { + Warning($"light has _fifty_percent_distance of {d50:F6} but no zero_percent_distance\n"); + d0 = 2.0f * d50; + } + float a = 0, b = 1, c = 0; + if (!MathLib.SolveInverseQuadraticMonotonic(0, 1.0f, d50, 2.0f, d0, 256.0f, ref a, ref b, ref c)) + Warning($"can't solve quadratic for light {d50:F6} {d0:F6}\n"); + float v50 = c + d50 * (b + d50 * a); + float scale = 2.0f / v50; + a *= scale; + b *= scale; + c *= scale; + Attenuation2 = a; + Attenuation1 = b; + Attenuation0 = c; + } } diff --git a/Source.Common/Mathematics/MathLib.cs b/Source.Common/Mathematics/MathLib.cs index 144203f91..9335fe8d8 100644 --- a/Source.Common/Mathematics/MathLib.cs +++ b/Source.Common/Mathematics/MathLib.cs @@ -3700,6 +3700,57 @@ public static void BSpline(in Vector3 p1, in Vector3 p2, in Vector3 p3, in Vecto output += b; output += c; } + + public static float FLerp(float f1, float f2, float i1, float i2, float x) => f1 + (f2 - f1) * (x - i1) / (i2 - i1); + + public static bool SolveInverseQuadratic(float x1, float y1, float x2, float y2, float x3, float y3, out float a, out float b, out float c) { + a = b = c = 0; + float det = (x1 - x2) * (x1 - x3) * (x2 - x3); + + if (det == 0.0f) + return false; + + a = (x3 * (-y1 + y2) + x2 * (y1 - y3) + x1 * (-y2 + y3)) / det; + b = (x3 * x3 * (y1 - y2) + x1 * x1 * (y2 - y3) + x2 * x2 * (-y1 + y3)) / det; + c = (x1 * x3 * (-x1 + x3) * y2 + x2 * x2 * (x3 * y1 - x1 * y3) + x2 * (-(x3 * x3 * y1) + x1 * x1 * y3)) / det; + return true; + } + + public static bool SolveInverseQuadraticMonotonic(float x1, float y1, float x2, float y2, float x3, float y3, ref float a, ref float b, ref float c) { + if (x1 > x2) { + (x1, x2) = (x2, x1); + (y1, y2) = (y2, y1); + } + if (x2 > x3) { + (x2, x3) = (x3, x2); + (y2, y3) = (y3, y2); + } + if (x1 > x2) { + (x1, x2) = (x2, x1); + (y1, y2) = (y2, y1); + } + + for (int factor = 0; factor <= 100.0; factor += 5) { + float blendToLinearFactor = factor / 100.0f; + float tempy2 = (1 - blendToLinearFactor) * y2 + blendToLinearFactor * FLerp(y1, y3, x1, x3, x2); + if (!SolveInverseQuadratic(x1, y1, x2, tempy2, x3, y3, out a, out b, out c)) + return false; + float derivative = 2.0f * a + b; + if ((y1 < y2) && (y2 < y3)) { + if (derivative >= 0.0) + return true; + } + else { + if ((y1 > y2) && (y2 > y3)) { + if (derivative <= 0.0) + return true; + } + else + return true; + } + } + return true; + } } [StructLayout(LayoutKind.Sequential, Pack = 16, Size = sizeof(float) * 4 * 3)] diff --git a/Source.Engine/GarrysMod/Resources.cs b/Source.Engine/GarrysMod/Resources.cs index cfe995d05..29c3bab2a 100644 --- a/Source.Engine/GarrysMod/Resources.cs +++ b/Source.Engine/GarrysMod/Resources.cs @@ -230,7 +230,51 @@ public Color GetTextureColour(ITexture texture, int x, int y) { return new Color(0, 0, 0, 255); } - public void SavePNG(int unk1, int unk2, Span unk3, ReadOnlySpan unk4, int unk5, int unk6) => throw new NotImplementedException(); + public void SavePNG(int width, int height, Span pixels, ReadOnlySpan path, int outWidth, int outHeight) { + FIBITMAP bitmap = FreeImage.Allocate(width, height, 32, 0, 0, 0); + if (bitmap.IsNull) { + Warning("[CResources::SavePNG] Freeimage couldn't allocate!\n"); + return; + } + + IntPtr bits = FreeImage.GetBits(bitmap); + if (bits == IntPtr.Zero) { + Warning("[CResources::SavePNG] Freeimage couldn't GetBits!\n"); + return; + } + + unsafe { + pixels[..(width * height * 4)].CopyTo(new Span((byte*)bits, width * height * 4)); + } + + FIBITMAP output = bitmap; + if (outHeight != height || outWidth != width) { + output = FreeImage.Rescale(bitmap, outWidth, outHeight, FREE_IMAGE_FILTER.FILTER_BILINEAR); + FreeImage.Unload(bitmap); + } + + FreeImage.FlipVertical(output); + + FIMEMORY memory = FreeImage.OpenMemory(IntPtr.Zero, 0); + FreeImage.SaveToMemory(FREE_IMAGE_FORMAT.FIF_PNG, output, memory, FREE_IMAGE_SAVE_FLAGS.PNG_Z_BEST_SPEED); + + IntPtr data = IntPtr.Zero; + uint size = 0; + FreeImage.AcquireMemory(memory, ref data, ref size); + + IFileHandle? file = size == 0 || data == IntPtr.Zero ? null : g_pFileSystem.Open(path, FileOpenOptions.Write | FileOpenOptions.Binary); + if (file == null) + Warning($"Couldn't save PNG to '{path}' ({size} bytes)\n"); + else { + unsafe { + file.Stream.Write(new ReadOnlySpan((byte*)data, (int)size)); + } + file.Dispose(); + } + + FreeImage.CloseMemory(memory); + FreeImage.Unload(output); + } public void SaveJPG(int unk1, int unk2, int unk3, Span unk4, ReadOnlySpan unk5, int unk6, int unk7, Stream unk8) => throw new NotImplementedException(); public bool ShouldRecordSound() => throw new NotImplementedException(); public void AudioSamples(Span unk1, uint unk2, byte unk3, byte unk4) => throw new NotImplementedException(); diff --git a/Source.Engine/ImplStudio.cs b/Source.Engine/ImplStudio.cs index c3f2e0ec7..041fddde2 100644 --- a/Source.Engine/ImplStudio.cs +++ b/Source.Engine/ImplStudio.cs @@ -698,14 +698,16 @@ public void DrawModelExecute(ref DrawModelState state, ref ModelRenderInfo pInfo #endif } - bool SuppressEngineLighting = false; + bool EngineLightingSuppressed = false; + + public void SuppressEngineLighting(bool suppress) => EngineLightingSuppressed = suppress; LightingState ActualLightingState; readonly BSPDWorldLight[] WorldLights = new BSPDWorldLight[Render.MAXLOCALLIGHTS]; readonly BSPDWorldLightPtr[] SourceLight = new BSPDWorldLightPtr[Render.MAXLOCALLIGHTS]; private void StudioSetupLighting(DrawModelState state, in Vector3 absEntCenter, ref LightCacheHandle_t lightcache, bool vertexLit, bool needsEnvCubemap, ref bool staticLighting, ref DrawModelInfo drawInfo, ModelRenderInfo renderInfo, StudioRenderFlags drawFlags) { - if (SuppressEngineLighting) + if (EngineLightingSuppressed) return; #if !SWDS diff --git a/Source.Engine/ModelInfo.cs b/Source.Engine/ModelInfo.cs index 97010f3f8..9266121c0 100644 --- a/Source.Engine/ModelInfo.cs +++ b/Source.Engine/ModelInfo.cs @@ -212,7 +212,11 @@ public void OnDynamicModelsStringTableChange(int stringIndex, ReadOnlySpan } public Model? FindOrLoadModel(ReadOnlySpan name) { - throw new NotImplementedException(); + Model? model = GetModel(GetModelIndex(name)); + if (model != null) + return model; + + return modelloader.GetModelForName(name, ModelLoaderFlags.ClientDLL); } public VCollide? GetVCollide(Model? model) { diff --git a/Source.MaterialSystem/MatRenderContext.cs b/Source.MaterialSystem/MatRenderContext.cs index a9fd29ce8..7d82acff3 100644 --- a/Source.MaterialSystem/MatRenderContext.cs +++ b/Source.MaterialSystem/MatRenderContext.cs @@ -1071,9 +1071,7 @@ public void PushSelectionName(int name) { throw new NotImplementedException("Incomplete port of IMatRenderContext"); } - public void ReadPixels(int x, int y, int width, int height, Span data, ImageFormat dstFormat) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void ReadPixels(int x, int y, int width, int height, Span data, ImageFormat dstFormat) => shaderAPI.ReadPixels(x, y, width, height, data, dstFormat); public void ReadPixelsAndStretch(ref System.Drawing.Rectangle srcRect, ref System.Drawing.Rectangle pDstRect, Span buffer, ImageFormat dstFormat, int dstStride) { throw new NotImplementedException("Incomplete port of IMatRenderContext"); @@ -1119,9 +1117,7 @@ public void SetFlexWeights(int firstWeight, ReadOnlySpan weights) { throw new NotImplementedException("Incomplete port of IMatRenderContext"); } - public void SetFloatRenderingParameter(int parm_number, float value) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void SetFloatRenderingParameter(int parm_number, float value) => shaderAPI.SetFloatRenderingParameter(parm_number, value); public void SetFogZ(float fogZ) { throw new NotImplementedException("Incomplete port of IMatRenderContext"); @@ -1139,9 +1135,7 @@ public void SetHeightClipZ(float z) { throw new NotImplementedException("Incomplete port of IMatRenderContext"); } - public void SetIntRenderingParameter(int parm_number, int value) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void SetIntRenderingParameter(int parm_number, int value) => shaderAPI.SetIntRenderingParameter(parm_number, value); public void SetLookupWeight(ColorCorrectionHandle_t handle, float weight) { throw new NotImplementedException("Incomplete port of IMatRenderContext"); @@ -1171,9 +1165,7 @@ public void SetShadowDepthBiasFactors(float slopeScaleDepthBias, float depthBias throw new NotImplementedException("Incomplete port of IMatRenderContext"); } - public void SetVectorRenderingParameter(int parm_number, in Vector3 value) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void SetVectorRenderingParameter(int parm_number, in Vector3 value) => shaderAPI.SetVectorRenderingParameter(parm_number, value); public void SyncToken(ReadOnlySpan token) { throw new NotImplementedException("Incomplete port of IMatRenderContext"); @@ -1211,13 +1203,9 @@ public MatCallQueue GetCallQueueInternal() { throw new NotImplementedException("Incomplete port of IMatRenderContextInternal"); } - public float GetFloatRenderingParameter(int parmNumber) { - throw new NotImplementedException("Incomplete port of IMatRenderContextInternal"); - } + public float GetFloatRenderingParameter(int parmNumber) => shaderAPI.GetFloatRenderingParameter(parmNumber); - public int GetIntRenderingParameter(int parmNumber) { - throw new NotImplementedException("Incomplete port of IMatRenderContextInternal"); - } + public int GetIntRenderingParameter(int parmNumber) => shaderAPI.GetIntRenderingParameter(parmNumber); public void GetLightmapDimensions(out int w, out int h) { throw new NotImplementedException("Incomplete port of IMatRenderContextInternal"); @@ -1231,9 +1219,7 @@ public int GetLightmapPage() { throw new NotImplementedException("Incomplete port of IMatRenderContextInternal"); } - public Vector3 GetVectorRenderingParameter(int parmNumber) { - throw new NotImplementedException("Incomplete port of IMatRenderContextInternal"); - } + public Vector3 GetVectorRenderingParameter(int parmNumber) => shaderAPI.GetVectorRenderingParameter(parmNumber); public unsafe bool OnDrawMesh(IMesh mesh, PrimList* pLists, int nLists) { throw new NotImplementedException("Incomplete port of IMatRenderContextInternal"); diff --git a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs index 4fa49e05e..5d086b58a 100644 --- a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs +++ b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs @@ -125,7 +125,7 @@ public bool OnDeviceInit() { DeviceState DeviceState = DeviceState.OK; - public void ClearBuffers(bool clearColor, bool clearDepth, bool clearStencil, int renderTargetWidth = -1, int renderTargetHeight = -1) { + public unsafe void ClearBuffers(bool clearColor, bool clearDepth, bool clearStencil, int renderTargetWidth = -1, int renderTargetHeight = -1) { if (IsDeactivated()) return; @@ -145,18 +145,31 @@ public void ClearBuffers(bool clearColor, bool clearDepth, bool clearStencil, in glStencilMask(0xFF); if (flags != 0) { + bool* colorMask = stackalloc bool[4]; + glGetBooleanv(GL_COLOR_WRITEMASK, colorMask); + bool scissorWasEnabled = glIsEnabled(GL_SCISSOR_TEST); + if (clearColor) + glColorMask(true, true, true, true); + bool renderTargetMatchesViewport = (renderTargetWidth == -1 && renderTargetHeight == -1) || (renderTargetWidth == Viewport.Width && renderTargetHeight == Viewport.Height); - if (renderTargetMatchesViewport) + if (renderTargetMatchesViewport) { + glDisable(GL_SCISSOR_TEST); glClear(flags); + } else { glEnable(GL_SCISSOR_TEST); glScissor(Viewport.X, renderTargetHeight - (Viewport.Y + Viewport.Height), Viewport.Width, Viewport.Height); glClear(flags); glDisable(GL_SCISSOR_TEST); } + + if (scissorWasEnabled) + glEnable(GL_SCISSOR_TEST); + if (clearColor) + glColorMask(colorMask[0], colorMask[1], colorMask[2], colorMask[3]); } } @@ -2984,8 +2997,9 @@ public void SetDepthFeatheringPixelShaderConstant(int reg, float scale) { public int GetIntRenderingParameter(RenderParamInt parm) => GetIntRenderingParameter((int)parm); public int GetIntRenderingParameter(int parmNumber) { - // throw new NotImplementedException(); - return 0;// todo + if (parmNumber < 20) + return IntRenderingParameters[parmNumber]; + return 0; } public void SetPixelShaderStateAmbientLightCube(int reg, bool forceToBlack) { @@ -3251,8 +3265,35 @@ public void PushSelectionName(int name) { throw new NotImplementedException("Incomplete port of IShaderAPI"); } - public void ReadPixels(int x, int y, int width, int height, Span data, ImageFormat dstFormat) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + public unsafe void ReadPixels(int x, int y, int width, int height, Span data, ImageFormat dstFormat) { + FlushBufferedPrimitives(); + + int srcHeight; + if (UsingTextureRenderTarget) + srcHeight = ViewportMaxHeight; + else + GetBackBufferDimensions(out _, out srcHeight); + + int pitch = width * 4; + byte[] bits = new byte[pitch * height]; + + int prevRead, drawFBO; + glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &prevRead); + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &drawFBO); + glBindFramebuffer(GL_READ_FRAMEBUFFER, (uint)drawFBO); + glPixelStorei(GL_PACK_ALIGNMENT, 1); + fixed (byte* p = bits) + glReadPixels(x, srcHeight - (y + height), width, height, GL_BGRA, GL_UNSIGNED_BYTE, p); + glBindFramebuffer(GL_READ_FRAMEBUFFER, (uint)prevRead); + + byte[] flipped = new byte[pitch * height]; + for (int row = 0; row < height; row++) + bits.AsSpan((height - 1 - row) * pitch, pitch).CopyTo(flipped.AsSpan(row * pitch, pitch)); + + if (dstFormat == ImageFormat.BGRA8888) + flipped.AsSpan(0, Math.Min(flipped.Length, data.Length)).CopyTo(data); + else + ImageLoader.ConvertImageFormat(flipped, ImageFormat.BGRA8888, data, dstFormat, width, height); } public void ReadPixels(ref System.Drawing.Rectangle srcRect, ref System.Drawing.Rectangle dstRect, Span data, ImageFormat dstFormat, int dstStride) { @@ -3448,7 +3489,9 @@ public void GetDXLevelDefaults(out GraphicsDriver max, out GraphicsDriver recomm } public float GetFloatRenderingParameter(int parmNumber) { - throw new NotImplementedException("Incomplete port of IShaderDynamicAPI"); + if (parmNumber < 20) + return FloatRenderingParameters[parmNumber]; + return 0.0f; } public ref readonly LightDesc GetLight(int lightNum) { @@ -3480,7 +3523,9 @@ public void GetStandardTextureDimensions(out int width, out int height, Standard } public Vector3 GetVectorRenderingParameter(int parmNumber) { - throw new NotImplementedException("Incomplete port of IShaderDynamicAPI"); + if (parmNumber < 20) + return VectorRenderingParameters[parmNumber]; + return new(0, 0, 0); } public ref MeshBuilder GetVertexModifyBuilder() { @@ -3547,12 +3592,18 @@ public void SetBumpEnvMatrix(TextureStage textureStage, float m00, float m01, fl throw new NotImplementedException("Incomplete port of IShaderDynamicAPI"); } + InlineArray20 IntRenderingParameters; + InlineArray20 FloatRenderingParameters; + InlineArray20 VectorRenderingParameters; + public void SetFloatRenderingParameter(int parmNumber, float value) { - throw new NotImplementedException("Incomplete port of IShaderDynamicAPI"); + if (parmNumber < 20) + FloatRenderingParameters[parmNumber] = value; } public void SetIntRenderingParameter(int parmNumber, int value) { - throw new NotImplementedException("Incomplete port of IShaderDynamicAPI"); + if (parmNumber < 20) + IntRenderingParameters[parmNumber] = value; } public void SetIntegerPixelShaderConstant(int var, ReadOnlySpan vec, bool force = false ) { @@ -3576,7 +3627,8 @@ public void SetTextureTransformDimension(TextureStage textureStage, int dimensio } public void SetVectorRenderingParameter(int parmNumber, in Vector3 value) { - throw new NotImplementedException("Incomplete port of IShaderDynamicAPI"); + if (parmNumber < 20) + VectorRenderingParameters[parmNumber] = value; } public void Translate(float x, float y, float z) { From 37f18396c1c11d204b35afc169ea9b81e767d996 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Sat, 10 Oct 2026 15:28:45 +0100 Subject: [PATCH 15/23] Finish LuaSurface --- Game.Client/GarrysMod/LuaSurface.cs | 114 ++++++++++++++++-- Source.Common/GUI/ISurface.cs | 5 + .../Surface/MatSystemSurface.cs | 10 ++ 3 files changed, 120 insertions(+), 9 deletions(-) diff --git a/Game.Client/GarrysMod/LuaSurface.cs b/Game.Client/GarrysMod/LuaSurface.cs index ce4cf07a1..1bc436b0c 100644 --- a/Game.Client/GarrysMod/LuaSurface.cs +++ b/Game.Client/GarrysMod/LuaSurface.cs @@ -1,3 +1,5 @@ +using Game.Client.HUD; + using Source; using Source.Common.GarrysMod.Lua; using Source.Common.GUI; @@ -59,7 +61,12 @@ static int SetDrawColor(ILuaInterface lua) { return 0; } - // todo: GetDrawColor + [LuaFunction] + static int GetDrawColor(ILuaInterface lua) { + surface.DrawGetColor(out Color color); + lua.PushColor(color); + return 1; + } [LuaFunction] static void DrawRect([LuaGet] int x, [LuaGet] int y, [LuaGet] int w, [LuaGet] int h) => surface.DrawFilledRect(x, y, x + w, y + h); @@ -72,7 +79,15 @@ static void DrawOutlinedRect([LuaGet] int x, [LuaGet] int y, [LuaGet] int w, [Lu surface.DrawFilledRect(w - thickness + x, thickness + y, x + w, h - thickness + y); } - // todo: DrawLine + [LuaFunction] + static int DrawLine(ILuaInterface lua) { + float y1 = (float)lua.CheckNumber(4); + float x1 = (float)lua.CheckNumber(3); + float y0 = (float)lua.CheckNumber(2); + float x0 = (float)lua.CheckNumber(1); + surface.DrawLine((int)x0, (int)y0, (int)x1, (int)y1); + return 0; + } [LuaFunction] static int SetTextColor(ILuaInterface lua) { @@ -80,7 +95,12 @@ static int SetTextColor(ILuaInterface lua) { return 0; } - // todo: GetTextColor + [LuaFunction] + static int GetTextColor(ILuaInterface lua) { + surface.DrawGetTextColor(out Color color); + lua.PushColor(color); + return 1; + } [LuaFunction] static void SetTextPos([LuaGet] int x, [LuaGet] int y) => surface.DrawSetTextPos(x, y); @@ -267,7 +287,15 @@ static void SetMaterial(IMaterial material) { return (wide, tall); } - // todo: GetHUDTexture + [LuaFunction] + static int GetHUDTexture(ILuaInterface lua) { + HudTexture? icon = gHUD.GetIcon(lua.CheckString(1)); + if (icon == null) + return 0; + lua.PushNumber((int)icon.TextureID); + return 1; + } + [LuaFunction] static int DrawTexturedRect(ILuaInterface lua) { int x = (int)lua.CheckNumber(1); @@ -279,7 +307,32 @@ static int DrawTexturedRect(ILuaInterface lua) { return 0; } - // todo: DrawTexturedRectRotated + [InlineArray(4)] struct InlineArrayRotatedVerts { SurfaceVertex first; } + static InlineArrayRotatedVerts RotatedVerts; + + [LuaFunction] + static int DrawTexturedRectRotated(ILuaInterface lua) { + int x = (int)lua.CheckNumber(1); + int y = (int)lua.CheckNumber(2); + float w = (int)lua.CheckNumber(3); + float h = (int)lua.CheckNumber(4); + float rotation = (float)lua.CheckNumber(5); + + (float sin, float cos) = MathF.SinCos(-rotation * 0.017453292f); + + RotatedVerts[0].Position = new(cos * w * -0.5f + x + -sin * h * -0.5f, sin * w * -0.5f + y + cos * h * -0.5f); + RotatedVerts[0].TexCoord = new(0, 0); + RotatedVerts[1].Position = new(cos * w + RotatedVerts[0].Position.X, sin * w + RotatedVerts[0].Position.Y); + RotatedVerts[1].TexCoord = new(1, 0); + RotatedVerts[2].Position = new(-sin * h + RotatedVerts[1].Position.X, RotatedVerts[1].Position.Y + cos * h); + RotatedVerts[2].TexCoord = new(1, 1); + RotatedVerts[3].Position = new(-sin * h + RotatedVerts[0].Position.X, RotatedVerts[0].Position.Y + cos * h); + RotatedVerts[3].TexCoord = new(0, 1); + + surface.DrawTexturedPolygon(RotatedVerts, true); + return 0; + } + [LuaFunction] static int PlaySound(ILuaInterface lua) { ReadOnlySpan sound = lua.CheckString(1); @@ -325,8 +378,26 @@ static int DrawPoly(ILuaInterface lua) { vertices.UnReference(); return 0; } - // todo: DisableClipping - // todo: DrawCircle + [LuaFunction] + static int DisableClipping(ILuaInterface lua) { + surface.GetClippingRect(out _, out _, out _, out _, out bool clippingDisabled); + surface.DisableClipping(lua.GetBool(1)); + lua.PushBool(clippingDisabled); + return 1; + } + + [LuaFunction] + static int DrawCircle(ILuaInterface lua) { + double x = lua.CheckNumber(1); + double y = lua.CheckNumber(2); + double radius = lua.CheckNumber(3); + if (lua.GetType(4) != LuaType.Nil) + surface.DrawSetColor(GetColor(lua, 4)); + + float segments = Math.Clamp(MathF.Abs((float)radius), 8, 64); + surface.DrawOutlinedCircle((int)x, (int)y, (int)radius, (int)segments); + return 0; + } [LuaFunction] static int DrawTexturedRectUV(ILuaInterface lua) { int x = (int)lua.GetNumber(1); @@ -344,6 +415,31 @@ static int DrawTexturedRectUV(ILuaInterface lua) { [LuaFunction] static float GetAlphaMultiplier() => surface.DrawGetAlphaMultiplier(); - // todo: GetPanelPaintState - // todo: GetScissorRect + [LuaFunction] + static int GetPanelPaintState(ILuaInterface lua) { + LuaTable table = new(null, 0); + surface.DrawGetTranslate(out int translateX, out int translateY); + table.SetMember("translate_x", translateX); + table.SetMember("translate_y", translateY); + surface.GetClippingRect(out int left, out int top, out int right, out int bottom, out bool clippingDisabled); + table.SetMember("scissor_left", left); + table.SetMember("scissor_top", top); + table.SetMember("scissor_right", right); + table.SetMember("scissor_bottom", bottom); + table.SetMember("scissor_enabled", !clippingDisabled); + table.Push(); + table.UnReference(); + return 1; + } + + [LuaFunction] + static int GetScissorRect(ILuaInterface lua) { + surface.GetClippingRect(out int left, out int top, out int right, out int bottom, out bool clippingDisabled); + lua.PushBool(!clippingDisabled); + lua.PushNumber(left); + lua.PushNumber(top); + lua.PushNumber(right); + lua.PushNumber(bottom); + return 5; + } } diff --git a/Source.Common/GUI/ISurface.cs b/Source.Common/GUI/ISurface.cs index 3812c81f4..4f8504e9c 100644 --- a/Source.Common/GUI/ISurface.cs +++ b/Source.Common/GUI/ISurface.cs @@ -231,6 +231,11 @@ public interface ISurface void PushFullscreenViewport(); ReadOnlySpan GetFontName(IFont font); ReadOnlySpan GetFontFamilyName(IFont font); +#if GMOD_DLL + void DrawGetColor(out Color color); + void DrawGetTextColor(out Color color); + void DrawGetTranslate(out int x, out int y); +#endif } public interface IMatSystemSurface : ISurface diff --git a/Source.MaterialSystem/Surface/MatSystemSurface.cs b/Source.MaterialSystem/Surface/MatSystemSurface.cs index 9a2c6d35b..47e08dfb9 100644 --- a/Source.MaterialSystem/Surface/MatSystemSurface.cs +++ b/Source.MaterialSystem/Surface/MatSystemSurface.cs @@ -2108,6 +2108,16 @@ public void GetClippingRect(out int left, out int top, out int right, out int bo clippingDisabled = !scissorRect.Scissor; } +#if GMOD_DLL + public void DrawGetColor(out Color color) => color = DrawColor; + public void DrawGetTextColor(out Color color) => color = DrawTextColor; + + public void DrawGetTranslate(out int x, out int y) { + x = TranslateX; + y = TranslateY; + } +#endif + public void PushFullscreenViewport() { using MatRenderContextPtr renderContext = new(materials); From a1973e3a3659971d9e64a26a2894414891b6c19e Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Sat, 10 Oct 2026 15:35:29 +0100 Subject: [PATCH 16/23] Finish LuaNet --- Game.Shared/GarrysMod/LuaNet.cs | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/Game.Shared/GarrysMod/LuaNet.cs b/Game.Shared/GarrysMod/LuaNet.cs index e822795eb..2f84d2b43 100644 --- a/Game.Shared/GarrysMod/LuaNet.cs +++ b/Game.Shared/GarrysMod/LuaNet.cs @@ -155,7 +155,17 @@ static int WriteAngle(ILuaInterface lua) { return 0; } - // todo: [LuaFunction] static int WriteMatrix(ILuaInterface lua) + [LuaFunction] + static int WriteMatrix(ILuaInterface lua) { + if (!g_Started) + return 0; + + ref Matrix4x4 matrix = ref LuaVMatrix.Get_VMatrix(1); + for (int i = 0; i < 4; i++) + for (int j = 0; j < 4; j++) + g_Write.WriteFloat(matrix[i, j]); + return 0; + } [LuaFunction] static int WriteInt(ILuaInterface lua) { @@ -554,7 +564,19 @@ static int ReadAngle(ILuaInterface lua) { return 1; } - // todo: [LuaFunction] static int ReadMatrix(ILuaInterface lua) + [LuaFunction] + static int ReadMatrix(ILuaInterface lua) { + if (g_NetIncoming == null) + return 0; + + ValidateDataSize(lua, 512); + Matrix4x4 matrix = default; + for (int i = 0; i < 4; i++) + for (int j = 0; j < 4; j++) + matrix[i, j] = g_NetIncoming.ReadFloat(); + LuaVMatrix.Push_VMatrix(matrix); + return 1; + } static readonly byte[] strString = new byte[0x10000]; From d5864fb07314712bebfbd0e9c164ea15f7c3acd6 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Sat, 10 Oct 2026 15:42:18 +0100 Subject: [PATCH 17/23] Finish LuaVGUI --- Game.Client/GarrysMod/LuaVGUI.cs | 54 +++++++++++++++++++++++++++++--- 1 file changed, 50 insertions(+), 4 deletions(-) diff --git a/Game.Client/GarrysMod/LuaVGUI.cs b/Game.Client/GarrysMod/LuaVGUI.cs index c2aaf3255..f263e4b63 100644 --- a/Game.Client/GarrysMod/LuaVGUI.cs +++ b/Game.Client/GarrysMod/LuaVGUI.cs @@ -12,10 +12,56 @@ public static partial class LuaVGUI [LuaLibrary] static readonly LuaLibrary LL_Factory_vgui = new("vgui"); - // todo: GetAll - // todo: CursorVisible - // todo: IsHoveringWorld - // todo: GetWorldPanel + static void AddChildren(List panels, IPanel panel) { + panels.Add(panel); + int count = panel.GetChildCount(); + for (int i = 0; i < count; i++) + AddChildren(panels, panel.GetChild(i)); + } + + [LuaFunction] + static int GetAll(ILuaInterface lua) { + IPanel root = surface.GetEmbeddedPanel(); + List panels = [root]; + int count = root.GetChildCount(); + for (int i = 0; i < count; i++) + AddChildren(panels, root.GetChild(i)); + + lua.PreCreateTable(panels.Count, 0); + int n = 0; + foreach (IPanel vpanel in panels) { + if (vpanel is not Panel panel || !panel.LuaPanel) + continue; + lua.PushNumber(++n); + Push_Panel(panel); + lua.SetTable(-3); + } + return 1; + } + + [LuaFunction] + static int CursorVisible(ILuaInterface lua) { + lua.PushBool(surface.IsCursorVisible()); + return 1; + } + + [LuaFunction] + static int IsHoveringWorld(ILuaInterface lua) { + if (!surface.IsCursorVisible()) { + lua.PushBool(false); + return 1; + } + Panel? world = GModBase.GetGModBasePanel(true); + lua.PushBool(vguiInput.GetMouseOver() == world); + return 1; + } + + [LuaFunction] + static int GetWorldPanel(ILuaInterface lua) { + Push_Panel(GModBase.GetGModBasePanel(true)); + return 1; + } + [LuaFunction] static int FocusedHasParent(ILuaInterface lua) { Panel? panel = Get_Panel(1); From b1392043dcbd3c18e39c58eee59e0189daf266d3 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Sat, 10 Oct 2026 15:55:55 +0100 Subject: [PATCH 18/23] Some more render funcs --- Game.Client/GarrysMod/LuaRender.cs | 427 ++++++++++++++++++++++++++--- 1 file changed, 383 insertions(+), 44 deletions(-) diff --git a/Game.Client/GarrysMod/LuaRender.cs b/Game.Client/GarrysMod/LuaRender.cs index c171e9ba9..16984cf27 100644 --- a/Game.Client/GarrysMod/LuaRender.cs +++ b/Game.Client/GarrysMod/LuaRender.cs @@ -128,7 +128,12 @@ static int GetRenderTargetEx(ILuaInterface lua) { // todo: SetMaterial // todo: SetLightmapTexture // todo: GetLightColor - // todo: GetAmbientLightColor + [LuaFunction] + static int GetAmbientLightColor(ILuaInterface lua) { + engine.GetAmbientLightColor(out Vector3 color); + LuaVector.Push_Vector(color); + return 1; + } // todo: ComputeDynamicLighting // todo: ComputeLighting // todo: GetSurfaceColor @@ -165,9 +170,42 @@ static int GetRenderTargetEx(ILuaInterface lua) { // todo: GetRefractTexture // todo: UpdatePowerOfTwoTexture // todo: GetPowerOfTwoTexture - // todo: GetRenderTarget - // todo: SetRenderTarget - // todo: SetRenderTargetEx + [LuaFunction("GetRenderTarget")] + static int GetCurrentRenderTarget(ILuaInterface lua) { + using MatRenderContextPtr renderContext = new(materials); + ITexture? texture = renderContext.GetRenderTarget(); + if (texture == null) + return 0; + LuaTexture.Push(texture); + return 1; + } + + [LuaFunction] + static int SetRenderTarget(ILuaInterface lua) { + ITexture? texture = null; + if (lua.IsType(1, LuaType.Texture)) + texture = (ITexture?)LuaTexture.LC_ITexture.Get(1); + using MatRenderContextPtr renderContext = new(materials); + renderContext.Flush(false); + renderContext.SetRenderTarget(texture); + return 0; + } + + [LuaFunction] + static int SetRenderTargetEx(ILuaInterface lua) { + int id = (int)(uint)lua.CheckNumber(1); + if (id < 0) + id = 0; + else if (id > 4) + id = 4; + ITexture? texture = null; + if (lua.IsType(2, LuaType.Texture)) + texture = (ITexture?)LuaTexture.LC_ITexture.Get(2); + using MatRenderContextPtr renderContext = new(materials); + renderContext.Flush(false); + renderContext.SetRenderTargetEx(id, texture); + return 0; + } static int RenderTargetStack; [LuaFunction] @@ -256,7 +294,13 @@ static int GetSuperFPTex2(ILuaInterface lua) { // todo: ResetModelLighting // todo: SetModelLighting // todo: SetAmbientLight - // todo: SetLightingOrigin + [LuaFunction] + static int SetLightingOrigin(ILuaInterface lua) { + ref Vector3 origin = ref LuaVector.Get_Vector(1); + using MatRenderContextPtr renderContext = new(materials); + renderContext.SetLightingOrigin(origin); + return 0; + } [LuaFunction] static void SetColorModulation([LuaGet] float r, [LuaGet] float g, [LuaGet] float b) { ReadOnlySpan color = [r, g, b]; @@ -472,53 +516,320 @@ static int RenderHUD(ILuaInterface lua) { return 0; } - // todo: SetViewPort + [LuaFunction] + static int SetViewPort(ILuaInterface lua) { + double x = lua.CheckNumber(1); + double y = lua.CheckNumber(2); + double w = lua.CheckNumber(3); + double h = lua.CheckNumber(4); + using MatRenderContextPtr renderContext = new(materials); + renderContext.Viewport((int)x, (int)y, (int)w, (int)h); + return 0; + } // todo: Clear // todo: ClearDepth // todo: RenderView // todo: GetViewSetup // todo: RenderHUD // todo: CopyRenderTargetToTexture - // todo: PushCustomClipPlane - // todo: PopCustomClipPlane - // todo: EnableClipping - // todo: SetStencilEnable - // todo: SetStencilFailOperation - // todo: SetStencilZFailOperation - // todo: SetStencilPassOperation - // todo: SetStencilCompareFunction - // todo: SetStencilReferenceValue - // todo: SetStencilTestMask - // todo: SetStencilWriteMask - // todo: ClearStencilBufferRectangle - // todo: ClearStencil - // todo: ClearBuffersObeyStencil - // todo: PerformFullScreenStencilOperation - // todo: FogMode - // todo: FogStart - // todo: FogEnd - // todo: SetFogZ - // todo: GetFogMode - // todo: FogColor - // todo: GetFogColor - // todo: GetFogDistances + static int CustomClipPlaneCount; + + [LuaFunction] + static int PushCustomClipPlane(ILuaInterface lua) { + ref Vector3 normal = ref LuaVector.Get_Vector(1); + double distance = lua.CheckNumber(2); + Span plane = [normal.X, normal.Y, normal.Z, (float)distance]; + using MatRenderContextPtr renderContext = new(materials); + renderContext.PushCustomClipPlane(plane); + CustomClipPlaneCount++; + return 0; + } + + [LuaFunction] + static int PopCustomClipPlane(ILuaInterface lua) { + if (CustomClipPlaneCount < 1) { + lua.ErrorFromLua("render.PopCustomClipPlane underflow\n"); + return 0; + } + CustomClipPlaneCount--; + using MatRenderContextPtr renderContext = new(materials); + renderContext.PopCustomClipPlane(); + return 0; + } + + [LuaFunction] + static int EnableClipping(ILuaInterface lua) { + bool enable = lua.GetBool(1); + using MatRenderContextPtr renderContext = new(materials); + lua.PushBool(renderContext.EnableClipping(enable)); + return 1; + } + [LuaFunction] + static int SetStencilEnable(ILuaInterface lua) { + bool enable = lua.GetBool(1); + using MatRenderContextPtr renderContext = new(materials); + renderContext.SetStencilEnable(enable); + return 0; + } + + [LuaFunction] + static int SetStencilFailOperation(ILuaInterface lua) { + double op = lua.CheckNumber(1); + using MatRenderContextPtr renderContext = new(materials); + renderContext.SetStencilFailOperation((StencilOperation)(int)op); + return 0; + } + + [LuaFunction] + static int SetStencilZFailOperation(ILuaInterface lua) { + double op = lua.CheckNumber(1); + using MatRenderContextPtr renderContext = new(materials); + renderContext.SetStencilZFailOperation((StencilOperation)(int)op); + return 0; + } + + [LuaFunction] + static int SetStencilPassOperation(ILuaInterface lua) { + double op = lua.CheckNumber(1); + using MatRenderContextPtr renderContext = new(materials); + renderContext.SetStencilPassOperation((StencilOperation)(int)op); + return 0; + } + + [LuaFunction] + static int SetStencilCompareFunction(ILuaInterface lua) { + double cmp = lua.CheckNumber(1); + using MatRenderContextPtr renderContext = new(materials); + renderContext.SetStencilCompareFunction((StencilComparisonFunction)(int)cmp); + return 0; + } + + [LuaFunction] + static int SetStencilReferenceValue(ILuaInterface lua) { + double reference = lua.CheckNumber(1); + using MatRenderContextPtr renderContext = new(materials); + renderContext.SetStencilReferenceValue((int)reference); + return 0; + } + + [LuaFunction] + static int SetStencilTestMask(ILuaInterface lua) { + double mask = lua.CheckNumber(1); + using MatRenderContextPtr renderContext = new(materials); + renderContext.SetStencilTestMask((uint)(int)mask); + return 0; + } + + [LuaFunction] + static int SetStencilWriteMask(ILuaInterface lua) { + double mask = lua.CheckNumber(1); + using MatRenderContextPtr renderContext = new(materials); + renderContext.SetStencilWriteMask((uint)(int)mask); + return 0; + } + + [LuaFunction] + static int ClearStencilBufferRectangle(ILuaInterface lua) { + double xmin = lua.CheckNumber(1); + double ymin = lua.CheckNumber(2); + double xmax = lua.CheckNumber(3); + double ymax = lua.CheckNumber(4); + double value = lua.CheckNumber(5); + using MatRenderContextPtr renderContext = new(materials); + renderContext.ClearStencilBufferRectangle((int)xmin, (int)ymin, (int)xmax, (int)ymax, (int)value); + return 0; + } + + [LuaFunction] + static int ClearStencil(ILuaInterface lua) { + using MatRenderContextPtr renderContext = new(materials); + renderContext.ClearBuffers(false, false, true); + return 0; + } + [LuaFunction] + static int ClearBuffersObeyStencil(ILuaInterface lua) { + double r = lua.CheckNumber(1); + double g = lua.CheckNumber(2); + double b = lua.CheckNumber(3); + double a = lua.CheckNumber(4); + bool depth = lua.GetBool(5); + using MatRenderContextPtr renderContext = new(materials); + renderContext.ClearColor3ub((byte)(int)r, (byte)(int)g, (byte)(int)b); + renderContext.ClearColor4ub((byte)(int)r, (byte)(int)g, (byte)(int)b, (byte)(int)a); + renderContext.ClearBuffersObeyStencil(true, depth); + return 0; + } + + [LuaFunction] + static int PerformFullScreenStencilOperation(ILuaInterface lua) { + using MatRenderContextPtr renderContext = new(materials); + renderContext.PerformFullScreenStencilOperation(); + return 0; + } + + [LuaFunction] + static int FogMode(ILuaInterface lua) { + double mode = lua.CheckNumber(1); + using MatRenderContextPtr renderContext = new(materials); + renderContext.FogMode((MaterialFogMode)(int)mode); + return 0; + } + + [LuaFunction] + static int FogStart(ILuaInterface lua) { + double start = lua.CheckNumber(1); + using MatRenderContextPtr renderContext = new(materials); + renderContext.FogStart((float)start); + return 0; + } + + [LuaFunction] + static int FogEnd(ILuaInterface lua) { + double end = lua.CheckNumber(1); + using MatRenderContextPtr renderContext = new(materials); + renderContext.FogEnd((float)end); + return 0; + } + + [LuaFunction] + static int SetFogZ(ILuaInterface lua) { + double fogZ = lua.CheckNumber(1); + using MatRenderContextPtr renderContext = new(materials); + renderContext.SetFogZ((float)fogZ); + return 0; + } + + [LuaFunction] + static int GetFogMode(ILuaInterface lua) { + using MatRenderContextPtr renderContext = new(materials); + lua.PushNumber((int)renderContext.GetFogMode()); + return 1; + } + + [LuaFunction] + static int FogColor(ILuaInterface lua) { + double r = lua.CheckNumber(1); + double g = lua.CheckNumber(2); + double b = lua.CheckNumber(3); + using MatRenderContextPtr renderContext = new(materials); + renderContext.FogColor3ub((byte)(int)r, (byte)(int)g, (byte)(int)b); + return 0; + } + + [LuaFunction] + static int GetFogColor(ILuaInterface lua) { + using MatRenderContextPtr renderContext = new(materials); + renderContext.GetFogColor(out Color rgb); + lua.PushNumber(rgb.R); + lua.PushNumber(rgb.G); + lua.PushNumber(rgb.B); + return 3; + } + + [LuaFunction] + static int GetFogDistances(ILuaInterface lua) { + using MatRenderContextPtr renderContext = new(materials); + renderContext.GetFogDistances(out float start, out float end, out float fogZ); + lua.PushNumber(start); + lua.PushNumber(end); + lua.PushNumber(fogZ); + return 3; + } + // todo: GetFogMaxDensity // todo: FogMaxDensity - // todo: CullMode - // todo: SetScissorRect - // todo: ResetToneMappingScale - // todo: SetGoalToneMappingScale - // todo: TurnOnToneMapping - // todo: SetToneMappingScaleLinear - // todo: GetToneMappingScaleLinear + + [LuaFunction] + static int CullMode(ILuaInterface lua) { + float mode = (int)lua.CheckNumber(1); + if (mode <= 0) + mode = 0; + if (2 <= mode) + mode = 2; + using MatRenderContextPtr renderContext = new(materials); + renderContext.CullMode((MaterialCullMode)(int)mode); + return 0; + } + + [LuaFunction] + static int ResetToneMappingScale(ILuaInterface lua) { + double scale = lua.CheckNumber(1); + using MatRenderContextPtr renderContext = new(materials); + renderContext.ResetToneMappingScale((float)scale); + return 0; + } + + [LuaFunction] + static int SetGoalToneMappingScale(ILuaInterface lua) { + double scale = lua.CheckNumber(1); + using MatRenderContextPtr renderContext = new(materials); + renderContext.SetGoalToneMappingScale((float)scale); + return 0; + } + + [LuaFunction] + static int TurnOnToneMapping(ILuaInterface lua) { + using MatRenderContextPtr renderContext = new(materials); + renderContext.TurnOnToneMapping(); + return 0; + } + + [LuaFunction] + static int SetToneMappingScaleLinear(ILuaInterface lua) { + ref Vector3 scale = ref LuaVector.Get_Vector(1); + using MatRenderContextPtr renderContext = new(materials); + renderContext.SetToneMappingScaleLinear(scale); + return 0; + } + + [LuaFunction] + static int GetToneMappingScaleLinear(ILuaInterface lua) { + using MatRenderContextPtr renderContext = new(materials); + LuaVector.Push_Vector(renderContext.GetToneMappingScaleLinear()); + return 1; + } + // todo: CapturePixels // todo: ReadPixel - // todo: OverrideDepthEnable - // todo: OverrideAlphaWriteEnable - // todo: OverrideColorWriteEnable + + [LuaFunction] + static int OverrideDepthEnable(ILuaInterface lua) { + bool enable = lua.GetBool(1); + bool depthEnable = lua.GetBool(2); + using MatRenderContextPtr renderContext = new(materials); + renderContext.OverrideDepthEnable(enable, depthEnable); + return 0; + } + + [LuaFunction] + static int OverrideAlphaWriteEnable(ILuaInterface lua) { + bool enable = lua.GetBool(1); + bool alphaWriteEnable = lua.GetBool(2); + using MatRenderContextPtr renderContext = new(materials); + renderContext.OverrideAlphaWriteEnable(enable, alphaWriteEnable); + return 0; + } + + [LuaFunction] + static int OverrideColorWriteEnable(ILuaInterface lua) { + bool enable = lua.GetBool(1); + bool colorWriteEnable = lua.GetBool(2); + using MatRenderContextPtr renderContext = new(materials); + renderContext.OverrideColorWriteEnable(enable, colorWriteEnable); + return 0; + } + // todo: OverrideBlend // todo: OverrideBlendFunc - // todo: DepthRange + + [LuaFunction] + static int DepthRange(ILuaInterface lua) { + double zNear = lua.CheckNumber(1); + double zFar = lua.CheckNumber(2); + using MatRenderContextPtr renderContext = new(materials); + renderContext.DepthRange((float)zNear, (float)zFar); + return 0; + } // todo: MaterialOverride // todo: MaterialOverrideByIndex // todo: DrawSphere @@ -535,7 +846,17 @@ static int RenderHUD(ILuaInterface lua) { // todo: WorldMaterialOverride // todo: BrushMaterialOverride // todo: ModelMaterialOverride - // todo: SetLightingMode + [LuaFunction] + static int SetLightingMode(ILuaInterface lua) { + int mode = (int)lua.CheckNumber(1); + using MatRenderContextPtr renderContext = new(materials); + if (mode < 0) + mode = 0; + else if (mode > 2) + mode = 2; + renderContext.SetIntRenderingParameter(0, mode); + return 0; + } // todo: Capture static readonly List FilterMinStack = [0]; static readonly List FilterMagStack = [0]; @@ -610,8 +931,26 @@ static int PopFilterMin(ILuaInterface lua) { return 0; } // todo: RedownloadAllLightmaps - // todo: SetWriteDepthToDestAlpha + [LuaFunction] + static int SetWriteDepthToDestAlpha(ILuaInterface lua) { + bool enable = lua.GetBool(1); + using MatRenderContextPtr renderContext = new(materials); + renderContext.SetIntRenderingParameter(10, enable ? 1 : 0); + return 0; + } // todo: RenderFlashlights - // todo: ComputePixelDiameterOfSphere - // todo: IsTakingScreenshot + [LuaFunction] + static int ComputePixelDiameterOfSphere(ILuaInterface lua) { + ref Vector3 origin = ref LuaVector.Get_Vector(1); + double radius = lua.CheckNumber(2); + using MatRenderContextPtr renderContext = new(materials); + lua.PushNumber(renderContext.ComputePixelDiameterOfSphere(origin, (float)radius)); + return 1; + } + + [LuaFunction] + static int IsTakingScreenshot(ILuaInterface lua) { + lua.PushBool(engine.IsTakingScreenshot()); + return 1; + } } From 193919990a0484ad3e90c6ce5abcae7a0d743911 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Sat, 10 Oct 2026 19:08:33 +0100 Subject: [PATCH 19/23] Remove duplicate lerp --- Source.Common/Mathematics/MathLib.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Source.Common/Mathematics/MathLib.cs b/Source.Common/Mathematics/MathLib.cs index 9335fe8d8..ea4d2cd0a 100644 --- a/Source.Common/Mathematics/MathLib.cs +++ b/Source.Common/Mathematics/MathLib.cs @@ -3701,8 +3701,6 @@ public static void BSpline(in Vector3 p1, in Vector3 p2, in Vector3 p3, in Vecto output += c; } - public static float FLerp(float f1, float f2, float i1, float i2, float x) => f1 + (f2 - f1) * (x - i1) / (i2 - i1); - public static bool SolveInverseQuadratic(float x1, float y1, float x2, float y2, float x3, float y3, out float a, out float b, out float c) { a = b = c = 0; float det = (x1 - x2) * (x1 - x3) * (x2 - x3); @@ -3732,7 +3730,7 @@ public static bool SolveInverseQuadraticMonotonic(float x1, float y1, float x2, for (int factor = 0; factor <= 100.0; factor += 5) { float blendToLinearFactor = factor / 100.0f; - float tempy2 = (1 - blendToLinearFactor) * y2 + blendToLinearFactor * FLerp(y1, y3, x1, x3, x2); + float tempy2 = (1 - blendToLinearFactor) * y2 + blendToLinearFactor * Lerp(y1, y3, x1, x3, x2); if (!SolveInverseQuadratic(x1, y1, x2, tempy2, x3, y3, out a, out b, out c)) return false; float derivative = 2.0f * a + b; From 2fb58751fd0ec9c634d8dd132e068390220657ac Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Sat, 10 Oct 2026 18:47:08 -0700 Subject: [PATCH 20/23] SolveInverseQuadratic a/b/c as refs --- Source.Common/Mathematics/MathLib.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Source.Common/Mathematics/MathLib.cs b/Source.Common/Mathematics/MathLib.cs index ea4d2cd0a..e04c991bd 100644 --- a/Source.Common/Mathematics/MathLib.cs +++ b/Source.Common/Mathematics/MathLib.cs @@ -3701,8 +3701,7 @@ public static void BSpline(in Vector3 p1, in Vector3 p2, in Vector3 p3, in Vecto output += c; } - public static bool SolveInverseQuadratic(float x1, float y1, float x2, float y2, float x3, float y3, out float a, out float b, out float c) { - a = b = c = 0; + public static bool SolveInverseQuadratic(float x1, float y1, float x2, float y2, float x3, float y3, ref float a, ref float b, ref float c) { float det = (x1 - x2) * (x1 - x3) * (x2 - x3); if (det == 0.0f) @@ -3731,7 +3730,7 @@ public static bool SolveInverseQuadraticMonotonic(float x1, float y1, float x2, for (int factor = 0; factor <= 100.0; factor += 5) { float blendToLinearFactor = factor / 100.0f; float tempy2 = (1 - blendToLinearFactor) * y2 + blendToLinearFactor * Lerp(y1, y3, x1, x3, x2); - if (!SolveInverseQuadratic(x1, y1, x2, tempy2, x3, y3, out a, out b, out c)) + if (!SolveInverseQuadratic(x1, y1, x2, tempy2, x3, y3, ref a, ref b, ref c)) return false; float derivative = 2.0f * a + b; if ((y1 < y2) && (y2 < y3)) { From 5875f8bf2e4c45f6756f7716a62393bdc556c0f7 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Sat, 10 Oct 2026 18:47:08 -0700 Subject: [PATCH 21/23] Fix cam.End2D underflow error name --- Game.Client/GarrysMod/LuaCam.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Game.Client/GarrysMod/LuaCam.cs b/Game.Client/GarrysMod/LuaCam.cs index ee1879f07..bee355cf1 100644 --- a/Game.Client/GarrysMod/LuaCam.cs +++ b/Game.Client/GarrysMod/LuaCam.cs @@ -132,7 +132,7 @@ static int End3D(ILuaInterface lua) { [LuaFunction] static int End2D(ILuaInterface lua) { if (Start2DCount < 1) { - lua.ErrorFromLua("cam.End3D underflow\n"); + lua.ErrorFromLua("cam.End2D underflow\n"); return 0; } From b299a4a1de047c04641a8ae58adb1d130eadf74d Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Sat, 10 Oct 2026 18:47:08 -0700 Subject: [PATCH 22/23] Fix bitmap leak in SavePNG when GetBits fails --- Source.Engine/GarrysMod/Resources.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Source.Engine/GarrysMod/Resources.cs b/Source.Engine/GarrysMod/Resources.cs index 29c3bab2a..fb5cabd64 100644 --- a/Source.Engine/GarrysMod/Resources.cs +++ b/Source.Engine/GarrysMod/Resources.cs @@ -240,6 +240,7 @@ public void SavePNG(int width, int height, Span pixels, ReadOnlySpan IntPtr bits = FreeImage.GetBits(bitmap); if (bits == IntPtr.Zero) { Warning("[CResources::SavePNG] Freeimage couldn't GetBits!\n"); + FreeImage.Unload(bitmap); return; } From 06190c7413a9f4f9e6fc017cc0009709e3a6a542 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Sat, 10 Oct 2026 18:47:10 -0700 Subject: [PATCH 23/23] Fix cam.Start crash on empty type string --- Game.Client/GarrysMod/LuaCam.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Game.Client/GarrysMod/LuaCam.cs b/Game.Client/GarrysMod/LuaCam.cs index bee355cf1..0ef41617c 100644 --- a/Game.Client/GarrysMod/LuaCam.cs +++ b/Game.Client/GarrysMod/LuaCam.cs @@ -40,7 +40,7 @@ static int Start(ILuaInterface lua) { ResetFrameStateChecked(); - if (data.GetMemberStr("type", "3D")![0] == '2') { + if (data.GetMemberStr("type", "3D")!.StartsWith('2')) { using MatRenderContextPtr renderContext = new(materials); ClientModeShared.SetupVGuiMatrices(true, renderContext); ((ClientModeShared)clientMode).SetupGModSurface(true);