diff --git a/Game.Client/GarrysMod/LuaCam.cs b/Game.Client/GarrysMod/LuaCam.cs index 0ef41617..eb22f1ff 100644 --- a/Game.Client/GarrysMod/LuaCam.cs +++ b/Game.Client/GarrysMod/LuaCam.cs @@ -42,7 +42,7 @@ static int Start(ILuaInterface lua) { if (data.GetMemberStr("type", "3D")!.StartsWith('2')) { using MatRenderContextPtr renderContext = new(materials); - ClientModeShared.SetupVGuiMatrices(true, renderContext); + ClientModeShared.SetupVGuiMatrices(true, renderContext.Context); ((ClientModeShared)clientMode).SetupGModSurface(true); renderContext.OverrideAlphaWriteEnable(true, true); Start2DCount++; @@ -140,7 +140,7 @@ static int End2D(ILuaInterface lua) { using MatRenderContextPtr renderContext = new(materials); renderContext.OverrideAlphaWriteEnable(false, false); ((ClientModeShared)clientMode).SetupGModSurface(false); - ClientModeShared.SetupVGuiMatrices(false, renderContext); + ClientModeShared.SetupVGuiMatrices(false, renderContext.Context); return 0; } diff --git a/Game.Client/GarrysMod/SpawnIcon.cs b/Game.Client/GarrysMod/SpawnIcon.cs index 5a3f01b5..0cdb9348 100644 --- a/Game.Client/GarrysMod/SpawnIcon.cs +++ b/Game.Client/GarrysMod/SpawnIcon.cs @@ -333,15 +333,15 @@ void Render() { renderContext.ClearColor4ub(255, 0, 0, 0); renderContext.ClearBuffers(true, true); - RenderPass(red, ent, renderContext, viewSetup.Width, viewSetup.Height); + RenderPass(red, ent, renderContext.Context, viewSetup.Width, viewSetup.Height); renderContext.ClearColor4ub(0, 255, 0, 0); renderContext.ClearBuffers(true, true); - RenderPass(green, ent, renderContext, viewSetup.Width, viewSetup.Height); + RenderPass(green, ent, renderContext.Context, viewSetup.Width, viewSetup.Height); renderContext.ClearColor4ub(0, 0, 255, 0); renderContext.ClearBuffers(true, true); - RenderPass(blue, ent, renderContext, viewSetup.Width, viewSetup.Height); + RenderPass(blue, ent, renderContext.Context, viewSetup.Width, viewSetup.Height); CombinePasses(red, green, blue, viewSetup.Width, viewSetup.Height); diff --git a/Game.Client/HLClient.cs b/Game.Client/HLClient.cs index 29b1bdf4..1c56b8c2 100644 --- a/Game.Client/HLClient.cs +++ b/Game.Client/HLClient.cs @@ -503,7 +503,7 @@ public void HudUpdate(bool active) { gHUD.UpdateHud(active); - BaseAnimating.AutoAllowBoneAccess boneAccess = new(true, true); + using BaseAnimating.AutoAllowBoneAccess boneAccess = new(true, true); IGameSystem.UpdateAllSystems(frameTime); vgui!.GetAnimationController().UpdateAnimations(gpGlobals.CurTime); diff --git a/Game.Client/View.cs b/Game.Client/View.cs index ba454138..d681296b 100644 --- a/Game.Client/View.cs +++ b/Game.Client/View.cs @@ -418,10 +418,11 @@ public void RenderView(in ViewSetup viewRender, ClearFlags clearFlags, RenderVie SkyboxVisibility skyboxVisible = SkyboxVisibility.NotVisible; { - SkyboxView skyView = new SkyboxView(this); + SkyboxView skyView = FreeSkyboxViews.Count > 0 ? FreeSkyboxViews.Pop() : new SkyboxView(this); if ((drew3dSkybox = skyView.Setup(in viewRender, ref clearFlags, ref skyboxVisible)) != false) AddViewToScene(skyView); skyView.ReleaseLists(); + FreeSkyboxViews.Push(skyView); } if ((clearFlags & ClearFlags.ClearColor) == 0) { @@ -515,7 +516,7 @@ public void RenderView(in ViewSetup viewRender, ClearFlags clearFlags, RenderVie // VGui_PostRender(); using (renderContext = new MatRenderContextPtr(materials)) { #if GMOD_DLL - ((ClientModeShared)clientMode).PostRenderVGui(renderContext); + ((ClientModeShared)clientMode).PostRenderVGui(renderContext.Context); #endif if (pTexture != null) { // renderContext.OverrideAlphaWriteEnable(false, true); @@ -743,10 +744,11 @@ private void DrawWorldAndEntities(bool drawSkybox, in ViewSetup viewIn, ClearFla DetermineWaterRenderInfo(in fogVolumeInfo, out WaterRenderInfo info); if (info.CheapWater) { - SimpleWorldView noWaterView = new SimpleWorldView(this); + SimpleWorldView noWaterView = FreeSimpleWorldViews.Count > 0 ? FreeSimpleWorldViews.Pop() : new SimpleWorldView(this); noWaterView.Setup(in viewIn, clearFlags, drawSkybox, in fogVolumeInfo, in info); AddViewToScene(noWaterView); noWaterView.ReleaseLists(); + FreeSimpleWorldViews.Push(noWaterView); return; } @@ -754,19 +756,26 @@ private void DrawWorldAndEntities(bool drawSkybox, in ViewSetup viewIn, ClearFla fogVolumeInfo.VisibleFogVolumeLeaf = -1; if (!fogVolumeInfo.EyeInFogVolume) { - AboveWaterView aboveWaterView = new AboveWaterView(this); + AboveWaterView aboveWaterView = FreeAboveWaterViews.Count > 0 ? FreeAboveWaterViews.Pop() : new AboveWaterView(this); aboveWaterView.Setup(in viewIn, drawSkybox, in fogVolumeInfo, in info); AddViewToScene(aboveWaterView); aboveWaterView.ReleaseLists(); + FreeAboveWaterViews.Push(aboveWaterView); } else { - UnderWaterView underWaterView = new UnderWaterView(this); + UnderWaterView underWaterView = FreeUnderWaterViews.Count > 0 ? FreeUnderWaterViews.Pop() : new UnderWaterView(this); underWaterView.Setup(in viewIn, drawSkybox, in fogVolumeInfo, in info); AddViewToScene(underWaterView); underWaterView.ReleaseLists(); + FreeUnderWaterViews.Push(underWaterView); } } + readonly Stack FreeSkyboxViews = []; + readonly Stack FreeSimpleWorldViews = []; + readonly Stack FreeAboveWaterViews = []; + readonly Stack FreeUnderWaterViews = []; + public static bool DoesViewPlaneIntersectWater(float waterZ, int leafWaterDataID) { if (leafWaterDataID == -1) return false; diff --git a/Game.Client/ViewBeams.cs b/Game.Client/ViewBeams.cs index 3972b504..d692d912 100644 --- a/Game.Client/ViewBeams.cs +++ b/Game.Client/ViewBeams.cs @@ -875,7 +875,7 @@ private void DrawSegs(int noise_divisions, ReadOnlySpan noise, Model spri // Specify all the segments. using MatRenderContextPtr renderContext = new(materials); BeamSegDraw segDraw = new(); - segDraw.Start(renderContext, segments, null); + segDraw.Start(renderContext.Context, segments, null); for (i = 0; i < segments; i++) { Assert(noiseIndex < (noise_divisions << 16)); diff --git a/Game.Client/ViewRender.cs b/Game.Client/ViewRender.cs index ac91cf65..a6fc1939 100644 --- a/Game.Client/ViewRender.cs +++ b/Game.Client/ViewRender.cs @@ -794,6 +794,7 @@ public virtual void ReleaseLists() { WorldRenderList?.Release(); WorldRenderList = null; ClientRenderablesList.Shared.Free(RenderablesList); + RenderablesList = null!; } public override DrawFlags GetDrawFlags() { return DrawFlags; diff --git a/Game.Server/Player.cs b/Game.Server/Player.cs index 0da87e0a..82343051 100644 --- a/Game.Server/Player.cs +++ b/Game.Server/Player.cs @@ -18,6 +18,7 @@ using System.Diagnostics; using System.Numerics; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; namespace Game.Server; @@ -426,6 +427,7 @@ public void SetPhysicsFlag(PlayerPhysFlag flag, bool set) { public TimeUnit_t LerpTime; public bool LagCompensation; public bool PredictWeapons; + readonly List AvailableCommandsBuf = []; public static void SendProxy_CropFlagsToPlayerFlagBitsLength(SendProp prop, object instance, IFieldAccessor field, ref DVariant outData, int element, int objectID) { int mask = (1 << Constants.PLAYER_FLAG_BITS) - 1; @@ -943,7 +945,7 @@ public virtual void ImpulseCommands() { } if (tr.Fraction != 1.0) { // line hit something, so paint a decal - // todo + // todo } break; @@ -1219,7 +1221,7 @@ CommandContext RemoveAllCommandContextsExceptNewest() { void RemoveAllCommandContexts() => CommandContext.Clear(); - void ReplaceContextCommands(CommandContext ctx, UserCmd[] cmds, int commands) { + void ReplaceContextCommands(CommandContext ctx, ReadOnlySpan cmds, int commands) { ctx.Cmds.Clear(); ctx.NumCmds = commands; @@ -1386,7 +1388,7 @@ public override void PhysicsSimulate() { int command_context_count = GetCommandContextCount(); - List vecAvailCommands = []; + AvailableCommandsBuf.Clear(); for (int context_number = 0; context_number < command_context_count; context_number++) { CommandContext ctx = GetCommandContext(context_number); @@ -1404,32 +1406,32 @@ public override void PhysicsSimulate() { while (droppedcmds > numbackup) { UserCmd lastCmd = GetLastUserCommand(); lastCmd.CommandNumber++; - vecAvailCommands.Add(lastCmd); + AvailableCommandsBuf.Add(lastCmd); droppedcmds--; } while (droppedcmds > 0) { int cmdnum = ctx.NumCmds + droppedcmds - 1; - vecAvailCommands.Add(ctx.Cmds[cmdnum]); + AvailableCommandsBuf.Add(ctx.Cmds[cmdnum]); droppedcmds--; } } for (int i = ctx.NumCmds - 1; i >= 0; i--) - vecAvailCommands.Add(ctx.Cmds[i]); + AvailableCommandsBuf.Add(ctx.Cmds[i]); LastCmd = ctx.Cmds[ctx.Cmds.Count - 1]; } int commandLimit = IsSimulatingOnAlternateTicks() ? 2 : 1; - int commandsToRun = vecAvailCommands.Count; - if (gpGlobals.SimTicksThisFrame >= commandLimit && vecAvailCommands.Count > commandLimit) { - int commandsToRollOver = Math.Min(vecAvailCommands.Count, (gpGlobals.SimTicksThisFrame - 1)); - commandsToRun = vecAvailCommands.Count - commandsToRollOver; + int commandsToRun = AvailableCommandsBuf.Count; + if (gpGlobals.SimTicksThisFrame >= commandLimit && AvailableCommandsBuf.Count > commandLimit) { + int commandsToRollOver = Math.Min(AvailableCommandsBuf.Count, (gpGlobals.SimTicksThisFrame - 1)); + commandsToRun = AvailableCommandsBuf.Count - commandsToRollOver; Assert(commandsToRun >= 0); if (commandsToRollOver > 0) { CommandContext ctx = RemoveAllCommandContextsExceptNewest(); - ReplaceContextCommands(ctx, [.. vecAvailCommands.GetRange(vecAvailCommands.Count - commandsToRollOver, commandsToRollOver)], commandsToRollOver); + ReplaceContextCommands(ctx, CollectionsMarshal.AsSpan(AvailableCommandsBuf).Slice(AvailableCommandsBuf.Count - commandsToRollOver, commandsToRollOver), commandsToRollOver); } else RemoveAllCommandContexts(); @@ -1458,7 +1460,7 @@ public override void PhysicsSimulate() { IPredictionSystem.SuppressHostEvents(this); for (int i = 0; i < commandsToRun; ++i) { - PlayerRunCommand(vecAvailCommands[i], MoveHelperServer.s_MoveHelperServer); + PlayerRunCommand(AvailableCommandsBuf[i], MoveHelperServer.s_MoveHelperServer); if (PhysicsController != null) { UpdateVPhysicsPosition(NewVPhysicsPosition, NewVPhysicsVelocity, (float)vphysicsArrivalTime); diff --git a/Source.Common/MaterialSystem/IMaterialSystem.cs b/Source.Common/MaterialSystem/IMaterialSystem.cs index 68b29bf0..226ded16 100644 --- a/Source.Common/MaterialSystem/IMaterialSystem.cs +++ b/Source.Common/MaterialSystem/IMaterialSystem.cs @@ -1286,7 +1286,7 @@ void DrawScreenSpaceRectangle( #endif } -public readonly struct MatRenderContextPtr : IDisposable, IMatRenderContext +public readonly ref struct MatRenderContextPtr : IDisposable { public readonly IMatRenderContext Context; diff --git a/Source.Engine/DtLocalTransfer.cs b/Source.Engine/DtLocalTransfer.cs index e694f3c8..48043c57 100644 --- a/Source.Engine/DtLocalTransfer.cs +++ b/Source.Engine/DtLocalTransfer.cs @@ -31,6 +31,9 @@ public static class LocalTransfer "(SP only) - show entities that were copied using small optimized lists (FL_EDICT_PARTIAL_CHANGE)." ); + static ServerDatatableStack? s_ServerStack; + static ClientDatatableStack? s_ClientStack; + public static void TransferEntity(BaseEdict edict, SendTable sendTable, object srcEnt, RecvTable recvTable, object destEnt, bool newlyCreated, bool justEnteredPVS, int objectID) { TotalEntChanges++; EdictChangeInfo changeInfo = g_SharedChangeInfo!.ChangeInfos[edict.GetChangeInfo()]; @@ -49,14 +52,18 @@ public static void TransferEntity(BaseEdict edict, SendTable sendTable, object s FastSortList(propIndices, changeOffsets); // Setup the structure to traverse the source tree. - ErrorIfNot(precalc != null, ($"SendTable_Encode: Missing precalc for SendTable {sendTable.NetTableName}.")); - ServerDatatableStack serverStack = new(precalc, srcEnt, objectID); + if (precalc == null) + Error($"SendTable_Encode: Missing precalc for SendTable {sendTable.NetTableName}."); + ServerDatatableStack serverStack = s_ServerStack ??= new(precalc, srcEnt, objectID); + serverStack.Reset(precalc, srcEnt, objectID); serverStack.Init(true); // Setup the structure to traverse the dest tree. RecvDecoder? decoder = recvTable.Decoder; - ErrorIfNot(decoder != null, ($"RecvTable_Decode: table '{recvTable.GetName()}' missing a decoder.")); - ClientDatatableStack clientStack = new(decoder, destEnt, objectID); + if (decoder == null) + Error($"RecvTable_Decode: table '{recvTable.GetName()}' missing a decoder."); + ClientDatatableStack clientStack = s_ClientStack ??= new(decoder, destEnt, objectID); + clientStack.Reset(decoder, destEnt, objectID); clientStack.Init(true); // Cool. We can get away with just transferring a few. @@ -86,14 +93,18 @@ public static void TransferEntity(BaseEdict edict, SendTable sendTable, object s else { // Setup the structure to traverse the source tree. SendTablePrecalc precalc = sendTable.Precalc!; - ErrorIfNot(precalc != null, ($"SendTable_Encode: Missing precalc for SendTable {sendTable.NetTableName}.")); - ServerDatatableStack serverStack = new(precalc, srcEnt, objectID); + if (precalc == null) + Error($"SendTable_Encode: Missing precalc for SendTable {sendTable.NetTableName}."); + ServerDatatableStack serverStack = s_ServerStack ??= new(precalc, srcEnt, objectID); + serverStack.Reset(precalc, srcEnt, objectID); serverStack.Init(); // Setup the structure to traverse the dest tree. RecvDecoder? decoder = recvTable.Decoder; - ErrorIfNot(decoder != null, ($"RecvTable_Decode: table '{recvTable.GetName()}' missing a decoder.")); - ClientDatatableStack clientStack = new(decoder, destEnt, objectID); + if (decoder == null) + Error($"RecvTable_Decode: table '{recvTable.GetName()}' missing a decoder."); + ClientDatatableStack clientStack = s_ClientStack ??= new(decoder, destEnt, objectID); + clientStack.Reset(decoder, destEnt, objectID); clientStack.Init(); AddToPartialChangeEntsList(Array.IndexOf(sv.Edicts, edict), false); diff --git a/Source.Engine/EngineRecvTable.cs b/Source.Engine/EngineRecvTable.cs index 188a949c..d33aeaf1 100644 --- a/Source.Engine/EngineRecvTable.cs +++ b/Source.Engine/EngineRecvTable.cs @@ -133,6 +133,15 @@ public DatatableStack(SendTablePrecalc precalc, object instance, int objectID) { ObjectID = objectID; } + public void Reset(SendTablePrecalc precalc, object instance, int objectID) { + Precalc = precalc; + Instance = instance; + ObjectID = objectID; + CurPropIndex = 0; + CurProp = null; + Initted = false; + } + protected static readonly object Uncomputed = new(); public void Init(bool explicitRoutes = false) { @@ -227,12 +236,17 @@ public int GetObjectID() { public class ClientDatatableStack : DatatableStack { - readonly RecvDecoder Decoder; + RecvDecoder Decoder; public ClientDatatableStack(RecvDecoder decoder, object instance, int objectID) : base(decoder.Precalc, instance, objectID) { Decoder = decoder; } + public void Reset(RecvDecoder decoder, object instance, int objectID) { + Decoder = decoder; + Reset(decoder.Precalc, instance, objectID); + } + public override void RecurseAndCallProxies(SendNode node, object? instance) { Proxies[node.GetRecursiveProxyIndex()] = instance; diff --git a/Source.Engine/FrameSnapshot.cs b/Source.Engine/FrameSnapshot.cs index d69a52eb..4007d985 100644 --- a/Source.Engine/FrameSnapshot.cs +++ b/Source.Engine/FrameSnapshot.cs @@ -1,13 +1,15 @@  using CommunityToolkit.HighPerformance; +using System.Buffers; + using Source.Common; using Source.Common.Commands; using Source.Common.Engine; namespace Source.Engine; -public class FrameSnapshotEntry +public struct FrameSnapshotEntry { public ServerClass? Class; public int SerialNumber; @@ -45,6 +47,10 @@ public void ReleaseReference() { volatile int References; public void Dispose() { + if (ValidEntities != null) + ArrayPool.Shared.Return(ValidEntities); + if (Entities != null) + ArrayPool.Shared.Return(Entities); ValidEntities = null; Entities = null; TempEntities = null; @@ -95,15 +101,12 @@ public FrameSnapshot CreateEmptySnapshot(int tickcount, int maxEntities) { snap.NumEntities = maxEntities; snap.NumValidEntities = 0; snap.ValidEntities = null; - snap.Entities = new FrameSnapshotEntry[maxEntities]; - - for (int i = 0; i < maxEntities; i++) { - snap.Entities[i] = new FrameSnapshotEntry { - Class = null, - SerialNumber = -1, - PackedData = INVALID_PACKED_ENTITY_HANDLE - }; - } + snap.Entities = ArrayPool.Shared.Rent(maxEntities); + snap.Entities.AsSpan(0, maxEntities).Fill(new FrameSnapshotEntry { + Class = null, + SerialNumber = -1, + PackedData = INVALID_PACKED_ENTITY_HANDLE + }); FrameSnapshots.AddLast(snap); snap.ListIndex = FrameSnapshots.Count - 1; @@ -111,16 +114,15 @@ public FrameSnapshot CreateEmptySnapshot(int tickcount, int maxEntities) { } public FrameSnapshot TakeTickSnapshot(int tickcount) { - Span validEntities = stackalloc ushort[Constants.MAX_EDICTS]; - FrameSnapshot snap = CreateEmptySnapshot(tickcount, sv.NumEdicts); + ushort[] validEntities = ArrayPool.Shared.Rent(sv.NumEdicts); int maxclients = sv.GetClientCount(); int numValid = 0; for (int i = 0; i < sv.NumEdicts; i++) { Edict edict = sv.Edicts![i]; - FrameSnapshotEntry entry = snap.Entities![i]; + ref FrameSnapshotEntry entry = ref snap.Entities![i]; IServerUnknown? unk = edict.GetUnknown(); @@ -145,7 +147,7 @@ public FrameSnapshot TakeTickSnapshot(int tickcount) { } snap.NumValidEntities = numValid; - snap.ValidEntities = validEntities[..numValid].ToArray(); + snap.ValidEntities = validEntities; snap.ExplicitDeleteSlots.AddRange(ExplicitDeleteSlots); ExplicitDeleteSlots.Clear(); diff --git a/Source.Engine/GLRSurf.cs b/Source.Engine/GLRSurf.cs index 9f1a20f8..5635e5db 100644 --- a/Source.Engine/GLRSurf.cs +++ b/Source.Engine/GLRSurf.cs @@ -678,7 +678,7 @@ static void Shader_DrawChainsWireframe(List surfaceList) { for (int i = 0; i < surfaceList.Count; i++) { SurfaceHandle_t surfID = surfaceList[i]; Assert(!ModelLoader.SurfaceHasDispInfo(ref ModelLoader.SurfaceHandleFromIndex(surfID))); - Shader_DrawSurfaceDynamic(renderContext, surfID, false); + Shader_DrawSurfaceDynamic(renderContext.Context, surfID, false); } } break; @@ -760,7 +760,7 @@ public static void Shader_DrawDispChain(int sortGroup, in MSurfaceSortList list, count += group.SurfaceCount; if (count != 0) { - SurfaceHandle_t[] pList = new SurfaceHandle_t[count]; + Span pList = stackalloc SurfaceHandle_t[count]; int i = 0; foreach (SurfaceSortGroup group in groupList) { for (short blockIndex = group.ListHead; blockIndex != -1; blockIndex = list.GetSurfaceBlock(blockIndex).NextBlock) { @@ -917,7 +917,7 @@ static void Shader_WorldEnd(WorldRenderList renderList, DrawWorldListFlags flags // overlaymgr todo #if !SWDS - Render.DecalSurfaceDraw(renderCtx, sortGroup); + Render.DecalSurfaceDraw(renderCtx.Context, sortGroup); #endif g_ShadowMgr.DrawFlashlightDecals(sortGroup, flashlightMask); @@ -950,6 +950,7 @@ public static bool Shader_LeafContainsTranslucentSurfaces(IWorldRenderList rende return false; } + static readonly List s_TranslucentSurfaceList = []; public static void Shader_DrawTranslucentSurfaces(IWorldRenderList renderListIn, int sortIndex, uint flags, bool shadowDepth) { if (!r_drawtranslucentworld.GetBool()) return; @@ -964,7 +965,7 @@ public static void Shader_DrawTranslucentSurfaces(IWorldRenderList renderListIn, skipLight = true; } - List surfaceList = []; + List surfaceList = s_TranslucentSurfaceList; for (int i = 0; i < (int)MatSortGroup.Max; ++i) { if ((flags & (1u << i)) == 0) continue; @@ -987,7 +988,7 @@ public static void Shader_DrawTranslucentSurfaces(IWorldRenderList renderListIn, if (!skipLight) renderContext.BindLightmapPage(MatSys.MaterialSortInfoArray![ModelLoader.MSurf_MaterialSortID(ref surface)].LightmapPageID); - Shader_DrawSurfaceDynamic(renderContext, surfID, false); + Shader_DrawSurfaceDynamic(renderContext.Context, surfID, false); // todo } @@ -1351,7 +1352,7 @@ public static void R_DrawBrushModel(IClientEntity? baseEntity, Model? model, in } using MatRenderContextPtr renderContext = new(materials); - using BrushModelTransform brushTransform = new(origin, angles, renderContext); + using BrushModelTransform brushTransform = new(origin, angles, renderContext.Context); Assert(model!.Brush.FirstModelSurface != 0); @@ -1368,7 +1369,7 @@ public static void R_DrawBrushModel(IClientEntity? baseEntity, Model? model, in else if (drawOpaque) g_BrushBatchRenderer.DrawOpaqueBrushModel(baseEntity, model, origin, depthMode); - Shader_BrushEnd(renderContext, brushTransform.GetNonIdentityMatrix(), model, depthMode != RenderDepthMode.Normal, baseEntity); + Shader_BrushEnd(renderContext.Context, brushTransform.GetNonIdentityMatrix(), model, depthMode != RenderDepthMode.Normal, baseEntity); if (r_drawbrushmodels.GetInt() == 2) { g_ShaderDebug.Wireframe = wireframe; @@ -1384,7 +1385,7 @@ public static void R_DrawBrushModelShadow(IClientRenderable renderable) { QAngle angles = renderable.GetRenderAngles(); using MatRenderContextPtr renderContext = new(materials); - using BrushModelTransform brushTransform = new(origin, angles, renderContext); + using BrushModelTransform brushTransform = new(origin, angles, renderContext.Context); g_BrushBatchRenderer.DrawBrushModelShadow(model, renderable); } public static void R_DrawIdentityBrushModel(IWorldRenderList renderListIn, Model? model) => throw new NotImplementedException(); @@ -1986,7 +1987,7 @@ private void DrawTransLists(ref TransRender renderT, object? proxyData) { } #if !SWDS - Render.DecalSurfaceDraw(renderContext, BRUSHMODEL_DECAL_SORT_GROUP); + Render.DecalSurfaceDraw(renderContext.Context, BRUSHMODEL_DECAL_SORT_GROUP); #endif #if !SWDS diff --git a/Source.Engine/Lightcache.cs b/Source.Engine/Lightcache.cs index 5bd9c484..c7861523 100644 --- a/Source.Engine/Lightcache.cs +++ b/Source.Engine/Lightcache.cs @@ -9,6 +9,7 @@ using System.Numerics; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; namespace Source.Engine; @@ -90,7 +91,7 @@ public enum HackLightCacheFlags HasDoneStaticLighting = 0x4 } -public class LightingStateInfo +public struct LightingStateInfo { public InlineArrayMaxLocalLights Illum; public bool LightingStateHasSkylight; @@ -105,22 +106,17 @@ public void Clear() { Illum[i] = 0; LightingStateHasSkylight = false; } - - public void CopyFrom(LightingStateInfo src) { - for (int i = 0; i < Render.MAXLOCALLIGHTS; i++) - Illum[i] = src.Illum[i]; - LightingStateHasSkylight = src.LightingStateHasSkylight; - } } [InlineArray(BaseLightCache.MAX_LIGHTSTYLE_BYTES)] public struct InlineArrayLightstyleBytes { public byte item; } -public class BaseLightCache : LightingStateInfo +public struct BaseLightCache { public const int MAX_LIGHTSTYLE_BITS = BSPFileCommon.MAX_LIGHTSTYLES; public const int MAX_LIGHTSTYLE_BYTES = (MAX_LIGHTSTYLE_BITS + 7) / 8; public BaseLightCache() { + Info = new(); LightingOrigin = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); LastFrameUpdatedLightStyles = -1; LastFrameUpdatedDynamicLighting = -1; @@ -129,10 +125,11 @@ public BaseLightCache() { EnvCubemapTexture = null; } - public bool HasLightStyle() => (LightingFlags & (int)(HackLightCacheFlags.HasSwitchableLightStyle | HackLightCacheFlags.HasNonSwitchableLightStyle)) != 0; - public bool HasSwitchableLightStyle() => (LightingFlags & (int)HackLightCacheFlags.HasSwitchableLightStyle) != 0; - public bool HasNonSwitchableLightStyle() => (LightingFlags & (int)HackLightCacheFlags.HasNonSwitchableLightStyle) != 0; + public readonly bool HasLightStyle() => (LightingFlags & (int)(HackLightCacheFlags.HasSwitchableLightStyle | HackLightCacheFlags.HasNonSwitchableLightStyle)) != 0; + public readonly bool HasSwitchableLightStyle() => (LightingFlags & (int)HackLightCacheFlags.HasSwitchableLightStyle) != 0; + public readonly bool HasNonSwitchableLightStyle() => (LightingFlags & (int)HackLightCacheFlags.HasNonSwitchableLightStyle) != 0; + public LightingStateInfo Info; public LightingState StaticLightingState; public LightingState LightStyleLightingState; public int LastFrameUpdatedLightStyles; @@ -145,18 +142,21 @@ public BaseLightCache() { public ITexture? EnvCubemapTexture; } -public class LightCache : BaseLightCache +public struct LightCache { public LightCache() { + Base = new(); + StaticPrecalcLightingStateInfo = new(); StaticPrecalcNumLocalLights = 0; Next = Bucket = 0xFFFF; LruPrev = LruNext = 0xFFFF; X = Y = Z = int.MinValue; } + public BaseLightCache Base; public InlineArrayMaxLocalLights StaticPrecalcLocalLight; public ushort StaticPrecalcNumLocalLights; - public LightingStateInfo StaticPrecalcLightingStateInfo = new(); + public LightingStateInfo StaticPrecalcLightingStateInfo; public ushort Next; public ushort Bucket; public ushort LruPrev; @@ -165,17 +165,20 @@ public LightCache() { public int Index; } -public class PropLightcache : BaseLightCache +public struct PropLightcache { + public BaseLightCache Base; public uint Flags; public int DLightActive; public int DLightMarkFrame; - public List LightStyleWorldLights = []; + public List LightStyleWorldLights; public int SwitchableLightFrame; public Vector3 Mins; public Vector3 Maxs; public PropLightcache() { + Base = new(); + LightStyleWorldLights = []; Flags = 0; DLightActive = 0; DLightMarkFrame = 0; @@ -184,7 +187,7 @@ public PropLightcache() { Maxs = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); } - public bool HasDlights() => DLightActive != 0; + public readonly bool HasDlights() => DLightActive != 0; } public class LightVecState @@ -241,9 +244,9 @@ public partial class Render private static int FrameIndex = 0; public static int r_framecount = 0; - private static ushort GetLightCacheIndex(LightCache cache) => (ushort)cache.Index; - private static LightCache GetLightLRUHead() => LightCaches[LIGHT_LRU_HEAD_INDEX]; - private static LightCache GetLightLRUTail() => LightCaches[LIGHT_LRU_TAIL_INDEX]; + private static ushort GetLightCacheIndex(in LightCache cache) => (ushort)cache.Index; + private static ref LightCache GetLightLRUHead() => ref LightCaches[LIGHT_LRU_HEAD_INDEX]; + private static ref LightCache GetLightLRUTail() => ref LightCaches[LIGHT_LRU_TAIL_INDEX]; public void R_StudioInitLightingCache() { int i; @@ -281,7 +284,7 @@ public void R_StudioInitLightingCache() { InvalidateStaticLightingCache(); } - private static void LightcacheMark(LightCache cache) { + private static void LightcacheMark(ref LightCache cache) { if (cache.LruNext == 0 && cache.LruPrev == 0) return; @@ -298,7 +301,7 @@ private static void LightcacheMark(LightCache cache) { GetLightLRUTail().LruPrev = GetLightCacheIndex(cache); } - private static void LightcacheUnlink(LightCache cache) { + private static void LightcacheUnlink(ref LightCache cache) { ushort bucket = cache.Bucket; if (bucket == 0xFFFF) @@ -324,15 +327,15 @@ private static void LightcacheUnlink(LightCache cache) { } } - private static LightCache LightcacheGetLRU() { - LightCache cache = LightCaches[GetLightLRUHead().LruNext]; + private static ref LightCache LightcacheGetLRU() { + ref LightCache cache = ref LightCaches[GetLightLRUHead().LruNext]; - LightcacheMark(cache); + LightcacheMark(ref cache); - LightcacheUnlink(cache); + LightcacheUnlink(ref cache); - cache.Leaf = -1; - return cache; + cache.Base.Leaf = -1; + return ref cache; } private static int LightcacheHashKey(int x, int y, int z, int leaf) { @@ -341,28 +344,28 @@ private static int LightcacheHashKey(int x, int y, int z, int leaf) { return (int)key; } - private static LightCache? FindInCache(int bucket, int x, int y, int z, int leaf) { + private static ref LightCache FindInCache(int bucket, int x, int y, int z, int leaf) { ushort cacheIndex; for (cacheIndex = LightBuckets[bucket]; cacheIndex != 0xFFFF; cacheIndex = LightCaches[cacheIndex].Next) { - LightCache cache = LightCaches[cacheIndex]; + ref LightCache cache = ref LightCaches[cacheIndex]; - if (cache.X == x && cache.Y == y && cache.Z == z && cache.Leaf == leaf) - return cache; + if (cache.X == x && cache.Y == y && cache.Z == z && cache.Base.Leaf == leaf) + return ref cache; } - return null; + return ref Unsafe.NullRef(); } - private static void LinkToBucket(int bucket, LightCache cache) { + private static void LinkToBucket(int bucket, ref LightCache cache) { cache.Next = LightBuckets[bucket]; - LightBuckets[bucket] = GetLightCacheIndex(cache); + LightBuckets[bucket] = GetLightCacheIndex(in cache); cache.Bucket = (ushort)bucket; } - private static LightCache NewLightcacheEntry(int bucket) { - LightCache cache = LightcacheGetLRU(); - LinkToBucket(bucket, cache); - return cache; + private static ref LightCache NewLightcacheEntry(int bucket) { + ref LightCache cache = ref LightcacheGetLRU(); + LinkToBucket(bucket, ref cache); + return ref cache; } private static void ComputeLightcacheBounds(in Vector3 vecOrigin, out Vector3 mins, out Vector3 maxs) { @@ -410,30 +413,30 @@ private static bool AllowFullCacheMiss(LightCacheFlags flags) { return true; } - private static LightCache? FindNearestCache(int x, int y, int z, int leafIndex) { + private static ref LightCache FindNearestCache(int x, int y, int z, int leafIndex) { int bestDist = int.MaxValue; - LightCache? best = null; + ref LightCache best = ref Unsafe.NullRef(); ushort current = GetLightLRUTail().LruPrev; while (current != LIGHT_LRU_HEAD_INDEX) { - LightCache cache = LightCaches[current]; + ref LightCache cache = ref LightCaches[current]; int dist = 0; int dx = Math.Abs(cache.X - x); int dy = Math.Abs(cache.Y - y); int dz = Math.Abs(cache.Z - z); - if (leafIndex != cache.Leaf) + if (leafIndex != cache.Base.Leaf) dist += 2; dist = Math.Max(dist, dx); dist = Math.Max(dist, dy); dist = Math.Max(dist, dz); if (dist < bestDist) { - best = cache; + best = ref cache; bestDist = dist; if (dist <= 1) break; } current = cache.LruPrev; } - return best; + return ref best; } private static void ComputeAmbientFromLeaf(in Vector3 start, int leafID, Span lightBoxColor, ref bool addedLeafAmbientCube) { @@ -814,7 +817,7 @@ private void ComputeAmbientFromSphericalSamples(in Vector3 start, Span #endif } - private static bool IsCachedLightStylesValid(BaseLightCache cache) { + private static bool IsCachedLightStylesValid(in BaseLightCache cache) { if (!cache.HasLightStyle()) return true; @@ -828,7 +831,7 @@ private static bool IsCachedLightStylesValid(BaseLightCache cache) { return true; } - private void AdjustLightCacheOrigin(LightCache cache, in Vector3 origin, int originLeaf) { + private void AdjustLightCacheOrigin(ref LightCache cache, in Vector3 origin, int originLeaf) { Trace tr; Ray ray = default; TraceFilterWorldOnly worldTraceFilter = new(); @@ -855,7 +858,7 @@ private void AdjustLightCacheOrigin(LightCache cache, in Vector3 origin, int ori } if (traceToCenter && tr.StartSolid) - MathLib.VectorCopy(origin, out cache.LightingOrigin); + MathLib.VectorCopy(origin, out cache.Base.LightingOrigin); else if (!traceToCenter || tr.Fraction < 1) { center.X = (cacheMins.X + cacheMaxs.X) * 0.5f; center.Y = (cacheMins.Y + cacheMaxs.Y) * 0.5f; @@ -865,12 +868,12 @@ private void AdjustLightCacheOrigin(LightCache cache, in Vector3 origin, int ori ray.Init(origin, center); engineTrace.TraceRay(in ray, Mask.Opaque, ref worldTraceFilter, out tr); if (tr.Fraction < 1) - MathLib.VectorCopy(origin, out cache.LightingOrigin); + MathLib.VectorCopy(origin, out cache.Base.LightingOrigin); else - MathLib.VectorCopy(center, out cache.LightingOrigin); + MathLib.VectorCopy(center, out cache.Base.LightingOrigin); } else { - MathLib.VectorCopy(center, out cache.LightingOrigin); + MathLib.VectorCopy(center, out cache.Base.LightingOrigin); } } @@ -895,29 +898,29 @@ private void AdjustLightCacheOrigin(LightCache cache, in Vector3 origin, int ori return null; } - private ReadOnlySpan ComputeStaticLightingForCacheEntry(BaseLightCache cache, scoped in Vector3 origin, int leaf, bool staticProp = false) { + private ReadOnlySpan ComputeStaticLightingForCacheEntry(ref BaseLightCache cache, scoped in Vector3 origin, int leaf, bool staticProp = false) { ReadOnlySpan vis = CM.ClusterPVS(CM.LeafCluster(leaf)); R_StudioGetAmbientLightForPoint(leaf, origin, cache.StaticLightingState.BoxColor, staticProp, out bool addedLeafAmbientCube); if (r_ambientlightingonly.GetInt() == 0) - AddStaticLighting(cache, origin, vis, staticProp, addedLeafAmbientCube); + AddStaticLighting(ref cache, origin, vis, staticProp, addedLeafAmbientCube); return vis; } - private ReadOnlySpan PrecalcLightingState(LightCache cache, ReadOnlySpan vis) { + private ReadOnlySpan PrecalcLightingState(ref LightCache cache, ReadOnlySpan vis) { LightingState lightingState = default; lightingState.ZeroLightingState(); cache.StaticPrecalcLightingStateInfo.Clear(); int i; - for (i = 0; i < cache.StaticLightingState.NumLights; i++) - vis = AddWorldLightToLightingState(cache.StaticLightingState.LocalLight[i], null, ref lightingState, cache.StaticPrecalcLightingStateInfo, cache.LightingOrigin, vis, true, false); + for (i = 0; i < cache.Base.StaticLightingState.NumLights; i++) + vis = AddWorldLightToLightingState(cache.Base.StaticLightingState.LocalLight[i], null, ref lightingState, ref cache.StaticPrecalcLightingStateInfo, cache.Base.LightingOrigin, vis, true, false); for (i = 0; i < 6; i++) - cache.StaticLightingState.BoxColor[i] += lightingState.BoxColor[i]; + cache.Base.StaticLightingState.BoxColor[i] += lightingState.BoxColor[i]; cache.StaticPrecalcNumLocalLights = (ushort)lightingState.NumLights; for (i = 0; i < cache.StaticPrecalcNumLocalLights; i++) @@ -926,22 +929,22 @@ private ReadOnlySpan PrecalcLightingState(LightCache cache, ReadOnlySpan AddLightingState(scoped ref LightingState dst, scoped in LightingState src, LightingStateInfo info, scoped in Vector3 bucketOrigin, ReadOnlySpan vis, bool dynamic, bool ignoreVis) { + private ReadOnlySpan AddLightingState(scoped ref LightingState dst, scoped in LightingState src, scoped ref LightingStateInfo info, scoped in Vector3 bucketOrigin, ReadOnlySpan vis, bool dynamic, bool ignoreVis) { int i; for (i = 0; i < src.NumLights; i++) - vis = AddWorldLightToLightingState(src.LocalLight[i], null, ref dst, info, bucketOrigin, vis, dynamic, ignoreVis); + vis = AddWorldLightToLightingState(src.LocalLight[i], null, ref dst, ref info, bucketOrigin, vis, dynamic, ignoreVis); for (i = 0; i < 6; i++) dst.BoxColor[i] += src.BoxColor[i]; @@ -1011,7 +1014,7 @@ private static void WorldLightFromDynamicLight(DLight dynamicLight, ref BSPDWorl static readonly BSPDWorldLight[] s_pDynamicLight = new BSPDWorldLight[Constants.MAX_DLIGHTS + Constants.MAX_ELIGHTS]; - private ReadOnlySpan AddDLights(LightingStateInfo info, scoped ref LightingState lightingState, scoped in Vector3 origin, int leaf, ReadOnlySpan vis) { + private ReadOnlySpan AddDLights(scoped ref LightingStateInfo info, scoped ref LightingState lightingState, scoped in Vector3 origin, int leaf, ReadOnlySpan vis) { if (!CL.ActiveDlights) return vis; @@ -1034,13 +1037,13 @@ private ReadOnlySpan AddDLights(LightingStateInfo info, scoped ref Lightin WorldLightFromDynamicLight(dl, ref s_pDynamicLight[i]); - vis = AddWorldLightToLightingState(new BSPDWorldLightPtr(s_pDynamicLight, i), null, ref lightingState, info, origin, vis, true, ignoreVis, ignoreVisTest); + vis = AddWorldLightToLightingState(new BSPDWorldLightPtr(s_pDynamicLight, i), null, ref lightingState, ref info, origin, vis, true, ignoreVis, ignoreVisTest); } return vis; } - private ReadOnlySpan AddELights(LightingStateInfo info, scoped ref LightingState lightingState, scoped in Vector3 origin, int leaf, ReadOnlySpan vis) { + private ReadOnlySpan AddELights(scoped ref LightingStateInfo info, scoped ref LightingState lightingState, scoped in Vector3 origin, int leaf, ReadOnlySpan vis) { if (!CL.ActiveElights) return vis; @@ -1063,7 +1066,7 @@ private ReadOnlySpan AddELights(LightingStateInfo info, scoped ref Lightin WorldLightFromDynamicLight(dl, ref s_pDynamicLight[Constants.MAX_DLIGHTS + i]); - vis = AddWorldLightToLightingState(new BSPDWorldLightPtr(s_pDynamicLight, Constants.MAX_DLIGHTS + i), null, ref lightingState, info, origin, vis, true, ignoreVis, ignoreVisTest); + vis = AddWorldLightToLightingState(new BSPDWorldLightPtr(s_pDynamicLight, Constants.MAX_DLIGHTS + i), null, ref lightingState, ref info, origin, vis, true, ignoreVis, ignoreVisTest); } return vis; @@ -1090,7 +1093,7 @@ private ReadOnlySpan FastRejectLightSource(bool ignoreVis, ReadOnlySpan AddWorldLightToLightingState(scoped in BSPDWorldLightPtr light, LightZBuffer[]? zBuf, scoped ref LightingState lightingState, LightingStateInfo info, scoped in Vector3 bucketOrigin, ReadOnlySpan vis, bool dynamic = false, bool ignoreVis = false, bool ignoreVisTest = false) { + private ReadOnlySpan AddWorldLightToLightingState(scoped in BSPDWorldLightPtr light, LightZBuffer[]? zBuf, scoped ref LightingState lightingState, scoped ref LightingStateInfo info, scoped in Vector3 bucketOrigin, ReadOnlySpan vis, bool dynamic = false, bool ignoreVis = false, bool ignoreVisTest = false) { Assert(lightingState.NumLights >= 0 && lightingState.NumLights <= MAXLOCALLIGHTS); BSPDWorldLightPtr worldLightPtr = light; @@ -1160,10 +1163,10 @@ private ReadOnlySpan AddWorldLightToLightingState(scoped in BSPDWorldLight return vis; } - private void AddStaticLighting(BaseLightCache cache, in Vector3 origin, ReadOnlySpan vis, bool staticProp, bool addedLeafAmbientCube) { + private void AddStaticLighting(ref BaseLightCache cache, in Vector3 origin, ReadOnlySpan vis, bool staticProp, bool addedLeafAmbientCube) { int i; cache.StaticLightingState.NumLights = 0; - cache.LightingStateHasSkylight = false; + cache.Info.LightingStateHasSkylight = false; if (!staticProp) { cache.LightingFlags &= ~(int)(HackLightCacheFlags.HasSwitchableLightStyle | HackLightCacheFlags.HasNonSwitchableLightStyle); @@ -1187,7 +1190,7 @@ private void AddStaticLighting(BaseLightCache cache, in Vector3 origin, ReadOnly } if (worldLight.Style == 0) - AddWorldLightToLightingState(wl, zBuf, ref cache.StaticLightingState, cache, origin, vis, false, false); + AddWorldLightToLightingState(wl, zBuf, ref cache.StaticLightingState, ref cache.Info, origin, vis, false, false); else { if (!staticProp) { int b = worldLight.Style >> 3; @@ -1209,7 +1212,7 @@ private void AddStaticLighting(BaseLightCache cache, in Vector3 origin, ReadOnly } } - private ReadOnlySpan ComputeLightStyles(LightCache cache, scoped ref LightingState lightingState, scoped in Vector3 origin, int leaf, ReadOnlySpan vis) { + private ReadOnlySpan ComputeLightStyles(ref LightCache cache, scoped ref LightingState lightingState, scoped in Vector3 origin, int leaf, ReadOnlySpan vis) { LightingStateInfo info = new(); lightingState.ZeroLightingState(); @@ -1221,33 +1224,33 @@ private ReadOnlySpan ComputeLightStyles(LightCache cache, scoped ref Light int b = worldLight.Style >> 3; int bit = worldLight.Style & 0x7; - if ((cache.Lightstyles[b] & (1 << bit)) == 0) + if ((cache.Base.Lightstyles[b] & (1 << bit)) == 0) continue; if (vis.IsEmpty) vis = CM.ClusterPVS(CM.LeafCluster(leaf)); - AddWorldLightToLightingState(wl, null, ref lightingState, info, origin, vis); + AddWorldLightToLightingState(wl, null, ref lightingState, ref info, origin, vis); } - cache.LastFrameUpdatedLightStyles = r_framecount; + cache.Base.LastFrameUpdatedLightStyles = r_framecount; return vis; } - private ReadOnlySpan ComputeDynamicLighting(LightCache cache, scoped ref LightingState lightingState, scoped in Vector3 lightingOrigin, int leaf, ReadOnlySpan vis) { - if (cache.LastFrameUpdatedDynamicLighting != r_framecount) { + private ReadOnlySpan ComputeDynamicLighting(ref LightCache cache, scoped ref LightingState lightingState, scoped in Vector3 lightingOrigin, int leaf, ReadOnlySpan vis) { + if (cache.Base.LastFrameUpdatedDynamicLighting != r_framecount) { LightingStateInfo info = new(); - cache.DynamicLightingState.ZeroLightingState(); + cache.Base.DynamicLightingState.ZeroLightingState(); - vis = AddDLights(info, ref cache.DynamicLightingState, lightingOrigin, leaf, vis); - vis = AddELights(info, ref cache.DynamicLightingState, lightingOrigin, leaf, vis); + vis = AddDLights(ref info, ref cache.Base.DynamicLightingState, lightingOrigin, leaf, vis); + vis = AddELights(ref info, ref cache.Base.DynamicLightingState, lightingOrigin, leaf, vis); - cache.LastFrameUpdatedDynamicLighting = r_framecount; + cache.Base.LastFrameUpdatedDynamicLighting = r_framecount; } - Assert(cache.DynamicLightingState.NumLights >= 0 && cache.DynamicLightingState.NumLights <= MAXLOCALLIGHTS); - if (!Unsafe.AreSame(ref lightingState, ref cache.DynamicLightingState)) - lightingState = cache.DynamicLightingState; + Assert(cache.Base.DynamicLightingState.NumLights >= 0 && cache.Base.DynamicLightingState.NumLights <= MAXLOCALLIGHTS); + if (!Unsafe.AreSame(ref lightingState, ref cache.Base.DynamicLightingState)) + lightingState = cache.Base.DynamicLightingState; return vis; } @@ -1266,13 +1269,13 @@ public void StudioCheckReinitLightingCache() { private readonly List PropCaches = []; public ref LightingState LightcacheGetStatic(LightCacheHandle_t cache, out ITexture? envCubemap, LightCacheFlags flags = LightCacheFlags.Static | LightCacheFlags.Dynamic | LightCacheFlags.LightStyle) { - PropLightcache pcache = PropCaches[(int)cache - 1]; + ref PropLightcache pcache = ref CollectionsMarshal.AsSpan(PropCaches)[(int)cache - 1]; - envCubemap = pcache.EnvCubemapTexture; + envCubemap = pcache.Base.EnvCubemapTexture; bool recalcStaticLighting = false; - bool recalcLightStyles = pcache.HasLightStyle() && pcache.LastFrameUpdatedLightStyles != r_framecount && !IsCachedLightStylesValid(pcache); - bool recalcDLights = pcache.HasDlights() && pcache.LastFrameUpdatedDynamicLighting != r_framecount; + bool recalcLightStyles = pcache.Base.HasLightStyle() && pcache.Base.LastFrameUpdatedLightStyles != r_framecount && !IsCachedLightStylesValid(in pcache.Base); + bool recalcDLights = pcache.HasDlights() && pcache.Base.LastFrameUpdatedDynamicLighting != r_framecount; if (flags != (LightCacheFlags)pcache.Flags) { recalcStaticLighting = true; @@ -1282,7 +1285,7 @@ public ref LightingState LightcacheGetStatic(LightCacheHandle_t cache, out IText pcache.Flags = (uint)flags; } else if (!recalcDLights && !recalcLightStyles) - return ref pcache.DynamicLightingState; + return ref pcache.Base.DynamicLightingState; else { if (recalcLightStyles) recalcDLights = true; @@ -1291,53 +1294,53 @@ public ref LightingState LightcacheGetStatic(LightCacheHandle_t cache, out IText LightingState accumulatedState = default; if ((flags & LightCacheFlags.Static) != 0) { - if (recalcStaticLighting && (pcache.LightingFlags & (int)HackLightCacheFlags.HasDoneStaticLighting) == 0) { - ComputeStaticLightingForCacheEntry(pcache, pcache.LightingOrigin, pcache.Leaf, true); - pcache.LightingFlags |= (int)HackLightCacheFlags.HasDoneStaticLighting; + if (recalcStaticLighting && (pcache.Base.LightingFlags & (int)HackLightCacheFlags.HasDoneStaticLighting) == 0) { + ComputeStaticLightingForCacheEntry(ref pcache.Base, pcache.Base.LightingOrigin, pcache.Base.Leaf, true); + pcache.Base.LightingFlags |= (int)HackLightCacheFlags.HasDoneStaticLighting; } - accumulatedState = pcache.StaticLightingState; + accumulatedState = pcache.Base.StaticLightingState; } else accumulatedState.ZeroLightingState(); if ((flags & LightCacheFlags.LightStyle) != 0) { if (recalcLightStyles) { - AddLightStylesForStaticProp(pcache, ref accumulatedState); - pcache.LightStyleLightingState = accumulatedState; - pcache.LastFrameUpdatedLightStyles = r_framecount; + AddLightStylesForStaticProp(ref pcache, ref accumulatedState); + pcache.Base.LightStyleLightingState = accumulatedState; + pcache.Base.LastFrameUpdatedLightStyles = r_framecount; } else - accumulatedState = pcache.LightStyleLightingState; + accumulatedState = pcache.Base.LightStyleLightingState; } if ((flags & LightCacheFlags.Dynamic) != 0) { if (recalcDLights) { - AddDLightsForStaticProps(pcache, ref accumulatedState, pcache); - pcache.DynamicLightingState = accumulatedState; - pcache.LastFrameUpdatedDynamicLighting = r_framecount; + AddDLightsForStaticProps(ref pcache.Base.Info, ref accumulatedState, ref pcache); + pcache.Base.DynamicLightingState = accumulatedState; + pcache.Base.LastFrameUpdatedDynamicLighting = r_framecount; } else - accumulatedState = pcache.DynamicLightingState; + accumulatedState = pcache.Base.DynamicLightingState; } else - pcache.DynamicLightingState = accumulatedState; + pcache.Base.DynamicLightingState = accumulatedState; - return ref pcache.DynamicLightingState; + return ref pcache.Base.DynamicLightingState; } - private void AddLightStylesForStaticProp(PropLightcache pcache, ref LightingState lightingState) { + private void AddLightStylesForStaticProp(ref PropLightcache pcache, ref LightingState lightingState) { for (int i = 0; i < pcache.LightStyleWorldLights.Count; ++i) { Assert(pcache.LightStyleWorldLights[i] >= 0); Assert(pcache.LightStyleWorldLights[i] < host_state.WorldBrush!.NumWorldLights); BSPDWorldLightPtr wl = new(host_state.WorldBrush!.WorldLights!, pcache.LightStyleWorldLights[i]); Assert(wl.Dereference().Style != 0); - AddWorldLightToLightingState(wl, null, ref lightingState, pcache, pcache.LightingOrigin, default, false, true); + AddWorldLightToLightingState(wl, null, ref lightingState, ref pcache.Base.Info, pcache.Base.LightingOrigin, default, false, true); } } - private void AddDLightsForStaticProps(LightingStateInfo info, ref LightingState lightingState, PropLightcache pcache) { + private void AddDLightsForStaticProps(scoped ref LightingStateInfo info, ref LightingState lightingState, ref PropLightcache pcache) { // todo } @@ -1353,46 +1356,46 @@ private void AddDLightsForStaticProps(LightingStateInfo info, ref LightingState ReadOnlySpan vis = default; bool computeLightStyles = (flags & LightCacheFlags.LightStyle) != 0; - LightCache? cache = FindInCache(bucket, x, y, z, originLeaf); + ref LightCache cache = ref FindInCache(bucket, x, y, z, originLeaf); - if (cache != null) { - LightcacheMark(cache); + if (!Unsafe.IsNullRef(ref cache)) { + LightcacheMark(ref cache); - if (computeLightStyles && IsCachedLightStylesValid(cache)) + if (computeLightStyles && IsCachedLightStylesValid(in cache.Base)) computeLightStyles = false; } else if (!AllowFullCacheMiss(flags)) { - cache = FindNearestCache(x, y, z, originLeaf); - originLeaf = cache!.Leaf; + cache = ref FindNearestCache(x, y, z, originLeaf); + originLeaf = cache.Base.Leaf; x = cache.X; y = cache.Y; z = cache.Z; } - if (cache == null) { - cache = NewLightcacheEntry(bucket); + if (Unsafe.IsNullRef(ref cache)) { + cache = ref NewLightcacheEntry(bucket); cache.X = x; cache.Y = y; cache.Z = z; - cache.Leaf = originLeaf; + cache.Base.Leaf = originLeaf; if (r_lightcachecenter.GetBool()) - AdjustLightCacheOrigin(cache, origin, originLeaf); + AdjustLightCacheOrigin(ref cache, origin, originLeaf); else - cache.LightingOrigin = origin; + cache.Base.LightingOrigin = origin; - cache.EnvCubemapTexture = FindEnvCubemapForPoint(cache.LightingOrigin); + cache.Base.EnvCubemapTexture = FindEnvCubemapForPoint(cache.Base.LightingOrigin); - vis = ComputeStaticLightingForCacheEntry(cache, cache.LightingOrigin, originLeaf); - vis = PrecalcLightingState(cache, vis); + vis = ComputeStaticLightingForCacheEntry(ref cache.Base, cache.Base.LightingOrigin, originLeaf); + vis = PrecalcLightingState(ref cache, vis); } - stats.HasNonSwitchableLightStyles = cache.HasNonSwitchableLightStyle(); - stats.HasSwitchableLightStyles = cache.HasSwitchableLightStyle(); + stats.HasNonSwitchableLightStyles = cache.Base.HasNonSwitchableLightStyle(); + stats.HasSwitchableLightStyles = cache.Base.HasSwitchableLightStyle(); if (computeLightStyles) { - vis = ComputeLightStyles(cache, ref cache.LightStyleLightingState, cache.LightingOrigin, originLeaf, vis); + vis = ComputeLightStyles(ref cache, ref cache.Base.LightStyleLightingState, cache.Base.LightingOrigin, originLeaf, vis); stats.NeedsSwitchableLightStyleUpdate = true; } else @@ -1400,25 +1403,25 @@ private void AddDLightsForStaticProps(LightingStateInfo info, ref LightingState stats.HasDLights = false; if ((flags & LightCacheFlags.Dynamic) != 0) { - vis = ComputeDynamicLighting(cache, ref cache.DynamicLightingState, cache.LightingOrigin, originLeaf, vis); - if (cache.DynamicLightingState.NumLights > 0) + vis = ComputeDynamicLighting(ref cache, ref cache.Base.DynamicLightingState, cache.Base.LightingOrigin, originLeaf, vis); + if (cache.Base.DynamicLightingState.NumLights > 0) stats.HasDLights = true; } if ((flags & LightCacheFlags.Static) != 0) - CopyPrecalcedLightingState(cache, ref lightingState, info); + CopyPrecalcedLightingState(in cache, ref lightingState, ref info); else lightingState.ZeroLightingState(); if ((flags & LightCacheFlags.LightStyle) != 0) - vis = AddLightingState(ref lightingState, cache.LightStyleLightingState, info, cache.LightingOrigin, vis, true, false); + vis = AddLightingState(ref lightingState, cache.Base.LightStyleLightingState, ref info, cache.Base.LightingOrigin, vis, true, false); if ((flags & LightCacheFlags.Dynamic) != 0) - vis = AddLightingState(ref lightingState, cache.DynamicLightingState, info, cache.LightingOrigin, vis, true, false); + vis = AddLightingState(ref lightingState, cache.Base.DynamicLightingState, ref info, cache.Base.LightingOrigin, vis, true, false); // todo r_drawlightcache - return cache.EnvCubemapTexture; + return cache.Base.EnvCubemapTexture; } public void InvalidateStaticLightingCache() { @@ -1760,13 +1763,13 @@ private float LightIntensityAndDirectionInBox(ref BSPDWorldLight light, LightZBu return LightIntensityAndDirectionAtPoint(ref light, zBuf, mid, flags | LightIntensityFlags.NoRadiusCheck, null, out direction); } - private void BuildStaticLightingCacheLightStyleInfo(PropLightcache cache, in Vector3 mins, in Vector3 maxs) { + private void BuildStaticLightingCacheLightStyleInfo(ref PropLightcache cache, in Vector3 mins, in Vector3 maxs) { Span vis = default; bool haveVis = false; Assert(cache.LightStyleWorldLights.Count == 0); - cache.LightingFlags &= ~(int)(HackLightCacheFlags.HasSwitchableLightStyle | HackLightCacheFlags.HasNonSwitchableLightStyle); + cache.Base.LightingFlags &= ~(int)(HackLightCacheFlags.HasSwitchableLightStyle | HackLightCacheFlags.HasNonSwitchableLightStyle); for (int i = 0; i < BaseLightCache.MAX_LIGHTSTYLE_BYTES; i++) - cache.Lightstyles[i] = 0; + cache.Base.Lightstyles[i] = 0; WorldBrushData worldBrush = host_state.WorldBrush!; for (short i = 0; i < worldBrush.NumWorldLights; ++i) { @@ -1775,13 +1778,13 @@ private void BuildStaticLightingCacheLightStyleInfo(PropLightcache cache, in Vec continue; if (!haveVis) { - vis = CM.ClusterPVS(CM.LeafCluster(cache.Leaf)); + vis = CM.ClusterPVS(CM.LeafCluster(cache.Base.Leaf)); haveVis = true; } if ((vis[wl.Cluster >> 3] & (1 << (wl.Cluster & 7))) != 0) { BSPDWorldLight tmpLight = wl; tmpLight.Style = 0; - float ratio = LightIntensityAndDirectionInBox(ref tmpLight, null, cache.LightingOrigin, mins, maxs, + float ratio = LightIntensityAndDirectionInBox(ref tmpLight, null, cache.Base.LightingOrigin, mins, maxs, LightIntensityFlags.NoOcclusionCheck | LightIntensityFlags.IgnoreLightstyleValue, out _); if (ratio <= 0.0f) continue; @@ -1790,11 +1793,11 @@ private void BuildStaticLightingCacheLightStyleInfo(PropLightcache cache, in Vec int b = wl.Style >> 3; int bit = wl.Style & 0x7; - cache.Lightstyles[b] |= (byte)(1 << bit); + cache.Base.Lightstyles[b] |= (byte)(1 << bit); if (MatSysInterface.LightStyleNumFrames[wl.Style] <= 1) - cache.LightingFlags |= (int)HackLightCacheFlags.HasSwitchableLightStyle; + cache.Base.LightingFlags |= (int)HackLightCacheFlags.HasSwitchableLightStyle; else - cache.LightingFlags |= (int)HackLightCacheFlags.HasNonSwitchableLightStyle; + cache.Base.LightingFlags |= (int)HackLightCacheFlags.HasNonSwitchableLightStyle; } } } @@ -1802,15 +1805,15 @@ private void BuildStaticLightingCacheLightStyleInfo(PropLightcache cache, in Vec // Precache lighting public LightCacheHandle_t CreateStaticLightingCache(in Vector3 origin, in Vector3 mins, in Vector3 maxs) { PropLightcache pcache = new() { - LightingOrigin = origin, Flags = 0, Mins = mins, - Maxs = maxs, - Leaf = CM.PointLeafnum(origin), - EnvCubemapTexture = FindEnvCubemapForPoint(origin) + Maxs = maxs }; + pcache.Base.LightingOrigin = origin; + pcache.Base.Leaf = CM.PointLeafnum(origin); + pcache.Base.EnvCubemapTexture = FindEnvCubemapForPoint(origin); - BuildStaticLightingCacheLightStyleInfo(pcache, mins, maxs); + BuildStaticLightingCacheLightStyleInfo(ref pcache, mins, maxs); PropCaches.Add(pcache); return PropCaches.Count; @@ -1826,13 +1829,13 @@ public bool ComputeVertexLightingFromSphericalSamples(in Vector3 vertex, in Vect } public bool StaticLightCacheAffectedByDynamicLight(LightCacheHandle_t handle) { - PropLightcache pcache = PropCaches[(int)handle - 1]; + ref PropLightcache pcache = ref CollectionsMarshal.AsSpan(PropCaches)[(int)handle - 1]; return pcache.HasDlights(); } public bool StaticLightCacheAffectedByAnimatedLightStyle(LightCacheHandle_t handle) { - PropLightcache pcache = PropCaches[(int)handle - 1]; - if (!pcache.HasLightStyle()) + ref PropLightcache pcache = ref CollectionsMarshal.AsSpan(PropCaches)[(int)handle - 1]; + if (!pcache.Base.HasLightStyle()) return false; else { for (int i = 0; i < pcache.LightStyleWorldLights.Count; ++i) { @@ -1848,8 +1851,8 @@ public bool StaticLightCacheAffectedByAnimatedLightStyle(LightCacheHandle_t hand } public bool StaticLightCacheNeedsSwitchableLightUpdate(LightCacheHandle_t handle) { - PropLightcache pcache = PropCaches[(int)handle - 1]; - if (!pcache.HasSwitchableLightStyle()) + ref PropLightcache pcache = ref CollectionsMarshal.AsSpan(PropCaches)[(int)handle - 1]; + if (!pcache.Base.HasSwitchableLightStyle()) return false; else { for (int i = 0; i < pcache.LightStyleWorldLights.Count; ++i) { diff --git a/Source.Engine/RAreaPortal.cs b/Source.Engine/RAreaPortal.cs index 493ad25e..840d7379 100644 --- a/Source.Engine/RAreaPortal.cs +++ b/Source.Engine/RAreaPortal.cs @@ -11,7 +11,7 @@ namespace Source.Engine; -public class PortalRect +public struct PortalRect { public float Left, Top, Right, Bottom; } @@ -19,7 +19,7 @@ public class PortalRect public class AreaCullInfo { public Frustum_t Frustum = new(); - public PortalRect Rect = new(); + public PortalRect Rect; public ushort GlobalCounter; } @@ -49,7 +49,7 @@ public static class RAreaPortal static ushort g_GlobalCounter = 1; static ViewSetup g_viewSetup; - static PortalRect g_viewWindow = new(); + static PortalRect g_viewWindow; static Matrix4x4 g_ScreenFromWorldProjection; public static void R_Areaportal_LevelInit() { @@ -69,15 +69,11 @@ public static void R_Areaportal_LevelShutdown() { static byte R_TestBit(byte[] bits, int bit) => (byte)(bits[bit >> 3] & (1 << (bit & 7))); - class PortalClip - { - public readonly Vector3[] v0 = new Vector3[MAX_PORTAL_VERTS]; - public readonly Vector3[] v1 = new Vector3[MAX_PORTAL_VERTS]; - public readonly Vector3[][] lists; - public PortalClip() => lists = [v0, v1]; - } + static bool GetPortalScreenExtents(ref BSPDAreaPortal portal, out PortalRect portalRect, Span reflectionWaterHeight) { + Span v0 = stackalloc Vector3[MAX_PORTAL_VERTS]; + Span v1 = stackalloc Vector3[MAX_PORTAL_VERTS]; - static bool GetPortalScreenExtents(ref BSPDAreaPortal portal, PortalClip clip, PortalRect portalRect, Span reflectionWaterHeight) { + portalRect = default; portalRect.Left = portalRect.Bottom = float.MaxValue; portalRect.Right = portalRect.Top = float.MinValue; bool validExtents = false; @@ -89,10 +85,10 @@ static bool GetPortalScreenExtents(ref BSPDAreaPortal portal, PortalClip clip, P for (int j = 0; j < passCount; ++j) { int i; for (i = 0; i < startVerts; i++) { - clip.v0[i] = brushData.ClipPortalVerts![portal.FirstClipPortalVert + i]; + v0[i] = brushData.ClipPortalVerts![portal.FirstClipPortalVert + i]; if (j == 1) - clip.v0[i].Z = 2.0f * reflectionWaterHeight[0] - clip.v0[i].Z; + v0[i].Z = 2.0f * reflectionWaterHeight[0] - v0[i].Z; } int curList = 0; @@ -100,8 +96,8 @@ static bool GetPortalScreenExtents(ref BSPDAreaPortal portal, PortalClip clip, P for (int iPlane = 0; iPlane < 4; iPlane++) { ref readonly CollisionPlane plane = ref g_Frustum.GetPlane(iPlane); - Vector3[] pIn = clip.lists[curList]; - Vector3[] pOut = clip.lists[curList == 0 ? 1 : 0]; + Span pIn = curList == 0 ? v0 : v1; + Span pOut = curList == 0 ? v1 : v0; int outVerts = 0; int prev = startVerts - 1; @@ -143,7 +139,7 @@ static bool GetPortalScreenExtents(ref BSPDAreaPortal portal, PortalClip clip, P Assert(curList == 0); for (i = 0; i < startVerts; i++) { - ref Vector3 point = ref clip.v0[i]; + ref Vector3 point = ref v0[i]; g_EngineRenderer.ClipTransformWithProjection(g_ScreenFromWorldProjection, point, out Vector3 screenPos); @@ -164,7 +160,8 @@ static bool GetPortalScreenExtents(ref BSPDAreaPortal portal, PortalClip clip, P return validExtents; } - static bool GetRectIntersection(PortalRect rect1, PortalRect rect2, PortalRect outRect) { + static bool GetRectIntersection(in PortalRect rect1, in PortalRect rect2, out PortalRect outRect) { + outRect = default; outRect.Left = MathF.Max(rect1.Left, rect2.Left); outRect.Right = MathF.Min(rect1.Right, rect2.Right); if (outRect.Left >= outRect.Right) @@ -178,7 +175,7 @@ static bool GetRectIntersection(PortalRect rect1, PortalRect rect2, PortalRect o return true; } - static void R_FlowThroughArea(int area, in Vector3 vecVisOrigin, PortalRect clipRect, ReadOnlySpan visData, Span reflectionWaterHeight) { + static void R_FlowThroughArea(int area, in Vector3 vecVisOrigin, in PortalRect clipRect, ReadOnlySpan visData, Span reflectionWaterHeight) { if (g_AreaCullInfo[area].GlobalCounter != g_GlobalCounter) { g_VisibleAreas[g_nVisibleAreas] = (ushort)area; ++g_nVisibleAreas; @@ -190,7 +187,7 @@ static void R_FlowThroughArea(int area, in Vector3 vecVisOrigin, PortalRect clip g_AreaCullInfo[area].Rect.Bottom = clipRect.Bottom; } else { - PortalRect frustumRect = g_AreaCullInfo[area].Rect; + ref PortalRect frustumRect = ref g_AreaCullInfo[area].Rect; frustumRect.Left = MathF.Min(frustumRect.Left, clipRect.Left); frustumRect.Bottom = MathF.Min(frustumRect.Bottom, clipRect.Bottom); frustumRect.Top = MathF.Max(frustumRect.Top, clipRect.Top); @@ -205,7 +202,6 @@ static void R_FlowThroughArea(int area, in Vector3 vecVisOrigin, PortalRect clip Assert(area < host_state.WorldBrush!.NumAreas); ref BSPDArea areaData = ref host_state.WorldBrush!.Areas![area]; - PortalClip clipTmp = new(); for (int iAreaPortal = 0; iAreaPortal < areaData.NumAreaPortals; iAreaPortal++) { Assert(areaData.FirstAreaPortal + iAreaPortal < brushData.NumAreaPortals); @@ -225,26 +221,26 @@ static void R_FlowThroughArea(int area, in Vector3 vecVisOrigin, PortalRect clip if (R_TestBit(cl.AreaBits, areaPortal.OtherArea) == 0) continue; - PortalRect portalRect = new(); + PortalRect portalRect; bool portalVis = true; float distTolerance = (visData.Length != 0) ? visData[0].DistToAreaPortalTolerance : 0.1f; if (dist > distTolerance) - portalVis = GetPortalScreenExtents(ref areaPortal, clipTmp, portalRect, reflectionWaterHeight); + portalVis = GetPortalScreenExtents(ref areaPortal, out portalRect, reflectionWaterHeight); else { + portalRect = default; portalRect.Left = -1; portalRect.Top = 1; portalRect.Right = 1; portalRect.Bottom = -1; } if (portalVis) { - PortalRect intersection = new(); - if (GetRectIntersection(portalRect, clipRect, intersection)) { + if (GetRectIntersection(in portalRect, in clipRect, out PortalRect intersection)) { if (r_DrawPortals.GetInt() != 0) { g_PortalRects.Add(intersection); } - R_FlowThroughArea(areaPortal.OtherArea, vecVisOrigin, intersection, visData, reflectionWaterHeight); + R_FlowThroughArea(areaPortal.OtherArea, vecVisOrigin, in intersection, visData, reflectionWaterHeight); } } } @@ -477,7 +473,7 @@ public static void R_SetupAreaBits(int forceViewLeaf = -1, ReadOnlySpan tempEntsSorted = []; public virtual void WriteTempEntities(BaseClient client, FrameSnapshot to, FrameSnapshot from, bf_write pBuf, int nMaxEnts) { SVC_TempEntities msg = new(); msg.DataOut.StartWriting(tempEntsBuffer, tempEntsBuffer.Length); @@ -429,7 +430,8 @@ public virtual void WriteTempEntities(BaseClient client, FrameSnapshot to, Frame else pSnapshot = to; - List sorted = new(nMaxEnts); + List sorted = tempEntsSorted; + sorted.Clear(); while (pSnapshot != null && sorted.Count < nMaxEnts) { for (int i = 0; i < pSnapshot.NumTempEntities; i++) { @@ -515,6 +517,7 @@ public virtual void WriteTempEntities(BaseClient client, FrameSnapshot to, Frame msg.NumEntries = sorted.Count; msg.WriteToBuffer(pBuf); + sorted.Clear(); } diff --git a/Source.Engine/Server/EntsWrite.cs b/Source.Engine/Server/EntsWrite.cs index d2706990..50d19efb 100644 --- a/Source.Engine/Server/EntsWrite.cs +++ b/Source.Engine/Server/EntsWrite.cs @@ -118,8 +118,8 @@ static bool NeedsExplicitCreate(EntityWriteInfo u) { if (index >= u.FromSnapshot!.NumEntities) return true; - FrameSnapshotEntry fromEnt = u.FromSnapshot.Entities![index]; - FrameSnapshotEntry toEnt = u.ToSnapshot.Entities![index]; + ref readonly FrameSnapshotEntry fromEnt = ref u.FromSnapshot.Entities![index]; + ref readonly FrameSnapshotEntry toEnt = ref u.ToSnapshot.Entities![index]; return (fromEnt.Class == null) || fromEnt.SerialNumber != toEnt.SerialNumber; } @@ -215,7 +215,7 @@ static void WriteEnterPVS(EntityWriteInfo u) { Assert(u.NewEntity < u.ToSnapshot.NumEntities); - FrameSnapshotEntry entry = u.ToSnapshot.Entities![u.NewEntity]; + ref readonly FrameSnapshotEntry entry = ref u.ToSnapshot.Entities![u.NewEntity]; ServerClass? entryClass = entry.Class; diff --git a/Source.Engine/Server/GameServer.cs b/Source.Engine/Server/GameServer.cs index 72825420..188f7d2c 100644 --- a/Source.Engine/Server/GameServer.cs +++ b/Source.Engine/Server/GameServer.cs @@ -428,8 +428,8 @@ private void SetupMaxPlayers(int iDesiredMaxPlayers) { } public override void SendClientMessages(bool bSendSnapshots) { - int receivingClientCount = 0; - GameClient[] receivingClients = new GameClient[Constants.ABSOLUTE_PLAYER_LIMIT]; + InlineArray128 receivingClientsBuffer = default; + SpanList receivingClients = new(receivingClientsBuffer); for (int i = 0; i < GetClientCount(); i++) { GameClient client = Client(i); @@ -438,8 +438,7 @@ public override void SendClientMessages(bool bSendSnapshots) { continue; if (bSendSnapshots && client.IsActive()) { - receivingClients[receivingClientCount] = client; - receivingClientCount++; + receivingClients.Add(client); } else { if (client.IsFakeClient()) @@ -454,11 +453,12 @@ public override void SendClientMessages(bool bSendSnapshots) { } } + int receivingClientCount = receivingClients.Count; if (receivingClientCount > 0) { FrameSnapshot snapshot = FrameSnapshotManager.TakeTickSnapshot((int)TickCount); CopyTempEntities(snapshot); - PackedEntities.ComputeClientPacks(receivingClientCount, receivingClients, snapshot); + PackedEntities.ComputeClientPacks(receivingClientCount, receivingClients.AsSpan(), snapshot); // if (receivingClientCount > 1 && sv_parallel_sendsnapshot.GetBool()) { // diff --git a/Source.Engine/Server/PackedEntities.cs b/Source.Engine/Server/PackedEntities.cs index e7766970..ff505a4d 100644 --- a/Source.Engine/Server/PackedEntities.cs +++ b/Source.Engine/Server/PackedEntities.cs @@ -193,7 +193,7 @@ static SendTable GetEntSendTable(Edict edict) { throw new NotImplementedException(); } - static void NetworkBackDoor(int clientCount, GameClient[] clients, FrameSnapshot snapshot) { + static void NetworkBackDoor(int clientCount, ReadOnlySpan clients, FrameSnapshot snapshot) { Assert(clientCount == 1); GameClient client = clients[0]; // update variables cl, pInfo, frame for current client @@ -224,7 +224,7 @@ static void NetworkBackDoor(int clientCount, GameClient[] clients, FrameSnapshot EngineServer.InvalidateSharedEdictChangeInfos(); } - static void Normal(int clientCount, GameClient[] clients, FrameSnapshot snapshot) { + static void Normal(int clientCount, ReadOnlySpan clients, FrameSnapshot snapshot) { Assert(snapshot.NumValidEntities >= 0 && snapshot.NumValidEntities <= Constants.MAX_EDICTS); List workItems = []; @@ -280,7 +280,7 @@ static void Normal(int clientCount, GameClient[] clients, FrameSnapshot snapshot // InvalidateSharedEdictChangeInfos(); todo } - public static void ComputeClientPacks(int clientCount, GameClient[] clients, FrameSnapshot snapshot) { + public static void ComputeClientPacks(int clientCount, ReadOnlySpan clients, FrameSnapshot snapshot) { for (int i = 0; i < clientCount; i++) { CheckTransmitInfo info = clients[i].PackInfo; diff --git a/Source.Engine/ShadowMgr.cs b/Source.Engine/ShadowMgr.cs index 62fd3024..bc628360 100644 --- a/Source.Engine/ShadowMgr.cs +++ b/Source.Engine/ShadowMgr.cs @@ -2068,7 +2068,7 @@ public void DrawFlashlightDecals(int sortGroup, bool doMasking) { EnableStencilAndScissorMasking(renderContext, flashlightInfo, doMasking); #if !SWDS - Render.DecalSurfaceDraw(renderContext, sortGroup); + Render.DecalSurfaceDraw(renderContext.Context, sortGroup); #endif } diff --git a/Source.Engine/SpatialPartition.cs b/Source.Engine/SpatialPartition.cs index 462663ad..b8733d77 100644 --- a/Source.Engine/SpatialPartition.cs +++ b/Source.Engine/SpatialPartition.cs @@ -759,16 +759,23 @@ public sealed class VoxelTree public PartitionVisits? GetVisits() => t_visits; public int GetTreeId() => TreeId; + [ThreadStatic] static Stack? t_freeVisits; + public PartitionVisits? BeginVisit() { var prev = t_visits; - var visits = new PartitionVisits(); + Stack free = t_freeVisits ??= new(); + var visits = free.Count > 0 ? free.Pop() : new PartitionVisits(); visits.Resize(_nextVisitBit); visits.ClearAll(); t_visits = visits; return prev; } - public void EndVisit(PartitionVisits? prev) => t_visits = prev; + public void EndVisit(PartitionVisits? prev) { + if (t_visits != null) + (t_freeVisits ??= new()).Push(t_visits); + t_visits = prev; + } public VoxelTree() { _levelCount = 0; diff --git a/Source.StudioRender/StudioRender.cs b/Source.StudioRender/StudioRender.cs index 63b248fe..291e5c16 100644 --- a/Source.StudioRender/StudioRender.cs +++ b/Source.StudioRender/StudioRender.cs @@ -107,7 +107,7 @@ internal void DrawModel(ref DrawModelInfo info, StudioRenderCtx RC, Span