Merge Ω-W2-T5: bound the waveform zero-crossing snap to a pixel radius

Single-cycle loop marks stop teleporting to the one interior crossing. Ctrl on a
marker drag defeats the snap, and no longer loses the grab to a coincident node.
This commit is contained in:
2026-08-03 16:09:27 -04:00
11 changed files with 316 additions and 33 deletions
+1 -1
View File
@@ -340,7 +340,7 @@ anything for a trigger shape.
- `sample_chrome` — the CHROME band's interior: the toolbar row (title + the whole right-anchored control run — bake Hold cell, bake, preview, velocity knob cell, loop enable, channel toggle, Browse) over the strip row, which the piano strip owns outright. The title takes what the run leaves; the strip takes its whole row, inset only by the shared band pad so it lines up with the waveform band beneath. Every run member's width is RESERVED unconditionally, the Hold cell included — the only conditionally-drawn one, and the leftmost, so what its reservation buys is a title slot that does not re-measure when a loop is dialled in or out (`sample_chrome.h` records the cost). Also `previewGlyph`, the preview button's play triangle — three vertices for one filled-triangle draw, so the button's label needs no font metric and no image asset.
- `bake_hold` — the Hold knob's value domain and nothing else: the knob's normalized [0,1] mapped onto the note-length ladder and back, ordered by LENGTH rather than by the ladder's presentation order. Split from `sample_chrome` on the same axis `deck_values` was split from `knob_deck` — that says where the cell is, this says what its position means.
- `keyboard_strip` — piano-keyboard strip: true white/black key geometry (whites tiled at one width, blacks overlaid at one width and height, straddling their boundary), hit-test resolving black-over-white by zone, root-marker rect, the absolute-position drag resolver, and MIDI note naming under the C4 convention. **Same-class keys are one integer width by construction; the residue of an indivisible band width (`w % 75`, up to 74 px) lands in symmetric end margins, never in a key** — uniform widths and gap-free edge-to-edge tiling cannot both hold, and uniformity wins.
- `waveform_view` — the WAVEFORM band's interior: `resolveLaneSplit` is THE lane-split decision (two lanes only when the mode is stereo AND the source has a second channel — a mono source under stereo mode is dual-mono and draws one lane), free of any pixel geometry so the meter's bar count can ask the same question without a band rect; `waveformSurface` folds it and then measures it against the band, which is why its `laneCount` can still report 1 for a Stereo split on a band too thin to divide. It also yields **the** overlay area, and `laneEnvelope` splits one multi-channel envelope pass per lane. Also maps frame span linearly across a rect; generic named draggable markers with drag-delta resolver, clamp, and zero-crossing snap, plus `markerHandleRect` a top-strip grab tab distinct from a marker's full-height column, so two markers that share a frame stay independently grabbable (the column goes to the first in draw order; the tab, asked first, resolves the other).
- `waveform_view` — the WAVEFORM band's interior: `resolveLaneSplit` is THE lane-split decision (two lanes only when the mode is stereo AND the source has a second channel — a mono source under stereo mode is dual-mono and draws one lane), free of any pixel geometry so the meter's bar count can ask the same question without a band rect; `waveformSurface` folds it and then measures it against the band, which is why its `laneCount` can still report 1 for a Stereo split on a band too thin to divide. It also yields **the** overlay area, and `laneEnvelope` splits one multi-channel envelope pass per lane. Also maps frame span linearly across a rect, plus generic named draggable markers with a drag-delta resolver, clamp, and the zero-crossing snap. The snap is RADIUS-BOUNDED (`snapToZeroCrossing`), the radius denominated in PIXELS and converted through `xToFrame`; `nearestZeroCrossing` beside it is the unbounded primitive and is NOT what a drag applies. Ctrl defeats the snap outright at the shell (`editor_input_waveform.cpp`), the same "get out of the way, I want exactness" role it plays on the knobs' fine drag. `markerHandleRect` is a top-strip grab tab distinct from a marker's full-height column, so two markers that share a frame stay independently grabbable the column goes to the first in draw order, the tab, asked first, resolves the other.
- **Overlay contract (consumed by later waveform work).** `WaveformSurface::overlay` — equivalently the standalone `waveformOverlayArea(band)` — is the band's DRAWN COLUMN SPAN at the band's full height, in both modes: same inset and same width as `component_geometry`'s `waveformColumnCount`, so overlay pixel and waveform column are one pixel and every overlay lands on the column that draws the frame it names. Deriving that width instead of restating the inset is what keeps the two chains from drifting apart again. Everything riding the waveform (the amp-envelope trace and its node handles, the start/loop markers, the loop region) draws ONCE into it, spanning both stacked lanes; hit-testing resolves against the same area so a grab in the lower lane reaches them. Anything drawn or hit-tested per lane is a duplicate and a defect — structurally enforced: `overlay` is the distinct `OverlayArea` type (`editor_geometry`), not `Rect`, so every overlay-consuming API (`frameToX`/`markerAtPoint`/`resolveDragFrame`, `envelope_edit`'s `nodeAtPoint`/`resolveNodeDrag`, `envelope_overlay`'s `buildEnvelopePolyline`) rejects a lane rect at compile time rather than silently accepting one.
- **The four marks.** One grammar — line + shaped cap + label — over START / LOOP / END / XFADE. Which of them are PRESENT is the mode's answer, and drawn iff grabbable: Trigger carries START alone (the loop pair and the fade are absent, not dim), Gate always carries the pair so the drag-to-set-loop gesture survives the enable being off, and the fade needs an active loop to have a seam. `markerHandleRect` IS the cap: every mark's is the same rect shape, only the glyph inside differs, which is what keeps the claim arbitration seeing one nominal cap area. `capAtPoint` resolves caps in the REVERSE of the column order, so any coincident PAIR stays separable (one answers its cap, the other its column) and the crossfade — the one mark with no column — can never be shadowed. `layoutMarkLabels` places the promoted (grabbed/hovered) mark first and suppresses any box that would overlap one already placed. `crossfadeWedgeHeight` is the ONE ramp both the audible region and the ingredient ghost draw, because they are the same fade weight over the two spans it mixes.
- `loop_marks` — the loop enable's state machine, split from the geometry above on the axis the surface already has: that says where a mark is, this says what the loop IS. `SampleLoop::hasLoop` is the single authority and `resolveLoopMarks`/`applyLoopMarks` are its only two folds — the resolve re-parks on `defaultLoopBounds` only when the span is one `resolveLoop` would refuse (so a user's off keeps its positions and `parked` separates the two OFF states), and the write folds collapse-to-off in and ties the crossfade to the SPAN rather than to the enable. Links `loop_span` so the span the user is offered and the span the engine accepts stay one definition.
+6 -1
View File
@@ -28,7 +28,12 @@ VelocityCurve::Box splineOverlayBox(const OverlayArea& area) {
WaveformClaimant resolveWaveformClaim(const WaveformClaim& node, const WaveformClaim& tab,
const WaveformClaim& marker, SplineGesture gesture) {
if (gesture == SplineGesture::kControlLeft && node.hit) return WaveformClaimant::kNode;
// The override is for a node with NOTHING else in the running: a cap or column also hit
// must fall through to the ordinary smallest-area arbitration below, exactly like a plain
// left-click, so Ctrl pressed before the button can never steal a mark grab out from under
// the cursor.
if (gesture == SplineGesture::kControlLeft && node.hit && !tab.hit && !marker.hit)
return WaveformClaimant::kNode;
if (node.hit && (!tab.hit || node.area <= tab.area) && (!marker.hit || node.area <= marker.area))
return WaveformClaimant::kNode;
if (tab.hit && (!marker.hit || tab.area <= marker.area)) return WaveformClaimant::kTab;
+5 -2
View File
@@ -75,8 +75,11 @@ enum class WaveformClaimant { kNone, kNode, kTab, kMarker };
// editor_input_waveform.cpp's mouseDownWaveform for the live constants). Every mark's cap is
// one markerHandleRect, so the `tab` slot carries ONE nominal area however many marks feed it;
// which mark it resolves to is waveform_view's capAtPoint, not this. A control-click has no
// cap/column meaning (they answer plain grabs only), so it resolves to the node whenever the
// node is in the running, regardless of area.
// cap/column meaning (only the node's hard/smooth toggle answers it), so it claims the node
// outright ONLY when no cap or column also hits — a cap or column in the running instead falls
// through to the ordinary smallest-area arbitration below, same as a plain click. Ctrl must
// never be able to steal a mark grab out from under the cursor merely because it was pressed
// before the button.
WaveformClaimant resolveWaveformClaim(const WaveformClaim& node, const WaveformClaim& tab,
const WaveformClaim& marker, SplineGesture gesture);
+38 -11
View File
@@ -178,17 +178,15 @@ std::int64_t resolveDragFrame(const OverlayArea& area, std::int64_t frameCount,
return xToFrame(area, frameCount, grabX + dxPixels);
}
std::int64_t nearestZeroCrossing(const AudioSample* pcm, std::int64_t frames,
std::int64_t target) {
if (pcm == nullptr || frames < 2) return clampFrame(target, frames > 0 ? frames - 1 : 0);
// Clamp target into a valid sample index [0, frames).
std::int64_t t = target;
if (t < 0) t = 0;
if (t > frames - 1) t = frames - 1;
namespace {
// The fan-out both entry points below share, so the two cannot grow two search orders: at each
// distance d probe t-d before t+d, which is what resolves an equidistant tie to the LOWER frame.
// Answers -1 when no crossing lies within `maxDistance` — the caller decides what that means.
std::int64_t crossingWithin(const AudioSample* pcm, std::int64_t frames, std::int64_t t,
std::int64_t maxDistance) {
// A crossing lives at frame i (1 <= i < frames) when sign(pcm[i-1]) != sign(pcm[i]) OR
// pcm[i] == 0. isCrossing(i) tests exactly that. We fan out from t: at each distance d we
// probe t-d before t+d, so an equidistant tie resolves to the LOWER frame (deterministic).
// pcm[i] == 0.
auto isCrossing = [&](std::int64_t i) -> bool {
if (i < 1 || i >= frames) return false;
const AudioSample a = pcm[i - 1];
@@ -198,7 +196,7 @@ std::int64_t nearestZeroCrossing(const AudioSample* pcm, std::int64_t frames,
};
if (isCrossing(t)) return t;
for (std::int64_t d = 1; d < frames; ++d) {
for (std::int64_t d = 1; d <= maxDistance; ++d) {
const std::int64_t lo = t - d;
if (lo >= 1 && isCrossing(lo)) return lo; // lower side wins the tie
const std::int64_t hi = t + d;
@@ -206,7 +204,36 @@ std::int64_t nearestZeroCrossing(const AudioSample* pcm, std::int64_t frames,
// Stop once both probes have run off both ends — no crossing anywhere.
if (lo < 1 && hi >= frames) break;
}
return t; // no sign change in the whole buffer -> keep the raw (clamped) target
return -1;
}
// Clamp into a valid sample index [0, frames).
std::int64_t clampSampleIndex(std::int64_t target, std::int64_t frames) {
return clampFrame(target, frames > 0 ? frames - 1 : 0);
}
} // namespace
std::int64_t nearestZeroCrossing(const AudioSample* pcm, std::int64_t frames,
std::int64_t target) {
const std::int64_t t = clampSampleIndex(target, frames);
if (pcm == nullptr || frames < 2) return t;
// `frames` bounds every reachable distance from any t in [0, frames), so this is the whole
// buffer.
const std::int64_t c = crossingWithin(pcm, frames, t, frames);
return c >= 0 ? c : t; // no sign change anywhere -> keep the raw (clamped) target
}
std::int64_t zeroCrossingSnapFrames(const OverlayArea& area, std::int64_t frameCount) {
return xToFrame(area, frameCount, area.rect.x + kZeroCrossingSnapPx);
}
std::int64_t snapToZeroCrossing(const AudioSample* pcm, std::int64_t frames, std::int64_t target,
std::int64_t maxDistanceFrames) {
const std::int64_t t = clampSampleIndex(target, frames);
if (pcm == nullptr || frames < 2 || maxDistanceFrames < 0) return t;
const std::int64_t c = crossingWithin(pcm, frames, t, maxDistanceFrames);
return c >= 0 ? c : t; // nothing that near -> the mark stays where it was dropped
}
} // namespace reasampler::instrument::ui
+41 -5
View File
@@ -185,12 +185,48 @@ int markerAtPoint(const OverlayArea& area, std::int64_t frameCount, const std::i
std::int64_t resolveDragFrame(const OverlayArea& area, std::int64_t frameCount,
std::int64_t startFrame, int dxPixels);
// Nearest zero-crossing frame to `target` in the mono PCM, for loop/start snap. A crossing is a
// frame i (1 <= i < frames) where pcm[i-1] and pcm[i] differ in sign (pcm[i] == 0 snaps to i).
// Search fans out symmetrically from the clamped target; an equidistant tie resolves to the
// lower frame. No sign change anywhere (or fewer than 2 frames) returns the clamped target
// unchanged.
// --- The zero-crossing snap ----------------------------------------------------------------
// Nearest zero-crossing frame to `target` in the mono PCM. A crossing is a frame i
// (1 <= i < frames) where pcm[i-1] and pcm[i] differ in sign (pcm[i] == 0 snaps to i). Search
// fans out symmetrically from the clamped target; an equidistant tie resolves to the lower
// frame. No sign change anywhere (or fewer than 2 frames) returns the clamped target unchanged.
//
// This answers WHERE the nearest crossing is, over the whole buffer. It is not what a drag
// should apply — see snapToZeroCrossing. No production caller: the drag applies the bounded
// entry. Keep this one anyway — it is the differential oracle the radius tests check the bounded
// entry against (dense material must equal it exactly; sparse and single-cycle material must
// not), and re-adopting it as a drag snap is the exact defect snapToZeroCrossing's own header
// warns against.
std::int64_t nearestZeroCrossing(const AudioSample* pcm, std::int64_t frames,
std::int64_t target);
// How far, in PIXELS, a mark may be pulled to reach a crossing. Aliases the mark's own grab band
// on purpose: the snap may move a mark only as far as the pointer could have been from it and
// still have grabbed it. `[verify — DAW]` a displacement inside the neighbourhood the user was
// already pointing at is one they cannot see — asserted from the geometry, not observed by eye
// in a live editor window.
//
// PIXELS rather than frames because the drag itself resolves in pixels — resolveDragFrame answers
// the column's own first frame, so a frame radius under one column's span would be unreachable on
// a long capture, and a fixed frame radius means a different VISIBLE distance at every sample
// length.
inline constexpr int kZeroCrossingSnapPx = kMarkerGrabWidth;
// That radius in frames for this overlay, read off THE mapping rather than a second ratio.
// Answers 0 below one frame per pixel, which is right: at that zoom the user is placing
// individual frames, and only a mark dropped exactly on a crossing snaps.
std::int64_t zeroCrossingSnapFrames(const OverlayArea& area, std::int64_t frameCount);
// THE snap a marker drag applies: the nearest crossing WITHIN maxDistanceFrames of the clamped
// target, or the target itself when none is that near. Same fan-out and same tie rule as
// nearestZeroCrossing.
//
// The radius is what makes this a snap rather than a constraint. Unbounded, the search always
// finds something: on single-cycle material, whose whole ~800-frame buffer holds one or two
// crossings, it pinned the loop marks hundreds of frames from where they were dropped — halving
// the loop and doubling the pitch. Do not remove the bound.
std::int64_t snapToZeroCrossing(const AudioSample* pcm, std::int64_t frames, std::int64_t target,
std::int64_t maxDistanceFrames);
} // namespace reasampler::instrument::ui
+8
View File
@@ -311,3 +311,11 @@ against a performance budget — they are there because `VoiceEngine::applyLiveT
"channel identity derives from `app_version` accessors, no scattered `#ifdef`s" —
`INLINE_UID` needs literal brace-init tokens, so it can't route through a runtime
string accessor.
- **Ctrl held during a waveform marker drag defeats the zero-crossing snap outright**
(`editor_input_waveform.cpp`'s `dragWaveform`, reading `dragModifiers().ctrl` — the same
"get out of the way, I want exactness" role Ctrl plays as the knobs' fine drag). It is
undiscoverable by design — no cursor cue, no label — so this note is its only home; the
radius itself (`core/instrument/ui/waveform_view`'s `snapToZeroCrossing`) is documented there,
not here. `resolveWaveformClaim` (`core/instrument/ui/spline_edit`) is the reason Ctrl held
BEFORE mouse-down still reaches the mark rather than stealing a coincident envelope-node grab
or hard/smooth toggle.
@@ -282,13 +282,16 @@ void ReaSamplerEditor::dragWaveform(const FaceLayout& fl, int x, int y) {
dragStartMarkers_.crossfade};
std::int64_t newFrame = resolveDragFrame(overlay, frames, startVals[idx], dx);
// Snap to the nearest zero crossing in the decoded PCM. Pure over the cached mono
// frames — no host types, no file I/O. The crossfade handle is exempt: it sets a fade
// LENGTH, and the whole point of the fade is that its edges need no zero crossing.
// Snap to a zero crossing in the decoded PCM, but only one within kZeroCrossingSnapPx of
// where the mark was dropped. Pure over the cached mono frames — no host types, no file I/O.
// The crossfade handle is exempt: it sets a fade LENGTH, and the whole point of the fade is
// that its edges need no zero crossing. Ctrl defeats the snap outright, the same "get out of
// the way, I want exactness" role it plays as the knobs' fine drag. `[verify — DAW]` this
// `GetKeyState` read has no test target — nothing in CI observes the defeat actually landing.
const std::vector<AudioSample>& pcm = monoPcmFor(selectedId_);
if (!pcm.empty() && waveMarker_ != WaveMarker::kCrossfade) {
newFrame = nearestZeroCrossing(pcm.data(), static_cast<std::int64_t>(pcm.size()),
newFrame);
if (!pcm.empty() && waveMarker_ != WaveMarker::kCrossfade && !dragModifiers().ctrl) {
newFrame = snapToZeroCrossing(pcm.data(), frames, newFrame,
zeroCrossingSnapFrames(overlay, frames));
}
// Build the edited marker set from the snapshot, moving only the grabbed marker, then