forked from nkast/MonoGame
-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
PipelineManager.cs
939 lines (793 loc) · 39.3 KB
/
PipelineManager.cs
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
// MonoGame - Copyright (C) The MonoGame Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Compiler;
using Microsoft.Xna.Framework.Graphics;
namespace Microsoft.Xna.Framework.Content.Pipeline.Builder
{
internal class PipelineManager
{
[DebuggerDisplay("ImporterInfo: {type.Name}")]
private struct ImporterInfo
{
public ContentImporterAttribute attribute;
public Type type;
public DateTime assemblyTimestamp;
};
private List<ImporterInfo> _importers;
[DebuggerDisplay("ProcessorInfo: {type.Name}")]
private struct ProcessorInfo
{
public ContentProcessorAttribute attribute;
public Type type;
public DateTime assemblyTimestamp;
};
private List<ProcessorInfo> _processors;
private List<Type> _writers;
// Keep track of all built assets. (Required to resolve automatic names "AssetName_n".)
// Key = absolute, normalized path of source file
// Value = list of build events
// (Note: When using external references, an asset may be built multiple times
// with different parameters.)
private readonly Dictionary<string, List<BuildEvent>> _buildEventsMap;
// Store default values for content processor parameters. (Necessary to compare processor
// parameters. See PipelineBuildEvent.AreParametersEqual.)
// Key = name of content processor
// Value = processor parameters
private readonly Dictionary<string, OpaqueDataDictionary> _processorDefaultValues;
private readonly SortedSet<string> _processingBuildEvents;
public string ProjectDirectory { get; private set; }
public string ResponseFilename { get; private set; }
public string OutputDirectory { get; private set; }
public string IntermediateDirectory { get; private set; }
public bool Quiet { get; private set; }
private ContentCompiler _compiler;
internal readonly ConsoleLogger Logger;
public List<string> Assemblies { get; private set; }
/// <summary>
/// The current target graphics profile for which all content is built.
/// </summary>
public GraphicsProfile Profile { get; set; }
/// <summary>
/// The current target platform for which all content is built.
/// </summary>
public TargetPlatform Platform { get; set; }
/// <summary>
/// The build configuration passed thru to content processors.
/// </summary>
public string Config { get; set; }
/// <summary>
/// Gets or sets the compression method.
/// </summary>
public ContentCompression Compression { get; set; }
internal const String DefaultFileCollectionFilename = "assetsdb.kniContent";
public PipelineManager(string projectDir, string responseFilename, string outputDir, string intermediateDir, bool quiet)
{
_buildEventsMap = new Dictionary<string, List<BuildEvent>>();
_processorDefaultValues = new Dictionary<string, OpaqueDataDictionary>();
_processingBuildEvents = new SortedSet<string>();
Assemblies = new List<string>();
Logger = new ConsoleLogger();
ProjectDirectory = PathHelper.NormalizeDirectory(projectDir);
ResponseFilename = responseFilename;
OutputDirectory = PathHelper.NormalizeDirectory(outputDir);
IntermediateDirectory = PathHelper.NormalizeDirectory(intermediateDir);
Quiet = quiet;
}
public void AddAssembly(string assemblyFilePath)
{
if (assemblyFilePath == null)
throw new ArgumentException("assemblyFilePath cannot be null!");
if (!Path.IsPathRooted(assemblyFilePath))
throw new ArgumentException("assemblyFilePath must be absolute!");
// Make sure we're not adding the same assembly twice.
assemblyFilePath = PathHelper.Normalize(assemblyFilePath);
if (!this.Assemblies.Contains(assemblyFilePath))
{
this.Assemblies.Add(assemblyFilePath);
//TODO need better way to update caches
_processors = null;
_importers = null;
_writers = null;
}
}
private void ResolveAssemblies()
{
_importers = new List<ImporterInfo>();
_processors = new List<ProcessorInfo>();
_writers = new List<Type>();
// import the build-in Processors
LoadAssembly(typeof(Microsoft.Xna.Framework.Content.Pipeline.IContentProcessor).Assembly); // Common
LoadAssembly(typeof(Microsoft.Xna.Framework.Content.Pipeline.Processors.SoundEffectProcessor).Assembly); // Audio
LoadAssembly(typeof(Microsoft.Xna.Framework.Content.Pipeline.Processors.VideoProcessor).Assembly); // Media
LoadAssembly(typeof(Microsoft.Xna.Framework.Content.Pipeline.Processors.TextureProcessor).Assembly); // Graphics
LoadAssembly(typeof(Microsoft.Xna.Framework.Content.Pipeline.Processors.EffectProcessor).Assembly); // Graphics Effects
// import the referenced Processors
foreach (string assemblyPath in Assemblies)
{
try
{
LoadAssembly(Assembly.LoadFrom(assemblyPath));
}
catch (BadImageFormatException e)
{
Logger.LogWarning(null, null, "Assembly is either corrupt or built using a different " +
"target platform than this process. Reference another target architecture (x86, x64, " +
"AnyCPU, etc.) of this assembly. '{0}': {1}", assemblyPath, e.Message);
// The assembly failed to load... nothing
// we can do but ignore it.
continue;
}
catch (Exception e)
{
Logger.LogWarning(null, null, "Failed to load assembly '{0}': {1}", assemblyPath, e.Message);
continue;
}
}
}
private void LoadAssembly(Assembly asm)
{
Type[] exportedTypes;
DateTime assemblyTimestamp;
try
{
exportedTypes = asm.GetTypes();
assemblyTimestamp = File.GetLastWriteTime(asm.Location);
}
catch (ReflectionTypeLoadException e)
{
string missingTypes = String.Empty;
foreach (var le in e.LoaderExceptions)
missingTypes += le.Message;
Logger.LogWarning(null, null, missingTypes +
" '{0}': {1}", asm.Location, e.Message);
// The assembly failed to load... nothing
// we can do but ignore it.
return;
}
catch (Exception e)
{
Logger.LogWarning(null, null, "Failed to load assembly '{0}': {1}", asm.Location, e.Message);
return;
}
foreach (Type type in exportedTypes)
{
if (type.IsAbstract)
continue;
if (type.GetInterface(@"IContentImporter") != null)
{
var attributes = type.GetCustomAttributes(typeof(ContentImporterAttribute), false);
if (attributes.Length != 0)
{
var importerAttribute = attributes[0] as ContentImporterAttribute;
_importers.Add(new ImporterInfo
{
attribute = importerAttribute,
type = type,
assemblyTimestamp = assemblyTimestamp
});
}
else
{
// If no attribute specify default one
var importerAttribute = new ContentImporterAttribute(".*");
importerAttribute.DefaultProcessor = "";
importerAttribute.DisplayName = type.Name;
var importerInfo = new ImporterInfo
{
attribute = importerAttribute,
type = type,
assemblyTimestamp = assemblyTimestamp
};
if (_importers.Contains(importerInfo))
{
Logger.LogWarning(null, null, "Duplicate Type '{0}': {1}", type.Name);
continue;
}
_importers.Add(importerInfo);
}
}
else if (type.GetInterface(@"IContentProcessor") != null)
{
var attributes = type.GetCustomAttributes(typeof(ContentProcessorAttribute), false);
if (attributes.Length != 0)
{
var processorAttribute = attributes[0] as ContentProcessorAttribute;
var processorInfo = new ProcessorInfo
{
attribute = processorAttribute,
type = type,
assemblyTimestamp = assemblyTimestamp
};
if (_processors.Contains(processorInfo))
{
Logger.LogWarning(null, null, "Duplicate Type '{0}': {1}", type.Name);
continue;
}
_processors.Add(processorInfo);
}
}
else if (type.GetInterface(@"ContentTypeWriter") != null)
{
// TODO: This doesn't work... how do i find these?
_writers.Add(type);
}
}
}
public Type[] GetImporterTypes()
{
if (_importers == null)
ResolveAssemblies();
List<Type> types = new List<Type>();
foreach (var item in _importers)
{
types.Add(item.type);
}
return types.ToArray();
}
public Type[] GetProcessorTypes()
{
if (_processors == null)
ResolveAssemblies();
List<Type> types = new List<Type>();
foreach (var item in _processors)
{
types.Add(item.type);
}
return types.ToArray();
}
public IContentImporter CreateImporter(string name)
{
if (_importers == null)
ResolveAssemblies();
// Search for the importer.
foreach (var info in _importers)
{
if (info.type.Name.Equals(name))
return Activator.CreateInstance(info.type) as IContentImporter;
}
return null;
}
public string FindImporterByExtension(string ext)
{
if (_importers == null)
ResolveAssemblies();
// Search for the importer.
foreach (var info in _importers)
{
if (info.attribute.FileExtensions.Any(e => e.Equals(ext, StringComparison.InvariantCultureIgnoreCase)))
return info.type.Name;
}
return null;
}
public DateTime GetImporterAssemblyTimestamp(string name)
{
if (_importers == null)
ResolveAssemblies();
// Search for the importer.
foreach (var info in _importers)
{
if (info.type.Name.Equals(name))
return info.assemblyTimestamp;
}
return DateTime.MaxValue;
}
public string FindDefaultProcessor(string importer)
{
if (_importers == null)
ResolveAssemblies();
// Search for the importer.
foreach (var info in _importers)
{
if (info.type.Name == importer)
return info.attribute.DefaultProcessor;
}
return null;
}
public Type GetProcessorType(string name)
{
if (_processors == null)
ResolveAssemblies();
// Search for the processor type.
foreach (var info in _processors)
{
if (info.type.Name.Equals(name))
return info.type;
}
return null;
}
public void ResolveImporterAndProcessor(string sourceFilepath, ref string importerName, ref string processorName)
{
// Resolve the importer name.
if (string.IsNullOrEmpty(importerName))
importerName = FindImporterByExtension(Path.GetExtension(sourceFilepath));
if (string.IsNullOrEmpty(importerName))
throw new Exception(string.Format("Couldn't find a default importer for '{0}'!", sourceFilepath));
// Resolve the processor name.
if (string.IsNullOrEmpty(processorName))
processorName = FindDefaultProcessor(importerName);
if (string.IsNullOrEmpty(processorName))
throw new Exception(string.Format("Couldn't find a default processor for importer '{0}'!", importerName));
}
public IContentProcessor CreateProcessor(string name, OpaqueDataDictionary processorParameters)
{
Type processorType = GetProcessorType(name);
if (processorType == null)
return null;
// Create the processor.
IContentProcessor processor = (IContentProcessor)Activator.CreateInstance(processorType);
// Convert and set the parameters on the processor.
foreach (var param in processorParameters)
{
PropertyInfo property = processorType.GetProperty(param.Key, BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance);
if (property == null || property.GetSetMethod(false) == null)
continue;
// If the property value is already of the correct type then set it.
if (property.PropertyType.IsInstanceOfType(param.Value))
property.SetValue(processor, param.Value, null);
else
{
// Find a type converter for this property.
TypeConverter typeConverter = TypeDescriptor.GetConverter(property.PropertyType);
if (typeConverter.CanConvertFrom(param.Value.GetType()))
{
object propValue = typeConverter.ConvertFrom(null, CultureInfo.InvariantCulture, param.Value);
property.SetValue(processor, propValue, null);
}
}
}
return processor;
}
/// <summary>
/// Gets the default values for the content processor parameters.
/// </summary>
/// <param name="processorName">The name of the content processor.</param>
/// <returns>
/// A dictionary containing the default value for each parameter. Returns
/// <see langword="null"/> if the content processor has not been created yet.
/// </returns>
public OpaqueDataDictionary GetProcessorDefaultValues(string processorName)
{
// null is not allowed as key in dictionary.
if (processorName == null)
processorName = string.Empty;
OpaqueDataDictionary defaultValues;
lock (_processorDefaultValues)
{
if (!_processorDefaultValues.TryGetValue(processorName, out defaultValues))
{
// Create the content processor instance and read the default values.
defaultValues = new OpaqueDataDictionary();
var processorType = GetProcessorType(processorName);
if (processorType != null)
{
try
{
var processor = (IContentProcessor)Activator.CreateInstance(processorType);
var properties = processorType.GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
defaultValues.Add(property.Name, property.GetValue(processor, null));
}
catch
{
// Ignore exception. Will be handled in ProcessContent.
}
}
_processorDefaultValues.Add(processorName, defaultValues);
}
}
return defaultValues;
}
public DateTime GetProcessorAssemblyTimestamp(string name)
{
if (_processors == null)
ResolveAssemblies();
// Search for the processor.
foreach (var info in _processors)
{
if (info.type.Name.Equals(name))
return info.assemblyTimestamp;
}
return DateTime.MaxValue;
}
public OpaqueDataDictionary ValidateProcessorParameters(string processorName, OpaqueDataDictionary processorParameters)
{
OpaqueDataDictionary result = new OpaqueDataDictionary();
Type processorType = GetProcessorType(processorName);
if (processorType == null || processorParameters == null)
{
return result;
}
foreach (var param in processorParameters)
{
PropertyInfo property = processorType.GetProperty(param.Key, BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance);
if (property == null || property.GetSetMethod(false) == null)
continue;
// Make sure we can assign the value.
if (!property.PropertyType.IsInstanceOfType(param.Value))
{
// Make sure we can convert the value.
TypeConverter typeConverter = TypeDescriptor.GetConverter(property.PropertyType);
if (!typeConverter.CanConvertFrom(param.Value.GetType()))
continue;
}
result.Add(param.Key, param.Value);
}
return result;
}
private void ResolveOutputFilepath(string sourceFilepath, ref string outputFilepath)
{
// If the output path is null... build it from the source file path.
if (string.IsNullOrEmpty(outputFilepath))
{
string filename = Path.GetFileNameWithoutExtension(sourceFilepath) + ".xnb";
string directory = PathHelper.GetRelativePath(ProjectDirectory,
Path.GetDirectoryName(sourceFilepath) +
Path.DirectorySeparatorChar);
outputFilepath = Path.Combine(OutputDirectory, directory, filename);
}
else
{
// If the extension is not XNB or the source file extension then add XNB.
string sourceExt = Path.GetExtension(sourceFilepath);
if (outputFilepath.EndsWith(sourceExt, StringComparison.InvariantCultureIgnoreCase))
outputFilepath = outputFilepath.Substring(0, outputFilepath.Length - sourceExt.Length);
if (!outputFilepath.EndsWith(".xnb", StringComparison.InvariantCultureIgnoreCase))
outputFilepath += ".xnb";
// If the path isn't rooted then put it into the output directory.
if (!Path.IsPathRooted(outputFilepath))
outputFilepath = Path.Combine(OutputDirectory, outputFilepath);
}
outputFilepath = PathHelper.Normalize(outputFilepath);
}
private void DeleteBuildEvent(string destFile)
{
string dbname = ResponseFilename;
if (dbname == String.Empty)
dbname = DefaultFileCollectionFilename;
string relativeEventPath = Path.ChangeExtension(PathHelper.GetRelativePath(OutputDirectory, destFile), BuildEvent.Extension);
string intermediateEventPath = Path.Combine(IntermediateDirectory, Path.GetFileNameWithoutExtension(dbname), relativeEventPath);
FileHelper.DeleteIfExists(intermediateEventPath);
}
private void SaveBuildEvent(string destFile, BuildEvent buildEvent)
{
string dbname = ResponseFilename;
if (dbname == String.Empty)
dbname = DefaultFileCollectionFilename;
string relativeEventPath = Path.ChangeExtension(PathHelper.GetRelativePath(OutputDirectory, destFile), BuildEvent.Extension);
string intermediateEventPath = Path.Combine(IntermediateDirectory, Path.GetFileNameWithoutExtension(dbname), relativeEventPath);
intermediateEventPath = Path.GetFullPath(intermediateEventPath);
buildEvent.SaveBinary(intermediateEventPath);
}
internal BuildEvent LoadBuildEvent(string destFile)
{
string dbname = ResponseFilename;
if (dbname == String.Empty)
dbname = DefaultFileCollectionFilename;
string relativeEventPath = Path.ChangeExtension(PathHelper.GetRelativePath(OutputDirectory, destFile), BuildEvent.Extension);
string intermediateEventPath = Path.Combine(IntermediateDirectory, Path.GetFileNameWithoutExtension(dbname), relativeEventPath);
intermediateEventPath = Path.GetFullPath(intermediateEventPath);
return BuildEvent.LoadBinary(intermediateEventPath);
}
internal BuildEvent CreateBuildEvent(string sourceFilepath, string outputFilepath, string importerName, string processorName, OpaqueDataDictionary processorParameters)
{
sourceFilepath = PathHelper.Normalize(sourceFilepath);
ResolveOutputFilepath(sourceFilepath, ref outputFilepath);
ResolveImporterAndProcessor(sourceFilepath, ref importerName, ref processorName);
OpaqueDataDictionary ProcessorParams = ValidateProcessorParameters(processorName, processorParameters);
BuildEvent buildEvent = new BuildEvent
{
SourceFile = sourceFilepath,
DestFile = outputFilepath,
Importer = importerName,
Processor = processorName,
Parameters = ProcessorParams,
};
return buildEvent;
}
internal void BuildContent(ConsoleLogger logger, BuildEvent buildEvent, BuildEvent cachedBuildEvent, string destFilePath)
{
if (!File.Exists(buildEvent.SourceFile))
{
logger.LogMessage("{0}", buildEvent.SourceFile);
throw new PipelineException("The source file '{0}' does not exist!", buildEvent.SourceFile);
}
logger.PushFile(buildEvent.SourceFile);
// Keep track of all build events. (Required to resolve automatic names "AssetName_n".)
TrackBuildEvent(buildEvent);
bool building = RegisterBuildEvent(buildEvent);
bool rebuild = buildEvent.NeedsRebuild(this, cachedBuildEvent);
rebuild = rebuild && !building;
if (rebuild)
logger.LogMessage("{0}", buildEvent.SourceFile);
if (!rebuild && !this.Quiet)
logger.LogMessage("Skipping {0}", buildEvent.SourceFile);
logger.Indent();
try
{
if (!rebuild && cachedBuildEvent != null)
{
// While this asset doesn't need to be rebuilt the dependent assets might.
foreach (string asset in cachedBuildEvent.BuildAsset)
{
BuildEvent assetCachedBuildEvent = LoadBuildEvent(asset);
// If we cannot find the cached event for the dependancy
// then we have to trigger a rebuild of the parent content.
if (assetCachedBuildEvent == null)
{
rebuild = true;
break;
}
BuildEvent depBuildEvent = new BuildEvent
{
SourceFile = assetCachedBuildEvent.SourceFile,
DestFile = assetCachedBuildEvent.DestFile,
Importer = assetCachedBuildEvent.Importer,
Processor = assetCachedBuildEvent.Processor,
Parameters = assetCachedBuildEvent.Parameters,
};
// Give the asset a chance to rebuild.
BuildContent(logger, depBuildEvent, assetCachedBuildEvent, asset);
}
}
// Do we need to rebuild?
if (rebuild)
{
// Import and process the content.
object processedObject = ProcessContent(logger, buildEvent);
// Write the content to disk.
WriteXnb(processedObject, buildEvent);
// Store the timestamp of the DLLs containing the importer and processor.
buildEvent.ImporterTime = GetImporterAssemblyTimestamp(buildEvent.Importer);
buildEvent.ProcessorTime = GetProcessorAssemblyTimestamp(buildEvent.Processor);
// Store the new event into the intermediate folder.
SaveBuildEvent(destFilePath, buildEvent);
}
}
finally
{
logger.Unindent();
logger.PopFile();
}
}
private bool RegisterBuildEvent(BuildEvent buildEvent)
{
lock (_processingBuildEvents)
{
if (!_processingBuildEvents.Contains(buildEvent.DestFile))
{
_processingBuildEvents.Add(buildEvent.DestFile);
return false;
}
}
return true;
}
public object ProcessContent(ConsoleLogger logger, BuildEvent buildEvent)
{
if (!File.Exists(buildEvent.SourceFile))
throw new PipelineException("The source file '{0}' does not exist!", buildEvent.SourceFile);
// Store the last write time of the source file
// so we can detect if it has been changed.
buildEvent.SourceTime = File.GetLastWriteTime(buildEvent.SourceFile);
// Make sure we can find the importer and processor.
IContentImporter importer = CreateImporter(buildEvent.Importer);
if (importer == null)
throw new PipelineException("Failed to create importer '{0}'", buildEvent.Importer);
// Try importing the content.
object importedObject;
try
{
ImporterContext importContext = new ImporterContext(this, logger, buildEvent);
importedObject = importer.Import(buildEvent.SourceFile, importContext);
}
catch (PipelineException) { throw; }
catch (InvalidContentException) { throw; }
catch (Exception inner)
{
throw new PipelineException(string.Format("Importer '{0}' had unexpected failure!", buildEvent.Importer), inner);
}
// The pipelineEvent.Processor can be null or empty. In this case the
// asset should be imported but not processed.
if (string.IsNullOrEmpty(buildEvent.Processor))
return importedObject;
IContentProcessor processor = CreateProcessor(buildEvent.Processor, buildEvent.Parameters);
if (processor == null)
throw new PipelineException("Failed to create processor '{0}'", buildEvent.Processor);
// Make sure the input type is valid.
if (!processor.InputType.IsAssignableFrom(importedObject.GetType()))
{
throw new PipelineException(
string.Format("The type '{0}' cannot be processed by {1} as a {2}!",
importedObject.GetType().FullName,
buildEvent.Processor,
processor.InputType.FullName));
}
// Process the imported object.
object processedObject;
try
{
ProcessorContext processContext = new ProcessorContext(this, logger, buildEvent);
processedObject = processor.Process(importedObject, processContext);
}
catch (PipelineException) { throw; }
catch (InvalidContentException) { throw; }
catch (Exception inner)
{
throw new PipelineException(string.Format("Processor '{0}' had unexpected failure!", buildEvent.Processor), inner);
}
return processedObject;
}
public void CleanContent(string sourceFilepath, string outputFilepath)
{
// First try to load the event file.
ResolveOutputFilepath(sourceFilepath, ref outputFilepath);
BuildEvent cachedBuildEvent = LoadBuildEvent(outputFilepath);
if (cachedBuildEvent != null)
{
// Recursively clean additional (nested) assets.
foreach (string asset in cachedBuildEvent.BuildAsset)
{
BuildEvent assetCachedBuildEvent = LoadBuildEvent(asset);
if (assetCachedBuildEvent == null)
{
Logger.LogMessage("Cleaning {0}", asset);
// Remove asset (.xnb file) from output folder.
FileHelper.DeleteIfExists(asset);
// Remove event file (.mgcontent file) from intermediate folder.
DeleteBuildEvent(asset);
continue;
}
CleanContent(string.Empty, asset);
}
// Remove related output files (non-XNB files) that were copied to the output folder.
foreach (var asset in cachedBuildEvent.BuildOutput)
{
Logger.LogMessage("Cleaning {0}", asset);
FileHelper.DeleteIfExists(asset);
}
}
Logger.LogMessage("Cleaning {0}", outputFilepath);
// Remove asset (.xnb file) from output folder.
FileHelper.DeleteIfExists(outputFilepath);
// Remove event file (.mgcontent file) from intermediate folder.
DeleteBuildEvent(outputFilepath);
lock (_buildEventsMap)
{
_buildEventsMap.Remove(sourceFilepath);
}
}
private void WriteXnb(object content, BuildEvent buildEvent)
{
// Make sure the output directory exists.
string outputFileDir = Path.GetDirectoryName(buildEvent.DestFile);
Directory.CreateDirectory(outputFileDir);
if (_compiler == null)
_compiler = new ContentCompiler();
// Write the XNB.
using (Stream stream = new FileStream(buildEvent.DestFile, FileMode.Create, FileAccess.Write, FileShare.None))
_compiler.Compile(stream, content, Platform, Profile, Compression, OutputDirectory, outputFileDir);
// Store the last write time of the output XNB here
// so we can verify it hasn't been tampered with.
buildEvent.DestTime = File.GetLastWriteTime(buildEvent.DestFile);
}
/// <summary>
/// Stores the pipeline build event (in memory) if no matching event is found.
/// </summary>
/// <param name="buildEvent">The pipeline build event.</param>
internal void TrackBuildEvent(BuildEvent buildEvent)
{
lock (_buildEventsMap)
{
List<BuildEvent> buildEvents;
if (!_buildEventsMap.TryGetValue(buildEvent.SourceFile, out buildEvents))
{
buildEvents = new List<BuildEvent>(1);
_buildEventsMap.Add(buildEvent.SourceFile, buildEvents);
}
BuildEvent matchedBuildEvent = FindMatchingEvent(buildEvents, buildEvent.DestFile, buildEvent.Importer, buildEvent.Processor, buildEvent.Parameters);
if (matchedBuildEvent == null)
buildEvents.Add(buildEvent);
}
}
/// <summary>
/// Gets an automatic asset name, such as "AssetName_0".
/// </summary>
/// <param name="sourceFileName">The source file name.</param>
/// <param name="importerName">The name of the content importer. Can be <see langword="null"/>.</param>
/// <param name="processorName">The name of the content processor. Can be <see langword="null"/>.</param>
/// <param name="processorParameters">The processor parameters. Can be <see langword="null"/>.</param>
/// <returns>The asset name.</returns>
public string GetAssetName(string sourceFileName, string importerName, string processorName, OpaqueDataDictionary processorParameters, ContentBuildLogger logger)
{
if (!Path.IsPathRooted(sourceFileName))
sourceFileName = Path.Combine(this.ProjectDirectory, sourceFileName);
// Get source file name, which is used for lookup in _pipelineBuildEvents.
sourceFileName = PathHelper.Normalize(sourceFileName);
string relativeSourceFileName = PathHelper.GetRelativePath(ProjectDirectory, sourceFileName);
List<BuildEvent> buildEvents;
lock (_buildEventsMap)
{
if (_buildEventsMap.TryGetValue(sourceFileName, out buildEvents))
{
// This source file has already been build.
// --> Compare pipeline build events.
ResolveImporterAndProcessor(sourceFileName, ref importerName, ref processorName);
BuildEvent matchedBuildEvent = FindMatchingEvent(buildEvents, null, importerName, processorName, processorParameters);
if (matchedBuildEvent != null)
{
// Matching pipeline build event found.
string existingName = matchedBuildEvent.DestFile;
existingName = PathHelper.GetRelativePath(OutputDirectory, existingName);
existingName = existingName.Substring(0, existingName.Length - 4); // Remove ".xnb".
return existingName;
}
logger.LogMessage(string.Format("Warning: Asset {0} built multiple times with different settings.", relativeSourceFileName));
}
}
// No pipeline build event with matching settings found.
// Get default asset name by searching the existing .mgcontent files.
string directoryName = Path.GetDirectoryName(relativeSourceFileName);
string fileName = Path.GetFileNameWithoutExtension(relativeSourceFileName);
string assetName = Path.Combine(directoryName, fileName);
assetName = PathHelper.Normalize(assetName);
for (int index = 0; ; index++)
{
string destFile = assetName + '_' + index;
BuildEvent existingBuildEvent = LoadBuildEvent(destFile);
if (existingBuildEvent == null)
return destFile;
string existingBuildEventDestFile = existingBuildEvent.DestFile;
existingBuildEventDestFile = PathHelper.GetRelativePath(ProjectDirectory, existingBuildEventDestFile);
existingBuildEventDestFile = Path.Combine(Path.GetDirectoryName(existingBuildEventDestFile), Path.GetFileNameWithoutExtension(existingBuildEventDestFile));
existingBuildEventDestFile = PathHelper.Normalize(existingBuildEventDestFile);
string fullDestFile = Path.Combine(OutputDirectory, destFile);
string relativeDestFile = PathHelper.GetRelativePath(ProjectDirectory, fullDestFile);
relativeDestFile = PathHelper.Normalize(relativeDestFile);
if (existingBuildEventDestFile.Equals(relativeDestFile)
&& existingBuildEvent.Importer == importerName
&& existingBuildEvent.Processor == processorName)
{
OpaqueDataDictionary defaultValues = GetProcessorDefaultValues(processorName);
if (BuildEvent.AreParametersEqual(existingBuildEvent.Parameters, processorParameters, defaultValues))
return destFile;
}
}
}
/// <summary>
/// Determines whether the specified list contains a matching pipeline build event.
/// </summary>
/// <param name="pipelineBuildEvents">The list of pipeline build events.</param>
/// <param name="destFile">Absolute path to the output file. Can be <see langword="null"/>.</param>
/// <param name="importerName">The name of the content importer. Can be <see langword="null"/>.</param>
/// <param name="processorName">The name of the content processor. Can be <see langword="null"/>.</param>
/// <param name="processorParameters">The processor parameters. Can be <see langword="null"/>.</param>
/// <returns>
/// The matching pipeline build event, or <see langword="null"/>.
/// </returns>
private BuildEvent FindMatchingEvent(List<BuildEvent> pipelineBuildEvents, string destFile, string importerName, string processorName, OpaqueDataDictionary processorParameters)
{
foreach (BuildEvent existingBuildEvent in pipelineBuildEvents)
{
if ((destFile == null || existingBuildEvent.DestFile.Equals(destFile))
&& existingBuildEvent.Importer == importerName
&& existingBuildEvent.Processor == processorName)
{
OpaqueDataDictionary defaultValues = GetProcessorDefaultValues(processorName);
if (BuildEvent.AreParametersEqual(existingBuildEvent.Parameters, processorParameters, defaultValues))
{
return existingBuildEvent;
}
}
}
return null;
}
}
}