diff --git a/Game.Client/CDLL_Util.cs b/Game.Client/CDLL_Util.cs index c5be0aa54..0af65e648 100644 --- a/Game.Client/CDLL_Util.cs +++ b/Game.Client/CDLL_Util.cs @@ -51,6 +51,11 @@ public static void PrecacheOther(ReadOnlySpan classname) { entity.Release(); } + public static void Remove(C_BaseEntity? entity) { + if (entity != null && !entity.IsMarkedForDeletion()) + ClientThinkList().AddToDeleteList(entity.GetClientHandle()); + } + } public static partial class Util_Globals { diff --git a/Game.Client/C_BaseAnimating.cs b/Game.Client/C_BaseAnimating.cs index 34ad032f0..aa7788d0e 100644 --- a/Game.Client/C_BaseAnimating.cs +++ b/Game.Client/C_BaseAnimating.cs @@ -75,6 +75,8 @@ public static void PushAllowBoneAccess(bool allowForNormalModels, bool allowForV } } + public int GetNumBodyGroups() => Animation.GetNumBodyGroups(GetModelPtr()); + public void SetBodygroup(int group, int value) { Animation.SetBodygroup(GetModelPtr(), ref Body, group, value); } @@ -1158,6 +1160,11 @@ public void AddToClientSideAnimationList() { UpdateRelevantInterpolatedVars(); } + public override void Term() { + RemoveFromClientSideAnimationList(true); + base.Term(); + } + public void RemoveFromClientSideAnimationList(bool beingDestroyed = false) { if (INVALID_CLIENTSIDEANIMATION_LIST_HANDLE == ClientSideAnimationListHandle) return; diff --git a/Game.Client/C_BaseCombatWeapon.cs b/Game.Client/C_BaseCombatWeapon.cs index 57186379e..8b8399914 100644 --- a/Game.Client/C_BaseCombatWeapon.cs +++ b/Game.Client/C_BaseCombatWeapon.cs @@ -12,6 +12,9 @@ public partial class C_BaseCombatWeapon : C_BaseAnimating { public override bool IsBaseCombatWeapon() => true; public override GarrysMod.LuaClass Lua_GetLuaClass() => GarrysMod.LuaEntity.LC_Weapon; + public bool Dropped; + public virtual bool WasDropped() => Dropped; + public virtual void SetDropped() => Dropped = true; public virtual void DrawHUD() { } public virtual void DrawHUDBackground() { } public override bool IsWeapon() => true; diff --git a/Game.Client/C_BaseEntity.cs b/Game.Client/C_BaseEntity.cs index 9ed81573d..c69bad800 100644 --- a/Game.Client/C_BaseEntity.cs +++ b/Game.Client/C_BaseEntity.cs @@ -34,6 +34,13 @@ public static class BaseEntityConsts public const int MULTIPLAYER_BACKUP = 90; } +public enum CollideType +{ + ShouldNotCollide = 0, + ShouldCollide, + ShouldRespond +} + public enum InterpolateResult { Stop = 0, @@ -183,6 +190,10 @@ public partial class C_BaseEntity : IClientEntity public virtual bool IsBaseCombatWeapon() => false; public virtual bool IsCombatItem() => false; + public void SetClassname(ReadOnlySpan classname) { + // todo + } + static readonly char[] GetClassname__outstr = new char[256]; public ReadOnlySpan GetClassname() { GetClassname__outstr[0] = '\0'; @@ -554,7 +565,7 @@ protected static void RecvProxy_SimulationTime(ref readonly RecvProxyData data, RecvPropInt(FIELD.OF(nameof(CollisionGroup))), RecvPropFloat(FIELD.OF(nameof(Elasticity))), RecvPropFloat(FIELD.OF(nameof(ShadowCastDistance))), - RecvPropEHandle(FIELD.OF(nameof(OwnerEntity))), + RecvPropEHandle(FIELD.OF(nameof(OwnerEntity)), RecvProxy_OwnerEntity), RecvPropEHandle(FIELD.OF(nameof(EffectEntity))), RecvPropInt(FIELD.OF(nameof(NetworkMoveParent)), 0, RecvProxy_IntToMoveParent), RecvPropInt(FIELD.OF(nameof(ParentAttachment))), @@ -586,9 +597,9 @@ protected static void RecvProxy_SimulationTime(ref readonly RecvProxyData data, RecvPropBool(FIELD.OF(nameof(OnFire))), RecvPropFloat(FIELD.OF(nameof(CreationTime))), - RecvPropFloat(FIELD.OF_VECTORELEM(nameof(Velocity), 0)), - RecvPropFloat(FIELD.OF_VECTORELEM(nameof(Velocity), 1)), - RecvPropFloat(FIELD.OF_VECTORELEM(nameof(Velocity), 2)), + RecvPropFloat(FIELD.OF_VECTORELEM(nameof(Velocity), 0), 0, RecvProxy_LocalVelocityX), + RecvPropFloat(FIELD.OF_VECTORELEM(nameof(Velocity), 1), 0, RecvProxy_LocalVelocityY), + RecvPropFloat(FIELD.OF_VECTORELEM(nameof(Velocity), 2), 0, RecvProxy_LocalVelocityZ), // NW2 table RecvPropGModTable(FIELD.OF(nameof(GMOD_DataTable))), @@ -610,6 +621,50 @@ protected static void RecvProxy_SimulationTime(ref readonly RecvProxyData data, RecvPropInt(FIELD.OF(nameof(MapCreatedID))), ]); + private static void RecvProxy_OwnerEntity(ref readonly RecvProxyData data, object instance, IFieldAccessor field) { + RecvProxy_IntToEHandle(in data, instance, field); + ((C_BaseEntity)instance).OnOwnerChanged(); + } + + public virtual void OnOwnerChanged() { } + + private static void RecvProxy_LocalVelocityX(ref readonly RecvProxyData data, object instance, IFieldAccessor field) { + C_BaseEntity ent = (C_BaseEntity)instance; + float newVelX = data.Value.Float; + Vector3 velocity = ent.GetLocalVelocity(); + if (velocity.X != newVelX) { + velocity.X = newVelX; + ent.SetLocalVelocity(velocity); + } + } + + private static void RecvProxy_LocalVelocityY(ref readonly RecvProxyData data, object instance, IFieldAccessor field) { + C_BaseEntity ent = (C_BaseEntity)instance; + float newVelY = data.Value.Float; + Vector3 velocity = ent.GetLocalVelocity(); + if (velocity.Y != newVelY) { + velocity.Y = newVelY; + ent.SetLocalVelocity(velocity); + } + } + + private static void RecvProxy_LocalVelocityZ(ref readonly RecvProxyData data, object instance, IFieldAccessor field) { + C_BaseEntity ent = (C_BaseEntity)instance; + float newVelZ = data.Value.Float; + Vector3 velocity = ent.GetLocalVelocity(); + if (velocity.Z != newVelZ) { + velocity.Z = newVelZ; + ent.SetLocalVelocity(velocity); + } + } + + public void SetLocalVelocity(in Vector3 velocity) { + if (Velocity != velocity) { + InvalidatePhysicsRecursive(InvalidatePhysicsBits.VelocityChanged); + Velocity = velocity; + } + } + private static void RecvProxy_MoveCollide(ref readonly RecvProxyData data, object instance, IFieldAccessor field) { ((C_BaseEntity)instance).SetMoveCollide((MoveCollide)data.Value.Int); } @@ -876,7 +931,7 @@ public static bool FClassnameIs(C_BaseEntity? entity, ReadOnlySpan classna return 0 == strcmp(entity.GetClassname(), classname); } - public void SetParent(C_BaseEntity parentEntity, int parentAttachment = 0) { + public void SetParent(C_BaseEntity? parentEntity, int parentAttachment = 0) { EHANDLE newParentHandle = default; newParentHandle.Set(parentEntity); if (newParentHandle.Index == MoveParent.Index) @@ -1090,8 +1145,13 @@ public void SetModelPointer(Model? model) { } void SetModelIndex(int index) { ModelIndex = index; +#if GMOD_DLL + if (index != -1) + SetModelPointer(modelinfo.GetModel(ModelIndex)); +#else Model? model = modelinfo.GetModel(ModelIndex); SetModelPointer(model); +#endif } public void SetModelByIndex(int modelIndex) { SetModelIndex(modelIndex); @@ -1846,14 +1906,12 @@ public virtual RenderGroup GetRenderGroup() { if (RenderMode == (int)Source.RenderMode.None) return RenderGroup.OpaqueEntity; - // todo - // int tempComputeFrame = FXComputeFrame; - // FXComputeFrame = gpGlobals.FrameCount; + long tempComputeFrame = FXComputeFrame; + FXComputeFrame = gpGlobals.FrameCount; int fxBlend = GetFxBlend(); - // todo - // FXComputeFrame = tempComputeFrame; + FXComputeFrame = tempComputeFrame; if (fxBlend == 0) return RenderGroup.OpaqueEntity; @@ -2027,7 +2085,31 @@ private TimeUnit_t GetLastChangeTime(LatchFlags flags) { return gpGlobals.CurTime; } - private void CreateShadow() { + public static bool AllowPrecache; + public static bool IsPrecacheAllowed() => AllowPrecache; + public static void SetAllowPrecache(bool allow) => AllowPrecache = allow; + + public void SetBlocksLOS(bool blocksLOS) { + if (blocksLOS) + RemoveEFlags(EFL.DontBlockLOS); + else + AddEFlags(EFL.DontBlockLOS); + } + + public virtual CollideType GetCollideType() => CollideType.ShouldNotCollide; + + public void UpdatePartitionListEntry() { + PartitionListMask list = PartitionListMask.ClientNonStaticEdicts; + CollideType shouldCollide = GetCollideType(); + if (shouldCollide == CollideType.ShouldCollide) + list |= PartitionListMask.ClientSolidEdicts; + else if (shouldCollide == CollideType.ShouldRespond) + list |= PartitionListMask.ClientResponsiveEdicts; + + partition.RemoveAndInsert((int)(PartitionListMask.ClientSolidEdicts | PartitionListMask.ClientResponsiveEdicts | PartitionListMask.ClientNonStaticEdicts), (int)list, CollisionProp().GetPartitionHandle()); + } + + public void CreateShadow() { ShadowType shadowType = ShadowCastType(); if (shadowType == ShadowType.None) DestroyShadow(); @@ -2066,7 +2148,7 @@ public virtual void SpawnClientEntity() { } public virtual void Precache() { } public PredictionContext? PredictionContext; - bool Dormant; + public bool Dormant; bool Predictable; bool DormantPredictable; long IncomingPacketEntityBecameDormant; @@ -2379,8 +2461,10 @@ private void RemoveAllDecals() { } + public bool DestroyedOnRecreateEntities; public void SetDestroyedOnRecreateEntities() { - + // ParticleProp().StopEmission(null, false); + DestroyedOnRecreateEntities = true; } public virtual ICollideable GetCollideable() => Collision; @@ -2407,8 +2491,125 @@ public void OnDataUnchangedInPVS() { return null; } + long FXComputeFrame = -1; + + public virtual byte GetClientSideFade() => 255; + public virtual void ComputeFxBlend() { - // todo + if (FXComputeFrame == gpGlobals.FrameCount) + return; + + int blend = 0; + float offset = EntIndex() * 363.0f; + + switch ((RenderFx)RenderFX) { + case RenderFx.PulseSlowWide: + blend = (int)(ColorRender.A + 64 * MathF.Sin((float)gpGlobals.CurTime * 2 + offset)); + break; + case RenderFx.PulseFastWide: + blend = (int)(ColorRender.A + 64 * MathF.Sin((float)gpGlobals.CurTime * 8 + offset)); + break; + case RenderFx.PulseFastWider: + blend = (int)(255 * MathF.Abs(MathF.Sin((float)gpGlobals.CurTime * 12 + offset))); + break; + case RenderFx.PulseSlow: + blend = (int)(ColorRender.A + 16 * MathF.Sin((float)gpGlobals.CurTime * 2 + offset)); + break; + case RenderFx.PulseFast: + blend = (int)(ColorRender.A + 16 * MathF.Sin((float)gpGlobals.CurTime * 8 + offset)); + break; + case RenderFx.FadeSlow: + if (ColorRender.A > 0) + SetRenderColorA((byte)(ColorRender.A - 1)); + else + SetRenderColorA(0); + blend = ColorRender.A; + break; + case RenderFx.FadeFast: + if (ColorRender.A > 3) + SetRenderColorA((byte)(ColorRender.A - 4)); + else + SetRenderColorA(0); + blend = ColorRender.A; + break; + case RenderFx.SolidSlow: + if (ColorRender.A < 255) + SetRenderColorA((byte)(ColorRender.A + 1)); + else + SetRenderColorA(255); + blend = ColorRender.A; + break; + case RenderFx.SolidFast: + if (ColorRender.A < 252) + SetRenderColorA((byte)(ColorRender.A + 4)); + else + SetRenderColorA(255); + blend = ColorRender.A; + break; + case RenderFx.StrobeSlow: + blend = (int)(20 * MathF.Sin((float)gpGlobals.CurTime * 4 + offset)); + blend = blend < 0 ? 0 : ColorRender.A; + break; + case RenderFx.StrobeFast: + blend = (int)(20 * MathF.Sin((float)gpGlobals.CurTime * 16 + offset)); + blend = blend < 0 ? 0 : ColorRender.A; + break; + case RenderFx.StrobeFaster: + blend = (int)(20 * MathF.Sin((float)gpGlobals.CurTime * 36 + offset)); + blend = blend < 0 ? 0 : ColorRender.A; + break; + case RenderFx.FlickerSlow: + blend = (int)(20 * (MathF.Sin((float)gpGlobals.CurTime * 2) + MathF.Sin((float)gpGlobals.CurTime * 17 + offset))); + blend = blend < 0 ? 0 : ColorRender.A; + break; + case RenderFx.FlickerFast: + blend = (int)(20 * (MathF.Sin((float)gpGlobals.CurTime * 16) + MathF.Sin((float)gpGlobals.CurTime * 23 + offset))); + blend = blend < 0 ? 0 : ColorRender.A; + break; + case RenderFx.Hologram: + case RenderFx.Distort: { + Vector3 tmp = GetAbsOrigin() - ViewAccessors.CurrentViewOrigin(); + float dist = MathLib.DotProduct(tmp, ViewAccessors.CurrentViewForward()); + if ((RenderFx)RenderFX == RenderFx.Distort) + dist = 1; + if (dist <= 0) + blend = 0; + else { + SetRenderColorA(180); + if (dist <= 100) + blend = ColorRender.A; + else + blend = (int)((1.0 - (dist - 100) * (1.0 / 400.0)) * ColorRender.A); + blend += random.RandomInt(-32, 31); + } + } + break; + default: + if (RenderMode == (int)Source.RenderMode.Normal) + blend = 255; + else + blend = ColorRender.A; + break; + } + + blend = Math.Clamp(blend, 0, 255); + + byte fadeAlpha = GetClientSideFade(); + if (fadeAlpha != 255) { + float flBlend = blend / 255.0f; + float flFade = fadeAlpha / 255.0f; + blend = (int)(flBlend * flFade * 255.0f + 0.5f); + blend = Math.Clamp(blend, 0, 255); + } + + RenderFXBlend = (byte)blend; + FXComputeFrame = gpGlobals.FrameCount; + + if (renderHandle != INVALID_CLIENT_RENDER_HANDLE) + clientLeafSystem.SetRenderGroup(renderHandle, GetRenderGroup()); + + if (ShadowHandle != CLIENTSHADOW_INVALID_HANDLE) + g_ClientShadowMgr.SetFalloffBias(ShadowHandle, (byte)(255 - RenderFXBlend)); } public virtual object GetDataTableBasePtr() { diff --git a/Game.Client/C_BasePlayer.cs b/Game.Client/C_BasePlayer.cs index e1fdb76b5..b635bc866 100644 --- a/Game.Client/C_BasePlayer.cs +++ b/Game.Client/C_BasePlayer.cs @@ -112,6 +112,22 @@ public bool GetSteamID(out CSteamID id) { } return false; } + PlayerInfo NetworkIDInfo; + InlineArray33 NetworkIDString; + public ReadOnlySpan GetNetworkIDString() { + if (engine.GetPlayerInfo(EntIndex(), out NetworkIDInfo)) { + if (NetworkIDInfo.FakePlayer) + return "BOT"; + uint friendsID = NetworkIDInfo.FriendsID; + if (friendsID != 0) + sprintf(NetworkIDString, "STEAM_0:%u:%u").U(friendsID & 1).U(friendsID >> 1); + else + for (int i = 0; i < 33; i++) + NetworkIDString[i] = (char)NetworkIDInfo.GUID[i]; + return ((ReadOnlySpan)NetworkIDString).SliceNullTerminatedString(); + } + return "NULL"; + } public bool IsHLTV() => IsLocalPlayer() && engine.IsHLTV(); public bool IsBot() => false; // TODO, gmod public static bool ShouldDrawLocalPlayer() { @@ -325,6 +341,7 @@ public virtual void PreThink() { public bool IsInAVehicle() => Vehicle.Get() != null; #if GMOD_DLL public virtual bool RestrictPlayerPitch() => false; + public virtual bool CanAttack() => true; #endif public virtual void SetAnimation(PlayerAnim playerAnim) { } // todo diff --git a/Game.Client/C_BaseViewModel.cs b/Game.Client/C_BaseViewModel.cs index 34aeb7a8a..aa193a0b1 100644 --- a/Game.Client/C_BaseViewModel.cs +++ b/Game.Client/C_BaseViewModel.cs @@ -4,6 +4,10 @@ using Source.Common.Mathematics; namespace Game.Client; + +#if GMOD_DLL +using Game.Client.GarrysMod; +#endif using DEFINE = Source.DEFINE; public partial class C_BaseViewModel @@ -26,11 +30,75 @@ public partial class C_BaseViewModel ]); public override DataMap? GetPredDescMap() => PredMap; int OldAnimationParity; +#if GMOD_DLL public override int DrawModel(StudioFlags flags) { if (!ReadyToDraw) return 0; - if((flags & StudioFlags.Render) != 0) { + C_BasePlayer? player = C_BasePlayer.GetLocalPlayer(); + if (GetOwningWeapon() == null) { + if (GetModelPtr() == null) + return 0; + if (stricmp(modelinfo.GetModelName(GetModel()), "weapons/v_hands.mdl") != 0) + return 0; + } + + if ((flags & StudioFlags.Render) == 0) + GetOwningWeapon(); + else { + float blend = (float)(GetFxBlend() / 255.0f); + if (blend <= 0.0f) + return 0; + + render.SetBlend(blend); + Span color = stackalloc float[3]; + GetColorModulation(color); + render.SetColorModulation(color); + + C_BaseCombatWeapon? preWeapon = GetOwningWeapon(); + if (preWeapon != null && player != null && gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PreDrawViewModel)) { + LuaEntity.Push_Entity(this); + LuaEntity.Push_Entity(player); + LuaEntity.Push_Entity(preWeapon); + g_Lua!.PushNumber((int)flags); + if (gGM.CallFinish(4)) + return 0; + } + } + + C_BaseCombatWeapon? weapon = GetOwningWeapon(); + int ret; + if (player != null && player.IsOverridingViewmodel()) + ret = player.DrawOverriddenViewmodel(this, flags); + else if (weapon != null && weapon.IsOverridingViewmodel()) + ret = weapon.DrawOverriddenViewmodel(this, flags); + else + ret = base.DrawModel(flags); + + StudioFlags drawnFlags = flags; + if ((flags & StudioFlags.Render) != 0 && weapon != null) { + drawnFlags = flags | StudioFlags.Transparency; + if ((flags & (StudioFlags.ShadowDepthTexture | StudioFlags.SSAODepthTexture)) != 0) + drawnFlags = flags & ~StudioFlags.Transparency; + weapon.ViewModelDrawn(this); + } + + if ((drawnFlags & StudioFlags.Render) != 0 && weapon != null && player != null && gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PostDrawViewModel)) { + LuaEntity.Push_Entity(this); + LuaEntity.Push_Entity(player); + LuaEntity.Push_Entity(weapon); + g_Lua!.PushNumber((int)drawnFlags); + gGM.CallNoReturns(4); + } + + return ret; + } +#else + public override int DrawModel(StudioFlags flags) { + if (!ReadyToDraw) + return 0; + + if ((flags & StudioFlags.Render) != 0) { // Determine blending amount and tell engine float blend = (float)(GetFxBlend() / 255.0f); @@ -57,19 +125,20 @@ public override int DrawModel(StudioFlags flags) { ret = base.DrawModel(flags); if ((flags & StudioFlags.Render) != 0) { - if (OldAnimationParity != AnimationParity) + if (OldAnimationParity != AnimationParity) OldAnimationParity = AnimationParity; // Tell the weapon itself that we've rendered, in case it wants to do something - if (weapon != null) + if (weapon != null) weapon.ViewModelDrawn(this); } return ret; } +#endif public void UpdateAnimationParity() { C_BasePlayer? player = C_BasePlayer.GetLocalPlayer(); - if(OldAnimationParity != AnimationParity && !GetPredictable()) { + if (OldAnimationParity != AnimationParity && !GetPredictable()) { double curtime = player != null && IsIntermediateDataAllocated() ? player.GetFinalPredictedTime() : gpGlobals.CurTime; SetCycle(0); AnimTime = curtime; @@ -98,21 +167,21 @@ public override bool Interpolate(TimeUnit_t currentTime) { // Predicted viewmodels have fixed up interval if (GetPredictable() || IsClientCreated()) { Assert(player != null); - TimeUnit_t curtime = player != null? player.GetFinalPredictedTime() : gpGlobals.CurTime; + TimeUnit_t curtime = player != null ? player.GetFinalPredictedTime() : gpGlobals.CurTime; elapsed_time = curtime - AnimTime; - if (!engine.IsPaused()) + if (!engine.IsPaused()) elapsed_time += (gpGlobals.InterpolationAmount * TICK_INTERVAL); } // Prediction errors? - if (elapsed_time < 0) + if (elapsed_time < 0) elapsed_time = 0; TimeUnit_t dt = elapsed_time * GetSequenceCycleRate(studioHdr, GetSequence()) * GetPlaybackRate(); if (dt >= 1.0f) { - if (!IsSequenceLooping(GetSequence())) + if (!IsSequenceLooping(GetSequence())) dt = 0.999; - else + else dt = MathLib.Fmodf(dt, 1.0); } SetCycle(dt); diff --git a/Game.Client/ClassMap.cs b/Game.Client/ClassMap.cs index 805f46da1..7b37e5f36 100644 --- a/Game.Client/ClassMap.cs +++ b/Game.Client/ClassMap.cs @@ -32,10 +32,10 @@ public class ClassMap : IClassMap { public static readonly ClassMap g_ClassMap = new(); public static ClassMap GetClassMap() => g_ClassMap; - static ClassMap(){ + static ClassMap() { // Here is where we start initializing things based on LinkEntityToClassAttribute's - var typePairs = Assembly.GetExecutingAssembly().GetTypesWithAttributeMulti< LinkEntityToClassAttribute>(); - foreach(var type in typePairs){ + var typePairs = Assembly.GetExecutingAssembly().GetTypesWithAttributeMulti(); + foreach (var type in typePairs) { var attr = type.Value; DynamicMethod m = new DynamicMethod("LinkEntity_Instantiate" + type.Key.Name + "_ToMap_" + attr.LocalName, typeof(C_BaseEntity), []); @@ -70,6 +70,16 @@ public void Add(Type type, ReadOnlySpan mapname, ReadOnlySpan classn } public C_BaseEntity? CreateEntity(ReadOnlySpan mapname) { +#if GMOD_DLL + if (GarrysMod.GarrysMod.g_LuaManager != null) { + Span lowered = stackalloc char[512]; + strcpy(lowered, mapname); + strlower(lowered); + C_BaseEntity? luaEnt = GarrysMod.GarrysMod.g_LuaManager.CreateEntity(((ReadOnlySpan)lowered).SliceNullTerminatedString()); + if (luaEnt != null) + return luaEnt; + } +#endif foreach (var kvp in ClassDict) { ClassEntry lookup = kvp.Value; if (stricmp(lookup.GetMapName(), mapname) != 0) diff --git a/Game.Client/ClientShadowMgr.cs b/Game.Client/ClientShadowMgr.cs index c16e58815..96f16984c 100644 --- a/Game.Client/ClientShadowMgr.cs +++ b/Game.Client/ClientShadowMgr.cs @@ -1082,7 +1082,7 @@ public void SetShadowDistance(float maxDistance) { public void SetShadowBlobbyCutoffArea(float minArea) => MinShadowArea = minArea; public float GetBlobbyCutoffArea() => MinShadowArea; - public void SetFalloffBias(ClientShadowHandle_t handle, byte bias) => throw new NotImplementedException(); + public void SetFalloffBias(ClientShadowHandle_t handle, byte bias) => g_ShadowMgr.SetFalloffBias(Shadows[handle].Shadow.ShadowHandle, bias); public void RestoreRenderState() { foreach (ClientShadowHandle_t h in ValidShadowHandles) diff --git a/Game.Client/GarrysMod/C_GMOD_Player.cs b/Game.Client/GarrysMod/C_GMOD_Player.cs index a9e3b7129..2948be022 100644 --- a/Game.Client/GarrysMod/C_GMOD_Player.cs +++ b/Game.Client/GarrysMod/C_GMOD_Player.cs @@ -73,6 +73,18 @@ public partial class C_GMOD_Player() : C_HL2MP_Player() public Vector3 PlayerColor; [NetworkName("m_WeaponColor")] public Vector3 WeaponColor; + + public virtual Vector3 GetPlayerColor() => PlayerColor; + + public virtual void SetPlayerColor(in Vector3 color) { + if (PlayerColor != color) + PlayerColor = color; + } + + public virtual void SetWeaponColor(in Vector3 color) { + if (WeaponColor != color) + WeaponColor = color; + } [NetworkName("m_Hands")] public EHANDLE Hands = new(); [NetworkName("m_iMaxArmor")] @@ -82,6 +94,9 @@ public partial class C_GMOD_Player() : C_HL2MP_Player() [NetworkName("m_bSprintEnabled")] public bool SprintEnabled; + public override bool RestrictPlayerPitch() => (GModPlayerFlags & 16) == 0; + public override bool CanAttack() => PressedWidget.Get() == null; + public override void UpdateClientSideAnimation() { if (Driving.Get() != null) { if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PlayerDriveAnimate)) { diff --git a/Game.Client/GarrysMod/C_LuaNextBot.cs b/Game.Client/GarrysMod/C_LuaNextBot.cs index 123948d20..fca7772db 100644 --- a/Game.Client/GarrysMod/C_LuaNextBot.cs +++ b/Game.Client/GarrysMod/C_LuaNextBot.cs @@ -1,3 +1,4 @@ +using Game.Client.GarrysMod; using Game.Shared; using Source; @@ -12,8 +13,28 @@ namespace Game.Client.NextBot; public class C_LuaNextBot : C_NextBotCombatCharacter { public static readonly RecvTable DT_LuaNextBot = new(DT_NextBot, [ - RecvPropDataTable("m_ScriptedEntity", DT_ScriptedEntity), + RecvPropDataTable("m_ScriptedEntity", FIELD.OF(nameof(ScriptedEntity)), ScriptedEntity.DT_ScriptedEntity, 0, RECV_GET_OBJECT_AT_FIELD(FIELD.OF(nameof(ScriptedEntity)))), RecvPropInt(FIELD.OF(nameof(LifeState))) ]); public static readonly new ClientClass ClientClass = new ClientClass(DT_LuaNextBot); + + public readonly ScriptedEntity ScriptedEntity = new(); + + public C_LuaNextBot() { + ScriptedEntity.Init(this, 1); + } + + public override ReadOnlySpan GetLuaScriptName() => ScriptedEntity.GetScriptName(); + + public override void InitializeScriptedEntity(ReadOnlySpan name) { + ScriptedEntity.SetScriptName(name); + SetClassname(name); + ScriptedEntity.StartLua(); + } + + public override void OnDataChanged(DataUpdateType updateType) { + base.OnDataChanged(updateType); + if (updateType == DataUpdateType.Created) + ScriptedEntity.StartLua(); + } } diff --git a/Game.Client/GarrysMod/LuaCSEnt.cs b/Game.Client/GarrysMod/LuaCSEnt.cs new file mode 100644 index 000000000..71076b1db --- /dev/null +++ b/Game.Client/GarrysMod/LuaCSEnt.cs @@ -0,0 +1,78 @@ +using Source; +using Source.Common; +using Source.Common.Engine; +using Source.Common.GarrysMod.Lua; + +using System.Numerics; + +namespace Game.Client.GarrysMod; + +public static partial class LuaCSEnt +{ + [LuaClass] + public static readonly LuaEntityClass LC_CSEnt = new("CSEnt", LuaType.Entity, null, "Entity"); + + [LuaMethod] + static int CSEnt____tostring(ILuaInterface lua) { + C_BaseEntity? ent = LuaEntity.Get_Entity(1, true); + if (ent == null) { + lua.PushString("[NULL CSEntity]"); + return 1; + } + lua.PushString($"CSEntity [{ent.GetClassname()}]"); + return 1; + } + + [LuaGlobal] + static int ClientsideModel(ILuaInterface lua) { + string name = lua.CheckString(1); + if (name.Length < 2) + return 0; + + RenderGroup renderGroup = RenderGroup.Other; + if (lua.GetType(2) == LuaType.Number) { + int group = (int)lua.GetNumber(2); + if (group < 0 || group == 0) + renderGroup = RenderGroup.OpaqueEntityHuge; + else if (group > (int)RenderGroup.Other) + renderGroup = RenderGroup.Other; + else if (group == (int)RenderGroup.OpaqueStatic) + renderGroup = RenderGroup.OpaqueEntity; + else + renderGroup = (RenderGroup)group; + } + + C_BaseFlex ent = new(); + int modelIndex = LuaUtil.UTIL_GetModelIndex(name); + if (modelIndex == -1 && (name[0] != '*' || (modelIndex = modelinfo.GetModelIndex(name)) == -1)) + ent.SetModelPointer(modelinfo.FindOrLoadModel(name)); + + if (!ent.InitializeAsClientEntity(modelIndex == -1 ? null : name, renderGroup)) { + Warning($"Failed to initialize ClientsideModel '{name}'!\n"); + ent.Release(); + return 0; + } + + ent.Dormant = false; + ent.InvalidateBoneCache(); + ent.FrameAdvance(1.0f); + ent.StudioFrameAdvance(); + Model? model = ent.GetModel(); + if (model != null) { + modelinfo.GetModelRenderBounds(model, out Vector3 mins, out Vector3 maxs); + ent.SetCollisionBounds(mins, maxs); + } + ent.SetCollisionGroup(CollisionGroup.Debris); + ent.Spawn(); + + LuaObject? luaEnt = ent.GetLuaEntity(); + if (luaEnt == null) { + ent.Release(); + return 0; + } + luaEnt.Push(); + LC_CSEnt.MetaTable.Push(); + lua.SetMetaTable(-2); + return 1; + } +} diff --git a/Game.Client/GarrysMod/LuaPanel.cs b/Game.Client/GarrysMod/LuaPanel.cs index 4e4873ba4..96f128e3f 100644 --- a/Game.Client/GarrysMod/LuaPanel.cs +++ b/Game.Client/GarrysMod/LuaPanel.cs @@ -76,6 +76,28 @@ static int Panel____index(ILuaInterface lua) { return 0; } + [LuaMethod] + static int Panel__PaintManual(ILuaInterface lua) { + Panel? panel = Get_Panel(1); + if (panel == null) { + lua.Error("Tried to use a NULL Panel!"); + return 0; + } + panel.PaintManual(lua.GetType(2) != LuaType.Nil &&lua.GetBool(2)); + return 0; + } + + [LuaMethod] + static int Panel__PaintAt(ILuaInterface lua) { + Panel? panel = Get_Panel(1); + if (panel == null) { + lua.Error("Tried to use a NULL Panel!"); + return 0; + } + panel.PaintAt((int)lua.CheckNumber(2), (int)lua.CheckNumber(3)); + return 0; + } + [LuaMethod] static int Panel____newindex(ILuaInterface lua) { Panel? panel = Get_Panel(1); @@ -135,10 +157,10 @@ static int Panel__IsVisible(ILuaInterface lua) { static void Panel__SetVisible(Panel panel, [LuaGet] bool visible) => panel.SetVisible(visible); [LuaMethod] - static void Panel__SetPos(Panel panel, int x, int y) => panel.SetPos(x, y); + static void Panel__SetPos(Panel panel, [LuaGet] int x, [LuaGet] int y) => panel.SetPos(x, y); [LuaMethod] - static void Panel__SetSize(Panel panel, int wide, int tall) => panel.SetSize(wide, tall); + static void Panel__SetSize(Panel panel, [LuaGet] int wide, [LuaGet] int tall) => panel.SetSize(wide, tall); [LuaMethod] static void Panel__SetParent(ILuaInterface lua, Panel panel) { @@ -233,7 +255,7 @@ static int Panel__IsEnabled(ILuaInterface lua) { static void Panel__SetEnabled(Panel panel, [LuaGet] bool state) => panel.SetEnabled(state); [LuaMethod] - static void Panel__SetMinimumSize(Panel panel, int wide, int tall) => panel.SetMinimumSize(wide, tall); + static void Panel__SetMinimumSize(Panel panel, [LuaGet] int wide, [LuaGet] int tall) => panel.SetMinimumSize(wide, tall); [LuaMethod] static bool Panel__IsMarkedForDeletion(Panel panel) => panel.IsMarkedForDeletion(); @@ -249,7 +271,7 @@ static void Panel__MakePopup(Panel panel) { static void Panel__InvalidateLayout(Panel panel, [LuaGet] bool layoutNow) => panel.InvalidateLayout(layoutNow, false); [LuaMethod] - static void Panel__SetZPos(Panel panel, int z) => panel.SetZPos(z); + static void Panel__SetZPos(Panel panel, [LuaGet] int z) => panel.SetZPos(z); [LuaMethod] static int Panel__GetZPos(Panel panel) => panel.GetZPos(); @@ -1025,13 +1047,13 @@ static void Panel__SetFontInternal(ILuaInterface lua, Panel panel) { } [LuaMethod] - static (int, int) Panel__LocalToScreen(Panel panel, int x, int y) { + static (int, int) Panel__LocalToScreen(Panel panel, [LuaGet] int x, [LuaGet] int y) { panel.LocalToScreen(ref x, ref y); return (x, y); } [LuaMethod] - static (int, int) Panel__ScreenToLocal(Panel panel, int x, int y) { + static (int, int) Panel__ScreenToLocal(Panel panel, [LuaGet] int x, [LuaGet] int y) { panel.ScreenToLocal(ref x, ref y); return (x, y); } diff --git a/Game.Client/GarrysMod/LuaRender.cs b/Game.Client/GarrysMod/LuaRender.cs index 16984cf27..ba9217012 100644 --- a/Game.Client/GarrysMod/LuaRender.cs +++ b/Game.Client/GarrysMod/LuaRender.cs @@ -165,7 +165,27 @@ static int GetAmbientLightColor(ILuaInterface lua) { // todo: GetFullScreenDepthTexture // todo: GetResolvedFullFrameDepth // todo: BindLocalCubemap - // todo: UpdateScreenEffectTexture + static readonly Vector3[] SuppressedAmbientLight = [new(1, 1, 1), new(1, 1, 1), new(1, 1, 1), new(1, 1, 1), new(1, 1, 1), new(1, 1, 1)]; + + [LuaFunction] + static int SuppressEngineLighting(ILuaInterface lua) { + bool suppress = lua.GetBool(1); + modelrender.SuppressEngineLighting(suppress); + if (suppress) { + studiorender.SetAmbientLightColors(SuppressedAmbientLight); + studiorender.SetLocalLights(0, null); + } + return 0; + } + + [LuaFunction] + static int UpdateScreenEffectTexture(ILuaInterface lua) { + int textureIndex = 0; + if (lua.GetType(1) == LuaType.Number) + textureIndex = (int)lua.GetNumber(1); + ViewScene.UpdateScreenEffectTexture(textureIndex, 0, 0, ScreenWidth(), ScreenHeight(), false); + return 0; + } // todo: UpdateRefractTexture // todo: GetRefractTexture // todo: UpdatePowerOfTwoTexture diff --git a/Game.Client/HistoryResource.cs b/Game.Client/HistoryResource.cs index f7a90e65a..00a028268 100644 --- a/Game.Client/HistoryResource.cs +++ b/Game.Client/HistoryResource.cs @@ -65,6 +65,7 @@ public override void ApplySchemeSettings(IScheme scheme) { } public override void Init() { + IHudElement.HookMessage("SWEPCmd", MsgFunc_SWEPCmd); IHudElement.HookMessage("ItemPickup", MsgFunc_ItemPickup); IHudElement.HookMessage("AmmoDenied", MsgFunc_AmmoDenied); Reset(); @@ -152,6 +153,22 @@ private void AddIconToHistory(HRType type, int id, BaseCombatWeapon? weapon, int ++CurrentHistorySlot; } + static InlineArray32 SWEPCmdFunction; + static InlineArray256 SWEPCmdArgs; + private void MsgFunc_SWEPCmd(bf_read msg) { + if (gHUD.FindElement("CHudGMod") == null || g_Lua == null) + return; + int encodedEHandle = msg.ReadLong(); + int entity = encodedEHandle & ((1 << Constants.MAX_EDICT_BITS) - 1); + int serialNum = encodedEHandle >> Constants.MAX_EDICT_BITS; + EHANDLE ent = new(entity, serialNum); + if (ent.Get() is not C_WeaponSWEP weapon) + return; + msg.ReadString(SWEPCmdFunction); + msg.ReadString(SWEPCmdArgs); + weapon.RunSWEPCmd(((ReadOnlySpan)SWEPCmdFunction).SliceNullTerminatedString(), ((ReadOnlySpan)SWEPCmdArgs).SliceNullTerminatedString()); + } + private void MsgFunc_ItemPickup(bf_read msg) { Span name = stackalloc char[1024]; msg.ReadString(name); diff --git a/Game.Client/Physics.cs b/Game.Client/Physics.cs index 74c4824bc..72cd42358 100644 --- a/Game.Client/Physics.cs +++ b/Game.Client/Physics.cs @@ -23,6 +23,13 @@ public static class PhysicsSystemHook static PhysicsSystemHook() { SetPhysicsGameSystem(g_PhysicsSystem); } + + public static bool PhysIsInCallback() { + if (physenv != null && physenv.IsInSimulation()) + return true; + // return g_Collisions.IsInCallback(); TODO + return false; + } } public class PhysicsSystem : AutoGameSystemPerFrame @@ -33,12 +40,12 @@ public override void LevelInitPostEntity() { PhysicsLevelInit(); } - static readonly ConVar cl_phys_timescale = new( "cl_phys_timescale", "1.0", FCvar.Cheat, "Sets the scale of time for client-side physics (ragdolls)" ); + static readonly ConVar cl_phys_timescale = new("cl_phys_timescale", "1.0", FCvar.Cheat, "Sets the scale of time for client-side physics (ragdolls)"); internal void PhysicsSimulate() { TimeUnit_t frametime = gpGlobals.FrameTime; - if(physenv != null){ + if (physenv != null) { physenv.DebugCheckContacts(); physenv.Simulate(frametime * cl_phys_timescale.GetDouble()); diff --git a/Game.Client/ViewRender.cs b/Game.Client/ViewRender.cs index d952c04e9..d4b1308b3 100644 --- a/Game.Client/ViewRender.cs +++ b/Game.Client/ViewRender.cs @@ -1611,8 +1611,7 @@ 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; + gGM?.Call((int)LUA_POOLEDSTRING.PostDrawSkyBox); #endif Rendering3DSkybox = false; } diff --git a/Game.Server/BaseAnimating.cs b/Game.Server/BaseAnimating.cs index 45dad5666..e7a3e0e1e 100644 --- a/Game.Server/BaseAnimating.cs +++ b/Game.Server/BaseAnimating.cs @@ -1132,6 +1132,8 @@ public int FindTransitionSequence(int currentSequence, int goalSequence) { return sequence; } + public int GetNumBodyGroups() => Animation.GetNumBodyGroups(GetModelPtr()); + public void SetBodygroup(int group, int value) { int newBody = Body; Animation.SetBodygroup(GetModelPtr(), ref newBody, group, value); diff --git a/Game.Server/BaseCombatCharacter.cs b/Game.Server/BaseCombatCharacter.cs index 29bbeb05b..9187c5a22 100644 --- a/Game.Server/BaseCombatCharacter.cs +++ b/Game.Server/BaseCombatCharacter.cs @@ -548,6 +548,10 @@ public override void UpdateOnRemove() { return weapon; } + public bool NoAmmo; + + public override BaseCombatCharacter? MyCombatCharacterPointer() => this; + public virtual void Weapon_Equip(BaseCombatWeapon weapon) { for (int i = 0; i < MAX_WEAPONS; i++) { if (MyWeapons[i].Get() == null) { @@ -558,18 +562,20 @@ public virtual void Weapon_Equip(BaseCombatWeapon weapon) { weapon.ChangeTeam(GetTeamNumber()); - if (weapon.GetMaxClip1() == -1) - GiveAmmo(weapon.GetDefaultClip1(), weapon.PrimaryAmmoType); - else if (weapon.GetDefaultClip1() > weapon.GetMaxClip1()) { - weapon.iClip1 = weapon.GetMaxClip1(); - GiveAmmo(weapon.GetDefaultClip1() - weapon.GetMaxClip1(), weapon.PrimaryAmmoType); - } + if (!NoAmmo && !weapon.WasDropped()) { + if (weapon.GetMaxClip1() == -1) + GiveAmmo(weapon.GetDefaultClip1(), weapon.PrimaryAmmoType); + else if (weapon.GetDefaultClip1() > weapon.GetMaxClip1()) { + weapon.iClip1 = weapon.GetMaxClip1(); + GiveAmmo(weapon.GetDefaultClip1() - weapon.GetMaxClip1(), weapon.PrimaryAmmoType); + } - if (weapon.GetMaxClip2() == -1) - GiveAmmo(weapon.GetDefaultClip2(), weapon.SecondaryAmmoType); - else if (weapon.GetDefaultClip2() > weapon.GetMaxClip2()) { - weapon.iClip2 = weapon.GetMaxClip2(); - GiveAmmo(weapon.GetDefaultClip2() - weapon.GetMaxClip2(), weapon.SecondaryAmmoType); + if (weapon.GetMaxClip2() == -1) + GiveAmmo(weapon.GetDefaultClip2(), weapon.SecondaryAmmoType); + else if (weapon.GetDefaultClip2() > weapon.GetMaxClip2()) { + weapon.iClip2 = weapon.GetMaxClip2(); + GiveAmmo(weapon.GetDefaultClip2() - weapon.GetMaxClip2(), weapon.SecondaryAmmoType); + } } weapon.Equip(this); diff --git a/Game.Server/BaseCombatWeapon.cs b/Game.Server/BaseCombatWeapon.cs index 2534e46fe..b4eeb88bf 100644 --- a/Game.Server/BaseCombatWeapon.cs +++ b/Game.Server/BaseCombatWeapon.cs @@ -16,6 +16,10 @@ public partial class BaseCombatWeapon : BaseAnimating { public static readonly ConVar weapon_showproficiency = new("weapon_showproficiency", "0"); + public bool Dropped; + public virtual bool WasDropped() => Dropped; + public virtual void SetDropped() => Dropped = true; + public OutputEvent OnPlayerUse = new(); public OutputEvent OnPlayerPickup = new(); public OutputEvent OnNPCPickup = new(); diff --git a/Game.Server/BaseEntity.cs b/Game.Server/BaseEntity.cs index e1d10b43a..a3d965ef9 100644 --- a/Game.Server/BaseEntity.cs +++ b/Game.Server/BaseEntity.cs @@ -895,6 +895,16 @@ public bool IsViewable() { public virtual void UpdateOnRemove() { Util.g_bReceivedChainedUpdateOnRemove = true; +#if GMOD_DLL + for (int i = 0; i < DeleteOnRemoveList.Count; i++) { + BaseEntity? ent = DeleteOnRemoveList[i].Get(); + if (ent == null) + continue; + Util.RemoveSafe(ent); + DeleteOnRemoveList[i] = new(); + } +#endif + // Virtual call to shut down any looping sounds. StopLoopingSounds(); @@ -1677,25 +1687,25 @@ public bool IsFloating() { public byte WaterType; [NetworkName("m_GMOD_bool")] - InlineArray32 GMOD_bool; + public InlineArray32 GMOD_bool; [NetworkName("m_GMOD_float")] - InlineArray32 GMOD_float; + public InlineArray32 GMOD_float; [NetworkName("m_GMOD_int")] - InlineArray32 GMOD_int; + public InlineArray32 GMOD_int; [NetworkName("m_GMOD_Vector")] - InlineArray32 GMOD_Vector; + public InlineArray32 GMOD_Vector; [NetworkName("m_GMOD_QAngle")] - InlineArray32 GMOD_QAngle; + public InlineArray32 GMOD_QAngle; [NetworkName("m_GMOD_EHANDLE")] - InlineArray32 GMOD_EHANDLE; // << ENSURE THESE ARE INITIALIZED!!!! + public InlineArrayNew32 GMOD_EHANDLE = new(); [NetworkName("m_GMOD_String0")] - InlineArray512 GMOD_String0; + public InlineArray512 GMOD_String0; [NetworkName("m_GMOD_String1")] - InlineArray512 GMOD_String1; + public InlineArray512 GMOD_String1; [NetworkName("m_GMOD_String2")] - InlineArray512 GMOD_String2; + public InlineArray512 GMOD_String2; [NetworkName("m_GMOD_String3")] - InlineArray512 GMOD_String3; + public InlineArray512 GMOD_String3; public int DataObjectTypes; @@ -1724,6 +1734,16 @@ public bool IsFloating() { public virtual int GetMaxHealth() => MaxHealth; public void GetMaxHealth(int amt) => MaxHealth = amt; + public void SetMaxHealth(int amt) => MaxHealth = amt; + public virtual BaseCombatCharacter? MyCombatCharacterPointer() => null; + + public readonly List DeleteOnRemoveList = []; + + public virtual void DeleteOnRemove(BaseEntity? ent) { + EHANDLE handle = new(); + handle.Set(ent); + DeleteOnRemoveList.Add(handle); + } public int GetHealth() => Health; public int SetHealth(int amt) => Health = amt; @@ -2229,7 +2249,18 @@ public void SetName(ReadOnlySpan name) { public void SetName(string? name) { Name = name; } - public void SetOwnerEntity(BaseEntity? owner) => OwnerEntity.Set(owner); + public virtual void SetOwnerEntity(BaseEntity? owner) { + if (OwnerEntity.Get() == owner) + return; + if (OwnerEntity.Get() != owner) { + NetworkStateChanged(); + OwnerEntity.Set(owner); + } + CollisionRulesChanged(); + OnOwnerChanged(); + } + + public virtual void OnOwnerChanged() { } public BaseEntity? GetOwnerEntity() => OwnerEntity.Get(); public void SetMoveType(MoveType val, MoveCollide moveCollide = Source.MoveCollide.Default) { diff --git a/Game.Server/GameInterface.cs b/Game.Server/GameInterface.cs index 131266041..b79173fa6 100644 --- a/Game.Server/GameInterface.cs +++ b/Game.Server/GameInterface.cs @@ -57,6 +57,12 @@ public static void UserMessageBegin(in IRecipientFilter filter, ReadOnlySpan userName, ReadOnlySpan n throw new NotImplementedException(); } + static readonly UserCmd[] ProcessUsercmdsBuffer = new UserCmd[CMD_MAXBACKUP]; public TimeUnit_t ProcessUsercmds(Edict player, bf_read buf, int numCmds, int totalCmds, int droppedPackets, bool ignore, bool paused) { int i; UserCmd from, to; - UserCmd[] cmds = new UserCmd[CMD_MAXBACKUP]; + UserCmd[] cmds = ProcessUsercmdsBuffer; UserCmd cmdNull = new(); diff --git a/Game.Server/GarrysMod/GMOD_Player.cs b/Game.Server/GarrysMod/GMOD_Player.cs index 780886eb4..67af4151d 100644 --- a/Game.Server/GarrysMod/GMOD_Player.cs +++ b/Game.Server/GarrysMod/GMOD_Player.cs @@ -81,6 +81,9 @@ public override void Spawn() { } } + public override bool RestrictPlayerPitch() => (GModPlayerFlags & 16) == 0; + public override bool CanAttack() => PressedWidget.Get() == null; + public override BaseEntity EntSelectSpawnPoint() { BaseEntity? spot = null; while ((spot = gEntList.FindEntityByClassname(spot, "info_player_start")) != null) { @@ -91,6 +94,7 @@ public override BaseEntity EntSelectSpawnPoint() { return base.EntSelectSpawnPoint(); } + public bool ShouldDropWeapon; [NetworkName("m_iGModPlayerFlags")] public int GModPlayerFlags; [NetworkName("m_HoveredWidget")] @@ -121,6 +125,22 @@ public override BaseEntity EntSelectSpawnPoint() { public Vector3 PlayerColor = new(255, 255, 255); [NetworkName("m_WeaponColor")] public Vector3 WeaponColor = new(255, 255, 255); + + public virtual Vector3 GetPlayerColor() => PlayerColor; + + public virtual void SetPlayerColor(in Vector3 color) { + if (PlayerColor != color) { + NetworkStateChanged(); + PlayerColor = color; + } + } + + public virtual void SetWeaponColor(in Vector3 color) { + if (WeaponColor != color) { + NetworkStateChanged(); + WeaponColor = color; + } + } [NetworkName("m_Hands")] public EHANDLE Hands = new(); [NetworkName("m_iMaxArmor")] diff --git a/Game.Server/GarrysMod/LuaNextBot.cs b/Game.Server/GarrysMod/LuaNextBot.cs index e6cac2d1c..91c575b96 100644 --- a/Game.Server/GarrysMod/LuaNextBot.cs +++ b/Game.Server/GarrysMod/LuaNextBot.cs @@ -1,4 +1,5 @@ using Game.Server; +using Game.Server.GarrysMod; using Game.Shared; using Source.Common; @@ -11,8 +12,22 @@ namespace Game.Server.NextBot; public class LuaNextBot : NextBotCombatCharacter { public static readonly SendTable DT_LuaNextBot = new(DT_NextBot, [ - SendPropDataTable("m_ScriptedEntity", DT_ScriptedEntity), + SendPropDataTable("m_ScriptedEntity", FIELD.OF(nameof(ScriptedEntity)), ScriptedEntity.DT_ScriptedEntity), SendPropInt(FIELD.OF(nameof(LifeState)), 3, PropFlags.Unsigned) ]); public static readonly new ServerClass ServerClass = new ServerClass(DT_LuaNextBot); + + public readonly ScriptedEntity ScriptedEntity = new(); + + public LuaNextBot() { + ScriptedEntity.Init(this, 1); + } + + public override ReadOnlySpan GetLuaScriptName() => ScriptedEntity.GetScriptName(); + + public override void InitializeScriptedEntity(ReadOnlySpan name) { + ScriptedEntity.SetScriptName(name); + SetClassname(name); + ScriptedEntity.StartLua(); + } } diff --git a/Game.Server/HL2MP/HL2MP_Player.cs b/Game.Server/HL2MP/HL2MP_Player.cs index 98712e44e..c7e452fa8 100644 --- a/Game.Server/HL2MP/HL2MP_Player.cs +++ b/Game.Server/HL2MP/HL2MP_Player.cs @@ -359,6 +359,11 @@ public override void PreThink() { SetLocalAngles(oldAngles); } + public void DoAnimationEvent(PlayerAnimEvent evt, int data, bool predicted) { + PlayerAnimState.DoAnimationEvent(evt, data); + TEPlayerAnimEvent.TE_PlayerAnimEvent(this, evt, data, predicted); + } + public override void PostThink() { base.PostThink(); diff --git a/Game.Server/Player.cs b/Game.Server/Player.cs index e48a3fd87..6b613eae4 100644 --- a/Game.Server/Player.cs +++ b/Game.Server/Player.cs @@ -248,6 +248,32 @@ public enum PlayerPhysFlag [NetworkName("CBasePlayer")] public partial class BasePlayer : BaseCombatCharacter { + [NetworkName("m_ArmorValue")] + public int ArmorValue; + + public int GetArmorValue() => ArmorValue; + + public void SetArmorValue(int value) { + if (ArmorValue != value) { + NetworkStateChanged(); + ArmorValue = value; + } + } + + static InlineArray1024 InfoBuffer; + + public ReadOnlySpan GetInfo(ReadOnlySpan name) { + strcpy(InfoBuffer, engine.GetClientConVarValue(engine.IndexOfEdict(Edict()), name)); + return ((ReadOnlySpan)InfoBuffer).SliceNullTerminatedString(); + } + + public float GetInfoNum(ReadOnlySpan name, float fallback) { + strcpy(InfoBuffer, engine.GetClientConVarValue(engine.IndexOfEdict(Edict()), name)); + if (InfoBuffer[0] == '\0') + return fallback; + return (float)atof(InfoBuffer); + } + [Flags] public enum SF { @@ -534,6 +560,7 @@ public void SetBodyPitch(float pitch) { public override bool IsInAVehicle() => Vehicle.Get() != null; #if GMOD_DLL public virtual bool RestrictPlayerPitch() => false; + public virtual bool CanAttack() => true; #endif public float GetStepSize() => Local.StepSize; @@ -853,15 +880,15 @@ public bool HasAnyAmmoOfType(int ammoIndex) { } pent.SetLocalOrigin(GetLocalOrigin()); - // pent.AddSpawnFlags(SF_NORESPAWN); + pent.AddSpawnFlags(SF.NoRespawn); BaseCombatWeapon? weapon = (BaseCombatWeapon?)((BaseEntity)pent); weapon?.SetSubType(subType); Util.DispatchSpawn(pent); - // if (pent != null && !(pent.IsMarkedForDeletion())) - // pent.Touch(this); + if (pent != null && !(pent.IsMarkedForDeletion())) + pent.Touch(this); return pent; } @@ -1872,6 +1899,12 @@ public virtual void ForceDropOfCarriedPhysObjects(BaseEntity? ground) { } internal int GetUserID() => engine.GetPlayerUserId(Edict()); + public bool GetSteamID(out Steamworks.CSteamID id) { + Steamworks.CSteamID? steamID = engine.GetClientSteamID(Edict()); + id = steamID ?? default; + return steamID != null; + } + internal ReadOnlySpan GetNetworkIDString() { ReadOnlySpan str = engine.GetPlayerNetworkIDString(Edict()); int l = strcpy(NetworkIDString, str); diff --git a/Game.Server/SourceDllMain.cs b/Game.Server/SourceDllMain.cs index 86dc33975..b3fd5d80f 100644 --- a/Game.Server/SourceDllMain.cs +++ b/Game.Server/SourceDllMain.cs @@ -8,6 +8,7 @@ using Source.Common.DataCache; using Source.Common.Engine; using Source.Common.Filesystem; +using Source.Common.MaterialSystem; using Source.Common.SceneFileCache; using Source.Common.Server; using Source.Common.SoundEmitterSystem; @@ -35,6 +36,7 @@ public static void Link(IServiceCollection services) { [Dependency] public static IVoiceServer g_pVoiceServer { get; private set; } = null!; [Dependency] public static UserMessages usermessages { get; private set; } = null!; [Dependency] public static IMDLCache mdlcache { get; private set; } = null!; + [Dependency] public static IMaterialSystem materials { get; private set; } = null!; [Dependency] public static ISceneFileCache scenefilecache { get; private set; } = null!; [KeyedDependency(Key = Realm.Server)] public static IVModelInfo modelinfo { get; private set; } = null!; [Dependency] public static GlobalEntityList gEntList { get; private set; } = null!; diff --git a/Game.Server/TEPlayerAnimEvent.cs b/Game.Server/TEPlayerAnimEvent.cs index 2070b047f..78350def5 100644 --- a/Game.Server/TEPlayerAnimEvent.cs +++ b/Game.Server/TEPlayerAnimEvent.cs @@ -18,7 +18,19 @@ public class TEPlayerAnimEvent(ReadOnlySpan name) : BaseTempEntity(name) [NetworkName("m_hPlayer")] public EHANDLE Player = new(); [NetworkName("m_iEvent")] - public readonly int Event; + public int Event; [NetworkName("m_nData")] - public readonly int Data; + public int Data; + + public static readonly TEPlayerAnimEvent g_TEPlayerAnimEvent = new("PlayerAnimEvent"); + + public static void TE_PlayerAnimEvent(BasePlayer player, PlayerAnimEvent evt, int data, bool predicted) { + PVSFilter filter = new(player.EyePosition()); + if (predicted) + filter.UsePredictionRules(); + g_TEPlayerAnimEvent.Player.Set(player); + g_TEPlayerAnimEvent.Event = (int)evt; + g_TEPlayerAnimEvent.Data = data; + g_TEPlayerAnimEvent.Create(ref filter, 0); + } } diff --git a/Game.Server/Util.cs b/Game.Server/Util.cs index 2bdf8fb3f..6bc3aea42 100644 --- a/Game.Server/Util.cs +++ b/Game.Server/Util.cs @@ -89,6 +89,16 @@ public class CEntityFactoryDictionary : IEntityFactoryDictionary public IServerNetworkable? Create(ReadOnlySpan className) { className = className.SliceNullTerminatedString(); IEntityFactory? factory = FindFactory(className); +#if GMOD_DLL + if (Game.Client.GarrysMod.GarrysMod.g_LuaManager != null) { + Span lowered = stackalloc char[512]; + strcpy(lowered, className); + strlower(lowered); + IServerNetworkable? luaEnt = Game.Client.GarrysMod.GarrysMod.g_LuaManager.CreateEntity(((ReadOnlySpan)lowered).SliceNullTerminatedString(), factory != null); + if (luaEnt != null) + return luaEnt; + } +#endif if (factory == null) { Warning($"Attempted to create unknown entity type {className}!\n"); return null; @@ -665,6 +675,18 @@ public static int DispatchSpawn(BaseEntity? entity) { return 0; } +#if GMOD_DLL + public static void RemoveSafe(BaseEntity? entity) { + if (entity == null) + return; + if (Game.Client.GarrysMod.GarrysMod.IsSacredEntity(entity.Classname ?? "")) { + Warning($"Refusing to delete entity '{entity.Classname ?? ""}'!\n"); + return; + } + Remove(entity.NetworkProp()); + } +#endif + public static void Remove(BaseEntity? entity) { if (entity == null) return; diff --git a/Game.Shared/Animation.cs b/Game.Shared/Animation.cs index d0af2ba1f..489dd46aa 100644 --- a/Game.Shared/Animation.cs +++ b/Game.Shared/Animation.cs @@ -386,6 +386,12 @@ public static int SelectWeightedSequence(StudioHdr? studiohdr, Activity activity return studiohdr.SelectWeightedSequence((int)activity, curSequence); } + internal static int GetNumBodyGroups(StudioHdr? studioHdr) { + if (studioHdr == null) + return 0; + return studioHdr.NumBodyParts(); + } + internal static void SetBodygroup(StudioHdr? studioHdr, ref int body, int group, int value) { if (studioHdr == null) return; diff --git a/Game.Shared/BaseCombatCharacterShared.cs b/Game.Shared/BaseCombatCharacterShared.cs index c618b786e..1cc48366e 100644 --- a/Game.Shared/BaseCombatCharacterShared.cs +++ b/Game.Shared/BaseCombatCharacterShared.cs @@ -8,8 +8,10 @@ #if CLIENT_DLL namespace Game.Client; +using Game.Client.GarrysMod; #else namespace Game.Server; +using Game.Server.GarrysMod; #endif public partial class @@ -20,16 +22,13 @@ public partial class #endif { public int GetAmmoCount(int ammoIndex) { - if (ammoIndex == -1) + if ((uint)ammoIndex >= MAX_AMMO_SLOTS) return 0; - // TODO, it is 4 am, I do not want to do this right now - // FIXME FIX ME FIX ME -#if CLIENT_DLL + if (GetAmmoDef().MaxCarry(ammoIndex) == AmmoDef.INFINITE_AMMO) + return 999; + return Ammo[ammoIndex]; -#else - return 0; -#endif } public virtual BaseCombatWeapon? Weapon_OwnsThisType(ReadOnlySpan weapon, int subtype) { @@ -118,6 +117,27 @@ public void RemoveAmmo(int count, int ammoIndex) { } public void RemoveAmmo(int count, ReadOnlySpan name) => RemoveAmmo(count, GetAmmoDef().Index(name)); +#if GMOD_DLL + public static void OnAmmoChanged(BaseCombatCharacter? ent, int ammoIndex, int oldCount, int newCount) { + if (oldCount != newCount && ent != null && ent.IsPlayer() && gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PlayerAmmoChanged)) { + LuaEntity.Push_Entity(ent); + g_Lua!.PushNumber(ammoIndex); + g_Lua.PushNumber(oldCount); + g_Lua.PushNumber(newCount); + gGM.CallNoReturns(4); + } + } + + public void RemoveAllAmmo() { + for (int i = 0; i < MAX_AMMO_SLOTS; i++) { + int old = Ammo[i]; + if (Ammo[i] != 0) + Ammo.Set(i, 0); + OnAmmoChanged(this, i, old, 0); + } + } +#endif + public virtual Vector3 Weapon_ShootPosition() => EyePosition(); public bool SwitchToNextBestWeapon(BaseCombatWeapon current) { diff --git a/Game.Shared/BaseCombatWeaponShared.cs b/Game.Shared/BaseCombatWeaponShared.cs index 9001f998a..8c1457e87 100644 --- a/Game.Shared/BaseCombatWeaponShared.cs +++ b/Game.Shared/BaseCombatWeaponShared.cs @@ -34,6 +34,12 @@ namespace Game.Server; #endif using Source.Common.SoundEmitterSystem; +using Source.Common.Commands; +#if GMOD_DLL && CLIENT_DLL +using Game.Client.GarrysMod; +#elif GMOD_DLL +using Game.Server.GarrysMod; +#endif using System.Runtime.CompilerServices; @@ -288,6 +294,23 @@ public virtual Activity ActivityOverride(Activity baseAct, ref bool required) { #if GMOD_DLL public virtual ReadOnlySpan GetHoldType() => "normal"; + public virtual void SetHoldType(ReadOnlySpan holdType) { } + public static readonly ConVar sv_defaultdeployspeed = new("sv_defaultdeployspeed", "4", FCvar.Replicated, "", 0.1, 10.0); + + public TimeUnit_t LastShootTimeValue; + public virtual TimeUnit_t LastShootTime() => LastShootTimeValue; + public virtual void SetLastShootTime(TimeUnit_t time) => LastShootTimeValue = time; + + public float GetDeploySpeed() { + LuaObject? table = GetLuaTable(); + if (table == null) + return sv_defaultdeployspeed.GetFloat() > 0.1f ? sv_defaultdeployspeed.GetFloat() : 0.1f; + if (table.GetMemberFloat("m_WeaponDeploySpeed", sv_defaultdeployspeed.GetFloat()) > 0.1f) + return table.GetMemberFloat("m_WeaponDeploySpeed", sv_defaultdeployspeed.GetFloat()); + return 0.1f; + } + + public void SetDeploySpeed(float speed) => GetLuaTable()?.SetMember("m_WeaponDeploySpeed", speed); #endif public override void Activate() { @@ -1432,9 +1455,9 @@ public override void Spawn() { HudHintMinDisplayTime = 0; } - public bool VisibleInWeaponSelection() => true; - public int GetPosition() => GetWpnData().Position; - public int GetSlot() => GetWpnData().Slot; + public virtual bool VisibleInWeaponSelection() => true; + public virtual int GetPosition() => GetWpnData().Position; + public virtual int GetSlot() => GetWpnData().Slot; WEAPON_FILE_INFO_HANDLE WeaponFileInfoHandle; public WEAPON_FILE_INFO_HANDLE GetWeaponFileInfoHandle() => WeaponFileInfoHandle; @@ -1443,8 +1466,8 @@ public FileWeaponInfo GetWpnData() { return WeaponParse.GetFileWeaponInfoFromHandle(WeaponFileInfoHandle); } - public ReadOnlySpan GetName() => GetWpnData().ClassName.SliceNullTerminatedString(); - public ReadOnlySpan GetPrintName() => GetWpnData().PrintName.SliceNullTerminatedString(); + public virtual ReadOnlySpan GetName() => GetWpnData().ClassName.SliceNullTerminatedString(); + public virtual ReadOnlySpan GetPrintName() => GetWpnData().PrintName.SliceNullTerminatedString(); #if CLIENT_DLL public HudTexture GetSpriteActive() => GetWpnData().IconActive; public HudTexture GetSpriteInactive() => GetWpnData().IconInactive; @@ -1477,10 +1500,10 @@ public bool CanBeSelected() { return HasAmmo(); } - public int GetMaxClip1() => GetWpnData().MaxClip1; - public int GetMaxClip2() => GetWpnData().MaxClip2; - public int GetDefaultClip1() => GetWpnData().DefaultClip1; - public int GetDefaultClip2() => GetWpnData().DefaultClip2; + public virtual int GetMaxClip1() => GetWpnData().MaxClip1; + public virtual int GetMaxClip2() => GetWpnData().MaxClip2; + public virtual int GetDefaultClip1() => GetWpnData().DefaultClip1; + public virtual int GetDefaultClip2() => GetWpnData().DefaultClip2; public bool IsMeleeWeapon() => GetWpnData().MeleeWeapon; public int SubType; @@ -1489,13 +1512,13 @@ public bool CanBeSelected() { public bool UsesClipsForAmmo1() => GetMaxClip1() != WEAPON_NOCLIP; public bool UsesClipsForAmmo2() => GetMaxClip2() != WEAPON_NOCLIP; - public int GetWeight() => GetWpnData().Weight; - public bool AllowsAutoSwitchTo() => GetWpnData().AutoSwitchTo; - public bool AllowsAutoSwitchFrom() => GetWpnData().AutoSwitchFrom; + public virtual int GetWeight() => GetWpnData().Weight; + public virtual bool AllowsAutoSwitchTo() => GetWpnData().AutoSwitchTo; + public virtual bool AllowsAutoSwitchFrom() => GetWpnData().AutoSwitchFrom; public bool UsesPrimaryAmmo() => PrimaryAmmoType >= 0; public bool UsesSecondaryAmmo() => SecondaryAmmoType >= 0; - public ReadOnlySpan GetViewModel(int _ = 0) => GetWpnData().ViewModel.SliceNullTerminatedString(); - public ReadOnlySpan GetWorldModel() => GetWpnData().WorldModel.SliceNullTerminatedString(); + public virtual ReadOnlySpan GetViewModel(int _ = 0) => GetWpnData().ViewModel.SliceNullTerminatedString(); + public virtual ReadOnlySpan GetWorldModel() => GetWpnData().WorldModel.SliceNullTerminatedString(); public ReadOnlySpan GetAnimPrefix() => GetWpnData().AnimationPrefix.SliceNullTerminatedString(); } #endif diff --git a/Game.Shared/BaseEntityShared.cs b/Game.Shared/BaseEntityShared.cs index 651b96059..306ec2487 100644 --- a/Game.Shared/BaseEntityShared.cs +++ b/Game.Shared/BaseEntityShared.cs @@ -106,16 +106,6 @@ public partial class { public const int BASEENTITY_MSG_REMOVE_DECALS = 1; - // TODO FIXME REVIEW: SHOULD THIS ACTUALLY GO HERE? - public static Table DT_ScriptedEntity = new(nameof(DT_ScriptedEntity), [ -#if CLIENT_DLL - RecvPropString(FIELD.OF(nameof(ScriptName))) -#elif GAME_DLL - SendPropString(FIELD.OF(nameof(ScriptName))) -#endif - ]); - [NetworkName("m_strScriptName")] - public InlineArrayMaxPath ScriptName; public bool IsAnimatedEveryTick() => AnimatedEveryTick; public bool IsSimulatedEveryTick() => SimulatedEveryTick; diff --git a/Game.Shared/BasePlayerShared.cs b/Game.Shared/BasePlayerShared.cs index 8f2bd4371..7ac47d865 100644 --- a/Game.Shared/BasePlayerShared.cs +++ b/Game.Shared/BasePlayerShared.cs @@ -485,6 +485,66 @@ public virtual float GetPlayerMaxSpeed() { public virtual float GetWalkSpeed() => Local.WalkSpeed; public virtual float GetUnDuckSpeed() => Local.UnDuckSpeed; + // TODO: these should use [NetworkVar] +#if CLIENT_DLL + public virtual void SetSprintSpeed(float speed) => Local.SprintSpeed = speed; + public virtual void SetWalkSpeed(float speed) => Local.WalkSpeed = speed; + public virtual void SetSlowWalkSpeed(float speed) => Local.SlowWalkSpeed = speed; + public virtual void SetLadderSpeed(float speed) => Local.LadderSpeed = speed; + public virtual void SetCrouchedWalkSpeed(float speed) => Local.CrouchedWalkSpeed = speed; + public virtual void SetDuckSpeed(float speed) => Local.DuckSpeed = speed; + public virtual void SetUnDuckSpeed(float speed) => Local.UnDuckSpeed = speed; +#else + public virtual void SetSprintSpeed(float speed) { + if (Local.SprintSpeed != speed) { + NetworkStateChanged(); + Local.SprintSpeed = speed; + } + } + + public virtual void SetWalkSpeed(float speed) { + if (Local.WalkSpeed != speed) { + NetworkStateChanged(); + Local.WalkSpeed = speed; + } + } + + public virtual void SetSlowWalkSpeed(float speed) { + if (Local.SlowWalkSpeed != speed) { + NetworkStateChanged(); + Local.SlowWalkSpeed = speed; + } + } + + public virtual void SetLadderSpeed(float speed) { + if (Local.LadderSpeed != speed) { + NetworkStateChanged(); + Local.LadderSpeed = speed; + } + } + + public virtual void SetCrouchedWalkSpeed(float speed) { + if (Local.CrouchedWalkSpeed != speed) { + NetworkStateChanged(); + Local.CrouchedWalkSpeed = speed; + } + } + + public virtual void SetDuckSpeed(float speed) { + if (Local.DuckSpeed != speed) { + NetworkStateChanged(); + Local.DuckSpeed = speed; + } + } + + public virtual void SetUnDuckSpeed(float speed) { + if (Local.UnDuckSpeed != speed) { + NetworkStateChanged(); + Local.UnDuckSpeed = speed; + } + } +#endif + int SkipStep; public void UpdateStepSound(SurfaceData_ptr? surface, in Vector3 origin, in Vector3 velocity) { diff --git a/Game.Shared/GarrysMod/BaseEntityLua.cs b/Game.Shared/GarrysMod/BaseEntityLua.cs index 62ab75680..b16a57ebf 100644 --- a/Game.Shared/GarrysMod/BaseEntityLua.cs +++ b/Game.Shared/GarrysMod/BaseEntityLua.cs @@ -27,6 +27,9 @@ public partial class public virtual bool IsRagdollProp() => false; public virtual bool IsJeep() => false; public virtual void PostLuaSpawn() { } + public virtual ReadOnlySpan GetLuaScriptName() => null; + public virtual void InitializeScriptedEntity(ReadOnlySpan name) { } + public virtual void Lua_OnEntityInitialized() { } public virtual LuaClass Lua_GetLuaClass() => LuaEntity.LC_Entity; public virtual void PushEntity() { diff --git a/Game.Shared/GarrysMod/GarrysMod.cs b/Game.Shared/GarrysMod/GarrysMod.cs index a70f9aaef..f60abde49 100644 --- a/Game.Shared/GarrysMod/GarrysMod.cs +++ b/Game.Shared/GarrysMod/GarrysMod.cs @@ -2,6 +2,9 @@ global using static Game.Client.GarrysMod.GarrysModSingletons; using Game.Shared; +#if GAME_DLL +using Game.Server.GarrysMod; +#endif using Microsoft.Extensions.DependencyInjection; @@ -252,6 +255,60 @@ public static void OnLoaded() { #endif } + static readonly string[] SacredEntities = [ + "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 IsSacredEntity(ReadOnlySpan className) { + foreach (string sacred in SacredEntities) + if (stricmp(className, sacred) == 0) + return true; + return false; + } + +#if GAME_DLL + static readonly string[] OverridableWeapons = [ + "weapon_crowbar", "weapon_stunstick", "weapon_357", "weapon_pistol", "weapon_smg1", "weapon_ar2", "weapon_crossbow", + "weapon_shotgun", "weapon_frag", "weapon_slam", "weapon_bugbait", "weapon_physcannon", "weapon_physgun", "weapon_alyxgun", + "weapon_annabelle", "weapon_rpg", "weapon_crowbar_hl1", "weapon_357_hl1", "weapon_glock_hl1", "weapon_egon", + "weapon_handgrenade", "weapon_hornetgun", "weapon_mp5_hl1", "weapon_crossbow_hl1", "weapon_rpg_hl1", "weapon_satchel", + "weapon_snark", "weapon_shotgun_hl1", "weapon_gauss", "weapon_tripmine" + ]; + + static readonly string[] OverridableEntities = [ + "point_servercommand", "point_teleport", "point_viewcontrol", "env_credits", "env_hudhint", "env_screenoverlay", "env_zoom", + "filter_activator_team", "filter_activator_context", "game_player_equip", "info_npc_spawn_destination", "logic_auto", + "player_loadsaved", "player_speedmod", "npc_template_maker", "npc_maker", "prop_physics_respawnable", "trigger_auto", + "trigger_changelevel", "trigger_hurt", "trigger_multiple", "trigger_once", "trigger_teleport", "trigger_transition", + "trigger_push", "ambient_generic", "func_pushable", "func_healthcharger", "func_recharge", "func_tankmortar", + "item_suitcharger", "item_healthcharger", "item_longjump", "item_suit", "item_healthkit", "item_battery", "weaponbox", + "speaker", "monster_satchel", "monster_tripmine", "info_player_teamspawn", "info_vehicle_groundspawn", "ammo_crossbow", + "ammo_egonclip", "ammo_gaussclip", "ammo_glockclip", "ammo_9mmclip", "ammo_mp5clip", "ammo_9mmar", "ammo_9mmbox", + "ammo_mp5grenades", "ammo_argrenades", "ammo_357", "ammo_rpgclip", "ammo_buckshot", "bounce_bomb", "combine_bouncemine", + "combine_mine", "prop_car_alarm", "prop_car_glass", "prop_health_cabinet", "asw_door", "dod_control_point", + "team_control_point", "prop_portal_stats_display", "npc_personality_core", "prop_tractor_beam", "prop_under_floor_button", + "prop_floor_ball_button", "prop_floor_cube_button", "prop_under_button", "prop_floor_button", "prop_button", + "prop_indicator_panel", "prop_testchamber_door", "prop_wall_projector", "npc_wheatley_boss", "prop_laser_relay", + "prop_dropper", "env_portal_laser", "prop_laser_catcher", "prop_weighted_cube", "prop_exploding_barrel", "prop_flare", + "item_crate" + ]; + + public static bool IsAllowedToOverrideWeapon(ReadOnlySpan className) { + foreach (string weapon in OverridableWeapons) + if (stricmp(weapon, className) == 0) + return true; + return false; + } + + public static bool IsAllowedToOverrideEntity(ReadOnlySpan className) { + foreach (string entity in OverridableEntities) + if (stricmp(entity, className) == 0) + return true; + return false; + } +#endif + public class LuaManager { public bool RunScript(ReadOnlySpan file, ReadOnlySpan pathId, bool run, ReadOnlySpan source) { @@ -262,6 +319,28 @@ public bool RunScript(ReadOnlySpan file, ReadOnlySpan pathId, bool r public bool ScriptExists(ReadOnlySpan file, ReadOnlySpan pathId) => get.LuaShared()!.LoadFile(file, pathId, false, true) != null; +#if CLIENT_DLL + public C_BaseEntity? CreateEntity(ReadOnlySpan className) => LuaSENTManager.gSENTManager!.CreateEntity(className); +#else + public IServerNetworkable? CreateEntity(ReadOnlySpan className, bool hasFactory) { + if (hasFactory) { + if (IsAllowedToOverrideWeapon(className)) { + IServerNetworkable? weapon = LuaSWEPManager.gSWEPManager!.CreateEntity(className); + if (weapon != null) + return weapon; + } + if (!IsAllowedToOverrideEntity(className)) + return null; + } + else { + IServerNetworkable? weapon = LuaSWEPManager.gSWEPManager!.CreateEntity(className); + if (weapon != null) + return weapon; + } + return LuaSENTManager.gSENTManager!.CreateEntity(className); + } +#endif + public void Startup() { #if CLIENT_DLL Msg("Clientside Lua startup!\n"); diff --git a/Game.Shared/GarrysMod/LuaEntity.cs b/Game.Shared/GarrysMod/LuaEntity.cs index 68dfd5186..a3dfa3f96 100644 --- a/Game.Shared/GarrysMod/LuaEntity.cs +++ b/Game.Shared/GarrysMod/LuaEntity.cs @@ -57,8 +57,46 @@ public static partial class LuaEntity public static readonly LuaEntityClass LC_Vehicle = new("Vehicle", LuaType.Entity, null, "Entity"); public static readonly LuaEntityClass LC_Weapon = new("Weapon", LuaType.Entity, null, "Entity"); - // todo - static readonly List> RemoveList = []; + static readonly List RemoveList = []; + static bool ProcessingRemoveList; + + public static void RemoveQueuedEntities() { + ProcessingRemoveList = true; + for (int i = 0; i < RemoveList.Count; i++) { + BaseEntity? ent = RemoveList[i].Get(); + if (ent != null) + Util.Remove(ent); + } + RemoveList.Clear(); + ProcessingRemoveList = false; + } + + [LuaMethod] + static int Entity__Remove(ILuaInterface lua) { + if (LuaEnts.IsRendering()) { + lua.ErrorNoHalt("Entity:Remove cannot be called while rendering\n"); + return 0; + } + + BaseEntity ent = Get_Entity(1, false)!; + if (LuaEnts.IsProtectedEntity(ent) || IsQueuedForRemoval(ent)) + return 0; + if (ent.IsMarkedForDeletion()) + return 0; +#if CLIENT_DLL + if (ent.EntIndex() != -1) { + lua.ErrorNoHalt($"Trying to remove server entity {ent.GetClassname()}#{ent.EntIndex()} on client!\n"); + return 0; + } +#endif + if (ent.VPhysicsGetObject() == null || !PhysIsInCallback()) + // TODO! + // if (ent.VPhysicsGetObject() == null || (!PhysIsInCallback() && !ent.GMOD_VPhysicsTest(ent.VPhysicsGetObject(), true))) + ent.AddSolidFlags(SolidFlags.NotSolid); + ent.AddEffects(EntityEffects.NoDraw); + RemoveList.Add(new(ent.GetRefEHandle())); + return 0; + } static bool IsQueuedForRemoval(BaseEntity ent) { foreach (Handle handle in RemoveList) { @@ -109,6 +147,15 @@ static bool IsQueuedForRemoval(BaseEntity ent) { return ent; } + public static BaseCombatWeapon? Get_Weapon(int stackPos, bool allowNull) { + BaseEntity? ent = Get_Entity(stackPos, allowNull); + if (ent != null && ent.IsBaseCombatWeapon()) + return (BaseCombatWeapon)ent; + if (!allowNull) + g_Lua!.Error("Weapon is NULL/Not a Weapon"); + return null; + } + public static void Push_Entity(BaseEntity? ent) { if (g_Lua == null || g_Lua.Global() == null) return; @@ -244,6 +291,440 @@ static int Entity__SetBodyGroups(ILuaInterface lua) { return 0; } +#if GAME_DLL + [LuaMethod] + static int Entity__DeleteOnRemove(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + ent.DeleteOnRemove(Get_Entity(2, false)); + return 0; + } +#endif + + [LuaMethod] + static int Entity__AddEffects(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + ent.AddEffects((EntityEffects)(int)lua.GetNumber(2)); + return 0; + } + + [LuaMethod] + static int Entity__DrawShadow(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + if (lua.GetBool(2)) { + ent.RemoveEffects(EntityEffects.NoShadow); + return 0; + } + ent.AddEffects(EntityEffects.NoShadow); + return 0; + } + + [LuaMethod] + static int Entity__SetMoveType(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + float moveType = (int)lua.GetNumber(2); + if (moveType <= 0.0f) + moveType = 0.0f; + if (11.0f <= moveType) + moveType = 11.0f; + ent.SetMoveType((MoveType)(int)moveType, MoveCollide.Default); + return 0; + } + + [LuaMethod] + static int Entity__SetNotSolid(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + SolidFlags flags; + if (!lua.GetBool(2)) + flags = ent.GetSolidFlags() & ~SolidFlags.NotSolid; + else + flags = ent.GetSolidFlags() | SolidFlags.NotSolid; + ent.CollisionProp().SetSolidFlags(flags); + return 0; + } + + [LuaMethod] + static int Entity__SetTransmitWithParent(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; +#if GAME_DLL + if (lua.GetBool(2)) { + ent.NetworkStateChanged(); + ent.GModFlags |= 1 << 6; // TODO, need an enum + return 0; + } + ent.NetworkStateChanged(); + ent.GModFlags &= ~(1 << 6); +#else + ent.GModFlags = lua.GetBool(2) ? ent.GModFlags | 1 << 6 : ent.GModFlags & ~(1 << 6); +#endif + return 0; + } + + [LuaMethod] + static int Entity__SetParent(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + LuaType type = lua.GetType(2); + if (type != LuaType.Entity && type != LuaType.Nil) + lua.TypeError("Entity", 2); + BaseEntity? parent = UserGet(2); + if (ent == parent) + return 0; +#if CLIENT_DLL + int attachment; + if (lua.GetType(3) == LuaType.Number) { + attachment = (int)lua.GetNumber(3); + if ((uint)(attachment + 1) > 256) + lua.ErrorFromLua("Invalid attachment supplied to Entity.SetParent, must be 0 or above, and less than the attachment count."); + } + else + attachment = 0; + ent.SetParent(parent, attachment); +#else + if (lua.GetType(3) == LuaType.Number) { + int attachment = (int)lua.GetNumber(3); + if ((uint)(attachment + 1) > 256) + lua.ErrorFromLua("Invalid attachment supplied to Entity.SetParent, must be 0 or above, and less than the attachment count."); + ent.SetParent(parent, attachment); + return 0; + } + ent.SetParent(parent, -1); +#endif + return 0; + } + + [LuaMethod] + static int Entity__GetOwner(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseEntity? owner; + if (ent is BaseViewModel viewModel) + owner = viewModel.GetOwner(); + else + owner = ent.GetOwnerEntity(); + Push_Entity(owner); + return 1; + } + + [LuaMethod] + static int Entity__SetOwner(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + LuaType type = lua.GetType(2); + if (type != LuaType.Entity && type != LuaType.Nil) + lua.TypeError("Entity", 2); + ent.SetOwnerEntity(UserGet(2)); + return 0; + } + + [LuaMethod] + static int Entity__SetDTBool(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + bool value = lua.GetBool(3); + int index = (int)lua.GetNumber(2); + if ((uint)index < 32 && ent.GMOD_bool[index] != value) { +#if GAME_DLL + ent.NetworkStateChanged(); +#endif + ent.GMOD_bool[index] = value; + } + return 0; + } + + [LuaMethod] + static int Entity__GetDTBool(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + int index = (int)lua.GetNumber(2); + lua.PushBool(ent.GMOD_bool[(uint)index < 32 ? index : 0]); + return 1; + } + + [LuaMethod] + static int Entity__SetDTFloat(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + float value = (float)lua.GetNumber(3); + int index = (int)lua.GetNumber(2); + if ((uint)index < 32 && ent.GMOD_float[index] != value) { +#if GAME_DLL + ent.NetworkStateChanged(); +#endif + ent.GMOD_float[index] = value; + } + return 0; + } + + [LuaMethod] + static int Entity__GetDTFloat(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + int index = (int)lua.GetNumber(2); + lua.PushNumber(ent.GMOD_float[(uint)index < 32 ? index : 0]); + return 1; + } + + [LuaMethod] + static int Entity__SetDTInt(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + int value = (int)lua.GetNumber(3); + int index = (int)lua.GetNumber(2); + if ((uint)index < 32 && ent.GMOD_int[index] != value) { +#if GAME_DLL + ent.NetworkStateChanged(); +#endif + ent.GMOD_int[index] = value; + } + return 0; + } + + [LuaMethod] + static int Entity__GetDTInt(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + int index = (int)lua.GetNumber(2); + lua.PushNumber(ent.GMOD_int[(uint)index < 32 ? index : 0]); + return 1; + } + + [LuaMethod] + static int Entity__SetDTVector(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + Vector3 value = LuaVector.Get_Vector(3); + int index = (int)lua.GetNumber(2); + if ((uint)index < 32 && ent.GMOD_Vector[index] != value) { +#if GAME_DLL + ent.NetworkStateChanged(); +#endif + ent.GMOD_Vector[index] = value; + } + return 0; + } + + [LuaMethod] + static int Entity__GetDTVector(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + int index = (int)lua.GetNumber(2); + LuaVector.Push_Vector(ent.GMOD_Vector[(uint)index < 32 ? index : 0]); + return 1; + } + + [LuaMethod] + static int Entity__SetDTAngle(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + QAngle value = LuaAngle.Get_Angle(3); + int index = (int)lua.GetNumber(2); + if ((uint)index < 32 && ent.GMOD_QAngle[index] != value) { +#if GAME_DLL + ent.NetworkStateChanged(); +#endif + ent.GMOD_QAngle[index] = value; + } + return 0; + } + + [LuaMethod] + static int Entity__GetDTAngle(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + int index = (int)lua.GetNumber(2); + LuaAngle.Push_Angle(ent.GMOD_QAngle[(uint)index < 32 ? index : 0]); + return 1; + } + + [LuaMethod] + static int Entity__SetDTEntity(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + LuaType type = lua.GetType(3); + if (type != LuaType.Entity && type != LuaType.Nil) + lua.TypeError("Entity", 3); + BaseEntity? value = UserGet(3); + int index = (int)lua.GetNumber(2); + if ((uint)index < 32 && ent.GMOD_EHANDLE[index].Get() != value) { +#if GAME_DLL + ent.NetworkStateChanged(); +#endif + ent.GMOD_EHANDLE[index].Set(value); + } + return 0; + } + + [LuaMethod] + static int Entity__GetDTEntity(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + int index = (int)lua.GetNumber(2); + Push_Entity(ent.GMOD_EHANDLE[(uint)index < 32 ? index : 0].Get()); + return 1; + } + + [LuaMethod] + static int Entity__SetDTString(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + string? value = lua.GetString(3); + switch ((int)lua.GetNumber(2)) { + case 0: +#if GAME_DLL + ent.NetworkStateChanged(); +#endif + strcpy(ent.GMOD_String0, value); + break; + case 1: +#if GAME_DLL + ent.NetworkStateChanged(); +#endif + strcpy(ent.GMOD_String1, value); + break; + case 2: +#if GAME_DLL + ent.NetworkStateChanged(); +#endif + strcpy(ent.GMOD_String2, value); + break; + case 3: +#if GAME_DLL + ent.NetworkStateChanged(); +#endif + strcpy(ent.GMOD_String3, value); + break; + } + return 0; + } + + [LuaMethod] + static int Entity__GetDTString(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + int index = (int)lua.GetNumber(2); + if (index == 1) + lua.PushString(((ReadOnlySpan)ent.GMOD_String1).SliceNullTerminatedString()); + else if (index == 2) + lua.PushString(((ReadOnlySpan)ent.GMOD_String2).SliceNullTerminatedString()); + else if (index == 3) + lua.PushString(((ReadOnlySpan)ent.GMOD_String3).SliceNullTerminatedString()); + else + lua.PushString(((ReadOnlySpan)ent.GMOD_String0).SliceNullTerminatedString()); + return 1; + } + +#if CLIENT_DLL + [LuaMethod] + static int Entity__DrawModel(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + ent.DrawModel((StudioFlags)(int)lua.CheckNumberOpt(2, (int)StudioFlags.Render)); + return 0; + } +#endif + + [LuaMethod] + static int Entity__SetNoDraw(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + if (lua.GetBool(2)) + ent.AddEffects(EntityEffects.NoDraw); + else + ent.RemoveEffects(EntityEffects.NoDraw); + return 0; + } + + [LuaMethod] + static int Entity__IsPlayer(ILuaInterface lua) { + lua.PushBool(false); + return 1; + } + + [LuaMethod] + static int Entity__IsNPC(ILuaInterface lua) { + lua.PushBool(false); + return 1; + } + + [LuaMethod] + static int Entity__IsScripted(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + ReadOnlySpan name = ent.GetLuaScriptName(); + lua.PushBool(!name.IsEmpty && name[0] != '\0'); + return 1; + } + + [LuaMethod] + static int Entity__GetSequence(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating != null && !ent.IsMarkedForDeletion()) { + lua.PushNumber(animating.GetSequence()); + return 1; + } + lua.PushNumber(0); + return 1; + } + + [LuaMethod] + static int Entity__GetCycle(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating != null && !ent.IsMarkedForDeletion()) { + lua.PushNumber((float)animating.GetCycle()); + return 1; + } + lua.PushNumber(0); + return 1; + } + + [LuaMethod] + static int Entity__GetPlaybackRate(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating != null && !ent.IsMarkedForDeletion()) { + lua.PushNumber(animating.GetPlaybackRate()); + return 1; + } + lua.PushNumber(0); + return 1; + } + + [LuaMethod] + static int Entity__GetSequenceActivity(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating != null && !ent.IsMarkedForDeletion()) { + lua.PushNumber((int)animating.GetSequenceActivity((int)lua.GetNumber(2))); + return 1; + } + lua.PushNumber(0); + return 1; + } + + [LuaMethod] + static int Entity__GetSequenceGroundSpeed(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating != null && !ent.IsMarkedForDeletion()) { + int sequence = (int)lua.GetNumber(2); + lua.PushNumber((float)animating.GetSequenceGroundSpeed(animating.GetModelPtr(), sequence)); + return 1; + } + lua.PushNumber(0); + return 1; + } + + [LuaMethod] + static int Entity__GetNumBodyGroups(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating != null && !ent.IsMarkedForDeletion()) { + lua.PushNumber(animating.GetNumBodyGroups()); + return 1; + } + lua.PushNumber(0); + return 1; + } + + [LuaMethod] + static int Entity__SetBodygroup(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating == null || IsEntityRemoving(ent, false)) + return 0; + + int value = 0; + if ((int)lua.GetNumber(3) > 0) + value = (int)lua.GetNumber(3); + int group = 0; + if ((int)lua.GetNumber(2) > 0) + group = (int)lua.GetNumber(2); + animating.SetBodygroup(group, value); + return 0; + } + [LuaMethod] static int Entity__LookupAttachment(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; @@ -402,6 +883,30 @@ static int Entity__SetAngles(ILuaInterface lua) { return 0; } + [LuaMethod] + static int Entity__SetHealth(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + int health = (int)lua.GetNumber(2); +#if CLIENT_DLL + ent.SetHealth(health); +#else + if (ent.Health != health) { + ent.NetworkStateChanged(); + ent.SetHealth(health); + } +#endif + return 0; + } + +#if GAME_DLL + [LuaMethod] + static int Entity__SetMaxHealth(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + ent.SetMaxHealth((int)lua.GetNumber(2)); + return 0; + } +#endif + [LuaMethod] static int Entity__SetSkin(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; @@ -529,6 +1034,67 @@ static int Entity__GetVelocity(ILuaInterface lua) { return 1; } + [LuaMethod] + static int Entity__SequenceDuration(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating == null) + return 0; + + if (lua.GetType(2) == LuaType.Number) { + lua.PushNumber((float)animating.SequenceDuration((int)lua.GetNumber(2))); + return 1; + } + + lua.PushNumber((float)animating.SequenceDuration(animating.GetModelPtr(), animating.GetSequence())); + return 1; + } + + [LuaMethod] + static int Entity__SetSequence(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating == null || IsQueuedForRemoval(ent) || ent.IsMarkedForDeletion()) + return 0; + + int sequence; + if (lua.GetType(2) == LuaType.Number) + sequence = (int)lua.GetNumber(2); + else + sequence = animating.LookupSequence(lua.GetString(2)); + + animating.SetSequence(sequence); + lua.PushNumber((float)animating.SequenceDuration(animating.GetModelPtr(), sequence)); + return 1; + } + + [LuaMethod] + static int Entity__SetCycle(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating == null || IsQueuedForRemoval(ent) || ent.IsMarkedForDeletion()) + return 0; + + float cycle = (float)lua.GetNumber(2); +#if GAME_DLL + if (!float.IsFinite(cycle)) + cycle = 0.0f; +#endif + animating.SetCycle(cycle); + return 0; + } + + [LuaMethod] + static int Entity__GetColor4Part(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + Color color = ent.ColorRender; + lua.PushNumber(color.R); + lua.PushNumber(color.G); + lua.PushNumber(color.B); + lua.PushNumber(color.A); + return 4; + } + [LuaMethod] static int Entity__LookupSequence(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; diff --git a/Game.Shared/GarrysMod/LuaEnts.cs b/Game.Shared/GarrysMod/LuaEnts.cs index 4ebb39f9f..730b925f9 100644 --- a/Game.Shared/GarrysMod/LuaEnts.cs +++ b/Game.Shared/GarrysMod/LuaEnts.cs @@ -55,14 +55,14 @@ public static bool IsProtectedEntity(BaseEntity ent) { return IsProtectedClass(ent.GetClassname()); } + // todo: render depth counter + public static bool IsRendering() => false; + #if CLIENT_DLL // todo: CreateClientProp // todo: CreateClientRope // todo: CreateClientside #else - // todo: render depth counter - static bool IsRendering() => false; - [LuaFunction] static int Create(ILuaInterface lua) { if (IsRendering()) { diff --git a/Game.Shared/GarrysMod/LuaGameSystem.cs b/Game.Shared/GarrysMod/LuaGameSystem.cs index f1e5cc5fa..381fcd197 100644 --- a/Game.Shared/GarrysMod/LuaGameSystem.cs +++ b/Game.Shared/GarrysMod/LuaGameSystem.cs @@ -44,7 +44,7 @@ public override void LevelInitPreEntity() { } public override void Update(double frametime) { // RemoveQueuedRenderTargets(); - // RemoveQueuedEntities(); + LuaEntity.RemoveQueuedEntities(); // RunMapCleanupIfNeeded(); if (g_Lua == null || GarrysMod.g_LuaManager == null || gGM == null) return; @@ -72,7 +72,7 @@ public override void FrameUpdatePreEntityThink() { } garrysmod.Think(); // RemoveQueuedRecipientFilters(); - // RemoveQueuedEntities(); + LuaEntity.RemoveQueuedEntities(); // RunMapCleanupIfNeeded(); if (gpGlobals.TickCount != LastTick) { LastTick = gpGlobals.TickCount; diff --git a/Game.Shared/GarrysMod/LuaGamemode.cs b/Game.Shared/GarrysMod/LuaGamemode.cs index 369783a29..176d0227c 100644 --- a/Game.Shared/GarrysMod/LuaGamemode.cs +++ b/Game.Shared/GarrysMod/LuaGamemode.cs @@ -169,7 +169,7 @@ public void SetGamemode(string name, bool initialize) { if (initialize) { LuaSWEPManager.gSWEPManager!.LoadScripts(); - // todo: LuaSENTManager.LoadScripts(); + LuaSENTManager.gSENTManager!.LoadScripts(); // todo: gEffectManager.LoadScripts(); Call("CreateTeams"); Call("PreGamemodeLoaded"); diff --git a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs index ff2c9c548..9d66c8789 100644 --- a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs +++ b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs @@ -1,6 +1,7 @@ #if CLIENT_DLL || GAME_DLL using Source; using Source.Common.Commands; +using Source.Common.Mathematics; using Source.Common.GarrysMod; using Source.Common.GarrysMod.Lua; #if CLIENT_DLL @@ -100,6 +101,22 @@ public static void RGBtoHSV(int r, int g, int b, out float h, out float s, out f v = maxInt / 255.0f; } + [LuaGlobal] + static int LocalToWorld(ILuaInterface lua) { + Vector3 localPos = LuaVector.Get_Vector(1); + QAngle localAng = LuaAngle.Get_Angle(2); + Vector3 originPos = LuaVector.Get_Vector(3); + QAngle originAng = LuaAngle.Get_Angle(4); + + MathLib.AngleMatrix(originAng, originPos, out Matrix3x4 matrix); + MathLib.VectorTransform(localPos, matrix, out Vector3 worldPos); + QAngle worldAng = MathLib.TransformAnglesToWorldSpace(localAng, matrix); + + LuaVector.Push_Vector(worldPos); + LuaAngle.Push_Angle(worldAng); + return 2; + } + [LuaGlobal] static int HSVToColor(ILuaInterface lua) { float value = (float)lua.CheckNumber(3); diff --git a/Game.Client/GarrysMod/LuaMaterial.cs b/Game.Shared/GarrysMod/LuaMaterial.cs similarity index 99% rename from Game.Client/GarrysMod/LuaMaterial.cs rename to Game.Shared/GarrysMod/LuaMaterial.cs index 5c5119767..1cc851b1f 100644 --- a/Game.Client/GarrysMod/LuaMaterial.cs +++ b/Game.Shared/GarrysMod/LuaMaterial.cs @@ -1,3 +1,4 @@ +#if CLIENT_DLL || GAME_DLL using Source; using Source.Common.Formats.Keyvalues; using Source.Common.GarrysMod.Lua; @@ -7,7 +8,11 @@ using System.Numerics; using System.Runtime.InteropServices; +#if CLIENT_DLL namespace Game.Client.GarrysMod; +#else +namespace Game.Server.GarrysMod; +#endif public static partial class LuaMaterial { @@ -620,3 +625,4 @@ static int CreateMaterial(ILuaInterface lua) { return 1; } } +#endif diff --git a/Game.Shared/GarrysMod/LuaPlayer.cs b/Game.Shared/GarrysMod/LuaPlayer.cs index 284fe6236..78eead4fc 100644 --- a/Game.Shared/GarrysMod/LuaPlayer.cs +++ b/Game.Shared/GarrysMod/LuaPlayer.cs @@ -2,6 +2,7 @@ #if CLIENT_DLL || GAME_DLL using Game.Shared; +using Source.Common.Commands; using Source.Common.GarrysMod.Lua; using Source.Common.Mathematics; @@ -91,6 +92,50 @@ static int Player__ConCommand(ILuaInterface lua) { #endif } + [LuaMethod] + static int Player__IsPlayer(ILuaInterface lua) { + lua.PushBool(true); + return 1; + } + + [LuaMethod] + static int Player__SteamID(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + lua.PushString(player.GetNetworkIDString()); + return 1; + } + + [LuaMethod] + static int Player__SteamID64(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + if (!player.GetSteamID(out Steamworks.CSteamID steamID)) { + lua.PushString("0"); + return 1; + } + lua.PushString(steamID.m_SteamID.ToString()); + return 1; + } + + [LuaMethod] + static int Player__AccountID(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + if (!player.GetSteamID(out Steamworks.CSteamID steamID)) { + lua.PushNumber(0); + return 1; + } + lua.PushNumber(steamID.GetAccountID().m_AccountID); + return 1; + } + +#if GAME_DLL + [LuaMethod] + static int Player__OwnerSteamID64(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + lua.PushString(engine.GMOD_GetPlayerOwnerSteamID(player.Edict()).m_SteamID.ToString()); + return 1; + } +#endif + [LuaMethod] static int Player__KeyDown(ILuaInterface lua) { BasePlayer player = Get_Player(1, false)!; @@ -351,6 +396,279 @@ static int Player__GetShootPos(ILuaInterface lua) { return 1; } + [LuaMethod] + static int Player__SetRunSpeed(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + player.SetSprintSpeed((float)lua.GetNumber(2)); + return 0; + } + + [LuaMethod] + static int Player__SetWalkSpeed(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + player.SetWalkSpeed((float)lua.GetNumber(2)); + return 0; + } + + [LuaMethod] + static int Player__SetSlowWalkSpeed(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + player.SetSlowWalkSpeed((float)lua.GetNumber(2)); + return 0; + } + + [LuaMethod] + static int Player__SetCrouchedWalkSpeed(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + player.SetCrouchedWalkSpeed((float)lua.GetNumber(2)); + return 0; + } + + [LuaMethod] + static int Player__SetDuckSpeed(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + player.SetDuckSpeed((float)lua.GetNumber(2)); + return 0; + } + + [LuaMethod] + static int Player__SetUnDuckSpeed(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + player.SetUnDuckSpeed((float)lua.GetNumber(2)); + return 0; + } + + [LuaMethod] + static int Player__SetJumpPower(ILuaInterface lua) { + GMOD_Player player = (GMOD_Player)Get_Player(1, false)!; + float power = (float)lua.GetNumber(2); + if (player.JumpPower != power) { +#if GAME_DLL + player.NetworkStateChanged(); +#endif + player.JumpPower = power; + } + return 0; + } + + [LuaMethod] + static int Player__SetAvoidPlayers(ILuaInterface lua) { + GMOD_Player player = (GMOD_Player)Get_Player(1, false)!; + int flags = lua.GetBool(2) ? player.GModPlayerFlags | 8 : player.GModPlayerFlags & ~8; +#if GAME_DLL + if (player.GModPlayerFlags != flags) + player.NetworkStateChanged(); +#endif + player.GModPlayerFlags = flags; + return 0; + } + + [LuaMethod] + static int Player__SetNoCollideWithTeammates(ILuaInterface lua) { + GMOD_Player player = (GMOD_Player)Get_Player(1, false)!; + int flags = lua.GetBool(2) ? player.GModPlayerFlags | 2 : player.GModPlayerFlags & ~2; +#if GAME_DLL + if (player.GModPlayerFlags != flags) + player.NetworkStateChanged(); +#endif + player.GModPlayerFlags = flags; + return 0; + } + +#if GAME_DLL + [LuaMethod] + static int Player__SetArmor(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + player.SetArmorValue((int)lua.GetNumber(2)); + return 0; + } + + [LuaMethod] + static int Player__SetMaxArmor(ILuaInterface lua) { + GMOD_Player player = (GMOD_Player)Get_Player(1, false)!; + int armor = (int)lua.GetNumber(2); + if (player.MaxArmor != armor) { + player.NetworkStateChanged(); + player.MaxArmor = armor; + } + return 0; + } + + [LuaMethod] + static int Player__ShouldDropWeapon(ILuaInterface lua) { + GMOD_Player player = (GMOD_Player)Get_Player(1, false)!; + player.ShouldDropWeapon = lua.GetBool(2); + return 0; + } +#endif + + [LuaMethod] + static int Player__GetInfo(ILuaInterface lua) { + if (!LuaConVar.IsAllowedToGetConvarInfo(lua.GetString(2))) + return 0; +#if CLIENT_DLL + ConVar? convar = cvar.FindVar(lua.GetString(2)); + if (convar == null) + return 0; + lua.PushString(convar.GetString()); + return 1; +#else + BasePlayer player = Get_Player(1, false)!; + if (player.IsFakeClient()) { + lua.PushString(""); + return 1; + } + lua.PushString(player.GetInfo(lua.GetString(2))); + return 1; +#endif + } + + [LuaMethod] + static int Player__GetInfoNum(ILuaInterface lua) { + if (!LuaConVar.IsAllowedToGetConvarInfo(lua.GetString(2))) + return 0; + float fallback = (float)lua.GetNumber(3); +#if CLIENT_DLL + ConVar? convar = cvar.FindVar(lua.GetString(2)); + if (convar != null) + fallback = convar.GetFloat(); + lua.PushNumber(fallback); + return 1; +#else + BasePlayer player = Get_Player(1, false)!; + if (player.IsFakeClient()) { + lua.PushNumber(0); + return 1; + } + lua.PushNumber(player.GetInfoNum(lua.GetString(2), fallback)); + return 1; +#endif + } + +#if GAME_DLL + [LuaMethod] + static int Player__RemoveAllAmmo(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + player.RemoveAllAmmo(); + return 0; + } + + [LuaMethod] + static int Player__SelectWeapon(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + if (lua.GetType(2) == LuaType.Entity) { + BaseCombatWeapon? weapon = LuaEntity.Get_Weapon(2, true); + if (weapon != null) { + player.SelectItem(weapon.Classname ?? "", 0); + return 0; + } + } + player.SelectItem(lua.GetString(2), 0); + return 0; + } + + [LuaMethod] + static int Player__Give(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + bool noAmmo = false; + if (lua.GetType(3) != LuaType.Nil) { + noAmmo = lua.GetBool(3); + if (noAmmo && player.MyCombatCharacterPointer() != null) + player.MyCombatCharacterPointer()!.NoAmmo = true; + } + BaseEntity? ent = player.GiveNamedItem(lua.GetString(2), 0); + if (noAmmo && player.MyCombatCharacterPointer() != null) { + player.MyCombatCharacterPointer()!.NoAmmo = false; + if (ent is BaseCombatWeapon weapon) { + int clip1 = weapon.iClip1 >= 0 ? 0 : weapon.iClip1; + if (weapon.iClip1 != clip1) + weapon.iClip1 = clip1; + int clip2 = weapon.iClip2 >= 0 ? 0 : weapon.iClip2; + if (weapon.iClip2 != clip2) + weapon.iClip2 = clip2; + } + } + LuaEntity.Push_Entity(ent); + return 1; + } + + [LuaMethod] + static int Player__GiveAmmo(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + int count = (int)lua.GetNumber(2); + if (count < 1) + return 0; + if (lua.GetType(3) == LuaType.String) { + bool suppress = lua.GetBool(4); + int ammoIndex = GetAmmoDef().Index(lua.GetString(3)); + lua.PushNumber(player.GiveAmmo(count, ammoIndex, suppress)); + } + else { + bool suppress = lua.GetBool(4); + lua.PushNumber(player.GiveAmmo(count, (int)lua.GetNumber(3), suppress)); + } + return 1; + } +#endif + + [LuaMethod] + static int Player__GetViewModel(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + int index = 0; + if (lua.GetType(2) == LuaType.Number) { + int value = (int)lua.GetNumber(2); + if (value > -1) { + if (value > 2) + value = 2; + index = value; + } + } + LuaEntity.Push_Entity(player.GetViewModel(index, true)); + return 1; + } + + [LuaMethod] + static int Player__GetHands(ILuaInterface lua) { + GMOD_Player player = (GMOD_Player)Get_Player(1, false)!; + LuaEntity.Push_Entity(player.Hands.Get()); + return 1; + } + + [LuaMethod] + static int Player__SetHands(ILuaInterface lua) { + GMOD_Player player = (GMOD_Player)Get_Player(1, false)!; + BaseEntity? hands = LuaEntity.Get_Entity(2, false); +#if GAME_DLL + if (player.Hands.Get() != hands) + player.NetworkStateChanged(); +#endif + player.Hands.Set(hands); + return 0; + } + + [LuaMethod] + static int Player__GetPlayerColor(ILuaInterface lua) { + GMOD_Player player = (GMOD_Player)Get_Player(1, false)!; + LuaVector.Push_Vector(player.GetPlayerColor()); + return 1; + } + + [LuaMethod] + static int Player__SetPlayerColor(ILuaInterface lua) { + GMOD_Player player = (GMOD_Player)Get_Player(1, false)!; + Vector3 color = LuaVector.Get_Vector(2); + player.SetPlayerColor(color); + return 0; + } + + [LuaMethod] + static int Player__SetWeaponColor(ILuaInterface lua) { + GMOD_Player player = (GMOD_Player)Get_Player(1, false)!; + Vector3 color = LuaVector.Get_Vector(2); + player.SetWeaponColor(color); + return 0; + } + [LuaFunction] static int GetByID(ILuaInterface lua) { BasePlayer? player = Util.PlayerByIndex((int)g_Lua!.CheckNumber(1)); diff --git a/Game.Shared/GarrysMod/LuaSENTManager.cs b/Game.Shared/GarrysMod/LuaSENTManager.cs new file mode 100644 index 000000000..b8d441179 --- /dev/null +++ b/Game.Shared/GarrysMod/LuaSENTManager.cs @@ -0,0 +1,184 @@ +#if CLIENT_DLL || GAME_DLL +using Source; +using Source.Common; +using Source.Common.GarrysMod; +using Source.Common.GarrysMod.Lua; + +using static Game.Client.GarrysMod.GarrysMod; + +#if CLIENT_DLL +namespace Game.Client.GarrysMod; +#else +namespace Game.Server.GarrysMod; +#endif + +public class LuaSENTManager +{ + public static LuaSENTManager? gSENTManager = new(); + + public LuaSENTManager() => gSENTManager = this; + + static void GetSENTsFunction(ReadOnlySpan name, LuaObject func) { + LuaObject scriptedEnts = new(); + g_Lua!.Global().GetMember("scripted_ents", scriptedEnts); + if (!scriptedEnts.isTable()) + Warning("'scripted_ents' library is not a table. Make sure your addons are not overriding the 'scripted_ents' global variable.\n"); + else { + scriptedEnts.GetMember(name, func); + if (!func.isFunction()) + Warning($"scripted_ents.{name} is not a function. Make sure your addons are not overriding it.\n"); + } + scriptedEnts.UnReference(); + } + + public void LoadScript(ReadOnlySpan scriptName) { + if (g_LuaManager == null || g_Lua == null || g_Lua.Global() == null) + return; + + Span nameBuffer = stackalloc char[260]; + strcpy(nameBuffer, scriptName); + string name = new string(((ReadOnlySpan)nameBuffer).SliceNullTerminatedString()).ToLowerInvariant(); + + string path; + if (name.Contains(".lua", StringComparison.OrdinalIgnoreCase)) { + path = $"entities/{name}"; + Span stripped = stackalloc char[260]; + name.AsSpan().StripExtension(stripped); + name = new string(((ReadOnlySpan)stripped).SliceNullTerminatedString()); + } + else { +#if CLIENT_DLL + path = $"entities/{name}/cl_init.lua"; +#else + path = $"entities/{name}/init.lua"; +#endif + if (!g_LuaManager.ScriptExists(path, LuaPathID)) + path = $"entities/{name}/shared.lua"; + } + + if (!g_LuaManager.ScriptExists(path, LuaPathID)) + return; + + LuaTable ent = new("ENT", 0); + ent.SetMember("Folder", $"entities/{name}"); + g_LuaManager.RunScript(path, LuaPathID, true, "!ENT"); + + if (!ent.MemberIsNil("Base") || !ent.MemberIsNil("Type")) { + LuaObject register = new(); + GetSENTsFunction("Register", register); + if (register.isFunction()) { + register.Push(); + ent.Push(); + g_Lua.PushString(name); + g_Lua.CallInternalNoReturns(2); + g_Lua.Global().SetMemberNil("ENT"); + } + register.UnReference(); + } + else + g_Lua.ErrorNoHalt($"Refusing to load {name} because it is missing Type and Base keys!\n"); + + ent.UnReference(); + } + + public void ReloadSpecific(ReadOnlySpan name) => LoadScript(name); + + public void LoadScripts() { + List scripts = []; + get.LuaShared()!.FindScripts("entities/*", LuaPathID, scripts); + foreach (LuaFindResult script in scripts) + LoadScript(script.FileName); + + LuaObject onLoaded = new(); + GetSENTsFunction("OnLoaded", onLoaded); + if (onLoaded.isFunction()) { + onLoaded.Push(); + g_Lua!.CallInternalNoReturns(0); + } + onLoaded.UnReference(); + } + +#if CLIENT_DLL + public C_BaseEntity? CreateEntity(ReadOnlySpan name) { +#else + public IServerNetworkable? CreateEntity(ReadOnlySpan name) { +#endif + if (IsSacredEntity(name) || g_Lua == null || g_Lua.Global() == null) + return null; + + LuaObject get = new(); + GetSENTsFunction("Get", get); + if (!get.isFunction()) { + get.UnReference(); + return null; + } + + get.Push(); + g_Lua.PushString(name); +#if CLIENT_DLL + C_BaseEntity? ent = null; +#else + IServerNetworkable? ent = null; +#endif + LuaObject sent = new(); + if (g_Lua.CallInternalGet(1, sent) && sent.isTable()) { + string? type = sent.GetMemberStr("Type", null); + if (type == null) + Warning($"Error: Tried to make a SENT ({name}) but it didn't have a 'Type' key!\n"); + else { +#if CLIENT_DLL + if (stricmp(type, "anim") != 0 && stricmp(type, "vehicle") != 0) + Warning($"Error: Tried to make a SENT ({name}) but the 'Type' ({type}) was invalid!\n"); + else { + ent = GetClassMap().CreateEntity("sent_anim"); + if (ent == null) + Warning($"Error: Couldn't make SENT ({name}) (?!?)\n"); + else { + if (ent.HasLuaTable()) + Warning("CREATING ENTITY - ALREADY HAS A LUA TABLE! AND IT SHOULDN'T!\n"); + ent.InitializeAsClientEntity(null, Source.Common.Engine.RenderGroup.TwoPass); + ent.UpdatePartitionListEntry(); + ent.CollisionProp().UpdatePartition(); + ent.SetBlocksLOS(false); + ent.CreateShadow(); + ent.UpdateVisibility(); + ent.InitializeScriptedEntity(name); + } + } +#else + ReadOnlySpan className = null; + if (stricmp(type, "anim") == 0 || stricmp(type, "vehicle") == 0) + className = "sent_anim"; + else if (stricmp(type, "ai") == 0) + className = "sent_ai"; + else if (stricmp(type, "point") == 0) + className = "sent_point"; + else if (stricmp(type, "filter") == 0) + className = "sent_filter"; + else if (stricmp(type, "brush") == 0) + className = "sent_brush"; + else if (stricmp(type, "nextbot") == 0) + className = "sent_nextbot"; + else + Warning($"Error: Tried to make a SENT ({name}) but the 'Type' ({type}) was invalid!\n"); + + if (!className.IsEmpty) { + ent = EntityFactoryDictionary().Create(className); + if (ent == null) + Warning($"Error: Couldn't make SENT ({name}) (?!?)\n"); + else { + if (((BaseEntity)ent.GetBaseEntity()!).HasLuaTable()) + Warning("CREATING ENTITY - ALREADY HAS A LUA TABLE! AND IT SHOULDN'T!\n"); + ((BaseEntity)ent.GetBaseEntity()!).InitializeScriptedEntity(name); + } + } +#endif + } + } + + sent.UnReference(); + get.UnReference(); + return ent; + } +} +#endif diff --git a/Game.Shared/GarrysMod/LuaSWEPManager.cs b/Game.Shared/GarrysMod/LuaSWEPManager.cs index fb8c48921..0b193adf9 100644 --- a/Game.Shared/GarrysMod/LuaSWEPManager.cs +++ b/Game.Shared/GarrysMod/LuaSWEPManager.cs @@ -1,5 +1,6 @@ #if CLIENT_DLL || GAME_DLL using Source; +using Source.Common; using Source.Common.GarrysMod; using Source.Common.GarrysMod.Lua; @@ -95,6 +96,36 @@ public void LoadScript(ReadOnlySpan scriptName) { swep.UnReference(); } +#if GAME_DLL + public IServerNetworkable? CreateEntity(ReadOnlySpan name) { + if (IsSacredEntity(name) || g_Lua == null) + return null; + + LuaObject get = new(); + GetWeaponFunction("Get", get); + if (!get.isFunction()) { + get.UnReference(); + return null; + } + + IServerNetworkable? ent = null; + LuaObject swep = new(); + get.Push(); + g_Lua.PushString(name); + if (!g_Lua.CallInternalGet(1, swep)) + Warning($"Error creating scripted weapon {name} (errored?)\n"); + else if (swep.isTable()) { + ent = EntityFactoryDictionary().Create("weapon_swep"); + if (ent != null) + ((BaseEntity)ent.GetBaseEntity()!).InitializeScriptedEntity(name); + } + + swep.UnReference(); + get.UnReference(); + return ent; + } +#endif + public void ReloadSpecific(ReadOnlySpan name) => LoadScript(name); public void LoadScripts() { diff --git a/Game.Client/GarrysMod/LuaTexture.cs b/Game.Shared/GarrysMod/LuaTexture.cs similarity index 88% rename from Game.Client/GarrysMod/LuaTexture.cs rename to Game.Shared/GarrysMod/LuaTexture.cs index 1920b6dcc..eca1e392b 100644 --- a/Game.Client/GarrysMod/LuaTexture.cs +++ b/Game.Shared/GarrysMod/LuaTexture.cs @@ -1,7 +1,12 @@ +#if CLIENT_DLL || GAME_DLL using Source.Common.GarrysMod.Lua; using Source.Common.MaterialSystem; +#if CLIENT_DLL namespace Game.Client.GarrysMod; +#else +namespace Game.Server.GarrysMod; +#endif public static partial class LuaTexture { @@ -22,3 +27,4 @@ public static void Push(ITexture? texture) { [LuaMethod] static string ITexture__GetName(ITexture texture) => new(texture.GetName()); } +#endif diff --git a/Game.Shared/GarrysMod/LuaUtil.cs b/Game.Shared/GarrysMod/LuaUtil.cs index 68560c9b4..0a3fdb98d 100644 --- a/Game.Shared/GarrysMod/LuaUtil.cs +++ b/Game.Shared/GarrysMod/LuaUtil.cs @@ -16,6 +16,7 @@ #endif using System.Numerics; +using System.Runtime.CompilerServices; #if CLIENT_DLL namespace Game.Client.GarrysMod; @@ -95,6 +96,53 @@ public static bool UTIL_IsValidRagdollModel(ReadOnlySpan name) { return collide != null && collide.SolidCount > 1; } + [LuaFunction] + static int AimVector(ILuaInterface lua) { + QAngle angles = LuaAngle.Get_Angle(1); + float fov = (float)lua.GetNumber(2); + float x = (float)lua.GetNumber(3); + float y = (float)lua.GetNumber(4); + float w = (float)lua.GetNumber(5); + float h = (float)lua.GetNumber(6); + float halfW = w * 0.5f; + float right = x - halfW; + float up = h * 0.5f - y; + float forward = halfW / MathF.Tan(fov * (MathF.PI / 360.0f)); + MathLib.AngleVectors(angles, out Vector3 fwd, out Vector3 rt, out Vector3 upv); + Vector3 dir = fwd * forward + rt * right + upv * up; + MathLib.VectorNormalize(ref dir); + LuaVector.Push_Vector(dir); + return 1; + } + + [LuaFunction] + static int IntersectRayWithOBB(ILuaInterface lua) { + Vector3 rayStart = LuaVector.Get_Vector(1); + Vector3 rayDelta = LuaVector.Get_Vector(2); + Vector3 boxOrigin = LuaVector.Get_Vector(3); + QAngle boxAngles = LuaAngle.Get_Angle(4); + Vector3 boxMins = LuaVector.Get_Vector(5); + Vector3 boxMaxs = LuaVector.Get_Vector(6); + + MathLib.AngleMatrix(boxAngles, out Matrix3x4 worldToBox); + MathLib.MatrixInvert(worldToBox, out worldToBox); + + MathLib.VectorRotate(rayStart - boxOrigin, worldToBox, out Vector3 localStart); + MathLib.VectorRotate(rayStart + rayDelta - boxOrigin, worldToBox, out Vector3 localEnd); + + Ray ray = default; + ray.Init(boxOrigin + localStart, boxOrigin + localEnd); + + GameTrace trace = new(); + if (!CollisionUtils.IntersectRayWithBox(in ray, boxOrigin + boxMins, boxOrigin + boxMaxs, 0.0f, ref trace, ref Unsafe.NullRef())) + return 0; + + LuaVector.Push_Vector(rayStart + rayDelta * trace.Fraction); + LuaVector.Push_Vector(trace.Plane.Normal); + lua.PushNumber(trace.Fraction); + return 3; + } + [LuaFunction] static int IsValidRagdoll(ILuaInterface lua) { string? name = lua.CheckString(1); diff --git a/Game.Shared/GarrysMod/LuaWeapon.cs b/Game.Shared/GarrysMod/LuaWeapon.cs new file mode 100644 index 000000000..a7e1157e7 --- /dev/null +++ b/Game.Shared/GarrysMod/LuaWeapon.cs @@ -0,0 +1,323 @@ +#if CLIENT_DLL || GAME_DLL +using Game.Shared; + +using Source.Common.GarrysMod.Lua; + +#if CLIENT_DLL +namespace Game.Client.GarrysMod; +#else +namespace Game.Server.GarrysMod; +#endif + +public static partial class LuaWeapon +{ + [LuaClass] + static readonly LuaEntityClass LC_Weapon = LuaEntity.LC_Weapon; + + [LuaMethod] + static int Weapon__IsScripted(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + ReadOnlySpan name = weapon.GetLuaScriptName(); + lua.PushBool(!name.IsEmpty && name[0] != '\0'); + return 1; + } + + [LuaMethod] + static int Weapon__IsWeapon(ILuaInterface lua) { + lua.PushBool(true); + return 1; + } + + [LuaMethod] + static int Weapon__AllowsAutoSwitchFrom(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushBool(weapon.AllowsAutoSwitchFrom()); + return 1; + } + + [LuaMethod] + static int Weapon__AllowsAutoSwitchTo(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushBool(weapon.AllowsAutoSwitchTo()); + return 1; + } + + [LuaMethod] + static int Weapon__Clip1(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushNumber(weapon.iClip1); + return 1; + } + + [LuaMethod] + static int Weapon__Clip2(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushNumber(weapon.iClip2); + return 1; + } + + [LuaMethod] + static int Weapon__SetClip1(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + weapon.SetDropped(); + int clip = (int)lua.CheckNumber(2); + if (weapon.iClip1 != clip) { +#if GAME_DLL + weapon.NetworkStateChanged(); +#endif + weapon.iClip1 = clip; + } + return 0; + } + + [LuaMethod] + static int Weapon__SetClip2(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + weapon.SetDropped(); + int clip = (int)lua.CheckNumber(2); + if (weapon.iClip2 != clip) { +#if GAME_DLL + weapon.NetworkStateChanged(); +#endif + weapon.iClip2 = clip; + } + return 0; + } + + [LuaMethod] + static int Weapon__DefaultReload(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + Activity act = (Activity)(int)lua.CheckNumber(2); + bool ret = weapon.DefaultReload(weapon.GetMaxClip1(), weapon.GetMaxClip2(), act); +#if GAME_DLL + BaseCombatCharacter? owner = weapon.GetOwner(); + if (ret && owner != null && owner.IsPlayer()) + ((HL2MP_Player)owner).DoAnimationEvent(PlayerAnimEvent.Reload, 0, true); +#endif + lua.PushBool(ret); + return 1; + } + + [LuaMethod] + static int Weapon__GetActivity(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushNumber((int)weapon.GetActivity()); + return 1; + } + + [LuaMethod] + static int Weapon__SetActivity(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + weapon.SetActivity((Activity)(int)lua.CheckNumber(2)); + return 0; + } + + [LuaMethod] + static int Weapon__GetHoldType(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushString(weapon.GetHoldType()); + return 1; + } + + [LuaMethod] + static int Weapon__SetHoldType(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + weapon.SetHoldType(lua.CheckString(2)); + return 0; + } + + [LuaMethod] + static int Weapon__GetMaxClip1(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushNumber(weapon.GetMaxClip1()); + return 1; + } + + [LuaMethod] + static int Weapon__GetMaxClip2(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushNumber(weapon.GetMaxClip2()); + return 1; + } + + [LuaMethod] + static int Weapon__GetNextPrimaryFire(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushNumber(weapon.NextPrimaryAttack); + return 1; + } + + [LuaMethod] + static int Weapon__GetNextSecondaryFire(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushNumber(weapon.NextSecondaryAttack); + return 1; + } + + [LuaMethod] + static int Weapon__SetNextPrimaryFire(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + double time = lua.CheckNumber(2); + if (weapon.NextPrimaryAttack != time) { +#if GAME_DLL + weapon.NetworkStateChanged(); +#endif + weapon.NextPrimaryAttack = time; + } + return 0; + } + + [LuaMethod] + static int Weapon__SetNextSecondaryFire(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + double time = lua.CheckNumber(2); + if (weapon.NextSecondaryAttack != time) { +#if GAME_DLL + weapon.NetworkStateChanged(); +#endif + weapon.NextSecondaryAttack = time; + } + return 0; + } + + [LuaMethod] + static int Weapon__GetPrimaryAmmoType(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushNumber(weapon.GetPrimaryAmmoType()); + return 1; + } + + [LuaMethod] + static int Weapon__GetSecondaryAmmoType(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushNumber(weapon.GetSecondaryAmmoType()); + return 1; + } + + [LuaMethod] + static int Weapon__GetPrintName(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushString(weapon.GetPrintName()); + return 1; + } + + [LuaMethod] + static int Weapon__GetSlot(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushNumber(weapon.GetSlot()); + return 1; + } + + [LuaMethod] + static int Weapon__GetSlotPos(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushNumber(weapon.GetPosition()); + return 1; + } + + [LuaMethod] + static int Weapon__GetWeaponViewModel(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushString(weapon.GetViewModel(0)); + return 1; + } + + [LuaMethod] + static int Weapon__GetWeaponWorldModel(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushString(weapon.GetWorldModel()); + return 1; + } + + [LuaMethod] + static int Weapon__GetWeight(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushNumber(weapon.GetWeight()); + return 1; + } + + [LuaMethod] + static int Weapon__HasAmmo(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushBool(weapon.HasAmmo()); + return 1; + } + + [LuaMethod] + static int Weapon__IsWeaponVisible(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushBool(weapon.IsWeaponVisible()); + return 1; + } + +#if CLIENT_DLL + [LuaMethod] + static int Weapon__IsCarriedByLocalPlayer(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushBool(weapon.IsCarriedByLocalPlayer()); + return 1; + } +#endif + + [LuaMethod] + static int Weapon__SendWeaponAnim(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + if ((int)lua.CheckNumber(2) < 0) + lua.ArgError(2, "invalid act"); + weapon.SendWeaponAnim((Activity)(int)lua.CheckNumber(2)); + return 0; + } + + [LuaMethod] + static int Weapon__GetDeploySpeed(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushNumber(weapon.GetDeploySpeed()); + return 1; + } + + [LuaMethod] + static int Weapon__SetDeploySpeed(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + weapon.SetDeploySpeed((float)lua.CheckNumber(2)); + return 0; + } + + [LuaMethod] + static int Weapon__LastShootTime(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + lua.PushNumber(weapon.LastShootTime()); + return 1; + } + + [LuaMethod] + static int Weapon__SetLastShootTime(ILuaInterface lua) { + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + TimeUnit_t time = gpGlobals.CurTime; + if (lua.GetType(2) == LuaType.Number) + time = lua.GetNumber(2); + weapon.SetLastShootTime(time); + return 0; + } + [LuaMethod] + static int Weapon__CallOnClient(ILuaInterface lua) { +#if GAME_DLL + BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; + BaseCombatCharacter? owner = weapon.GetOwner(); + if (owner != null && owner.IsPlayer()) { + SingleUserRecipientFilter filter = new((BasePlayer)owner); + filter.MakeReliable(); + ReadOnlySpan function = lua.CheckString(2); + ReadOnlySpan args = lua.GetString(3) ?? ""; + UserMessageBegin(filter, "SWEPCmd"); + WRITE_EHANDLE(weapon); + WRITE_STRING(function); + WRITE_STRING(args); + MessageEnd(); + return 0; + } + DevMsg("ERROR! CallOnClient called on weapon without an owner!\n"); +#endif + return 0; + } +} +#endif diff --git a/Game.Shared/GarrysMod/SENT_AI.cs b/Game.Shared/GarrysMod/SENT_AI.cs index 10df22312..a46c0c354 100644 --- a/Game.Shared/GarrysMod/SENT_AI.cs +++ b/Game.Shared/GarrysMod/SENT_AI.cs @@ -5,9 +5,11 @@ #if CLIENT_DLL namespace Game.Client; +using Game.Client.GarrysMod; using FIELD = Source.FIELD; #else namespace Game.Server; +using Game.Server.GarrysMod; using FIELD = Source.FIELD; #endif @@ -36,9 +38,9 @@ public partial class { public static readonly Table DT_SENT_AI = new(DT_AI_BaseNPC, [ #if CLIENT_DLL - RecvPropDataTable("m_ScriptedEntity", DT_ScriptedEntity) + RecvPropDataTable("m_ScriptedEntity", FIELD.OF(nameof(ScriptedEntity)), ScriptedEntity.DT_ScriptedEntity, 0, RECV_GET_OBJECT_AT_FIELD(FIELD.OF(nameof(ScriptedEntity)))) #elif GAME_DLL - SendPropDataTable("m_ScriptedEntity", DT_ScriptedEntity) + SendPropDataTable("m_ScriptedEntity", FIELD.OF(nameof(ScriptedEntity)), ScriptedEntity.DT_ScriptedEntity) #endif ]); @@ -49,5 +51,31 @@ public partial class ServerClass #endif = new Class(DT_SENT_AI); + + public readonly ScriptedEntity ScriptedEntity = new(); + +#if CLIENT_DLL + public C_SENT_AI() { +#else + public SENT_AI() { +#endif + ScriptedEntity.Init(this, 1); + } + + public override ReadOnlySpan GetLuaScriptName() => ScriptedEntity.GetScriptName(); + + public override void InitializeScriptedEntity(ReadOnlySpan name) { + ScriptedEntity.SetScriptName(name); + SetClassname(name); + ScriptedEntity.StartLua(); + } + +#if CLIENT_DLL + public override void OnDataChanged(DataUpdateType updateType) { + base.OnDataChanged(updateType); + if (updateType == DataUpdateType.Created) + ScriptedEntity.StartLua(); + } +#endif } #endif diff --git a/Game.Shared/GarrysMod/SENT_Anim.cs b/Game.Shared/GarrysMod/SENT_Anim.cs index 83aec19dd..7ca226bdc 100644 --- a/Game.Shared/GarrysMod/SENT_Anim.cs +++ b/Game.Shared/GarrysMod/SENT_Anim.cs @@ -5,9 +5,14 @@ #if CLIENT_DLL namespace Game.Client; +using Game.Client.GarrysMod; +using Source.Common.Engine; using FIELD = Source.FIELD; #else namespace Game.Server; + +using Game.Server.GarrysMod; + using FIELD = Source.FIELD; #endif @@ -31,14 +36,14 @@ public partial class #if CLIENT_DLL C_SENT_Anim : C_BaseAnimatingOverlay #elif GAME_DLL - SENT_Anim : BaseAnimatingOverlay + SENT_Anim : BaseAnimatingOverlay #endif { public static readonly Table DT_SENT_anim = new(DT_BaseAnimatingOverlay, [ #if CLIENT_DLL - RecvPropDataTable("m_ScriptedEntity", DT_ScriptedEntity) + RecvPropDataTable("m_ScriptedEntity", FIELD.OF(nameof(ScriptedEntity)), ScriptedEntity.DT_ScriptedEntity, 0, RECV_GET_OBJECT_AT_FIELD(FIELD.OF(nameof(ScriptedEntity)))) #elif GAME_DLL - SendPropDataTable("m_ScriptedEntity", DT_ScriptedEntity) + SendPropDataTable("m_ScriptedEntity", FIELD.OF(nameof(ScriptedEntity)), ScriptedEntity.DT_ScriptedEntity) #endif ]); @@ -49,5 +54,51 @@ public partial class ServerClass #endif = new Class(DT_SENT_anim); + + public readonly ScriptedEntity ScriptedEntity = new(); + +#if CLIENT_DLL + public C_SENT_Anim() { +#else + public SENT_Anim() { +#endif + ScriptedEntity.Init(this, 1); + } + + public override ReadOnlySpan GetLuaScriptName() => ScriptedEntity.GetScriptName(); + + public override void InitializeScriptedEntity(ReadOnlySpan name) { + ScriptedEntity.SetScriptName(name); + SetClassname(name); + ScriptedEntity.StartLua(); + } + +#if CLIENT_DLL + public override RenderGroup GetRenderGroup() { + RenderGroup group = RenderMode == (int)Source.RenderMode.None ? RenderGroup.OpaqueEntity : base.GetRenderGroup(); + if (!HasLuaTable()) + return group; + + if (GetLuaTable()!.GetMemberBool("WantsTranslucency", false) && group == RenderGroup.OpaqueEntity) + group = RenderGroup.TwoPass; + + int luaGroup = GetLuaTable()!.GetMemberInt("RenderGroup", (int)group); + if (luaGroup < 0) + return RenderGroup.OpaqueEntityHuge; + if (luaGroup > (int)RenderGroup.Other) + return RenderGroup.Other; + if (luaGroup == (int)RenderGroup.OpaqueStatic) + return RenderGroup.OpaqueEntity; + if (luaGroup == (int)RenderGroup.OpaqueStaticHuge) + return RenderGroup.OpaqueEntityHuge; + return (RenderGroup)luaGroup; + } + + public override void OnDataChanged(DataUpdateType updateType) { + base.OnDataChanged(updateType); + if (updateType == DataUpdateType.Created) + ScriptedEntity.StartLua(); + } +#endif } #endif diff --git a/Game.Shared/GarrysMod/SENT_Point.cs b/Game.Shared/GarrysMod/SENT_Point.cs index 0608135ac..3c95b3088 100644 --- a/Game.Shared/GarrysMod/SENT_Point.cs +++ b/Game.Shared/GarrysMod/SENT_Point.cs @@ -5,9 +5,11 @@ #if CLIENT_DLL namespace Game.Client; +using Game.Client.GarrysMod; using FIELD = Source.FIELD; #else namespace Game.Server; +using Game.Server.GarrysMod; using FIELD = Source.FIELD; #endif @@ -37,9 +39,9 @@ public partial class { public static readonly Table DT_SENT_point = new(DT_BaseEntity, [ #if CLIENT_DLL - RecvPropDataTable("m_ScriptedEntity", DT_ScriptedEntity) + RecvPropDataTable("m_ScriptedEntity", FIELD.OF(nameof(ScriptedEntity)), ScriptedEntity.DT_ScriptedEntity, 0, RECV_GET_OBJECT_AT_FIELD(FIELD.OF(nameof(ScriptedEntity)))) #elif GAME_DLL - SendPropDataTable("m_ScriptedEntity", DT_ScriptedEntity) + SendPropDataTable("m_ScriptedEntity", FIELD.OF(nameof(ScriptedEntity)), ScriptedEntity.DT_ScriptedEntity) #endif ]); @@ -50,5 +52,31 @@ public partial class ServerClass #endif = new Class(DT_SENT_point); + + public readonly ScriptedEntity ScriptedEntity = new(); + +#if CLIENT_DLL + public C_SENT_Point() { +#else + public SENT_Point() { +#endif + ScriptedEntity.Init(this, 1); + } + + public override ReadOnlySpan GetLuaScriptName() => ScriptedEntity.GetScriptName(); + + public override void InitializeScriptedEntity(ReadOnlySpan name) { + ScriptedEntity.SetScriptName(name); + SetClassname(name); + ScriptedEntity.StartLua(); + } + +#if CLIENT_DLL + public override void OnDataChanged(DataUpdateType updateType) { + base.OnDataChanged(updateType); + if (updateType == DataUpdateType.Created) + ScriptedEntity.StartLua(); + } +#endif } #endif diff --git a/Game.Shared/GarrysMod/ScriptedEntity.cs b/Game.Shared/GarrysMod/ScriptedEntity.cs new file mode 100644 index 000000000..f297c1bd1 --- /dev/null +++ b/Game.Shared/GarrysMod/ScriptedEntity.cs @@ -0,0 +1,268 @@ +#if CLIENT_DLL || GAME_DLL +using Source; +using Source.Common; +using Source.Common.GarrysMod.Lua; + +using static Game.Client.GarrysMod.GarrysMod; + +#if CLIENT_DLL +namespace Game.Client.GarrysMod; +using FIELD = Source.FIELD; +#else +namespace Game.Server.GarrysMod; + +using FIELD = Source.FIELD; +#endif + +public class ScriptedEntity +{ +#if CLIENT_DLL + public static readonly RecvTable DT_ScriptedEntity = new(nameof(DT_ScriptedEntity), [ + RecvPropString(FIELD.OF(nameof(ScriptName))) + ]); +#else + public static readonly SendTable DT_ScriptedEntity = new(nameof(DT_ScriptedEntity), [ + SendPropString(FIELD.OF(nameof(ScriptName))) + ]); +#endif + + public bool Started; + public int EntityType; + public BaseEntity? ParentEntity; + [NetworkName("m_strScriptName")] + public InlineArray64 ScriptName; +#if GAME_DLL + public string? ScriptNamePooled; +#endif + public InlineArray64 ModuleName; + public InlineArray64 SelfName; + + public ScriptedEntity() { + ScriptName[0] = '\0'; +#if GAME_DLL + ScriptNamePooled = null; +#endif + strcpy(ModuleName, "scripted_ents"); + strcpy(SelfName, "Entity"); + SetScriptName(""); +#if GAME_DLL + ScriptNamePooled = null; +#endif + EntityType = 0; + Started = false; + } + + public virtual void NetworkStateChanged() { +#if GAME_DLL + ParentEntity?.NetworkStateChanged(); +#endif + } + + public void Init(BaseEntity parent, int type) { + ParentEntity = parent; + EntityType = type; + } + + public void SetModuleName(ReadOnlySpan name) => strcpy(ModuleName, name); + public void SetSelfName(ReadOnlySpan name) => strcpy(SelfName, name); + public ReadOnlySpan GetScriptName() => ((ReadOnlySpan)ScriptName).SliceNullTerminatedString(); + + public void SetScriptName(ReadOnlySpan name) { + Span lowered = stackalloc char[64]; + strcpy(lowered, name); + strlower(lowered); + NetworkStateChanged(); + strcpy(ScriptName, lowered); +#if GAME_DLL + ScriptNamePooled = new string(((ReadOnlySpan)ScriptName).SliceNullTerminatedString()); +#endif + } + + public bool Call(int args, int rets) { + if (rets == 0) { + g_Lua!.CallInternalNoReturns(args + 1); + return true; + } + return g_Lua!.CallInternal(args + 1, rets); + } + + public bool StartFunction(int pooledName) { + if (!ThreadInMainThread() || !Started) + return false; + + ParentEntity!.GetLuaTable()!.Push(); + g_Lua!.PushPooledString(pooledName); + g_Lua.GetTable(-2); + g_Lua.Remove(-2); + if (g_Lua.GetType(-1) == LuaType.Function) { + LuaEntity.Push_Entity(ParentEntity); + return true; + } + g_Lua.Pop(1); + return false; + } + + public bool StartFunction(ReadOnlySpan name) { + if (!ThreadInMainThread() || !Started) + return false; + + ParentEntity!.GetLuaTable()!.Push(); + g_Lua!.PushString(name); + g_Lua.GetTable(-2); + g_Lua.Remove(-2); + if (g_Lua.GetType(-1) == LuaType.Function) { + LuaEntity.Push_Entity(ParentEntity); + return true; + } + g_Lua.Pop(1); + return false; + } + + public bool CallFunction(int pooledName, bool getBool) { + if (!Started) + return false; + + ParentEntity!.GetLuaTable()!.Push(); + g_Lua!.PushPooledString(pooledName); + g_Lua.GetTable(-2); + g_Lua.Remove(-2); + if (g_Lua.GetType(-1) == LuaType.Function) { + LuaEntity.Push_Entity(ParentEntity); + if (getBool) + return g_Lua.CallInternalGetBool(1); + g_Lua.CallInternalNoReturns(1); + return false; + } + g_Lua.Pop(1); + return false; + } + + public bool CallFunction(ReadOnlySpan name, bool getBool) { + if (!Started) + return false; + + bool ret; + LuaObject func = new(); + ParentEntity!.GetLuaTable()!.GetMember(name, func); + if (!func.isFunction()) { + LuaEntity.LC_Entity.MetaTable.GetMember(name, func); + if (!func.isFunction()) { + func.UnReference(); + return false; + } + } + + func.Push(); + LuaEntity.Push_Entity(ParentEntity); + if (!getBool) { + g_Lua!.CallInternalNoReturns(1); + ret = false; + } + else + ret = g_Lua!.CallInternalGetBool(1); + func.UnReference(); + return ret; + } + + public void InitializeDataTables() { + if (!Started) + return; + + LuaObject setupDataTables = new(); + ParentEntity!.GetLuaTable()!.GetMember("SetupDataTables", setupDataTables); + if (setupDataTables.isFunction()) { + CallFunction("InstallDataTable", true); + CallFunction("SetupDataTables", true); + } + setupDataTables.UnReference(); + } + +#if CLIENT_DLL + static void LuaEntityCreated(BaseEntity? ent) { + // todo + } +#endif + + public void StartLua() { + if (g_Lua == null || g_LuaManager == null || Started || ScriptName[0] == '\0') + return; + + Started = true; + if (ParentEntity == null) + Error("CScriptedEntity with no m_ParentEntity"); + + if (ParentEntity.GetLuaEntity() == null) + Error("CScriptedEntity with invalid m_ParentEntity->GetLuaEntity()"); + + if (!ParentEntity.GetLuaEntity()!.isEntity()) { + Warning("CScriptedEntity: Entity isn't entity!\n"); + return; + } + + if (!ParentEntity.GetLuaTable()!.isTable()) { + Warning("CScriptedEntity: Table isn't table!\n"); + return; + } + + ReadOnlySpan scriptName = GetScriptName(); + ReadOnlySpan moduleName = ((ReadOnlySpan)ModuleName).SliceNullTerminatedString(); + + LuaObject module = new(); + module.SetFromGlobal(moduleName); + if (!module.isTable()) { + g_Lua.ErrorFromLua($"Error: Scripted Entity {scriptName} couldn't be created! '{moduleName}' library doesn't exist or is not a table!\n"); + module.UnReference(); + return; + } + + LuaObject get = new(); + module.GetMember("Get", get); + if (!get.isFunction()) { + g_Lua.ErrorFromLua($"Error: Scripted Entity {scriptName} couldn't be created! {moduleName}.Get() doesn't exist or is not a function!\n"); + get.UnReference(); + module.UnReference(); + return; + } + + get.Push(); + g_Lua.PushString(scriptName); + if (ParentEntity.HasLuaTable()) + ParentEntity.GetLuaTable()!.Push(); + else + g_Lua.PushNil(); + + LuaObject table = new(); + if (!g_Lua.CallInternalGet(2, table)) { + g_Lua.ErrorFromLua($"Error: Scripted Entity {scriptName} couldn't be created! {moduleName}.Get() failed!\n"); + Started = false; + } + else { + if (!table.isTable()) { + Warning($"Error creating '{scriptName}' (Make sure the file is AddCSLuaFile'd and there aren't any errors!)\n"); + LuaTable empty = new(null, 0); + table.Set(empty); + empty.UnReference(); + } + + ParentEntity.SetLuaTable(table); + ParentEntity.GetLuaTable()!.SetMemberEntity(((ReadOnlySpan)SelfName).SliceNullTerminatedString(), ParentEntity); +#if CLIENT_DLL + LuaEntityCreated(ParentEntity); +#endif + ParentEntity.Lua_OnEntityInitialized(); + InitializeDataTables(); +#if CLIENT_DLL + if (ParentEntity.EntIndex() != -1) { + C_BaseEntity.SetAllowPrecache(true); + CallFunction("Initialize", true); + C_BaseEntity.SetAllowPrecache(false); + } +#endif + } + + table.UnReference(); + get.UnReference(); + module.UnReference(); + } +} +#endif diff --git a/Game.Shared/GarrysMod/WeaponSWEP.cs b/Game.Shared/GarrysMod/WeaponSWEP.cs index 459378d59..45e01792e 100644 --- a/Game.Shared/GarrysMod/WeaponSWEP.cs +++ b/Game.Shared/GarrysMod/WeaponSWEP.cs @@ -1,4 +1,5 @@ -#if (CLIENT_DLL || GAME_DLL) && GMOD_DLL +using System.Numerics; +#if (CLIENT_DLL || GAME_DLL) && GMOD_DLL using Game.Shared; using Source; @@ -6,9 +7,13 @@ #if CLIENT_DLL namespace Game.Client; +using Game.Client.GarrysMod; using FIELD = Source.FIELD; #else namespace Game.Server; + +using Game.Server.GarrysMod; + using FIELD = Source.FIELD; #endif @@ -37,10 +42,10 @@ public partial class { public static readonly Table DT_WeaponSWEP = new(DT_BaseHL2MPCombatWeapon, [ #if CLIENT_DLL - RecvPropDataTable("m_ScriptedEntity", DT_ScriptedEntity), + RecvPropDataTable("m_ScriptedEntity", FIELD.OF(nameof(ScriptedEntity)), ScriptedEntity.DT_ScriptedEntity, 0, RECV_GET_OBJECT_AT_FIELD(FIELD.OF(nameof(ScriptedEntity)))), RecvPropString(FIELD.OF(nameof(HoldType))) #elif GAME_DLL - SendPropDataTable("m_ScriptedEntity", DT_ScriptedEntity), + SendPropDataTable("m_ScriptedEntity", FIELD.OF(nameof(ScriptedEntity)), ScriptedEntity.DT_ScriptedEntity), SendPropString(FIELD.OF(nameof(HoldType))) #endif ]); @@ -58,7 +63,431 @@ public partial class #endif [NetworkName("m_strHoldType")] - public InlineArray64 HoldType; + public InlineArray80 HoldType; + + public readonly ScriptedEntity ScriptedEntity = new(); + +#if CLIENT_DLL + public C_WeaponSWEP() { +#else + public WeaponSWEP() { +#endif + ScriptedEntity.Init(this, 2); + ScriptedEntity.SetModuleName("weapons"); + ScriptedEntity.SetSelfName("Weapon"); + } + + string ViewModelName = ""; + string WorldModelName = ""; + string PrintName = ""; + int Slot = -1; + int SlotPos = -1; + long LastLuaDataUpdate; + bool LuaDataLocked; + InlineArray80 LastHoldType; + BaseEntity? LastOwner; + int MaxClip1; + int DefaultClip1; + bool PrimaryAutomatic; + int MaxClip2; + int DefaultClip2; + bool SecondaryAutomatic; +#if CLIENT_DLL + bool AccurateCrosshair; +#else + int Weight; + bool AutoSwitchTo; + bool AutoSwitchFrom; +#endif + + public virtual void UpdateLuaData(bool force) { + if (!ScriptedEntity.Started) + return; + + bool update = false; + if (!LuaDataLocked) + update = force; + if (!update && LastLuaDataUpdate == gpGlobals.FrameCount) + return; + + LastLuaDataUpdate = gpGlobals.FrameCount; + SetClassname(ScriptedEntity.GetScriptName()); + + LuaObject? table = GetLuaTable(); + if (table == null) + return; + + ViewModelName = table.GetMemberStr("ViewModel", "models/weapons/v_pistol.mdl") ?? ""; + WorldModelName = table.GetMemberStr("WorldModel", "models/weapons/w_pistol.mdl") ?? ""; + PrintName = table.GetMemberStr("PrintName", "") ?? ""; +#if CLIENT_DLL + AccurateCrosshair = table.GetMemberBool("AccurateCrosshair", false); +#else + Weight = table.GetMemberInt("Weight", 0); + AutoSwitchTo = table.GetMemberBool("AutoSwitchTo", true); + AutoSwitchFrom = table.GetMemberBool("AutoSwitchFrom", true); +#endif + + LuaObject primary = new(); + table.GetMember("Primary", primary); + string? ammo = null; + if (primary.isTable()) { + MaxClip1 = primary.GetMemberInt("ClipSize", 0); + DefaultClip1 = primary.GetMemberInt("DefaultClip", 0); + PrimaryAutomatic = primary.GetMemberBool("Automatic", true); + ammo = primary.GetMemberStr("Ammo", null); + } + primary.UnReference(); + if (ammo != null) { + int ammoType = GetAmmoDef().Index(ammo); + if (PrimaryAmmoType != ammoType) { +#if GAME_DLL + NetworkStateChanged(); +#endif + PrimaryAmmoType = ammoType; + } + } + else { + if (PrimaryAmmoType != -1) { +#if GAME_DLL + NetworkStateChanged(); +#endif + PrimaryAmmoType = -1; + } + PrimaryAutomatic = true; + MaxClip1 = -1; + DefaultClip1 = -1; + } + + LuaObject secondary = new(); + table.GetMember("Secondary", secondary); + ammo = null; + if (secondary.isTable()) { + MaxClip2 = secondary.GetMemberInt("ClipSize", 0); + DefaultClip2 = secondary.GetMemberInt("DefaultClip", 0); + SecondaryAutomatic = secondary.GetMemberBool("Automatic", true); + ammo = secondary.GetMemberStr("Ammo", null); + } + secondary.UnReference(); + if (ammo != null) { + int ammoType = GetAmmoDef().Index(ammo); + if (SecondaryAmmoType != ammoType) { +#if GAME_DLL + NetworkStateChanged(); +#endif + SecondaryAmmoType = ammoType; + } + } + else { + if (SecondaryAmmoType != -1) { +#if GAME_DLL + NetworkStateChanged(); +#endif + SecondaryAmmoType = -1; + } + SecondaryAutomatic = true; + MaxClip2 = -1; + DefaultClip2 = -1; + } + + if (iViewModelIndex != 0) { +#if GAME_DLL + NetworkStateChanged(); +#endif + iViewModelIndex = 0; + } + if (WorldModelIndex != 0) { +#if GAME_DLL + NetworkStateChanged(); +#endif + WorldModelIndex = 0; + } + if (!GetViewModel(0).IsEmpty) { + int index = PrecacheModel(GetViewModel(0)); + if (iViewModelIndex != index) { +#if GAME_DLL + NetworkStateChanged(); +#endif + iViewModelIndex = index; + } + } + if (!GetWorldModel().IsEmpty) { + int index = PrecacheModel(GetWorldModel()); + if (WorldModelIndex != index) { +#if GAME_DLL + NetworkStateChanged(); +#endif + WorldModelIndex = index; + } + } + + if (strcmp(LastHoldType, HoldType) != 0) + UpdateHoldType(); + } + + public virtual void UpdateHoldType() { + if (HoldType[0] != '\0' && ScriptedEntity.StartFunction((int)LUA_POOLEDSTRING.SetWeaponHoldType)) { + g_Lua!.PushString(((ReadOnlySpan)HoldType).SliceNullTerminatedString()); + ScriptedEntity.Call(1, 0); + } + strcpy(LastHoldType, HoldType); + } + + public override void Precache() { } + + public override ReadOnlySpan GetHoldType() => ((ReadOnlySpan)HoldType).SliceNullTerminatedString(); + + public override void SetHoldType(ReadOnlySpan holdType) { + if (holdType.IsEmpty || holdType[0] == '\0') + return; +#if GAME_DLL + NetworkStateChanged(); +#endif + strcpy(HoldType, holdType); + } + +#if CLIENT_DLL + public virtual void RunSWEPCmd(ReadOnlySpan function, ReadOnlySpan args) { + if (ScriptedEntity.StartFunction(function)) { + g_Lua!.PushString(args); + ScriptedEntity.Call(1, 0); + } + } +#endif + + public bool GetPrimaryAutomatic() { + UpdateLuaData(true); + return PrimaryAutomatic; + } + + public bool GetSecondaryAutomatic() { + UpdateLuaData(true); + return SecondaryAutomatic; + } + +#if GAME_DLL + public override void Spawn() { + UpdateLuaData(true); + base.Spawn(); + bool allowPrecache = IsPrecacheAllowed(); + SetAllowPrecache(true); + ScriptedEntity.CallFunction("Initialize", false); + SetAllowPrecache(allowPrecache); + } + + public override void OnRestore() { + base.OnRestore(); + ScriptedEntity.InitializeDataTables(); + ScriptedEntity.CallFunction("OnRestore", true); + } +#endif + + public override void UpdateOnRemove() { + if (EntIndex() != -1 && ScriptedEntity.StartFunction((int)LUA_POOLEDSTRING.OnRemove)) { +#if GAME_DLL + g_Lua!.PushBool(false); +#else + g_Lua!.PushBool(DestroyedOnRecreateEntities); +#endif + ScriptedEntity.Call(1, 0); + } + base.UpdateOnRemove(); + } + + public override void OnOwnerChanged() { + if (GetOwnerEntity() == LastOwner) + return; + UpdateLuaData(true); + LastOwner = GetOwnerEntity(); + if (ScriptedEntity.Started) + ScriptedEntity.CallFunction("OwnerChanged", false); + } + + public override bool Deploy() { + UpdateLuaData(true); + base.Deploy(); + if (ScriptedEntity.StartFunction((int)LUA_POOLEDSTRING.Deploy) && ScriptedEntity.Call(0, 1)) + return g_Lua!.GetReturn(0).GetBool(); + return true; + } + + public override bool Holster(BaseCombatWeapon? switchingTo) { + if (ScriptedEntity.StartFunction((int)LUA_POOLEDSTRING.Holster)) { + LuaEntity.Push_Entity(switchingTo); + if (ScriptedEntity.Call(1, 1) && !g_Lua!.GetReturn(0).GetBool()) + return false; + } + if (switchingTo != this) + base.Holster(switchingTo!); + UpdateLuaData(true); +#if GAME_DLL + GameInterface.EntityMessageBegin(this, true); + WRITE_BYTE(1); + GameInterface.MessageEnd(); +#endif + return true; + } + + public override void ItemPostFrame() { + if (GetOwner() == null) + return; + UpdateLuaData(true); + RandomSeed(GetPredictionRandomSeed()); + ScriptedEntity.CallFunction((int)LUA_POOLEDSTRING.Tick, false); + ScriptedEntity.CallFunction((int)LUA_POOLEDSTRING.Think, false); + LuaDataLocked = true; + if (UsesClipsForAmmo1() || UsesClipsForAmmo2()) + CheckReload(); + LuaDataLocked = false; + BasePlayer? owner = ToBasePlayer(GetOwner()); + if (owner == null || !owner.CanAttack()) + return; + if ((owner.Buttons & InButtons.Attack2) != 0 && NextSecondaryAttack <= gpGlobals.CurTime) + SecondaryAttack(); + if ((owner.Buttons & InButtons.Attack) != 0 && NextPrimaryAttack <= gpGlobals.CurTime) + PrimaryAttack(); + if ((owner.Buttons & InButtons.Reload) != 0 && !InReload) + Reload(); + } + + public override bool Reload() { + ScriptedEntity.CallFunction((int)LUA_POOLEDSTRING.Reload, false); + return false; + } + + public override void PrimaryAttack() { + if (GetOwner() == null) + return; + BaseCombatCharacter? owner = GetOwner(); + if (owner == null || !owner.IsPlayer() || GetPrimaryAutomatic() || (((BasePlayer)owner).AfButtonPressed & InButtons.Attack) != 0) + ScriptedEntity.CallFunction((int)LUA_POOLEDSTRING.PrimaryAttack, false); + } + + public override void SecondaryAttack() { + BaseCombatCharacter? owner = GetOwner(); + if (owner != null && owner.IsPlayer() && !GetSecondaryAutomatic() && (((BasePlayer)owner).AfButtonPressed & InButtons.Attack2) == 0) + return; + ScriptedEntity.CallFunction((int)LUA_POOLEDSTRING.SecondaryAttack, false); + } + + public override Activity ActivityOverride(Activity baseAct, ref bool required) { + if (ScriptedEntity.StartFunction((int)LUA_POOLEDSTRING.TranslateActivity)) { + g_Lua!.PushNumber((int)baseAct); + if (ScriptedEntity.Call(1, 1)) { + int act = g_Lua.GetReturn(0).GetInt(); + return act == -1 ? baseAct : (Activity)act; + } + } + return baseAct; + } + + public override void Equip(BaseCombatCharacter owner) { + base.Equip(owner); + UpdateLuaData(true); + if (ScriptedEntity.StartFunction((int)LUA_POOLEDSTRING.Equip)) { + LuaEntity.Push_Entity(owner); + ScriptedEntity.Call(1, 0); + } + } + + public override void Drop(in Vector3 velocity) { + BaseCombatCharacter? owner = GetOwner(); + base.Drop(velocity); + SetOwner(null); + SetOwnerEntity(null); + UpdateLuaData(true); + if (ScriptedEntity.StartFunction((int)LUA_POOLEDSTRING.OnDrop)) { + LuaEntity.Push_Entity(owner); + ScriptedEntity.Call(1, 0); + } + } + +#if GAME_DLL + public override ReadOnlySpan GetName() => ScriptedEntity.ScriptNamePooled; +#else + public override ReadOnlySpan GetName() => ScriptedEntity.GetScriptName(); +#endif + + public override int GetSlot() { + if (Slot >= 0) + return Slot; + if (ScriptedEntity.Started && HasLuaTable()) { + Slot = GetLuaTable()!.GetMemberInt("Slot", 0); + return Slot; + } + return 0; + } + + public override int GetPosition() { + if (SlotPos >= 0) + return SlotPos; + if (!ScriptedEntity.Started || !HasLuaTable()) + return 0; + SlotPos = GetLuaTable()!.GetMemberInt("SlotPos", 1) * 100; + return SlotPos >= 0 ? SlotPos : 0; + } + + public override ReadOnlySpan GetPrintName() { + if (PrintName.Length == 0) + UpdateLuaData(true); + return PrintName; + } + + public override ReadOnlySpan GetViewModel(int _ = 0) => ViewModelName; + public override ReadOnlySpan GetWorldModel() => WorldModelName; + + public override int GetMaxClip1() { + UpdateLuaData(true); + return MaxClip1; + } + + public override int GetMaxClip2() { + UpdateLuaData(true); + return MaxClip2; + } + + public override int GetDefaultClip1() { + UpdateLuaData(true); + return DefaultClip1; + } + + public override int GetDefaultClip2() { + UpdateLuaData(true); + return DefaultClip2; + } + +#if GAME_DLL + public override int GetWeight() { + UpdateLuaData(true); + return Weight; + } + + public override bool AllowsAutoSwitchTo() { + UpdateLuaData(true); + return AutoSwitchTo; + } + + public override bool AllowsAutoSwitchFrom() { + UpdateLuaData(true); + return AutoSwitchFrom; + } +#endif + + public override ReadOnlySpan GetLuaScriptName() => ScriptedEntity.GetScriptName(); + + public override void InitializeScriptedEntity(ReadOnlySpan name) { + ScriptedEntity.SetScriptName(name); + SetClassname(name); + ScriptedEntity.StartLua(); + } + +#if CLIENT_DLL + public override void OnDataChanged(DataUpdateType updateType) { + base.OnDataChanged(updateType); + if (updateType == DataUpdateType.Created) + ScriptedEntity.StartLua(); + } +#endif } #endif diff --git a/Source.Common/CollisionUtils.cs b/Source.Common/CollisionUtils.cs index 2f7e4a46b..8aefd9b06 100644 --- a/Source.Common/CollisionUtils.cs +++ b/Source.Common/CollisionUtils.cs @@ -1,3 +1,4 @@ +using Source.Common.Formats.BSP; using Source.Common.MaterialSystem; using Source.Common.Mathematics; @@ -7,8 +8,132 @@ namespace Source.Common; +public struct BoxTraceInfo +{ + public float T1; + public float T2; + public int HitSide; + public bool StartSolid; +} + public static class CollisionUtils { + public static void Collision_ClearTrace(in Vector3 rayStart, in Vector3 rayDelta, ref GameTrace trace) { + trace.StartPos = rayStart; + trace.EndPos = rayStart; + trace.EndPos += rayDelta; + trace.StartSolid = false; + trace.AllSolid = false; + trace.Fraction = 1.0f; + trace.Contents = 0; + } + + public static bool IntersectRayWithBox(in Vector3 rayStart, in Vector3 rayDelta, in Vector3 boxMins, in Vector3 boxMaxs, float tolerance, out BoxTraceInfo trace) { + int i; + float d1, d2; + float f; + + trace.T1 = -1.0f; + trace.T2 = 1.0f; + trace.HitSide = -1; + + trace.StartSolid = true; + + for (i = 0; i < 6; ++i) { + if (i >= 3) { + d1 = rayStart[i - 3] - boxMaxs[i - 3]; + d2 = d1 + rayDelta[i - 3]; + } + else { + d1 = -rayStart[i] + boxMins[i]; + d2 = d1 - rayDelta[i]; + } + + if (d1 > 0 && d2 > 0) { + trace.StartSolid = false; + return false; + } + + if (d1 <= 0 && d2 <= 0) + continue; + + if (d1 > 0) + trace.StartSolid = false; + + if (d1 > d2) { + f = d1 - tolerance; + if (f < 0) + f = 0; + f /= (d1 - d2); + if (f > trace.T1) { + trace.T1 = f; + trace.HitSide = i; + } + } + else { + f = (d1 + tolerance) / (d1 - d2); + if (f < trace.T2) + trace.T2 = f; + } + } + + return trace.StartSolid || (trace.T1 < trace.T2 && trace.T1 >= 0.0f); + } + + public static bool IntersectRayWithBox(in Vector3 rayStart, in Vector3 rayDelta, in Vector3 boxMins, in Vector3 boxMaxs, float tolerance, ref GameTrace trace, ref float fractionLeftSolid) { + Collision_ClearTrace(rayStart, rayDelta, ref trace); + + if (IntersectRayWithBox(rayStart, rayDelta, boxMins, boxMaxs, tolerance, out BoxTraceInfo boxTrace)) { + trace.StartSolid = boxTrace.StartSolid; + if (boxTrace.T1 < boxTrace.T2 && boxTrace.T1 >= 0.0f) { + trace.Fraction = boxTrace.T1; + MathLib.VectorMA(trace.StartPos, boxTrace.T1, rayDelta, out trace.EndPos); + trace.Contents = Contents.Solid; + trace.Plane.Normal = vec3_origin; + if (boxTrace.HitSide >= 3) { + boxTrace.HitSide -= 3; + trace.Plane.Dist = boxMaxs[boxTrace.HitSide]; + trace.Plane.Normal[boxTrace.HitSide] = 1.0f; + trace.Plane.Type = (PlaneType)boxTrace.HitSide; + } + else { + trace.Plane.Dist = -boxMins[boxTrace.HitSide]; + trace.Plane.Normal[boxTrace.HitSide] = -1.0f; + trace.Plane.Type = (PlaneType)boxTrace.HitSide; + } + return true; + } + + if (trace.StartSolid) { + trace.AllSolid = (boxTrace.T2 <= 0.0f) || (boxTrace.T2 >= 1.0f); + trace.Fraction = 0; + if (!Unsafe.IsNullRef(ref fractionLeftSolid)) + fractionLeftSolid = boxTrace.T2; + trace.EndPos = trace.StartPos; + trace.Contents = Contents.Solid; + trace.Plane.Dist = trace.StartPos[0]; + trace.Plane.Normal = new(1.0f, 0.0f, 0.0f); + trace.Plane.Type = 0; + trace.StartPos = rayStart + (boxTrace.T2 * rayDelta); + return true; + } + } + + return false; + } + + public static bool IntersectRayWithBox(in Ray ray, in Vector3 boxMins, in Vector3 boxMaxs, float tolerance, ref GameTrace trace, ref float fractionLeftSolid) { + if (!ray.IsRay) { + Vector3 expandedMins = boxMins - ray.Extents; + Vector3 expandedMaxs = boxMaxs + ray.Extents; + bool intersects = IntersectRayWithBox(ray.Start, ray.Delta, expandedMins, expandedMaxs, tolerance, ref trace, ref fractionLeftSolid); + trace.StartPos += ray.StartOffset; + trace.EndPos += ray.StartOffset; + return intersects; + } + return IntersectRayWithBox(ray.Start, ray.Delta, boxMins, boxMaxs, tolerance, ref trace, ref fractionLeftSolid); + } + public static bool IntersectInfiniteRayWithSphere(in Vector3 rayOrigin, in Vector3 rayDelta, in Vector3 sphereCenter, float radius, out float t1, out float t2) { Vector3 sphereToRay = rayOrigin - sphereCenter; diff --git a/Source.Common/Mathematics/MathLib.cs b/Source.Common/Mathematics/MathLib.cs index 8754f9b0c..9c6a1bd0f 100644 --- a/Source.Common/Mathematics/MathLib.cs +++ b/Source.Common/Mathematics/MathLib.cs @@ -1119,7 +1119,18 @@ public static void NormalizeAngles(ref QAngle angles) { } public static void QuaternionMult(in Quaternion p, in Quaternion q, out Quaternion qt) { - qt = Quaternion.Multiply(p, q); + Unsafe.SkipInit(out qt); + if (Unsafe.AreSame(in p, in qt)) { + Quaternion p2 = p; + QuaternionMult(p2, q, out qt); + return; + } + + QuaternionAlign(p, q, out Quaternion q2); + qt.X = p.X * q2.W + p.Y * q2.Z - p.Z * q2.Y + p.W * q2.X; + qt.Y = -p.X * q2.Z + p.Y * q2.W + p.Z * q2.X + p.W * q2.Y; + qt.Z = p.X * q2.Y - p.Y * q2.X + p.Z * q2.W + p.W * q2.Z; + qt.W = -p.X * q2.X - p.Y * q2.Y - p.Z * q2.Z + p.W * q2.W; } public static void QuaternionScale(in Quaternion p, float t, out Quaternion q) { float r; diff --git a/Source.MaterialSystem/MatRenderContext.cs b/Source.MaterialSystem/MatRenderContext.cs index 22d883380..d1819e1e5 100644 --- a/Source.MaterialSystem/MatRenderContext.cs +++ b/Source.MaterialSystem/MatRenderContext.cs @@ -1006,9 +1006,7 @@ public OcclusionQueryObjectHandle_t CreateOcclusionQueryObject() { return h; } - public void CullMode(MaterialCullMode cullMode) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void CullMode(MaterialCullMode cullMode) => shaderAPI.CullMode(cullMode); public void DestroyMorph(IMorph morph) { throw new NotImplementedException("Incomplete port of IMatRenderContext"); @@ -1169,9 +1167,7 @@ public void OverrideBlendSeparateAlpha(bool unk1, bool unk2, int unk3, int unk4, throw new NotImplementedException("Incomplete port of IMatRenderContext"); } - public void OverrideColorWriteEnable(bool overrideEnable, bool colorWriteEnable) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void OverrideColorWriteEnable(bool overrideEnable, bool colorWriteEnable) => shaderAPI.OverrideColorWriteEnable(overrideEnable, colorWriteEnable); public void OverrideDepthEnable(bool enable, bool depthEnable) => shaderAPI.OverrideDepthEnable(enable, depthEnable); diff --git a/Source.MaterialSystem/Surface/Clip2D.cs b/Source.MaterialSystem/Surface/Clip2D.cs index 756bcc330..981af941b 100644 --- a/Source.MaterialSystem/Surface/Clip2D.cs +++ b/Source.MaterialSystem/Surface/Clip2D.cs @@ -143,7 +143,7 @@ public unsafe static int ClipPolygon(in ScissorRectState state, Span