1use std::sync::{
6 Arc,
7 atomic::{AtomicU64, Ordering},
8};
9
10use anyhow::bail;
11use parking_lot::Mutex;
12
13pub const APP_EFFECTS_DIR_ENV: &str = "SK_EFFECTS_DIR";
16
17pub const APP_EFFECTS_SCHEMA: u32 = 10;
19
20#[derive(Debug, Clone, PartialEq, Eq)]
22pub enum AppEffectSource {
23 Unlisted,
25 Missing(String),
27 Present {
29 file: String,
31 text: String,
33 },
34}
35
36impl AppEffectSource {
37 pub fn get(&self, language: &str) -> anyhow::Result<(&str, &str)> {
39 match self {
40 AppEffectSource::Unlisted => {
41 bail!("effects.json lists no {language} for it; rebuild the app with sk build")
42 }
43 AppEffectSource::Missing(file) => bail!("the app's effects have no {file}"),
44 AppEffectSource::Present { file, text } => Ok((file, text)),
45 }
46 }
47}
48
49#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct AppEffect {
53 pub name: String,
55 pub needs_backdrop: bool,
57 pub content: bool,
59 pub history: bool,
62 pub hlsl: AppEffectSource,
64 pub wgsl: AppEffectSource,
66 pub metal: AppEffectSource,
68}
69
70#[derive(Debug)]
72pub struct AppEffects {
73 pub origin: String,
75 pub manifest: String,
77 effects: Vec<AppEffect>,
78}
79
80#[derive(serde::Deserialize)]
81struct RawManifest {
82 schema: u32,
83 effects: Vec<RawEffect>,
84}
85
86#[derive(serde::Deserialize)]
87struct RawEffect {
88 name: String,
89 backdrop: bool,
90 #[serde(default)]
91 content: bool,
92 #[serde(default)]
93 history: bool,
94 #[serde(default)]
95 hlsl: Option<String>,
96 #[serde(default)]
97 wgsl: Option<String>,
98 #[serde(default)]
99 metal: Option<String>,
100}
101
102impl AppEffects {
103 pub fn new(
105 origin: impl Into<String>,
106 manifest: impl Into<String>,
107 files: impl IntoIterator<Item = (String, String)>,
108 ) -> Result<Self, String> {
109 let origin = origin.into();
110 let manifest = manifest.into();
111 let raw: RawManifest = serde_json::from_str(&manifest)
112 .map_err(|e| format!("{origin}: effects.json is not readable ({e})"))?;
113 if raw.schema != APP_EFFECTS_SCHEMA {
114 return Err(format!(
115 "{origin}: effects.json is schema {} but this build understands \
116 {APP_EFFECTS_SCHEMA} — rebuild the app with the sk that matches this host",
117 raw.schema
118 ));
119 }
120 let files: std::collections::HashMap<String, String> = files.into_iter().collect();
121 let source = |file: Option<String>| match file {
122 None => AppEffectSource::Unlisted,
123 Some(file) => match files.get(&file).cloned() {
124 Some(text) => AppEffectSource::Present { file, text },
125 None => AppEffectSource::Missing(file),
126 },
127 };
128 let effects = raw
129 .effects
130 .into_iter()
131 .map(|effect| AppEffect {
132 hlsl: source(effect.hlsl),
133 wgsl: source(effect.wgsl),
134 metal: source(effect.metal),
135 needs_backdrop: effect.backdrop,
136 content: effect.content,
137 history: effect.history,
138 name: effect.name,
139 })
140 .collect();
141 Ok(Self {
142 origin,
143 manifest,
144 effects,
145 })
146 }
147
148 pub fn from_dir(dir: &std::path::Path) -> Result<Self, String> {
150 let manifest_path = dir.join("effects.json");
151 let manifest = std::fs::read_to_string(&manifest_path)
152 .map_err(|e| format!("{} could not be read ({e})", manifest_path.display()))?;
153 let mut files = Vec::new();
154 let entries = std::fs::read_dir(dir)
155 .map_err(|e| format!("{} could not be listed ({e})", dir.display()))?;
156 for entry in entries.flatten() {
157 let path = entry.path();
158 let shader = path
159 .extension()
160 .is_some_and(|ext| ext == "hlsl" || ext == "wgsl" || ext == "metal");
161 let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
162 continue;
163 };
164 if shader {
165 let text = std::fs::read_to_string(&path)
166 .map_err(|e| format!("{} could not be read ({e})", path.display()))?;
167 files.push((name.to_string(), text));
168 }
169 }
170 Self::new(dir.display().to_string(), manifest, files)
171 }
172
173 pub fn effects(&self) -> &[AppEffect] {
175 &self.effects
176 }
177}
178
179struct Installed {
180 read: bool,
181 effects: Option<Arc<AppEffects>>,
182}
183
184static INSTALLED: Mutex<Installed> = Mutex::new(Installed {
185 read: false,
186 effects: None,
187});
188static GENERATION: AtomicU64 = AtomicU64::new(0);
189
190fn app_effects_dir() -> Option<std::path::PathBuf> {
191 std::env::var_os(APP_EFFECTS_DIR_ENV)
192 .filter(|dir| !dir.is_empty())
193 .map(std::path::PathBuf::from)
194}
195
196pub fn set_app_effects(effects: AppEffects) -> bool {
200 if app_effects_dir().is_some() {
201 return false;
202 }
203 let mut installed = INSTALLED.lock();
204 if installed.read {
205 return false;
206 }
207 installed.read = true;
208 installed.effects = Some(Arc::new(effects));
209 true
210}
211
212pub fn reload_app_effects(effects: AppEffects) {
215 let mut installed = INSTALLED.lock();
216 installed.read = true;
217 installed.effects = Some(Arc::new(effects));
218 GENERATION.fetch_add(1, Ordering::Release);
219}
220
221pub fn app_effects_generation() -> u64 {
223 GENERATION.load(Ordering::Acquire)
224}
225
226pub fn app_effects() -> Option<Arc<AppEffects>> {
229 let mut installed = INSTALLED.lock();
230 if !installed.read {
231 installed.read = true;
232 installed.effects = app_effects_dir().and_then(|dir| {
233 AppEffects::from_dir(&dir)
234 .map_err(|error| {
235 let message = format!(
236 "{APP_EFFECTS_DIR_ENV} is set to `{}` but {error} — the app's own \
237 `--shading` effects are unavailable",
238 dir.display()
239 );
240 log::warn!("{message}");
241 eprintln!("skathi: {message}");
242 })
243 .ok()
244 .map(Arc::new)
245 });
246 }
247 installed.effects.clone()
248}
249
250pub struct AppEffectPipelines<P> {
254 generation: Option<u64>,
255 slots: Vec<AppEffectSlot<P>>,
256}
257
258struct AppEffectSlot<P> {
259 effect: AppEffect,
261 pipeline: Option<P>,
262}
263
264impl<P> Default for AppEffectPipelines<P> {
265 fn default() -> Self {
266 Self {
267 generation: None,
268 slots: Vec::new(),
269 }
270 }
271}
272
273impl<P> AppEffectPipelines<P> {
274 pub fn sync(&mut self, mut build: impl FnMut(&AppEffect) -> anyhow::Result<P>) -> bool {
276 let generation = app_effects_generation();
277 if self.generation == Some(generation) {
278 return false;
279 }
280 self.generation = Some(generation);
281 let app = app_effects();
282 let effects = app.as_deref().map(AppEffects::effects).unwrap_or_default();
283 let mut previous = std::mem::take(&mut self.slots);
284 for effect in effects {
285 let old = previous
286 .iter()
287 .position(|slot| slot.effect.name == effect.name)
288 .map(|index| previous.swap_remove(index));
289 let pipeline = match old {
290 Some(old) if old.effect == *effect => old.pipeline,
291 old => match (build(effect), old.and_then(|old| old.pipeline)) {
292 (Ok(pipeline), _) => Some(pipeline),
293 (Err(error), Some(previous)) => {
294 advisory(
295 generation,
296 format!(
297 "`--shading: {}(…)` keeps its previous shader — the new one is \
298 unusable: {error:#}",
299 effect.name
300 ),
301 );
302 Some(previous)
303 }
304 (Err(error), None) => {
305 advisory(
306 generation,
307 format!("`--shading: {}(…)` is unavailable — {error:#}", effect.name),
308 );
309 None
310 }
311 },
312 };
313 self.slots.push(AppEffectSlot {
314 effect: effect.clone(),
315 pipeline,
316 });
317 }
318 true
319 }
320
321 pub fn get(&self, index: usize) -> Option<&P> {
323 self.slots.get(index)?.pipeline.as_ref()
324 }
325
326 pub fn get_mut(&mut self, index: usize) -> Option<&mut P> {
328 self.slots.get_mut(index)?.pipeline.as_mut()
329 }
330
331 pub fn pipelines(&self) -> impl Iterator<Item = &P> {
333 self.slots.iter().filter_map(|slot| slot.pipeline.as_ref())
334 }
335}
336
337fn advisory(generation: u64, message: String) {
339 static SEEN: Mutex<(u64, Vec<String>)> = Mutex::new((0, Vec::new()));
340 let mut seen = SEEN.lock();
341 if seen.0 != generation {
342 *seen = (generation, Vec::new());
343 }
344 if seen.1.contains(&message) {
345 return;
346 }
347 log::warn!("{message}");
348 eprintln!("skathi: {message}");
349 seen.1.push(message);
350}
351
352#[cfg(test)]
353mod tests {
354 use super::*;
355
356 #[test]
357 fn the_manifest_resolves_each_effect_to_its_shader_per_target() -> Result<(), String> {
358 let app = AppEffects::new(
359 "test",
360 r#"{"schema": 10, "kind": "user", "effects": [
361 {"name": "ripple", "backdrop": true, "hlsl": "ripple.hlsl", "wgsl": "ripple.wgsl"},
362 {"name": "plain", "backdrop": false, "hlsl": "plain.hlsl"}
363 ]}"#,
364 [("ripple.wgsl".to_string(), "// ripple".to_string())],
365 )?;
366 let [ripple, plain] = app.effects() else {
367 return Err(format!("{:?}", app.effects()));
368 };
369 assert!(ripple.needs_backdrop && !plain.needs_backdrop);
370 assert_eq!(
371 ripple.wgsl,
372 AppEffectSource::Present {
373 file: "ripple.wgsl".into(),
374 text: "// ripple".into()
375 }
376 );
377 assert_eq!(ripple.hlsl, AppEffectSource::Missing("ripple.hlsl".into()));
378 assert_eq!(plain.wgsl, AppEffectSource::Unlisted);
379 Ok(())
380 }
381}