Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
17 changes: 10 additions & 7 deletions crates/strobe-app/tests/transitions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,22 +100,25 @@ fn a_new_song_jumps_hard_transitions_and_crossfades_smooth_ones() -> Result<()>
);

assert!(session.song_change(), "{api:?}: something changes");
// 30 frames of 1/60 s: half of the one-second crossfade.
// 30 frames of 1/60 s into a `DURATION` 1 fade, whose time constant
// is 0.427 s (D703): b is at 1 - exp(-0.5 / 0.427), 0.69.
for _ in 0..30 {
session.advance(DT, &mut audio, Mouse::default(), DATE);
}
let halfway = centre(&session)?;
let midway = centre(&session)?;
// A hard transition may keep its value, as Synesthesia's does.
let dir = if midway[0] > 127 { 255 } else { 0 };
assert!(
near(halfway, [255, 128, 128]),
"{api:?}: dir jumped, a and b halfway: {halfway:?}"
near(midway, [dir, 79, 176]),
"{api:?}: dir at 0 or 1, a and b part of the way: {midway:?}"
);
for _ in 0..40 {
for _ in 0..200 {
session.advance(DT, &mut audio, Mouse::default(), DATE);
}
let after = centre(&session)?;
assert!(
near(after, [255, 0, 255]),
"{api:?}: the crossfade is done: {after:?}"
near(after, [dir, 0, 255]),
"{api:?}: the fade is done: {after:?}"
);
if let Some(code) = gl.error() {
return Err(anyhow!("{api:?}: GL error 0x{code:x}"));
Expand Down
12 changes: 8 additions & 4 deletions crates/strobe-scene/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,13 @@ IDs given here; a gap with no ID is by design, with its decision named.
(D238).
- `HARD_TRANSITIONS` and `SMOOTH_TRANSITIONS` are declared here and their
live values kept in `transition`, which the app changes on a song change
or the `new_song` command (D489). Whether Synesthesia picks values at
load, may repeat a value, and how long a family without `DURATION` fades
are not yet checked against Synesthesia (Q33, backlog C-07).
or the `new_song` command (D489). As Synesthesia does (D703), a hard
transition draws from all its values and may repeat, and a family fades
exponentially (0.207 s without `DURATION`). Whether the time constant
scales with `DURATION` is unchecked (Q33, backlog C-07).
- `bang smooth` peaks on the pressed frame (D702). A dropdown with more
`LABELS` than `VALUES` sends the last value for the extras, and an untyped
control with three or four `DEFAULT` numbers is a slider (D704).
- Strobe's own extensions are root keys (`PASS_SOURCES`, `SOURCE`, D90;
`MEDIA` folders, D186; `TAGS`, D205). An `X_STROBE` block, PLAN.md's
original idea, is ignored like any other unknown key.
Expand All @@ -133,5 +137,5 @@ IDs given here; a gap with no ID is by design, with its decision named.
[`OPEN_QUESTIONS.md`](../../docs/OPEN_QUESTIONS.md)). The shipped scenes
are written ES-clean.
- Unverified against real Synesthesia: the audio texture layout (Q10),
the bang-smooth envelope (Q4) and the rest of
the rest of
`OPEN_QUESTIONS.md` (backlog C-07).
78 changes: 51 additions & 27 deletions crates/strobe-scene/src/control/def.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,19 +77,26 @@ impl ControlDef {
return Err(SceneError::ReservedName(name));
}
// Real Synesthesia scenes have controls with only NAME, MIN, MAX and
// DEFAULT (7 in 65 on TORNADO, D193). With no TYPE, the default's
// components pick the one type with that many: two make an xy pad,
// three a colour (the only vec3), four a colour with alpha (dropped,
// as for a typed colour), and anything else a slider (D412, Q32).
let ty = if raw.ty.trim().is_empty() {
// DEFAULT (7 in 65 on TORNADO, D193). With no TYPE, two default
// components make an xy pad (D193), and anything else a slider: one
// with three, as Synesthesia 1.25.4 makes it, a slider from the
// first number (D704; four assumed the same).
let untyped = raw.ty.trim().is_empty();
let ty = if untyped {
match raw.default.as_ref().map(|d| d.to_vec().len()) {
Some(2) => "xy",
Some(3 | 4) => "color",
Some(_) | None => "slider",
}
} else {
raw.ty.as_str()
};
// The untyped slider's default is the list's first number.
let first_default = match raw.default.as_ref() {
Some(Components::Many(values)) if untyped && values.len() > 2 => {
values.first().copied().map(Components::One)
}
Some(_) | None => None,
};
let kind = ControlKind::parse(&name, ty)?;
let dims = kind.dimensions();

Expand Down Expand Up @@ -117,7 +124,7 @@ impl ControlDef {
| ControlKind::Toggle { .. }
| ControlKind::Bang(_)
| ControlKind::Xy(_)
| ControlKind::Dropdown { .. } => raw.default.as_ref(),
| ControlKind::Dropdown { .. } => first_default.as_ref().or(raw.default.as_ref()),
};
let fallback = components(&name, "MIN", None, dims, 0.0)?;
let mut default = match default_source {
Expand Down Expand Up @@ -277,28 +284,36 @@ fn components(
/// A dropdown's labels and values, each filled in from the other. An empty
/// list counts as absent.
///
/// When both are given with different lengths, the options are the ones
/// both lists give: label `i` with value `i`, as far as the shorter list
/// goes. Neither a value nor a label is invented, the scene keeps playing,
/// and the mismatch is logged (D412). What Synesthesia does with such a
/// control is not known (Q32).
/// When there are more labels than values, every label is an option and
/// the labels past the end of `VALUES` send its last value, as
/// Synesthesia 1.25.4 does (D704). When there are more values than labels,
/// the options stop at the last label (D412; Synesthesia not yet seen).
/// Either way the scene keeps playing and the mismatch is logged.
fn dropdown_options(name: &str, raw: &RawControl) -> Result<(Vec<String>, Vec<f32>), SceneError> {
let labels = raw.labels.as_ref().filter(|labels| !labels.is_empty());
let values = raw.values.as_ref().filter(|values| !values.is_empty());
match (labels, values) {
(Some(labels), Some(values)) => {
if labels.len() != values.len() {
if labels.len() > values.len() {
log::warn!(
"dropdown `{name}`: {} LABELS but {} VALUES; the last {} send the last value",
labels.len(),
values.len(),
labels.len() - values.len()
);
} else if labels.len() < values.len() {
log::warn!(
"dropdown `{name}`: {} LABELS but {} VALUES; keeping the first {} of each",
"dropdown `{name}`: {} LABELS but {} VALUES; keeping the first {}",
labels.len(),
values.len(),
labels.len().min(values.len())
labels.len()
);
}
let last = values.last().copied().unwrap_or(0.0);
Ok(labels
.iter()
.zip(values)
.map(|(label, value)| (label.clone(), *value))
.enumerate()
.map(|(i, label)| (label.clone(), values.get(i).copied().unwrap_or(last)))
.unzip())
}
(Some(labels), None) => Ok((
Expand Down Expand Up @@ -406,14 +421,19 @@ mod tests {
}

#[test]
fn a_dropdown_whose_labels_and_values_differ_keeps_the_options_both_give() -> Result<()> {
// One list longer than the other used to fail the whole scene.
fn a_dropdown_with_more_labels_than_values_sends_the_last_value_past_the_end() -> Result<()> {
// Synesthesia lists one, two, three for VALUES [1, 2], and three
// sends 2 (D704).
let def = control(
r#"{ "NAME": "m", "TYPE": "dropdown", "LABELS": ["a", "b", "c"], "VALUES": [5, 7] }"#,
)?;
assert_eq!(def.labels, vec!["a", "b"], "labels paired with a value");
assert_eq!(def.values, vec![5.0, 7.0], "every value kept");
assert_eq!(def.max[0], 1.0, "the range is the two options' indices");
assert_eq!(def.labels, vec!["a", "b", "c"], "every label is an option");
assert_eq!(
def.values,
vec![5.0, 7.0, 7.0],
"the last label sends the last value"
);
assert_eq!(def.max[0], 2.0, "the range is the three options' indices");
let def = control(
r#"{ "NAME": "m", "TYPE": "dropdown", "LABELS": ["a"], "VALUES": [5, 7, 9] }"#,
)?;
Expand All @@ -428,17 +448,21 @@ mod tests {
}

#[test]
fn an_untyped_control_with_three_or_four_default_components_is_a_colour() -> Result<()> {
// Two components make an xy pad (D193); three are a vec3, which only
// a colour is, and four a colour with alpha. A slider failed them.
fn an_untyped_control_with_three_or_four_default_components_is_a_slider() -> Result<()> {
// Synesthesia shows one slider "tint" at 0.20 for [0.2, 0.4, 0.6],
// and the shader sees 0.2 (D704).
for default in ["[0.2, 0.4, 0.6]", "[0.2, 0.4, 0.6, 1.0]"] {
let def = control(&format!(r#"{{ "NAME": "tint", "DEFAULT": {default} }}"#))?;
assert!(
matches!(def.kind, ControlKind::Color { .. }),
matches!(def.kind, ControlKind::Slider(_)),
"{default}: {:?}",
def.kind
);
assert_eq!(def.default, [0.2, 0.4, 0.6], "{default}: the default kept");
assert!(
(def.default[0] - 0.2).abs() < 1e-6,
"{default}: the first number is the default: {:?}",
def.default
);
}
let def = control(r#"{ "NAME": "amount", "DEFAULT": 0.5 }"#)?;
assert!(
Expand Down
92 changes: 33 additions & 59 deletions crates/strobe-scene/src/control/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,9 @@
//! spacing, so the pace drifts, and a control slowed after running fast
//! stops moving at all.
//! - **bang** outputs `MAX` for exactly one frame per press, then `MIN`;
//! presses between frames are counted, never lost. `bang smooth` runs an
//! attack/decay envelope; `bang counter` adds one per press.
//! presses between frames are counted, never lost. `bang smooth` jumps
//! to `MAX` on the frame that takes a press and decays at the smoothing
//! step after (D702); `bang counter` adds one per press.
//!
//! Nothing here allocates per frame; [`ControlBank::tick`] walks two
//! fixed-size vectors.
Expand All @@ -50,8 +51,6 @@ struct State {
presses: u32,
/// Bang counter total.
count: f32,
/// `bang smooth`: still rising toward the peak.
attacking: bool,
/// `traveler`: the rate, easing toward the target.
rate: Values,
/// `speed` and `traveler`: the integral, of which `output` is the
Expand Down Expand Up @@ -421,7 +420,6 @@ fn initial_state(def: &ControlDef) -> State {
output,
presses: 0,
count: 0.0,
attacking: false,
rate: def.default,
integral: [0.0; MAX_DIMENSIONS],
glide: None,
Expand All @@ -434,10 +432,6 @@ fn dropdown_value(def: &ControlDef, index: f32) -> f32 {
def.values.get(i).copied().unwrap_or(0.0)
}

/// The least a `bang smooth` attack rises per sixtieth of a second, so a
/// flash is quick whatever the control's `PARAMS`.
const ATTACK_FLOOR: f32 = 0.25;

/// The smoothing step for this frame: `PARAMS` per sixtieth of a second.
fn alpha(params: f32, dt: f32) -> f32 {
1.0 - (1.0 - params.clamp(0.0, 1.0)).powf(dt * 60.0)
Expand Down Expand Up @@ -513,24 +507,18 @@ fn step(def: &ControlDef, state: &mut State, dt: f32, rate: f32) {
state.presses = 0;
}
ControlKind::Bang(Bang::Smooth) => {
if state.presses > 0 {
state.attacking = true;
// The frame that takes a press shows the peak, and every frame
// after falls by the smoothing step, as Synesthesia 1.25.4 draws
// it (D702). The envelope runs in normalised units and is
// mapped to the range on the way out, so an inverted range
// still rises.
let t = if state.presses > 0 {
state.presses = 0;
}
// The envelope runs in normalised units and is mapped to the
// range on the way out, so an inverted range still rises. The
// attack rises at least a quarter of the way per sixtieth of a
// second, frame-rate independent like every other step.
let mut t = def.normalize(0, state.output[0]);
if state.attacking {
t += (1.0 - t) * a.max(alpha(ATTACK_FLOOR, dt));
if t > 0.98 {
t = 1.0;
state.attacking = false;
}
1.0
} else {
t -= t * a;
}
let t = def.normalize(0, state.output[0]);
t - t * a
};
state.output[0] = def.denormalize(0, t);
}
ControlKind::Bang(Bang::Counter) => {
Expand Down Expand Up @@ -958,43 +946,29 @@ mod tests {
Ok(())
}

/// Wall-clock seconds a `bang smooth` press takes to reach its peak at
/// `fps`.
fn seconds_to_peak(fps: f32) -> Result<f32> {
let mut b = bank(&[r#"{ "NAME": "b", "TYPE": "bang smooth" }"#])?;
b.press(0);
let dt = 1.0 / fps;
let mut elapsed = 0.0;
for _ in 0..1000 {
b.tick(dt);
elapsed += dt;
if out(&b, 0) >= 1.0 {
return Ok(elapsed);
}
}
Ok(f32::INFINITY)
}

#[test]
fn a_smooth_bangs_attack_takes_the_same_wall_time_at_any_frame_rate() -> Result<()> {
// The attack's floor was 0.25 per frame, not per sixtieth of a
// second: at 30 fps a flash rose half as fast, and a paused tick
// (dt 0) still moved it.
let (sixty, thirty) = (seconds_to_peak(60.0)?, seconds_to_peak(30.0)?);
assert!(
(sixty - thirty).abs() <= 1.0 / 30.0 + 1e-4,
"the peak at 60 fps ({sixty} s) and at 30 fps ({thirty} s) should agree to a frame"
);
let mut b = bank(&[r#"{ "NAME": "b", "TYPE": "bang smooth" }"#])?;
fn a_smooth_bang_peaks_on_the_pressed_frame_and_decays_as_synesthesia_does() -> Result<()> {
// Measured on the T480 (D702): a press shows 1.0 on the next frame,
// then PARAMS 0.3 reads 0.70, 0.48, 0.34, 0.24 a sixtieth apart.
let mut b = bank(&[r#"{ "NAME": "b", "TYPE": "bang smooth", "PARAMS": 0.3 }"#])?;
b.press(0);
b.tick(0.0);
assert_eq!(out(&b, 0), 0.0, "no time passed, so nothing rose");
b.tick(1.0 / 60.0);
assert!(
(out(&b, 0) - 0.25).abs() < 1e-5,
"at 60 fps the first frame still rises by a quarter: {}",
out(&b, 0)
);
assert_eq!(out(&b, 0), 1.0, "the pressed frame is the peak");
for (frame, measured) in [0.702_f32, 0.482, 0.341, 0.239].iter().enumerate() {
b.tick(1.0 / 60.0);
assert!(
(out(&b, 0) - measured).abs() < 0.015,
"frame {} after the peak: {} against Synesthesia's {measured}",
frame + 1,
out(&b, 0)
);
}
let mut paused = bank(&[r#"{ "NAME": "b", "TYPE": "bang smooth" }"#])?;
paused.press(0);
paused.tick(0.0);
assert_eq!(out(&paused, 0), 1.0, "a paused frame still shows the press");
paused.tick(0.0);
assert_eq!(out(&paused, 0), 1.0, "and holds it while no time passes");
Ok(())
}
}
11 changes: 6 additions & 5 deletions crates/strobe-scene/src/scene.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,13 +189,14 @@ pub struct SmoothTransition {
pub first: usize,
/// How many uniforms the family has, at least one.
pub len: usize,
/// The crossfade's length in seconds, `0` for a cut.
/// The family's `DURATION` in seconds, `0` for a cut; the fade's time
/// constant is this times [`crate::transition::TAU_PER_DURATION`].
pub duration: f32,
}

/// A family's crossfade when `DURATION` is left out. SSF documents no
/// default; three seconds is its own example's (Q33, D489).
pub const SMOOTH_DEFAULT_DURATION: f32 = 3.0;
/// The `DURATION` a family takes when it gives none: the one whose fade has
/// Synesthesia's measured time constant without one, 0.207 s (D703).
pub const SMOOTH_DEFAULT_DURATION: f32 = 0.207 / crate::transition::TAU_PER_DURATION;

/// A validated scene.
#[derive(Debug, Clone, PartialEq)]
Expand Down Expand Up @@ -334,7 +335,7 @@ impl SceneDef {
first: transition_uniforms.len(),
len: smooth.uniforms.len(),
// A negative length is a cut; a missing or unreadable
// one is SSF's example's.
// one fades as Synesthesia's does without one.
duration: smooth
.duration
.filter(|d| d.is_finite())
Expand Down
Loading
Loading