diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e0e1d170c..4d7a0cfa4 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -24,3 +24,6 @@ jobs: - name: Build run: dotnet build Source.NET.slnx -c ${{ matrix.configuration }} + + - name: Test + run: dotnet test --project Source.Common.Tests/Source.Common.Tests.csproj -c ${{ matrix.configuration }} --no-build diff --git a/Game.Client/C_RecipientFilter.cs b/Game.Client/C_RecipientFilter.cs index 1f813cd38..d82b0d63a 100644 --- a/Game.Client/C_RecipientFilter.cs +++ b/Game.Client/C_RecipientFilter.cs @@ -144,7 +144,7 @@ public void UsePredictionRules() { public bool IgnorePredictionCull() => bIgnorePredictionCull; public void SetIgnorePredictionCull(bool ignore) => bIgnorePredictionCull = ignore; - public void AddPlayersFromBitMask(in AbsolutePlayerLimitBitVec playerbits) { + public void AddPlayersFromBitMask(in PlayerBitSet playerbits) { C_BasePlayer? player = C_BasePlayer.GetLocalPlayer(); if (player == null) diff --git a/Game.Client/Game.Client.csproj b/Game.Client/Game.Client.csproj index df7625139..78929b603 100644 --- a/Game.Client/Game.Client.csproj +++ b/Game.Client/Game.Client.csproj @@ -37,6 +37,7 @@ + diff --git a/Game.Client/VoiceStatus.cs b/Game.Client/VoiceStatus.cs index ed5d531b5..9e00a1b49 100644 --- a/Game.Client/VoiceStatus.cs +++ b/Game.Client/VoiceStatus.cs @@ -94,18 +94,18 @@ public class VoiceStatus int ServerModEnable; // What we've sent to the server about our "voice_modenable" cvar. IPanel? ParentPanel; - PlayerBitVec VoicePlayers; // Who is currently talking. Indexed by client index. + PlayerBitSet VoicePlayers; // Who is currently talking. Indexed by client index. // This is the gamerules-defined list of players that you can hear. It is based on what teams people are on // and is totally separate from the ban list. Indexed by client index. - PlayerBitVec AudiblePlayers; + PlayerBitSet AudiblePlayers; // Players who have spoken at least once in the game so far - PlayerBitVec VoiceEnabledPlayers; + PlayerBitSet VoiceEnabledPlayers; // This is who the server THINKS we have banned (it can become incorrect when a new player arrives on the server). // It is checked periodically, and the server is told to squelch or unsquelch the appropriate players. - PlayerBitVec ServerBannedPlayers; + PlayerBitSet ServerBannedPlayers; IVoiceStatusHelper? Helper; // Each mod provides an implementation of this. @@ -211,7 +211,7 @@ public void DrawHeadLabels() { using MatRenderContextPtr renderContext = new(materials); for (int i = 0; i < VOICE_MAX_PLAYERS; i++) { - if (!VoicePlayers[i]) + if (!VoicePlayers.IsBitSet(i)) continue; C_BaseEntity? client = cl_entitylist.GetEnt(i + 1); @@ -300,11 +300,11 @@ public void UpdateSpeakerStatus(int entindex, bool talking) { return; if (talking) { - VoicePlayers[iClient] = true; - VoiceEnabledPlayers[iClient] = true; + VoicePlayers.Set(iClient, true); + VoiceEnabledPlayers.Set(iClient, true); } else - VoicePlayers[iClient] = false; + VoicePlayers.Set(iClient, false); } } @@ -345,7 +345,7 @@ void UpdateServerState(bool force) { if (BanMgr.GetPlayerBan(pi.GUID)) banMask |= 1u << (int)i; - if (ServerBannedPlayers[playerIndex]) + if (ServerBannedPlayers.IsBitSet(playerIndex)) serverBanMask |= 1u << (int)i; } @@ -374,13 +374,13 @@ void UpdateServerState(bool force) { public void HandleVoiceMaskMsg(bf_read msg) { uint dw; for (dw = 0; dw < VOICE_MAX_PLAYERS_DW; dw++) { - AudiblePlayers.SetDWord((int)dw, (uint)msg.ReadLong()); - ServerBannedPlayers.SetDWord((int)dw, (uint)msg.ReadLong()); + AudiblePlayers.SetWord((int)dw, (uint)msg.ReadLong()); + ServerBannedPlayers.SetWord((int)dw, (uint)msg.ReadLong()); if (voice_clientdebug.GetInt() != 0) { Msg("CVoiceStatus::HandleVoiceMaskMsg\n"); - Msg($" - m_AudiblePlayers[{dw}] = {AudiblePlayers.GetDWord((int)dw)}\n"); - Msg($" - m_ServerBannedPlayers[{dw}] = {ServerBannedPlayers.GetDWord((int)dw)}\n"); + Msg($" - m_AudiblePlayers[{dw}] = {AudiblePlayers.GetWord((int)dw)}\n"); + Msg($" - m_ServerBannedPlayers[{dw}] = {ServerBannedPlayers.GetWord((int)dw)}\n"); } } @@ -424,12 +424,12 @@ public bool IsPlayerBlocked(int player) { // returns false if the player can't hear the other client due to game rules (eg. the other team) public bool IsPlayerAudible(int player) { - return AudiblePlayers[player - 1]; + return AudiblePlayers.IsBitSet(player - 1); } // returns true if the player is currently speaking public bool IsPlayerSpeaking(int playerIndex) { - return VoicePlayers[playerIndex - 1]; + return VoicePlayers.IsBitSet(playerIndex - 1); } // returns true if the local player is attempting to speak diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index e9c75308e..c4ec8be49 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -3200,7 +3200,7 @@ public bool IsScheduleValid() { SetCustomInterruptCondition((int)SCOND_t.COND_NPC_FREEZE); - CustomInterruptConditions.And(Conditions, out AI_ScheduleBits testBits); + AI_ScheduleBits testBits = CustomInterruptConditions.And(Conditions); if (!testBits.IsAllClear()) { if (developer.GetInt() != 0) { @@ -4710,7 +4710,7 @@ public virtual bool CanBeAnEnemyOf(BaseEntity enemy) { public void RemoveIgnoredConditions() { ConditionsPreIgnore = Conditions; - Conditions.And(InverseIgnoreConditions, out Conditions); + Conditions = Conditions.And(InverseIgnoreConditions); if (NPCState == NPCState.Script && Cine.Get() != null) Cine.Get()!.RemoveIgnoredConditions(); diff --git a/Game.Server/AI_Condition.cs b/Game.Server/AI_Condition.cs index 82254a267..32c32b843 100644 --- a/Game.Server/AI_Condition.cs +++ b/Game.Server/AI_Condition.cs @@ -88,23 +88,5 @@ public enum SCOND_t LAST_SHARED_CONDITION } -[InlineArray(MAX_CONDITIONS >> 3)] -public struct AI_ScheduleBits -{ - public byte bytes; - public void ClearAll() => BitVecBase.ClearAll(this); - public void SetAll() => ((Span)this).Fill(0xff); - public void Set(int bit) => BitVecBase.Set(this, bit); - public void Clear(int bit) => BitVecBase.Clear(this, bit); - public bool IsBitSet(int bit) => BitVecBase.IsBitSet(this, bit); - public bool IsAllClear() => ((ReadOnlySpan)this).IndexOfAnyExcept((byte)0) < 0; - public void And(in AI_ScheduleBits other, out AI_ScheduleBits result) { - AI_ScheduleBits temp = default; - ReadOnlySpan a = this; - ReadOnlySpan b = other; - Span r = temp; - for (int i = 0; i < r.Length; i++) - r[i] = (byte)(a[i] & b[i]); - result = temp; - } -} +[BitVec(MAX_CONDITIONS)] +public partial struct AI_ScheduleBits; diff --git a/Game.Server/Game.Server.csproj b/Game.Server/Game.Server.csproj index c08c765d2..42bbf67e0 100644 --- a/Game.Server/Game.Server.csproj +++ b/Game.Server/Game.Server.csproj @@ -15,6 +15,8 @@ OutputItemType="Analyzer" ReferenceOutputAssembly="false" /> + diff --git a/Game.Server/HL2MP/HL2MP_Player.cs b/Game.Server/HL2MP/HL2MP_Player.cs index f798df569..e456a1250 100644 --- a/Game.Server/HL2MP/HL2MP_Player.cs +++ b/Game.Server/HL2MP/HL2MP_Player.cs @@ -380,7 +380,7 @@ void FireBullets(FireBulletsInfo info) { } void NoteWeaponFired() { } - public override bool WantsLagCompensationOnEntity(BaseEntity entity, in UserCmd cmd, ref readonly MaxEdictsBitVec entityTransmitBits) { + public override bool WantsLagCompensationOnEntity(BaseEntity entity, in UserCmd cmd, ref readonly MaxEdictsBitSet entityTransmitBits) { return base.WantsLagCompensationOnEntity(entity, in cmd, in entityTransmitBits); } diff --git a/Game.Server/Player.cs b/Game.Server/Player.cs index f4c81a80a..ad200b0e1 100644 --- a/Game.Server/Player.cs +++ b/Game.Server/Player.cs @@ -1421,7 +1421,7 @@ public override EdictFlags ShouldTransmit(CheckTransmitInfo info) { return base.ShouldTransmit(info); } - public virtual bool WantsLagCompensationOnEntity(BaseEntity entity, in UserCmd cmd, ref readonly MaxEdictsBitVec entityTransmitBits) { + public virtual bool WantsLagCompensationOnEntity(BaseEntity entity, in UserCmd cmd, ref readonly MaxEdictsBitSet entityTransmitBits) { if (!Unsafe.IsNullRef(in entityTransmitBits) && !entityTransmitBits.IsBitSet(entity.EntIndex())) return false; diff --git a/Game.Server/PlayerLagCompensation.cs b/Game.Server/PlayerLagCompensation.cs index 5a8532fac..bf53f4f28 100644 --- a/Game.Server/PlayerLagCompensation.cs +++ b/Game.Server/PlayerLagCompensation.cs @@ -294,7 +294,7 @@ public void StartLagCompensation(BasePlayer player, in Vector3 weaponPos = defau WeaponAngles = weaponAngles; WeaponRange = weaponRange; - ref readonly MaxEdictsBitVec entityTransmitBits = ref engine.GetEntityTransmitBitsForClient(player.EntIndex() - 1); + ref readonly MaxEdictsBitSet entityTransmitBits = ref engine.GetEntityTransmitBitsForClient(player.EntIndex() - 1); foreach (KeyValuePair kvp in CompensatedEntities) { EntityLagData ld = kvp.Value; diff --git a/Game.Server/RecipientFilter.cs b/Game.Server/RecipientFilter.cs index d8be21977..39911ec16 100644 --- a/Game.Server/RecipientFilter.cs +++ b/Game.Server/RecipientFilter.cs @@ -66,7 +66,7 @@ public void AddAllPlayers() { AddRecipient(player); } } - public void AddPlayersFromBitMask(ref AbsolutePlayerLimitBitVec playerbits) { + public void AddPlayersFromBitMask(ref PlayerBitSet playerbits) { int index = playerbits.FindNextSetBit(0); while (index > -1) { @@ -81,7 +81,7 @@ public void AddRecipientsByPVS(in Vector3 origin) { if (gpGlobals.MaxClients == 1) AddAllPlayers(); else { - AbsolutePlayerLimitBitVec playerbits = default; + PlayerBitSet playerbits = default; engine.Message_DetermineMulticastRecipients(false, origin, ref playerbits); AddPlayersFromBitMask(ref playerbits); } @@ -91,7 +91,7 @@ public void AddRecipientsByPAS(in Vector3 origin) { if (gpGlobals.MaxClients == 1) AddAllPlayers(); else { - AbsolutePlayerLimitBitVec playerbits = default; + PlayerBitSet playerbits = default; engine.Message_DetermineMulticastRecipients(true, origin, ref playerbits); AddPlayersFromBitMask(ref playerbits); } diff --git a/Game.Server/VoiceGameMgr.cs b/Game.Server/VoiceGameMgr.cs index e69d6b96d..15d04ccd4 100644 --- a/Game.Server/VoiceGameMgr.cs +++ b/Game.Server/VoiceGameMgr.cs @@ -2,6 +2,7 @@ using Game.Shared; +using Source; using Source.Common; using Source.Common.Commands; using Source.Common.Engine; @@ -25,17 +26,17 @@ public static class VoiceGameMgrGlobals public const double UPDATE_INTERVAL = 0.3; // These are stored off as VoiceGameMgr is created and deleted. - public static PlayerBitVec g_PlayerModEnable; // Set to 1 for each player if the player wants to use voice in this mod. + public static PlayerBitSet g_PlayerModEnable; // Set to 1 for each player if the player wants to use voice in this mod. // (If it's zero, then the server reports that the game rules are saying the // player can't hear anyone). - public static readonly PlayerBitVec[] g_BanMasks = new PlayerBitVec[VOICE_MAX_PLAYERS]; // Tells which players don't want to hear each other. + public static readonly PlayerBitSet[] g_BanMasks = new PlayerBitSet[VOICE_MAX_PLAYERS]; // Tells which players don't want to hear each other. // These are indexed as clients and each bit represents a client // (so player entity is bit+1). - public static readonly PlayerBitVec[] g_SentGameRulesMasks = new PlayerBitVec[VOICE_MAX_PLAYERS]; // These store the masks we last sent to each client so we can determine if - public static readonly PlayerBitVec[] g_SentBanMasks = new PlayerBitVec[VOICE_MAX_PLAYERS]; // we need to resend them. - public static PlayerBitVec g_bWantModEnable; + public static readonly PlayerBitSet[] g_SentGameRulesMasks = new PlayerBitSet[VOICE_MAX_PLAYERS]; // These store the masks we last sent to each client so we can determine if + public static readonly PlayerBitSet[] g_SentBanMasks = new PlayerBitSet[VOICE_MAX_PLAYERS]; // we need to resend them. + public static PlayerBitSet g_bWantModEnable; public static readonly ConVar voice_serverdebug = new("voice_serverdebug", "0"); @@ -106,9 +107,9 @@ public void ClientConnected(Edict edict) { int index = edict.EdictIndex - 1; // Clear out everything we use for deltas on this guy. - g_bWantModEnable[index] = true; - g_SentGameRulesMasks[index].Init(0); - g_SentBanMasks[index].Init(0); + g_bWantModEnable.Set(index, true); + g_SentGameRulesMasks[index].ClearAll(); + g_SentBanMasks[index].ClearAll(); } // Called on ClientCommand. Checks for the squelch and unsquelch commands. @@ -127,7 +128,7 @@ public bool ClientCommand(BasePlayer player, in TokenizedCommand args) { if (i <= VOICE_MAX_PLAYERS_DW) { VoiceServerDebug($"CVoiceGameMgr::ClientCommand: vban (0x{mask:x}) from {playerClientIndex}\n"); - g_BanMasks[playerClientIndex].SetDWord(i - 1, mask); + g_BanMasks[playerClientIndex].SetWord(i - 1, mask); } else VoiceServerDebug($"CVoiceGameMgr::ClientCommand: invalid index ({i})\n"); @@ -139,8 +140,8 @@ public bool ClientCommand(BasePlayer player, in TokenizedCommand args) { } else if (args[0].Equals("VModEnable", StringComparison.OrdinalIgnoreCase) && args.ArgC() >= 2) { VoiceServerDebug($"CVoiceGameMgr::ClientCommand: VModEnable ({(atoi(args[1]) != 0 ? 1 : 0)})\n"); - g_PlayerModEnable[playerClientIndex] = atoi(args[1]) != 0; - g_bWantModEnable[playerClientIndex] = false; + g_PlayerModEnable.Set(playerClientIndex, atoi(args[1]) != 0); + g_bWantModEnable.Set(playerClientIndex, false); //UpdateMasks(); return true; } @@ -160,7 +161,7 @@ public void SetProximityDistance(int distance) { } public bool IsPlayerIgnoringPlayer(int talker, int listener) { - return g_BanMasks[listener - 1][talker - 1]; + return g_BanMasks[listener - 1].IsBitSet(talker - 1); } // Force it to update the client masks. @@ -179,24 +180,24 @@ void UpdateMasks() { SingleUserRecipientFilter user = new(player); // Request the state of their "VModEnable" cvar. - if (g_bWantModEnable[iClient]) { + if (g_bWantModEnable.IsBitSet(iClient)) { UserMessageBegin(user, "RequestState"); MessageEnd(); // Since this is reliable, only send it once - g_bWantModEnable[iClient] = false; + g_bWantModEnable.Set(iClient, false); } - PlayerBitVec gameRulesMask = default; - PlayerBitVec proximityMask = default; + PlayerBitSet gameRulesMask = default; + PlayerBitSet proximityMask = default; bool proximity = false; - if (g_PlayerModEnable[iClient]) { + if (g_PlayerModEnable.IsBitSet(iClient)) { // Build a mask of who they can hear based on the game rules. for (int iOtherClient = 0; iOtherClient < MaxPlayers; iOtherClient++) { BaseEntity? otherEnt = Util.PlayerByIndex(iOtherClient + 1); if (otherEnt != null && otherEnt.IsPlayer() && (allTalk || Helper!.CanPlayerHearPlayer(player, (BasePlayer)otherEnt, ref proximity))) { - gameRulesMask[iOtherClient] = true; - proximityMask[iOtherClient] = proximity; + gameRulesMask.Set(iOtherClient, true); + proximityMask.Set(iOtherClient, proximity); } } } @@ -210,20 +211,20 @@ void UpdateMasks() { UserMessageBegin(user, "VoiceMask"); int dw; for (dw = 0; dw < VOICE_MAX_PLAYERS_DW; dw++) { - MessageWriteLong((int)gameRulesMask.GetDWord(dw)); - MessageWriteLong((int)g_BanMasks[iClient].GetDWord(dw)); + MessageWriteLong((int)gameRulesMask.GetWord(dw)); + MessageWriteLong((int)g_BanMasks[iClient].GetWord(dw)); } - MessageWriteByte(g_PlayerModEnable[iClient] ? 1 : 0); + MessageWriteByte(g_PlayerModEnable.IsBitSet(iClient) ? 1 : 0); MessageEnd(); } // Tell the engine. for (int iOtherClient = 0; iOtherClient < MaxPlayers; iOtherClient++) { - bool canHear = gameRulesMask[iOtherClient] && !g_BanMasks[iClient][iOtherClient]; + bool canHear = gameRulesMask.IsBitSet(iOtherClient) && !g_BanMasks[iClient].IsBitSet(iOtherClient); g_pVoiceServer.SetClientListening(iClient + 1, iOtherClient + 1, canHear); if (canHear) - g_pVoiceServer.SetClientProximity(iClient + 1, iOtherClient + 1, proximityMask[iOtherClient]); + g_pVoiceServer.SetClientProximity(iClient + 1, iOtherClient + 1, proximityMask.IsBitSet(iOtherClient)); } } } diff --git a/Game.Shared/ChoreoScene.cs b/Game.Shared/ChoreoScene.cs index f893c8668..5e505d961 100644 --- a/Game.Shared/ChoreoScene.cs +++ b/Game.Shared/ChoreoScene.cs @@ -38,14 +38,8 @@ public static bool IsBufferBinaryVCD(ReadOnlySpan buffer) { } } -[InlineArray(((int)ChoreoEvent.EventType.NumTypes + 31) / 32 * 4)] -public struct ChoreoEventTypeBitVec -{ - public byte bytes; - public bool IsBitSet(int bit) => BitVecBase.IsBitSet(this, bit); - public void Set(int bit, bool newVal) => BitVecBase.Set(this, bit, newVal); - public void ClearAll() => BitVecBase.ClearAll(this); -} +[BitVec((int)ChoreoEvent.EventType.NumTypes)] +public partial struct ChoreoEventTypeBitSet; public class ChoreoScene : ICurveDataAccessor { @@ -111,7 +105,7 @@ enum TimeRange readonly SortedList TimeZoomLookup = new(Comparer.Create(static (a, b) => stricmp(a, b))); string FileName = ""; - ChoreoEventTypeBitVec BitvecHasEventOfType; + ChoreoEventTypeBitSet BitvecHasEventOfType; bool IsBackgroundValue; bool IgnorePhonemesValue; diff --git a/Game.Shared/Game.Shared.csproj b/Game.Shared/Game.Shared.csproj index d87e6dcfd..b4bfd36ae 100644 --- a/Game.Shared/Game.Shared.csproj +++ b/Game.Shared/Game.Shared.csproj @@ -25,6 +25,7 @@ + diff --git a/Game.Shared/VoiceCommon.cs b/Game.Shared/VoiceCommon.cs index e98573737..4d730e6d8 100644 --- a/Game.Shared/VoiceCommon.cs +++ b/Game.Shared/VoiceCommon.cs @@ -2,48 +2,6 @@ namespace Game.Shared; -public struct PlayerBitVec : IEquatable -{ - PlayerBitVecDWords DWords; - - [System.Runtime.CompilerServices.InlineArray(VOICE_MAX_PLAYERS_DW)] - struct PlayerBitVecDWords { uint dw; } - - public bool this[int bit] { - readonly get => (DWords[bit >> 5] & (1u << (bit & 31))) != 0; - set { - if (value) - DWords[bit >> 5] |= 1u << (bit & 31); - else - DWords[bit >> 5] &= ~(1u << (bit & 31)); - } - } - - public void Init(int val = 0) { - for (int i = 0; i < VOICE_MAX_PLAYERS_DW; i++) - DWords[i] = val != 0 ? uint.MaxValue : 0; - } - - public readonly uint GetDWord(int i) => DWords[i]; - public void SetDWord(int i, uint val) => DWords[i] = val; - - public readonly bool Equals(PlayerBitVec other) { - for (int i = 0; i < VOICE_MAX_PLAYERS_DW; i++) - if (DWords[i] != other.DWords[i]) - return false; - return true; - } - public override readonly bool Equals(object? obj) => obj is PlayerBitVec other && Equals(other); - public override readonly int GetHashCode() { - HashCode hash = new(); - for (int i = 0; i < VOICE_MAX_PLAYERS_DW; i++) - hash.Add(DWords[i]); - return hash.ToHashCode(); - } - public static bool operator ==(PlayerBitVec a, PlayerBitVec b) => a.Equals(b); - public static bool operator !=(PlayerBitVec a, PlayerBitVec b) => !a.Equals(b); -} - public static class VoiceCommon { public const int VOICE_DEFAULT_PROXIMITY_RANGE = 1200; //100 feet diff --git a/Source.CodeAnalysis.BitVec/BitVecGenerator.cs b/Source.CodeAnalysis.BitVec/BitVecGenerator.cs new file mode 100644 index 000000000..1950f714a --- /dev/null +++ b/Source.CodeAnalysis.BitVec/BitVecGenerator.cs @@ -0,0 +1,164 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +using System.Linq; +using System.Text; + +namespace Source.CodeAnalysis.BitVec +{ + [Generator(LanguageNames.CSharp)] + public sealed class BitVecGenerator : IIncrementalGenerator + { + private const string AttributeMetadataName = "Source.BitVecAttribute"; + private const string GenericAttributeMetadataName = "Source.BitVecAttribute`1"; + + private static readonly DiagnosticDescriptor NotPartial = new DiagnosticDescriptor( + id: "BITVEC001", + title: "[BitVec] requires a partial struct", + messageFormat: "'{0}' is marked [BitVec] but is not partial; the generator cannot emit its storage and members", + category: "BitVec", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true); + + private static readonly DiagnosticDescriptor Unsupported = new DiagnosticDescriptor( + id: "BITVEC002", + title: "[BitVec] only supports top-level non-generic structs", + messageFormat: "'{0}' is marked [BitVec] but is nested or generic, which is not supported", + category: "BitVec", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true); + + private static readonly DiagnosticDescriptor InvalidArguments = new DiagnosticDescriptor( + id: "BITVEC003", + title: "[BitVec] has invalid arguments", + messageFormat: "'{0}' is marked [BitVec] with an invalid bit count or word type", + category: "BitVec", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true); + + private sealed class Model + { + public string? Namespace = null; + public string Name = ""; + public string WordType = "uint"; + public int BitsPerWord = 32; + public int NumBits; + public Diagnostic? Error; + } + + public void Initialize(IncrementalGeneratorInitializationContext context) { + IncrementalValuesProvider plain = context.SyntaxProvider.ForAttributeWithMetadataName( + AttributeMetadataName, + static (node, _) => node is StructDeclarationSyntax, + static (ctx, _) => CreateModel(ctx)); + + IncrementalValuesProvider generic = context.SyntaxProvider.ForAttributeWithMetadataName( + GenericAttributeMetadataName, + static (node, _) => node is StructDeclarationSyntax, + static (ctx, _) => CreateModel(ctx)); + + context.RegisterSourceOutput(plain, static (spc, model) => Emit(spc, model)); + context.RegisterSourceOutput(generic, static (spc, model) => Emit(spc, model)); + } + + private static Model CreateModel(GeneratorAttributeSyntaxContext ctx) { + INamedTypeSymbol symbol = (INamedTypeSymbol)ctx.TargetSymbol; + StructDeclarationSyntax syntax = (StructDeclarationSyntax)ctx.TargetNode; + Model model = new Model { Name = symbol.Name }; + + if (!syntax.Modifiers.Any(m => m.Text == "partial")) { + model.Error = Diagnostic.Create(NotPartial, syntax.Identifier.GetLocation(), symbol.Name); + return model; + } + + if (symbol.ContainingType != null || symbol.IsGenericType) { + model.Error = Diagnostic.Create(Unsupported, syntax.Identifier.GetLocation(), symbol.Name); + return model; + } + + model.Namespace = symbol.ContainingNamespace.IsGlobalNamespace ? null : symbol.ContainingNamespace.ToDisplayString(); + + AttributeData attribute = ctx.Attributes[0]; + if (attribute.ConstructorArguments.Length != 1 || !(attribute.ConstructorArguments[0].Value is int numBits) || numBits <= 0) { + model.Error = Diagnostic.Create(InvalidArguments, syntax.Identifier.GetLocation(), symbol.Name); + return model; + } + model.NumBits = numBits; + + INamedTypeSymbol? attributeClass = attribute.AttributeClass; + if (attributeClass != null && attributeClass.IsGenericType) { + ITypeSymbol wordType = attributeClass.TypeArguments[0]; + switch (wordType.SpecialType) { + case SpecialType.System_Byte: model.WordType = "byte"; model.BitsPerWord = 8; break; + case SpecialType.System_UInt16: model.WordType = "ushort"; model.BitsPerWord = 16; break; + case SpecialType.System_UInt32: model.WordType = "uint"; model.BitsPerWord = 32; break; + case SpecialType.System_UInt64: model.WordType = "ulong"; model.BitsPerWord = 64; break; + default: + model.Error = Diagnostic.Create(InvalidArguments, syntax.Identifier.GetLocation(), symbol.Name); + return model; + } + } + + return model; + } + + private static void Emit(SourceProductionContext spc, Model model) { + if (model.Error != null) { + spc.ReportDiagnostic(model.Error); + return; + } + + int numWords = (model.NumBits + model.BitsPerWord - 1) / model.BitsPerWord; + string name = model.Name; + string word = model.WordType; + string ops = $"global::Source.BitSetOps<{word}>"; + + StringBuilder sb = new StringBuilder(); + sb.AppendLine("// "); + sb.AppendLine("#nullable enable"); + sb.AppendLine(); + if (model.Namespace != null) { + sb.AppendLine($"namespace {model.Namespace};"); + sb.AppendLine(); + } + sb.AppendLine($"[global::System.Runtime.CompilerServices.InlineArray({numWords})]"); + sb.AppendLine($"partial struct {name} : global::System.IEquatable<{name}>"); + sb.AppendLine("{"); + sb.AppendLine($"\tprivate {word} _word;"); + sb.AppendLine(); + sb.AppendLine($"\tpublic const int NumBits = {model.NumBits};"); + sb.AppendLine(); + sb.AppendLine($"\tpublic readonly {word} GetWord(int i) => {ops}.GetWord(this, i);"); + sb.AppendLine($"\tpublic void SetWord(int i, {word} val) => {ops}.SetWord(this, i, val);"); + sb.AppendLine($"\tpublic readonly int GetNumWords() => {ops}.GetNumWords(this);"); + sb.AppendLine($"\tpublic readonly int Get(int bit) => {ops}.IsBitSet(this, bit) ? 1 : 0;"); + sb.AppendLine($"\tpublic readonly bool IsBitSet(int bit) => {ops}.IsBitSet(this, bit);"); + sb.AppendLine($"\tpublic void Set(int bit) => {ops}.Set(this, bit);"); + sb.AppendLine($"\tpublic void Clear(int bit) => {ops}.Clear(this, bit);"); + sb.AppendLine($"\tpublic void Set(int bit, bool newVal) => {ops}.Set(this, bit, newVal);"); + sb.AppendLine($"\tpublic readonly int FindNextSetBit(int startBit) => {ops}.FindNextSetBit(this, startBit);"); + sb.AppendLine($"\tpublic void ClearAll() => {ops}.ClearAll(this);"); + sb.AppendLine($"\tpublic void SetAll() => {ops}.SetAll(this);"); + sb.AppendLine($"\tpublic readonly bool IsAllClear() => {ops}.IsAllClear(this);"); + sb.AppendLine(); + foreach (string op in new[] { "And", "Or", "Xor" }) { + sb.AppendLine($"\tpublic readonly {name} {op}(in {name} other) {{"); + sb.AppendLine($"\t\t{name} result = default;"); + sb.AppendLine($"\t\t{ops}.{op}(this, other, result);"); + sb.AppendLine("\t\treturn result;"); + sb.AppendLine("\t}"); + } + sb.AppendLine(); + sb.AppendLine($"\tpublic readonly bool Equals({name} other) => {ops}.Compare(this, other);"); + sb.AppendLine($"\tpublic override readonly bool Equals(object? obj) => obj is {name} other && Equals(other);"); + sb.AppendLine($"\tpublic override readonly int GetHashCode() => {ops}.Hash(this);"); + sb.AppendLine($"\tpublic static bool operator ==({name} a, {name} b) => a.Equals(b);"); + sb.AppendLine($"\tpublic static bool operator !=({name} a, {name} b) => !a.Equals(b);"); + sb.AppendLine("}"); + + string hintName = model.Namespace != null ? $"{model.Namespace}.{name}.BitVec.g.cs" : $"{name}.BitVec.g.cs"; + spc.AddSource(hintName, SourceText.From(sb.ToString(), Encoding.UTF8)); + } + } +} diff --git a/Source.CodeAnalysis.BitVec/Source.CodeAnalysis.BitVec.csproj b/Source.CodeAnalysis.BitVec/Source.CodeAnalysis.BitVec.csproj new file mode 100644 index 000000000..5fe2175b2 --- /dev/null +++ b/Source.CodeAnalysis.BitVec/Source.CodeAnalysis.BitVec.csproj @@ -0,0 +1,19 @@ + + + + netstandard2.0 + false + true + true + latest + enable + false + Debug;Release;Debug (Dedicated);Release (Dedicated) + + + + + + + + diff --git a/Source.Common.Tests/BitSetGeneratorTests.cs b/Source.Common.Tests/BitSetGeneratorTests.cs new file mode 100644 index 000000000..81f906832 --- /dev/null +++ b/Source.Common.Tests/BitSetGeneratorTests.cs @@ -0,0 +1,87 @@ +namespace Source.Common.Tests; + +[BitVec(70)] +public partial struct TestBitSet70; + +[BitVec(13)] +public partial struct TestByteBitSet13; + +public class BitSetGeneratorTests +{ + [Fact] + public void StorageIsSizedFromBitCount() { + TestBitSet70 uintSet = default; + TestByteBitSet13 byteSet = default; + + Assert.Equal(70, TestBitSet70.NumBits); + Assert.Equal(3, uintSet.GetNumWords()); + Assert.Equal(13, TestByteBitSet13.NumBits); + Assert.Equal(2, byteSet.GetNumWords()); + } + + [Fact] + public void SetGetAndClear() { + TestBitSet70 set = default; + + set.Set(69); + Assert.True(set.IsBitSet(69)); + Assert.Equal(1, set.Get(69)); + Assert.Equal(69, set.FindNextSetBit(0)); + + set.Clear(69); + Assert.False(set.IsBitSet(69)); + Assert.Equal(0, set.Get(69)); + Assert.Equal(-1, set.FindNextSetBit(0)); + } + + [Fact] + public void WordsUseLittleEndianBitOrder() { + TestBitSet70 set = default; + set.Set(33); + + Assert.Equal(0u, set.GetWord(0)); + Assert.Equal(2u, set.GetWord(1)); + Assert.Equal(0u, set.GetWord(2)); + } + + [Fact] + public void EqualityAndHashFollowContent() { + TestBitSet70 a = default; + TestBitSet70 b = default; + a.Set(5); + b.Set(5); + + Assert.True(a == b); + Assert.False(a != b); + Assert.True(a.Equals(b)); + Assert.True(a.Equals((object)b)); + Assert.Equal(a.GetHashCode(), b.GetHashCode()); + + b.Set(64); + Assert.False(a == b); + Assert.True(a != b); + Assert.False(a.Equals((object)b)); + } + + [Fact] + public void ReadMembersWorkThroughReadOnlyReference() { + TestByteBitSet13 set = default; + set.Set(12); + + Assert.True(IsSetThroughIn(in set, 12)); + Assert.False(IsSetThroughIn(in set, 11)); + } + + static bool IsSetThroughIn(in TestByteBitSet13 set, int bit) => set.IsBitSet(bit); + + [Fact] + public void PlayerBitSetCoversAbsolutePlayerLimit() { + PlayerBitSet set = default; + + Assert.Equal(Constants.ABSOLUTE_PLAYER_LIMIT, PlayerBitSet.NumBits); + Assert.Equal(Constants.ABSOLUTE_PLAYER_LIMIT / 32, set.GetNumWords()); + + set.Set(Constants.ABSOLUTE_PLAYER_LIMIT - 1); + Assert.Equal(Constants.ABSOLUTE_PLAYER_LIMIT - 1, set.FindNextSetBit(0)); + } +} diff --git a/Source.Common.Tests/BitSetOpsTests.cs b/Source.Common.Tests/BitSetOpsTests.cs new file mode 100644 index 000000000..a936efd46 --- /dev/null +++ b/Source.Common.Tests/BitSetOpsTests.cs @@ -0,0 +1,139 @@ +using System.Numerics; + +namespace Source.Common.Tests; + +public abstract class BitSetOpsTests where T : unmanaged, IBinaryInteger, IUnsignedNumber +{ + const int NumWords = 3; + + static int BitsPerWord => BitSetOps.BitsPerWord; + static int NumBits => NumWords * BitsPerWord; + + public static TheoryData BoundaryBits() { + int bits = BitSetOps.BitsPerWord; + return [0, 1, bits - 1, bits, bits + 1, 2 * bits - 1, 2 * bits, 3 * bits - 1]; + } + + [Theory] + [MemberData(nameof(BoundaryBits))] + public void SetOnlyAffectsThatBit(int bit) { + Span words = stackalloc T[NumWords]; + BitSetOps.Set(words, bit); + + for (int i = 0; i < NumBits; i++) + Assert.Equal(i == bit, BitSetOps.IsBitSet(words, i)); + } + + [Theory] + [MemberData(nameof(BoundaryBits))] + public void ClearOnlyAffectsThatBit(int bit) { + Span words = stackalloc T[NumWords]; + BitSetOps.SetAll(words); + BitSetOps.Clear(words, bit); + + for (int i = 0; i < NumBits; i++) + Assert.Equal(i != bit, BitSetOps.IsBitSet(words, i)); + } + + [Theory] + [MemberData(nameof(BoundaryBits))] + public void SetWithValueSetsAndClears(int bit) { + Span words = stackalloc T[NumWords]; + + BitSetOps.Set(words, bit, true); + Assert.True(BitSetOps.IsBitSet(words, bit)); + + BitSetOps.Set(words, bit, false); + Assert.False(BitSetOps.IsBitSet(words, bit)); + Assert.Equal(-1, BitSetOps.FindNextSetBit(words, 0)); + } + + [Theory] + [MemberData(nameof(BoundaryBits))] + public void BitMapsToWordAndPosition(int bit) { + Span words = stackalloc T[NumWords]; + BitSetOps.Set(words, bit); + + for (int w = 0; w < NumWords; w++) { + T expected = w == bit / BitsPerWord ? T.One << (bit % BitsPerWord) : T.Zero; + Assert.Equal(expected, BitSetOps.GetWord(words, w)); + } + } + + [Fact] + public void SetWordIsVisibleAsBits() { + Span words = stackalloc T[NumWords]; + BitSetOps.SetWord(words, 1, T.One | (T.One << (BitsPerWord - 1))); + + Assert.True(BitSetOps.IsBitSet(words, BitsPerWord)); + Assert.True(BitSetOps.IsBitSet(words, 2 * BitsPerWord - 1)); + Assert.False(BitSetOps.IsBitSet(words, BitsPerWord + 1)); + } + + [Fact] + public void GetNumWordsIsSpanLength() { + Span words = stackalloc T[NumWords]; + Assert.Equal(NumWords, BitSetOps.GetNumWords(words)); + } + + [Fact] + public void FindNextSetBitOnEmptyReturnsMinusOne() { + Span words = stackalloc T[NumWords]; + Assert.Equal(-1, BitSetOps.FindNextSetBit(words, 0)); + } + + [Fact] + public void FindNextSetBitWalksAcrossWords() { + Span words = stackalloc T[NumWords]; + int first = 3; + int second = BitsPerWord + 2; + int third = 3 * BitsPerWord - 1; + BitSetOps.Set(words, first); + BitSetOps.Set(words, second); + BitSetOps.Set(words, third); + + Assert.Equal(first, BitSetOps.FindNextSetBit(words, 0)); + Assert.Equal(first, BitSetOps.FindNextSetBit(words, first)); + Assert.Equal(second, BitSetOps.FindNextSetBit(words, first + 1)); + Assert.Equal(third, BitSetOps.FindNextSetBit(words, second + 1)); + Assert.Equal(-1, BitSetOps.FindNextSetBit(words, third + 1)); + } + + [Fact] + public void FindNextSetBitPastEndReturnsMinusOne() { + Span words = stackalloc T[NumWords]; + BitSetOps.SetAll(words); + Assert.Equal(-1, BitSetOps.FindNextSetBit(words, NumBits)); + } + + [Fact] + public void SetAllAndClearAll() { + Span words = stackalloc T[NumWords]; + + BitSetOps.SetAll(words); + for (int i = 0; i < NumBits; i++) + Assert.True(BitSetOps.IsBitSet(words, i)); + + BitSetOps.ClearAll(words); + for (int i = 0; i < NumBits; i++) + Assert.False(BitSetOps.IsBitSet(words, i)); + } + + [Fact] + public void CompareAndHashFollowContent() { + Span a = stackalloc T[NumWords]; + Span b = stackalloc T[NumWords]; + BitSetOps.Set(a, BitsPerWord + 1); + BitSetOps.Set(b, BitsPerWord + 1); + + Assert.True(BitSetOps.Compare(a, b)); + Assert.Equal(BitSetOps.Hash(a), BitSetOps.Hash(b)); + + BitSetOps.Set(b, 0); + Assert.False(BitSetOps.Compare(a, b)); + } +} + +public sealed class ByteBitSetOpsTests : BitSetOpsTests; + +public sealed class UIntBitSetOpsTests : BitSetOpsTests; diff --git a/Source.Common.Tests/Source.Common.Tests.csproj b/Source.Common.Tests/Source.Common.Tests.csproj new file mode 100644 index 000000000..7ca852cdb --- /dev/null +++ b/Source.Common.Tests/Source.Common.Tests.csproj @@ -0,0 +1,27 @@ + + + + net10.0 + Exe + enable + enable + false + true + Debug;Release;Debug (Dedicated);Release (Dedicated) + bin\$(Configuration)\ + + + + + + + + + + + + + + + + diff --git a/Source.Common/BitSets.cs b/Source.Common/BitSets.cs new file mode 100644 index 000000000..50a94bf39 --- /dev/null +++ b/Source.Common/BitSets.cs @@ -0,0 +1,206 @@ +using Source.Common.Formats.BSP; +using Source.Common.Mathematics; + +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace Source; + +[AttributeUsage(AttributeTargets.Struct, Inherited = false)] +public sealed class BitVecAttribute(int numBits) : Attribute +{ + public int NumBits { get; } = numBits; +} + +[AttributeUsage(AttributeTargets.Struct, Inherited = false)] +public sealed class BitVecAttribute(int numBits) : Attribute where T : unmanaged, IBinaryInteger, IUnsignedNumber +{ + public int NumBits { get; } = numBits; +} + +public static class BitSetOps where T : unmanaged, IBinaryInteger, IUnsignedNumber +{ + public static int BitsPerWord => Unsafe.SizeOf() * 8; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T Mask(int bit) => T.One << (bit % BitsPerWord); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T GetWord(ReadOnlySpan words, int i) => words[i]; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + + public static void SetWord(Span words, int i, T val) => words[i] = val; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + + public static int GetNumWords(ReadOnlySpan words) => words.Length; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + + public static bool IsBitSet(ReadOnlySpan words, int bit) { + return (words[bit / BitsPerWord] & Mask(bit)) != T.Zero; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Set(Span words, int bit) { + words[bit / BitsPerWord] |= Mask(bit); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Clear(Span words, int bit) { + words[bit / BitsPerWord] &= ~Mask(bit); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Set(Span words, int bit, bool newVal) { + ref T word = ref words[bit / BitsPerWord]; + if (newVal) + word |= Mask(bit); + else + word &= ~Mask(bit); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ClearAll(Span words) { + words.Clear(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void SetAll(Span words) { + words.Fill(T.AllBitsSet); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool Compare(ReadOnlySpan a, ReadOnlySpan b) { + return a.SequenceEqual(b); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsAllClear(ReadOnlySpan words) { + return words.IndexOfAnyExcept(T.Zero) < 0; + } + + public static void And(ReadOnlySpan a, ReadOnlySpan b, Span result) { + for (int i = 0; i < result.Length; i++) + result[i] = a[i] & b[i]; + } + + public static void Or(ReadOnlySpan a, ReadOnlySpan b, Span result) { + for (int i = 0; i < result.Length; i++) + result[i] = a[i] | b[i]; + } + + public static void Xor(ReadOnlySpan a, ReadOnlySpan b, Span result) { + for (int i = 0; i < result.Length; i++) + result[i] = a[i] ^ b[i]; + } + + public static int Hash(ReadOnlySpan words) { + HashCode hash = new(); + hash.AddBytes(MemoryMarshal.AsBytes(words)); + return hash.ToHashCode(); + } + + public static int FindNextSetBit(ReadOnlySpan words, int startBit) { + int index = startBit / BitsPerWord; + if (index >= words.Length) + return -1; + + T word = words[index] & (T.AllBitsSet << (startBit % BitsPerWord)); + while (word == T.Zero) { + if (++index >= words.Length) + return -1; + word = words[index]; + } + return index * BitsPerWord + int.CreateTruncating(T.TrailingZeroCount(word)); + } +} + +/// +/// No idea if this works as it should... this is just simpler than porting the C++ right now +/// review later +/// +public struct VarBitSet +{ + public byte[] bytes; + public int NumBits; + public readonly int GetNumBits() => NumBits; + public void Resize(int resizeNumBits, bool clearAll = false) { + int numBytes = (resizeNumBits + 7) >> 3; + if (bytes == null) + bytes = new byte[numBytes]; + else if (numBytes != bytes.Length) + Array.Resize(ref bytes, numBytes); + else if (clearAll) + BitSetOps.ClearAll(bytes); + NumBits = resizeNumBits; + } + public void ReallocateIfNecessary(nint bitSet) { + if (bytes == null || Overflows(bitSet)) + Array.Resize(ref bytes, 1 + MathLib.CeilPow2((int)(bitSet >> 3))); + } + + public readonly bool Overflows(nint bit) { + return bytes == null || bit < 0 || (bit >> 3) >= bytes.Length; + } + + public int Get(int bit) { + if (Overflows(bit)) return 0; + return BitSetOps.IsBitSet(bytes, bit) ? 1 : 0; + } + public bool IsBitSet(int bit) { + if (Overflows(bit)) return false; + return BitSetOps.IsBitSet(bytes, bit); + } + public void Set(int bit) { + ReallocateIfNecessary(bit); + BitSetOps.Set(bytes, bit); + } + public void Clear(int bit) { + if (Overflows(bit)) return; + BitSetOps.Clear(bytes, bit); + } + public void Set(int bit, bool newVal) { + if (newVal == false && Overflows(bit)) + return; + ReallocateIfNecessary(bit); + BitSetOps.Set(bytes, bit, newVal); + } + public int FindNextSetBit(int startBit) => BitSetOps.FindNextSetBit(bytes, startBit); + public void ClearAll() => BitSetOps.ClearAll(bytes); + public bool TestAndSet(int bit) { + ReallocateIfNecessary(bit); + bool old = BitSetOps.IsBitSet(bytes, bit); + BitSetOps.Set(bytes, bit); + return old; + } +} + +/// +/// An inline bit-vector array of MAX_EDICTS >> 3 bytes. +/// +[BitVec(BSPFileCommon.MAX_DISPVERTS)] +public partial struct MaxDispVertsBitSet; + + +/// +/// An inline bit-vector array able to hold the 85 nodes of a 17x17 displacement. +/// +[BitVec(85)] +public partial struct DispNodeIntersectBitSet; + +/// +/// An inline bit-vector array of MAX_EDICTS >> 3 bytes. +/// +[BitVec(Constants.MAX_EDICTS)] +public partial struct MaxEdictsBitSet; + +/// +/// An inline bit-vector array of ABSOLUTE_PLAYER_LIMIT >> 3 bytes. +/// +[BitVec(Constants.ABSOLUTE_PLAYER_LIMIT)] +public partial struct PlayerBitSet; + +/// +/// An inline bit-vector array of MAX_EVENT_NUMBER >> 3 bytes. +/// +[BitVec(MAX_EVENT_NUMBER)] +public partial struct MaxEventNumberBitSet; diff --git a/Source.Common/BoneBitList.cs b/Source.Common/BoneBitList.cs index 74d52f587..480055655 100644 --- a/Source.Common/BoneBitList.cs +++ b/Source.Common/BoneBitList.cs @@ -2,18 +2,9 @@ namespace Source.Common; -[InlineArray(Studio.MAXSTUDIOBONES >> 3)] -public struct BoneBitList +[BitVec(Studio.MAXSTUDIOBONES)] +public partial struct BoneBitList { - public byte bytes; - - public int Get(int bit) => BitVecBase.IsBitSet(this, bit) ? 1 : 0; - public bool IsBitSet(int bit) => BitVecBase.IsBitSet(this, bit); - public void Set(int bit) => BitVecBase.Set(this, bit); - public void Clear(int bit) => BitVecBase.Clear(this, bit); - public void Set(int bit, bool newVal) => BitVecBase.Set(this, bit, newVal); - public int FindNextSetBit(int startBit) => BitVecBase.FindNextSetBit(this, startBit); - [MethodImpl(MethodImplOptions.AggressiveInlining)] public void MarkBone(int bone) => Set(bone); [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IsBoneMarked(int bone) => Get(bone) != 0; } diff --git a/Source.Common/BuildDisp.cs b/Source.Common/BuildDisp.cs index 9844280bc..dc85fb812 100644 --- a/Source.Common/BuildDisp.cs +++ b/Source.Common/BuildDisp.cs @@ -544,7 +544,7 @@ public class CoreDispInfo : DispUtilsHelper CoreDispInfo[]? ListBase; nint ListSize; - MaxDispVertsBitVec AllowedVerts; + MaxDispVertsBitSet AllowedVerts; nint ListIndex; @@ -928,7 +928,7 @@ public void CalcDispSurfCoords(bool lightmap, int lightmapID) { public void SetListIndex(nint index) => throw new NotImplementedException(); public nint GetListIndex() => throw new NotImplementedException(); - public ref MaxDispVertsBitVec GetAllowedVerts() => ref AllowedVerts; + public ref MaxDispVertsBitSet GetAllowedVerts() => ref AllowedVerts; public void AllowedVerts_Clear() => throw new NotImplementedException(); public int AllowedVerts_GetNumDWords() => throw new NotImplementedException(); public uint AllowedVerts_GetDWord(int i) => throw new NotImplementedException(); diff --git a/Source.Common/DispTesselate.cs b/Source.Common/DispTesselate.cs index 92cd27a87..2b08ad660 100644 --- a/Source.Common/DispTesselate.cs +++ b/Source.Common/DispTesselate.cs @@ -2,7 +2,7 @@ namespace Source.Common; public abstract class BaseTesselateHelper { - public MaxDispVertsBitVec ActiveVerts; + public MaxDispVertsBitSet ActiveVerts; public PowerInfo PowerInfo = null!; public int NIndices; diff --git a/Source.Common/Engine/DataTableSend.cs b/Source.Common/Engine/DataTableSend.cs index a418346a5..dd161ba12 100644 --- a/Source.Common/Engine/DataTableSend.cs +++ b/Source.Common/Engine/DataTableSend.cs @@ -1,21 +1,18 @@ -using System.Collections; - -namespace Source.Common.Engine; +namespace Source.Common.Engine; public class SendProxyRecipients { public const int MAX_DATATABLE_PROXIES = 32; - public BitArray Bits; + public PlayerBitSet Bits; - public SendProxyRecipients() => Bits = new(Constants.ABSOLUTE_PLAYER_LIMIT); - public void SetAllRecipients() => Bits.SetAll(true); - public void ClearAllRecipients() => Bits.SetAll(false); - public void SetRecipient(int clientIndex) => Bits.Set(clientIndex, true); - public void ClearRecipient(int clientIndex) => Bits.Set(clientIndex, false); - public bool GetRecipient(int clientIndex) => Bits[clientIndex]; + public void SetAllRecipients() => Bits.SetAll(); + public void ClearAllRecipients() => Bits.ClearAll(); + public void SetRecipient(int clientIndex) => Bits.Set(clientIndex); + public void ClearRecipient(int clientIndex) => Bits.Clear(clientIndex); + public bool GetRecipient(int clientIndex) => Bits.IsBitSet(clientIndex); public void SetOnly(int clientIndex) { - Bits.SetAll(false); - Bits.Set(clientIndex, true); + Bits.ClearAll(); + Bits.Set(clientIndex); } } diff --git a/Source.Common/Exts.cs b/Source.Common/Exts.cs index a942521c3..09814c212 100644 --- a/Source.Common/Exts.cs +++ b/Source.Common/Exts.cs @@ -39,212 +39,6 @@ public enum Realm Menu } -public static class BitVecBase -{ - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static uint GetDWord(this Span bytes, int i) { - return bytes.Cast()[i]; - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void SetDWord(this Span bytes, int i, uint val) { - bytes.Cast()[i] = val; - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] public static byte ByteMask(int bit) => (byte)(1 << (bit % 8)); - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool IsBitSet(this Span bytes, int bit) { - int byteIndex = bit >> 3; - byte b = bytes[byteIndex]; - return (b & ByteMask(bit)) != 0; - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Set(this Span bytes, int bit) { - ref byte b = ref bytes[bit >> 3]; - b |= ByteMask(bit); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Clear(this Span bytes, int bit) { - ref byte b = ref bytes[bit >> 3]; - b &= (byte)~ByteMask(bit); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Set(this Span bytes, int bit, bool newVal) { - ref byte b = ref bytes[bit >> 3]; - if (newVal) - b |= ByteMask(bit); - else - b &= (byte)~ByteMask(bit); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void ClearAll(this Span bytes) { - memreset(bytes); - } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static int FindNextSetBit(this Span bytes, int startBit) { - while ((startBit >> 3) < bytes.Length && !IsBitSet(bytes, startBit)) - startBit++; - if ((startBit >> 3) >= bytes.Length) - return -1; - return startBit; - } - - public static int GetNumDWords(this Span bytes) { - return bytes.Length == 0 ? 0 : (1 + ((bytes.Length - 1) / 4)); - } -} - -/// -/// No idea if this works as it should... this is just simpler than porting the C++ right now -/// review later -/// -public struct VarBitVec -{ - public byte[] bytes; - public int NumBits; - public readonly int GetNumBits() => NumBits; - public void Resize(int resizeNumBits, bool clearAll = false) { - int numBytes = (resizeNumBits + 7) >> 3; - if (bytes == null) - bytes = new byte[numBytes]; - else if (numBytes != bytes.Length) - Array.Resize(ref bytes, numBytes); - else if (clearAll) - BitVecBase.ClearAll(bytes); - NumBits = resizeNumBits; - } - public void ReallocateIfNecessary(nint bitSet) { - if (bytes == null || Overflows(bitSet)) - Array.Resize(ref bytes, 1 + MathLib.CeilPow2((int)(bitSet >> 3))); - } - - public readonly bool Overflows(nint bit) { - return bytes == null || bit < 0 || (bit >> 3) >= bytes.Length; - } - - public uint GetDWord(int i) => BitVecBase.GetDWord(bytes, i); - public int Get(int bit) { - if (Overflows(bit)) return 0; - return BitVecBase.IsBitSet(bytes, bit) ? 1 : 0; - } - public bool IsBitSet(int bit) { - if (Overflows(bit)) return false; - return BitVecBase.IsBitSet(bytes, bit); - } - public void Set(int bit) { - ReallocateIfNecessary(bit); - BitVecBase.Set(bytes, bit); - } - public void Clear(int bit) { - if (Overflows(bit)) return; - BitVecBase.Clear(bytes, bit); - } - public void Set(int bit, bool newVal) { - if (newVal == false && Overflows(bit)) - return; - ReallocateIfNecessary(bit); - BitVecBase.Set(bytes, bit, newVal); - } - public int FindNextSetBit(int startBit) => BitVecBase.FindNextSetBit(bytes, startBit); - public void ClearAll() => BitVecBase.ClearAll(bytes); - public bool TestAndSet(int bit) { - ReallocateIfNecessary(bit); - bool old = BitVecBase.IsBitSet(bytes, bit); - BitVecBase.Set(bytes, bit); - return old; - } -} - -/// -/// An inline bit-vector array of MAX_EDICTS >> 3 bytes. -/// -[InlineArray((BSPFileCommon.MAX_DISPVERTS + 31) / 32 * 4)] -public struct MaxDispVertsBitVec -{ - public byte bytes; - public uint GetDWord(int i) => BitVecBase.GetDWord(this, i); - public void SetDWord(int i, uint val) => BitVecBase.SetDWord(this, i, val); - public int GetNumDWords() => (BSPFileCommon.MAX_DISPVERTS + 31) / 32; - public int Get(int bit) => BitVecBase.IsBitSet(this, bit) ? 1 : 0; - public bool IsBitSet(int bit) => BitVecBase.IsBitSet(this, bit); - public void Set(int bit) => BitVecBase.Set(this, bit); - public void Clear(int bit) => BitVecBase.Clear(this, bit); - public void Set(int bit, bool newVal) => BitVecBase.Set(this, bit, newVal); - public int FindNextSetBit(int startBit) => BitVecBase.FindNextSetBit(this, startBit); - public void ClearAll() => BitVecBase.ClearAll(this); -} - - -/// -/// An inline bit-vector array able to hold the 85 nodes of a 17x17 displacement. -/// -[InlineArray((85 + 31) / 32 * 4)] -public struct DispNodeIntersectBitVec -{ - public byte bytes; - public uint GetDWord(int i) => BitVecBase.GetDWord(this, i); - public void SetDWord(int i, uint val) => BitVecBase.SetDWord(this, i, val); - public int GetNumDWords() => (85 + 31) / 32; - public int Get(int bit) => BitVecBase.IsBitSet(this, bit) ? 1 : 0; - public bool IsBitSet(int bit) => BitVecBase.IsBitSet(this, bit); - public void Set(int bit) => BitVecBase.Set(this, bit); - public void Clear(int bit) => BitVecBase.Clear(this, bit); - public void Set(int bit, bool newVal) => BitVecBase.Set(this, bit, newVal); - public int FindNextSetBit(int startBit) => BitVecBase.FindNextSetBit(this, startBit); - public void ClearAll() => BitVecBase.ClearAll(this); -} - -/// -/// An inline bit-vector array of MAX_EDICTS >> 3 bytes. -/// -[InlineArray(Constants.MAX_EDICTS >> 3)] -public struct MaxEdictsBitVec -{ - public byte bytes; - public uint GetDWord(int i) => BitVecBase.GetDWord(this, i); - public int Get(int bit) => BitVecBase.IsBitSet(this, bit) ? 1 : 0; - public bool IsBitSet(int bit) => BitVecBase.IsBitSet(this, bit); - public void Set(int bit) => BitVecBase.Set(this, bit); - public void Clear(int bit) => BitVecBase.Clear(this, bit); - public void Set(int bit, bool newVal) => BitVecBase.Set(this, bit, newVal); - public int FindNextSetBit(int startBit) => BitVecBase.FindNextSetBit(this, startBit); - public void ClearAll() => BitVecBase.ClearAll(this); - public int GetNumDWords() => BitVecBase.GetNumDWords(this); -} - -/// -/// An inline bit-vector array of ABSOLUTE_PLAYER_LIMIT >> 3 bytes. -/// -[InlineArray(Constants.ABSOLUTE_PLAYER_LIMIT >> 3)] -public struct AbsolutePlayerLimitBitVec -{ - public byte bytes; - public uint GetDWord(int i) => BitVecBase.GetDWord(this, i); - public int Get(int bit) => BitVecBase.IsBitSet(this, bit) ? 1 : 0; - public bool IsBitSet(int bit) => BitVecBase.IsBitSet(this, bit); - public void Set(int bit) => BitVecBase.Set(this, bit); - public void Clear(int bit) => BitVecBase.Clear(this, bit); - public void Set(int bit, bool newVal) => BitVecBase.Set(this, bit, newVal); - public int FindNextSetBit(int startBit) => BitVecBase.FindNextSetBit(this, startBit); - public void ClearAll() => BitVecBase.ClearAll(this); -} - -/// -/// An inline bit-vector array of MAX_EVENT_NUMBER >> 3 bytes. -/// -[InlineArray(MAX_EVENT_NUMBER >> 3)] -public struct MaxEventNumberBitVec -{ - public byte bytes; - public uint GetDWord(int i) => BitVecBase.GetDWord(this, i); - public void SetDWord(int i, uint val) => BitVecBase.SetDWord(this, i, val); - public int Get(int bit) => BitVecBase.IsBitSet(this, bit) ? 1 : 0; - public bool IsBitSet(int bit) => BitVecBase.IsBitSet(this, bit); - public void Set(int bit) => BitVecBase.Set(this, bit); - public void Clear(int bit) => BitVecBase.Clear(this, bit); - public void Set(int bit, bool newVal) => BitVecBase.Set(this, bit, newVal); - public int FindNextSetBit(int startBit) => BitVecBase.FindNextSetBit(this, startBit); - public void ClearAll() => BitVecBase.ClearAll(this); -} - public interface IPoolableObject { void Init(); diff --git a/Source.Common/IServerNetworkable.cs b/Source.Common/IServerNetworkable.cs index d0818c144..5ecda4262 100644 --- a/Source.Common/IServerNetworkable.cs +++ b/Source.Common/IServerNetworkable.cs @@ -22,8 +22,8 @@ public class CheckTransmitInfo { public readonly byte[] PVS = new byte[(((BSPFileCommon.MAX_MAP_CLUSTERS + (8 - 1)) / 8) * 8) / 8]; public int PVSSize; - public MaxEdictsBitVec TransmitEdict; // THESE ARE POINTERS IN C++: FIGURE THIS OUT!!! - public MaxEdictsBitVec TransmitAlways; // THESE ARE POINTERS IN C++: FIGURE THIS OUT!!! + public MaxEdictsBitSet TransmitEdict; // THESE ARE POINTERS IN C++: FIGURE THIS OUT!!! + public MaxEdictsBitSet TransmitAlways; // THESE ARE POINTERS IN C++: FIGURE THIS OUT!!! public int AreasNetworked; public InlineArrayMaxWorldAreas Areas; diff --git a/Source.Common/Networking/NetMessages.cs b/Source.Common/Networking/NetMessages.cs index 40848f2e4..c1b6c0e42 100644 --- a/Source.Common/Networking/NetMessages.cs +++ b/Source.Common/Networking/NetMessages.cs @@ -1061,7 +1061,7 @@ public class CLC_ListenEvents : NetMessage, IPoolableObject { public CLC_ListenEvents() : base(CLC.ListenEvents) { } public override NetChannelGroup GetGroup() => NetChannelGroup.SignOn; - public MaxEventNumberBitVec EventArray = new(); + public MaxEventNumberBitSet EventArray = new(); public void Init() { } public void Reset() { @@ -1072,7 +1072,7 @@ public override bool WriteToBuffer(bf_write buffer) { buffer.WriteNetMessageType(this); int count = MAX_EVENT_NUMBER / 32; for (int i = 0; i < count; i++) - buffer.WriteUBitLong(EventArray.GetDWord(i), 32); + buffer.WriteUBitLong(EventArray.GetWord(i), 32); return !buffer.Overflowed; } @@ -1080,7 +1080,7 @@ public override bool WriteToBuffer(bf_write buffer) { public override bool ReadFromBuffer(bf_read buffer) { int count = MAX_EVENT_NUMBER / 32; for (int i = 0; i < count; i++) - EventArray.SetDWord(i, buffer.ReadUBitLong(32)); + EventArray.SetWord(i, buffer.ReadUBitLong(32)); return !buffer.Overflowed; } diff --git a/Source.Common/Server/IEngineServer.cs b/Source.Common/Server/IEngineServer.cs index 851c264af..0b0f819dc 100644 --- a/Source.Common/Server/IEngineServer.cs +++ b/Source.Common/Server/IEngineServer.cs @@ -110,7 +110,7 @@ public interface IEngineServer void StaticDecal(in Vector3 originInEntitySpace, int decalIndex, int entityIndex, int modelIndex, bool lowpriority); // Given the current PVS(or PAS) and origin, determine which players should hear/receive the message - void Message_DetermineMulticastRecipients(bool usepas, in Vector3 origin, ref AbsolutePlayerLimitBitVec playerbits); + void Message_DetermineMulticastRecipients(bool usepas, in Vector3 origin, ref PlayerBitSet playerbits); // Begin a message from a server side entity to its client side counterpart (func_breakable glass, e.g.) bf_write? EntityMessageBegin(int ent_index, ServerClass ent_class, bool reliable); @@ -221,7 +221,7 @@ public interface IEngineServer // Also, this will return NULL if the client doesn't exist or if this client hasn't acked any frames yet. // // iClientIndex is the CLIENT index, so if you use pPlayer->entindex(), subtract 1. - ref readonly MaxEdictsBitVec GetEntityTransmitBitsForClient(int iClientIndex); + ref readonly MaxEdictsBitSet GetEntityTransmitBitsForClient(int iClientIndex); // Is the game paused? bool IsPaused(); diff --git a/Source.Common/Source.Common.csproj b/Source.Common/Source.Common.csproj index cd3c28087..333ff1651 100644 --- a/Source.Common/Source.Common.csproj +++ b/Source.Common/Source.Common.csproj @@ -35,6 +35,7 @@ + diff --git a/Source.Engine/CL.cs b/Source.Engine/CL.cs index 5e107fa7a..252f2e7d9 100644 --- a/Source.Engine/CL.cs +++ b/Source.Engine/CL.cs @@ -380,7 +380,7 @@ private void CallPostDataUpdates(EntityReadInfo u) { } } - private void MarkEntitiesOutOfPVS(ref MaxEdictsBitVec pvsFlags) { + private void MarkEntitiesOutOfPVS(ref MaxEdictsBitSet pvsFlags) { int highest_index = EntityList.GetHighestEntityIndex(); for (int i = 0; i <= highest_index; i++) { IClientNetworkable? ent = EntityList.GetClientNetworkable(i); diff --git a/Source.Engine/CModel_Private.cs b/Source.Engine/CModel_Private.cs index 2c4d44358..988ad343a 100644 --- a/Source.Engine/CModel_Private.cs +++ b/Source.Engine/CModel_Private.cs @@ -18,8 +18,8 @@ namespace Source.Engine; internal class TraceVisits { - public AbsolutePlayerLimitBitVec m_Brushes; - public VarBitVec m_Disps; + public PlayerBitSet m_Brushes; + public VarBitSet m_Disps; } diff --git a/Source.Engine/ClientFrame.cs b/Source.Engine/ClientFrame.cs index c83f70c24..d484bd73c 100644 --- a/Source.Engine/ClientFrame.cs +++ b/Source.Engine/ClientFrame.cs @@ -12,9 +12,9 @@ public class ClientFrame : IPoolableObject public int LastEntity; public long TickCount; - public MaxEdictsBitVec TransmitEntity; - public MaxEdictsBitVec FromBaseline; - public MaxEdictsBitVec TransmitAlways; + public MaxEdictsBitSet TransmitEntity; + public MaxEdictsBitSet FromBaseline; + public MaxEdictsBitSet TransmitAlways; public ClientFrame? Next; public FrameSnapshot? Snapshot; diff --git a/Source.Engine/Disp.cs b/Source.Engine/Disp.cs index a13f62b08..79c3b1192 100644 --- a/Source.Engine/Disp.cs +++ b/Source.Engine/Disp.cs @@ -93,7 +93,7 @@ public enum DecalFlags : byte public struct DispDecalBase { - public DispNodeIntersectBitVec NodeIntersect; + public DispNodeIntersectBitSet NodeIntersect; public DecalFlags Flags; public ushort NVerts; diff --git a/Source.Engine/DispInfo.cs b/Source.Engine/DispInfo.cs index 29da9a3c2..9c7024779 100644 --- a/Source.Engine/DispInfo.cs +++ b/Source.Engine/DispInfo.cs @@ -28,8 +28,8 @@ public class DispInfo : DispUtilsHelper, IDispInfo public readonly List Indices = []; public readonly List Verts = []; - public MaxDispVertsBitVec ActiveVerts; - public MaxDispVertsBitVec AllowedVerts; + public MaxDispVertsBitSet ActiveVerts; + public MaxDispVertsBitSet AllowedVerts; int LMPageID; diff --git a/Source.Engine/DispMapload.cs b/Source.Engine/DispMapload.cs index 9fb9fe517..729a0cf76 100644 --- a/Source.Engine/DispMapload.cs +++ b/Source.Engine/DispMapload.cs @@ -295,9 +295,9 @@ public static bool DispInfo_CreateFromMapDisp(Model world, int disp, ref BSPDDis coreDisp.InitDispInfo(mapDisp.Power, mapDisp.MinTess, mapDisp.SmoothingAngle, verts, tris); coreDisp.SetNeighborData(mapDisp.EdgeNeighbors, mapDisp.CornerNeighbors); - ErrorIfNot(coreDisp.GetAllowedVerts().GetNumDWords() == 10, $"DispInfo_StoreMapData: size mismatch in 'allowed verts' list ({coreDisp.GetAllowedVerts().GetNumDWords()} != 10)"); - for (int iVert = 0; iVert < coreDisp.GetAllowedVerts().GetNumDWords(); ++iVert) - coreDisp.GetAllowedVerts().SetDWord(iVert, (uint)mapDisp.AllowedVerts[iVert]); + ErrorIfNot(coreDisp.GetAllowedVerts().GetNumWords() == 10, $"DispInfo_StoreMapData: size mismatch in 'allowed verts' list ({coreDisp.GetAllowedVerts().GetNumWords()} != 10)"); + for (int iVert = 0; iVert < coreDisp.GetAllowedVerts().GetNumWords(); ++iVert) + coreDisp.GetAllowedVerts().SetWord(iVert, (uint)mapDisp.AllowedVerts[iVert]); ref BSPMSurface2 parent = ref pDisp.GetParent(); BuildDispSurfInit(world, coreDisp, ref parent); diff --git a/Source.Engine/EngineSendTable.cs b/Source.Engine/EngineSendTable.cs index 1e87adc67..11cb0b6d5 100644 --- a/Source.Engine/EngineSendTable.cs +++ b/Source.Engine/EngineSendTable.cs @@ -399,13 +399,13 @@ void AddProp(int prop) { if (NewStateProxies == null || curChild.GetDataTableProxyIndex() >= NumNewStateProxies) Error($"PropCullStack::CallPropProxy - invalid new state proxy index {curChild.GetDataTableProxyIndex()} (num new state proxies: {NumNewStateProxies})"); - bool cur = NewStateProxies[curChild.GetDataTableProxyIndex()].Bits.Get(Client); + bool cur = NewStateProxies[curChild.GetDataTableProxyIndex()].Bits.IsBitSet(Client); if (OldStateProxies != null) { if (curChild.GetDataTableProxyIndex() >= NumOldStateProxies) Error($"PropCullStack::CallPropProxy - invalid old state proxy index {curChild.GetDataTableProxyIndex()} (num old state proxies: {NumOldStateProxies})"); - bool prev = OldStateProxies[curChild.GetDataTableProxyIndex()].Bits.Get(Client); + bool prev = OldStateProxies[curChild.GetDataTableProxyIndex()].Bits.IsBitSet(Client); if (prev != cur) { if (prev) return null; diff --git a/Source.Engine/EngineServerImpl.cs b/Source.Engine/EngineServerImpl.cs index 46b8c59d6..04689ca68 100644 --- a/Source.Engine/EngineServerImpl.cs +++ b/Source.Engine/EngineServerImpl.cs @@ -490,16 +490,16 @@ public int GetClusterForOrigin(in Vector3 org) { public int GetEntityCount() => sv.NumEdicts - sv.FreeEdicts; - public ref readonly MaxEdictsBitVec GetEntityTransmitBitsForClient(int iClientIndex) { + public ref readonly MaxEdictsBitSet GetEntityTransmitBitsForClient(int iClientIndex) { if (iClientIndex < 0 || iClientIndex >= sv.GetClientCount()) { Assert(false); - return ref Unsafe.NullRef(); + return ref Unsafe.NullRef(); } GameClient client = sv.Client(iClientIndex); ClientFrame? deltaFrame = client.FrameManager.GetClientFrame(client.DeltaTick); if (deltaFrame == null) - return ref Unsafe.NullRef(); + return ref Unsafe.NullRef(); return ref deltaFrame.TransmitEntity; } @@ -727,7 +727,7 @@ public void MessageEnd() { s_MsgData.Reset(); // clear message data } - public void Message_DetermineMulticastRecipients(bool usepas, in Vector3 origin, ref AbsolutePlayerLimitBitVec playerbits) { + public void Message_DetermineMulticastRecipients(bool usepas, in Vector3 origin, ref PlayerBitSet playerbits) { int cluster = CM.LeafCluster(CM.PointLeafnum(origin)); byte[] pvs = new byte[BSPFileCommon.MAX_MAP_LEAFS / 8]; int visflag = usepas ? CM.DVIS_PAS : CM.DVIS_PVS; diff --git a/Source.Engine/GLRSurf.cs b/Source.Engine/GLRSurf.cs index 0e3172522..f35dab5ba 100644 --- a/Source.Engine/GLRSurf.cs +++ b/Source.Engine/GLRSurf.cs @@ -151,7 +151,7 @@ public class WorldRenderList : IWorldRenderList public readonly List VisibleLeaves = []; public readonly List VisibleLeafFogVolumes = []; - public VarBitVec VisitedSurfs = new(); + public VarBitSet VisitedSurfs = new(); public bool SkyVisible; int Refs = 1; @@ -335,9 +335,9 @@ public static void BuildIndicesForWorldSurface(ref MeshBuilder meshBuilder, Surf public static void Surf_ComputeCentroid(SurfaceHandle_t surfID, out Vector3 vecCentroid) => throw new NotImplementedException(); public static int SortInfoToLightmapPage(int sortID) => throw new NotImplementedException(); public static IWorldRenderList AllocWorldRenderList() => WorldRenderList.FindOrCreateList(host_state!.WorldBrush!.NumSurfaces); - [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool VisitSurface(ref VarBitVec visitedSurfs, SurfaceHandle_t surfID) => !visitedSurfs.TestAndSet(surfID); - [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void MarkSurfaceVisited(ref VarBitVec visitedSurfs, SurfaceHandle_t surfID) => visitedSurfs.Set(surfID); - [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool VisitedSurface(ref VarBitVec visitedSurfs, int index) => visitedSurfs.IsBitSet(index); + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool VisitSurface(ref VarBitSet visitedSurfs, SurfaceHandle_t surfID) => !visitedSurfs.TestAndSet(surfID); + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void MarkSurfaceVisited(ref VarBitSet visitedSurfs, SurfaceHandle_t surfID) => visitedSurfs.Set(surfID); + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool VisitedSurface(ref VarBitSet visitedSurfs, int index) => visitedSurfs.IsBitSet(index); public static void R_DrawTopView(bool enable) => throw new NotImplementedException(); public static void R_TopViewBounds(in Vector2 mins, in Vector2 maxs) => throw new NotImplementedException(); @@ -1026,7 +1026,7 @@ static void DrawDisplacementsInLeaf(WorldRenderList renderList, BSPMLeaf leaf) { if (leaf.DispCount == 0) return; - ref VarBitVec visitedSurfs = ref renderList.VisitedSurfs; + ref VarBitSet visitedSurfs = ref renderList.VisitedSurfs; for (int i = 0; i < leaf.DispCount; i++) { IDispInfo dispInfo = DispInfo.MLeaf_Disaplcement(leaf, i)!; @@ -1067,7 +1067,7 @@ static void R_DrawLeaf(WorldRenderList renderList, BSPMLeaf pleaf) { int i; int surfaceCount = pleaf.NumMarkNodeSurfaces; Span pSurfID = host_state.WorldBrush!.MarkSurfaces.AsSpan(pleaf.FirstMarkSurface); - ref VarBitVec visitedSurfs = ref renderList.VisitedSurfs; + ref VarBitSet visitedSurfs = ref renderList.VisitedSurfs; for (i = 0; i < surfaceCount; ++i) { SurfaceHandle_t surfID = pSurfID[i]; ref BSPMSurface2 surface = ref ModelLoader.SurfaceHandleFromIndex(surfID); @@ -1142,7 +1142,7 @@ static void R_RecursiveWorldNode(WorldRenderList renderList, BSPMNode node, int SurfaceHandle_t surfID = node.FirstSurface; int i = ModelLoader.MSurf_Index(ref ModelLoader.SurfaceHandleFromIndex(surfID)); int lastSurface = i + node.NumSurfaces; - ref VarBitVec visitedSurfs = ref renderList.VisitedSurfs; + ref VarBitSet visitedSurfs = ref renderList.VisitedSurfs; for (; i < lastSurface; ++i, ++surfID) { if (!VisitedSurface(ref visitedSurfs, i)) continue; diff --git a/Source.Engine/LocalNetworkBackdoor.cs b/Source.Engine/LocalNetworkBackdoor.cs index 40e13c601..6ccba9f8c 100644 --- a/Source.Engine/LocalNetworkBackdoor.cs +++ b/Source.Engine/LocalNetworkBackdoor.cs @@ -42,12 +42,12 @@ public void EndEntityStateUpdate() { ClientDLL.FrameStageNotify(Source.Common.Client.ClientFrameStage.NetUpdatePostDataUpdateEnd); // Handle entities removed (= SV_WriteDeletions() in normal mode) - int nDWords = PrevEntsAlive.GetNumDWords(); + int nDWords = PrevEntsAlive.GetNumWords(); // Handle entities removed. for (i = 0; i < nDWords; i++) { - uint prevEntsAlive = PrevEntsAlive.GetDWord(i); - uint entsAlive = EntsAlive.GetDWord(i); + uint prevEntsAlive = PrevEntsAlive.GetWord(i); + uint entsAlive = EntsAlive.GetWord(i); uint toDelete = (prevEntsAlive ^ entsAlive) & prevEntsAlive; if (toDelete != 0) { @@ -311,8 +311,8 @@ ref nFastCopyProps } } - MaxEdictsBitVec EntsAlive; - MaxEdictsBitVec PrevEntsAlive; + MaxEdictsBitSet EntsAlive; + MaxEdictsBitSet PrevEntsAlive; InlineArrayMaxEdicts EntsCreatedIndices; int EntsCreated; InlineArrayMaxEdicts EntsChangedIndices; diff --git a/Source.Engine/PackedEntity.cs b/Source.Engine/PackedEntity.cs index d4c3a463b..d818e7d62 100644 --- a/Source.Engine/PackedEntity.cs +++ b/Source.Engine/PackedEntity.cs @@ -89,12 +89,8 @@ public bool CompareRecipients(ReadOnlySpan recipients) { return false; for (int i = 0; i < recipients.Length; i++) { - var a = recipients[i].Bits; - var b = Recipients[i].Bits; - for (int bit = 0; bit < a.Length; bit++) { - if (a[bit] != b[bit]) - return false; - } + if (recipients[i].Bits != Recipients[i].Bits) + return false; } return true; diff --git a/Source.Engine/PrEdict.cs b/Source.Engine/PrEdict.cs index 86659a5e0..4bf8b1209 100644 --- a/Source.Engine/PrEdict.cs +++ b/Source.Engine/PrEdict.cs @@ -31,7 +31,7 @@ public class ED static readonly ConVar sv_useexplicitdelete = new("1", FCvar.DevelopmentOnly, "Explicitly delete dormant client entities caused by AllowImmediateReuse()."); static readonly ConVar sv_lowEdicthreshold = new("8", FCvar.None, "When only this many edicts are free, take the action specified by sv_lowedict_action.", 0, Constants.MAX_EDICTS); static readonly ConVar sv_lowedict_action = new("0", FCvar.None, "0 - no action, 1 - warn to log file, 2 - attempt to restart the game, if applicable, 3 - restart the map, 4 - go to the next map in the map cycle, 5 - spew all edicts.", 0, 5); - static MaxEdictsBitVec FreeEdicts; + static MaxEdictsBitSet FreeEdicts; public static Edict? Alloc(int forceEdictIndex) { if (forceEdictIndex >= 0) { diff --git a/Source.Engine/Server/BaseClient.cs b/Source.Engine/Server/BaseClient.cs index fca2fa6f6..7314aa276 100644 --- a/Source.Engine/Server/BaseClient.cs +++ b/Source.Engine/Server/BaseClient.cs @@ -818,7 +818,7 @@ public bool SendNetMsg(INetMessage msg, bool forceReliable = false) { FrameSnapshot? LastSnapshot; // todo? ^ public FrameSnapshot? Baseline; public int BaselineUpdateTick; - public MaxEdictsBitVec BaselinesSent; + public MaxEdictsBitSet BaselinesSent; public int BaselineUsed; public int ForceWaitForTick; diff --git a/Source.Engine/Server/EntsWrite.cs b/Source.Engine/Server/EntsWrite.cs index fc1acc8de..bd98ef437 100644 --- a/Source.Engine/Server/EntsWrite.cs +++ b/Source.Engine/Server/EntsWrite.cs @@ -10,7 +10,7 @@ class EntityWriteInfo : EntityInfo public int ClientEntity; public PackedEntity? OldPack; public PackedEntity? NewPack; - public MaxEdictsBitVec DeletionFlags; + public MaxEdictsBitSet DeletionFlags; public FrameSnapshot? FromSnapshot; // = From->GetSnapshot(); public FrameSnapshot ToSnapshot; // = m_pTo->GetSnapshot(); public FrameSnapshot Baseline; // the clients baseline diff --git a/Source.Engine/Server/GameClient.cs b/Source.Engine/Server/GameClient.cs index 9d60fc360..88d74de0b 100644 --- a/Source.Engine/Server/GameClient.cs +++ b/Source.Engine/Server/GameClient.cs @@ -40,8 +40,8 @@ public GameClient(int slot, BaseServer server) { IsInReplayMode = false; } public bool VoiceLoopback; - public AbsolutePlayerLimitBitVec VoiceStreams; - public AbsolutePlayerLimitBitVec VoiceProximity; + public PlayerBitSet VoiceStreams; + public PlayerBitSet VoiceProximity; public int LastMovementTick; public int SoundSequence; public Edict Edict = null!; @@ -52,7 +52,7 @@ public GameClient(int slot, BaseServer server) { public readonly CheckTransmitInfo PackInfo = new(); public bool IsInReplayMode; public readonly CheckTransmitInfo PrevPackInfo = new(); - public MaxEdictsBitVec PrevTransmitEdict; + public MaxEdictsBitSet PrevTransmitEdict; protected override bool ProcessClientInfo(CLC_ClientInfo msg) { base.ProcessClientInfo(msg); diff --git a/Source.NET.slnx b/Source.NET.slnx index 346cce269..ea8b4b413 100644 --- a/Source.NET.slnx +++ b/Source.NET.slnx @@ -19,6 +19,9 @@ + + + @@ -141,6 +144,11 @@ + + + + + diff --git a/global.json b/global.json new file mode 100644 index 000000000..f17b86a55 --- /dev/null +++ b/global.json @@ -0,0 +1,5 @@ +{ + "test": { + "runner": "Microsoft.Testing.Platform" + } +}