Проверенный контрактТочноеMIT
PanoramaS4BassEngine
Адрес0xa4b88015cf78c5e00de677ffa2e6c9ca4e10c501
- Баланс
0 ETH
- Транзакций
1
- Компилятор
solc 0.8.34
- Тот же код
Только этот контракт
Подробности
- Компилятор
- solc 0.8.34+commit.80d5c536
- Язык
- solidity
- Оптимизация
- Да, 200 прогонов
- Через IR
- да
- Лицензия
- MIT
- Совпадение
- Точноекод создания: да, код в сети: да
- Проверен на Sourcify
- Создан в блоке
- 26 438 056
- Транзакция создания
- 0x5f59537779…423b4ffc24
4 файла
- contracts/1of1s/contracts/contracts 11-17d bass and controller/PanoramaS4BassEngine.solглавный5,46 КБ
- contracts/1of1s/contracts/contracts 11-17d bass and controller/PanoramaTypesV2.sol3,05 КБ
- contracts/1of1s/contracts/contracts 11-17d bass and controller/branches.sol11,89 КБ
- contracts/1of1s/contracts/contracts 11-17d bass and controller/panoramaParts.sol14,85 КБ
contracts/1of1s/contracts/contracts 11-17d bass and controller/PanoramaS4BassEngine.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {Branches} from "./branches.sol";
import {panoramaParts} from "./panoramaParts.sol";
import {PanoramaTypesV2 as T} from "./PanoramaTypesV2.sol";
/// @notice Deterministic bass generator extracted from Panorama S4 core to stay under EIP-170.
/// @dev No mutable storage; the caller passes the same dependencies, resolved generation
/// data, chord-A result, bass ranges and effective rhythm seed used by the core.
contract PanoramaS4BassEngine {
struct Params {
uint8 modes;
uint8 registers;
uint8[2] steps;
uint8[2] density;
uint8[2] gate;
uint16[] durations;
uint16 targetTicks;
uint8 velocity;
}
function generate(
address branches_,
address parts_,
T.Resolved memory r,
panoramaParts.Result memory chordA,
Params memory w,
bool hasMood,
bytes32 rhythmSeed
) external view returns (bytes memory) {
Branches branches = Branches(branches_);
panoramaParts parts = panoramaParts(parts_);
uint256 seed = uint256(keccak256(abi.encode(rhythmSeed, "BASS")));
uint8 mode; uint8 base = 36; uint8 velocity = 96;
if (hasMood) {
mode = _pick3(w.modes, _bassRand(seed, "MODE", 0));
base = uint8(24 + 12 * _pick3(w.registers, _bassRand(seed, "REGISTER", 0)));
velocity = w.velocity;
}
uint8[] memory path = branches.generatePath(r.chords.chordCount, r.chords.startBranch, r.chords.closeLoop, r.chordSeed);
uint8[6] memory degrees = [uint8(0), 6, 3, 4, 5, 6];
uint8[][] memory rootChords = new uint8[][](path.length);
for (uint256 i; i < path.length; ++i) {
rootChords[i] = new uint8[](1);
rootChords[i][0] = base + uint8((uint256(r.chords.key) + r.chords.scale[degrees[path[i]]]) % 12);
}
if (mode == 2) {
// Shared harmony seed keeps bass chord boundaries identical to Chords A.
panoramaParts.Params memory p = r.parts[0];
p.tones = 1;
p.density = uint8(_drawBass(seed, "DENSITY", w.density));
p.gate = uint8(_drawBass(seed, "GATE", w.gate));
p.noteRhythm = panoramaParts.Pattern(
w.durations, uint8(_drawBass(seed, "STEPS", w.steps)), w.targetTicks
);
panoramaParts.Result memory b = parts.generate(rootChords, p, panoramaParts.Seeds(
r.partSeeds[0].harmony, _bassRand(seed, "GROUP", 0), _bassRand(seed, "NOTES", 0)
));
// The bass should not become silent even if the entire repeating mask misses.
if (b.notes.length == 0) {
b.notes = new panoramaParts.Note[](1);
b.notes[0] = panoramaParts.Note(rootChords[0][0], 0, chordA.chordEnds[0], velocity);
} else {
for (uint256 i; i < b.notes.length; ++i) b.notes[i].velocity = velocity;
}
return parts.pack7(b.notes, r.bpm);
}
panoramaParts.Note[] memory notes;
uint256 count;
uint256 chord;
uint256 previous;
if (mode == 0) {
notes = new panoramaParts.Note[](chordA.chordEnds.length);
for (uint256 i; i < chordA.chordEnds.length; ++i) {
uint16 end = chordA.chordEnds[i];
notes[count++] = panoramaParts.Note(rootChords[i][0],uint16(previous),uint16(end - previous),velocity);
previous = end;
}
} else {
notes = new panoramaParts.Note[](chordA.notes.length);
uint256 last = type(uint256).max;
for (uint256 i; i < chordA.notes.length; ++i) {
uint256 onset = chordA.notes[i].start;
if (onset == last) continue;
last = onset;
while (chord + 1 < chordA.chordEnds.length && onset >= chordA.chordEnds[chord]) ++chord;
uint256 hold = chordA.notes[i].duration;
if (onset + hold > chordA.chordEnds[chord]) hold = chordA.chordEnds[chord] - onset;
if (hold != 0) notes[count++] = panoramaParts.Note(rootChords[chord][0],uint16(onset),uint16(hold),velocity);
}
}
if (count == 0) {
// Preserve an audible bass downbeat when chord-A density yields no triggers.
notes = new panoramaParts.Note[](1);
notes[0] = panoramaParts.Note(rootChords[0][0], 0, chordA.chordEnds[0], velocity);
} else {
assembly { mstore(notes, count) }
}
return parts.pack7(notes, r.bpm);
}
function _bassRand(uint256 seed, bytes32 domain, uint256 index) private pure returns (uint256) {
return uint256(keccak256(abi.encode(seed, domain, index)));
}
function _drawBass(uint256 seed, bytes32 domain, uint8[2] memory bounds) private pure returns (uint256) {
return bounds[0] + _bassRand(seed, domain, 0) % (uint256(bounds[1]) - bounds[0] + 1);
}
function _pick3(uint8 mask, uint256 rand) private pure returns (uint8) {
uint256 count;
for (uint8 i; i < 3; ++i) if ((mask & (uint8(1) << i)) != 0) ++count;
uint256 pick = rand % count;
for (uint8 i; i < 3; ++i) if ((mask & (uint8(1) << i)) != 0) {
if (pick == 0) return i;
--pick;
}
revert();
}
}
contracts/1of1s/contracts/contracts 11-17d bass and controller/PanoramaTypesV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {Branches} from "./branches.sol";
import {panoramaParts} from "./panoramaParts.sol";
/// @notice Shared data formats. Characters choose sounds; moods choose generation ranges.
library PanoramaTypesV2 {
struct Range { uint16 min; uint16 max; }
struct ChordWeights {
uint8[7][] scales;
Branches.Mode[] modes;
uint8[][] shapes;
Range count;
Range thirds;
Range low;
Range high;
Range voices;
Range shuffle;
}
struct PatternWeights {
uint16[] durations;
Range steps;
// 0 = step mode. Otherwise exact length of THIS pattern, not the song.
uint16 targetTicks;
}
struct PartWeights {
PatternWeights groups;
PatternWeights rhythm;
Range tones;
Range density;
Range gate;
int8[] transpose;
}
struct DrumWeights {
Range bars;
uint16[] subdivisions;
Range complexity;
Range density1;
Range density2;
Range density3;
Range wonk;
Range wonkSteps;
Range accent;
Range accentOffset;
}
// Numeric audio settings use an explicit integer grid. value / scale is the
// renderer value; range samples are min + N*step, choices override the range.
struct AudioWeight {
uint8 track; // chord A, chord B, chord C, melody, kick, snare, hat
bytes32 parameter; // UTF-8 bytes32 name, e.g. "filter" or "delayBeats"
int32 min;
int32 max;
uint32 step;
uint32 scale;
int32[] choices;
}
struct AudioValue { uint8 track; bytes32 parameter; int32 value; uint32 scale; }
struct Mood {
Range bpm;
ChordWeights chords;
PatternWeights harmony;
PartWeights[3] parts;
DrumWeights[3] drums;
AudioWeight[] audio;
}
struct DrumParams {
uint16 bars;
uint16 subdivision;
uint16 density1; // 0..10000 after complexity
uint16 density2;
uint16 density3;
uint16 wonk;
uint16 wonkSteps;
uint16 accent;
uint16 accentOffset;
uint256 seed;
}
struct Resolved {
uint16 bpm;
Branches.Params chords;
panoramaParts.Params[3] parts;
panoramaParts.Seeds[3] partSeeds;
int8[3] transpose;
DrumParams[3] drums;
uint256 chordSeed;
}
}
interface IPanoramaMoodSourceV2 {
function resolve(uint8 mood, uint8 key, bytes32[3] calldata seeds)
external view returns (PanoramaTypesV2.Resolved memory);
function resolveAudio(uint8 mood, bytes32 seed) external view returns (bytes memory);
}
/// @notice A renderer is optional for music-data calls, required for tokenToJS.
/// @dev Implement this with the real Tone.js storage and BITS audio-fetching ABI.
interface IPanoramaRendererV2 {
function tokenToJS(address controller, uint256 tokenId) external view returns (string memory);
}
contracts/1of1s/contracts/contracts 11-17d bass and controller/branches.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @title Branches - deterministic, stateless raw chord generation
/// @notice No rhythm, playback, storage, owner, or external calls.
/// @dev Graph and Original degree sets come from No End in Sight.
/// Generalized voicing is NOT a seed-for-seed recreation of that JS work.
///
/// Usage (Remix tuple for Params, followed by a separate seed such as 123):
/// [9,[0,2,3,5,7,8,10],0,8,255,true,4,[],36,84,4,50]
/// This generates 8 closed-loop chords in A natural minor, original degree sets,
/// MIDI 36..84, four voices, 50% shuffle. No constructor arguments are required.
/// For parallel maj7 chords, change mode to 2 and shape to [0,4,7,11].
/// For diatonic ninth chords, change mode to 1 and thirdCount to 5.
/// Major scale: [0,2,4,5,7,9,11]. All degree/branch indices are zero-based.
///
/// Voicing semantics:
/// - First place each source tone at its lowest unused octave within range.
/// - Repeat chord pitch classes into additional octaves to supply extra voices.
/// - shuffleAmount is a per-note relocation probability out of 100 and also
/// scales the maximum octave travel (rounded up). Relocations use only free
/// pitches of the same pitch class, within the supplied MIDI range.
/// - Sort actual MIDI pitches ascending, then crop to voiceCount.
/// - A narrow range may omit source tones that have no available octave; it
/// reverts if fewer than voiceCount distinct valid pitches can be supplied.
/// - Original's repeated degree in branch 1 is retained in another octave when
/// it fits. Parallel shapes contain unique pitch classes, not absolute MIDI
/// notes or prescribed registers. A rootless shape is allowed.
/// - Zero shuffle means compact low placement, not the original fixed bass
/// octaves. Repeated branches may have different voicings at different indices.
/// - Path randomness is independent of key, mode, voice count, and shuffle.
/// - This is caller-seeded musical pseudorandomness, not unpredictable entropy.
/// - Both output functions return only chords; MIDI 0 is a valid note, not rest.
contract Branches {
enum Mode { Original, StackedThirds, Parallel }
struct Params {
uint8 key; // 0=C ... 11=B
uint8[7] scale; // Strictly ascending offsets, first=0, last<=11
Mode mode; // 0=Original, 1=StackedThirds, 2=Parallel
uint8 chordCount; // 1..32
uint8 startBranch; // 0..5, or 255 for seeded choice from [0,1,2,4]
bool closeLoop; // One-chord closed loops are rejected (no self edges)
uint8 thirdCount; // StackedThirds only: 3=triad ... 7=13th
uint8[] shape; // Parallel only: unique pitch-class offsets 0..11
uint8 lowNote; // Inclusive MIDI bound, 0..127
uint8 highNote; // Inclusive MIDI bound, lowNote..127
uint8 voiceCount; // 1..16; crop highest final pitches
uint8 shuffleAmount; // 0..100; octave relocation probability and reach
}
error InvalidKey();
error InvalidScale();
error InvalidCount();
error InvalidBranch();
error InvalidThirdCount();
error InvalidShape();
error InvalidRange();
error InvalidVoices();
error InvalidShuffle();
error NoClosedPath();
error InsufficientRange(uint8 branch, uint256 available, uint256 requested);
/// @notice Same pitches/order as generateBytes, one inner array per chord.
function generate(Params calldata p, uint256 seed) external pure returns (uint8[][] memory out) {
bytes[] memory packed = generateBytes(p, seed);
out = new uint8[][](packed.length);
for (uint256 i; i < packed.length; ++i) {
out[i] = new uint8[](packed[i].length);
for (uint256 j; j < packed[i].length; ++j) out[i][j] = uint8(packed[i][j]);
}
}
/// @notice One byte per MIDI note. No headers, durations, or terminators.
function generateBytes(Params calldata p, uint256 seed) public pure returns (bytes[] memory out) {
_validate(p);
uint8[] memory path = generatePath(p.chordCount, p.startBranch, p.closeLoop, seed);
out = new bytes[](path.length);
for (uint256 i; i < path.length; ++i) {
out[i] = _voice(p, path[i], uint256(keccak256(abi.encode(seed, "VOICING", i))));
}
}
/// @notice Inspect/reuse the root path independently of harmony and voicing.
function generatePath(uint8 count, uint8 start, bool closeLoop, uint256 seed)
public pure returns (uint8[] memory path)
{
if (count == 0 || count > 32) revert InvalidCount();
if (start == 255) {
uint8[4] memory starts = [uint8(0), 1, 2, 4];
start = starts[_rand(seed, "START", 0) % 4];
} else if (start > 5) revert InvalidBranch();
// reachable[k] is the set of nodes with a path of exactly k edges to start.
uint8[33] memory reachable;
reachable[0] = uint8(1 << start);
if (closeLoop) {
for (uint256 k = 1; k <= count; ++k) {
for (uint8 b; b < 6; ++b) {
if ((_edges(b) & reachable[k - 1]) != 0) reachable[k] |= uint8(1 << b);
}
}
if ((reachable[count] & uint8(1 << start)) == 0) revert NoClosedPath();
}
path = new uint8[](count);
path[0] = start;
for (uint256 i = 1; i < count; ++i) {
uint8 options = _edges(path[i - 1]);
if (closeLoop) options &= reachable[count - i];
path[i] = _choose(options, _rand(seed, "PATH", i));
}
}
/// @notice Explicit harmonic roots are the first degrees of original shapes.
/// @dev Original bass accompaniment used a different mapping for branch 1.
function rootDegree(uint8 branch) public pure returns (uint8) {
if (branch > 5) revert InvalidBranch();
uint8[6] memory roots = [uint8(0), 6, 3, 4, 5, 6];
return roots[branch];
}
function branchDegrees(uint8 branch) public pure returns (uint8[4] memory) {
if (branch > 5) revert InvalidBranch();
uint8[4][6] memory degrees = [
[uint8(0), 2, 6, 1], [uint8(6), 1, 4, 6],
[uint8(3), 5, 2, 4], [uint8(4), 6, 1, 3],
[uint8(5), 2, 0, 4], [uint8(6), 5, 1, 3]
];
return degrees[branch];
}
function _validate(Params calldata p) private pure {
if (p.key > 11) revert InvalidKey();
if (p.scale[0] != 0) revert InvalidScale();
for (uint256 i = 1; i < 7; ++i)
if (p.scale[i] <= p.scale[i - 1] || p.scale[i] > 11) revert InvalidScale();
if (p.lowNote > p.highNote || p.highNote > 127) revert InvalidRange();
if (p.voiceCount == 0 || p.voiceCount > 16) revert InvalidVoices();
if (p.shuffleAmount > 100) revert InvalidShuffle();
if (p.mode == Mode.StackedThirds && (p.thirdCount < 3 || p.thirdCount > 7))
revert InvalidThirdCount();
if (p.mode == Mode.Parallel) {
if (p.shape.length == 0 || p.shape.length > 12) revert InvalidShape();
uint256 seen;
for (uint256 i; i < p.shape.length; ++i) {
uint256 pc = p.shape[i];
if (pc > 11 || (seen & (1 << pc)) != 0) revert InvalidShape();
seen |= 1 << pc;
}
}
}
function _tones(Params calldata p, uint8 branch) private pure returns (uint8[] memory tones) {
uint8 root = rootDegree(branch);
if (p.mode == Mode.Original) {
uint8[4] memory degrees = branchDegrees(branch);
tones = new uint8[](4);
for (uint256 i; i < 4; ++i) tones[i] = (p.key + p.scale[degrees[i]]) % 12;
} else if (p.mode == Mode.StackedThirds) {
tones = new uint8[](p.thirdCount);
for (uint256 i; i < tones.length; ++i) tones[i] = (p.key + p.scale[(root + 2 * i) % 7]) % 12;
} else {
tones = new uint8[](p.shape.length);
uint256 rootPC = (p.key + p.scale[root]) % 12;
for (uint256 i; i < tones.length; ++i) tones[i] = uint8((rootPC + p.shape[i]) % 12);
}
}
function _voice(Params calldata p, uint8 branch, uint256 seed) private pure returns (bytes memory out) {
uint8[] memory tones = _tones(p, branch);
uint8[16] memory notes;
bool[128] memory used;
uint256 n;
uint256 mask;
// Place each source tone at its lowest unused octave within range.
// Original branch 1's repeated degree retains its octave doubling if it fits.
for (uint256 t; t < tones.length; ++t) {
mask |= 1 << tones[t];
for (uint256 midi = p.lowNote; midi <= p.highNote; ++midi) {
if (midi % 12 == tones[t] && !used[midi]) {
notes[n++] = uint8(midi);
used[midi] = true;
break;
}
}
}
// Add the lowest unoccupied octave copies when more voices are requested.
for (uint256 midi = p.lowNote; n < p.voiceCount && midi <= p.highNote; ++midi) {
if ((mask & (1 << (midi % 12))) != 0 && !used[midi]) {
notes[n++] = uint8(midi);
used[midi] = true;
}
}
if (n < p.voiceCount) revert InsufficientRange(branch, n, p.voiceCount);
// Canonical order makes parallel shape input order immaterial.
_sort(notes, n);
if (p.shuffleAmount != 0) _shuffle(notes, n, used, p, seed);
_sort(notes, n);
out = new bytes(p.voiceCount);
for (uint256 i; i < p.voiceCount; ++i) out[i] = bytes1(notes[i]);
}
function _shuffle(uint8[16] memory notes, uint256 n, bool[128] memory used,
Params calldata p, uint256 seed) private pure
{
uint256 maxOctaves = (uint256(p.highNote) - p.lowNote) / 12;
uint256 reach = (maxOctaves * p.shuffleAmount + 99) / 100;
for (uint256 i; i < n; ++i) {
if (_rand(seed, "MOVE", i) % 100 >= p.shuffleAmount) continue;
uint8 old = notes[i];
uint8[11] memory candidates;
uint256 count;
for (uint256 midi = old % 12; midi <= p.highNote; midi += 12) {
uint256 distance = midi > old ? midi - old : old - midi;
if (midi >= p.lowNote && !used[midi] && distance <= reach * 12)
candidates[count++] = uint8(midi);
}
if (count == 0) continue;
uint8 next = candidates[_rand(seed, "OCTAVE", i) % count];
used[old] = false;
used[next] = true;
notes[i] = next;
}
}
function _sort(uint8[16] memory notes, uint256 n) private pure {
for (uint256 i = 1; i < n; ++i) {
uint8 v = notes[i];
uint256 j = i;
while (j > 0 && notes[j - 1] > v) { notes[j] = notes[j - 1]; --j; }
notes[j] = v;
}
}
function _edges(uint8 branch) private pure returns (uint8) {
uint8[6] memory masks = [uint8(62), 61, 59, 53, 47, 23];
return masks[branch];
}
function _choose(uint8 mask, uint256 random) private pure returns (uint8) {
uint256 count;
for (uint8 b; b < 6; ++b) if ((mask & uint8(1 << b)) != 0) ++count;
if (count == 0) revert NoClosedPath();
uint256 pick = random % count;
for (uint8 b; b < 6; ++b) {
if ((mask & uint8(1 << b)) != 0) {
if (pick == 0) return b;
--pick;
}
}
revert NoClosedPath();
}
function _rand(uint256 seed, bytes32 domain, uint256 index) private pure returns (uint256) {
return uint256(keccak256(abi.encode(seed, domain, index)));
}
}
contracts/1of1s/contracts/contracts 11-17d bass and controller/panoramaParts.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @title panoramaParts — chord-only sequencing for Branches outputs
/// @notice Three clocks, one pattern type. No storage, external calls or audio settings.
/// @dev A tick is 1/32 note: 8 per beat, 32 per 4/4 bar. MIDI zero is valid.
/// V2 adds targetTicks to Pattern: a new ABI and deployment are required.
contract panoramaParts {
uint16 public constant TICKS_PER_BEAT = 8;
uint16 public constant TICKS_PER_BAR = 32;
uint16 public constant MAX_TICKS = 4096;
uint16 public constant MAX_EVENTS = 2048;
/// @dev Same definition for harmony, subrhythm and note rhythm.
struct Pattern {
uint16[] durations; // Allowed durations in ticks; [4] fixes eighth notes
uint8 steps; // 1..32 fixed count; 0 = auto count in target mode only
uint16 targetTicks; // 0 = legacy step mode; otherwise exact phrase length, <=4096
}
struct Params {
Pattern harmony; // Each step advances to the next supplied chord
Pattern subrhythm; // Each step chooses a different seeded group of chord tones
Pattern noteRhythm; // Each step is a potential trigger for the current group
uint8 tones; // 0 = all supplied chord tones, otherwise 1..16
uint8 density; // 0..100 hit probability for each note-rhythm step
uint8 gate; // 1..100 percent of note-rhythm step, at least one tick
bool roundToBar; // Pad progression end with silence to a whole 4/4 bar
}
struct Seeds { uint256 harmony; uint256 subrhythm; uint256 noteRhythm; }
struct Phrase {
uint16[] durations; // Actual chosen durations, in order
uint16 totalTicks; // Sum of durations: this pattern's phrase length
}
struct Note { uint8 note; uint16 start; uint16 duration; uint8 velocity; }
struct Result {
Phrase harmony;
Phrase subrhythm;
Phrase noteRhythm;
bool[] hits; // Repeating note-rhythm hit/rest mask
uint16[] chordEnds; // Cumulative, exclusive chord boundaries
uint16 activeTicks;
uint16 totalTicks; // Loop length including optional ending silence
Note[] notes; // Simultaneous chord tones share a start tick
}
struct Cursor { uint256 count; uint256 chord; uint256 step; uint256 time; }
struct State {
bytes[] chords;
uint256 width;
uint16[] ends;
Phrase groups;
Phrase rhythm;
bool[] hits;
}
error InvalidChords();
error InvalidNotes();
error InvalidPattern();
error TargetNotReachable();
error InvalidParams();
error HarmonyMustDivideChordCount();
error TooManyEvents();
error InvalidPackedTiming();
/// @notice Accept uint8[][] from Branches.generate. No roots or other parts needed.
function generate(uint8[][] calldata chords, Params calldata p, Seeds calldata seeds)
external pure returns (Result memory)
{
if (chords.length == 0 || chords.length > 32) revert InvalidChords();
bytes[] memory packed = new bytes[](chords.length);
for (uint256 i; i < chords.length; ++i) {
if (chords[i].length == 0 || chords[i].length > 16) revert InvalidChords();
packed[i] = new bytes(chords[i].length);
for (uint256 j; j < chords[i].length; ++j) packed[i][j] = bytes1(chords[i][j]);
}
return _generate(packed,p,seeds);
}
/// @notice Accept bytes[] from Branches.generateBytes; returns the same Result.
function generateBytes(bytes[] calldata chords, Params calldata p, Seeds calldata seeds)
external pure returns (Result memory)
{
return _generate(chords,p,seeds);
}
/// @notice Use this same helper to preview any of the three rhythm phrases.
/// @dev Repeated allowed durations provide weighting; randomness is caller-seeded.
function makePattern(Pattern memory p, uint256 seed) public pure returns (Phrase memory) {
return _makePattern(p,seed,0);
}
/// @notice Preview harmony with the same chord-count constraint used by generate.
function makeHarmonyPattern(Pattern memory p, uint256 seed, uint8 chordCount)
external pure returns (Phrase memory)
{
if (chordCount == 0 || chordCount > 32) revert InvalidChords();
return _makePattern(p,seed,chordCount);
}
/// @dev Target mode never clips or invents durations. Duplicate durations retain
/// their weighting among choices that can still complete the exact target.
/// Automatic step count is chosen uniformly among feasible counts, not phrases.
function _makePattern(Pattern memory p, uint256 seed, uint256 chordCount)
private pure returns (Phrase memory phrase)
{
if (p.steps > 32 || p.durations.length == 0 || p.durations.length > 32 ||
p.targetTicks > MAX_TICKS || (p.steps == 0 && p.targetTicks == 0))
revert InvalidPattern();
for (uint256 i; i < p.durations.length; ++i)
if (p.durations[i] == 0 || p.durations[i] > 128) revert InvalidPattern();
if (p.steps != 0 && chordCount != 0 && chordCount % p.steps != 0)
revert HarmonyMustDivideChordCount();
if (p.targetTicks == 0) {
phrase.durations = new uint16[](p.steps);
for (uint256 i; i < p.steps; ++i) {
uint16 d = p.durations[_rand(seed,"DURATION",i) % p.durations.length];
phrase.durations[i] = d;
phrase.totalTicks += d;
}
return phrase;
}
// Bitset DP: reachable[n][t] iff n allowed durations can sum to t.
// At most 33 rows * 17 words; shifts avoid a per-tick inner loop.
uint256 words = uint256(p.targetTicks) / 256 + 1;
uint256 limit = p.steps == 0 ? 32 : p.steps;
uint256[] memory reachable = new uint256[]((limit+1)*words);
reachable[0] = 1;
for (uint256 n = 1; n <= limit; ++n) {
for (uint256 j; j < p.durations.length; ++j) {
uint256 d = p.durations[j]; // 1..128: always less than one word
for (uint256 w; w < words; ++w) {
uint256 bits = reachable[(n-1)*words+w];
reachable[n*words+w] |= bits << d;
if (w+1 < words) reachable[n*words+w+1] |= bits >> (256-d);
}
}
}
uint256 count = p.steps;
if (count == 0) {
uint256 choices;
for (uint256 n = 1; n <= limit; ++n)
if ((chordCount == 0 || chordCount % n == 0) &&
_reachable(reachable,words,n,p.targetTicks)) ++choices;
if (choices == 0) revert TargetNotReachable();
uint256 pick = _rand(seed,"STEPS",0) % choices;
for (uint256 n = 1; n <= limit; ++n) {
if ((chordCount == 0 || chordCount % n == 0) &&
_reachable(reachable,words,n,p.targetTicks)) {
if (pick == 0) { count = n; break; }
--pick;
}
}
} else if (!_reachable(reachable,words,count,p.targetTicks)) {
revert TargetNotReachable();
}
phrase.durations = new uint16[](count);
phrase.totalTicks = p.targetTicks;
uint256 remaining = p.targetTicks;
for (uint256 i; i < count; ++i) {
uint16[32] memory candidates;
uint256 choices;
for (uint256 j; j < p.durations.length; ++j) {
uint16 d = p.durations[j];
if (d <= remaining && _reachable(reachable,words,count-i-1,remaining-d))
candidates[choices++] = d;
}
uint16 chosen = candidates[_rand(seed,"DURATION",i) % choices];
phrase.durations[i] = chosen;
remaining -= chosen;
}
}
function _reachable(uint256[] memory table,uint256 words,uint256 count,uint256 ticks)
private pure returns (bool)
{
return (table[count*words+ticks/256] & (uint256(1) << (ticks%256))) != 0;
}
/// @notice One bar per chord; 4-group subphrase; eight eighth-note trigger steps.
function defaults() external pure returns (Params memory p) {
p.harmony = Pattern(_one(32),1,0);
p.subrhythm = Pattern(_one(8),4,0);
p.noteRhythm = Pattern(_one(4),8,0);
p.tones = 2; p.density = 75; p.gate = 85; p.roundToBar = true;
}
function seedsFrom(uint256 seed) external pure returns (Seeds memory) {
return Seeds(_rand(seed,"HARMONY",0),_rand(seed,"SUBRHYTHM",0),_rand(seed,"NOTE_RHYTHM",0));
}
function _generate(bytes[] memory chords, Params calldata p, Seeds calldata seeds)
private pure returns (Result memory out)
{
uint256 width = _validateChords(chords);
if (p.tones > 16 || p.density > 100 || p.gate == 0 || p.gate > 100) revert InvalidParams();
out.harmony = _makePattern(p.harmony,seeds.harmony,chords.length);
out.subrhythm = makePattern(p.subrhythm,seeds.subrhythm);
out.noteRhythm = makePattern(p.noteRhythm,seeds.noteRhythm);
uint256 harmonySteps = out.harmony.durations.length;
out.chordEnds = new uint16[](chords.length);
for (uint256 i; i < chords.length; ++i) {
out.activeTicks += out.harmony.durations[i % harmonySteps];
out.chordEnds[i] = out.activeTicks;
}
// 32 chords * 128 ticks <= MAX_TICKS, also for bar padding.
out.totalTicks = p.roundToBar ? uint16((uint256(out.activeTicks)+31)/32*32) : out.activeTicks;
out.hits = new bool[](out.noteRhythm.durations.length);
for (uint256 i; i < out.hits.length; ++i)
out.hits[i] = _rand(seeds.noteRhythm,"HIT",i) % 100 < p.density;
State memory s = State(chords,width,out.chordEnds,out.subrhythm,out.noteRhythm,out.hits);
out.notes = _notes(s,p,seeds.subrhythm);
}
function _notes(State memory s, Params calldata p, uint256 seed) private pure returns (Note[] memory out) {
uint256 active = s.ends[s.ends.length-1];
out = new Note[](_min(MAX_EVENTS,active * (p.tones == 0 ? s.width : _min(s.width,p.tones))));
Cursor memory cursor;
while (cursor.time < active) {
while (cursor.time >= s.ends[cursor.chord]) ++cursor.chord;
uint256 step = cursor.step % s.rhythm.durations.length;
uint256 duration = s.rhythm.durations[step];
if (s.hits[step]) {
uint256 slot = _slot(s.groups,cursor.time % s.groups.totalTicks);
bytes memory group = _group(s.chords[cursor.chord],p.tones,s.width,seed,slot);
uint256 hold = duration * p.gate / 100;
if (hold == 0) hold = 1;
hold = _min(hold,s.ends[cursor.chord]-cursor.time);
for (uint256 j; j < group.length; ++j) {
if (cursor.count == out.length) revert TooManyEvents();
out[cursor.count++] = Note(uint8(group[j]),uint16(cursor.time),uint16(hold),100);
}
}
cursor.time += duration;
++cursor.step;
}
uint256 count = cursor.count;
assembly { mstore(out,count) }
}
/// @dev A shuffled register ranking is shared across chords for each subrhythm slot.
function _group(bytes memory chord,uint8 tones,uint256 width,uint256 seed,uint256 slot)
private pure returns (bytes memory out)
{
uint256 n = tones == 0 ? chord.length : _min(tones,chord.length);
out = new bytes(n);
uint8[16] memory ranks;
for (uint256 i; i < width; ++i) ranks[i] = uint8(i);
for (uint256 i = width-1; i > 0; --i) {
uint256 j = _rand(seed,"GROUP",slot*16+i) % (i+1);
(ranks[i],ranks[j]) = (ranks[j],ranks[i]);
}
uint256 used; uint256 count;
for (uint256 i; i < width && count < n; ++i) {
uint256 index = uint256(ranks[i])*chord.length/width;
if ((used & (1 << index)) != 0) continue;
used |= 1 << index; out[count++] = chord[index];
}
}
function _slot(Phrase memory phrase,uint256 phase) private pure returns (uint256) {
for (uint256 i; i < phrase.durations.length; ++i) {
if (phase < phrase.durations[i]) return i;
phase -= phrase.durations[i];
}
revert InvalidPattern();
}
function _validateChords(bytes[] memory chords) private pure returns (uint256 width) {
if (chords.length == 0 || chords.length > 32) revert InvalidChords();
for (uint256 i; i < chords.length; ++i) {
uint256 n = chords[i].length;
if (n == 0 || n > 16) revert InvalidChords();
if (n > width) width = n;
uint256 used;
for (uint256 j; j < n; ++j) {
uint8 note = uint8(chords[i][j]);
if (note > 127 || (used & (uint256(1) << note)) != 0) revert InvalidNotes();
used |= uint256(1) << note;
}
}
}
/// @notice Optional adapter to existing 7-byte note format; no header/terminator.
/// @dev note(1), start ms(3), duration ms(2), velocity(1), big-endian.
/// Loop length is separate. Oversize milliseconds revert, never truncate.
function pack7(Note[] calldata notes,uint16 bpm) external pure returns (bytes memory out) {
if (bpm < 30 || bpm > 240 || notes.length > MAX_EVENTS) revert InvalidPackedTiming();
out = new bytes(notes.length*7);
for (uint256 i; i < notes.length; ++i) {
Note calldata n = notes[i];
if (n.note > 127 || n.velocity == 0 || n.velocity > 127 || n.duration == 0)
revert InvalidPackedTiming();
uint256 start = uint256(n.start)*60000/(uint256(bpm)*8);
uint256 duration = uint256(n.duration)*60000/(uint256(bpm)*8);
if (start > 0xffffff || duration == 0 || duration > 0xffff) revert InvalidPackedTiming();
uint256 j = i*7;
out[j] = bytes1(n.note); out[j+1] = bytes1(uint8(start >> 16));
out[j+2] = bytes1(uint8(start >> 8)); out[j+3] = bytes1(uint8(start));
out[j+4] = bytes1(uint8(duration >> 8)); out[j+5] = bytes1(uint8(duration));
out[j+6] = bytes1(n.velocity);
}
}
function _one(uint16 value) private pure returns (uint16[] memory a) { a = new uint16[](1); a[0] = value; }
function _min(uint256 a,uint256 b) private pure returns (uint256) { return a < b ? a : b; }
function _rand(uint256 seed,bytes32 domain,uint256 index) private pure returns (uint256) {
return uint256(keccak256(abi.encode(seed,domain,index)));
}
}
Настройки компилятораПоказать
{
"viaIR": true,
"optimizer": {
"runs": 200,
"enabled": true
},
"remappings": []
}Исходный код и метаданные: Sourcify.
Исходный код принадлежит авторам контракта.