Skip to content

audit(wave/diff-eq): overflow risk + perf wins in WaveSimulation Q15 stencil (behind WaveFx) #3073

Closed

Description

@zackees

Summary

The differential-equation solver behind WaveFx (fl::WaveSimulation2D_Real / fl::WaveSimulation1D_Real) implements a standard explicit leapfrog finite-difference scheme for the 2D wave equation:

u(t+1) = 2·u(t) - u(t-1) + C²·∇²u(t) - u(t+1)/D     (then clamp to Q15)

The scheme itself is correct and a reasonable choice for visual LED effects. This audit flags one latent correctness bug, several micro-optimization wins that matter for the embedded targets FastLED runs on (AVR, Cortex-M0, ESP32), and a couple of algorithmic options worth considering.

Files:

  • src/fl/math/wave/wave_simulation_real.h
  • src/fl/math/wave/wave_simulation_real.cpp.hpp

1. Correctness: Q15 multiply can overflow i32 (latent)

Location: wave_simulation_real.cpp.hpp:259 (2D) and :125 (1D)

i32 term = (mCourantSq32 * laplacian) >> 15;

Worst-case 2D Laplacian magnitude (all neighbors at +32767, center at -32768, or vice-versa):

  • |laplacian|_max = 4·32767 + 4·32768 = 262,140
  • |mCourantSq|_max = 32767 (Q15 of ~0.9999)
  • Product: 32767 × 262,140 ≈ 8.59 × 10⁹ → overflows i32 (max ≈ 2.15 × 10⁹)

The default speed = 0.16 (≈ 5,243 in Q15) keeps the product around 1.37 × 10⁹, comfortably in range, but the public API (setSpeed(float)) and the float→Q15 converter accept values all the way to 1.0. Any caller pushing speed > ~0.25 with near-saturated cells can wrap to a negative term and produce visible glitches or instability.

Suggested fixes (pick one):

a) Promote the multiply to 64-bit:

i32 term = static_cast<i32>((static_cast<i64>(mCourantSq32) * laplacian) >> 15);

On 32-bit MCUs the i64 multiply is 2–4× the cost of i32, but this kernel is memory-bound — likely negligible.

b) Clamp mCourantSq at the setter to a documented stability bound (e.g., ≤ 0.25 for the 5-point 2D stencil, which is the CFL limit anyway). This is free at runtime and makes the implicit assumption explicit.

c) Shrink the Laplacian range — see §5 (higher-order stencil), which also helps here.

I'd vote (a) + (b): belt-and-braces.


2. Perf: damping division can be a shift

Location: wave_simulation_real.cpp.hpp:132 (1D) and :264 (2D)

i32 dampening_factor = 1 << mDampening;  // power of two
...
f = f - (f / dampening_factor);

dampening_factor is always a power of two, so the division is equivalent to f >> mDampening for non-negative f. For negative f, signed division truncates toward zero while >> rounds toward -∞ (off by 1 LSB). On a visually-damped Q15 simulation that 1-LSB asymmetry is invisible.

Cost difference:

  • AVR (no HW divider): 32-bit signed / ≈ 150–200 cycles; >> ≈ ~32 cycles.
  • Cortex-M0 / RP2040 / Teensy-LC: similar — software divide.
  • Cortex-M4/M7 / ESP32 / ESP32-S3: HW divide ≈ 2–12 cycles vs 1 cycle for shift.

This is the hottest line in the inner loop on AVR — it runs once per cell per step. Suggested:

f -= (f >> mDampening);

If preserving the exact rounding for negative values matters (it shouldn't, given half-duplex clamps negatives to zero anyway), use the standard "shift-with-round-to-zero" idiom:

f -= (f < 0 ? -((-f) >> mDampening) : (f >> mDampening));

3. Perf: fold the half-duplex pass into the main loop

Location: wave_simulation_real.cpp.hpp:276–286 (2D) and :143–150 (1D)

The half-duplex clamp currently runs as a second full pass over the grid:

for (j ...) for (i ...)
    if (next[index] < 0) next[index] = 0;

This doubles memory traffic for the grid. On ESP32-PSRAM (used by vector_psram<i16> for the 2D grid) the extra traversal is especially expensive. Fold it into the existing loop right before the store:

if (mHalfDuplex && f < 0) f = 0;
next[index] = (i16)f;

Even better: combine the half-duplex clamp with the Q15 clamp using fl::clamp/std::clamp, which most modern compilers lower branchlessly:

i32 lo = mHalfDuplex ? 0 : -32768;
next[index] = static_cast<i16>(fl::clamp(f, lo, 32767));

The lo value can be hoisted out of the inner loop.


4. Perf: branchless clamp + reduced cell indexing

Location: wave_simulation_real.cpp.hpp:267–270 and similar in 1D

The current clamp:

if (f > 32767) f = 32767;
else if (f < -32768) f = -32768;

…is fine on amd64/arm64 (cmov), but on AVR / M0 it compiles to two compares + branches. static_cast<i16>(fl::clamp(...)) typically lowers to ssat-equivalent or branchless min/max sequences on Cortex-M4+.

Also: int index = j * stride + i; recomputes j*stride for every i inside the inner loop. Hoist:

for (fl::size j = 1; j <= height; ++j) {
    const i32 row = j * stride;
    const i16* row_curr = curr + row;
    const i16* row_above = curr + row - stride;
    const i16* row_below = curr + row + stride;
    i16* row_next = next + row;
    for (fl::size i = 1; i <= width; ++i) {
        const i32 c = row_curr[i];
        i32 lap = row_curr[i+1] + row_curr[i-1] + row_above[i] + row_below[i] - (c << 2);
        ...
    }
}

This is something the optimizer should do but often doesn't with fl::size (size_t) and a non-restricted pointer aliasing pair. Spelling it out + __restrict__ on curr/next removes any doubt.


5. Algorithmic option: 9-point isotropic Laplacian (super-sampled mode)

The 5-point stencil currently in use is O(h²) accurate and anisotropic — waves visibly prefer the 4 cardinal directions over the 4 diagonals, producing a square-ish ripple shape that's a known artifact of this scheme. For LED-grid resolutions this is usually invisible, but at SUPER_SAMPLE_4X / _8X it becomes noticeable on circular ripples.

A 9-point isotropic Laplacian:

∇²u ≈ [1/6·(diagonals) + 2/3·(neighbors) - 10/3·center] / h²

is O(h²) but with isotropic leading error, giving rounder ripples for ~2× the read/ALU per cell. Worth offering as an opt-in mode for the super-sampled path (which is already paying for higher resolution).

Not urgent; nice-to-have for visual quality.


6. Algorithmic option: precompute damping as a Q15 multiplier

Replace f -= f / D with a single Q15 multiply by the precomputed constant K = ((D - 1) / D) in Q15. Precomputed once at setDampening():

i16 mDampDecayQ15 = wave_detail::float_to_fixed(1.0f - 1.0f / (1 << damp));

Inner loop becomes:

f = (static_cast<i64>(f) * mDampDecayQ15) >> 15;

This is equivalent to the shift fix in §2 but extends to non-power-of-two damping factors if the API ever needs them. On Cortex-M4+ this is a single smmlsr/smulwb. On AVR it's a 16×32 multiply, ~30 cycles — same ballpark as the shift but with cleaner semantics.


7. SIMD opportunity (host + ESP32-S3 + Teensy 4)

The inner kernel is a textbook 5-point stencil — natural fit for SIMD:

  • Host (test/WASM): SSE2 / AVX2 / NEON 8× i16 lanes. Easy 4–8× speedup.
  • ESP32-S3 PIE (128-bit SIMD): EE.VLD/EE.VST + 16-bit ops, similar 8-wide gain. There is no existing SIMD path in wave_simulation_real.cpp.hpp — the rest of the codebase has PIE infra (search EE_VADDS, xt_simd).
  • Teensy 4 (Cortex-M7): __SADD16 / __SSAT16 / __SMLAD SIMD intrinsics can process 2× i16 per instruction.

Not a small change, but WaveFx is one of the heavier Fx2d effects and is regularly run at 4×/8× super-sample on ESP32-S3 grids, so the wins would be felt.


Suggested execution order

  1. §1 (overflow fix) — small, safety-critical patch. Should be merged on its own.
  2. §2 (damp shift) + §3 (fold half-duplex) + §4 (branchless clamp + hoisted indexing) — bundle into one perf PR. Easy to verify with tests/fl/math/wave/* + a microbench.
  3. §6 (precomputed damp Q15) — supersedes §2 if you want non-power-of-two damping; otherwise §2 is simpler.
  4. §5 (9-point isotropic stencil) — opt-in for super-sample modes only.
  5. §7 (SIMD) — separate larger effort, behind a #ifdef gate per platform.

Test plan

  • bash test WaveSimulation (existing host unit tests) — golden-output for default speed/damping/grid sizes; should be byte-identical after §1/§2/§3/§4 except for the §2 negative-rounding 1-LSB drift (acceptable diff).
  • bash compile uno --examples FxWave2d — confirms AVR build still fits in flash after micro-opts.
  • bash autoresearch teensy41 --parlio on examples/Fx/FxWave2d — visual check of ripple shape (especially §5 9-point stencil if pursued).
  • Microbench: count cycles per update() on host for a 64×64 grid before/after.

cc: original author Shawn Silverman (per file header) for stencil-choice context.

Activity

  1. moved this from Triage to Done in FastLED Trackeron Jun 15, 2026
  2. zackees commented on Jun 15, 2026

    @zackees
    MemberAuthor

    Auto-closed by #3083 (squash SHA 15393b8377a4a65c20cf5212d18e6c324931c2dc). Validation evidence:

    • New test tests/fl/math/wave/wave_simulation_real.cpp (5 cases) passes on master post-merge — bash test fl_math_wave_wave_simulation_real --cpp → ✅ All tests passed (1/1). The test cases drive the worst-case scenario described in §1 (2D sim at CFL bound 0.5 with saturated checkerboard cells; same for 1D at CFL bound 1.0) and confirm no i32 overflow leaks past the post-update clamp.
    • Pre-existing uno CI failure observed on the PR was the fl::math F template helper colliding with the Arduino WString.h F() macro — unrelated to this PR, and independently fixed on master in fix(avr/math): #undef Arduino F() macro before fl::math polynomial templates (unbreak master Uno build) #3086 the same hour.

    §1 (correctness): DONE.

    Deferred items remain open as named commitments in #3083's body:

    • §2 — damping division → arithmetic shift (perf, AVR/M0)
    • §3 — fold half-duplex pass into main update loop
    • §4 — branchless Q15 clamp + hoisted indexing + __restrict__
    • §5 — 9-point isotropic Laplacian (super-sample opt-in)
    • §6 — precomputed Q15 damping multiplier
    • §7 — SIMD kernels (host + ESP32-S3 PIE + Teensy 4 DSP)

    These can be picked up by re-opening this issue or filing focused follow-ups.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions