forked from MonoGame/MonoGame
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContentBuilder.cs
More file actions
440 lines (384 loc) · 17.1 KB
/
Copy pathContentBuilder.cs
File metadata and controls
440 lines (384 loc) · 17.1 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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
// MonoGame - Copyright (C) MonoGame Foundation, Inc
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
using System.Collections;
using System.Reflection;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Compiler;
using MonoGame.Framework.Content.Pipeline.Builder.Logger;
using MonoGame.Framework.Content.Pipeline.Builder.Server;
namespace MonoGame.Framework.Content.Pipeline.Builder;
/// <summary>
/// This class is the entry point for the content builder system.
/// </summary>
public abstract class ContentBuilder
{
private class ContentRequest
{
public required string InputPath { get; init; }
public required ContentInfo ContentInfo { get; init; }
public required ContentServer Server { get; set; }
public required ContentRequestedArgs Args { get; set; }
}
private class SkipLogException() : Exception;
private readonly Queue<ContentRequest> _contentRequestQueue = [];
private readonly object _contentRequestLock = new();
private readonly Dictionary<string, List<ContentInfo>> _content = [];
private readonly Dictionary<string, string> _outputContent = [];
/// <summary>
/// Parameters to be used by the <see cref="ContentBuilder"/> or any of its subsystems.
///
/// Can be passed from CLI args, see <see cref="Run(string[])"/>.
/// </summary>
public ContentBuilderParams Parameters { get; set; } = new ContentBuilderParams();
/// <summary>
/// Gets or sets the logger to be used by the <see cref="ContentBuilder"/>.
/// </summary>
/// <value><see cref="ContentBuildLogger"/> by default.</value>
public ContentBuildLogger Logger { get; set; } = new ContentBuilderLogger();
/// <summary>
/// Gets or sets the content cahcing system to be used by the <see cref="ContentBuilder"/>.
/// </summary>
public virtual IContentCache ContentCache { get; init; } = new ContentCache();
/// <summary>
/// Called to build system to gather information about how to handle the content. It gets called only once during initialization.
/// </summary>
/// <returns>An <see cref="IContentCollection"/> that contains information about the content handling.</returns>
public abstract IContentCollection GetContentCollection();
/// <summary>
/// Returns the number of content items that failed to build.
/// </summary>
public uint FailedToBuild { get; private set; }
/// <summary>
/// Returns the number of content items that built successfully.
/// </summary>
public uint SucceededToBuild { get; private set; }
/// <summary>
/// Initiates a build of the specified asset and then writes down the result to disk..
/// </summary>
/// <param name="relativeSrcPath">A relative path to the source asset.</param>
/// <param name="contentInfo">The desired <see cref="ContentInfo"/> to be used for the content building.</param>
/// <param name="relativeDstPath">The desired relative output path.</param>
/// <param name="parentContext">Only set when the method is being called by the ContentProcessorContext to build one of its children.</param>
public void BuildAndWriteContent(string relativeSrcPath, ContentInfo contentInfo, string? relativeDstPath = null, ContentProcessorContext? parentContext = null)
{
Logger.PushFile(Path.Combine(Parameters.RootedSourceDirectory, relativeSrcPath));
try
{
ProcessContent(relativeSrcPath, contentInfo, true, relativeDstPath, parentContext);
SucceededToBuild++;
}
catch (Exception ex)
{
FailedToBuild++;
if (ex is not SkipLogException)
{
Logger.Log(LogLevel.Error, $"Content failed to build: {ex}");
}
if (parentContext != null)
{
throw new SkipLogException();
}
}
finally
{
Logger.PopFile();
}
}
/// <summary>
/// Initiates a build of the specified asset and then loads the result into memory.
/// </summary>
/// <param name="relativeSrcPath">A relative path to the source asset.</param>
/// <param name="contentInfo">The desired <see cref="ContentInfo"/> to be used for the content building.</param>
/// <param name="relativeDstPath">The desired relative output path.</param>
/// <param name="parentContext">Only set when the method is being called by the ContentProcessorContext to build one of its children.</param>
/// <returns>The built object that the <see cref="IContentProcessor.Process(object, ContentProcessorContext)"/> returned.</returns>
public object? BuildAndLoadContent(string relativeSrcPath, ContentInfo contentInfo, string? relativeDstPath = null, ContentProcessorContext? parentContext = null)
{
Logger.PushFile(Path.Combine(Parameters.RootedSourceDirectory, relativeSrcPath));
try
{
var content = ProcessContent(relativeSrcPath, contentInfo, false, relativeDstPath, parentContext);
SucceededToBuild++;
return content;
}
catch (Exception ex)
{
FailedToBuild++;
if (ex is not SkipLogException)
{
Logger.Log(LogLevel.Error, $"Content failed to build: {ex}");
}
if (parentContext != null)
{
throw new SkipLogException();
}
}
finally
{
Logger.PopFile();
}
return null;
}
private object? ProcessContent(string relativePath, ContentInfo contentInfo, bool writeToDisk, string? relativeOutputPath, ContentProcessorContext? parentContext)
{
var filePath = Path.Combine(Parameters.RootedSourceDirectory, relativePath);
var relativeDestPath = Path.Combine(contentInfo.ContentRoot, string.IsNullOrEmpty(relativeOutputPath) ? relativePath.GetDestinationPath(contentInfo.ShouldBuild, contentInfo.GetOutputPath) : relativeOutputPath).Sanitize();
var outputPath = Path.Combine(Parameters.RootedOutputDirectory, relativeDestPath).Sanitize();
var outputDir = Path.GetDirectoryName(outputPath);
if (string.IsNullOrWhiteSpace(outputDir))
{
return null;
}
if (!Directory.Exists(outputDir))
{
Directory.CreateDirectory(outputDir);
}
if (contentInfo.ShouldBuild) // ensure importer and processor are set
{
if (!ContentBuilderHelper.GetImporter(relativePath, contentInfo.Importer, out IContentImporter importer))
{
Logger.Log(LogLevel.Warning, "Importer: Not found");
return null;
}
if (!ContentBuilderHelper.GetProcessor(importer, contentInfo.Processor, out IContentProcessor processor))
{
Logger.Log(LogLevel.Warning, "Processor: Not found");
return null;
}
if (contentInfo.Importer != importer || contentInfo.Processor != processor)
{
contentInfo = new ContentInfo(contentInfo.ContentRoot, contentInfo.ShouldBuild, importer, processor, contentInfo.GetOutputPath);
}
}
if (!Parameters.Rebuild)
{
var fileCache = ContentCache.ReadContentFileCache(this, relativeDestPath);
if (fileCache != null && fileCache.IsValid(this, contentInfo))
{
Logger.Log(LogLevel.Debug, $"Cache: Found");
ContentCache.MarkUsed(fileCache);
(parentContext as ContentBuilderProcessorContext)?.ContentFileCache.AddDependency(this, fileCache);
return null;
}
}
if (!contentInfo.ShouldBuild)
{
Logger.Log(Path.GetRelativePath(Logger.LoggerRootDirectory, outputPath).Sanitize());
if (File.Exists(outputPath))
{
File.Delete(outputPath);
}
File.Copy(filePath, outputPath);
var fileCache = ContentCache.CreateContentFileCache(this, contentInfo);
fileCache.AddDependency(this, relativePath);
fileCache.AddOutputFile(this, outputPath);
ContentCache.WriteContentFileCache(this, relativeDestPath, fileCache);
ContentCache.MarkUsed(fileCache);
(parentContext as ContentBuilderProcessorContext)?.ContentFileCache.AddDependency(this, fileCache);
return null;
}
Logger.Log(LogLevel.Debug, $"Cache: Not Found");
Logger.Log(LogLevel.Debug, $"Importer: {contentInfo.Importer!.GetType().Name}");
Logger.Log(LogLevel.Debug, $"Processor: {contentInfo.Processor!.GetType().Name}");
Logger.Log(Path.GetRelativePath(Logger.LoggerRootDirectory, outputPath).Sanitize());
var contentFileCache = ContentCache.CreateContentFileCache(this, contentInfo);
contentFileCache.AddDependency(this, relativePath);
var importContext = new ContentBuilderImporterContext(this, contentFileCache);
var importedObject = contentInfo.Importer!.Import(filePath, importContext);
var processorContext = new ContentBuilderProcessorContext(this, relativePath, contentInfo, contentFileCache, outputPath);
using var _ = ContextScopeFactory.BeginContext(processorContext);
var processedObject = contentInfo.Processor!.Process(importedObject, processorContext);
if (writeToDisk)
{
var compiler = new ContentCompiler();
using var stream = new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.None);
compiler.Compile(stream, processedObject, Parameters.Platform, Parameters.GraphicsProfile, Parameters.CompressContent, Parameters.RootedOutputDirectory, outputDir);
contentFileCache.AddOutputFile(this, outputPath);
ContentCache.WriteContentFileCache(this, relativeDestPath, contentFileCache);
ContentCache.MarkUsed(contentFileCache);
(parentContext as ContentBuilderProcessorContext)?.ContentFileCache.AddDependency(this, contentFileCache);
}
return processedObject;
}
/// <summary>
/// Runs the <see cref="ContentBuilder"/> with the specified parameters.
/// </summary>
/// <param name="parameters">A <see cref="ContentBuilderParams"/> describing both the platform paramteres for the content compilation as well as the configuration of the <see cref="ContentBuilder"/> itself.</param>
public bool Run(ContentBuilderParams parameters)
{
ContentBuilderHelper.LoadAssemblies();
Parameters = parameters;
Logger.LoggerLogLevel = Parameters.LogLevel;
Logger.LoggerRootDirectory = Parameters.WorkingDirectory;
if (parameters.Mode == ContentBuilderMode.None)
{
// This means we are just showing the help menu.
return false;
}
Directory.SetCurrentDirectory(Parameters.WorkingDirectory);
Logger.Log("Starting Content Builder");
Logger.Indent();
foreach (var prop in Parameters.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (prop.GetValue(Parameters) is IList list)
{
Logger.Log(LogLevel.Debug, $"{prop.Name}:");
foreach (var item in list)
{
Logger.Log(LogLevel.Debug, $"- {item}");
}
}
else
{
Logger.Log(LogLevel.Debug, $"{prop.Name}: {prop.GetValue(Parameters)}");
}
}
Logger.Unindent();
ContentCache.LoadCache(this);
var contentCollection = GetContentCollection();
ScanFiles(contentCollection, Parameters.RootedSourceDirectory);
switch (Parameters.Mode)
{
case ContentBuilderMode.Builder:
return RunBuild();
case ContentBuilderMode.Server:
RunServer();
break;
}
return true;
}
/// <summary>
/// A helper method to run the <see cref="ContentBuilder"/> with the passed <see cref="ContentBuilderParams"/> from the entry point args.
/// </summary>
/// <param name="args">An array of string to be deserialized into <see cref="ContentBuilderParams"/>.</param>
public void Run(string[] args) => Run(ContentBuilderParams.Parse(args));
private void ScanFiles(IContentCollection contentCollection, string directory)
{
foreach (var dir in Directory.GetDirectories(directory))
{
if (Path.GetFileName(dir).StartsWith('.'))
continue;
ScanFiles(contentCollection, dir);
}
foreach (var filePath in Directory.GetFiles(directory))
{
if (Path.GetFileName(filePath).StartsWith('.'))
continue;
var relativePath = Path.GetRelativePath(Parameters.RootedSourceDirectory, filePath);
relativePath = relativePath.Sanitize();
if (contentCollection.GetContentInfo(relativePath, out List<ContentInfo> contentInfos) && contentInfos.Count > 0)
{
_content[relativePath] = contentInfos;
foreach (var contentInfo in contentInfos)
{
_outputContent[Path.Combine(contentInfo.ContentRoot, contentInfo.GetOutputPath(relativePath))] = relativePath;
}
}
}
}
private bool RunBuild()
{
foreach (var pair in _content)
{
foreach(var contentInfo in pair.Value)
{
BuildAndWriteContent(pair.Key, contentInfo);
}
}
if (!Parameters.SkipClean && FailedToBuild == 0)
{
ContentCache.CleanCache(this);
}
ContentCache.FlushCache(this);
Logger.Log("Content Builder Finished");
Logger.Indent();
Logger.Log($"{SucceededToBuild} succeeded, {FailedToBuild} failed");
Logger.Unindent();
return FailedToBuild == 0;
}
private void RunServer()
{
Console.CancelKeyPress += delegate
{
foreach (var server in Parameters.Servers)
{
server.StopListening();
}
// We don't want to call CleanCache in server mode as we don't go through all the files!
ContentCache.FlushCache(this);
};
foreach (var server in Parameters.Servers)
{
server.Logger = Logger;
server.ContentRequested += ServerContentRequested;
server.StartListening();
}
while (true)
{
ContentRequest? request = null;
lock (_contentRequestQueue)
{
if (_contentRequestQueue.Count > 0)
{
request = _contentRequestQueue.Dequeue();
}
}
if (request != null)
{
BuildAndWriteContent(request.InputPath, request.ContentInfo);
request.Args.FilePath = Path.Combine(Parameters.RootedOutputDirectory, Path.Combine(request.ContentInfo.ContentRoot, request.ContentInfo.GetOutputPath(request.InputPath)));
request.Server.NotifyContentRequestCompiled();
}
else
{
lock (_contentRequestLock)
{
Monitor.Wait(_contentRequestLock);
}
}
}
}
private void ServerContentRequested(object? server, ContentRequestedArgs args)
{
if (server is not ContentServer contentServer)
{
return;
}
var outputPath = args.ContentPath.Sanitize();
if (_outputContent.TryGetValue(outputPath, out var inputPath))
{
if (_content.TryGetValue(inputPath, out List<ContentInfo>? contentInfos))
{
foreach (var contentInfo in contentInfos)
{
if (contentInfo.GetOutputPath(inputPath) != outputPath)
{
continue;
}
if (ContentCache.ReadContentFileCache(this, outputPath) is not null)
{
// we've already found a valid cached version of content, so no need for any compilation here
args.FilePath = Path.Combine(Parameters.RootedOutputDirectory, outputPath);
return;
}
args.CompilationStarted = true;
lock (_contentRequestQueue)
{
_contentRequestQueue.Enqueue(new ContentRequest
{
InputPath = inputPath,
ContentInfo = contentInfo,
Server = contentServer,
Args = args
});
lock (_contentRequestLock)
{
Monitor.Pulse(_contentRequestLock);
}
}
}
}
}
}
}