From 6e18245c8b6aba72272224b6a141c3969c0ff311 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:36:12 +0200 Subject: [PATCH] Generate entity factories with a source generator --- Game.Client/ClassMap.cs | 20 -- Game.Client/Game.Client.csproj | 1 + Game.Server/Game.Server.csproj | 2 + Game.Server/SourceDllMain.cs | 6 - Game.Server/Util.cs | 17 -- .../EntityFactoryGenerator.cs | 204 ++++++++++++++++++ ...Source.CodeAnalysis.EntityFactories.csproj | 19 ++ Source.NET.slnx | 3 + 8 files changed, 229 insertions(+), 43 deletions(-) create mode 100644 Source.CodeAnalysis.EntityFactories/EntityFactoryGenerator.cs create mode 100644 Source.CodeAnalysis.EntityFactories/Source.CodeAnalysis.EntityFactories.csproj diff --git a/Game.Client/ClassMap.cs b/Game.Client/ClassMap.cs index 7b37e5f36..da1bd2914 100644 --- a/Game.Client/ClassMap.cs +++ b/Game.Client/ClassMap.cs @@ -6,8 +6,6 @@ using System; using System.Collections.Generic; -using System.Reflection; -using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; @@ -32,24 +30,6 @@ public class ClassMap : IClassMap { public static readonly ClassMap g_ClassMap = new(); public static ClassMap GetClassMap() => g_ClassMap; - static ClassMap() { - // Here is where we start initializing things based on LinkEntityToClassAttribute's - var typePairs = Assembly.GetExecutingAssembly().GetTypesWithAttributeMulti(); - foreach (var type in typePairs) { - var attr = type.Value; - - DynamicMethod m = new DynamicMethod("LinkEntity_Instantiate" + type.Key.Name + "_ToMap_" + attr.LocalName, typeof(C_BaseEntity), []); - ILGenerator il = m.GetILGenerator(); - - il.Emit(OpCodes.Newobj, type.Key.GetConstructor([]) ?? throw new Exception("no constructor for auto factory")); - il.Emit(OpCodes.Castclass, typeof(C_BaseEntity)); - il.Emit(OpCodes.Ret); - - DispatchFunction dispatch = m.CreateDelegate(); - - GetClassMap().Add(type.Key, attr.LocalName, type.Key.Name, dispatch); - } - } readonly Dictionary ClassDict = []; diff --git a/Game.Client/Game.Client.csproj b/Game.Client/Game.Client.csproj index 78929b603..7f2eb8ea1 100644 --- a/Game.Client/Game.Client.csproj +++ b/Game.Client/Game.Client.csproj @@ -38,6 +38,7 @@ + diff --git a/Game.Server/Game.Server.csproj b/Game.Server/Game.Server.csproj index 42bbf67e0..19e23fc2e 100644 --- a/Game.Server/Game.Server.csproj +++ b/Game.Server/Game.Server.csproj @@ -17,6 +17,8 @@ OutputItemType="Analyzer" ReferenceOutputAssembly="false" /> + diff --git a/Game.Server/SourceDllMain.cs b/Game.Server/SourceDllMain.cs index b3fd5d80f..1a079baba 100644 --- a/Game.Server/SourceDllMain.cs +++ b/Game.Server/SourceDllMain.cs @@ -1,7 +1,5 @@ using Game.Shared; -using Microsoft.Extensions.DependencyInjection; - using Source; using Source.Common; using Source.Common.Commands; @@ -18,10 +16,6 @@ namespace Game.Server; public static class SourceDllMain { - public static void Link(IServiceCollection services) { - ClassMap.Init(); - } - [Dependency] public static IEngineServer engine { get; private set; } = null!; [Dependency] public static IFileSystem filesystem { get; private set; } = null!; [Dependency] public static ServerGlobalVariables gpGlobals { get; private set; } = null!; diff --git a/Game.Server/Util.cs b/Game.Server/Util.cs index 9446be768..b19b4defd 100644 --- a/Game.Server/Util.cs +++ b/Game.Server/Util.cs @@ -31,23 +31,6 @@ namespace Game; -public static class ClassMap -{ - static bool Initialized; - public static void Init() { - if (Initialized) return; - Initialized = true; - // Here is where we start initializing things based on LinkEntityToClassAttribute's - var typePairs = Assembly.GetExecutingAssembly().GetTypesWithAttributeMulti(); - foreach (var type in typePairs) { - var attr = type.Value; - - var factoryType = typeof(CEntityFactory<>).MakeGenericType(type.Key); - Activator.CreateInstance(factoryType, [type.Value.LocalName]); - } - } -} - public interface IEntityFactory { IServerNetworkable? Create(ReadOnlySpan className); diff --git a/Source.CodeAnalysis.EntityFactories/EntityFactoryGenerator.cs b/Source.CodeAnalysis.EntityFactories/EntityFactoryGenerator.cs new file mode 100644 index 000000000..622f95f20 --- /dev/null +++ b/Source.CodeAnalysis.EntityFactories/EntityFactoryGenerator.cs @@ -0,0 +1,204 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Text; + +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Text; + +namespace Source.CodeAnalysis.EntityFactories +{ + [Generator(LanguageNames.CSharp)] + public sealed class EntityFactoryGenerator : IIncrementalGenerator + { + const string LinkAttribute = "Game.Shared.LinkEntityToClassAttribute"; + const string ClientClassMap = "Game.Client.ClassMap"; + const string ClientBaseEntity = "Game.Client.C_BaseEntity"; + const string ServerFactory = "Game.CEntityFactory`1"; + const string G = "global::"; + + static readonly DiagnosticDescriptor Skipped = new DiagnosticDescriptor( + id: "ENTFACT001", + title: "Linked entity class cannot get a generated factory", + messageFormat: "'{0}' is linked to '{1}' but {2}, so no factory is registered", + category: "EntityFactories", + defaultSeverity: DiagnosticSeverity.Warning, + isEnabledByDefault: true); + + enum Side { None, Client, Server } + enum Ctor { Missing, Public, Internal, Hidden } + + sealed class Entry : IEquatable + { + public string TypeName = ""; + public string Name = ""; + public string[] LocalNames = Array.Empty(); + public string[] Bases = Array.Empty(); + public bool IsGeneric; + public bool IsAbstract; + public bool IsAccessible; + public Ctor Ctor; + public Location? Location; + + public bool Equals(Entry? other) => + other != null && TypeName == other.TypeName && Name == other.Name && IsGeneric == other.IsGeneric && IsAbstract == other.IsAbstract + && IsAccessible == other.IsAccessible && Ctor == other.Ctor && LocalNames.SequenceEqual(other.LocalNames) + && Bases.SequenceEqual(other.Bases) && Equals(Location, other.Location); + public override bool Equals(object? obj) => Equals(obj as Entry); + public override int GetHashCode() => TypeName.GetHashCode(); + } + + public void Initialize(IncrementalGeneratorInitializationContext context) { + IncrementalValuesProvider entries = context.SyntaxProvider.ForAttributeWithMetadataName( + LinkAttribute, + static (node, _) => true, + static (ctx, _) => Transform(ctx)) + .Where(static e => e != null) + .Select(static (e, _) => e!); + + IncrementalValueProvider<(Side, string)> side = context.CompilationProvider.Select(static (compilation, _) => DetectSide(compilation)); + + context.RegisterSourceOutput(entries.Collect().Combine(side), static (spc, input) => Execute(spc, input.Left, input.Right.Item1, input.Right.Item2)); + } + + static (Side, string) DetectSide(Compilation compilation) { + if (compilation.GetTypeByMetadataName(ClientClassMap) != null) { + INamedTypeSymbol? baseEntity = compilation.GetTypeByMetadataName(ClientBaseEntity); + return baseEntity == null ? (Side.None, "") : (Side.Client, baseEntity.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)); + } + + INamedTypeSymbol? factory = compilation.GetTypeByMetadataName(ServerFactory); + if (factory != null) { + ITypeSymbol? constraint = factory.TypeParameters[0].ConstraintTypes.FirstOrDefault(); + return (Side.Server, constraint?.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) ?? ""); + } + + return (Side.None, ""); + } + + static Entry? Transform(GeneratorAttributeSyntaxContext ctx) { + if (!(ctx.TargetSymbol is INamedTypeSymbol type) || type.TypeKind != TypeKind.Class) + return null; + + string[] names = ctx.Attributes + .Where(a => a.ConstructorArguments.Length == 1 && a.ConstructorArguments[0].Value is string) + .Select(a => (string)a.ConstructorArguments[0].Value!) + .ToArray(); + if (names.Length == 0) + return null; + + List bases = new List(); + for (INamedTypeSymbol? t = type.BaseType; t != null; t = t.BaseType) + bases.Add(t.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)); + + return new Entry { + TypeName = type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), + Name = type.Name, + LocalNames = names, + Bases = bases.ToArray(), + IsGeneric = IsGeneric(type), + IsAbstract = type.IsAbstract, + IsAccessible = IsAccessible(type), + Ctor = ParameterlessCtor(type), + Location = ctx.TargetNode.GetLocation(), + }; + } + + static bool IsGeneric(INamedTypeSymbol type) { + for (INamedTypeSymbol? t = type; t != null; t = t.ContainingType) + if (t.IsGenericType) + return true; + return false; + } + + static bool IsAccessible(INamedTypeSymbol type) { + for (INamedTypeSymbol? t = type; t != null; t = t.ContainingType) { + Accessibility a = t.DeclaredAccessibility; + if (a != Accessibility.Public && a != Accessibility.Internal && a != Accessibility.ProtectedOrInternal) + return false; + } + return true; + } + + static Ctor ParameterlessCtor(INamedTypeSymbol type) { + IMethodSymbol? ctor = type.InstanceConstructors.FirstOrDefault(c => c.Parameters.Length == 0); + if (ctor == null) + return Ctor.Missing; + switch (ctor.DeclaredAccessibility) { + case Accessibility.Public: return Ctor.Public; + case Accessibility.Internal: + case Accessibility.ProtectedOrInternal: return Ctor.Internal; + default: return Ctor.Hidden; + } + } + + static string? Problem(Entry e, Side side, string baseEntity) { + if (e.IsGeneric) return "is generic"; + if (e.IsAbstract) return "is abstract"; + if (!e.IsAccessible) return "is not accessible from generated code"; + if (baseEntity.Length != 0 && e.TypeName != baseEntity && !e.Bases.Contains(baseEntity)) return "does not derive from " + baseEntity; + if (side == Side.Server && e.Ctor != Ctor.Public) return "has no public parameterless constructor"; + if (e.Ctor == Ctor.Missing) return "has no parameterless constructor"; + return null; + } + + static void Execute(SourceProductionContext spc, ImmutableArray entries, Side side, string baseEntity) { + if (side == Side.None) + return; + + StringBuilder accessors = new StringBuilder(); + StringBuilder body = new StringBuilder(); + int accessorId = 0; + + foreach (Entry e in entries) { + string? problem = Problem(e, side, baseEntity); + if (problem != null) { + spc.ReportDiagnostic(Diagnostic.Create(Skipped, e.Location, e.TypeName, e.LocalNames[0], problem)); + continue; + } + + if (side == Side.Server) { + foreach (string name in e.LocalNames) + body.AppendLine($"\t\tnew {G}Game.CEntityFactory<{e.TypeName}>({Literal(name)});"); + continue; + } + + string factory; + if (e.Ctor == Ctor.Hidden) { + string accessor = "__Create" + accessorId++; + accessors.AppendLine("\t[global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Constructor)]"); + accessors.AppendLine($"\tstatic extern {e.TypeName} {accessor}();"); + accessors.AppendLine(); + factory = $"static () => {accessor}()"; + } + else + factory = $"static () => new {e.TypeName}()"; + + foreach (string name in e.LocalNames) + body.AppendLine($"\t\t{G}Game.Client.ClassMap.GetClassMap().Add(typeof({e.TypeName}), {Literal(name)}, {Literal(e.Name)}, {factory});"); + } + + StringBuilder sb = new StringBuilder(); + sb.AppendLine("// "); + sb.AppendLine("#nullable enable"); + sb.AppendLine("#pragma warning disable CA2255"); + sb.AppendLine(); + sb.AppendLine("namespace Source.Generated;"); + sb.AppendLine(); + sb.AppendLine("internal static class EntityFactoryRegistration"); + sb.AppendLine("{"); + sb.Append(accessors); + sb.AppendLine("\t[global::System.Runtime.CompilerServices.ModuleInitializer]"); + sb.AppendLine("\tinternal static void Register() {"); + sb.Append(body); + sb.AppendLine("\t}"); + sb.AppendLine("}"); + + spc.AddSource("EntityFactoryRegistration.g.cs", SourceText.From(sb.ToString(), Encoding.UTF8)); + } + + static string Literal(string value) => SymbolDisplay.FormatLiteral(value, true); + } +} diff --git a/Source.CodeAnalysis.EntityFactories/Source.CodeAnalysis.EntityFactories.csproj b/Source.CodeAnalysis.EntityFactories/Source.CodeAnalysis.EntityFactories.csproj new file mode 100644 index 000000000..5fe2175b2 --- /dev/null +++ b/Source.CodeAnalysis.EntityFactories/Source.CodeAnalysis.EntityFactories.csproj @@ -0,0 +1,19 @@ + + + + netstandard2.0 + false + true + true + latest + enable + false + Debug;Release;Debug (Dedicated);Release (Dedicated) + + + + + + + + diff --git a/Source.NET.slnx b/Source.NET.slnx index ddea36474..a3f97c6c4 100644 --- a/Source.NET.slnx +++ b/Source.NET.slnx @@ -31,6 +31,9 @@ + + +