forked from genaray/Arch.Extended
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuery.cs
More file actions
368 lines (316 loc) · 17.2 KB
/
Query.cs
File metadata and controls
368 lines (316 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
using System.Collections.Immutable;
using System.Text;
using Microsoft.CodeAnalysis;
namespace Arch.System.SourceGenerator;
public static class QueryUtils
{
/// <summary>
/// Appends the first elements of the types specified in the <see cref="parameterSymbols"/> from the previous specified arrays.
/// </summary>
/// <param name="sb">The <see cref="StringBuilder"/> instance.</param>
/// <param name="parameterSymbols">The <see cref="IEnumerable{T}"/> list of <see cref="IParameterSymbol"/>s which we wanna append the first elements for.</param>
/// <returns></returns>
public static StringBuilder GetFirstElements(this StringBuilder sb, IEnumerable<IParameterSymbol> parameterSymbols)
{
foreach (var symbol in parameterSymbols)
if(symbol.Type.Name is not "Entity" || !symbol.GetAttributes().Any(data => data.AttributeClass.Name.Contains("Data"))) // Prevent entity being added to the type array
sb.AppendLine($"ref var {symbol.Type.Name.ToLower()}FirstElement = ref chunk.GetFirst<{symbol.Type}>();");
return sb;
}
/// <summary>
/// Appends the components of the types specified in the <see cref="parameterSymbols"/> from the previous specified first elements.
/// </summary>
/// <param name="sb">The <see cref="StringBuilder"/> instance.</param>
/// <param name="parameterSymbols">The <see cref="IEnumerable{T}"/> list of <see cref="IParameterSymbol"/>s which we wanna append the components for.</param>
/// <returns></returns>
public static StringBuilder GetComponents(this StringBuilder sb, IEnumerable<IParameterSymbol> parameterSymbols)
{
foreach (var symbol in parameterSymbols)
if(symbol.Type.Name is not "Entity") // Prevent entity being added to the type array
sb.AppendLine($"ref var {symbol.Name.ToLower()} = ref Unsafe.Add(ref {symbol.Type.Name.ToLower()}FirstElement, entityIndex);");
return sb;
}
/// <summary>
/// Inserts the types defined in the <see cref="parameterSymbols"/> as parameters in a method.
/// <example>ref position, out velocity,...</example>
/// </summary>
/// <param name="sb">The <see cref="StringBuilder"/> instance.</param>
/// <param name="parameterSymbols">The <see cref="IEnumerable{T}"/> of <see cref="IParameterSymbol"/>s which we wanna insert.</param>
/// <returns></returns>
public static StringBuilder InsertParams(this StringBuilder sb, IEnumerable<IParameterSymbol> parameterSymbols)
{
foreach (var symbol in parameterSymbols)
sb.Append($"{CommonUtils.RefKindToString(symbol.RefKind)} {symbol.Name.ToLower()},");
if(sb.Length > 0) sb.Length--;
return sb;
}
/// <summary>
/// Creates a ComponentType array from the <see cref="parameterSymbols"/> passed through.
/// </summary>
/// <param name="sb">The <see cref="StringBuilder"/>.</param>
/// <param name="parameterSymbols">The <see cref="IList{T}"/> with <see cref="ITypeSymbol"/>s which we wanna create a ComponentType array for.</param>
/// <returns></returns>
public static StringBuilder GetTypeArray(this StringBuilder sb, IList<ITypeSymbol> parameterSymbols)
{
if (parameterSymbols.Count == 0)
{
sb.Append("Array.Empty<ComponentType>()");
return sb;
}
sb.Append("new ComponentType[]{");
foreach (var symbol in parameterSymbols)
if(symbol.Name is not "Entity") // Prevent entity being added to the type array
sb.Append($"typeof({symbol}),");
if (sb.Length > 0) sb.Length -= 1;
sb.Append('}');
return sb;
}
/// <summary>
/// Appends a set of <see cref="parameterSymbols"/> if they are marked by the data attribute.
/// <example>ref gameTime, out somePassedList,...</example>
/// </summary>
/// <param name="sb">The <see cref="StringBuilder"/> instance.</param>
/// <param name="parameterSymbols">The <see cref="IEnumerable{T}"/> of <see cref="IParameterSymbol"/>s which will be appended if they are marked with data.</param>
/// <returns></returns>
public static StringBuilder DataParameters(this StringBuilder sb, IEnumerable<IParameterSymbol> parameterSymbols)
{
sb.Append(',');
foreach (var parameter in parameterSymbols)
{
if (parameter.GetAttributes().Any(attributeData => attributeData.AttributeClass.Name.Contains("Data")))
sb.Append($"{CommonUtils.RefKindToString(parameter.RefKind)} {parameter.Type} {parameter.Name.ToLower()},");
}
sb.Length--;
return sb;
}
/// <summary>
/// Appends method calls made with their important data parameters.
/// <example>someQuery(World, gameTime); ...</example>
/// </summary>
/// <param name="sb">The <see cref="StringBuilder"/> instance.</param>
/// <param name="methodNames">The <see cref="IEnumerable{T}"/> of methods which we wanna call.</param>
/// <returns></returns>
public static StringBuilder CallMethods(this StringBuilder sb, IEnumerable<IMethodSymbol> methodNames)
{
foreach (var method in methodNames)
{
var data = new StringBuilder();
data.Append(',');
foreach (var parameter in method.Parameters)
{
if (!parameter.GetAttributes().Any(attributeData => attributeData.AttributeClass.Name.Contains("Data"))) continue;
data.Append($"{CommonUtils.RefKindToString(parameter.RefKind)} Data,");
break;
}
data.Length--;
sb.AppendLine($"{method.Name}Query(World {data});");
}
return sb;
}
/// <summary>
/// Gets all the types of a <see cref="AttributeData"/> as <see cref="ITypeSymbol"/>s and adds them to a list.
/// If the attribute is generic it will add the generic parameters, if its non generic it will add the non generic types from the constructor.
/// </summary>
/// <param name="data">The <see cref="AttributeData"/>.</param>
/// <param name="array">The <see cref="List{T}"/> where the found <see cref="ITypeSymbol"/>s are added to.</param>
public static void GetAttributeTypes(AttributeData data, List<ITypeSymbol> array)
{
if (data is not null && data.AttributeClass.IsGenericType)
{
array.AddRange(data.AttributeClass.TypeArguments);
}
else if (data is not null && !data.AttributeClass.IsGenericType)
{
var constructorArguments = data.ConstructorArguments[0].Values;
var constructorArgumentsTypes = constructorArguments.Select(constant => constant.Value as ITypeSymbol).ToList();
array.AddRange(constructorArgumentsTypes);
}
}
/// <summary>
/// Adds a query with an entity for a given annotated method. The attributes of these methods are used to generate the query.
/// </summary>
/// <param name="sb">The <see cref="StringBuilder"/> instance.</param>
/// <param name="methodSymbol">The <see cref="IMethodSymbol"/> which is annotated for source generation.</param>
/// <returns></returns>
public static StringBuilder AppendQueryMethod(this StringBuilder sb, IMethodSymbol methodSymbol)
{
// Check for entity param
var entity = methodSymbol.Parameters.Any(symbol => symbol.Type.Name.Equals("Entity"));
var entityParam = entity ? methodSymbol.Parameters.First(symbol => symbol.Type.Name.Equals("Entity")) : null;
// Get attributes
var attributeData = methodSymbol.GetAttributeData("All");
var anyAttributeData = methodSymbol.GetAttributeData("Any");
var noneAttributeData = methodSymbol.GetAttributeData("None");
var exclusiveAttributeData = methodSymbol.GetAttributeData("Exclusive");
// Get params / components except those marked with data or entities.
var components = methodSymbol.Parameters.ToList();
components.RemoveAll(symbol => symbol.Type.Name.Equals("Entity")); // Remove entitys
components.RemoveAll(symbol => symbol.GetAttributes().Any(data => data.AttributeClass.Name.Contains("Data"))); // Remove data annotated params
// Create all query array
var allArray = components.Select(symbol => symbol.Type).ToList();
var anyArray = new List<ITypeSymbol>();
var noneArray = new List<ITypeSymbol>();
var exclusiveArray = new List<ITypeSymbol>();
// Get All<...> or All(...) passed types and pass them to the arrays
GetAttributeTypes(attributeData, allArray);
GetAttributeTypes(anyAttributeData, anyArray);
GetAttributeTypes(noneAttributeData, noneArray);
GetAttributeTypes(exclusiveAttributeData, exclusiveArray);
// Remove doubles and entities
allArray = allArray.Distinct().ToList();
anyArray = anyArray.Distinct().ToList();
noneArray = noneArray.Distinct().ToList();
exclusiveArray = exclusiveArray.Distinct().ToList();
allArray.RemoveAll(symbol => symbol.Name.Equals("Entity"));
anyArray.RemoveAll(symbol => symbol.Name.Equals("Entity"));
noneArray.RemoveAll(symbol => symbol.Name.Equals("Entity"));
exclusiveArray.RemoveAll(symbol => symbol.Name.Equals("Entity"));
// Create data modell and generate it
var className = methodSymbol.ContainingSymbol.ToString();
var queryMethod = new QueryMethod
{
IsGlobalNamespace = methodSymbol.ContainingNamespace.IsGlobalNamespace,
Namespace = methodSymbol.ContainingNamespace.ToString(),
ClassName = className.Substring(className.LastIndexOf('.')+1),
IsStatic = methodSymbol.IsStatic,
IsEntityQuery = entity,
MethodName = methodSymbol.Name,
EntityParameter = entityParam,
Parameters = methodSymbol.Parameters,
Components = components,
AllFilteredTypes = allArray,
AnyFilteredTypes = anyArray,
NoneFilteredTypes = noneArray,
ExclusiveFilteredTypes = exclusiveArray
};
return sb.AppendQueryMethod(ref queryMethod);
}
/// <summary>
/// Adds a query with an entity for a given annotated method. The attributes of these methods are used to generate the query.
/// </summary>
/// <param name="sb">The <see cref="StringBuilder"/> instance.</param>
/// <param name="queryMethod">The <see cref="QueryMethod"/> which is generated.</param>
/// <returns></returns>
public static StringBuilder AppendQueryMethod(this StringBuilder sb, ref QueryMethod queryMethod)
{
var staticModifier = queryMethod.IsStatic ? "static" : "";
// Generate code
var data = new StringBuilder().DataParameters(queryMethod.Parameters);
var getFirstElements = new StringBuilder().GetFirstElements(queryMethod.Components);
var getComponents = new StringBuilder().GetComponents(queryMethod.Components);
var insertParams = new StringBuilder().InsertParams(queryMethod.Parameters);
var allTypeArray = new StringBuilder().GetTypeArray(queryMethod.AllFilteredTypes);
var anyTypeArray = new StringBuilder().GetTypeArray(queryMethod.AnyFilteredTypes);
var noneTypeArray = new StringBuilder().GetTypeArray(queryMethod.NoneFilteredTypes);
var exclusiveTypeArray = new StringBuilder().GetTypeArray(queryMethod.ExclusiveFilteredTypes);
var template =
$$"""
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Arch.Core;
using Arch.Core.Extensions;
using Arch.Core.Utils;
using ArrayExtensions = CommunityToolkit.HighPerformance.ArrayExtensions;
using Component = Arch.Core.Utils.Component;
{{(!queryMethod.IsGlobalNamespace ? $"namespace {queryMethod.Namespace} {{" : "")}}
public {{staticModifier}} partial class {{queryMethod.ClassName}}{
private {{staticModifier}} QueryDescription {{queryMethod.MethodName}}_QueryDescription = new QueryDescription{
All = {{allTypeArray}},
Any = {{anyTypeArray}},
None = {{noneTypeArray}},
Exclusive = {{exclusiveTypeArray}}
};
private {{staticModifier}} bool _{{queryMethod.MethodName}}_Initialized;
private {{staticModifier}} Query _{{queryMethod.MethodName}}_Query;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public {{staticModifier}} void {{queryMethod.MethodName}}Query(World world {{data}}){
if(!_{{queryMethod.MethodName}}_Initialized){
_{{queryMethod.MethodName}}_Query = world.Query(in {{queryMethod.MethodName}}_QueryDescription);
_{{queryMethod.MethodName}}_Initialized = true;
}
foreach(ref var chunk in _{{queryMethod.MethodName}}_Query.GetChunkIterator()){
var chunkSize = chunk.Size;
{{(queryMethod.IsEntityQuery ? "ref var entityFirstElement = ref chunk.Entity(0);" : "")}}
{{getFirstElements}}
foreach(var entityIndex in chunk)
{
{{(queryMethod.IsEntityQuery ? $"ref readonly var {queryMethod.EntityParameter.Name.ToLower()} = ref Unsafe.Add(ref entityFirstElement, entityIndex);" : "")}}
{{getComponents}}
{{queryMethod.MethodName}}({{insertParams}});
}
}
}
}
{{(!queryMethod.IsGlobalNamespace ? "}" : "")}}
""";
sb.Append(template);
return sb;
}
/// <summary>
/// Adds a basesystem that calls a bunch of query methods.
/// </summary>
/// <param name="sb">The <see cref="StringBuilder"/> instance.</param>
/// <param name="classToMethod">The <see cref="KeyValuePair{TKey,TValue}"/> which maps all query methods to a common class containing them.</param>
/// <returns></returns>
public static StringBuilder AppendBaseSystem(this StringBuilder sb, KeyValuePair<ISymbol, List<IMethodSymbol>> classToMethod)
{
// Get BaseSystem class
var classSymbol = classToMethod.Key as INamedTypeSymbol;
INamedTypeSymbol? parentSymbol = null;
var implementsUpdate = false;
var type = classSymbol;
while (type != null)
{
// Update was implemented by user, no need to do that by source generator.
if (type.MemberNames.Contains("Update"))
implementsUpdate = true;
type = type.BaseType;
// Ignore classes which do not derive from BaseSystem
if (type?.Name == "BaseSystem")
{
parentSymbol = type;
break;
}
}
if (parentSymbol == null || implementsUpdate)
return sb;
// Get generic of BaseSystem
var typeSymbol = parentSymbol.TypeArguments[1];
// Generate basesystem.
var baseSystem = new BaseSystem
{
Namespace = classSymbol.ContainingNamespace != null ? classSymbol.ContainingNamespace.ToString() : string.Empty,
GenericType = typeSymbol,
GenericTypeNamespace = typeSymbol.ContainingNamespace.ToString(),
Name = classSymbol.Name,
QueryMethods = classToMethod.Value,
};
return sb.AppendBaseSystem(ref baseSystem);
}
/// <summary>
/// Adds a basesystem that calls a bunch of query methods.
/// </summary>
/// <param name="sb">The <see cref="StringBuilder"/> instance.</param>
/// <param name="baseSystem">The <see cref="BaseSystem"/> which is generated.</param>
/// <returns></returns>
public static StringBuilder AppendBaseSystem(this StringBuilder sb, ref BaseSystem baseSystem)
{
var methodCalls = new StringBuilder().CallMethods(baseSystem.QueryMethods);
var template =
$$"""
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using {{baseSystem.GenericTypeNamespace}};
{{(baseSystem.Namespace != string.Empty ? $"namespace {baseSystem.Namespace} {{" : "")}}
public partial class {{baseSystem.Name}}{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void Update(in {{baseSystem.GenericType.ToDisplayString()}} {{baseSystem.GenericType.Name.ToLower()}}){
{{methodCalls}}
}
}
{{(baseSystem.Namespace != string.Empty ? "}" : "")}}
""";
return sb.Append(template);
}
}