Giuliani studies as own material category; beam-before-draw fix

- NEW material 'giuliani': figures require a real voicing — the generator
  assigns cycle positions (bass root + upper chord tones) to DISTINCT
  strings with valid frets per bar; bars that cannot be voiced are skipped
  (deterministic), clear error when nothing fits. Patterns: p-i-m, p-i-m-a,
  p-a-m-i, a-i-m, p-i-m-a-m-i, p-m-a-m-i-m. Honors the chord pool, string
  restrictions and the tuning; one figure per beat.
- 6/8 meter added (numerator 6) across score model, settings, generators;
  meter selects now offer 4/4, 3/4, 6/8.
- Arpeggio category: Giuliani entries replaced with note-sequence
  broken-chord figures (1-3-2-1, 1-3-2-5(8), 1-5-3-5(8), 1-2-3-5-3) —
  pure pitch sequences, no voicing claims.
- Beam fix (root cause): setBeam now happens BEFORE voice.draw — VexFlow
  decides flag vs beam at draw time; registering after drawing left both
  flag and beam. Beams drawn after notes, flags suppressed correctly.
This commit is contained in:
OpenClaw
2026-09-15 02:44:52 +00:00
parent 9acf32a32f
commit ffb2776c8c
9 changed files with 412 additions and 69 deletions

View File

@@ -324,9 +324,33 @@ export const PhraseSheetMusic: React.FC<PhraseSheetMusicProps> = ({
formatter.joinVoices(voices.map(v => v.voice));
formatter.format(voices.map(v => v.voice), formatWidth);
// --- Beams: BEFORE drawing notes. setBeam must happen prior to
// voice.draw — VexFlow decides flag vs beam on this.beam at
// draw time; registering late leaves BOTH flag and beam.
const beamPairs: { a: Fragment; b2: Fragment }[] = [];
const beamed = frags.filter(f => (f.isEighth || f.isSixteenth) && f.note instanceof StaveNote);
for (let i = 0; i + 1 < beamed.length; i++) {
const a = beamed[i], b2 = beamed[i + 1];
if (a.staveKey !== b2.staveKey) continue;
const step = a.isSixteenth ? 120 : 240;
if (b2.start - a.start !== step) continue;
if ((a.ticks !== step) || (b2.ticks !== step)) continue;
const beatA = Math.floor((a.start - measureStart) / 480);
const beatB = Math.floor((b2.start - measureStart) / 480);
if (beatA === beatB) beamPairs.push({ a, b2 });
}
// Apply beams to notes FIRST (suppresses flags), then draw.
const beams = beamPairs.map(({ a, b2 }) => {
const beam = new Beam([a.note, b2.note], false);
a.note.setBeam(beam);
b2.note.setBeam(beam);
return beam;
});
treble.setContext(context).draw();
if (bass) bass.setContext(context).draw();
for (const { voice, stave } of voices) voice.draw(context, stave);
for (const beam of beams) beam.setContext(context).draw();
if (isGrand && isFirstOfRow) {
const brace = new StaveConnector(treble, bass!);
@@ -337,27 +361,6 @@ export const PhraseSheetMusic: React.FC<PhraseSheetMusicProps> = ({
line.setContext(context).draw();
}
// --- Beams: consecutive eighth/16th pairs within one beat ---
// Note: the Beam must be registered on each note via setBeam,
// otherwise VexFlow still draws flags (beam === undefined in
// shouldDrawFlag) and you get BOTH flag and beam.
const beamed = frags.filter(f => (f.isEighth || f.isSixteenth) && f.note instanceof StaveNote);
for (let i = 0; i + 1 < beamed.length; i++) {
const a = beamed[i], b2 = beamed[i + 1];
if (a.staveKey !== b2.staveKey) continue;
// consecutive within the same beat, same subdivision size
const step = a.isSixteenth ? 120 : 240;
if (b2.start - a.start !== step) continue;
if ((a.ticks !== step) || (b2.ticks !== step)) continue;
const beatA = Math.floor((a.start - measureStart) / 480);
const beatB = Math.floor((b2.start - measureStart) / 480);
if (beatA === beatB) {
const beam = new Beam([a.note, b2.note], false);
a.note.setBeam(beam);
b2.note.setBeam(beam);
beam.setContext(context).draw();
}
}
}
// --- Ties between consecutive fragments of one event (this row) ---

View File

@@ -20,6 +20,7 @@ import { computePlayableNotes, isFrettedInstrument, positionsWithinWindow } from
import { generateMelody } from '../music/melodyGenerator';
import { generateScaleDrill } from '../music/scaleDrills';
import { generateArpeggio, type ArpeggioDegree } from '../music/arpeggioGenerator';
import { generateGiulianiStudy, GIULIANI_PATTERN_LABELS, type GiulianiPattern } from '../music/giulianiGenerator';
import { isMode, type ModeId } from '../music/scales';
import { ARPEGGIO_DEGREE_LABELS } from '../music/arpeggioGenerator';
import { scoreEvents, type Result, type Score, type ScoreEvent } from '../score/model';
@@ -191,6 +192,19 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
rhythm: phrase.scaleRhythm,
}, pool);
}
if (phrase.material === 'giuliani') {
return generateGiulianiStudy({
keyTonic: phrase.keyTonic,
keyMode: (isMode(phrase.keyMode) ? phrase.keyMode : 'major') as ModeId,
pattern: phrase.giulianiPattern,
meter: { numerator: phrase.meterNumerator, denominator: 4 },
tuningId: settings.tuningId,
bars: phrase.giulianiBars,
chordSelection: phrase.arpeggioChordSelection as string[],
seed: melodySeed,
allowedStrings: pf.strings,
}, pool);
}
if (phrase.material === 'arpeggio') {
return generateArpeggio({
keyTonic: phrase.keyTonic,
@@ -221,6 +235,7 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
phrase.arpeggioDegree, phrase.arpeggioPattern, phrase.arpeggioCoverage,
phrase.arpeggioBars, phrase.arpeggioProgression, phrase.arpeggioRhythm,
phrase.arpeggioChordSelection, melodySeed,
phrase.giulianiPattern, phrase.giulianiBars,
melodySeed, pool, importedScore]);
const fullScore: Result<Score> | null = useMemo(() => {
@@ -557,6 +572,7 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
<option value="melody">Melodies (generated)</option>
<option value="scale">Scale drills</option>
<option value="arpeggio">Arpeggios (generated)</option>
<option value="giuliani">Giuliani studies</option>
<option value="library">Exercises</option>
<option value="import">Imported file</option>
</select>
@@ -576,9 +592,10 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
</select>
</label>
<label>Meter
<select value={phrase.meterNumerator} onChange={e => setPhrase({ meterNumerator: Number(e.target.value) === 3 ? 3 : 4 })}>
<select value={phrase.meterNumerator} onChange={e => setPhrase({ meterNumerator: Math.max(3, Math.min(6, Number(e.target.value))) as 3 | 4 | 6 })}>
<option value={4}>4/4</option>
<option value={3}>3/4</option>
<option value={6}>6/8</option>
</select>
</label>
<label>Rhythm
@@ -608,9 +625,10 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
</select>
</label>
<label>Meter
<select value={phrase.meterNumerator} onChange={e => setPhrase({ meterNumerator: Number(e.target.value) === 3 ? 3 : 4 })}>
<select value={phrase.meterNumerator} onChange={e => setPhrase({ meterNumerator: Math.max(3, Math.min(6, Number(e.target.value))) as 3 | 4 | 6 })}>
<option value={4}>4/4</option>
<option value={3}>3/4</option>
<option value={6}>6/8</option>
</select>
</label>
</>
@@ -624,14 +642,11 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
<option value="down">Down</option>
<option value="updown">Up &amp; down</option>
<option value="1235">1-2-3-5</option>
<optgroup label="Giuliani studies">
<option value="giuliani-pim">p-i-m</option>
<option value="giuliani-pima">p-i-m-a</option>
<option value="giuliani-pami">p-a-m-i</option>
<option value="giuliani-aim">a-i-m</option>
<option value="giuliani-pimamim">p-i-m-a-m-i</option>
<option value="giuliani-pmamim">p-m-a-m-i-m</option>
<option value="giuliani-peamama">p-e-a-m-a-m</option>
<optgroup label="Broken-chord figures">
<option value="1321">1-3-2-1</option>
<option value="1325">1-3-2-5(8)</option>
<option value="1535">1-5-3-5(8)</option>
<option value="12353">1-2-3-5-3</option>
</optgroup>
</select>
</label>
@@ -688,14 +703,42 @@ export const PhraseTrainer = forwardRef<PhraseHandle, PhraseTrainerProps>(
</select>
</label>
<label>Meter
<select value={phrase.meterNumerator} onChange={e => setPhrase({ meterNumerator: Number(e.target.value) === 3 ? 3 : 4 })}>
<select value={phrase.meterNumerator} onChange={e => setPhrase({ meterNumerator: Math.max(3, Math.min(6, Number(e.target.value))) as 3 | 4 | 6 })}>
<option value={4}>4/4</option>
<option value={3}>3/4</option>
<option value={6}>6/8</option>
</select>
</label>
</>
)}
{phrase.material === 'giuliani' && (
<>
<label>Pattern
<select value={phrase.giulianiPattern} onChange={e => setPhrase({ giulianiPattern: e.target.value as PhraseSettings['giulianiPattern'] })}>
{(Object.keys(GIULIANI_PATTERN_LABELS) as GiulianiPattern[]).map(p => (
<option key={p} value={p}>{GIULIANI_PATTERN_LABELS[p]}</option>
))}
</select>
</label>
<label>Length
<select value={phrase.giulianiBars} onChange={e => setPhrase({ giulianiBars: Math.max(1, Math.min(8, Number(e.target.value))) })}>
{[1, 2, 4, 6, 8].map(b => <option key={b} value={b}>{b} bars</option>)}
</select>
</label>
<label>Meter
<select value={phrase.meterNumerator} onChange={e => setPhrase({ meterNumerator: Math.max(3, Math.min(6, Number(e.target.value))) as 3 | 4 | 6 })}>
<option value={4}>4/4</option>
<option value={3}>3/4</option>
<option value={6}>6/8</option>
</select>
</label>
<span style={{ fontSize: '11px', opacity: 0.7, alignSelf: 'center' }}>
Chords: from the arpeggio chord pool; voicing enforced (bass + upper strings).
</span>
</>
)}
{phrase.material === 'library' && (
<label>Exercise
<select value={phrase.libraryId || EXERCISES[0].id} onChange={e => setPhrase({ libraryId: e.target.value, startBar: 1 })}>

View File

@@ -18,13 +18,10 @@ export type ArpeggioPattern =
| 'up' | 'down' | 'updown' | '1235'
// Giuliani-style right-hand figures over one chord (indices into the
// chord cycle per note; 1=root 2=third 3=fifth 4=octave):
| 'giuliani-pim' // root-third-fifth (p-i-m)
| 'giuliani-pima' // root-third-fifth-octave (p-i-m-a)
| 'giuliani-pami' // root-octave-fifth-third (p-a-m-i)
| 'giuliani-aim' // root-octave-third (upper voices first)
| 'giuliani-pimamim' // p-i-m-a-m-i (six-note rolling figure)
| 'giuliani-pmamim' // p-m-a-m-i-m (asymmetric upper-voice figure)
| 'giuliani-peamama'; // p-e-a-m-a-m (wide bass + upper pairs)
| '1321' // root-fifth-third-root
| '1325' // root-fifth-third-octave
| '1535' // root-octave-fifth-octave
| '12353'; // root-third-fifth-octave-fifth
export type ArpeggioCoverage = 'one-octave' | 'two-octave';
/** How the chord per bar is chosen in sequence mode. */
export type ArpeggioProgression = 'random' | 'functional' | 'diatonic-cycle';
@@ -37,7 +34,7 @@ export interface ArpeggioConfig {
readonly degree: ArpeggioDegree;
readonly pattern: ArpeggioPattern;
readonly coverage: ArpeggioCoverage;
readonly meter: { readonly numerator: 3 | 4; readonly denominator: 4 };
readonly meter: { readonly numerator: 3 | 4 | 6; readonly denominator: 4 };
/** Sequence mode: bars > 1 with chord progression selection. */
readonly bars?: number;
readonly progression?: ArpeggioProgression;
@@ -60,13 +57,10 @@ export const ARPEGGIO_DEGREE_LABELS: Record<ArpeggioDegree, string> = {
export const PATTERN_LABELS: Record<ArpeggioPattern, string> = {
up: 'Up', down: 'Down', updown: 'Up & down', '1235': '1-2-3-5',
'giuliani-pim': 'Giuliani p-i-m',
'giuliani-pima': 'Giuliani p-i-m-a',
'giuliani-pami': 'Giuliani p-a-m-i',
'giuliani-aim': 'Giuliani a-i-m',
'giuliani-pimamim': 'Giuliani p-i-m-a-m-i',
'giuliani-pmamim': 'Giuliani p-m-a-m-i-m',
'giuliani-peamama': 'Giuliani p-e-a-m-a-m',
'1321': '1-3-2-1',
'1325': '1-3-2-5(8)',
'1535': '1-5-3-5(8)',
'12353': '1-2-3-5-3',
};
/**
@@ -76,21 +70,13 @@ export const PATTERN_LABELS: Record<ArpeggioPattern, string> = {
* figure repeats with an ascending octave shift per repetition (the bass
* stays in place — like the Maestoso studies).
*/
const GIULIANI_FIGURES: Record<string, number[]> = {
// Studies 1–20 feel: bass + two upper voices, ascending
'giuliani-pim': [0, 1, 2],
// Studies 21–40 feel: bass + three upper voices
'giuliani-pima': [0, 1, 2, 3],
// Descending upper voices after the bass
'giuliani-pami': [0, 3, 2, 1],
// Upper voices first (a-i-m), bass anchored at start of each cycle
'giuliani-aim': [0, 3, 1],
// Six-note rolling figure (studies 61–80 territory)
'giuliani-pimamim': [0, 1, 2, 3, 2, 1],
// Asymmetric: bass + upper triad roll
'giuliani-pmamim': [0, 2, 3, 2, 1, 2],
// Wide: bass, fifth, octave, then upper-voice pairs
'giuliani-peamama': [0, 2, 3, 1, 3, 1],
// Broken-chord figures — NOTE sequences on the cycle [0=root, 1=third,
// 2=fifth, 3=octave]; register ascends per repetition.
const BROKEN_FIGURES: Record<string, number[]> = {
'1321': [0, 2, 1, 0],
'1325': [0, 2, 1, 3],
'1535': [0, 3, 2, 3],
'12353': [0, 1, 2, 3, 2],
};
/** pc of a spelled degree (step letter + alter). */
@@ -199,7 +185,7 @@ function buildPath(key: KeyContext, degreeIndex: number, pool: number[], coverag
// figure selecting cycle positions per note; the octave wraps so
// e.g. p-i-m over C-E-G becomes C E G | C' E' G' ... (ascending
// octave register shift every figure repetition).
const figure = GIULIANI_FIGURES[pattern];
const figure = BROKEN_FIGURES[pattern];
// 4-note cycle per octave: root, third, fifth, octave
const cycleOct = (oct: number): number[] => [
base[0] + 12 * oct, base[1] + 12 * oct, base[2] + 12 * oct, base[0] + 12 * (oct + 1),

View File

@@ -0,0 +1,63 @@
import { describe, it, expect } from 'vitest';
import { generateGiulianiStudy } from './giulianiGenerator';
import { scoreEvents, validateScore } from '../score/model';
const strings = [40, 45, 50, 55, 59, 64];
const pool: number[] = [];
for (const open of strings) for (let f = 0; f <= 12; f++) pool.push(open + f);
const base = {
keyTonic: 'C',
keyMode: 'major' as const,
meter: { numerator: 4 as const, denominator: 4 as const },
tuningId: 'standard',
bars: 4,
chordSelection: [] as string[],
allowedStrings: [] as number[],
};
describe('generateGiulianiStudy', () => {
it('generates a 4-bar p-i-m-a study in C major', () => {
const r = generateGiulianiStudy({ ...base, pattern: 'pima', seed: 5 }, pool);
expect(r.ok).toBe(true);
if (!r.ok) return;
const ev = scoreEvents(r.value);
expect(r.value.measures.length).toBe(4);
expect(ev.length).toBe(4 * 4 * 4); // bars × beats × figure length
expect(validateScore(r.value)).toEqual([]);
expect(r.value.title).toContain('Giuliani');
});
it('keeps figure notes on distinct strings per repetition (voicing rule)', () => {
const r = generateGiulianiStudy({ ...base, pattern: 'pima', seed: 3 }, pool);
expect(r.ok).toBe(true);
if (!r.ok) return;
// For each repetition of 4 consecutive notes, all midis must differ
// (distinct cycle positions → distinct pitches within a beat figure)
const ev = scoreEvents(r.value);
for (let i = 0; i + 3 < ev.length; i += 4) {
const four = ev.slice(i, i + 4).map(e => e.pitch!.midi);
expect(new Set(four).size).toBe(4);
}
});
it('six-note figures work (pimamim)', () => {
const r = generateGiulianiStudy({ ...base, pattern: 'pimamim', seed: 1 }, pool);
expect(r.ok).toBe(true);
if (!r.ok) return;
const ev = scoreEvents(r.value);
expect(ev.length).toBe(4 * 4 * 6);
expect(validateScore(r.value)).toEqual([]);
});
it('is deterministic per seed', () => {
const a = generateGiulianiStudy({ ...base, pattern: 'pim', seed: 9 }, pool);
const b = generateGiulianiStudy({ ...base, pattern: 'pim', seed: 9 }, pool);
expect(JSON.stringify(a) === JSON.stringify(b)).toBe(true);
});
it('honors string restrictions (fails cleanly when impossible)', () => {
const r = generateGiulianiStudy({ ...base, pattern: 'pima', seed: 2, allowedStrings: [0] }, pool);
expect(r.ok).toBe(false); // 4 voices cannot live on one string
});
});

View File

@@ -0,0 +1,243 @@
/**
* Giuliani study generator (Phrase Mode material) — its own category
* because the figures require a REAL guitar voicing: the thumb takes the
* bass (root on a lower string) and i/m/a ride higher strings. A figure is
* only playable when each consecutive voice slot maps to a distinct string
* with a valid fret in the playable pool — arbitrary chord arpeggios cannot
* guarantee that.
*
* Voicing search: for a figure of voice-count V, pick a bass string (for
* the root) and V-1 higher strings; each note of the cycle is placed on its
* designated string at the fret matching the chord tone. Figure repeats
* over the chord; every bar re-voices (deterministically) so sequences work.
*/
import { PPQ, validateScore, type Result, type Score, type ScoreEvent, STEP_LETTERS, LETTER_PC, type StepLetter } from '../score/model';
import { keyFor, type KeyContext, type ModeId } from './scales';
import { TUNINGS, type Tuning } from '../music/Tunings';
import { makeRng } from './melodyGenerator';
export type GiulianiPattern =
| 'pim' // Studies 1–20 feel: bass + two upper voices
| 'pima' // Studies 21–40: bass + three upper voices
| 'pami' // bass + descending upper voices
| 'aim' // upper voices first
| 'pimamim'// six-note rolling
| 'pmamim';// asymmetric
export const GIULIANI_PATTERN_LABELS: Record<GiulianiPattern, string> = {
pim: 'p-i-m (3 voices)',
pima: 'p-i-m-a (4 voices)',
pami: 'p-a-m-i',
aim: 'a-i-m',
pimamim: 'p-i-m-a-m-i',
pmamim: 'p-m-a-m-i-m',
};
/** Figure voice slots per repetition (indices into the cycle [root, third, fifth, octave]). */
const FIGURES: Record<GiulianiPattern, number[]> = {
pim: [0, 1, 2],
pima: [0, 1, 2, 3],
pami: [0, 3, 2, 1],
aim: [0, 3, 1],
pimamim: [0, 1, 2, 3, 2, 1],
pmamim: [0, 2, 3, 2, 1, 2],
};
export interface GiulianiConfig {
readonly keyTonic: string;
readonly keyMode: ModeId;
readonly pattern: GiulianiPattern;
readonly meter: { readonly numerator: 3 | 4 | 6; readonly denominator: 4 };
readonly tuningId: string;
/** Bars (one chord per bar). */
readonly bars: number;
/** Chord degrees allowed (empty = all 7). */
readonly chordSelection: readonly string[];
/** Seed for chord sequence + voicing choices. */
readonly seed: number;
/** Deterministic pattern from the practice filter (strings restriction). */
readonly allowedStrings: readonly number[];
}
const DEGREE_INDEX: Record<string, number> = { I: 0, ii: 1, iii: 2, IV: 3, V: 4, vi: 5, 'vii0': 6 };
const degreePc = (d: { step: StepLetter; alter: number }): number =>
(LETTER_PC[STEP_LETTERS.indexOf(d.step)] + d.alter + 144) % 12;
function chordNameFor(key: KeyContext, degreeIndex: number): string {
const d = key.degrees[degreeIndex];
const third = key.degrees[(degreeIndex + 2) % 7];
const fifth = key.degrees[(degreeIndex + 4) % 7];
const root = d.step + (d.alter < 0 ? 'b'.repeat(-d.alter) : '#'.repeat(d.alter));
const thirdInterval = (degreePc(third) - degreePc(d) + 12) % 12;
const fifthInterval = (degreePc(fifth) - degreePc(d) + 12) % 12;
let suffix = '';
if (thirdInterval === 3 && fifthInterval === 7) suffix = 'm';
else if (thirdInterval === 3 && fifthInterval === 6) suffix = 'dim';
return root + suffix;
}
interface ChordTone { readonly pc: number; readonly step: StepLetter; readonly alter: number }
/** Diatonic triad pcs for a degree, spelled. */
function triadPcs(key: KeyContext, degreeIndex: number): ChordTone[] {
return [0, 2, 4].map(o => key.degrees[(degreeIndex + o) % 7]).map(d => ({
pc: degreePc(d), step: d.step, alter: d.alter,
}));
}
/**
* Voice a figure bar: assign each cycle position (root/third/fifth/octave)
* to a string with a valid fret, bass string lowest. Returns per-slot
* {stringIndex, fret, midi} or null when impossible with the allowed strings.
*/
function voiceBar(
tuning: Tuning,
chord: ChordTone[],
pattern: GiulianiPattern,
allowedStrings: number[],
): { stringIndex: number; fret: number; midi: number }[] | null {
const figure = FIGURES[pattern];
const maxVoice = Math.max(...figure) + 1; // e.g. 3 for p-i-m, 4 for p-i-m-a
const bassPc = chord[0].pc;
// Candidate strings sorted low→high for the bass; upper voices fill above.
const strings = tuning.strings.map((open, idx) => ({ open, idx }));
const sorted = [...strings].sort((a, b) => a.open - b.open);
const usable = sorted.filter(s => allowedStrings.length === 0 || allowedStrings.includes(s.idx));
const octavePcs = [...chord.map(c => c.pc), (chord[0].pc + 12) % 12];
// cyclePcs[i] = pitch class of cycle position i
const cyclePcs = octavePcs;
const bassCandidates = usable.filter(s => {
// bass must be able to reach the root within 12 frets
for (let fret = 0; fret <= 12; fret++) {
if (((s.open + fret) % 12 + 12) % 12 === bassPc) return true;
}
return false;
});
for (const bass of bassCandidates) {
// assign remaining voices to strings above the bass
const uppers = usable.filter(s => s.open > bass.open).slice(0, maxVoice - 1);
if (uppers.length < maxVoice - 1) continue;
// Voice slots: cycle positions 1..maxVoice-1 map to uppers in order
const slotStrings: ({ open: number; idx: number } | null)[] = [bass];
for (let v = 1; v < maxVoice; v++) slotStrings.push(uppers[v - 1]);
let ok = true;
const placement: { stringIndex: number; fret: number; midi: number }[] = [];
const usedFrets = new Set<string>();
for (let slot = 0; slot < maxVoice; slot++) {
const pc = cyclePcs[slot];
const s = slotStrings[slot];
if (!s) { ok = false; break; }
let found: number | null = null;
for (let fret = 0; fret <= 12; fret++) {
if ((((s.open + fret) % 12) + 12) % 12 === pc) { found = fret; break; }
}
if (found === null) { ok = false; break; }
const midi = s.open + found;
const key = `${slot}:${found}`;
if (usedFrets.has(key)) { ok = false; break; } // same string double-stop — not for these studies
usedFrets.add(key);
placement.push({ stringIndex: s.idx, fret: found, midi });
}
if (ok) return placement;
}
return null;
}
export function generateGiulianiStudy(
config: GiulianiConfig,
eligiblePitches: number[],
): Result<Score> {
const tuning = TUNINGS[config.tuningId];
if (!tuning) return { ok: false, error: 'No tuning available for Giuliani studies — pick a fretted instrument.' };
const key = keyFor(config.keyTonic, config.keyMode);
const poolSet = new Set(eligiblePitches.filter(m => Number.isInteger(m)));
if (poolSet.size === 0) return { ok: false, error: 'No playable notes in the selected range — widen the note set.' };
const rng = makeRng(config.seed);
const pick = <T,>(arr: T[]): T => arr[Math.floor(rng() * arr.length)];
// Chord sequence: random from selection (no immediate repeats)
const sel = (config.chordSelection ?? []).filter(d => d in DEGREE_INDEX);
const poolDegrees = (sel.length > 0 ? sel : Object.keys(DEGREE_INDEX)) as string[];
const degreeIndices: number[] = [];
for (let b = 0; b < config.bars; b++) {
const prev = degreeIndices[b - 1];
const candidates = poolDegrees
.map(d => DEGREE_INDEX[d])
.filter(di => di !== prev);
degreeIndices.push(pick(candidates.length > 0 ? candidates : poolDegrees.map(d => DEGREE_INDEX[d])));
}
// Voice each bar; drop bars that cannot be voiced (rare with full pool).
const full = config.meter.numerator * PPQ;
const events: ScoreEvent[] = [];
const chordSymbols: (string | null)[] = [];
const usableBars: { degreeIndex: number; placement: ReturnType<typeof voiceBar> }[] = [];
for (const di of degreeIndices) {
const chord = triadPcs(key, di);
const placement = voiceBar(tuning, chord, config.pattern, config.allowedStrings as number[]);
if (!placement) continue;
usableBars.push({ degreeIndex: di, placement });
}
if (usableBars.length === 0) {
return { ok: false, error: 'No bar could be voiced with the current string selection — allow more strings or a lower fret window.' };
}
// Rhythm: one note per slot (figure repeats); one figure per beat.
const figure = FIGURES[config.pattern];
// Each figure repetition occupies one beat; repetitions per bar = meter.numerator.
const notesPerBar = config.meter.numerator * figure.length;
const noteDur = full / notesPerBar;
let cursor = 0;
for (let b = 0; b < usableBars.length; b++) {
const { degreeIndex, placement } = usableBars[b];
if (!placement) continue;
chordSymbols.push(chordNameFor(key, degreeIndex));
for (let beat = 0; beat < config.meter.numerator; beat++) {
for (let f = 0; f < figure.length; f++) {
const slot = figure[f];
const note = placement[slot];
if (!note) continue;
// spelling via key degree of this pc
const pc = ((note.midi % 12) + 12) % 12;
const d = key.degrees.find(deg => degreePc(deg) === pc);
if (!d) continue;
const octave = (note.midi - pc) / 12 - 1;
events.push({
id: `g${b}-${beat}-${f}`,
startTick: cursor,
durationTicks: noteDur,
pitch: { midi: note.midi, step: d.step, alter: d.alter, octave },
});
cursor += noteDur;
}
}
}
const totalBars = usableBars.length;
const score: Score = {
version: 1,
id: `giuliani-${config.keyTonic}-${config.keyMode}-${config.pattern}-${config.bars}b-${config.seed}`,
title: `Giuliani study — ${key.tonic} ${config.pattern} (${totalBars} bars)`,
meter: config.meter,
key: { tonic: config.keyTonic, mode: config.keyMode, signature: key.signature },
measures: Array.from({ length: totalBars }, (_, i) => ({
number: i + 1,
startTick: i * full,
durationTicks: full,
})),
chordSymbols,
voices: [{ id: 'melody', events }],
};
const problems = validateScore(score);
if (problems.length > 0) return { ok: false, error: `Internal giuliani error: ${problems[0]}` };
return { ok: true, value: score };
}

View File

@@ -30,7 +30,7 @@ export interface MelodyConfig {
readonly keyMode: ModeId;
/** 1..8 */
readonly bars: number;
readonly meter: { readonly numerator: 3 | 4; readonly denominator: 4 };
readonly meter: { readonly numerator: 3 | 4 | 6; readonly denominator: 4 };
/** 1 = Simple (quarters/halves/wholes), 2 = Mixed (+ paired eighths, dotted quarters),
* 3 = Elaborate (+ sixteenths, sixteenth groups, dotted eighths). */
readonly rhythmLevel: 1 | 2 | 3;
@@ -86,7 +86,7 @@ const TEMPLATES_3_L3: number[][] = [
[120, 120, 120, 120, 120, 120, 120, 120, 480],
];
function templatesFor(meter: { numerator: 3 | 4 }, level: 1 | 2 | 3): number[][] {
function templatesFor(meter: { numerator: 3 | 4 | 6 }, level: 1 | 2 | 3): number[][] {
const base = meter.numerator === 4
? (level === 1 ? TEMPLATES_4_L1 : level === 2 ? [...TEMPLATES_4_L1, ...TEMPLATES_4_L2] : [...TEMPLATES_4_L1, ...TEMPLATES_4_L2, ...TEMPLATES_4_L3])
: (level === 1 ? TEMPLATES_3_L1 : level === 2 ? [...TEMPLATES_3_L1, ...TEMPLATES_3_L2] : [...TEMPLATES_3_L1, ...TEMPLATES_3_L2, ...TEMPLATES_3_L3]);

View File

@@ -19,7 +19,7 @@ export interface DrillConfig {
readonly keyMode: ModeId;
readonly direction: DrillDirection;
readonly coverage: DrillCoverage;
readonly meter: { readonly numerator: 3 | 4; readonly denominator: 4 };
readonly meter: { readonly numerator: 3 | 4 | 6; readonly denominator: 4 };
/** Note duration: quarters (default) or eighths. */
readonly rhythm?: DrillRhythm;
}

View File

@@ -86,7 +86,7 @@ export interface Score {
readonly version: 1;
readonly id: string;
readonly title: string;
readonly meter: { readonly numerator: 3 | 4; readonly denominator: 4 };
readonly meter: { readonly numerator: 3 | 4 | 6; readonly denominator: 4 };
readonly key: ScoreKey;
readonly measures: ScoreMeasure[];
/** Exactly one voice in v1. */

View File

@@ -42,7 +42,7 @@ export interface RhythmSettings {
volume: number;
}
export type PhraseMaterial = 'melody' | 'scale' | 'arpeggio' | 'library' | 'import';
export type PhraseMaterial = 'melody' | 'scale' | 'arpeggio' | 'giuliani' | 'library' | 'import';
export type PhrasePace = 'step' | 'tempo';
export interface PhraseSettings {
@@ -52,7 +52,7 @@ export interface PhraseSettings {
keyTonic: string;
keyMode: string; // ModeId
bars: number; // 1–8 (melodies)
meterNumerator: 3 | 4;
meterNumerator: 3 | 4 | 6;
rhythmLevel: 1 | 2 | 3;
scaleCoverage: 'one-octave' | 'two-octave' | 'position';
scaleDirection: 'up' | 'down' | 'updown';
@@ -67,6 +67,9 @@ export interface PhraseSettings {
arpeggioBars: number;
arpeggioProgression: 'random' | 'functional' | 'diatonic-cycle';
arpeggioRhythm: 'quarters' | 'eighths';
/** Giuliani study material (own category — voicing-enforced). */
giulianiPattern: 'pim' | 'pima' | 'pami' | 'aim' | 'pimamim' | 'pmamim';
giulianiBars: number;
/** Phrase-local fret window (guitar/bass) — overrides the note set. */
fretWindowEnabled: boolean;
fretMin: number;
@@ -104,6 +107,8 @@ export const DEFAULT_PHRASE_SETTINGS: PhraseSettings = {
arpeggioBars: 1,
arpeggioProgression: 'functional',
arpeggioRhythm: 'quarters',
giulianiPattern: 'pima',
giulianiBars: 4,
fretWindowEnabled: false,
fretMin: 0,
fretMax: 4,