From 0b689153712afa70444bb256a91969f0c9297c4b Mon Sep 17 00:00:00 2001 From: Marlin Forbes Date: Sat, 15 Aug 2026 14:47:22 +0200 Subject: [PATCH] Add proximity rhythm audition modes --- CMakeLists.txt | 2 + README.md | 4 +- Source/App/MainComponent.cpp | 72 ++++++ Source/Engine/EngineCommandQueue.h | 3 + Source/Engine/EngineController.cpp | 9 + Source/Engine/EngineController.h | 1 + Source/Engine/ProximityRhythmMapping.cpp | 160 +++++++++++++ Source/Engine/ProximityRhythmMapping.h | 66 ++++++ Source/Engine/SpatialWorld.cpp | 7 + Source/Engine/SpatialWorld.h | 2 + Source/Engine/TransportEngine.cpp | 254 +++++++++++++++++++-- Source/Engine/TransportEngine.h | 42 ++++ Source/UI/BridgeProtocol.cpp | 18 ++ Source/UI/BridgeProtocol.h | 3 + Tests/DriftTests.cpp | 273 ++++++++++++++++++++++- Tests/TransportStressTests.cpp | 32 +++ docs/TECHNICAL-DESIGN.md | 36 +++ ui/src/App.test.tsx | 60 ++++- ui/src/App.tsx | 54 +++++ ui/src/PhraseWorld.tsx | 19 ++ ui/src/bridge/transportBridge.ts | 115 +++++++++- ui/src/dragInteraction.test.ts | 11 + ui/src/styles.css | 22 +- ui/src/worldInterpolation.test.ts | 11 + 24 files changed, 1245 insertions(+), 31 deletions(-) create mode 100644 Source/Engine/ProximityRhythmMapping.cpp create mode 100644 Source/Engine/ProximityRhythmMapping.h diff --git a/CMakeLists.txt b/CMakeLists.txt index e7a0bdc..52d9a82 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -60,6 +60,8 @@ add_library(DriftEngine STATIC Source/Engine/Clock.h Source/Engine/EngineCommandQueue.cpp Source/Engine/EngineCommandQueue.h + Source/Engine/ProximityRhythmMapping.cpp + Source/Engine/ProximityRhythmMapping.h Source/Engine/SpatialWorld.cpp Source/Engine/SpatialWorld.h Source/Engine/SpeedActivityMapping.cpp diff --git a/README.md b/README.md index c5bf411..0db90e3 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,8 @@ New contacts are resolved in the table's stable pair order. If simultaneous cont Phrase speed also selects authored material. Native velocity magnitude is normalized against the maximum throw speed and smoothed with a deterministic 250 ms filter. Each phrase begins normal (`A`), slows into sparse (`C`), or accelerates into active (`B`). Hysteresis keeps the bands stable: normal enters sparse at `0.015` and sparse returns at `0.040`; normal enters active at `0.450` and active returns at `0.300`. Band changes take effect at the next eligible bar. Speed observation pauses during Freeze Motion and direct dragging, while audio playback continues. A collision targeting the same phrase and bar replaces a pending speed change. +Proximity currently has two deliberately temporary audition modes. Both derive a loose, linked, or tight coupling level from the smoothed surface gap between every phrase pair, with stable changes taking effect at the next eligible unscheduled bar. **Rhythm profiles** snap nearby phrases toward half-beat or beat grids without changing their notes, durations, or dynamics. **Shared accents** leave timing and density untouched and emphasize notes that already begin together. The selector changes modes on the next bar so the alternatives can be compared during uninterrupted playback; neither is yet designated as the production mapping. + ## Architecture Drift is designed as a native **JUCE** desktop application with an embedded **React** interface. **PixiJS** is the initial renderer for the spatial world. @@ -100,7 +102,7 @@ Drift is in the design and initial implementation phase. The first development b 5. [Prove transport stability under simulated UI stress](https://github.com/datashaman/drift/issues/5) 6. [Validate ten-minute playback through a real MIDI device](https://github.com/datashaman/drift/issues/6) -The native shell now connects React Play, Stop, Freeze Motion, BPM, MIDI-output, and direct phrase-drag controls to a native-owned monotonic transport and a four-role composition: drums, bass, chords, and melody. Stop freezes both playback and movement; Freeze Motion pauses only autonomous movement so phrases can be caught and repositioned while MIDI continues uninterrupted. Untouched phrases retain their velocity for resume, while a phrase manipulated during the freeze is released stationary. Drift schedules every phrase from the same transport to its assigned MIDI channel and advances the phrase bodies in a bounded normalized world at a fixed 120 Hz. Validated pointer intent crosses a bounded, coalescing command queue; PixiJS follows the pointer optimistically and reconciles to latest-state native snapshots at 30 Hz. A bounded recent pointer sample window gives each release a native-owned throw velocity, while stationary releases settle and edge or corner throws reflect inside the field. Every phrase now has three compatible authored variants. Both unique phrase collisions and stable speed-band crossings queue deterministic changes at the next eligible unscheduled bar, with collisions taking priority at a shared boundary. Physics and input pressure remain independent of musical time, and the interface exposes motion state, raw and smoothed phrase speed, stable and pending activity bands, current/pending variants, pair mappings, transition counts, timing, catch-up, queue, coalescing, rejection, and snapshot diagnostics. +The native shell now connects React Play, Stop, Freeze Motion, BPM, MIDI-output, proximity-audition, and direct phrase-drag controls to a native-owned monotonic transport and a four-role composition: drums, bass, chords, and melody. Stop freezes both playback and movement; Freeze Motion pauses only autonomous movement so phrases can be caught and repositioned while MIDI continues uninterrupted. Untouched phrases retain their velocity for resume, while a phrase manipulated during the freeze is released stationary. Drift schedules every phrase from the same transport to its assigned MIDI channel and advances the phrase bodies in a bounded normalized world at a fixed 120 Hz. Validated pointer intent crosses a bounded, coalescing command queue; PixiJS follows the pointer optimistically and reconciles to latest-state native snapshots at 30 Hz. A bounded recent pointer sample window gives each release a native-owned throw velocity, while stationary releases settle and edge or corner throws reflect inside the field. Every phrase now has three compatible authored variants. Unique collisions, stable speed-band crossings, and stable pair-coupling changes queue deterministic changes at the next eligible unscheduled bar. Proximity transforms the resolved collision/speed material rather than selecting another variant. Physics and input pressure remain independent of musical time, and the interface exposes motion state, phrase speeds, activity bands, variants, exact pair proximity and coupling state, audition mode, transition counts, timing, catch-up, queue, coalescing, rejection, and snapshot diagnostics. The native/UI bridge uses a validated protocol-versioned envelope. Invalid commands produce structured rejection events without mutating engine state, and every React load performs a fresh handshake that restores the current authoritative transport state without restarting playback. diff --git a/Source/App/MainComponent.cpp b/Source/App/MainComponent.cpp index d759265..a7824e4 100644 --- a/Source/App/MainComponent.cpp +++ b/Source/App/MainComponent.cpp @@ -106,6 +106,11 @@ void MainComponent::handleCommand (juce::var command) engineCommand.type = drift::engine::EngineCommandType::worldSetMotionPaused; engineCommand.motionPaused = validated.motionPaused; break; + case drift::ui::BridgeCommandType::proximitySetAuditionMode: + engineCommand.type = drift::engine::EngineCommandType::proximitySetAuditionMode; + engineCommand.proximityMode + = *drift::engine::proximityAuditionModeForName (validated.proximityMode); + break; case drift::ui::BridgeCommandType::transportSetTempo: engineCommand.type = drift::engine::EngineCommandType::transportSetTempo; break; @@ -239,6 +244,20 @@ void MainComponent::publishState() state.transport.diagnostics.speedIntentSuppressedCount)); diagnostics->setProperty ("speedTransitionAppliedCount", static_cast ( state.transport.diagnostics.speedTransitionAppliedCount)); + diagnostics->setProperty ("proximityLevelChangeCount", static_cast ( + state.transport.diagnostics.proximityLevelChangeCount)); + diagnostics->setProperty ("proximityIntentQueuedCount", static_cast ( + state.transport.diagnostics.proximityIntentQueuedCount)); + diagnostics->setProperty ("proximityIntentCoalescedCount", static_cast ( + state.transport.diagnostics.proximityIntentCoalescedCount)); + diagnostics->setProperty ("proximityIntentSuppressedCount", static_cast ( + state.transport.diagnostics.proximityIntentSuppressedCount)); + diagnostics->setProperty ("proximityTransitionAppliedCount", static_cast ( + state.transport.diagnostics.proximityTransitionAppliedCount)); + diagnostics->setProperty ("proximityModeQueuedCount", static_cast ( + state.transport.diagnostics.proximityModeQueuedCount)); + diagnostics->setProperty ("proximityModeAppliedCount", static_cast ( + state.transport.diagnostics.proximityModeAppliedCount)); diagnostics->setProperty ( "commandQueueDepth", static_cast (state.commandQueue.queueDepth)); diagnostics->setProperty ( @@ -284,6 +303,21 @@ void MainComponent::publishWorldSnapshot (const drift::engine::ControllerSnapsho payload->setProperty ("sequence", static_cast (++worldSnapshotSequence)); payload->setProperty ("engineTimeMs", state.transport.engineTimeSeconds * 1000.0); payload->setProperty ("motionPaused", state.transport.motionPaused); + payload->setProperty ( + "proximityMode", + juce::String { drift::engine::proximityAuditionModeName ( + state.transport.proximityMode) }); + payload->setProperty ( + "pendingProximityMode", + state.transport.pendingProximityMode + ? juce::var { juce::String { drift::engine::proximityAuditionModeName ( + *state.transport.pendingProximityMode) } } + : juce::var {}); + payload->setProperty ( + "pendingProximityModeApplyBeat", + state.transport.pendingProximityModeApplyBeat + ? juce::var { *state.transport.pendingProximityModeApplyBeat } + : juce::var {}); auto* transport = new juce::DynamicObject(); transport->setProperty ("playing", state.transport.playing); @@ -359,6 +393,30 @@ void MainComponent::publishWorldSnapshot (const drift::engine::ControllerSnapsho } payload->setProperty ("collisions", juce::var { collisions }); + juce::Array proximityPairs; + for (const auto& pair : state.transport.proximityPairs) + { + auto* pairObject = new juce::DynamicObject(); + pairObject->setProperty ("firstPhraseId", juce::String { pair.firstPhraseId }); + pairObject->setProperty ("secondPhraseId", juce::String { pair.secondPhraseId }); + pairObject->setProperty ("rawProximity", pair.rawProximity); + pairObject->setProperty ("smoothedProximity", pair.smoothedProximity); + pairObject->setProperty ( + "couplingLevel", + juce::String { drift::engine::couplingLevelName (pair.couplingLevel) }); + pairObject->setProperty ( + "pendingCouplingLevel", + pair.pendingCouplingLevel + ? juce::var { juce::String { drift::engine::couplingLevelName ( + *pair.pendingCouplingLevel) } } + : juce::var {}); + pairObject->setProperty ( + "pendingApplyBeat", + pair.pendingApplyBeat ? juce::var { *pair.pendingApplyBeat } : juce::var {}); + proximityPairs.add (juce::var { pairObject }); + } + payload->setProperty ("proximityPairs", juce::var { proximityPairs }); + auto* diagnostics = new juce::DynamicObject(); diagnostics->setProperty ( "physicsStepCount", @@ -387,6 +445,20 @@ void MainComponent::publishWorldSnapshot (const drift::engine::ControllerSnapsho state.transport.diagnostics.speedIntentSuppressedCount)); diagnostics->setProperty ("speedTransitionAppliedCount", static_cast ( state.transport.diagnostics.speedTransitionAppliedCount)); + diagnostics->setProperty ("proximityLevelChangeCount", static_cast ( + state.transport.diagnostics.proximityLevelChangeCount)); + diagnostics->setProperty ("proximityIntentQueuedCount", static_cast ( + state.transport.diagnostics.proximityIntentQueuedCount)); + diagnostics->setProperty ("proximityIntentCoalescedCount", static_cast ( + state.transport.diagnostics.proximityIntentCoalescedCount)); + diagnostics->setProperty ("proximityIntentSuppressedCount", static_cast ( + state.transport.diagnostics.proximityIntentSuppressedCount)); + diagnostics->setProperty ("proximityTransitionAppliedCount", static_cast ( + state.transport.diagnostics.proximityTransitionAppliedCount)); + diagnostics->setProperty ("proximityModeQueuedCount", static_cast ( + state.transport.diagnostics.proximityModeQueuedCount)); + diagnostics->setProperty ("proximityModeAppliedCount", static_cast ( + state.transport.diagnostics.proximityModeAppliedCount)); diagnostics->setProperty ( "droppedSnapshotCount", static_cast (droppedWorldSnapshotCount)); diagnostics->setProperty ( diff --git a/Source/Engine/EngineCommandQueue.h b/Source/Engine/EngineCommandQueue.h index d7eae1c..e4f37f5 100644 --- a/Source/Engine/EngineCommandQueue.h +++ b/Source/Engine/EngineCommandQueue.h @@ -1,6 +1,7 @@ #pragma once #include "Music/Phrase.h" +#include "Engine/ProximityRhythmMapping.h" #include #include @@ -18,6 +19,7 @@ enum class EngineCommandType transportPlay, transportStop, worldSetMotionPaused, + proximitySetAuditionMode, transportSetTempo, midiSelectOutput, phraseDragStart, @@ -35,6 +37,7 @@ struct EngineCommand std::string outputId; double bpm = 120.0; bool motionPaused = false; + ProximityAuditionMode proximityMode = ProximityAuditionMode::rhythmProfiles; music::NormalizedPosition position; music::NormalizedVelocity velocity; }; diff --git a/Source/Engine/EngineController.cpp b/Source/Engine/EngineController.cpp index 287fe38..0417041 100644 --- a/Source/Engine/EngineController.cpp +++ b/Source/Engine/EngineController.cpp @@ -36,6 +36,12 @@ void EngineController::setMotionPaused (bool paused) engine.setMotionPaused (paused); } +void EngineController::setProximityAuditionMode (ProximityAuditionMode mode) +{ + const std::scoped_lock lock { mutex }; + engine.setProximityAuditionMode (mode); +} + bool EngineController::setBpm (double bpm) { const std::scoped_lock lock { mutex }; @@ -117,6 +123,9 @@ void EngineController::applyCommand (const EngineCommand& command) case EngineCommandType::worldSetMotionPaused: engine.setMotionPaused (command.motionPaused); break; + case EngineCommandType::proximitySetAuditionMode: + engine.setProximityAuditionMode (command.proximityMode); + break; case EngineCommandType::transportSetTempo: engine.setBpm (command.bpm); break; diff --git a/Source/Engine/EngineController.h b/Source/Engine/EngineController.h index fe03bc8..1231b21 100644 --- a/Source/Engine/EngineController.h +++ b/Source/Engine/EngineController.h @@ -28,6 +28,7 @@ class EngineController final : private juce::HighResolutionTimer void play(); void stop(); void setMotionPaused (bool paused); + void setProximityAuditionMode (ProximityAuditionMode mode); bool setBpm (double bpm); bool selectMidiOutput (const std::string& outputId); CommandEnqueueResult enqueueCommand (EngineCommand command); diff --git a/Source/Engine/ProximityRhythmMapping.cpp b/Source/Engine/ProximityRhythmMapping.cpp new file mode 100644 index 0000000..aef1fc4 --- /dev/null +++ b/Source/Engine/ProximityRhythmMapping.cpp @@ -0,0 +1,160 @@ +#include "Engine/ProximityRhythmMapping.h" + +#include +#include + +namespace drift::engine +{ +const char* couplingLevelName (CouplingLevel level) noexcept +{ + switch (level) + { + case CouplingLevel::loose: return "loose"; + case CouplingLevel::linked: return "linked"; + case CouplingLevel::tight: return "tight"; + } + return "loose"; +} + +const char* proximityAuditionModeName (ProximityAuditionMode mode) noexcept +{ + switch (mode) + { + case ProximityAuditionMode::rhythmProfiles: return "rhythmProfiles"; + case ProximityAuditionMode::sharedAccents: return "sharedAccents"; + } + return "rhythmProfiles"; +} + +std::optional proximityAuditionModeForName ( + const std::string& name) noexcept +{ + if (name == "rhythmProfiles") return ProximityAuditionMode::rhythmProfiles; + if (name == "sharedAccents") return ProximityAuditionMode::sharedAccents; + return std::nullopt; +} + +int couplingLevelRank (CouplingLevel level) noexcept +{ + return static_cast (level); +} + +CouplingLevel couplingLevelAfterObservation (CouplingLevel current, + double proximity) noexcept +{ + proximity = std::clamp (proximity, 0.0, 1.0); + switch (current) + { + case CouplingLevel::loose: + return proximity >= ProximityTracker::looseToLinkedThreshold + ? CouplingLevel::linked : current; + case CouplingLevel::linked: + if (proximity <= ProximityTracker::linkedToLooseThreshold) + return CouplingLevel::loose; + if (proximity >= ProximityTracker::linkedToTightThreshold) + return CouplingLevel::tight; + return current; + case CouplingLevel::tight: + return proximity <= ProximityTracker::tightToLinkedThreshold + ? CouplingLevel::linked : current; + } + return CouplingLevel::loose; +} + +double normalizedPairProximity (const PhraseBody& first, + const PhraseBody& second) noexcept +{ + const auto centreDistance = std::hypot ( + first.position.x - second.position.x, + first.position.y - second.position.y); + const auto surfaceGap = std::max (0.0, centreDistance - first.radius - second.radius); + return 1.0 - std::clamp ( + surfaceGap / ProximityTracker::influenceSurfaceGap, 0.0, 1.0); +} + +std::optional ProximityTracker::observe ( + double normalizedProximity, + std::size_t fixedStepCount) +{ + raw = std::clamp (normalizedProximity, 0.0, 1.0); + if (! initialized) + { + smoothed = raw; + initialized = true; + } + + if (fixedStepCount == 0) + return std::nullopt; + + const auto alpha = 1.0 - std::exp ( + -SpatialWorld::fixedStepSeconds / smoothingTimeConstantSeconds); + for (std::size_t step = 0; step < fixedStepCount; ++step) + smoothed += alpha * (raw - smoothed); + + const auto next = couplingLevelAfterObservation (level, smoothed); + if (next == level) + return std::nullopt; + level = next; + return level; +} + +double ProximityTracker::rawProximity() const noexcept { return raw; } +double ProximityTracker::smoothedProximity() const noexcept { return smoothed; } +CouplingLevel ProximityTracker::observedLevel() const noexcept { return level; } + +std::vector applyRhythmProfile ( + const std::vector& events, + CouplingLevel level, + double phraseLengthBeats) +{ + if (level == CouplingLevel::loose) + return events; + + const auto grid = level == CouplingLevel::linked ? 0.5 : 1.0; + std::vector transformed; + transformed.reserve (events.size()); + for (auto event : events) + { + event.beat = std::round (event.beat / grid) * grid; + if (event.beat >= phraseLengthBeats) + event.beat -= phraseLengthBeats; + + const auto duplicate = std::find_if ( + transformed.begin(), transformed.end(), [&event] (const auto& candidate) { + return candidate.note == event.note + && std::abs (candidate.beat - event.beat) < 1.0e-9; + }); + if (duplicate == transformed.end()) + transformed.push_back (event); + else + { + duplicate->velocity = std::max (duplicate->velocity, event.velocity); + duplicate->durationBeats = std::max ( + duplicate->durationBeats, event.durationBeats); + } + } + + std::sort (transformed.begin(), transformed.end(), [] (const auto& first, + const auto& second) { + if (first.beat < second.beat) return true; + if (second.beat < first.beat) return false; + return first.note < second.note; + }); + return transformed; +} + +int sharedAccentBoost (double onsetBeat, + const std::vector& partnerEvents, + CouplingLevel level) noexcept +{ + if (level == CouplingLevel::loose) + return 0; + const auto shared = std::any_of ( + partnerEvents.begin(), partnerEvents.end(), [onsetBeat] (const auto& event) { + return std::abs (event.beat - onsetBeat) < 1.0e-9; + }); + if (! shared) + return 0; + return level == CouplingLevel::tight ? 24 : 12; +} +} // namespace drift::engine diff --git a/Source/Engine/ProximityRhythmMapping.h b/Source/Engine/ProximityRhythmMapping.h new file mode 100644 index 0000000..be1c8a1 --- /dev/null +++ b/Source/Engine/ProximityRhythmMapping.h @@ -0,0 +1,66 @@ +#pragma once + +#include "Engine/SpatialWorld.h" +#include "Music/Phrase.h" + +#include +#include +#include +#include + +namespace drift::engine +{ +enum class CouplingLevel +{ + loose, + linked, + tight, +}; + +enum class ProximityAuditionMode +{ + rhythmProfiles, + sharedAccents, +}; + +const char* couplingLevelName (CouplingLevel level) noexcept; +const char* proximityAuditionModeName (ProximityAuditionMode mode) noexcept; +std::optional proximityAuditionModeForName ( + const std::string& name) noexcept; +CouplingLevel couplingLevelAfterObservation (CouplingLevel current, + double smoothedProximity) noexcept; +int couplingLevelRank (CouplingLevel level) noexcept; +double normalizedPairProximity (const PhraseBody& first, + const PhraseBody& second) noexcept; + +class ProximityTracker +{ +public: + static constexpr double influenceSurfaceGap = 0.40; + static constexpr double smoothingTimeConstantSeconds = 0.250; + static constexpr double looseToLinkedThreshold = 0.40; + static constexpr double linkedToLooseThreshold = 0.30; + static constexpr double linkedToTightThreshold = 0.75; + static constexpr double tightToLinkedThreshold = 0.65; + + std::optional observe (double normalizedProximity, + std::size_t fixedStepCount = 1); + double rawProximity() const noexcept; + double smoothedProximity() const noexcept; + CouplingLevel observedLevel() const noexcept; + +private: + double raw = 0.0; + double smoothed = 0.0; + CouplingLevel level = CouplingLevel::loose; + bool initialized = false; +}; + +std::vector applyRhythmProfile ( + const std::vector& events, + CouplingLevel level, + double phraseLengthBeats); +int sharedAccentBoost (double onsetBeat, + const std::vector& partnerEvents, + CouplingLevel level) noexcept; +} // namespace drift::engine diff --git a/Source/Engine/SpatialWorld.cpp b/Source/Engine/SpatialWorld.cpp index 999d1db..84b994c 100644 --- a/Source/Engine/SpatialWorld.cpp +++ b/Source/Engine/SpatialWorld.cpp @@ -41,6 +41,7 @@ SpatialWorld::SpatialWorld (std::vector bodiesIn, double initialTime void SpatialWorld::advanceTo (double nowSeconds) { + latestStepBodySnapshots.clear(); const auto elapsedSeconds = std::max (0.0, nowSeconds - lastUpdateSeconds); lastUpdateSeconds = std::max (lastUpdateSeconds, nowSeconds); accumulatorSeconds += elapsedSeconds; @@ -50,6 +51,7 @@ void SpatialWorld::advanceTo (double nowSeconds) && stepCount < maximumCatchUpSteps) { integrateStep(); + latestStepBodySnapshots.push_back (phraseBodies); accumulatorSeconds -= fixedStepSeconds; ++stepCount; } @@ -189,6 +191,11 @@ const std::vector& SpatialWorld::bodies() const noexcept return phraseBodies; } +const std::vector>& SpatialWorld::stepBodySnapshots() const noexcept +{ + return latestStepBodySnapshots; +} + const SpatialWorldDiagnostics& SpatialWorld::diagnostics() const noexcept { return worldDiagnostics; diff --git a/Source/Engine/SpatialWorld.h b/Source/Engine/SpatialWorld.h index 5c81f0d..bb14ed7 100644 --- a/Source/Engine/SpatialWorld.h +++ b/Source/Engine/SpatialWorld.h @@ -67,6 +67,7 @@ class SpatialWorld const std::string& secondPhraseId) const; const std::vector& bodies() const noexcept; + const std::vector>& stepBodySnapshots() const noexcept; const SpatialWorldDiagnostics& diagnostics() const noexcept; std::size_t revision() const noexcept; @@ -95,6 +96,7 @@ class SpatialWorld SpatialWorldDiagnostics worldDiagnostics; std::map collisionPairs; std::vector pendingCollisionBegins; + std::vector> latestStepBodySnapshots; }; std::vector makePhraseBodies (const std::vector& phrases); diff --git a/Source/Engine/TransportEngine.cpp b/Source/Engine/TransportEngine.cpp index e5ac4c4..7d9af01 100644 --- a/Source/Engine/TransportEngine.cpp +++ b/Source/Engine/TransportEngine.cpp @@ -74,6 +74,27 @@ TransportEngine::TransportEngine (Clock& clockIn, music::MidiSink& sinkIn) 0, true); } + for (const auto& rule : collisionVariantRules()) + { + proximityPairs.push_back ({ + rule.firstPhraseId, + rule.secondPhraseId, + {}, + CouplingLevel::loose, + std::nullopt, + std::nullopt, + }); + const auto& first = *std::find_if ( + bodies.begin(), bodies.end(), [&rule] (const auto& body) { + return body.phraseId == rule.firstPhraseId; + }); + const auto& second = *std::find_if ( + bodies.begin(), bodies.end(), [&rule] (const auto& body) { + return body.phraseId == rule.secondPhraseId; + }); + proximityPairs.back().tracker.observe ( + normalizedPairProximity (first, second), 0); + } } void TransportEngine::play() @@ -102,6 +123,13 @@ void TransportEngine::stop() phrase.pendingVariantApplyBeat.reset(); pendingSpeedBands[phrase.id].reset(); } + for (auto& pair : proximityPairs) + { + pair.pendingLevel.reset(); + pair.pendingApplyBeat.reset(); + } + pendingProximityMode.reset(); + pendingProximityModeApplyBeat.reset(); } void TransportEngine::setMotionPaused (bool paused) @@ -112,6 +140,27 @@ void TransportEngine::setMotionPaused (bool paused) world.setMotionPaused (paused); } +void TransportEngine::setProximityAuditionMode (ProximityAuditionMode mode) +{ + if (mode == proximityMode && ! pendingProximityMode) + return; + + const auto state = transport.snapshot(); + const auto earliestUnscheduledBeat = std::max (state.beatPosition, scheduledThroughBeat) + + timingToleranceSeconds; + const auto applyAtBeat = music::quantizeForward ( + earliestUnscheduledBeat, barLengthBeats); + if (mode == proximityMode) + { + pendingProximityMode.reset(); + pendingProximityModeApplyBeat.reset(); + return; + } + pendingProximityMode = mode; + pendingProximityModeApplyBeat = applyAtBeat; + ++diagnostics.proximityModeQueuedCount; +} + bool TransportEngine::setBpm (double bpm) { if (! transport.setBpm (bpm)) @@ -149,6 +198,7 @@ void TransportEngine::tick() const auto state = transport.snapshot(); processCollisionContacts (state.beatPosition); processSpeedActivity (state.beatPosition, fixedSteps); + processProximity (state.beatPosition); applyDueIntents (state.beatPosition); if (! state.playing) @@ -181,6 +231,66 @@ void TransportEngine::tick() diagnostics.schedulingWatermarkBeat, scheduledThroughBeat); } +void TransportEngine::processProximity (double currentBeat) +{ + for (const auto& bodies : world.stepBodySnapshots()) + { + for (auto& pair : proximityPairs) + { + const auto first = std::find_if ( + bodies.begin(), bodies.end(), [&pair] (const auto& body) { + return body.phraseId == pair.firstPhraseId; + }); + const auto second = std::find_if ( + bodies.begin(), bodies.end(), [&pair] (const auto& body) { + return body.phraseId == pair.secondPhraseId; + }); + if (first == bodies.end() || second == bodies.end()) + continue; + + const auto change = pair.tracker.observe ( + normalizedPairProximity (*first, *second)); + if (! change) + continue; + + ++diagnostics.proximityLevelChangeCount; + const auto earliestUnscheduledBeat = std::max (currentBeat, scheduledThroughBeat) + + timingToleranceSeconds; + const auto applyAtBeat = music::quantizeForward ( + earliestUnscheduledBeat, barLengthBeats); + + if (pair.pendingLevel && pair.pendingApplyBeat) + { + if (std::abs (*pair.pendingApplyBeat - applyAtBeat) + <= timingToleranceSeconds) + { + if (*change == pair.activeLevel) + { + pair.pendingLevel.reset(); + pair.pendingApplyBeat.reset(); + } + else + { + pair.pendingLevel = *change; + } + ++diagnostics.proximityIntentCoalescedCount; + } + else + { + ++diagnostics.proximityIntentSuppressedCount; + } + continue; + } + + if (*change == pair.activeLevel) + continue; + pair.pendingLevel = *change; + pair.pendingApplyBeat = applyAtBeat; + ++diagnostics.proximityIntentQueuedCount; + } + } +} + void TransportEngine::processCollisionContacts (double currentBeat) { auto contacts = world.consumeCollisionBegins(); @@ -306,6 +416,26 @@ void TransportEngine::applyDueIntents (double currentBeat) } pendingSpeedBands[phrase.id].reset(); } + + for (auto& pair : proximityPairs) + { + if (! pair.pendingLevel || ! pair.pendingApplyBeat + || currentBeat + timingToleranceSeconds < *pair.pendingApplyBeat) + continue; + pair.activeLevel = *pair.pendingLevel; + pair.pendingLevel.reset(); + pair.pendingApplyBeat.reset(); + ++diagnostics.proximityTransitionAppliedCount; + } + + if (pendingProximityMode && pendingProximityModeApplyBeat + && currentBeat + timingToleranceSeconds >= *pendingProximityModeApplyBeat) + { + proximityMode = *pendingProximityMode; + pendingProximityMode.reset(); + pendingProximityModeApplyBeat.reset(); + ++diagnostics.proximityModeAppliedCount; + } } void TransportEngine::schedulePhraseRange (const music::Phrase& phrase, @@ -313,32 +443,103 @@ void TransportEngine::schedulePhraseRange (const music::Phrase& phrase, double endBeat, music::MidiSink& targetSink) const { - if (! phrase.pendingVariantId || ! phrase.pendingVariantApplyBeat) + std::vector boundaries { startBeat, endBeat }; + const auto addBoundary = [&boundaries, startBeat, endBeat] ( + const std::optional& boundary) { + if (boundary && *boundary > startBeat && *boundary < endBeat) + boundaries.push_back (*boundary); + }; + addBoundary (phrase.pendingVariantApplyBeat); + addBoundary (pendingProximityModeApplyBeat); + for (const auto& pair : proximityPairs) + if (pair.firstPhraseId == phrase.id || pair.secondPhraseId == phrase.id) + addBoundary (pair.pendingApplyBeat); + + std::sort (boundaries.begin(), boundaries.end()); + boundaries.erase (std::unique (boundaries.begin(), boundaries.end()), boundaries.end()); + for (std::size_t index = 0; index + 1 < boundaries.size(); ++index) { - scheduler.scheduleRange (phrase, startBeat, endBeat, targetSink); - return; + const auto segmentStart = boundaries[index]; + const auto segmentEnd = boundaries[index + 1]; + scheduler.scheduleRange ( + phrase, + proximityEventsAt (phrase, segmentStart), + segmentStart, + segmentEnd, + targetSink); } +} - const auto applyAtBeat = *phrase.pendingVariantApplyBeat; - if (startBeat < applyAtBeat) +const std::vector& TransportEngine::baseEventsAt ( + const music::Phrase& phrase, + double beat) const +{ + if (phrase.pendingVariantId && phrase.pendingVariantApplyBeat + && beat + timingToleranceSeconds >= *phrase.pendingVariantApplyBeat) { - scheduler.scheduleRange ( - phrase, startBeat, std::min (endBeat, applyAtBeat), targetSink); + if (const auto* variant = music::findVariant (phrase, *phrase.pendingVariantId)) + return variant->events; } + return phrase.events; +} - if (endBeat <= applyAtBeat) - return; +std::vector TransportEngine::proximityEventsAt ( + const music::Phrase& phrase, + double beat) const +{ + auto mode = proximityMode; + if (pendingProximityMode && pendingProximityModeApplyBeat + && beat + timingToleranceSeconds >= *pendingProximityModeApplyBeat) + mode = *pendingProximityMode; + + const auto levelAt = [beat] (const ProximityPairRuntime& pair) { + if (pair.pendingLevel && pair.pendingApplyBeat + && beat + timingToleranceSeconds >= *pair.pendingApplyBeat) + return *pair.pendingLevel; + return pair.activeLevel; + }; - const auto* pendingVariant = music::findVariant (phrase, *phrase.pendingVariantId); - if (pendingVariant != nullptr) + const auto& base = baseEventsAt (phrase, beat); + if (mode == ProximityAuditionMode::rhythmProfiles) { - scheduler.scheduleRange ( - phrase, - pendingVariant->events, - std::max (startBeat, applyAtBeat), - endBeat, - targetSink); + auto maximumLevel = CouplingLevel::loose; + for (const auto& pair : proximityPairs) + { + if (pair.firstPhraseId == phrase.id || pair.secondPhraseId == phrase.id) + { + const auto level = levelAt (pair); + if (couplingLevelRank (level) > couplingLevelRank (maximumLevel)) + maximumLevel = level; + } + } + return applyRhythmProfile (base, maximumLevel, phrase.lengthBeats); + } + + auto accented = base; + for (auto& event : accented) + { + auto boost = 0; + for (const auto& pair : proximityPairs) + { + std::string partnerId; + if (pair.firstPhraseId == phrase.id) + partnerId = pair.secondPhraseId; + else if (pair.secondPhraseId == phrase.id) + partnerId = pair.firstPhraseId; + else + continue; + const auto partner = std::find_if ( + phrases.begin(), phrases.end(), [&partnerId] (const auto& candidate) { + return candidate.id == partnerId; + }); + if (partner == phrases.end()) + continue; + boost = std::max (boost, sharedAccentBoost ( + event.beat, baseEventsAt (*partner, beat), levelAt (pair))); + } + event.velocity = std::min (127, event.velocity + boost); } + return accented; } music::Phrase* TransportEngine::findPhrase (const std::string& phraseId) noexcept @@ -436,6 +637,21 @@ EngineSnapshot TransportEngine::snapshot() const }); } + std::vector proximitySnapshots; + proximitySnapshots.reserve (proximityPairs.size()); + for (const auto& pair : proximityPairs) + { + proximitySnapshots.push_back ({ + pair.firstPhraseId, + pair.secondPhraseId, + pair.tracker.rawProximity(), + pair.tracker.smoothedProximity(), + pair.activeLevel, + pair.pendingLevel, + pair.pendingApplyBeat, + }); + } + return { state.playing, world.motionPaused(), @@ -448,6 +664,10 @@ EngineSnapshot TransportEngine::snapshot() const sink.messageCount(), std::move (phraseSnapshots), std::move (collisionSnapshots), + std::move (proximitySnapshots), + proximityMode, + pendingProximityMode, + pendingProximityModeApplyBeat, snapshotDiagnostics, }; } diff --git a/Source/Engine/TransportEngine.h b/Source/Engine/TransportEngine.h index eda74c8..c1cc366 100644 --- a/Source/Engine/TransportEngine.h +++ b/Source/Engine/TransportEngine.h @@ -2,6 +2,7 @@ #include "Engine/Clock.h" #include "Engine/SpatialWorld.h" +#include "Engine/ProximityRhythmMapping.h" #include "Engine/SpeedActivityMapping.h" #include "Music/MidiSink.h" #include "Music/Phrase.h" @@ -32,6 +33,13 @@ struct EngineDiagnostics std::size_t speedIntentQueuedCount = 0; std::size_t speedIntentSuppressedCount = 0; std::size_t speedTransitionAppliedCount = 0; + std::size_t proximityLevelChangeCount = 0; + std::size_t proximityIntentQueuedCount = 0; + std::size_t proximityIntentCoalescedCount = 0; + std::size_t proximityIntentSuppressedCount = 0; + std::size_t proximityTransitionAppliedCount = 0; + std::size_t proximityModeQueuedCount = 0; + std::size_t proximityModeAppliedCount = 0; }; struct PhraseSnapshot @@ -64,6 +72,17 @@ struct CollisionSnapshot double cooldownRemainingSeconds = 0.0; }; +struct ProximityPairSnapshot +{ + std::string firstPhraseId; + std::string secondPhraseId; + double rawProximity = 0.0; + double smoothedProximity = 0.0; + CouplingLevel couplingLevel = CouplingLevel::loose; + std::optional pendingCouplingLevel; + std::optional pendingApplyBeat; +}; + struct EngineSnapshot { bool playing = false; @@ -77,6 +96,10 @@ struct EngineSnapshot std::size_t scheduledEventCount = 0; std::vector phrases; std::vector collisions; + std::vector proximityPairs; + ProximityAuditionMode proximityMode = ProximityAuditionMode::rhythmProfiles; + std::optional pendingProximityMode; + std::optional pendingProximityModeApplyBeat; EngineDiagnostics diagnostics; }; @@ -103,6 +126,7 @@ class TransportEngine void play(); void stop(); void setMotionPaused (bool paused); + void setProximityAuditionMode (ProximityAuditionMode mode); bool setBpm (double bpm); void reschedule(); void recordBridgeReconnect(); @@ -124,12 +148,17 @@ class TransportEngine void processCollisionContacts (double currentBeat); void processSpeedActivity (double currentBeat, std::size_t fixedStepCount); + void processProximity (double currentBeat); bool queueIntent (const MusicalIntent& intent); void applyDueIntents (double currentBeat); void schedulePhraseRange (const music::Phrase& phrase, double startBeat, double endBeat, music::MidiSink& targetSink) const; + const std::vector& baseEventsAt ( + const music::Phrase& phrase, double beat) const; + std::vector proximityEventsAt ( + const music::Phrase& phrase, double beat) const; music::Phrase* findPhrase (const std::string& phraseId) noexcept; music::MidiSink& sink; @@ -143,5 +172,18 @@ class TransportEngine std::map speedTrackers; std::map> pendingSpeedBands; std::size_t observedPhysicsStepCount = 0; + struct ProximityPairRuntime + { + std::string firstPhraseId; + std::string secondPhraseId; + ProximityTracker tracker; + CouplingLevel activeLevel = CouplingLevel::loose; + std::optional pendingLevel; + std::optional pendingApplyBeat; + }; + std::vector proximityPairs; + ProximityAuditionMode proximityMode = ProximityAuditionMode::rhythmProfiles; + std::optional pendingProximityMode; + std::optional pendingProximityModeApplyBeat; }; } // namespace drift::engine diff --git a/Source/UI/BridgeProtocol.cpp b/Source/UI/BridgeProtocol.cpp index 0748c09..b505015 100644 --- a/Source/UI/BridgeProtocol.cpp +++ b/Source/UI/BridgeProtocol.cpp @@ -41,6 +41,8 @@ std::optional commandTypeForName (const juce::String& type) if (type == "transport.play") return BridgeCommandType::transportPlay; if (type == "transport.stop") return BridgeCommandType::transportStop; if (type == "world.setMotionPaused") return BridgeCommandType::worldSetMotionPaused; + if (type == "proximity.setAuditionMode") + return BridgeCommandType::proximitySetAuditionMode; if (type == "transport.setTempo") return BridgeCommandType::transportSetTempo; if (type == "midi.selectOutput") return BridgeCommandType::midiSelectOutput; if (type == "phrase.dragStart") return BridgeCommandType::phraseDragStart; @@ -107,6 +109,18 @@ CommandDispatchResult validateCommandEnvelope (const juce::var& envelope) command.motionPaused = static_cast (paused); } + else if (*commandType == BridgeCommandType::proximitySetAuditionMode) + { + const auto mode = payloadObject->getProperty ("mode"); + if (! mode.isString() + || (mode.toString() != "rhythmProfiles" + && mode.toString() != "sharedAccents")) + { + return reject (command.messageId, CommandRejectionCode::invalidPayload, + "The proximity mode must be rhythmProfiles or sharedAccents"); + } + command.proximityMode = mode.toString().toStdString(); + } else if (*commandType == BridgeCommandType::transportSetTempo) { const auto bpm = payloadObject->getProperty ("bpm"); @@ -253,6 +267,10 @@ CommandDispatchResult dispatchCommandEnvelope (const juce::var& envelope, if (handlers.onWorldSetMotionPaused) handlers.onWorldSetMotionPaused (command.motionPaused); break; + case BridgeCommandType::proximitySetAuditionMode: + if (handlers.onProximitySetAuditionMode) + handlers.onProximitySetAuditionMode (command.proximityMode); + break; case BridgeCommandType::transportSetTempo: if (handlers.onTransportSetTempo) handlers.onTransportSetTempo (command.bpm); break; diff --git a/Source/UI/BridgeProtocol.h b/Source/UI/BridgeProtocol.h index 2bc0b5c..119b87c 100644 --- a/Source/UI/BridgeProtocol.h +++ b/Source/UI/BridgeProtocol.h @@ -17,6 +17,7 @@ enum class BridgeCommandType transportPlay, transportStop, worldSetMotionPaused, + proximitySetAuditionMode, transportSetTempo, midiSelectOutput, phraseDragStart, @@ -46,6 +47,7 @@ struct ValidatedBridgeCommand std::string messageId; double bpm = 120.0; bool motionPaused = false; + std::string proximityMode; std::string outputId; std::string phraseId; std::string dragSessionId; @@ -82,6 +84,7 @@ struct CommandHandlers std::function onPhraseThrow; std::function phraseIdExists; std::function onWorldSetMotionPaused; + std::function onProximitySetAuditionMode; }; CommandDispatchResult validateCommandEnvelope (const juce::var& envelope); diff --git a/Tests/DriftTests.cpp b/Tests/DriftTests.cpp index 43b7f36..5da16fc 100644 --- a/Tests/DriftTests.cpp +++ b/Tests/DriftTests.cpp @@ -4,6 +4,7 @@ #include "Engine/SpatialWorld.h" #include "Engine/TransportEngine.h" #include "Engine/SpeedActivityMapping.h" +#include "Engine/ProximityRhythmMapping.h" #include "Music/MidiSink.h" #include "Music/MidiOutput.h" #include "Music/PhraseScheduler.h" @@ -196,6 +197,13 @@ juce::var makeMotionPayload (juce::var paused) return juce::var { object }; } +juce::var makeProximityModePayload (juce::var mode) +{ + auto* object = new juce::DynamicObject(); + object->setProperty ("mode", std::move (mode)); + return juce::var { object }; +} + juce::var makeOutputPayload (const juce::String& outputId) { auto* object = new juce::DynamicObject(); @@ -458,6 +466,101 @@ void testSpeedActivityMappingAndSmoothing() "Speed jitter inside the hysteresis window does not chatter bands"); } +void testProximityMappingAndTransformations() +{ + using drift::engine::CouplingLevel; + using drift::engine::PhraseBody; + using drift::engine::ProximityTracker; + + const PhraseBody first { "first", { 0.1, 0.5 }, {}, 0.05, 1.0 }; + expectNear (drift::engine::normalizedPairProximity ( + first, { "touching", { 0.2, 0.5 }, {}, 0.05, 1.0 }), + 1.0, "Touching body surfaces have maximum normalized proximity"); + expectNear (drift::engine::normalizedPairProximity ( + first, { "half", { 0.4, 0.5 }, {}, 0.05, 1.0 }), + 0.5, "A 0.20 surface gap maps to half proximity"); + expectNear (drift::engine::normalizedPairProximity ( + first, { "far", { 0.6, 0.5 }, {}, 0.05, 1.0 }), + 0.0, "A 0.40 surface gap clamps to zero proximity"); + + using drift::engine::couplingLevelAfterObservation; + expect (couplingLevelAfterObservation (CouplingLevel::loose, 0.40) + == CouplingLevel::linked + && couplingLevelAfterObservation (CouplingLevel::linked, 0.31) + == CouplingLevel::linked + && couplingLevelAfterObservation (CouplingLevel::linked, 0.30) + == CouplingLevel::loose, + "Loose/linked hysteresis includes both exact thresholds"); + expect (couplingLevelAfterObservation (CouplingLevel::linked, 0.75) + == CouplingLevel::tight + && couplingLevelAfterObservation (CouplingLevel::tight, 0.66) + == CouplingLevel::tight + && couplingLevelAfterObservation (CouplingLevel::tight, 0.65) + == CouplingLevel::linked, + "Linked/tight hysteresis includes both exact thresholds"); + + ProximityTracker smoothing; + smoothing.observe (0.1, 0); + smoothing.observe (0.9); + const auto alpha = 1.0 - std::exp ( + -drift::engine::SpatialWorld::fixedStepSeconds + / ProximityTracker::smoothingTimeConstantSeconds); + expectNear (smoothing.smoothedProximity(), 0.1 + alpha * 0.8, + "Proximity smoothing advances by one deterministic physics step"); + ProximityTracker jitter; + jitter.observe (0.35, 0); + for (auto step = 0; step < 1000; ++step) + jitter.observe (step % 2 == 0 ? 0.31 : 0.39); + expect (jitter.observedLevel() == CouplingLevel::loose, + "Proximity jitter below the entry threshold cannot flap coupling state"); + + const std::vector source { + { 0.25, 60, 80, 0.25 }, + { 0.75, 61, 81, 0.5 }, + { 3.75, 60, 90, 0.75 }, + }; + const auto linked = drift::engine::applyRhythmProfile ( + source, CouplingLevel::linked, 4.0); + expect (linked.size() == source.size() + && linked[0].beat == 0.0 + && linked[1].beat == 0.5 + && linked[2].beat == 1.0, + "Linked profiles snap to half beats, wrap the loop, and sort deterministically"); + const auto tight = drift::engine::applyRhythmProfile ( + source, CouplingLevel::tight, 4.0); + expect (tight.size() == 2 && tight[0].note == 60 && tight[0].velocity == 90 + && tight[0].durationBeats == 0.75 && tight[1].beat == 1.0, + "Tight profiles snap to beats and coalesce exact pitch/onset duplicates"); + expect (drift::engine::sharedAccentBoost (0.0, source, CouplingLevel::tight) == 0 + && drift::engine::sharedAccentBoost ( + 0.75, source, CouplingLevel::linked) == 12 + && drift::engine::sharedAccentBoost ( + 0.75, source, CouplingLevel::tight) == 24, + "Shared accents preserve weak pairs and apply the exact linked/tight boosts"); + + for (const auto& phrase : drift::music::makeInitialComposition()) + { + for (const auto& variant : phrase.variants) + { + for (const auto level : { CouplingLevel::loose, + CouplingLevel::linked, + CouplingLevel::tight }) + { + const auto transformed = drift::engine::applyRhythmProfile ( + variant.events, level, phrase.lengthBeats); + expect (std::all_of ( + transformed.begin(), transformed.end(), [&phrase] (const auto& event) { + return event.beat >= 0.0 && event.beat < phrase.lengthBeats + && event.note >= 0 && event.note <= 127 + && event.velocity > 0 && event.velocity <= 127 + && event.durationBeats > 0.0; + }), + "Every role/activity/profile combination remains valid MIDI material"); + } + } + } +} + void testCollisionVariantRulesAndCycle() { const std::array, 6> expected {{ @@ -987,15 +1090,15 @@ void testCollisionQueuesAndAppliesBassVariantAtBar() expect (state.diagnostics.collisionTransitionAppliedCount == 1, "Exactly one applied transition is observable"); - advanceToBeat (clock, engine, 4.6); + advanceToBeat (clock, engine, 4.9); const auto variantBNoteCount = std::count_if ( sink.messages().begin(), sink.messages().end(), [] (const auto& message) { return message.type == drift::music::MidiMessageType::noteOn && message.channel == 1 && message.note == 31 - && std::abs (message.beat - 4.75) < 1.0e-8; + && std::abs (message.beat - 5.0) < 1.0e-8; }); expect (variantBNoteCount == 1, - "Variant B schedules its distinguishing post-boundary note exactly once"); + "Variant B composes with tight profile snapping exactly once"); expect (sink.activeNoteCount() == 0, "The quantized variant transition preserves paired note-on and note-off output"); expect (state.diagnostics.lateMidiEventCount == 0, @@ -1272,6 +1375,148 @@ void testSpeedActivityQueuesQuantizedVariantsAndCollisionWins() "Ending a drag resumes observation from the retained native velocity"); } +void testProximityAuditionQuantizesWhileMotionIsFrozen() +{ + const auto phraseById = [] (const drift::engine::EngineSnapshot& snapshot, + const std::string& phraseId) + -> const drift::engine::PhraseSnapshot& { + const auto phrase = std::find_if ( + snapshot.phrases.begin(), snapshot.phrases.end(), [&] (const auto& candidate) { + return candidate.id == phraseId; + }); + if (phrase == snapshot.phrases.end()) + throw std::runtime_error ("Missing phrase snapshot"); + return *phrase; + }; + const auto pairByIds = [] (const drift::engine::EngineSnapshot& snapshot, + const std::string& first, + const std::string& second) + -> const drift::engine::ProximityPairSnapshot& { + const auto pair = std::find_if ( + snapshot.proximityPairs.begin(), snapshot.proximityPairs.end(), + [&] (const auto& candidate) { + return candidate.firstPhraseId == first + && candidate.secondPhraseId == second; + }); + if (pair == snapshot.proximityPairs.end()) + throw std::runtime_error ("Missing proximity pair snapshot"); + return *pair; + }; + const auto advanceToBeat = [] (FakeClock& clock, + drift::engine::TransportEngine& engine, + double targetBeat) { + while (engine.snapshot().beatPosition + 1.0e-9 < targetBeat) + { + clock.advance (0.002); + engine.tick(); + } + }; + + FakeClock clock; + drift::music::RecordingMidiSink sink; + drift::engine::TransportEngine engine { clock, sink }; + engine.play(); + engine.setMotionPaused (true); + expect (engine.beginPhraseDrag ("bass") + && engine.moveDraggedPhrase ("bass", { 0.30, 0.50 }), + "The proximity fixture can reposition bass during Freeze Motion"); + expect (engine.beginPhraseDrag ("chords") + && engine.moveDraggedPhrase ("chords", { 0.38, 0.50 }), + "The proximity fixture can reposition chords during Freeze Motion"); + + for (auto step = 0; step < 120; ++step) + { + clock.advance (drift::engine::SpatialWorld::fixedStepSeconds); + engine.tick(); + } + + auto snapshot = engine.snapshot(); + auto pair = pairByIds (snapshot, "bass", "chords"); + expect (snapshot.motionPaused && phraseById (snapshot, "bass").dragged, + "Frozen, directly dragged phrases remain under user control during observation"); + expect (pair.rawProximity == 1.0 && pair.smoothedProximity > 0.95 + && pair.couplingLevel == drift::engine::CouplingLevel::loose + && pair.pendingCouplingLevel == drift::engine::CouplingLevel::tight + && pair.pendingApplyBeat == 4.0, + "Close frozen phrases settle to a tight transition at the next bar"); + expect (snapshot.diagnostics.proximityLevelChangeCount == 2 + && snapshot.diagnostics.proximityIntentQueuedCount == 1 + && snapshot.diagnostics.proximityIntentCoalescedCount == 1, + "Linked-to-tight settling coalesces into one unambiguous boundary state"); + expect (phraseById (snapshot, "chords").pendingVariantId == "B", + "The same contact independently preserves its collision variant intent"); + + advanceToBeat (clock, engine, 4.0); + snapshot = engine.snapshot(); + pair = pairByIds (snapshot, "bass", "chords"); + expect (pair.couplingLevel == drift::engine::CouplingLevel::tight + && ! pair.pendingCouplingLevel && ! pair.pendingApplyBeat + && snapshot.diagnostics.proximityTransitionAppliedCount == 1, + "The tight coupling state applies and clears exactly at the bar"); + expect (snapshot.playing && snapshot.motionPaused + && snapshot.diagnostics.lateMidiEventCount == 0, + "Proximity application does not interrupt frozen-motion playback or MIDI timing"); + + advanceToBeat (clock, engine, 6.1); + const auto snappedBassNote = std::count_if ( + sink.messages().begin(), sink.messages().end(), [] (const auto& message) { + return message.type == drift::music::MidiMessageType::noteOn + && message.channel == 1 && message.note == 36 + && std::abs (message.beat - 6.0) < 1.0e-8; + }); + const auto unsnappedBassNote = std::count_if ( + sink.messages().begin(), sink.messages().end(), [] (const auto& message) { + return message.type == drift::music::MidiMessageType::noteOn + && message.channel == 1 && message.note == 36 + && std::abs (message.beat - 5.5) < 1.0e-8; + }); + expect (snappedBassNote == 1 && unsnappedBassNote == 0, + "Tight rhythm-profile scheduling snaps bass onsets without duplicate delivery"); + + FakeClock accentClock; + drift::music::RecordingMidiSink accentSink; + drift::engine::TransportEngine accentEngine { accentClock, accentSink }; + accentEngine.play(); + accentEngine.setMotionPaused (true); + accentEngine.setProximityAuditionMode ( + drift::engine::ProximityAuditionMode::sharedAccents); + accentEngine.beginPhraseDrag ("bass"); + accentEngine.moveDraggedPhrase ("bass", { 0.30, 0.50 }); + accentEngine.beginPhraseDrag ("chords"); + accentEngine.moveDraggedPhrase ("chords", { 0.38, 0.50 }); + for (auto step = 0; step < 120; ++step) + { + accentClock.advance (drift::engine::SpatialWorld::fixedStepSeconds); + accentEngine.tick(); + } + auto accentSnapshot = accentEngine.snapshot(); + expect (accentSnapshot.proximityMode + == drift::engine::ProximityAuditionMode::rhythmProfiles + && accentSnapshot.pendingProximityMode + == drift::engine::ProximityAuditionMode::sharedAccents + && accentSnapshot.pendingProximityModeApplyBeat == 4.0, + "Audition mode changes publish pending state at the same musical boundary"); + advanceToBeat (accentClock, accentEngine, 4.1); + accentSnapshot = accentEngine.snapshot(); + const auto accentedBass = std::count_if ( + accentSink.messages().begin(), accentSink.messages().end(), [] (const auto& message) { + return message.type == drift::music::MidiMessageType::noteOn + && message.channel == 1 && message.note == 36 + && message.velocity == 124 + && std::abs (message.beat - 4.0) < 1.0e-8; + }); + expect (accentSnapshot.proximityMode + == drift::engine::ProximityAuditionMode::sharedAccents + && ! accentSnapshot.pendingProximityMode + && accentSnapshot.diagnostics.proximityModeAppliedCount == 1, + "Shared-accent mode becomes authoritative exactly at the pending bar"); + expect (accentedBass == 1, + "Tight shared accents add exactly 24 velocity without changing the onset"); + expect (accentSink.activeNoteCount() == 0 + && accentSnapshot.diagnostics.lateMidiEventCount == 0, + "Both audition mappings retain paired, on-time MIDI output"); +} + void testFourPhrasesShareOneTransport() { FakeClock clock; @@ -1631,6 +1876,10 @@ void testBridgeRejectsInvalidCommandsBeforeMutation() {}, [] (const std::string& phraseId) { return phraseId == "bass"; }, [&engine] (bool paused) { engine.setMotionPaused (paused); }, + [&engine] (const std::string& mode) { + engine.setProximityAuditionMode ( + *drift::engine::proximityAuditionModeForName (mode)); + }, }; const auto playResult = drift::ui::dispatchCommandEnvelope ( @@ -1650,6 +1899,15 @@ void testBridgeRejectsInvalidCommandsBeforeMutation() handlers); expect (! engine.snapshot().motionPaused && engine.snapshot().playing, "A valid motion command resumes only the world"); + const auto proximityModeResult = drift::ui::dispatchCommandEnvelope ( + makeCommandEnvelope ( + "ui-proximity", "proximity.setAuditionMode", + makeProximityModePayload (juce::var { "sharedAccents" })), + handlers); + expect (proximityModeResult.command.has_value() + && engine.snapshot().pendingProximityMode + == drift::engine::ProximityAuditionMode::sharedAccents, + "A valid audition command queues the requested native proximity mode"); const auto scheduledBeforeRejections = sink.messages(); const auto expectRejected = [&] (juce::var command, @@ -1674,6 +1932,12 @@ void testBridgeRejectsInvalidCommandsBeforeMutation() "ui-motion", "world.setMotionPaused", makeMotionPayload (juce::var { "yes" })), drift::ui::CommandRejectionCode::invalidPayload, "A non-boolean motion state is rejected"); + expectRejected ( + makeCommandEnvelope ( + "ui-proximity-invalid", "proximity.setAuditionMode", + makeProximityModePayload (juce::var { "random" })), + drift::ui::CommandRejectionCode::invalidPayload, + "An unknown proximity audition mode is rejected"); expectRejected ( makeCommandEnvelope ("bad message id", "transport.stop", makeObject()), drift::ui::CommandRejectionCode::invalidMessageId, @@ -1788,6 +2052,7 @@ void testBridgeReconnectPreservesNativePlayback() {}, {}, {}, + {}, }; drift::ui::dispatchCommandEnvelope ( @@ -1842,6 +2107,7 @@ int main() testPhraseSchedulingAcrossLoopAndBar(); testInitialCompositionIsAuthoritative(); testSpeedActivityMappingAndSmoothing(); + testProximityMappingAndTransformations(); testCollisionVariantRulesAndCycle(); testSpatialWorldFixedStepAndBoundaries(); testSpatialWorldBoundsCatchUpWork(); @@ -1854,6 +2120,7 @@ int main() testEveryCollisionPairQueuesItsMappedTarget(); testSimultaneousCollisionsUseStablePriority(); testSpeedActivityQueuesQuantizedVariantsAndCollisionWins(); + testProximityAuditionQuantizesWhileMotionIsFrozen(); testFourPhrasesShareOneTransport(); testMotionPauseDoesNotInterruptPlayback(); testEngineIsIndependentOfUiUpdateTiming(); diff --git a/Tests/TransportStressTests.cpp b/Tests/TransportStressTests.cpp index 55407f7..4bbfd59 100644 --- a/Tests/TransportStressTests.cpp +++ b/Tests/TransportStressTests.cpp @@ -45,6 +45,7 @@ struct SimulationResult int dragMoveCount = 0; int throwCount = 0; int motionPauseToggleCount = 0; + int proximityModeToggleCount = 0; }; juce::var makeConnectCommand (int sequence) @@ -79,6 +80,7 @@ SimulationResult runSimulation (bool stressUi) {}, {}, {}, + {}, }; SimulationResult result; auto previousWatermark = 0.0; @@ -121,6 +123,16 @@ SimulationResult runSimulation (bool stressUi) if (engine.throwPhrase (phraseId, { 0.8 * direction, -0.45 })) ++result.throwCount; } + + if (tick % 30000 == 5000) + { + const auto modeCycle = tick / 30000; + engine.setProximityAuditionMode ( + modeCycle % 2 == 0 + ? drift::engine::ProximityAuditionMode::sharedAccents + : drift::engine::ProximityAuditionMode::rhythmProfiles); + ++result.proximityModeToggleCount; + } } engine.tick(); @@ -307,6 +319,13 @@ int main() && stressed.snapshot.diagnostics.speedIntentQueuedCount >= 1 && stressed.snapshot.diagnostics.speedTransitionAppliedCount >= 1, "the stress run did not exercise quantized speed activity transitions"); + require (stressed.proximityModeToggleCount >= 10 + && stressed.snapshot.diagnostics.proximityModeAppliedCount >= 9, + "the stress run did not repeatedly audition both proximity modes"); + require (stressed.snapshot.diagnostics.proximityLevelChangeCount >= 1 + && stressed.snapshot.diagnostics.proximityIntentQueuedCount >= 1 + && stressed.snapshot.diagnostics.proximityTransitionAppliedCount >= 1, + "the stress run did not exercise quantized proximity coupling"); std::cout << std::fixed << std::setprecision (9) << "Drift deterministic timing stress report\n" @@ -318,6 +337,7 @@ int main() << "Drag moves: " << stressed.dragMoveCount << '\n' << "Throws: " << stressed.throwCount << '\n' << "Motion pause toggles: " << stressed.motionPauseToggleCount << '\n' + << "Proximity mode toggles: " << stressed.proximityModeToggleCount << '\n' << "Bridge reconnects: " << stressed.snapshot.diagnostics.bridgeReconnectCount << '\n' << "Physics steps: " << stressed.snapshot.diagnostics.physicsStepCount << '\n' @@ -339,6 +359,18 @@ int main() << stressed.snapshot.diagnostics.speedIntentSuppressedCount << '\n' << "Speed transitions applied: " << stressed.snapshot.diagnostics.speedTransitionAppliedCount << '\n' + << "Proximity level changes: " + << stressed.snapshot.diagnostics.proximityLevelChangeCount << '\n' + << "Proximity intents queued: " + << stressed.snapshot.diagnostics.proximityIntentQueuedCount << '\n' + << "Proximity intents coalesced: " + << stressed.snapshot.diagnostics.proximityIntentCoalescedCount << '\n' + << "Proximity intents suppressed: " + << stressed.snapshot.diagnostics.proximityIntentSuppressedCount << '\n' + << "Proximity transitions applied: " + << stressed.snapshot.diagnostics.proximityTransitionAppliedCount << '\n' + << "Proximity modes applied: " + << stressed.snapshot.diagnostics.proximityModeAppliedCount << '\n' << "Recorded MIDI messages: " << stressed.messages.size() << '\n' << "Scheduling watermark: " << stressed.snapshot.diagnostics.schedulingWatermarkBeat << " beats\n" diff --git a/docs/TECHNICAL-DESIGN.md b/docs/TECHNICAL-DESIGN.md index 22802ce..bafc6d4 100644 --- a/docs/TECHNICAL-DESIGN.md +++ b/docs/TECHNICAL-DESIGN.md @@ -212,6 +212,7 @@ Initial command set: | `phrase.move` | Set target position during a drag | | `phrase.dragEnd` | End direct manipulation without a throw | | `phrase.throw` | End manipulation with release velocity | +| `proximity.setAuditionMode` | Queue the selected proximity experiment for the next bar | | `debug.setEnabled` | Enable or disable debug data publication | Example: @@ -260,6 +261,20 @@ Positions and velocities use normalized world coordinates so UI size and display "bar": 12, "beat": 2.25 }, + "proximityMode": "rhythmProfiles", + "pendingProximityMode": null, + "pendingProximityModeApplyBeat": null, + "proximityPairs": [ + { + "firstPhraseId": "bass", + "secondPhraseId": "chords", + "rawProximity": 0.72, + "smoothedProximity": 0.68, + "couplingLevel": "linked", + "pendingCouplingLevel": null, + "pendingApplyBeat": null + } + ], "phrases": [ { "id": "bass", @@ -372,6 +387,15 @@ Speed is normalized as velocity magnitude divided by `SpatialWorld::maximumThrow Observation is suspended while world motion is paused or the phrase is dragged: raw speed remains observable, but smoothing and the stable band do not advance. Observation resumes from the released native velocity. Only stable band changes emit intents, and accepted changes are quantized to the next eligible bar. +Proximity is evaluated for all six unordered phrase pairs after every fixed physics step, including while motion is frozen or a phrase is being dragged. It measures surface gap rather than centre distance: + +```text +surfaceGap = max(0, centreDistance - firstRadius - secondRadius) +rawProximity = 1 - clamp(surfaceGap / 0.40, 0, 1) +``` + +Each pair is independently smoothed with the same deterministic 250 ms exponential time constant. Coupling begins loose and uses inclusive hysteresis: loose enters linked at `≥ 0.40`, linked returns to loose at `≤ 0.30`, linked enters tight at `≥ 0.75`, and tight returns to linked at `≤ 0.65`. Stable changes are queued for the next eligible unscheduled bar. A newer state for the same boundary coalesces the pending pair transition; a competing transition for a different already-pending boundary is suppressed. + ### 9.3 MIDI scheduling pipeline For each scheduling window: @@ -404,6 +428,13 @@ Initial mappings: - `SpeedActivityMapping`: smoothed speed selects sparse, normal, or active material at the next bar. - `ProximityRhythmMapping`: pairwise proximity selects a rhythmic-coupling state at a configured quantization boundary. +`ProximityRhythmMapping` is being auditioned in two modes. Both run after collision and speed have resolved the active `A`/`B`/`C` phrase material: + +- **Rhythm profiles:** a phrase takes the strongest coupling it has with any neighbour. Loose leaves authored onsets unchanged, linked snaps them to the nearest half beat, and tight snaps them to the nearest beat. Pitch, duration, and velocity are preserved; chord notes remain simultaneous, and exact duplicate pitch/onset results are coalesced. +- **Shared accents:** timing and density remain unchanged. Exact onsets shared by a pair gain `+12` velocity when linked or `+24` when tight, clamped to MIDI velocity 127. When several neighbours qualify, the maximum boost wins rather than summing boosts. + +Changing audition mode is itself bar-quantized and does not stop transport or invalidate already-scheduled MIDI. The selector and pair relationship lines are evaluation instrumentation; neither candidate is yet the chosen production mapping. + `CollisionVariantMapping` uses the six stable unordered pair rules below. The target advances through its authored variant order `A → B → C → A`. | Ordered pair | Target phrase | @@ -533,6 +564,8 @@ The exact JUCE WebView bridge API and platform resource scheme must be validated - Boundary collisions preserve expected direction and bounded positions. - Contact tracking emits one collision per contact/cooldown cycle. - Proximity normalization and clamping are correct. +- Proximity smoothing and loose/linked/tight hysteresis are deterministic at exact boundaries and under threshold jitter. +- Rhythm-profile snapping, wrapping, chord simultaneity, duplicate coalescing, and shared-accent clamping are correct. - Mapping rules create expected intents. - Conflicting intents resolve deterministically. - Phrase loop enumeration produces correct events across bar and loop boundaries. @@ -546,6 +579,7 @@ The exact JUCE WebView bridge API and platform resource scheme must be validated - Simulated WebView commands result in authoritative snapshots and events. - UI snapshot backpressure drops stale state without blocking the engine. - Ten simulated minutes maintain phase alignment across all phrases. +- Ten simulated minutes exercise proximity transitions and mode changes with paired notes and zero late MIDI. ### 15.3 UI tests @@ -575,6 +609,8 @@ The engine records bounded diagnostic counters rather than unbounded logs: - Physics catch-up steps and capped catch-up incidents. - Active contacts and collision cooldowns. - Pending and applied intents. +- Raw, smoothed, stable, and pending state for all six proximity pairs. +- Current/pending proximity audition mode and proximity transition/mode counters. - Current scheduling watermark. The React debug overlay reads these through snapshots or low-rate debug events. diff --git a/ui/src/App.test.tsx b/ui/src/App.test.tsx index 8bdc7ed..5e1c9f4 100644 --- a/ui/src/App.test.tsx +++ b/ui/src/App.test.tsx @@ -50,6 +50,9 @@ function worldEvent( sequence, engineTimeMs: 1250, motionPaused: false, + proximityMode: 'rhythmProfiles', + pendingProximityMode: null, + pendingProximityModeApplyBeat: null, transport: { playing: true, bpm: 120, bar: 1, beat: 3.5 }, diagnostics: { physicsStepCount: 150, @@ -62,6 +65,13 @@ function worldEvent( speedIntentQueuedCount: 0, speedIntentSuppressedCount: 0, speedTransitionAppliedCount: 0, + proximityLevelChangeCount: 0, + proximityIntentQueuedCount: 0, + proximityIntentCoalescedCount: 0, + proximityIntentSuppressedCount: 0, + proximityTransitionAppliedCount: 0, + proximityModeQueuedCount: 0, + proximityModeAppliedCount: 0, droppedSnapshotCount: 112, maximumSnapshotIntervalMs: 34.2, commandQueueDepth: 2, @@ -78,6 +88,14 @@ function worldEvent( { firstPhraseId: 'chords', secondPhraseId: 'melody', targetPhraseId: 'chords', touching: false, cooldownRemainingMs: 0 }, { firstPhraseId: 'drums', secondPhraseId: 'melody', targetPhraseId: 'melody', touching: false, cooldownRemainingMs: 0 }, ], + proximityPairs: [ + { firstPhraseId: 'bass', secondPhraseId: 'chords', rawProximity: 0.1, smoothedProximity: 0.08, couplingLevel: 'loose', pendingCouplingLevel: null, pendingApplyBeat: null }, + { firstPhraseId: 'bass', secondPhraseId: 'drums', rawProximity: 0.2, smoothedProximity: 0.18, couplingLevel: 'loose', pendingCouplingLevel: null, pendingApplyBeat: null }, + { firstPhraseId: 'bass', secondPhraseId: 'melody', rawProximity: 0, smoothedProximity: 0, couplingLevel: 'loose', pendingCouplingLevel: null, pendingApplyBeat: null }, + { firstPhraseId: 'chords', secondPhraseId: 'drums', rawProximity: 0.3, smoothedProximity: 0.25, couplingLevel: 'loose', pendingCouplingLevel: null, pendingApplyBeat: null }, + { firstPhraseId: 'chords', secondPhraseId: 'melody', rawProximity: 0, smoothedProximity: 0, couplingLevel: 'loose', pendingCouplingLevel: null, pendingApplyBeat: null }, + { firstPhraseId: 'drums', secondPhraseId: 'melody', rawProximity: 0.3, smoothedProximity: 0.27, couplingLevel: 'loose', pendingCouplingLevel: null, pendingApplyBeat: null }, + ], phrases: [ { id: 'drums', @@ -238,6 +256,13 @@ describe('Drift bridge interface', () => { speedIntentQueuedCount: 0, speedIntentSuppressedCount: 0, speedTransitionAppliedCount: 0, + proximityLevelChangeCount: 0, + proximityIntentQueuedCount: 0, + proximityIntentCoalescedCount: 0, + proximityIntentSuppressedCount: 0, + proximityTransitionAppliedCount: 0, + proximityModeQueuedCount: 0, + proximityModeAppliedCount: 0, commandQueueDepth: 2, maximumCommandQueueDepth: 7, coalescedMoveCount: 12, @@ -257,6 +282,14 @@ describe('Drift bridge interface', () => { expect(screen.getByText('0.125 ms')).toBeTruthy() expect(screen.getByText('Moving')).toBeTruthy() + fireEvent.change(screen.getByLabelText('Proximity audition mode'), { + target: { value: 'sharedAccents' }, + }) + expect(bridge.commands.at(-1)).toMatchObject({ + type: 'proximity.setAuditionMode', + payload: { mode: 'sharedAccents' }, + }) + fireEvent.click(screen.getByRole('button', { name: /freeze motion/i })) expect(bridge.commands.at(-1)).toMatchObject({ type: 'world.setMotionPaused', @@ -333,6 +366,16 @@ describe('Drift bridge interface', () => { invalidMotion.payload.motionPaused = 'yes' as unknown as boolean eventListener?.(invalidMotion) expect(receivedWorldSequence).toBe(5) + + const invalidProximity = worldEvent(11) + invalidProximity.payload.proximityPairs[0].rawProximity = 1.2 + eventListener?.(invalidProximity) + expect(receivedWorldSequence).toBe(5) + + const invalidMode = worldEvent(12) + invalidMode.payload.proximityMode = 'random' as 'rhythmProfiles' + eventListener?.(invalidMode) + expect(receivedWorldSequence).toBe(5) }) it('renders four phrases from the latest authoritative world snapshot', () => { @@ -355,14 +398,25 @@ describe('Drift bridge interface', () => { expect(container.textContent).toContain('→ chords / clear / 0 ms') expect(container.textContent).toContain('drums + melody') expect(container.textContent).toContain('→ melody / clear / 0 ms') - - const pendingWorld = worldEvent(5) + expect(container.textContent).toContain('bass ↔ chords') + expect(container.textContent).toContain('loose / 0.10 raw / 0.08 smooth') + + const pendingProximity = worldEvent(5) + pendingProximity.payload.proximityPairs[0].pendingCouplingLevel = 'linked' + pendingProximity.payload.proximityPairs[0].pendingApplyBeat = 4 + pendingProximity.payload.pendingProximityMode = 'sharedAccents' + pendingProximity.payload.pendingProximityModeApplyBeat = 4 + act(() => bridge.publish(pendingProximity)) + expect(container.textContent).toContain('loose → linked') + expect(container.textContent).toContain('Rhythm profiles → Shared accents') + + const pendingWorld = worldEvent(6) pendingWorld.payload.phrases[1].pendingVariantId = 'B' pendingWorld.payload.phrases[1].pendingVariantApplyBeat = 4 act(() => bridge.publish(pendingWorld)) expect(screen.getByText(/BASS · A → B/)).toBeTruthy() - const appliedWorld = worldEvent(6) + const appliedWorld = worldEvent(7) appliedWorld.payload.phrases[1].currentVariantId = 'B' act(() => bridge.publish(appliedWorld)) expect(screen.getByText(/BASS · B · normal · speed .* · playing/)).toBeTruthy() diff --git a/ui/src/App.tsx b/ui/src/App.tsx index 9c917b2..feb1cdb 100644 --- a/ui/src/App.tsx +++ b/ui/src/App.tsx @@ -77,6 +77,7 @@ export function App({ bridge }: AppProps) { : 'Disconnected' const controlsReady = transportBridge.connected && bridgeReady + const proximityModeValue = worldSnapshot.pendingProximityMode ?? worldSnapshot.proximityMode return (
+ + @@ -259,6 +278,15 @@ export function App({ bridge }: AppProps) {
Motion
{worldSnapshot.motionPaused ? 'Frozen' : 'Moving'}
+
+
Proximity mode
+
+ {worldSnapshot.proximityMode === 'rhythmProfiles' ? 'Rhythm profiles' : 'Shared accents'} + {worldSnapshot.pendingProximityMode + ? ` → ${worldSnapshot.pendingProximityMode === 'rhythmProfiles' ? 'Rhythm profiles' : 'Shared accents'}` + : ''} +
+
{worldSnapshot.collisions.map((collision) => (
{collision.firstPhraseId} + {collision.secondPhraseId}
@@ -268,6 +296,15 @@ export function App({ bridge }: AppProps) {
))} + {worldSnapshot.proximityPairs.map((pair) => ( +
+
{pair.firstPhraseId} ↔ {pair.secondPhraseId}
+
+ {pair.couplingLevel}{pair.pendingCouplingLevel ? ` → ${pair.pendingCouplingLevel}` : ''} /{' '} + {pair.rawProximity.toFixed(2)} raw / {pair.smoothedProximity.toFixed(2)} smooth +
+
+ ))}
Transitions
@@ -294,6 +331,23 @@ export function App({ bridge }: AppProps) { {worldSnapshot.diagnostics.speedTransitionAppliedCount} applied
+
+
Proximity
+
+ {worldSnapshot.diagnostics.proximityLevelChangeCount} levels /{' '} + {worldSnapshot.diagnostics.proximityIntentQueuedCount} queued /{' '} + {worldSnapshot.diagnostics.proximityIntentCoalescedCount} coalesced /{' '} + {worldSnapshot.diagnostics.proximityIntentSuppressedCount} suppressed /{' '} + {worldSnapshot.diagnostics.proximityTransitionAppliedCount} applied +
+
+
+
Mode changes
+
+ {worldSnapshot.diagnostics.proximityModeQueuedCount} queued /{' '} + {worldSnapshot.diagnostics.proximityModeAppliedCount} applied +
+
Catch-up
diff --git a/ui/src/PhraseWorld.tsx b/ui/src/PhraseWorld.tsx index e6647f1..ec33302 100644 --- a/ui/src/PhraseWorld.tsx +++ b/ui/src/PhraseWorld.tsx @@ -164,6 +164,8 @@ export function PhraseWorld({ app.canvas.className = 'phrase-world-canvas' host.appendChild(app.canvas) const nodes = new Map() + const relationshipLines = new Graphics() + app.stage.addChild(relationshipLines) const makeNode = (phrase: PhraseSnapshot): SceneNode => { const colour = colourForPhrase(phrase) @@ -205,6 +207,23 @@ export function PhraseWorld({ const amount = transition.durationMs <= 0 ? 1 : elapsed / transition.durationMs const phrases = interpolatePhrases(transition.previous, transition.current, amount) const activeIds = new Set(phrases.map((phrase) => phrase.id)) + const phrasesById = new Map(phrases.map((phrase) => [phrase.id, phrase])) + + relationshipLines.clear() + for (const pair of transition.current.proximityPairs) { + if (pair.smoothedProximity <= 0.01) continue + const first = phrasesById.get(pair.firstPhraseId) + const second = phrasesById.get(pair.secondPhraseId) + if (!first || !second) continue + relationshipLines + .moveTo(first.position.x * app.screen.width, first.position.y * app.screen.height) + .lineTo(second.position.x * app.screen.width, second.position.y * app.screen.height) + .stroke({ + color: 0x6ed0c4, + width: 0.5 + pair.smoothedProximity * 2, + alpha: 0.04 + pair.smoothedProximity * 0.32, + }) + } for (const [phraseId, node] of nodes) { if (activeIds.has(phraseId)) continue diff --git a/ui/src/bridge/transportBridge.ts b/ui/src/bridge/transportBridge.ts index 0d6d8b7..83448fa 100644 --- a/ui/src/bridge/transportBridge.ts +++ b/ui/src/bridge/transportBridge.ts @@ -24,6 +24,13 @@ export interface EngineDiagnostics { speedIntentQueuedCount: number speedIntentSuppressedCount: number speedTransitionAppliedCount: number + proximityLevelChangeCount: number + proximityIntentQueuedCount: number + proximityIntentCoalescedCount: number + proximityIntentSuppressedCount: number + proximityTransitionAppliedCount: number + proximityModeQueuedCount: number + proximityModeAppliedCount: number commandQueueDepth: number maximumCommandQueueDepth: number coalescedMoveCount: number @@ -33,6 +40,8 @@ export interface EngineDiagnostics { export type PhraseRole = 'rhythm' | 'bass' | 'harmony' | 'lead' export type ActivityBand = 'sparse' | 'normal' | 'active' +export type CouplingLevel = 'loose' | 'linked' | 'tight' +export type ProximityAuditionMode = 'rhythmProfiles' | 'sharedAccents' export interface PhraseSnapshot { id: string @@ -65,6 +74,13 @@ export interface WorldDiagnostics { speedIntentQueuedCount: number speedIntentSuppressedCount: number speedTransitionAppliedCount: number + proximityLevelChangeCount: number + proximityIntentQueuedCount: number + proximityIntentCoalescedCount: number + proximityIntentSuppressedCount: number + proximityTransitionAppliedCount: number + proximityModeQueuedCount: number + proximityModeAppliedCount: number droppedSnapshotCount: number maximumSnapshotIntervalMs: number commandQueueDepth: number @@ -82,10 +98,23 @@ export interface CollisionSnapshot { cooldownRemainingMs: number } +export interface ProximityPairSnapshot { + firstPhraseId: string + secondPhraseId: string + rawProximity: number + smoothedProximity: number + couplingLevel: CouplingLevel + pendingCouplingLevel: CouplingLevel | null + pendingApplyBeat: number | null +} + export interface WorldSnapshot { sequence: number engineTimeMs: number motionPaused: boolean + proximityMode: ProximityAuditionMode + pendingProximityMode: ProximityAuditionMode | null + pendingProximityModeApplyBeat: number | null transport: { playing: boolean bpm: number @@ -94,6 +123,7 @@ export interface WorldSnapshot { } phrases: PhraseSnapshot[] collisions: CollisionSnapshot[] + proximityPairs: ProximityPairSnapshot[] diagnostics: WorldDiagnostics } @@ -137,6 +167,13 @@ export const initialTransportState: TransportState = { speedIntentQueuedCount: 0, speedIntentSuppressedCount: 0, speedTransitionAppliedCount: 0, + proximityLevelChangeCount: 0, + proximityIntentQueuedCount: 0, + proximityIntentCoalescedCount: 0, + proximityIntentSuppressedCount: 0, + proximityTransitionAppliedCount: 0, + proximityModeQueuedCount: 0, + proximityModeAppliedCount: 0, commandQueueDepth: 0, maximumCommandQueueDepth: 0, coalescedMoveCount: 0, @@ -149,9 +186,13 @@ export const initialWorldSnapshot: WorldSnapshot = { sequence: 0, engineTimeMs: 0, motionPaused: true, + proximityMode: 'rhythmProfiles', + pendingProximityMode: null, + pendingProximityModeApplyBeat: null, transport: { playing: false, bpm: 120, bar: 1, beat: 1 }, phrases: [], collisions: [], + proximityPairs: [], diagnostics: { physicsStepCount: 0, physicsCatchUpStepCount: 0, @@ -163,6 +204,13 @@ export const initialWorldSnapshot: WorldSnapshot = { speedIntentQueuedCount: 0, speedIntentSuppressedCount: 0, speedTransitionAppliedCount: 0, + proximityLevelChangeCount: 0, + proximityIntentQueuedCount: 0, + proximityIntentCoalescedCount: 0, + proximityIntentSuppressedCount: 0, + proximityTransitionAppliedCount: 0, + proximityModeQueuedCount: 0, + proximityModeAppliedCount: 0, droppedSnapshotCount: 0, maximumSnapshotIntervalMs: 0, commandQueueDepth: 0, @@ -178,6 +226,7 @@ export type TransportCommand = | { type: 'transport.play'; payload: Record } | { type: 'transport.stop'; payload: Record } | { type: 'world.setMotionPaused'; payload: { paused: boolean } } + | { type: 'proximity.setAuditionMode'; payload: { mode: ProximityAuditionMode } } | { type: 'transport.setTempo'; payload: { bpm: number } } | { type: 'midi.selectOutput'; payload: { outputId: string } } | { @@ -325,6 +374,13 @@ function isTransportState(payload: unknown): payload is TransportState { typeof diagnostics.speedIntentQueuedCount === 'number' && typeof diagnostics.speedIntentSuppressedCount === 'number' && typeof diagnostics.speedTransitionAppliedCount === 'number' && + typeof diagnostics.proximityLevelChangeCount === 'number' && + typeof diagnostics.proximityIntentQueuedCount === 'number' && + typeof diagnostics.proximityIntentCoalescedCount === 'number' && + typeof diagnostics.proximityIntentSuppressedCount === 'number' && + typeof diagnostics.proximityTransitionAppliedCount === 'number' && + typeof diagnostics.proximityModeQueuedCount === 'number' && + typeof diagnostics.proximityModeAppliedCount === 'number' && typeof diagnostics.commandQueueDepth === 'number' && typeof diagnostics.maximumCommandQueueDepth === 'number' && typeof diagnostics.coalescedMoveCount === 'number' && @@ -347,6 +403,14 @@ function isWorldSnapshot(payload: unknown): payload is WorldSnapshot { !isFiniteNumber(snapshot.engineTimeMs) || snapshot.engineTimeMs < 0 || typeof snapshot.motionPaused !== 'boolean' || + !['rhythmProfiles', 'sharedAccents'].includes(snapshot.proximityMode ?? '') || + (snapshot.pendingProximityMode !== null && + !['rhythmProfiles', 'sharedAccents'].includes(snapshot.pendingProximityMode ?? '')) || + (snapshot.pendingProximityModeApplyBeat !== null && + (!isFiniteNumber(snapshot.pendingProximityModeApplyBeat) || + snapshot.pendingProximityModeApplyBeat < 0)) || + ((snapshot.pendingProximityMode === null) !== + (snapshot.pendingProximityModeApplyBeat === null)) || typeof transport !== 'object' || transport === null || typeof transport.playing !== 'boolean' || @@ -355,6 +419,7 @@ function isWorldSnapshot(payload: unknown): payload is WorldSnapshot { !isFiniteNumber(transport.beat) || !Array.isArray(snapshot.phrases) || !Array.isArray(snapshot.collisions) || + !Array.isArray(snapshot.proximityPairs) || typeof diagnostics !== 'object' || diagnostics === null || !Number.isSafeInteger(diagnostics.physicsStepCount) || @@ -377,6 +442,20 @@ function isWorldSnapshot(payload: unknown): payload is WorldSnapshot { (diagnostics.speedIntentSuppressedCount ?? -1) < 0 || !Number.isSafeInteger(diagnostics.speedTransitionAppliedCount) || (diagnostics.speedTransitionAppliedCount ?? -1) < 0 || + !Number.isSafeInteger(diagnostics.proximityLevelChangeCount) || + (diagnostics.proximityLevelChangeCount ?? -1) < 0 || + !Number.isSafeInteger(diagnostics.proximityIntentQueuedCount) || + (diagnostics.proximityIntentQueuedCount ?? -1) < 0 || + !Number.isSafeInteger(diagnostics.proximityIntentCoalescedCount) || + (diagnostics.proximityIntentCoalescedCount ?? -1) < 0 || + !Number.isSafeInteger(diagnostics.proximityIntentSuppressedCount) || + (diagnostics.proximityIntentSuppressedCount ?? -1) < 0 || + !Number.isSafeInteger(diagnostics.proximityTransitionAppliedCount) || + (diagnostics.proximityTransitionAppliedCount ?? -1) < 0 || + !Number.isSafeInteger(diagnostics.proximityModeQueuedCount) || + (diagnostics.proximityModeQueuedCount ?? -1) < 0 || + !Number.isSafeInteger(diagnostics.proximityModeAppliedCount) || + (diagnostics.proximityModeAppliedCount ?? -1) < 0 || !Number.isSafeInteger(diagnostics.droppedSnapshotCount) || (diagnostics.droppedSnapshotCount ?? -1) < 0 || !isFiniteNumber(diagnostics.maximumSnapshotIntervalMs) || @@ -457,8 +536,8 @@ function isWorldSnapshot(payload: unknown): payload is WorldSnapshot { if (!phrasesAreValid) return false - const pairIds = new Set() - return snapshot.collisions.every((collision) => { + const collisionPairIds = new Set() + const collisionsAreValid = snapshot.collisions.every((collision) => { if (typeof collision !== 'object' || collision === null) return false const candidate = collision as Partial @@ -475,8 +554,36 @@ function isWorldSnapshot(payload: unknown): payload is WorldSnapshot { isFiniteNumber(candidate.cooldownRemainingMs) && candidate.cooldownRemainingMs >= 0 - if (!valid || pairIds.has(pairId)) return false - pairIds.add(pairId) + if (!valid || collisionPairIds.has(pairId)) return false + collisionPairIds.add(pairId) + return true + }) + if (!collisionsAreValid) return false + + const proximityPairIds = new Set() + return snapshot.proximityPairs.every((pair) => { + if (typeof pair !== 'object' || pair === null) return false + const candidate = pair as Partial + const pairId = `${candidate.firstPhraseId}:${candidate.secondPhraseId}` + const valid = + isMessageId(candidate.firstPhraseId) && + isMessageId(candidate.secondPhraseId) && + candidate.firstPhraseId < candidate.secondPhraseId && + phraseIds.has(candidate.firstPhraseId) && + phraseIds.has(candidate.secondPhraseId) && + isFiniteNumber(candidate.rawProximity) && + candidate.rawProximity >= 0 && candidate.rawProximity <= 1 && + isFiniteNumber(candidate.smoothedProximity) && + candidate.smoothedProximity >= 0 && candidate.smoothedProximity <= 1 && + ['loose', 'linked', 'tight'].includes(candidate.couplingLevel ?? '') && + (candidate.pendingCouplingLevel === null || + ['loose', 'linked', 'tight'].includes(candidate.pendingCouplingLevel ?? '')) && + (candidate.pendingApplyBeat === null || + (isFiniteNumber(candidate.pendingApplyBeat) && candidate.pendingApplyBeat >= 0)) && + ((candidate.pendingCouplingLevel === null) === + (candidate.pendingApplyBeat === null)) + if (!valid || proximityPairIds.has(pairId)) return false + proximityPairIds.add(pairId) return true }) } diff --git a/ui/src/dragInteraction.test.ts b/ui/src/dragInteraction.test.ts index 5832647..0f64ff1 100644 --- a/ui/src/dragInteraction.test.ts +++ b/ui/src/dragInteraction.test.ts @@ -37,9 +37,13 @@ function snapshot(sequence: number, dragged = false): WorldSnapshot { sequence, engineTimeMs: sequence * 33, motionPaused: false, + proximityMode: 'rhythmProfiles', + pendingProximityMode: null, + pendingProximityModeApplyBeat: null, transport: { playing: true, bpm: 120, bar: 1, beat: 1 }, phrases: [{ ...bass, dragged }], collisions: [], + proximityPairs: [], diagnostics: { physicsStepCount: 0, physicsCatchUpStepCount: 0, @@ -51,6 +55,13 @@ function snapshot(sequence: number, dragged = false): WorldSnapshot { speedIntentQueuedCount: 0, speedIntentSuppressedCount: 0, speedTransitionAppliedCount: 0, + proximityLevelChangeCount: 0, + proximityIntentQueuedCount: 0, + proximityIntentCoalescedCount: 0, + proximityIntentSuppressedCount: 0, + proximityTransitionAppliedCount: 0, + proximityModeQueuedCount: 0, + proximityModeAppliedCount: 0, droppedSnapshotCount: 0, maximumSnapshotIntervalMs: 0, commandQueueDepth: 0, diff --git a/ui/src/styles.css b/ui/src/styles.css index 9a52bae..1b24199 100644 --- a/ui/src/styles.css +++ b/ui/src/styles.css @@ -99,7 +99,8 @@ body { .transport-button:disabled, .motion-button:disabled, .tempo-control input:disabled, -.midi-output-control select:disabled { +.midi-output-control select:disabled, +.proximity-mode-control select:disabled { cursor: not-allowed; opacity: 0.42; } @@ -107,7 +108,8 @@ body { .transport-button:focus-visible, .motion-button:focus-visible, .tempo-control input:focus-visible, -.midi-output-control select:focus-visible { +.midi-output-control select:focus-visible, +.proximity-mode-control select:focus-visible { outline: 2px solid var(--sun); outline-offset: 3px; } @@ -136,7 +138,8 @@ body { text-align: center; } -.midi-output-control { +.midi-output-control, +.proximity-mode-control { display: grid; gap: 4px; color: var(--muted); @@ -158,6 +161,19 @@ body { text-transform: none; } +.proximity-mode-control select { + width: 150px; + padding: 8px 28px 8px 8px; + border: 1px solid rgba(110, 208, 196, 0.3); + border-radius: 4px; + color: var(--ink); + background: rgba(12, 18, 38, 0.8); + font: inherit; + font-size: 10px; + letter-spacing: 0; + text-transform: none; +} + .eyebrow, .build-tag, .status, diff --git a/ui/src/worldInterpolation.test.ts b/ui/src/worldInterpolation.test.ts index c1b1be5..8ba7d63 100644 --- a/ui/src/worldInterpolation.test.ts +++ b/ui/src/worldInterpolation.test.ts @@ -8,6 +8,9 @@ function snapshot(sequence: number, x: number, y: number): WorldSnapshot { sequence, engineTimeMs: sequence * 33, motionPaused: false, + proximityMode: 'rhythmProfiles', + pendingProximityMode: null, + pendingProximityModeApplyBeat: null, transport: { playing: true, bpm: 120, bar: 1, beat: 1 }, phrases: [ { @@ -31,6 +34,7 @@ function snapshot(sequence: number, x: number, y: number): WorldSnapshot { }, ], collisions: [], + proximityPairs: [], diagnostics: { physicsStepCount: sequence * 4, physicsCatchUpStepCount: 0, @@ -42,6 +46,13 @@ function snapshot(sequence: number, x: number, y: number): WorldSnapshot { speedIntentQueuedCount: 0, speedIntentSuppressedCount: 0, speedTransitionAppliedCount: 0, + proximityLevelChangeCount: 0, + proximityIntentQueuedCount: 0, + proximityIntentCoalescedCount: 0, + proximityIntentSuppressedCount: 0, + proximityTransitionAppliedCount: 0, + proximityModeQueuedCount: 0, + proximityModeAppliedCount: 0, droppedSnapshotCount: sequence * 3, maximumSnapshotIntervalMs: 34, commandQueueDepth: 0,