58 using (var process =
new Process())
60 process.StartInfo =
new ProcessStartInfo(
Compiler, arguments) {
61 UseShellExecute =
false, CreateNoWindow =
true,
62 RedirectStandardOutput =
true, RedirectStandardError =
true
70 var stdout = process.StandardOutput.ReadToEndAsync();
71 var stderr = process.StandardError.ReadToEndAsync();
72 while (!process.WaitForExit(100))
cancellation.Token.ThrowIfCancellationRequested();
73 var diagnostics = stdout.GetAwaiter().GetResult() + stderr.GetAwaiter().GetResult();
76 if (process.ExitCode != 0 || Regex.IsMatch(diagnostics,
@"\berror(\s+[A-Z][0-9]+)?\s*:", RegexOptions.IgnoreCase))
77 throw new InvalidOperationException(
"FXC failed (" + process.ExitCode +
"): " + arguments +
"\n" + diagnostics);
78 if (!String.IsNullOrWhiteSpace(diagnostics))
80 if (Regex.IsMatch(diagnostics,
@"\bwarning\s+[A-Z][0-9]+\s*:", RegexOptions.IgnoreCase))
81 Log.LogWarning(
"{0}", diagnostics.Trim());
82 else Log.LogMessage(MessageImportance.Low,
"{0}", diagnostics.Trim());
88 if (!process.HasExited) { process.Kill(); process.WaitForExit(); }
129 if (File.Exists(path) &&
new FileInfo(path).Length == bytes.Length && File.ReadAllBytes(path).SequenceEqual(bytes))
return;
130 var temporary = path +
"." + Guid.NewGuid().ToString(
"N") +
".tmp";
133 File.WriteAllBytes(temporary, bytes);
134 if (File.Exists(path)) File.Replace(temporary, path,
null);
135 else File.Move(temporary, path);
137 finally {
if (File.Exists(temporary)) File.Delete(temporary); }
147 var failures =
new ConcurrentQueue<Exception>();
153 Parallel.ForEach(Partitioner.Create(items, EnumerablePartitionerOptions.NoBuffering),
154 new ParallelOptions { MaxDegreeOfParallelism = MaxParallelism, CancellationToken = cancellation.Token }, item => {
155 try { action(item); }
156 catch (OperationCanceledException) {
throw; }
157 catch (Exception error) { failures.Enqueue(error);
cancellation.Cancel();
throw; }
164 if (!failures.IsEmpty)
throw new AggregateException(failures);
171 var timer = Stopwatch.StartNew();
172 string temporaryDirectory =
null;
175 if (MaxParallelism < 1 || MaxParallelism > 64)
throw new ArgumentException(
"NativeShaderMaxParallelism must be between 1 and 64.");
176 if (!Regex.IsMatch(
Optimization ??
"",
"^O[0-3]$"))
throw new ArgumentException(
"NativeShaderOptimization must be O0, O1, O2 or O3.");
180 var compilerDirectory = Path.GetDirectoryName(
Compiler);
181 var compilerLibraries = Directory.GetFiles(compilerDirectory,
"d3dcompiler_*.dll").OrderBy(p => p, StringComparer.OrdinalIgnoreCase).ToArray();
182 if (compilerLibraries.Length == 0)
183 throw new FileNotFoundException(
"Use Windows SDK FXC with its adjacent d3dcompiler DLL so the compiler identity can be verified.");
184 var compilerIdentity =
Hash(File.ReadAllBytes(
Compiler)) +
"\n" + String.Join(
"\n",
185 compilerLibraries.Select(p => Path.GetFileName(p) +
":" +
Hash(File.ReadAllBytes(p))));
186 var identities =
new HashSet<string>(StringComparer.OrdinalIgnoreCase);
189 if (!Regex.IsMatch(item.ItemSpec,
"^[A-Za-z0-9_-]+$") || !identities.Add(item.ItemSpec) ||
190 !Regex.IsMatch(item.GetMetadata(
"Entry"),
"^[A-Za-z_][A-Za-z0-9_]*$") ||
191 !Regex.IsMatch(item.GetMetadata(
"Profile"),
"^(vs|ps|gs|hs|ds|cs)_5_0$") ||
192 !Regex.IsMatch(item.GetMetadata(
"Samples"),
"^[1248]$"))
193 throw new ArgumentException(
"Invalid or duplicate native shader item: " + item.ItemSpec);
197 temporaryDirectory = Path.Combine(
CacheDirectory,
"tmp", Guid.NewGuid().ToString(
"N"));
198 Directory.CreateDirectory(temporaryDirectory);
199 var snapshots =
new ConcurrentDictionary<string, Snapshot>();
202 var item = group.First();
203 var path = Path.Combine(temporaryDirectory, Guid.NewGuid().ToString(
"N") +
".hlsl");
204 RunCompiler(
"/nologo /P " + Quote(path) +
" /D RISE_SCENE_SAMPLES=" + item.GetMetadata(
"Samples") +
" " + Quote(Path.GetFullPath(item.GetMetadata(
"Source"))));
205 var bytes = File.ReadAllBytes(path);
208 var dependencies = Regex.Matches(Encoding.UTF8.GetString(bytes),
"(?m)^#line [0-9]+ \"([^\"]+)\"")
209 .Cast<Match>().Select(m => m.Groups[1].Value.Replace(
"\\\\",
"\\")).Distinct(StringComparer.OrdinalIgnoreCase);
210 snapshots[group.Key] = new Snapshot { Path = path, Hash = Hash(bytes), Dependencies = String.Join(
"\n", dependencies) };
212 int hits = 0, compiled = 0;
213 ParallelWork(
Shaders, item => {
214 var snapshot = snapshots[
GroupKey(item)];
215 var compileFlags =
"/nologo /Ges /Zpr /" +
Optimization +
" /T " + item.GetMetadata(
"Profile") +
" /E " + item.GetMetadata(
"Entry");
216 var flags = compileFlags +
" /D RISE_SCENE_SAMPLES=" + item.GetMetadata(
"Samples");
217 var key =
Hash(Encoding.UTF8.GetBytes(
"RiseNativeShaderCache-v1\n" + compilerIdentity +
"\n" + flags +
"\n" + snapshot.Hash));
218 var directory = Path.Combine(
CacheDirectory, key.Substring(0, 2));
219 Directory.CreateDirectory(directory);
220 var cached = Path.Combine(directory, key +
".cso");
225 if (bytes !=
null) Interlocked.Increment(ref hits);
228 Log.LogMessage(MessageImportance.Normal,
"Compiling shader {0}", item.ItemSpec);
229 var output = Path.Combine(temporaryDirectory, item.ItemSpec +
".cso");
233 bytes = File.ReadAllBytes(output);
234 if (!
ValidBytecode(bytes))
throw new InvalidDataException(
"Invalid DXBC output for " + item.ItemSpec);
237 Interlocked.Increment(ref compiled);
242 "cache-key: " + key +
"\nbytecode-sha256: " +
Hash(bytes) +
"\nflags: " + flags +
"\n" + snapshot.Dependencies +
"\n"));
246 Log.LogMessage(MessageImportance.High,
"Native shaders: {0} cache hits, {1} compiled, {2} variants; {3:F2}s; peak {4} FXC processes.", hits, compiled,
Shaders.Length, timer.Elapsed.TotalSeconds,
PeakCompilerProcesses);
249 catch (OperationCanceledException) { Log.LogError(
"Native shader build cancelled.");
return false; }
250 catch (Exception error) {
Log.LogErrorFromException(error,
true);
return false; }
253 if (temporaryDirectory !=
null && Directory.Exists(temporaryDirectory))
254 Directory.Delete(temporaryDirectory,
true);