Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
37993fc
fix(forge): a dialect that was not checked is not a compile error
lnorton89 Dec 2, 2026
a7b5fe3
fix(forge): an answer with no text is an error, not a turn to replay
lnorton89 Dec 2, 2026
8ef8d6f
fix(forge): the frozen gate counts every channel, not green alone
lnorton89 Dec 2, 2026
8f0b423
fix(forge): round 0's log no longer claims a previous scene stands
lnorton89 Dec 2, 2026
6a9a12c
fix(forge): one Markdown fence around a block's body is dropped
lnorton89 Dec 2, 2026
833c011
fix(forge): a provider's error and refusal text is bounded
lnorton89 Dec 2, 2026
233f91e
fix(shadertoy): a Shadertoy uniform the author redefines as a macro c…
lnorton89 Dec 2, 2026
db17a4b
fix(shadertoy): gl_FragColor in code that never runs no longer blacke…
lnorton89 Dec 2, 2026
cea9485
fix(shadertoy): the generated keyboard image is not counted as a foun…
lnorton89 Dec 2, 2026
3ba2d40
fix(shadertoy): a shader URL with a port is still a shadertoy.com add…
lnorton89 Dec 2, 2026
fd775dc
docs(shadertoy): the invalid-key message names every character a key …
lnorton89 Dec 2, 2026
dfb5646
fix(shadertoy): the listener bounds the whole request, not each read
lnorton89 Dec 2, 2026
c36b3bc
fix(autocontrol): a name that bounds any array-indexing loop is never…
lnorton89 Dec 2, 2026
afe342e
fix(autocontrol): a reviewed range keeps the loop cap and holds the d…
lnorton89 Dec 2, 2026
3bec26c
fix(autocontrol): a loop bound that is not a whole number is not a count
lnorton89 Dec 2, 2026
27899f2
fix(autocontrol): a time factor too large to range is not a speed con…
lnorton89 Dec 2, 2026
4a0adea
fix(autocontrol): a constant used anywhere outside a function body is…
lnorton89 Dec 2, 2026
01b902e
fix(autocontrol): a bare speed macro divided by inside another macro …
lnorton89 Dec 2, 2026
402623a
docs(autocontrol): the tokenizer is strobe_scene::glsl, not strobe-sh…
lnorton89 Dec 2, 2026
b6c5b0a
test(site): the gate counts motion in red and blue alone
lnorton89 Dec 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions crates/strobe-autocontrol/src/analyze/consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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"),
] {
Expand Down
66 changes: 63 additions & 3 deletions crates/strobe-autocontrol/src/analyze/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,14 +202,23 @@ 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<Hit> {
let bound = found.bound;
if !scan.is_number(bound) || found.indexes_with_var || scan.brace_depth(bound) == 0 {
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));
Expand Down Expand Up @@ -348,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 {
Expand Down Expand Up @@ -935,6 +947,9 @@ pub(super) fn define_time_scales(scan: &Scan<'_>) -> Vec<Hit> {
} else {
value.value as f32
};
if !speed_ok(value) {
continue;
}
let name = specific(macro_name).map_or_else(
|| "speed".to_string(),
|name| {
Expand Down Expand Up @@ -962,9 +977,34 @@ pub(super) fn define_time_scales(scan: &Scan<'_>) -> Vec<Hit> {
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::Token<'_>> = 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)]
Expand Down Expand Up @@ -1016,6 +1056,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(),
Expand Down Expand Up @@ -1066,6 +1110,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);
Expand Down Expand Up @@ -1375,6 +1423,18 @@ 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"
);
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]
Expand Down
59 changes: 55 additions & 4 deletions crates/strobe-autocontrol/src/analyze/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,14 +146,20 @@ fn file_hits(scan: &Scan<'_>) -> Vec<Hit> {
let loops = expr::loops(scan);
let mut hits: Vec<Hit> = 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;
}
}
}
}
Expand Down Expand Up @@ -230,7 +236,8 @@ fn named_hit(named: &consts::Named) -> Option<Hit> {
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);
Expand Down Expand Up @@ -494,6 +501,50 @@ 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
// `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 = "\
Expand Down
34 changes: 28 additions & 6 deletions crates/strobe-autocontrol/src/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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<Generated, ChoiceError> {
let sources = Sources::from_folder(folder);
let candidates = analyze(&sources).candidates;
Expand Down Expand Up @@ -239,9 +261,9 @@ pub fn rewrite_chosen(folder: &SceneFolder, choices: &[Choice]) -> Result<Genera
.iter()
.map(|(candidate, choice)| {
let mut ranged = (*candidate).clone();
if ranged.value_type != ValueType::Colour && choice.min < choice.max {
ranged.min = vec![choice.min];
ranged.max = vec![choice.max];
if let Some((min, max)) = reviewed_range(candidate, choice.min, choice.max) {
ranged.min = vec![min];
ranged.max = vec![max];
}
rewrite::control_line(&ranged, &choice.name, false)
})
Expand Down
4 changes: 2 additions & 2 deletions crates/strobe-autocontrol/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion crates/strobe-autocontrol/src/naming.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
50 changes: 50 additions & 0 deletions crates/strobe-autocontrol/tests/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1432,3 +1432,53 @@ fn a_job_dropped_at_any_step_leaves_no_gl_object_behind() -> 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(())
}
Loading
Loading