From 37993fc6b644971a8d6abac0c1bd0ed6114af621 Mon Sep 17 00:00:00 2001 From: Lawrence Date: Wed, 2 Dec 2026 22:53:56 +0000 Subject: [PATCH 01/20] fix(forge): a dialect that was not checked is not a compile error make sent every round through the repair loop when the second dialect was skipped (--no-dialect, no ANGLE, the child timing out), telling the model its working scene did not compile. --- crates/strobe-forge/src/check.rs | 48 +++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/crates/strobe-forge/src/check.rs b/crates/strobe-forge/src/check.rs index 86db2878..701604fa 100644 --- a/crates/strobe-forge/src/check.rs +++ b/crates/strobe-forge/src/check.rs @@ -235,11 +235,14 @@ impl Report { self.failures.is_empty() } - /// The compile errors, if any dialect failed. + /// The compile errors, if any dialect failed. A dialect that was not + /// checked carries its reason in `error` too ("not asked for", no + /// ANGLE), but that is a warning, not something for `make` to repair. pub(crate) fn compile_errors(&self) -> Option { let errors: Vec = self .dialects .iter() + .filter(|d| d.status == dialect::Status::Failed) .filter_map(|d| d.error.as_ref().map(|e| format!("{}: {e}", d.dialect))) .collect(); (!errors.is_empty()).then(|| errors.join("\n")) @@ -1151,6 +1154,49 @@ mod tests { use super::*; use anyhow::{anyhow, ensure}; + /// A report with these dialect results and nothing else. + fn report_with(dialects: Vec) -> Report { + Report { + scene: String::new(), + title: String::new(), + control_count: 0, + renderer: String::new(), + context: String::new(), + size: [1, 1], + compile_ms: 0.0, + dialects, + frames: Vec::new(), + timing: None, + gates: None, + controls: Vec::new(), + warnings: Vec::new(), + failures: Vec::new(), + files: Vec::new(), + } + } + + #[test] + fn a_dialect_not_checked_is_not_a_compile_error() -> Result<()> { + let skipped = report_with(vec![ + DialectResult::ok("desktop GLSL 330", "llvmpipe"), + DialectResult::not_checked("GLSL ES 3.00", "not asked for"), + ]); + ensure!( + skipped.compile_errors().is_none(), + "a skipped dialect reads as a compile error: {:?}", + skipped.compile_errors() + ); + let broken = report_with(vec![ + DialectResult::ok("desktop GLSL 330", "llvmpipe"), + DialectResult::failed("GLSL ES 3.00", "ANGLE", "0:1: syntax error".to_owned()), + ]); + let Some(errors) = broken.compile_errors() else { + return Err(anyhow!("a failed dialect gave no compile error")); + }; + ensure!(errors.contains("syntax error"), "{errors}"); + Ok(()) + } + #[test] fn frame_names_drop_a_whole_number_fraction() -> Result<()> { ensure!(frame_name(2.0) == "frame-2s.png", "{}", frame_name(2.0)); From a7b5fe37af628d4215a83a3710373c7e81bf94b8 Mon Sep 17 00:00:00 2001 From: Lawrence Date: Wed, 2 Dec 2026 22:53:56 +0000 Subject: [PATCH 02/20] fix(forge): an answer with no text is an error, not a turn to replay An empty assistant turn kept in the history made the next request fail (Anthropic refuses empty content), which ended the run with repairs unused. --- crates/strobe-forge/src/anthropic.rs | 25 +++++++++++++++++++++++++ crates/strobe-forge/src/google.rs | 22 +++++++++++++++++++++- crates/strobe-forge/src/openai.rs | 26 ++++++++++++++++++++++---- 3 files changed, 68 insertions(+), 5 deletions(-) diff --git a/crates/strobe-forge/src/anthropic.rs b/crates/strobe-forge/src/anthropic.rs index ee3a25e5..78809f00 100644 --- a/crates/strobe-forge/src/anthropic.rs +++ b/crates/strobe-forge/src/anthropic.rs @@ -158,6 +158,16 @@ pub(crate) fn read_response(status: u16, text: &str) -> Result<(Value, String)> .join("") }) .unwrap_or_default(); + if text.trim().is_empty() { + // Kept, the empty turn would make the next request a 400. + let reason = value + .get("stop_reason") + .and_then(Value::as_str) + .unwrap_or("unstated"); + return Err(anyhow!( + "the model answered with no text (stop_reason {reason})" + )); + } Ok((blocks, text)) } @@ -281,6 +291,21 @@ mod tests { r#"{"content":[{"type":"text","text":" Result { let Some(candidate) = value.pointer("/candidates/0") else { return Err(anyhow!("the API answered with no candidates")); }; - match candidate.get("finishReason").and_then(Value::as_str) { + let finish = candidate.get("finishReason").and_then(Value::as_str); + match finish { Some("MAX_TOKENS") => { return Err(anyhow!( "the answer was cut off at maxOutputTokens ({MAX_TOKENS})" @@ -156,6 +157,13 @@ pub(crate) fn read_response(status: u16, text: &str) -> Result { .join("") }) .unwrap_or_default(); + if text.trim().is_empty() { + // Kept, the empty turn would be replayed as the model's answer. + return Err(anyhow!( + "the model answered with no text (finishReason {})", + finish.unwrap_or("unstated") + )); + } Ok(text) } @@ -261,6 +269,18 @@ mod tests { "cut off", ), (200, r#"{"candidates":[]}"#, "no candidates"), + // No text at all: replaying it as the model's turn would be + // refused, so it is an error and the user turn is taken back. + ( + 200, + r#"{"candidates":[{"finishReason":"OTHER"}]}"#, + "no text", + ), + ( + 200, + r#"{"candidates":[{"content":{"parts":[{"text":"hm","thought":true}]},"finishReason":"STOP"}]}"#, + "no text", + ), ]; for (status, text, expected) in cases { let got = read_response(status, text); diff --git a/crates/strobe-forge/src/openai.rs b/crates/strobe-forge/src/openai.rs index 6d25c8cb..69723c81 100644 --- a/crates/strobe-forge/src/openai.rs +++ b/crates/strobe-forge/src/openai.rs @@ -107,7 +107,10 @@ pub(crate) fn read_response(status: u16, text: &str) -> Result { .and_then(Value::as_str) .filter(|refusal| !refusal.is_empty()) { - return Err(anyhow!("the model declined (refusal): {refusal}")); + return Err(anyhow!( + "the model declined (refusal): {}", + http::bounded(refusal) + )); } match choice.get("finish_reason").and_then(Value::as_str) { Some("length") => { @@ -122,11 +125,21 @@ pub(crate) fn read_response(status: u16, text: &str) -> Result { } Some(_) | None => {} } - Ok(choice + let text = choice .pointer("/message/content") .and_then(Value::as_str) - .unwrap_or_default() - .to_owned()) + .unwrap_or_default(); + if text.trim().is_empty() { + // Kept, the empty turn would be replayed as the assistant's answer. + return Err(anyhow!( + "the model answered with no text (finish_reason {})", + choice + .get("finish_reason") + .and_then(Value::as_str) + .unwrap_or("unstated") + )); + } + Ok(text.to_owned()) } impl Author for OpenAi { @@ -233,6 +246,11 @@ mod tests { "content filter", ), (200, r#"{"choices":[]}"#, "no choices"), + ( + 200, + r#"{"choices":[{"message":{"content":null},"finish_reason":"stop"}]}"#, + "no text", + ), (502, "bad gateway", "not JSON"), ]; for (status, text, expected) in cases { From 8ef8d6f4ad815cf359ee572ecc3f3590b570b6f7 Mon Sep 17 00:00:00 2001 From: Lawrence Date: Wed, 2 Dec 2026 22:53:56 +0000 Subject: [PATCH 03/20] fix(forge): the frozen gate counts every channel, not green alone A hue cycle with green held read as frozen and failed the check. The website's gate changes with it (D562). --- crates/strobe-forge/src/gate.rs | 34 +++++++++++++++++++++++++++++++-- site/src/lib/play/image/gate.ts | 8 +++++++- 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/crates/strobe-forge/src/gate.rs b/crates/strobe-forge/src/gate.rs index 9802cd9c..a83b9a1b 100644 --- a/crates/strobe-forge/src/gate.rs +++ b/crates/strobe-forge/src/gate.rs @@ -219,7 +219,8 @@ pub(crate) fn gate(set: &FrameSet<'_>) -> GateResult { let spread = ((luma.squared / n - f64::from(mean).powi(2)).max(0.0)).sqrt() as f32; // The most any frame differs from the first, since a loop can end where - // it began. + // it began. Each pixel counts its largest channel change, so motion in + // red and blue alone (a hue cycle with green held) is still motion. let mut change = 0.0_f32; if let Some(first) = set.frames.first() { let pixels = (first.len() / 4).max(1) as f32; @@ -229,7 +230,13 @@ pub(crate) fn gate(set: &FrameSet<'_>) -> GateResult { .0 .iter() .zip(data.as_chunks::<4>().0) - .map(|(a, b)| u64::from(a[1].abs_diff(b[1]))) + .map(|(a, b)| { + u64::from( + a[0].abs_diff(b[0]) + .max(a[1].abs_diff(b[1])) + .max(a[2].abs_diff(b[2])), + ) + }) .sum(); change = change.max(sum as f32 / 255.0 / pixels); } @@ -316,6 +323,29 @@ mod tests { Ok(()) } + #[test] + fn motion_in_red_and_blue_alone_is_not_frozen() -> Result<()> { + // A hue cycle with green held at zero: it moves, and is not black. + let frames: Vec> = (0..30) + .map(|i| { + let colour = if i % 2 == 0 { + [200, 0, 50, 255] + } else { + [50, 0, 200, 255] + }; + colour.repeat(16 * 12) + }) + .collect(); + let got = gate(&FrameSet { + width: 16, + height: 12, + rate: 30.0, + frames: &frames, + }); + ensure!(!got.frozen, "red and blue changing is motion: {got:?}"); + Ok(()) + } + #[test] fn a_slow_fade_is_not_flashing_and_moves() -> Result<()> { let frames: Vec> = (0..60).map(|i| solid(16, 12, 60 + i as u8)).collect(); diff --git a/site/src/lib/play/image/gate.ts b/site/src/lib/play/image/gate.ts index a7a018e5..4e224cfb 100644 --- a/site/src/lib/play/image/gate.ts +++ b/site/src/lib/play/image/gate.ts @@ -121,12 +121,18 @@ export function gate(set: FrameSet): GateResult { if (blown / Math.max(1, count) > 0.5) problems.push("blown out"); // The most any frame differs from the first, since a loop can end where it began. + // Each pixel counts its largest channel change, so motion in red and blue alone + // (a hue cycle with green held) is still motion. Kept in step with strobe-forge (D562). let change = 0; const first = set.frames[0]; if (first) { for (const data of set.frames) { let sum = 0; - for (let i = 0; i < first.length; i += 4) sum += Math.abs((first[i + 1] ?? 0) - (data[i + 1] ?? 0)) / 255; + for (let i = 0; i < first.length; i += 4) { + let most = 0; + for (let c = 0; c < 3; c++) most = Math.max(most, Math.abs((first[i + c] ?? 0) - (data[i + c] ?? 0))); + sum += most / 255; + } change = Math.max(change, sum / (first.length / 4)); } if (set.frames.length > 1 && change < 0.0008) problems.push("does not move"); From 8f0b4232eef9b60fbc23d2bfe1d69e69d010bc01 Mon Sep 17 00:00:00 2001 From: Lawrence Date: Wed, 2 Dec 2026 22:53:56 +0000 Subject: [PATCH 04/20] fix(forge): round 0's log no longer claims a previous scene stands --- crates/strobe-forge/src/forge.rs | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/crates/strobe-forge/src/forge.rs b/crates/strobe-forge/src/forge.rs index 4237b4be..60da8fe9 100644 --- a/crates/strobe-forge/src/forge.rs +++ b/crates/strobe-forge/src/forge.rs @@ -164,6 +164,13 @@ pub(crate) fn make( } }; let standing_passed = standing.as_ref().is_some_and(|(_, _, v)| v.passed); + // What happens to a rejected round: the previous scene stands, or, + // with none yet, there is nothing to stand. + let after = if standing.is_some() { + "so the previous scene stands; the check below is of that one." + } else { + "and there is no earlier scene to keep." + }; let note = match result { Some((candidate, verdict)) if verdict.passed || (!standing_passed && verdict.compile_error.is_none()) => @@ -172,16 +179,14 @@ pub(crate) fn make( None } Some((_, verdict)) => Some(format!( - "That revision {}, so the previous scene stands; the check below is of that one.", + "That revision {}, {after}", if verdict.compile_error.is_some() { "never compiled" } else { "fails a hard gate" } )), - None => Some( - "No answer in that round could be used, so the previous scene stands.".to_owned(), - ), + None => Some(format!("No answer in that round could be used, {after}")), }; if let Some(note) = ¬e { log.push(format!("round {round}: {note}")); @@ -490,6 +495,12 @@ mod tests { !out.join("main.glsl").exists(), "nothing written as the scene" ); + // Round 0 had no scene before it, so the log must not claim one. + let log = std::fs::read_to_string(out.join("forge-log.md"))?; + ensure!( + !log.contains("previous scene stands"), + "round 0 has no previous scene: {log}" + ); Ok(()) } } From 6a9a12c4680483d73082143c53f3affad6790dca Mon Sep 17 00:00:00 2001 From: Lawrence Date: Wed, 2 Dec 2026 22:53:56 +0000 Subject: [PATCH 05/20] fix(forge): one Markdown fence around a block's body is dropped --- crates/strobe-forge/src/reply.rs | 40 +++++++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/crates/strobe-forge/src/reply.rs b/crates/strobe-forge/src/reply.rs index 76b2d836..52611166 100644 --- a/crates/strobe-forge/src/reply.rs +++ b/crates/strobe-forge/src/reply.rs @@ -11,8 +11,9 @@ //! //! The model answers with two tagged blocks, `` and //! ``, each exactly once. Short prose around them -//! is allowed and ignored. Everything else is refused with a message the -//! next turn hands back to the model: +//! is allowed and ignored, and so is one Markdown fence wrapping a block's +//! body. Everything else is refused with a message the next turn hands +//! back to the model: //! //! - any other file, `script.js` included (the generated scene has no //! script: the model's code runs only as a shader, `docs/LLM_SHADER_CREATION.md`); @@ -73,7 +74,7 @@ pub(crate) fn parse(text: &str) -> Result { let Some(body_end) = body_start.find(CLOSE) else { return Err(format!("the block for {name} has no ")); }; - let body = body_start[..body_end].trim_matches(['\r', '\n']).to_owned(); + let body = unfence(body_start[..body_end].trim_matches(['\r', '\n'])).to_owned(); let slot = match name { "main.glsl" => &mut glsl, "scene.json" => &mut json, @@ -106,6 +107,23 @@ pub(crate) fn parse(text: &str) -> Result { Ok(Candidate { glsl, json }) } +/// `body` without one Markdown fence around it: a first line of three +/// backticks (and an optional language) and a last line of three backticks. +/// Anything else is returned as it is. +fn unfence(body: &str) -> &str { + let Some((first, inner)) = body.split_once('\n') else { + return body; + }; + if !first.trim_end().starts_with("```") { + return body; + } + let inner = inner.trim_end_matches(['\r', '\n', ' ', '\t']); + match inner.strip_suffix("```") { + Some(inner) => inner.trim_end_matches(['\r', '\n']), + None => body, + } +} + /// Checks `scene.json`'s keys and that the scene format accepts it. pub(crate) fn validate_json(json: &str) -> Result<(), String> { let value: serde_json::Value = @@ -151,6 +169,22 @@ mod tests { Ok(()) } + #[test] + fn a_markdown_fence_inside_a_block_is_dropped() -> Result<()> { + // Models often wrap code in a fence out of habit; each one would + // otherwise cost a paid repair ("```glsl" does not compile). + let plain = parse(&fixture::reply(fixture::GLSL)).map_err(|e| anyhow!(e))?; + let fenced = format!( + "\r\n```glsl\r\n{}```\r\n\n\n```json\n{}\n```\n", + fixture::GLSL, + plain.json + ); + let got = parse(&fenced).map_err(|e| anyhow!(e))?; + ensure!(got.glsl.trim() == plain.glsl.trim(), "glsl: {:?}", got.glsl); + ensure!(got.json.trim() == plain.json.trim(), "json: {:?}", got.json); + Ok(()) + } + #[test] fn malformed_replies_say_what_is_wrong() -> Result<()> { let cases = [ From 833c011168acf2d78bc90185b1474857594e61bf Mon Sep 17 00:00:00 2001 From: Lawrence Date: Wed, 2 Dec 2026 22:53:56 +0000 Subject: [PATCH 06/20] fix(forge): a provider's error and refusal text is bounded --- crates/strobe-forge/src/http.rs | 43 ++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/crates/strobe-forge/src/http.rs b/crates/strobe-forge/src/http.rs index 05b8f62d..d66fbf06 100644 --- a/crates/strobe-forge/src/http.rs +++ b/crates/strobe-forge/src/http.rs @@ -70,5 +70,46 @@ pub(crate) fn api_error(status: u16, value: &Value, kind: &str, message: &str) - .pointer(message) .and_then(Value::as_str) .unwrap_or("no message"); - anyhow!("the API refused the request ({status} {kind}): {message}") + anyhow!( + "the API refused the request ({status} {}): {}", + bounded(kind), + bounded(message) + ) +} + +/// `text` cut to a length a log line and a terminal can carry: a provider's +/// message is its own, and ureq lets a body run to 10 MB. +pub(crate) fn bounded(text: &str) -> String { + const MOST: usize = 500; + match text.char_indices().nth(MOST) { + Some((at, _)) => format!("{}… ({} bytes in all)", &text[..at], text.len()), + None => text.to_owned(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use anyhow::{Result, ensure}; + use serde_json::json; + + #[test] + fn a_provider_error_message_is_bounded() -> Result<()> { + let huge = "é".repeat(100_000); + let value = json!({ "error": { "type": huge, "message": huge } }); + let error = api_error(500, &value, "/error/type", "/error/message").to_string(); + ensure!( + error.len() < 3_000, + "the error carries {} bytes of the provider's text", + error.len() + ); + let short = api_error( + 401, + &json!({ "error": { "message": "bad key" } }), + "/t", + "/error/message", + ); + ensure!(short.to_string().ends_with("bad key"), "{short}"); + Ok(()) + } } From 233f91e1aa397aa272bc2bdfb4e6dd113a1edcf2 Mon Sep 17 00:00:00 2001 From: Lawrence Date: Wed, 2 Dec 2026 22:56:04 +0000 Subject: [PATCH 07/20] fix(shadertoy): a Shadertoy uniform the author redefines as a macro compiles `#define iTime (iTime * 0.5)` is legal on Shadertoy, where iTime is a uniform; the shim's own #define made it a macro redefinition. --- crates/strobe-shadertoy/src/convert/shim.rs | 39 +++++++++++++++++---- crates/strobe-shadertoy/tests/render.rs | 26 ++++++++++++++ 2 files changed, 58 insertions(+), 7 deletions(-) diff --git a/crates/strobe-shadertoy/src/convert/shim.rs b/crates/strobe-shadertoy/src/convert/shim.rs index 39b61130..b3f0c013 100644 --- a/crates/strobe-shadertoy/src/convert/shim.rs +++ b/crates/strobe-shadertoy/src/convert/shim.rs @@ -159,6 +159,8 @@ struct Parts { decls: String, /// `#define`s placed after the shim, before the author's code. macros: String, + /// Statements at the start of `strobe_begin()`. + begin: String, } impl Parts { @@ -172,9 +174,24 @@ impl Parts { /// the assembler moves the initialisers to the top of `main` in that /// order, D192), so the author's globals below see these values; an /// assignment in `strobe_begin` came too late and left them zero. - fn define(&mut self, name: &str, glsl: &str, value: &str) { + /// + /// When the author defines `` as a macro themselves (`#define + /// iTime (iTime * 0.5)`, legal on Shadertoy where `iTime` is a uniform), + /// a second `#define` would not compile. The author's macro body then + /// needs a variable under the bare name, so one is declared and set in + /// `strobe_begin()`. It cannot be initialised where it is declared: on + /// ES that initialiser moves into `main`, below the author's macro, + /// which would turn `iTime = ...` into `(iTime * 0.5) = ...`. So in + /// that case alone a global *the author* initialises from the name + /// reads zero, as before D415. + fn define(&mut self, name: &str, glsl: &str, value: &str, author_macros: &BTreeSet) { let _ = writeln!(self.decls, "{glsl} strobe_{name} = {value};"); - let _ = writeln!(self.macros, "#define {name} strobe_{name}"); + if author_macros.contains(name) { + let _ = writeln!(self.decls, "{glsl} {name};"); + let _ = writeln!(self.begin, " {name} = strobe_{name};"); + } else { + let _ = writeln!(self.macros, "#define {name} strobe_{name}"); + } } } @@ -227,13 +244,18 @@ pub(super) fn pass_file(plan: &Plan, pass: &PlannedPass, shader: &Shader) -> Gen .push_str("vec4 strobe_clock = texelFetch(st_clock, ivec2(0, 0), 0);\n"); } if used("iResolution") { - parts.define("iResolution", "vec3", "vec3(RENDERSIZE, 1.0)"); + parts.define("iResolution", "vec3", "vec3(RENDERSIZE, 1.0)", &pass.macros); } if used("iTime") { - parts.define("iTime", "float", "strobe_clock.x"); + parts.define("iTime", "float", "strobe_clock.x", &pass.macros); } if used("iTimeDelta") { - parts.define("iTimeDelta", "float", "strobe_clock.z * strobe_rate()"); + parts.define( + "iTimeDelta", + "float", + "strobe_clock.z * strobe_rate()", + &pass.macros, + ); } if used("iFrame") { parts @@ -243,6 +265,7 @@ pub(super) fn pass_file(plan: &Plan, pass: &PlannedPass, shader: &Shader) -> Gen "iFrame", "int", "int(max(FRAMECOUNT - (strobe_frame - 1.0), 0.0) + 0.5)", + &pass.macros, ); } if used("iFrameRate") { @@ -250,13 +273,14 @@ pub(super) fn pass_file(plan: &Plan, pass: &PlannedPass, shader: &Shader) -> Gen "iFrameRate", "float", "(strobe_clock.z > 0.0 ? 1.0 / strobe_clock.z : 60.0)", + &pass.macros, ); } if used("iMouse") { - parts.define("iMouse", "vec4", "_mouse"); + parts.define("iMouse", "vec4", "_mouse", &pass.macros); } if used("iDate") { - parts.define("iDate", "vec4", "strobe_Date"); + parts.define("iDate", "vec4", "strobe_Date", &pass.macros); } if used("iSampleRate") { parts.macros.push_str("#define iSampleRate 44100.0\n"); @@ -362,6 +386,7 @@ pub(super) fn pass_file(plan: &Plan, pass: &PlannedPass, shader: &Shader) -> Gen ); } body.push_str("void strobe_begin() {\n"); + body.push_str(&parts.begin); if image { body.push_str( " strobe_fragCoord = (gl_FragCoord.xy - 0.5 * RENDERSIZE) / st_zoom + 0.5 * RENDERSIZE;\n", diff --git a/crates/strobe-shadertoy/tests/render.rs b/crates/strobe-shadertoy/tests/render.rs index 6aa8f498..ef79d20e 100644 --- a/crates/strobe-shadertoy/tests/render.rs +++ b/crates/strobe-shadertoy/tests/render.rs @@ -939,3 +939,29 @@ fn a_global_initialised_from_a_channel_array_sees_its_value() -> Result<()> { } Ok(()) } + +#[test] +fn a_shadertoy_uniform_the_author_redefines_as_a_macro_still_works() -> Result<()> { + // On Shadertoy `iTime` is a real uniform, so `#define iTime (iTime*0.5)` + // is legal and common (slow the whole shader down). The shim's own + // `#define iTime strobe_iTime` made it a macro redefinition, which does + // not compile. + let code = "#define iTime (iTime * 0.5)\n\ + #define iResolution (iResolution * 1.0)\n\ + void mainImage(out vec4 c, in vec2 p) {\n\ + \x20 c = vec4(iTime, p.x / iResolution.x, 0.0, 1.0);\n\ + }"; + let (_, scene) = import_text(&inline(code), "uniform-macro")?; + for api in BOTH { + // 31 frames: the last has TIME 0.5, so the slowed iTime is 0.25. + let Some(frame) = render(api, &scene, 31, full_precision(), |_, _| Ok(()))? else { + continue; + }; + let [r, g, _, _] = frame.center(); + assert!( + near(r, 64) && near(g, 128), + "{api:?}: iTime 0.25 -> 64, x fraction 0.5 -> 128; got ({r}, {g})" + ); + } + Ok(()) +} From db17a4b4a09b1634548c4d6f1a71fe271e70cb8d Mon Sep 17 00:00:00 2001 From: Lawrence Date: Wed, 2 Dec 2026 22:56:50 +0000 Subject: [PATCH 08/20] fix(shadertoy): gl_FragColor in code that never runs no longer blackens a pass Any mention of gl_FragColor (an #if 0 block, an unused helper) made the pass return the legacy variable, which stayed black when only mainImage's output was written. --- crates/strobe-shadertoy/src/convert/shim.rs | 19 ++++++++--- crates/strobe-shadertoy/tests/convert.rs | 6 ++-- .../tests/golden/legacy/main.glsl | 4 +-- crates/strobe-shadertoy/tests/render.rs | 34 +++++++++++++++++++ 4 files changed, 54 insertions(+), 9 deletions(-) diff --git a/crates/strobe-shadertoy/src/convert/shim.rs b/crates/strobe-shadertoy/src/convert/shim.rs index b3f0c013..64a3b9c5 100644 --- a/crates/strobe-shadertoy/src/convert/shim.rs +++ b/crates/strobe-shadertoy/src/convert/shim.rs @@ -195,6 +195,9 @@ impl Parts { } } +/// What the legacy `gl_FragColor` holds until the shader writes it. +const LEGACY_UNSET: &str = "-65504.0"; + /// Lines in the file header. const HEADER_LINES: u32 = 3; @@ -335,10 +338,16 @@ pub(super) fn pass_file(plan: &Plan, pass: &PlannedPass, shader: &Shader) -> Gen ); } } + // The legacy output starts at a value no shader writes (the most + // negative half float, so it survives mediump), and `renderMain` uses + // `mainImage`'s output while it is still there: a mention of + // `gl_FragColor` in code that never runs (an `#if 0` block, an unused + // helper) must not turn the pass black. if pass.legacy_frag_color { - parts - .decls - .push_str("vec4 strobe_gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n"); + let _ = writeln!( + parts.decls, + "vec4 strobe_gl_FragColor = vec4({LEGACY_UNSET});" + ); } // Names the author declares that the assembler already did. @@ -462,9 +471,9 @@ pub(super) fn pass_file(plan: &Plan, pass: &PlannedPass, shader: &Shader) -> Gen out.push_str(&code); let _ = writeln!(out, "{}", super::ENTRY_MARKER); let result = if pass.legacy_frag_color { - "strobe_gl_FragColor" + format!("strobe_gl_FragColor.x == {LEGACY_UNSET} ? strobe_color : strobe_gl_FragColor") } else { - "strobe_color" + "strobe_color".to_owned() }; let _ = write!( out, diff --git a/crates/strobe-shadertoy/tests/convert.rs b/crates/strobe-shadertoy/tests/convert.rs index 39a69dfc..b0060390 100644 --- a/crates/strobe-shadertoy/tests/convert.rs +++ b/crates/strobe-shadertoy/tests/convert.rs @@ -311,8 +311,10 @@ fn legacy_source_is_normalised_and_reported() -> Result<()> { "gl_FragColor renamed" ); assert!( - image.contains("return strobe_end(strobe_gl_FragColor)"), - "and returned" + image.contains( + "return strobe_end(strobe_gl_FragColor.x == -65504.0 ? strobe_color : strobe_gl_FragColor)" + ), + "and returned once written" ); assert!( buffer.contains("#ifdef GL_ES\n#define tanh strobe_user_tanh\n#endif"), diff --git a/crates/strobe-shadertoy/tests/golden/legacy/main.glsl b/crates/strobe-shadertoy/tests/golden/legacy/main.glsl index dc71a670..eed34e55 100644 --- a/crates/strobe-shadertoy/tests/golden/legacy/main.glsl +++ b/crates/strobe-shadertoy/tests/golden/legacy/main.glsl @@ -3,7 +3,7 @@ // Tab line 1 is file line 19 for Image. vec2 strobe_fragCoord = vec2(0.0); vec3 strobe_iResolution = vec3(RENDERSIZE, 1.0); -vec4 strobe_gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); +vec4 strobe_gl_FragColor = vec4(-65504.0); void strobe_begin() { strobe_fragCoord = (gl_FragCoord.xy - 0.5 * RENDERSIZE) / st_zoom + 0.5 * RENDERSIZE; } @@ -29,5 +29,5 @@ vec4 renderMain() { vec4 strobe_color = vec4(0.0, 0.0, 0.0, 1.0); strobe_begin(); mainImage(strobe_color, strobe_fragCoord); - return strobe_end(strobe_gl_FragColor); + return strobe_end(strobe_gl_FragColor.x == -65504.0 ? strobe_color : strobe_gl_FragColor); } diff --git a/crates/strobe-shadertoy/tests/render.rs b/crates/strobe-shadertoy/tests/render.rs index ef79d20e..d63ea98e 100644 --- a/crates/strobe-shadertoy/tests/render.rs +++ b/crates/strobe-shadertoy/tests/render.rs @@ -965,3 +965,37 @@ fn a_shadertoy_uniform_the_author_redefines_as_a_macro_still_works() -> Result<( } Ok(()) } + +#[test] +fn gl_fragcolor_in_code_that_never_runs_does_not_blacken_the_pass() -> Result<()> { + // Any mention of gl_FragColor made renderMain return the legacy + // variable, which stayed black when only `mainImage`'s output was + // written: here the mention sits in an `#if 0` block. + let code = "void mainImage(out vec4 c, in vec2 p) { c = vec4(1.0, 0.0, 0.0, 1.0); }\n\ + #if 0\n\ + void legacy() { gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0); }\n\ + #endif\n"; + let (_, scene) = import_text(&inline(code), "dead-gl-fragcolor")?; + for api in BOTH { + let Some(frame) = render(api, &scene, 1, Options::default(), |_, _| Ok(()))? else { + continue; + }; + let [r, g, _, _] = frame.center(); + assert!( + r == 255 && g == 0, + "{api:?}: mainImage's red must show; got ({r}, {g})" + ); + } + // A legacy shader that writes gl_FragColor itself still shows it. + let (_, scene) = import("legacy")?; + for api in BOTH { + let Some(frame) = render(api, &scene, 12, Options::default(), |_, _| Ok(()))? else { + continue; + }; + assert!( + frame.lit_fraction() > 0.9, + "{api:?}: the legacy fixture still draws" + ); + } + Ok(()) +} From cea9485da2885abbc45dcbad77ab0417f4e6d1af Mon Sep 17 00:00:00 2001 From: Lawrence Date: Wed, 2 Dec 2026 22:57:24 +0000 Subject: [PATCH 09/20] fix(shadertoy): the generated keyboard image is not counted as a found texture --- crates/strobe-shadertoy/src/convert/mod.rs | 7 +++++ crates/strobe-shadertoy/src/import.rs | 35 ++++++++++++++++------ 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/crates/strobe-shadertoy/src/convert/mod.rs b/crates/strobe-shadertoy/src/convert/mod.rs index 6da1be69..72839872 100644 --- a/crates/strobe-shadertoy/src/convert/mod.rs +++ b/crates/strobe-shadertoy/src/convert/mod.rs @@ -374,6 +374,13 @@ pub enum ConvertError { InvalidScene(#[from] strobe_scene::SceneError), } +/// Whether `file`, a name under `images/`, is one the converter writes +/// itself (the black placeholder, the keyboard image, the pending list) +/// rather than a texture the shader brought. +pub(crate) fn is_generated_image(file: &str) -> bool { + names::is_generated_image(file) +} + /// Converts `shader`. See the module docs for what comes out. pub fn convert(shader: &Shader, options: &Options) -> Result { let plan = plan::build(shader, options)?; diff --git a/crates/strobe-shadertoy/src/import.rs b/crates/strobe-shadertoy/src/import.rs index f7e4dc05..a9425c10 100644 --- a/crates/strobe-shadertoy/src/import.rs +++ b/crates/strobe-shadertoy/src/import.rs @@ -256,18 +256,16 @@ pub fn import_json(text: &str, options: &ImportOptions<'_>) -> Result Result<()> { + let library = scratch("keyboard")?; + let done = import_json( + include_str!("../tests/fixtures/keyboard.json"), + &ImportOptions::offline(&library), + )?; + assert!( + done.dir.join("images/st_keyboard.png").is_file(), + "the keyboard image is written" + ); + assert_eq!( + done.textures_found, 0, + "st_keyboard.png is generated, not a texture the shader brought" + ); + std::fs::remove_dir_all(&library)?; + Ok(()) + } + #[test] fn a_second_import_asks_and_replace_swaps_it() -> Result<()> { let library = scratch("again")?; From 3ba2d408fbcc17763577b65b717fee400b46b31e Mon Sep 17 00:00:00 2001 From: Lawrence Date: Wed, 2 Dec 2026 22:58:04 +0000 Subject: [PATCH 10/20] fix(shadertoy): a shader URL with a port is still a shadertoy.com address --- crates/strobe-shadertoy/src/id.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/strobe-shadertoy/src/id.rs b/crates/strobe-shadertoy/src/id.rs index 5ff25b3a..4324654b 100644 --- a/crates/strobe-shadertoy/src/id.rs +++ b/crates/strobe-shadertoy/src/id.rs @@ -76,7 +76,15 @@ impl ShaderId { let mut parts = path.split('/'); let host = parts.next().unwrap_or_default(); - if !HOSTS.contains(&host.to_ascii_lowercase().as_str()) { + // A port (`www.shadertoy.com:443`) is still that host; only digits + // are dropped, so `shadertoy.com:x` stays a wrong host. + let bare_host = match host.rsplit_once(':') { + Some((name, port)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => { + name + } + Some(_) | None => host, + }; + if !HOSTS.contains(&bare_host.to_ascii_lowercase().as_str()) { return Err(IdError::WrongHost(host.to_string())); } let segments: Vec<&str> = parts.filter(|part| !part.is_empty()).collect(); @@ -136,6 +144,8 @@ mod tests { "https://www.shadertoy.com/view/XsXXDn/", "//www.shadertoy.com/view/XsXXDn", "https://www.shadertoy.com/api/v1/shaders/XsXXDn?key=abc", + "https://www.shadertoy.com:443/view/XsXXDn", + "http://shadertoy.com:80/view/XsXXDn", ] { let id = ShaderId::parse(text)?; assert_eq!(id.as_str(), "XsXXDn", "`{text}`"); @@ -165,6 +175,14 @@ mod tests { "https://example.com/view/XsXXDn", IdError::WrongHost("example.com".to_string()), ), + ( + "https://shadertoy.com:x/view/XsXXDn", + IdError::WrongHost("shadertoy.com:x".to_string()), + ), + ( + "https://example.com:443/view/XsXXDn", + IdError::WrongHost("example.com:443".to_string()), + ), ( "https://www.shadertoy.com/browse", IdError::NotAShaderPage("https://www.shadertoy.com/browse".to_string()), From fd775dcb7ed4545deb33ce56d5c8ecea62b1c853 Mon Sep 17 00:00:00 2001 From: Lawrence Date: Wed, 2 Dec 2026 22:58:04 +0000 Subject: [PATCH 11/20] docs(shadertoy): the invalid-key message names every character a key may hold --- crates/strobe-shadertoy/src/acquire/key.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/strobe-shadertoy/src/acquire/key.rs b/crates/strobe-shadertoy/src/acquire/key.rs index 5f172268..61d6ff2f 100644 --- a/crates/strobe-shadertoy/src/acquire/key.rs +++ b/crates/strobe-shadertoy/src/acquire/key.rs @@ -54,8 +54,8 @@ pub enum KeyError { }, /// A key was found but it is not a plausible key. #[error( - "the Shadertoy API key from {source_name} is not valid (expected letters and digits, \ - up to {MAX_KEY_LEN} characters)" + "the Shadertoy API key from {source_name} is not valid (expected letters, digits, \ + `_` and `-`, up to {MAX_KEY_LEN} characters)" )] Invalid { /// `STROBE_SHADERTOY_KEY` or the file path. From dfb564695dd46b58a270048882a9cd2eadbb562d Mon Sep 17 00:00:00 2001 From: Lawrence Date: Wed, 2 Dec 2026 22:59:16 +0000 Subject: [PATCH 12/20] fix(shadertoy): the listener bounds the whole request, not each read A local client sending a byte every few seconds stayed inside the per-read timeout and could hold a connection slot for hours; four of them made the listener answer every import with 503. --- crates/strobe-shadertoy/src/listener/mod.rs | 37 ++++++++++++++-- crates/strobe-shadertoy/tests/listener.rs | 47 +++++++++++++++++++++ 2 files changed, 80 insertions(+), 4 deletions(-) diff --git a/crates/strobe-shadertoy/src/listener/mod.rs b/crates/strobe-shadertoy/src/listener/mod.rs index 155bf6a7..a8c7654c 100644 --- a/crates/strobe-shadertoy/src/listener/mod.rs +++ b/crates/strobe-shadertoy/src/listener/mod.rs @@ -47,8 +47,9 @@ //! business (it parses and validates again). //! //! Connections are served on short-lived threads, at most -//! [`MAX_CONNECTIONS`] at once, each with read and write timeouts, so a -//! stalled client cannot hold the listener. +//! [`MAX_CONNECTIONS`] at once, each with read and write timeouts and a +//! deadline for the whole request, so neither a stalled client nor one +//! trickling a byte at a time can hold the listener. //! //! The listener never imports anything itself. It calls the [`Handler`] it //! was given, which in the app queues the job on the import worker and @@ -66,7 +67,7 @@ use std::net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::thread::JoinHandle; -use std::time::Duration; +use std::time::{Duration, Instant}; use wire::{HeadError, drain, read_head, respond}; /// The default port (PLAN section 6.1). @@ -187,8 +188,11 @@ pub struct ListenerConfig { pub token: Token, /// The body cap. pub max_body: usize, - /// Read and write timeout per connection. + /// Read and write timeout per connection: how long one read may wait. pub io_timeout: Duration, + /// How long the whole request (head and body) may take to arrive, so a + /// client trickling a byte per read cannot hold a connection slot. + pub request_deadline: Duration, } impl ListenerConfig { @@ -199,6 +203,7 @@ impl ListenerConfig { token, max_body: MAX_BODY, io_timeout: Duration::from_secs(10), + request_deadline: Duration::from_secs(30), } } } @@ -387,6 +392,11 @@ fn serve(mut stream: TcpStream, shared: &Shared) { /// Reads, authorises and validates one request, and runs the handler. fn handle(stream: &mut TcpStream, shared: &Shared) -> Result { let config = &shared.config; + let mut stream = Deadline { + inner: stream, + until: Instant::now() + config.request_deadline, + }; + let stream = &mut stream; let head = match read_head(stream) { Ok(head) => head, Err(HeadError::Closed) => return Err(silent()), @@ -472,6 +482,25 @@ fn silent() -> Rejection { Rejection::new(400, "empty request") } +/// A reader that refuses to read past `until`. Each read on the socket +/// is already bounded by the read timeout; this bounds them all together. +struct Deadline<'a, R> { + inner: &'a mut R, + until: Instant, +} + +impl std::io::Read for Deadline<'_, R> { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if Instant::now() >= self.until { + return Err(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "the request took too long to arrive", + )); + } + self.inner.read(buf) + } +} + /// The `length` body bytes: those already read, then the rest. fn read_body( stream: &mut impl std::io::Read, diff --git a/crates/strobe-shadertoy/tests/listener.rs b/crates/strobe-shadertoy/tests/listener.rs index d4331dbd..0c2e1d2a 100644 --- a/crates/strobe-shadertoy/tests/listener.rs +++ b/crates/strobe-shadertoy/tests/listener.rs @@ -519,3 +519,50 @@ fn a_stalled_client_does_not_block_others() -> Result<()> { assert_eq!(answer.status, 200, "{answer:?}"); Ok(()) } + +#[test] +fn a_client_trickling_its_request_is_cut_off() -> Result<()> { + // Each read finishes inside the per-read timeout, so only a deadline + // on the whole request stops a local process that sends a byte every + // few hundred milliseconds from holding a connection slot for hours. + let token = Token::generate()?; + let mut config = ListenerConfig::new(0, token); + config.io_timeout = Duration::from_secs(1); + config.request_deadline = Duration::from_secs(2); + let listener = Listener::start(config, Arc::new(|_| imported()))?; + let mut trickle = TcpStream::connect(listener.addr())?; + trickle.set_read_timeout(Some(Duration::from_millis(300)))?; + trickle.write_all(b"POST /import HTTP/1.1\r\nX-Pad: ")?; + let started = std::time::Instant::now(); + let mut answer = Vec::new(); + while started.elapsed() < Duration::from_secs(10) { + if trickle.write_all(b"a").is_err() { + break; + } + let mut chunk = [0_u8; 512]; + match trickle.read(&mut chunk) { + Ok(0) => break, + Ok(n) => { + answer.extend_from_slice(chunk.get(..n).unwrap_or_default()); + break; + } + Err(e) + if matches!( + e.kind(), + std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut + ) => {} + Err(_) => break, + } + } + let waited = started.elapsed(); + assert!( + waited < Duration::from_secs(6), + "the trickling client held its connection for {waited:?}" + ); + let text = String::from_utf8_lossy(&answer); + assert!( + answer.is_empty() || text.starts_with("HTTP/1.1 400"), + "a cut-off request is refused: {text}" + ); + Ok(()) +} From c36b3bcef45777967640218443f2715e53a3a217 Mon Sep 17 00:00:00 2001 From: Lawrence Date: Wed, 2 Dec 2026 23:01:14 +0000 Subject: [PATCH 13/20] fix(autocontrol): a name that bounds any array-indexing loop is never a control --- crates/strobe-autocontrol/src/analyze/mod.rs | 34 ++++++++++++++++++-- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/strobe-autocontrol/src/analyze/mod.rs b/crates/strobe-autocontrol/src/analyze/mod.rs index 78a958e7..a609b3b6 100644 --- a/crates/strobe-autocontrol/src/analyze/mod.rs +++ b/crates/strobe-autocontrol/src/analyze/mod.rs @@ -146,14 +146,20 @@ fn file_hits(scan: &Scan<'_>) -> Vec { let loops = expr::loops(scan); let mut hits: Vec = Vec::new(); - // Loop bounds, literal or named. + // Loop bounds, literal or named. A name that bounds a loop indexing an + // array with its variable is never a candidate, whatever other loops it + // bounds: raising it would read past the array, as with a literal bound. for found in &loops { if let Some(hit) = expr::loop_hit(scan, found) { hits.push(hit); - } else if scan.is_any_ident(found.bound) && !found.indexes_with_var { + } else if scan.is_any_ident(found.bound) { let name = scan.t(found.bound); for constant in named.iter_mut().filter(|n| n.name == name) { - constant.loop_bound = true; + if found.indexes_with_var { + constant.safe = false; + } else { + constant.loop_bound = true; + } } } } @@ -494,6 +500,28 @@ vec4 renderMain() { Ok(()) } + #[test] + fn a_name_that_bounds_any_array_indexing_loop_is_never_a_candidate() -> Result<()> { + // The second loop alone would make N a count; the first indexes + // `w` with its variable, so raising N would read past the array. + let code = "\ +#define N 8 +vec4 renderMain() { + float w[8]; + float a = 0.0; + for (int i = 0; i < N; i++) { w[i] = float(i); } + for (int j = 0; j < N; j++) { a += 0.01; } + return vec4(a + w[3]); +} +"; + let got = summary(&analyse_one(code)?); + assert!( + got.iter().all(|(_, name, _)| name != "n"), + "N bounds a loop that indexes an array: {got:?}" + ); + Ok(()) + } + #[test] fn repeated_time_scales_and_colours_are_one_candidate_with_two_sites() -> Result<()> { let code = "\ From afe342e3af24fdd0aa4375555c5de77cd1816c43 Mon Sep 17 00:00:00 2001 From: Lawrence Date: Wed, 2 Dec 2026 23:03:32 +0000 Subject: [PATCH 14/20] fix(autocontrol): a reviewed range keeps the loop cap and holds the default rewrite_chosen wrote any min < max it was given, so a loop count could be dragged past LOOP_CAP (the iGPU hang guard) or below one iteration, and a range that left out the default had the scene clamp it. --- crates/strobe-autocontrol/src/generate.rs | 34 ++++++++++++--- crates/strobe-autocontrol/tests/engine.rs | 50 +++++++++++++++++++++++ 2 files changed, 78 insertions(+), 6 deletions(-) diff --git a/crates/strobe-autocontrol/src/generate.rs b/crates/strobe-autocontrol/src/generate.rs index e5877680..1b6e3c08 100644 --- a/crates/strobe-autocontrol/src/generate.rs +++ b/crates/strobe-autocontrol/src/generate.rs @@ -38,7 +38,7 @@ //! made belongs to a value it holds. use crate::analyze::{Analysis, analyze}; -use crate::candidate::{Candidate, Group, Kind, ValueType}; +use crate::candidate::{Candidate, Group, Kind, LOOP_CAP, ValueType}; use crate::naming::{Taken, assign, assign_with_roles}; use crate::report::{CandidateReport, Report, ReportOptions, Verdict, round5}; use crate::rewrite::{self, AudioBind, PlannedControl}; @@ -186,14 +186,36 @@ pub enum ChoiceError { Generate(#[from] GenerateError), } +/// The range a review asked for, made safe to write: `None` (keep the +/// measured range) for a colour or a range that is empty or not finite. +/// It always holds the default, the value that was verified, and a loop +/// count stays between one iteration and [`LOOP_CAP`] (or its own +/// default, when that is higher): a slider must not be able to hang a +/// 2012 integrated GPU, whoever drew the range. +fn reviewed_range(candidate: &Candidate, min: f32, max: f32) -> Option<(f32, f32)> { + let default = candidate.default.first().copied()?; + if !(min.is_finite() && max.is_finite() && min < max) { + return None; + } + let (min, max) = (min.min(default), max.max(default)); + match candidate.value_type { + ValueType::Colour => None, + ValueType::Float => Some((min, max)), + ValueType::Int | ValueType::Count => { + Some((min.max(1.0).min(default), max.min(LOOP_CAP.max(default)))) + } + } +} + /// `folder` rewritten with exactly `choices` as its new controls, listed by /// group in the order given, with each slider's range as chosen. No GL and /// no scoring: the candidates were measured already, and the analysis is a /// pure function of the code, so it finds them again by `id`. A choice /// whose candidate no longer reads as it did is refused, not guessed at. /// The result's report carries no fidelity; the default of every kept -/// control is still the original literal, so the picture at defaults is the -/// one [`generate`] verified. +/// control is still the original literal, and each range is widened to +/// hold it, so the picture at defaults is the one +/// [`generate`] verified. pub fn rewrite_chosen(folder: &SceneFolder, choices: &[Choice]) -> Result { let sources = Sources::from_folder(folder); let candidates = analyze(&sources).candidates; @@ -239,9 +261,9 @@ pub fn rewrite_chosen(folder: &SceneFolder, choices: &[Choice]) -> Result Result<()> { ); Ok(()) } + +#[test] +fn a_reviewed_loop_range_keeps_the_hang_cap_and_the_default() -> Result<()> { + // A reviewer (or a page passing JSON through) can ask for any range; + // a loop count must still never pass LOOP_CAP, never drop below one + // iteration, and the range must hold the verified default. + let (name, path) = fixtures()? + .into_iter() + .find(|(name, _)| name == "march_field") + .ok_or_else(|| anyhow!("march_field fixture"))?; + let folder = import(&name, &path)?; + let candidates = strobe_autocontrol::analyze(&Sources::from_folder(&folder)).candidates; + let lp = candidates + .iter() + .find(|c| { + matches!( + c.value_type, + strobe_autocontrol::ValueType::Int | strobe_autocontrol::ValueType::Count + ) + }) + .ok_or_else(|| anyhow!("march_field has no loop count candidate"))?; + let default = lp.default.first().copied().unwrap_or(0.0); + let cap = strobe_autocontrol::candidate::LOOP_CAP.max(default); + for (min, max) in [(-5.0, 1.0e6), (default * 3.0, default * 4.0)] { + let choices = [Choice { + candidate: lp.id, + name: "march_steps".to_string(), + context: lp.context.clone(), + min, + max, + }]; + let reviewed = rewrite_chosen(&folder, &choices)?; + let line = reviewed + .control_lines + .first() + .ok_or_else(|| anyhow!("no control line"))?; + let value: serde_json::Value = serde_json::from_str(line.trim().trim_end_matches(','))?; + let got_min = value["MIN"].as_f64().unwrap_or(f64::NAN) as f32; + let got_max = value["MAX"].as_f64().unwrap_or(f64::NAN) as f32; + assert!( + got_max <= cap && got_min >= 1.0, + "asked {min}..{max}: {got_min}..{got_max} must stay inside 1..{cap}" + ); + assert!( + (got_min..=got_max).contains(&default), + "asked {min}..{max}: {got_min}..{got_max} must hold the default {default}" + ); + } + Ok(()) +} From 3bec26c6edc122b2347039d299423c06bf1898d6 Mon Sep 17 00:00:00 2001 From: Lawrence Date: Wed, 2 Dec 2026 23:05:33 +0000 Subject: [PATCH 15/20] fix(autocontrol): a loop bound that is not a whole number is not a count floor(n + 0.5) moved a bound like 6.2832 or 10.5 at its default, so the control started on a different picture (a gap in a ring, an extra step). --- crates/strobe-autocontrol/src/analyze/expr.rs | 8 +++++- crates/strobe-autocontrol/src/analyze/mod.rs | 25 ++++++++++++++++++- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/strobe-autocontrol/src/analyze/expr.rs b/crates/strobe-autocontrol/src/analyze/expr.rs index f473ad1f..6197b89c 100644 --- a/crates/strobe-autocontrol/src/analyze/expr.rs +++ b/crates/strobe-autocontrol/src/analyze/expr.rs @@ -209,7 +209,9 @@ pub(super) fn loop_hit(scan: &Scan<'_>, found: &Loop) -> Option { return None; } let num = parse_number(scan.t(bound))?; - if !(4.0..=4096.0).contains(&num.value) { + // A count is a whole number: `floor(n + 0.5)` would move a bound like + // `6.2832` at its default, changing the picture the control starts at. + if !(4.0..=4096.0).contains(&num.value) || num.value.fract() != 0.0 { return None; } let (start, end) = (scan.start(bound), scan.end(bound)); @@ -1066,6 +1068,10 @@ mod tests { "for (int i = 0; i < n; i++) { x += 1.0; }", "for (int i = 64; i > 0; i--) { x += 1.0; }", "for (int i = 0; j < 64; i++) { x += 1.0; }", + // Not a count: rounding the bound changes the loop at its + // default (6.2832 becomes 6.0, a gap in the ring). + "for (float a = 0.0; a < 6.2832; a += 0.1) { x += a; }", + "for (float d = 0.0; d < 10.5; d += 0.5) { x += d; }", ] { let code = in_main(body); let scan = Scan::new("f.glsl", &code); diff --git a/crates/strobe-autocontrol/src/analyze/mod.rs b/crates/strobe-autocontrol/src/analyze/mod.rs index a609b3b6..dead0483 100644 --- a/crates/strobe-autocontrol/src/analyze/mod.rs +++ b/crates/strobe-autocontrol/src/analyze/mod.rs @@ -236,7 +236,8 @@ fn named_hit(named: &consts::Named) -> Option { return None; } let loop_count = named.loop_bound; - if loop_count && !(4.0..=4096.0).contains(&named.value) { + // A count is a whole number (see `expr::loop_hit`). + if loop_count && (!(4.0..=4096.0).contains(&named.value) || named.value.fract() != 0.0) { return None; } let name = readable(&named.name); @@ -500,6 +501,28 @@ vec4 renderMain() { Ok(()) } + #[test] + fn a_named_bound_that_is_not_a_whole_number_is_not_a_count() -> Result<()> { + let code = "\ +#define REACH 10.5 +vec4 renderMain() { + float a = 0.0; + for (float t = 0.0; t < REACH; t += 0.5) { a += 0.01; } + return vec4(a); +} +"; + let analysis = analyse_one(code)?; + assert!( + analysis + .candidates + .iter() + .all(|c| !matches!(c.value_type, ValueType::Count | ValueType::Int)), + "REACH is not a count of iterations: {:?}", + summary(&analysis) + ); + Ok(()) + } + #[test] fn a_name_that_bounds_any_array_indexing_loop_is_never_a_candidate() -> Result<()> { // The second loop alone would make N a count; the first indexes From 27899f2fe846240727d90f9bcad1761c73379f34 Mon Sep 17 00:00:00 2001 From: Lawrence Date: Wed, 2 Dec 2026 23:05:59 +0000 Subject: [PATCH 16/20] fix(autocontrol): a time factor too large to range is not a speed control TIME * 2e38 or TIME / 1e-39 wrote an infinite MAX into scene.json, which failed the whole generation instead of dropping one candidate. --- crates/strobe-autocontrol/src/analyze/expr.rs | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/crates/strobe-autocontrol/src/analyze/expr.rs b/crates/strobe-autocontrol/src/analyze/expr.rs index 6197b89c..23920ac1 100644 --- a/crates/strobe-autocontrol/src/analyze/expr.rs +++ b/crates/strobe-autocontrol/src/analyze/expr.rs @@ -202,6 +202,13 @@ fn loop_name(scan: &Scan<'_>, found: &Loop) -> String { } } +/// Whether `speed`, a time multiplier, can be a slider: finite, and small +/// enough that its range (up to twice it) and the scene's JSON stay +/// finite. The same bound as [`scale_value_ok`]'s. +fn speed_ok(speed: f32) -> bool { + speed.is_finite() && speed.abs() < 1e5 +} + /// The hit for a literal loop bound. pub(super) fn loop_hit(scan: &Scan<'_>, found: &Loop) -> Option { let bound = found.bound; @@ -350,6 +357,9 @@ pub(super) fn time_scales(scan: &Scan<'_>, named: &[Named]) -> Vec<(Hit, Option< f.value = 1.0 / f.value; f.text = format!("/{}", f.text); } + if !speed_ok(f.value) { + continue; + } let (start, end) = (scan.start(first), scan.end(last)); found.push(( Hit { @@ -937,6 +947,9 @@ pub(super) fn define_time_scales(scan: &Scan<'_>) -> Vec { } else { value.value as f32 }; + if !speed_ok(value) { + continue; + } let name = specific(macro_name).map_or_else( || "speed".to_string(), |name| { @@ -1018,6 +1031,10 @@ mod tests { "float a = TIME + 0.3;", "float a = foo.TIME * 0.3;", "float a = TIME * x;", + // Out of range: 2x the factor (the slider's max) or 1/factor is + // not finite, and an `inf` in scene.json fails the whole scene. + "float a = TIME * 2e38;", + "float a = TIME / 1e-39;", ] { assert!( time_literals(&in_main(body)).is_empty(), @@ -1381,6 +1398,11 @@ float glow(vec2 p) { float v = 0.0; for (int i = 0; i < 9; i++) { v += 0.1; } re .is_empty(), "a parameter called TIME" ); + assert!( + found("#define T (TIME / 1e-39)\nvec4 renderMain() { return vec4(sin(T)); }\n") + .is_empty(), + "a speed that is not finite" + ); } #[test] From 4a0adeadd47636608d9da238a9d07eb1e2f195d5 Mon Sep 17 00:00:00 2001 From: Lawrence Date: Wed, 2 Dec 2026 23:07:54 +0000 Subject: [PATCH 17/20] fix(autocontrol): a constant used anywhere outside a function body is unsafe A use inside parentheses at global scope (float g = sqrt(S);) or a parameter of the same name (float f(float K)) was offered as safe, and its rewrite cannot compile. --- crates/strobe-autocontrol/src/analyze/consts.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/strobe-autocontrol/src/analyze/consts.rs b/crates/strobe-autocontrol/src/analyze/consts.rs index 44962ee0..2c9c7c42 100644 --- a/crates/strobe-autocontrol/src/analyze/consts.rs +++ b/crates/strobe-autocontrol/src/analyze/consts.rs @@ -459,7 +459,11 @@ fn examine_uses(scan: &Scan<'_>, named: &Named) -> (usize, bool) { // define's name token is inside the directive token and is never // visited, so every hit here is a real use. uses += 1; - let global = scan.brace_depth(i) == 0 && scan.paren_depth(i) == 0; + // Anything outside a function body: a global initialiser, inside a + // call or not (`float g = sqrt(S);`), or a parameter list, where + // the name can only be a parameter's own (`float f(float K)`), + // which a pasted `(k)` would break. + let global = scan.brace_depth(i) == 0; let array_size = (i > 0 && scan.is(i - 1, "[")) || scan.is(i + 1, "]"); let case_label = i > 0 && scan.is_ident(i - 1, "case"); let in_const = scan.is_ident(scan.statement_start(i), "const"); @@ -561,6 +565,14 @@ mod tests { ("#define N 4\n#if N > 2\n#endif\n", "preprocessor condition"), ("#define S 3.0\nconst float T = S * 2.0;\n", "another const"), ("#define S 3.0\nfloat g = S;\n", "global initialiser"), + ( + "#define S 3.0\nfloat g = sqrt(S);\n", + "global initialiser, inside a call", + ), + ( + "const float K = 1.5;\nfloat f(float K) { return K * 2.0; }\nvoid main() { float a = f(K); }\n", + "a parameter of the same name", + ), ("#define S 3.0\n#define S 4.0\n", "defined twice"), ("#define S 3.0\n#undef S\n", "undefined"), ] { From 01b902e882db260f70ae91b6c1a7b3a9e16df93b Mon Sep 17 00:00:00 2001 From: Lawrence Date: Wed, 2 Dec 2026 23:09:54 +0000 Subject: [PATCH 18/20] fix(autocontrol): a bare speed macro divided by inside another macro is left alone --- crates/strobe-autocontrol/src/analyze/expr.rs | 36 +++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/crates/strobe-autocontrol/src/analyze/expr.rs b/crates/strobe-autocontrol/src/analyze/expr.rs index 23920ac1..72496b61 100644 --- a/crates/strobe-autocontrol/src/analyze/expr.rs +++ b/crates/strobe-autocontrol/src/analyze/expr.rs @@ -977,9 +977,34 @@ pub(super) fn define_time_scales(scan: &Scan<'_>) -> Vec { found } -/// Whether `name` is used anywhere right after a `/` or `%`. +/// Whether `name` is used anywhere right after a `/` or `%`, in code or in +/// another macro's body (`#define U (1.0 / T)`). fn macro_used_after_division(scan: &Scan<'_>, name: &str) -> bool { - (1..scan.len()).any(|i| scan.is_ident(i, name) && (scan.is(i - 1, "/") || scan.is(i - 1, "%"))) + let in_code = (1..scan.len()) + .any(|i| scan.is_ident(i, name) && (scan.is(i - 1, "/") || scan.is(i - 1, "%"))); + in_code + || (0..scan.len()) + .filter(|&d| scan.kind(d) == Some(TokKind::Directive)) + .filter_map(|d| match glsl::split_directive(scan.t(d)) { + Some(("define", body)) => Some(body), + Some(_) | None => None, + }) + .any(|body| { + let tokens: Vec> = glsl::lex_directive_body(body) + .into_iter() + .filter(|t| { + !matches!( + t.kind, + TokKind::Space | TokKind::LineComment | TokKind::BlockComment + ) + }) + .collect(); + tokens.windows(2).any(|pair| { + matches!(pair, [op, ident] if matches!(op.text, "/" | "%") + && ident.kind == TokKind::Ident + && ident.text == name) + }) + }) } #[cfg(test)] @@ -1403,6 +1428,13 @@ float glow(vec2 p) { float v = 0.0; for (int i = 0; i < 9; i++) { v += 0.1; } re .is_empty(), "a speed that is not finite" ); + assert!( + found( + "#define T TIME * 0.3\n#define U (1.0 / T)\nvec4 renderMain() { return vec4(U); }\n" + ) + .is_empty(), + "bare and divided by inside another macro: the paste would change" + ); } #[test] From 402623a958846af1bd8b3b0614c10cfbdf6f04d4 Mon Sep 17 00:00:00 2001 From: Lawrence Date: Wed, 2 Dec 2026 23:10:25 +0000 Subject: [PATCH 19/20] docs(autocontrol): the tokenizer is strobe_scene::glsl, not strobe-shadertoy's --- crates/strobe-autocontrol/src/analyze/consts.rs | 2 +- crates/strobe-autocontrol/src/lib.rs | 4 ++-- crates/strobe-autocontrol/src/naming.rs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/strobe-autocontrol/src/analyze/consts.rs b/crates/strobe-autocontrol/src/analyze/consts.rs index 2c9c7c42..1b1cd15c 100644 --- a/crates/strobe-autocontrol/src/analyze/consts.rs +++ b/crates/strobe-autocontrol/src/analyze/consts.rs @@ -4,7 +4,7 @@ // `const float NAME = 0.3;`) and checks they are safe to turn // into uniforms. // -// Dependencies: crate::source, strobe-shadertoy (directive tokenizer) +// Dependencies: crate::source, strobe-scene (directive tokenizer) // ============================================================================ //! Named constants. diff --git a/crates/strobe-autocontrol/src/lib.rs b/crates/strobe-autocontrol/src/lib.rs index 111c6027..a36cbd96 100644 --- a/crates/strobe-autocontrol/src/lib.rs +++ b/crates/strobe-autocontrol/src/lib.rs @@ -4,7 +4,7 @@ // scene, rewrites them into uniforms and keeps the ones that // visibly change the image. // -// Dependencies: strobe-scene, strobe-shadertoy (tokenizer), strobe-gfx (scoring) +// Dependencies: strobe-scene (tokenizer), strobe-gfx (scoring) // ============================================================================ //! Auto-generated controls. @@ -22,7 +22,7 @@ //! ``` //! //! - [`mod@analyze`] is pure static analysis over the lossless tokenizer of -//! `strobe-shadertoy`: `#define`s and `const`s, `TIME` multipliers, loop +//! `strobe_scene::glsl`: `#define`s and `const`s, `TIME` multipliers, loop //! bounds, `vec3` colours, coordinate scales and frequencies. It is //! conservative on purpose. //! - [`rewrite`] turns chosen candidates into uniform references **without diff --git a/crates/strobe-autocontrol/src/naming.rs b/crates/strobe-autocontrol/src/naming.rs index 2f688ea2..6c628e13 100644 --- a/crates/strobe-autocontrol/src/naming.rs +++ b/crates/strobe-autocontrol/src/naming.rs @@ -3,7 +3,7 @@ // Description: Readable, unique, legal control names: snake_case from the // source identifier, numbered when shared, never colliding. // -// Dependencies: strobe-scene (names, SceneFolder), strobe-shadertoy (glsl) +// Dependencies: strobe-scene (names, SceneFolder, glsl) // ============================================================================ //! Control names. From b6c5b0a19a700f1510ae3e541f1766492a3c9b98 Mon Sep 17 00:00:00 2001 From: Lawrence Date: Wed, 2 Dec 2026 23:14:53 +0000 Subject: [PATCH 20/20] test(site): the gate counts motion in red and blue alone --- site/tests/unit/from-image.test.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/site/tests/unit/from-image.test.ts b/site/tests/unit/from-image.test.ts index b0f81df9..279ee71b 100644 --- a/site/tests/unit/from-image.test.ts +++ b/site/tests/unit/from-image.test.ts @@ -167,6 +167,18 @@ describe("the gates", () => { check(frames([255, 255, 255]), "blown"); check([textured(3), textured(3), textured(3)], "does not move"); }); + + it("counts motion in red and blue alone as motion", () => { + // A hue cycle with green held at zero; strobe-forge's gate has the same case (D562). + const tint = (rgb: number[]) => { + const data = new Uint8ClampedArray(8 * 8 * 4); + for (let i = 0; i < 8 * 8; i += 1) data.set([...rgb, 255], i * 4); + return data; + }; + const set = Array.from({ length: 30 }, (_, i) => tint(i % 2 === 0 ? [200, 0, 50] : [50, 0, 200])); + const result = gate({ width: 8, height: 8, rate: 30, frames: set }); + expect(result.problems.join(), "it moves").not.toContain("does not move"); + }); }); describe("straightening", () => {