Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion Game.Server/BaseEntity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -973,7 +973,11 @@ public virtual void UpdateOnRemove() {
}
}

if (GlobalName != null) {
if (GlobalName != null
#if GMOD_DLL
&& !GMODGameRules.CleaningUpMap
#endif
) {
// NOTE: During level shutdown the global list will suppress this
// it assumes your changing levels or the game will end
// causing the whole list to be flushed
Expand Down
4 changes: 4 additions & 0 deletions Game.Server/EntityList.cs
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,10 @@ public void AddListenerEntity(IEntityListener listener) {
public void RemoveListenerEntity(IEntityListener listener) => EntityListeners.Remove(listener);

public void CleanupDeleteList() {
#if GMOD_DLL
if (GarrysMod.LuaGame.MapCleanupRunning && !GarrysMod.LuaGame.MapCleanupDeferred)
return;
#endif
PhysOnCleanupDeleteList();

Util.g_bDisableEhandleAccess = true;
Expand Down
3 changes: 2 additions & 1 deletion Game.Server/GameInterface.cs
Original file line number Diff line number Diff line change
Expand Up @@ -560,7 +560,7 @@ public bool LevelInit(ReadOnlySpan<char> pMapName, ReadOnlyMemory<byte> pMapEnti
gpGlobals.LoadType = MapLoadType.NewGame;

// Clear out entity references, and parse the entities into it.
// g_MapEntityRefs.Purge();
g_MapEntityRefs.Clear();
MapLoadEntityFilter filter = new();
MapEntity_ParseAllEntities(pMapEntities, filter);

Expand Down Expand Up @@ -1183,6 +1183,7 @@ class MapLoadEntityFilter : IMapEntityFilter
entref.SerialNumber = ret.Edict()!.NetworkSerialNumber;
}

g_MapEntityRefs.Add(entref);
return ret;
}
}
2 changes: 2 additions & 0 deletions Game.Server/MapEntities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ public static class MapEntities
{
static ref Edict? g_pForceAttachEdict => ref BaseEntity.g_pForceAttachEdict;

internal static readonly List<MapEntityRef> g_MapEntityRefs = [];

// creates an entity by string name, but does not spawn it
public static BaseEntity? CreateEntityByName(ReadOnlySpan<char> className, int forceEdictIndex = -1) {
if (forceEdictIndex != -1) {
Expand Down
123 changes: 123 additions & 0 deletions Game.Shared/GarrysMod/GMODGameRules.cs
Original file line number Diff line number Diff line change
Expand Up @@ -822,6 +822,129 @@ public override void InitDefaultAIRelationships() {
BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.PlayerAllyVital, Disposition.LI, 0);
BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.HackedRollermine, Disposition.LI, 0);
}

public static bool CleaningUpMap;

static readonly string[] PreserveEnts = [
"ai_network",
"ai_hint",
"env_sun",
"env_wind",
"env_fog_controller",
"infodecal",
"info_projecteddecal",
"info_node",
"info_node_hint",
"info_hint",
"info_node_air",
"info_node_air_hint",
"info_node_climb",
"info_node_air",
"info_map_parameters",
"info_ladder",
"player",
"path_corner",
"scene_manager",
"shadow_control",
"sky_camera",
"soundent",
"viewmodel",
"predicted_viewmodel",
"worldspawn",
"point_devshot_camera",
"physgun_beam",
"player_manager",
"gmod_gamerules",
"trigger_soundscape",
"env_soundscape",
"env_soundscape_proxy",
"env_soundscape_triggerable",
"env_sound",
"env_skypaint",
"gmod_hands",
];

static bool IsPreservedClass(ReadOnlySpan<char> className) {
foreach (string name in PreserveEnts) {
if (stricmp(name, className) == 0)
return true;
}
return false;
}

static bool CleanupFilterContains(ILuaObject? filters, ReadOnlySpan<char> className) {
if (filters == null || !filters.isTable())
return false;

ILuaInterface lua = g_Lua!;
filters.Push();
lua.PushNil();
while (lua.Next(-2)) {
if (lua.GetString(-1) is string value && className.SequenceEqual(value)) {
lua.Pop(3);
return true;
}
lua.Pop(1);
}
lua.Pop(1);
return false;
}

sealed class GMODMapEntityFilter(ILuaObject? filters) : IMapEntityFilter
{
int Iterator;

public bool ShouldCreateEntity(ReadOnlySpan<char> className) {
if (!IsPreservedClass(className) && !CleanupFilterContains(filters, className))
return true;

if (Iterator < g_MapEntityRefs.Count)
Iterator++;
return false;
}

public BaseEntity? CreateNextEntity(ReadOnlySpan<char> className) {
if (Iterator >= g_MapEntityRefs.Count)
return null;

MapEntityRef entRef = g_MapEntityRefs[Iterator++];
if (entRef.Edict != -1 && engine.PEntityOfEntIndex(entRef.Edict) == null)
return CreateEntityByName(className, entRef.Edict);
return CreateEntityByName(className);
}
}

public void CleanUpMap(ILuaObject? filters) {
BaseEntity? ent = gEntList.FirstEnt();
AI_DynamicLink.gm_bInitialized = false;
// todo: AI_DynamicLink.PurgeDynamicLinks();
// todo: AI_DynamicLink.ResetStates();

CleaningUpMap = true;
while (ent != null) {
if (ent is BaseCombatWeapon weapon) {
BaseEntity? owner = weapon.GetOwner();
if ((owner == null || !owner.IsPlayer()) && !ent.IsEFlagSet(EFL.KeepOnRecreateEntities))
Util.Remove(ent);
}
else {
ReadOnlySpan<char> className = ent.GetClassname();
if (!IsPreservedClass(className) && !ent.IsEFlagSet(EFL.KeepOnRecreateEntities) && !LuaEnts.IsProtectedEntity(ent) && !CleanupFilterContains(filters, className))
Util.Remove(ent);
}
ent = gEntList.NextEnt(ent);
}
CleaningUpMap = false;

gEntList.CleanupDeleteList();
g_EventQueue.Clear();
engine.AllowImmediateEdictReuse();

MapEntity_ParseAllEntities(engine.GetMapEntitiesString(), new GMODMapEntityFilter(filters), true);

AI_DynamicLink.InitDynamicLinks();
// todo: unidentified reset call that follows InitDynamicLinks
}
#endif
}
#endif
145 changes: 145 additions & 0 deletions Game.Shared/GarrysMod/LuaGame.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,151 @@ static int SetGlobalCounter(ILuaInterface lua) {
GlobalEntity.SetCounter(index, counter);
return 0;
}

public static bool MapCleanupRunning;
public static bool MapCleanupDeferred;
static bool MapCleanupPending;
static bool MapCleanupDontSendToClients;
static readonly LuaObject MapCleanupFilters = new();
static readonly LuaObject MapCleanupCallback = new();

[LuaFunction]
static int CleanUpMap(ILuaInterface lua) {
// todo: refuse with "Cannot run game.CleanUpMap while deleting entities!\n" while entities are being deleted
if (MapCleanupRunning || MapCleanupPending) {
lua.ErrorFromLua("Cannot run game.CleanUpMap while it is already running!\n");
return 0;
}

bool dontSendToClients = lua.GetType(1) != LuaType.Nil && lua.GetBool(1);

LuaObject filters = new(2, LuaType.None);
if (!filters.isNil() && !filters.isTable()) {
filters.UnReference();
lua.TypeError("table", 2);
}

LuaObject callback = new(3, LuaType.None);
if (!callback.isNil() && !callback.isFunction()) {
callback.UnReference();
filters.UnReference();
lua.TypeError("function", 3);
}

if (callback.isNil())
DoCleanUpMap(dontSendToClients, filters);
else {
MapCleanupPending = true;
MapCleanupCallback.Set(callback);
MapCleanupFilters.Set(filters);
MapCleanupDontSendToClients = dontSendToClients;
}

callback.UnReference();
filters.UnReference();
return 0;
}

static void DoCleanUpMap(bool dontSendToClients, ILuaObject filters) {
MapCleanupRunning = true;
gGM?.Call((int)LUA_POOLEDSTRING.PreCleanupMap);

if (g_pGameRules is GMODGameRules rules)
rules.CleanUpMap(filters);

if (!dontSendToClients) {
RecipientFilter filter = new();
filter.AddAllPlayers();
filter.MakeReliable();
GarrysMod.BroadcastLua(filter, "game.CleanUpMap()");
}

// todo: unidentified step between the client broadcast and AllowImmediateEdictReuse
engine.AllowImmediateEdictReuse();

gGM?.Call((int)LUA_POOLEDSTRING.PostCleanupMap);
MapCleanupRunning = false;
}

public static void RunMapCleanupIfNeeded() {
if (!MapCleanupPending)
return;

MapCleanupDeferred = true;
DoCleanUpMap(MapCleanupDontSendToClients, MapCleanupFilters);
MapCleanupDeferred = false;
MapCleanupPending = false;

if (g_Lua != null && MapCleanupCallback.isFunction()) {
MapCleanupCallback.Push();
g_Lua.CallInternalNoReturns(0);
}

MapCleanupCallback.UnReference();
MapCleanupFilters.UnReference();
MapCleanupDontSendToClients = false;
}
#endif

#if CLIENT_DLL
public static bool MapCleanupRunning;
static bool MapCleanupPending;
static readonly LuaObject MapCleanupCallback = new();

[LuaFunction]
static int CleanUpMap(ILuaInterface lua) {
// todo: refuse with "Cannot run game.CleanUpMap while deleting entities!\n" while entities are being deleted
if (MapCleanupRunning || MapCleanupPending) {
lua.ErrorFromLua("Cannot run game.CleanUpMap while it is already running!\n");
return 0;
}

LuaObject callback = new(3, LuaType.None);
if (!callback.isNil() && !callback.isFunction()) {
callback.UnReference();
lua.TypeError("function", 3);
}

if (callback.isNil())
DoCleanUpMap();
else {
MapCleanupPending = true;
MapCleanupCallback.Set(callback);
}

callback.UnReference();
return 0;
}

static void DoCleanUpMap() {
MapCleanupRunning = true;
gGM?.Call((int)LUA_POOLEDSTRING.PreCleanupMap);

// todo: remove the Lua-created clientside entities
engine.ClientCmd("r_cleardecals\n");
enginesound.StopAllSounds(true);
// todo: unidentified call that follows StopAllSounds
// todo: release every C_Hairball in the client entity list
// todo: unidentified step before the PostCleanupMap hook

gGM?.Call((int)LUA_POOLEDSTRING.PostCleanupMap);
MapCleanupRunning = false;
}

public static void RunMapCleanupIfNeeded() {
if (!MapCleanupPending)
return;

DoCleanUpMap();
MapCleanupPending = false;

if (g_Lua != null && MapCleanupCallback.isFunction()) {
MapCleanupCallback.Push();
g_Lua.CallInternalNoReturns(0);
}

MapCleanupCallback.UnReference();
}
#endif

[LuaFunction]
Expand Down
4 changes: 2 additions & 2 deletions Game.Shared/GarrysMod/LuaGameSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public override void Update(double frametime) {
LuaMesh.FlushPendingDestroy();
// RemoveQueuedRenderTargets();
LuaEntity.RemoveQueuedEntities();
// RunMapCleanupIfNeeded();
LuaGame.RunMapCleanupIfNeeded();
if (g_Lua == null || GarrysMod.g_LuaManager == null || gGM == null)
return;

Expand Down Expand Up @@ -81,7 +81,7 @@ public override void FrameUpdatePreEntityThink() {
garrysmod.Think();
// RemoveQueuedRecipientFilters();
LuaEntity.RemoveQueuedEntities();
// RunMapCleanupIfNeeded();
LuaGame.RunMapCleanupIfNeeded();
if (gpGlobals.TickCount != LastTick) {
LastTick = gpGlobals.TickCount;
gGM.Call((int)LUA_POOLEDSTRING.Tick);
Expand Down
Loading