Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / library / ml / src / main / rust / build.rs

build.rs153 lines · 5.8 KiBRaw
1//! Compiles `shaders/*.comp` to SPIR-V in `OUT_DIR`.
2//!
3//! The library and the host examples `include_bytes!` the compiled shaders
4//! from `OUT_DIR`. Previously the library read them from the Gradle
5//! `compileShaders` output (`library/ml/build/spirv`), so standalone
6//! `cargo check` / `cargo test` failed in a clean checkout until that Gradle
7//! task had run, and the examples referenced an `OUT_DIR` that no build
8//! script ever populated. Compiling here uses the same compiler and flags
9//! as the Gradle task (`--target-env=vulkan1.1 -O`, NDK `glslc`), so the
10//! Android build embeds identical SPIR-V; the Gradle task's output is still
11//! honoured as a fallback when no `glslc` can be found. When neither is
12//! available the build fails loudly rather than embedding stub shaders.
13
14use std::env;
15use std::fs;
16use std::path::PathBuf;
17use std::process::{exit, Command};
18
19fn main() {
20 if let Err(message) = run() {
21 eprintln!("modelrunner build script: {message}");
22 exit(1);
23 }
24}
25
26fn run() -> Result<(), String> {
27 let manifest_dir = env::var_os("CARGO_MANIFEST_DIR")
28 .map(PathBuf::from)
29 .ok_or_else(|| "CARGO_MANIFEST_DIR is not set".to_owned())?;
30 let out_dir =
31 env::var_os("OUT_DIR").map(PathBuf::from).ok_or_else(|| "OUT_DIR is not set".to_owned())?;
32 let shader_dir = manifest_dir.join("shaders");
33 println!("cargo:rerun-if-changed={}", shader_dir.display());
34 println!("cargo:rerun-if-env-changed=GLSLC");
35 println!("cargo:rerun-if-env-changed=ANDROID_HOME");
36 println!("cargo:rerun-if-env-changed=ANDROID_SDK_ROOT");
37 println!("cargo:rerun-if-env-changed=ANDROID_NDK_HOME");
38
39 let mut sources = Vec::new();
40 let entries = fs::read_dir(&shader_dir)
41 .map_err(|error| format!("cannot read {}: {error}", shader_dir.display()))?;
42 for entry in entries {
43 let path =
44 entry.map_err(|error| format!("cannot read {}: {error}", shader_dir.display()))?.path();
45 if path.extension().is_some_and(|ext| ext == "comp") {
46 sources.push(path);
47 }
48 }
49 sources.sort();
50 if sources.is_empty() {
51 return Err(format!("no .comp shaders in {}", shader_dir.display()));
52 }
53
54 if let Some(glslc) = find_glslc() {
55 for source in &sources {
56 let file_name = source
57 .file_name()
58 .ok_or_else(|| format!("shader {} has no file name", source.display()))?
59 .to_string_lossy()
60 .into_owned();
61 let output = out_dir.join(format!("{file_name}.spv"));
62 let status = Command::new(&glslc)
63 .args(["--target-env=vulkan1.1", "-O", "-o"])
64 .arg(&output)
65 .arg(source)
66 .status()
67 .map_err(|error| format!("cannot run {}: {error}", glslc.display()))?;
68 if !status.success() {
69 return Err(format!(
70 "{} failed on {} with {status}",
71 glslc.display(),
72 source.display()
73 ));
74 }
75 }
76 return Ok(());
77 }
78
79 // No compiler: copy the Gradle `compileShaders` output verbatim.
80 let prebuilt = manifest_dir.join("../../../build/spirv");
81 let mut copied = 0usize;
82 for source in &sources {
83 let file_name = source
84 .file_name()
85 .ok_or_else(|| format!("shader {} has no file name", source.display()))?
86 .to_string_lossy()
87 .into_owned();
88 let from = prebuilt.join(format!("{file_name}.spv"));
89 if from.is_file() {
90 fs::copy(&from, out_dir.join(format!("{file_name}.spv")))
91 .map_err(|error| format!("cannot copy {}: {error}", from.display()))?;
92 copied += 1;
93 }
94 }
95 if copied == sources.len() {
96 return Ok(());
97 }
98 Err(format!(
99 "glslc not found (set GLSLC, put it on PATH, or install the Android NDK) and \
100 prebuilt SPIR-V is incomplete in {}; refusing to embed stub shaders",
101 prebuilt.display()
102 ))
103}
104
105/// `GLSLC`, then `PATH`, then the newest NDK under the Android SDK.
106fn find_glslc() -> Option<PathBuf> {
107 let exe = if cfg!(windows) { "glslc.exe" } else { "glslc" };
108 if let Some(path) = env::var_os("GLSLC").map(PathBuf::from) {
109 if path.is_file() {
110 return Some(path);
111 }
112 }
113 if let Some(path_var) = env::var_os("PATH") {
114 for dir in env::split_paths(&path_var) {
115 let candidate = dir.join(exe);
116 if candidate.is_file() {
117 return Some(candidate);
118 }
119 }
120 }
121 let mut sdk_roots: Vec<PathBuf> = ["ANDROID_NDK_HOME", "ANDROID_HOME", "ANDROID_SDK_ROOT"]
122 .iter()
123 .filter_map(|key| env::var_os(key).map(PathBuf::from))
124 .collect();
125 if let Some(home) = env::var_os("HOME").map(PathBuf::from) {
126 sdk_roots.push(home.join("Android/Sdk"));
127 }
128 let mut candidates = Vec::new();
129 for root in &sdk_roots {
130 // `ANDROID_NDK_HOME` points at the NDK itself; the others at the SDK,
131 // whose NDKs live under `ndk/<version>/`.
132 let ndk_dirs: Vec<PathBuf> = if root.join("shader-tools").is_dir() {
133 vec![root.clone()]
134 } else {
135 match fs::read_dir(root.join("ndk")) {
136 Ok(entries) => entries.filter_map(|entry| entry.ok().map(|e| e.path())).collect(),
137 Err(_) => Vec::new(),
138 }
139 };
140 for ndk in ndk_dirs {
141 if let Ok(hosts) = fs::read_dir(ndk.join("shader-tools")) {
142 for host in hosts.filter_map(|entry| entry.ok().map(|e| e.path())) {
143 let candidate = host.join(exe);
144 if candidate.is_file() {
145 candidates.push(candidate);
146 }
147 }
148 }
149 }
150 }
151 candidates.sort();
152 candidates.pop()
153}