Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(desktop): use DXC for Windows shaders (#2135)

Luke Parker941fba8e7ea8
diff --git a/apps/desktop/scripts/prepare.js b/apps/desktop/scripts/prepare.js
index dc3e28d9a..93b9ea065 100644
--- a/apps/desktop/scripts/prepare.js
+++ b/apps/desktop/scripts/prepare.js
@@ -87,6 +87,8 @@ export async function createTauriPlatformConfigs(
],
resources: {
"../../../target/ffmpeg/bin/*.dll": "./",
+ "../../../target/native-deps/dxc/*.dll": "./",
+ "../../../target/native-deps/dxc/LICENSE-*.txt": "licenses/dxc/",
"../../../target/native-deps/onnxruntime/lib/*.dll": "./",
},
windows: {
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index fa9d74947..e1f71c5f6 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -200,12 +200,52 @@ pub fn create_wgpu_instance_sync() -> wgpu::Instance {
#[cfg(target_os = "windows")]
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
backends: wgpu::Backends::DX12,
+ backend_options: wgpu::BackendOptions {
+ dx12: wgpu::Dx12BackendOptions {
+ shader_compiler: bundled_dxc_compiler(),
+ },
+ ..Default::default()
+ },
..Default::default()
});
instance
}
+#[cfg(target_os = "windows")]
+fn bundled_dxc_compiler() -> wgpu::Dx12Compiler {
+ let Some((dxc_path, dxil_path)) = bundled_dxc_paths() else {
+ tracing::debug!("Bundled DXC unavailable; using FXC for DX12 shader compilation");
+ return wgpu::Dx12Compiler::Fxc;
+ };
+
+ tracing::info!(
+ dxc_path = %dxc_path.display(),
+ dxil_path = %dxil_path.display(),
+ "Using bundled DXC for DX12 shader compilation"
+ );
+ wgpu::Dx12Compiler::DynamicDxc {
+ dxc_path: dxc_path.to_string_lossy().into_owned(),
+ dxil_path: dxil_path.to_string_lossy().into_owned(),
+ max_shader_model: wgpu::DxcShaderModel::V6_7,
+ }
+}
+
+#[cfg(target_os = "windows")]
+fn bundled_dxc_paths() -> Option<(PathBuf, PathBuf)> {
+ let executable = std::env::current_exe().ok()?;
+ let executable_dir = executable.parent()?;
+ let profile_dir = (executable_dir.file_name()? == "deps")
+ .then(|| executable_dir.parent())
+ .flatten();
+
+ [Some(executable_dir), profile_dir]
+ .into_iter()
+ .flatten()
+ .map(|dir| (dir.join("dxcompiler.dll"), dir.join("dxil.dll")))
+ .find(|(dxc_path, dxil_path)| dxc_path.is_file() && dxil_path.is_file())
+}
+
pub async fn create_wgpu_instance() -> wgpu::Instance {
create_wgpu_instance_sync()
}
diff --git a/scripts/setup.js b/scripts/setup.js
index ca7b116f1..3c02605e6 100644
--- a/scripts/setup.js
+++ b/scripts/setup.js
@@ -1,6 +1,7 @@
// @ts-check
import { exec as execCb, execFile as execFileCb } from "node:child_process";
+import { createHash } from "node:crypto";
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { env } from "node:process";
@@ -204,6 +205,8 @@ async function main() {
);
console.log("Copied ffmpeg/lib and ffmpeg/include to target/native-deps");
+ await setupWindowsDxc();
+
const onnxRuntimePath = await setupWindowsOnnxRuntime();
cargoConfigContents += `ORT_DYLIB_PATH = { relative = true, force = true, value = "${cargoConfigPath(
path.relative(__root, onnxRuntimePath),
@@ -497,6 +500,108 @@ async function setupWindowsOnnxRuntime() {
return outputPath;
}
+async function setupWindowsDxc() {
+ const asset = {
+ version: "1.9.2607.13",
+ name: "microsoft.direct3d.dxc.1.9.2607.13.zip",
+ url: "https://api.nuget.org/v3-flatcontainer/microsoft.direct3d.dxc/1.9.2607.13/microsoft.direct3d.dxc.1.9.2607.13.nupkg",
+ sha256: "5d6acd23089b2979a3c1d39b7e31227da989a47b5d9f3db57111ad4717ea537e",
+ };
+ const assetArch = { x86_64: "x64", aarch64: "arm64" }[arch];
+ if (!assetArch)
+ throw new Error(`Unsupported Windows architecture for DXC: ${arch}`);
+
+ const archivePath = await downloadVerifiedAsset(asset);
+ const extractDir = path.join(targetDir, asset.name.replace(/\.zip$/, ""));
+ const outputDir = path.join(targetDir, "native-deps", "dxc");
+ const markerPath = path.join(outputDir, "asset.txt");
+ const marker = `${asset.name}:${assetArch}:${asset.sha256}`;
+ const currentMarker = await fs
+ .readFile(markerPath, "utf-8")
+ .then((value) => value.trim())
+ .catch(() => null);
+ const files = [
+ {
+ name: "dxcompiler.dll",
+ source: ["build", "native", "bin", assetArch, "dxcompiler.dll"],
+ runtime: true,
+ },
+ {
+ name: "dxil.dll",
+ source: ["build", "native", "bin", assetArch, "dxil.dll"],
+ runtime: true,
+ },
+ { name: "LICENSE-LLVM.txt", source: ["LICENSE-LLVM.txt"] },
+ { name: "LICENSE-MS.txt", source: ["LICENSE-MS.txt"] },
+ ];
+ const missingAssets = await missingFiles(
+ outputDir,
+ files.map((file) => file.name),
+ );
+
+ if (currentMarker !== marker || missingAssets.length > 0) {
+ await fs.rm(extractDir, { recursive: true, force: true }).catch(() => {});
+ await exec(
+ `Expand-Archive -Path "${archivePath}" -DestinationPath "${extractDir}" -Force`,
+ { shell: "powershell.exe" },
+ );
+ await fs.rm(outputDir, { recursive: true, force: true }).catch(() => {});
+ await fs.mkdir(outputDir, { recursive: true });
+ for (const file of files)
+ await fs.copyFile(
+ path.join(extractDir, ...file.source),
+ path.join(outputDir, file.name),
+ );
+ await fs.writeFile(markerPath, marker);
+ console.log(`Prepared DXC ${asset.version} for ${assetArch}`);
+ } else console.log(`Using cached DXC ${asset.version} for ${assetArch}`);
+
+ const profileDirs = [
+ path.join(targetDir, "debug"),
+ path.join(targetDir, "release"),
+ ];
+ if (process.env.RUST_TARGET_TRIPLE)
+ for (const profile of ["debug", "release"])
+ profileDirs.push(
+ path.join(targetDir, process.env.RUST_TARGET_TRIPLE, profile),
+ );
+
+ for (const profileDir of profileDirs) {
+ await fs.mkdir(profileDir, { recursive: true });
+ for (const file of files.filter((file) => file.runtime))
+ await fs.copyFile(
+ path.join(outputDir, file.name),
+ path.join(profileDir, file.name),
+ );
+ }
+ console.log("Copied DXC DLLs to target profile directories");
+}
+
+async function downloadVerifiedAsset(asset) {
+ const archivePath = path.join(targetDir, asset.name);
+ if (!(await fileExists(archivePath))) {
+ const response = await fetch(asset.url);
+ if (!response.ok)
+ throw new Error(
+ `Failed to download ${asset.name}: HTTP ${response.status}`,
+ );
+ await fs.writeFile(archivePath, Buffer.from(await response.arrayBuffer()));
+ console.log(`Downloaded ${asset.name}`);
+ } else console.log(`Using cached ${asset.name}`);
+
+ const actualHash = createHash("sha256")
+ .update(await fs.readFile(archivePath))
+ .digest("hex");
+ if (actualHash !== asset.sha256) {
+ await fs.rm(archivePath, { force: true });
+ throw new Error(
+ `${asset.name} SHA-256 mismatch: got ${actualHash}, expected ${asset.sha256}; removed invalid cached archive`,
+ );
+ }
+
+ return archivePath;
+}
+
async function writeFileIfChanged(filePath, contents) {
const currentContents = await fs
.readFile(filePath, "utf-8")