JITCompiler.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Drawing;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Runtime;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using NTERA.Core;
  12. using NTERA.Engine.Compiler;
  13. using NTERA.Engine.Runtime.Resources;
  14. namespace NTERA.Engine.Runtime
  15. {
  16. public class JITCompiler : IExecutionProvider
  17. {
  18. public ICollection<FunctionDefinition> DefinedProcedures { get; protected set; }
  19. public ICollection<FunctionDefinition> DefinedFunctions { get; protected set; }
  20. public ICollection<FunctionVariable> DefinedConstants { get; protected set; }
  21. public CSVDefinition CSVDefinition { get; protected set; }
  22. protected Dictionary<string, ImageDefinition> ImageDefinitions { get; set; }
  23. protected Dictionary<FunctionDefinition, string> ProcedureFiles { get; set; }
  24. public Dictionary<FunctionDefinition, ExecutionNode[]> CompiledProcedures { get; protected set; } = new Dictionary<FunctionDefinition, ExecutionNode[]>();
  25. public string InputDirectory { get; }
  26. protected string CSVPath { get; set; }
  27. protected string ERBPath { get; set; }
  28. protected string ResourcePath { get; set; }
  29. public static int Threads = 4;
  30. public JITCompiler(string path)
  31. {
  32. InputDirectory = path;
  33. }
  34. public void Initialize(IConsole console)
  35. {
  36. Stopwatch stopwatch = new Stopwatch();
  37. stopwatch.Start();
  38. CSVPath = Path.Combine(InputDirectory, "CSV");
  39. ERBPath = Path.Combine(InputDirectory, "ERB");
  40. ResourcePath = Path.Combine(InputDirectory, "resources");
  41. CSVDefinition = new CSVDefinition();
  42. ImageDefinitions = new Dictionary<string, ImageDefinition>();
  43. if (!Directory.Exists(InputDirectory) || !Directory.Exists(CSVPath) || !Directory.Exists(ERBPath)) {
  44. console.PrintError($"{InputDirectory} does not appear to be an era game. Expecting to find {InputDirectory}/CSV and /ERB and /resources.\nPlease set current working directory or the ERA environment variable to the era folder.");
  45. return;
  46. }
  47. console.PrintSystemLine("Preprocessing CSV files...");
  48. foreach (var file in Directory.EnumerateFiles(CSVPath, "*.csv", SearchOption.AllDirectories))
  49. {
  50. string localName = Path.GetFileNameWithoutExtension(file);
  51. if (localName == null || localName.EndsWith("_TR"))
  52. continue;
  53. Preprocessor.ProcessCSV(CSVDefinition, localName, File.ReadLines(file, Encoding.UTF8));
  54. }
  55. foreach (var file in Directory.EnumerateFiles(ResourcePath, "*.csv", SearchOption.TopDirectoryOnly))
  56. {
  57. foreach (var line in Preprocessor.SplitCSV(File.ReadLines(file)))
  58. {
  59. if (line.Count != 2 && line.Count != 6)
  60. throw new ParserException($"Unable to parse resource CSV file '{Path.GetFileName(file)}'");
  61. ImageDefinition definition = new ImageDefinition
  62. {
  63. Name = line[0],
  64. Filename = line[1],
  65. Dimensions = null
  66. };
  67. if (line.Count == 6)
  68. {
  69. definition.Dimensions = new Rectangle(int.Parse(line[2]), int.Parse(line[3]), int.Parse(line[4]), int.Parse(line[5]));
  70. }
  71. ImageDefinitions[definition.Name] = definition;
  72. }
  73. }
  74. console.PrintSystemLine("Preprocessing header files...");
  75. ConcurrentBag<FunctionVariable> preprocessedConstants = new ConcurrentBag<FunctionVariable>();
  76. #if DEBUG
  77. foreach (var file in Directory.EnumerateFiles(ERBPath, "*.erh", SearchOption.AllDirectories))
  78. #else
  79. Parallel.ForEach(Directory.EnumerateFiles(ERBPath, "*.erh", SearchOption.AllDirectories), new ParallelOptions
  80. {
  81. MaxDegreeOfParallelism = Threads
  82. }, file =>
  83. #endif
  84. {
  85. foreach (var variable in Preprocessor.PreprocessHeaderFile(File.ReadAllText(file)))
  86. preprocessedConstants.Add(variable);
  87. #if DEBUG
  88. }
  89. #else
  90. });
  91. #endif
  92. DefinedConstants = preprocessedConstants.ToArray();
  93. console.PrintSystemLine("Preprocessing functions...");
  94. ProcedureFiles = new Dictionary<FunctionDefinition, string>();
  95. ConcurrentDictionary<FunctionDefinition, string> preprocessedFunctions = new ConcurrentDictionary<FunctionDefinition, string>();
  96. #if DEBUG
  97. foreach (var file in Directory.EnumerateFiles(ERBPath, "*.erb", SearchOption.AllDirectories))
  98. #else
  99. Parallel.ForEach(Directory.EnumerateFiles(ERBPath, "*.erb", SearchOption.AllDirectories), new ParallelOptions
  100. {
  101. MaxDegreeOfParallelism = Threads
  102. }, file =>
  103. #endif
  104. {
  105. foreach (var kv in Preprocessor.PreprocessCodeFile(File.ReadAllText(file), Path.GetFileName(file), DefinedConstants))
  106. {
  107. preprocessedFunctions[kv.Key] = kv.Value;
  108. ProcedureFiles[kv.Key] = file;
  109. }
  110. #if DEBUG
  111. }
  112. #else
  113. });
  114. #endif
  115. DefinedProcedures = preprocessedFunctions.Select(kv => kv.Key).ToArray();
  116. var declaredFunctions = BaseDefinitions.DefaultGlobalFunctions.ToList();
  117. declaredFunctions.AddRange(DefinedProcedures.Where(x => x.IsReturnFunction));
  118. DefinedFunctions = declaredFunctions;
  119. console.PrintSystemLine("Compacting memory...");
  120. GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
  121. GC.Collect();
  122. stopwatch.Stop();
  123. console.PrintSystemLine($"Completed initialization in {stopwatch.ElapsedMilliseconds}ms");
  124. }
  125. public IEnumerable<ExecutionNode> GetExecutionNodes(FunctionDefinition function)
  126. {
  127. if (CompiledProcedures.ContainsKey(function))
  128. return CompiledProcedures[function];
  129. string filename = ProcedureFiles[function];
  130. var preprocessed = Preprocessor.PreprocessCodeFile(File.ReadAllText(filename), Path.GetFileName(filename), DefinedConstants);
  131. Parser parser = new Parser(preprocessed.Single(x => x.Key.Name == function.Name).Value, function, DefinedFunctions, DefinedProcedures.Where(x => !x.IsReturnFunction).ToArray(), BaseDefinitions.DefaultGlobalVariables, function.Variables, BaseDefinitions.DefaultKeywords, CSVDefinition, DefinedConstants);
  132. var nodes = parser.Parse(out var localErrors, out var localWarnings)?.ToArray();
  133. if (localErrors.Count > 0)
  134. throw new ParserException($"Failed to compile '{function.Name}'");
  135. CompiledProcedures.Add(function, nodes);
  136. return nodes;
  137. }
  138. protected Dictionary<string, Bitmap> BitmapCache = new Dictionary<string, Bitmap>();
  139. public Bitmap GetImage(string imageName, out ImageDefinition definition)
  140. {
  141. definition = ImageDefinitions[imageName];
  142. string filename = Path.Combine(ResourcePath, definition.Filename);
  143. if (!BitmapCache.TryGetValue(filename, out var bitmap))
  144. {
  145. bitmap = new Bitmap(filename);
  146. BitmapCache.Add(filename, bitmap);
  147. }
  148. return bitmap;
  149. }
  150. }
  151. }