-- |
-- Module      : Harmonic.Interface.Tidal.Score
-- Description : Score mode — bar blocks, degrees against the progression's layers, dynamic marks
--
-- The literal, linear way of writing for the orchestra: a piece is a list of
-- blocks addressed by bar number, each a stack of lines that read scale
-- degrees against a layer of the progression the form carries (T the chord,
-- S its pentatonic, M its mode), played by a primed instrument that takes its
-- dynamic as a mark. It is the counterpart of the kinetics workflow and shares
-- its slot: the progression in @k@ is a one-bar key from 'inKey', a generated
-- or recalled context, or anything else that feeds 'Harmonic.Interface.Tidal.Form.iK'.
--
-- @
-- key  = inKey D "major"                      -- one bar: D F# A | D E F# A B | D major
-- form = [rh 1 1 0.4 key, rh 9 1 0.8 key]     -- the dynamic arc, in score bars
--
-- tune k = stack [silence
--   ,flute'   M "[1,2]" "p"  k "[5 [2 4 . 5] [4 3 2 4 . 5] [4 5] ~!3]/28"
--   ,violin1' M 1       "mp" k "[12 [9 11 . 12] …]/28"
--   ]
--
-- andante f k d = p "score" $ f $ score pre [bars 3 9 $ tune k, …] |* vel d
--
-- do let k = preroll pre $ iK tempo form (rep key 1)
--    mapM_ id [hush, setbpm tempo, resetCycles, display k, andante id k $ (*1) 0.8]
-- @
--
-- Time is the session's: one cycle is one beat, four cycles a bar, bar 1 the
-- first bar of the piece. A block runs on its own clock ('seqP' starts each
-- pattern from its cycle 0 at the block's first beat), so an ostinato written
-- @\"[a b c]\/12\"@ starts on @a@ wherever the block is placed and a
-- @\"<~ x x>\"@ alternation counts its passes from the entry.
module Harmonic.Interface.Tidal.Score (
    -- * Blocks
    bars, score,
    -- * Pitch
    inKey, degrees,
    -- * Dynamics
    dyn, dynTable, ramp,
) where

import Data.Char (toLower)
import Data.Foldable (toList)
import Data.List (sort)
import Text.Read (readMaybe)
import Sound.Tidal.Context
import Harmonic.Interface.Tidal.Bridge (degreeLookup, closedPosition)
import Harmonic.Interface.Tidal.Form (Kinetics(..), IK)
import qualified Harmonic.Rules.Types.Harmony as H
import Harmonic.Rules.Types.Pitch (NoteName, PitchClass(..), pitchClass, mkPitchClass, sharp)
import qualified Harmonic.Rules.Types.Progression as Pr
import qualified Harmonic.Rules.Types.ProgressionContext as PC
import Harmonic.Rules.Types.ProgressionContext (Layer)
import qualified Harmonic.Rules.Types.Scale as Sc

-- | A block of a score: bars @b1@ to @b2@ inclusive, 1-indexed, four cycles
-- per bar, as a 'seqP' triple. 'seqP' starts each block's pattern from its
-- own cycle 0, so the same mininotation reads the same at bar 1 and at bar 17.
bars :: Time -> Time -> Pattern a -> (Time, Time, Pattern a)
bars :: forall a. Time -> Time -> Pattern a -> (Time, Time, Pattern a)
bars Time
b1 Time
b2 Pattern a
p = ((Time
b1 Time -> Time -> Time
forall a. Num a => a -> a -> a
- Time
1) Time -> Time -> Time
forall a. Num a => a -> a -> a
* Time
4, Time
b2 Time -> Time -> Time
forall a. Num a => a -> a -> a
* Time
4, Pattern a
p)

-- | Sequence a list of blocks with @pre@ bars of pre-roll, so the count-in,
-- the clock start and any controller resets land before bar 1 begins at
-- cycle @pre * 4@. Pair it with 'Harmonic.Interface.Tidal.Form.preroll' on
-- the form, so the two clocks agree.
score :: Int -> [(Time, Time, Pattern a)] -> Pattern a
score :: forall a. Int -> [(Time, Time, Pattern a)] -> Pattern a
score Int
pre = Time -> Pattern a -> Pattern a
forall a. Time -> Pattern a -> Pattern a
rotR (Int -> Time
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
pre Time -> Time -> Time
forall a. Num a => a -> a -> a
* Time
4) (Pattern a -> Pattern a)
-> ([(Time, Time, Pattern a)] -> Pattern a)
-> [(Time, Time, Pattern a)]
-> Pattern a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [(Time, Time, Pattern a)] -> Pattern a
forall a. [(Time, Time, Pattern a)] -> Pattern a
seqP

-- | A one-bar progression context for a key: the tonic triad on T (the
-- mode's degrees 1 3 5, so a minor key gives a minor triad and Lydian a
-- major one), the key's pentatonic on S (its parent major key's, rooted on
-- the tonic where the tonic belongs to it — A minor gives A C D E G — and
-- the mode's degrees 1 2 3 5 6 for the melodic and harmonic families) and
-- the mode itself on M. It feeds 'Harmonic.Interface.Tidal.Form.iK' like any
-- generated or recalled context, and round-trips through
-- 'Harmonic.Interface.Tidal.Recall.save'.
--
-- Names, case-insensitive: @major@ \/ @ionian@, @minor@ \/ @aeolian@,
-- @dorian@, @phrygian@, @lydian@, @mixolydian@, @locrian@, @melodic minor@,
-- @harmonic minor@, @harmonic major@, any 'Sc.ModeQuality' constructor
-- (@LydDom@, @AltDom@ …), and @chromatic@ (all twelve on every layer, so a
-- degree is a semitone). An unknown name is an error at declaration: a typo
-- must not become a silent scale.
inKey :: NoteName -> String -> PC.ProgressionContext
inKey :: NoteName -> String -> ProgressionContext
inKey NoteName
tonic String
nm = Progression
-> Progression
-> Progression
-> Maybe (Seq (Tristrata, StrataLabel))
-> Family
-> ProgressionContext
PC.ProgressionContext (NoteName -> [Int] -> Progression
one NoteName
tonic [Int]
triad) (NoteName -> [Int] -> Progression
one NoteName
sRoot [Int]
penta) (NoteName -> [Int] -> Progression
one NoteName
tonic [Int]
mode) Maybe (Seq (Tristrata, StrataLabel))
forall a. Maybe a
Nothing Family
PC.FTriad
  where
    one :: NoteName -> [Int] -> Progression
one NoteName
root [Int]
ivs = CadenceState -> Progression
Pr.singleton (NoteName -> Movement -> [Int] -> CadenceState
H.mkCadenceStatePCs NoteName
root Movement
H.Unison [Int]
ivs)
    r :: Int
r = PitchClass -> Int
unPitchClass (NoteName -> PitchClass
pitchClass NoteName
tonic)
    ([Int]
triad, [Int]
penta, [Int]
mode, NoteName
sRoot) = case String -> Maybe ModeQuality
modeByName String
nm of
      Maybe ModeQuality
Nothing | (Char -> Char) -> String -> String
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower String
nm String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
"chromatic" -> ([Int
0 .. Int
11], [Int
0 .. Int
11], [Int
0 .. Int
11], NoteName
tonic)
              | Bool
otherwise -> String -> ([Int], [Int], [Int], NoteName)
forall a. HasCallStack => String -> a
error (String
"inKey: unknown mode " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String -> String
forall a. Show a => a -> String
show String
nm)
      Just ModeQuality
q ->
        let ivs :: [Int]
ivs = [Int] -> [Int]
forall a. Ord a => [a] -> [a]
sort [ (PitchClass -> Int
unPitchClass PitchClass
pc Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
r) Int -> Int -> Int
forall a. Integral a => a -> a -> a
`mod` Int
12 | PitchClass
pc <- Mode -> [PitchClass]
Sc.modeChroma (ModeQuality -> PitchClass -> Mode
Sc.Mode ModeQuality
q (Int -> PitchClass
P Int
r)) ]
            (PitchClass
parentPC, ScaleFamily
fam) = Mode -> (PitchClass, ScaleFamily)
Sc.parentKey (ModeQuality -> PitchClass -> Mode
Sc.Mode ModeQuality
q (Int -> PitchClass
P Int
r))
            parentPenta :: [Int]
parentPenta = (PitchClass -> Int) -> [PitchClass] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map PitchClass -> Int
unPitchClass (Pentatonic -> [PitchClass]
Sc.pentaChroma (PentaFamily -> PitchClass -> Pentatonic
Sc.Pentatonic PentaFamily
Sc.MajorPenta PitchClass
parentPC))
            (Int
pentaRootPC, [Int]
pentaIvs)
              | ScaleFamily
fam ScaleFamily -> ScaleFamily -> Bool
forall a. Eq a => a -> a -> Bool
== ScaleFamily
Sc.Major Bool -> Bool -> Bool
&& Int
r Int -> [Int] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Int]
parentPenta = (Int
r, [Int] -> [Int]
forall a. Ord a => [a] -> [a]
sort [ (Int
p Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
r) Int -> Int -> Int
forall a. Integral a => a -> a -> a
`mod` Int
12 | Int
p <- [Int]
parentPenta ])
              | ScaleFamily
fam ScaleFamily -> ScaleFamily -> Bool
forall a. Eq a => a -> a -> Bool
== ScaleFamily
Sc.Major = (PitchClass -> Int
unPitchClass PitchClass
parentPC, [Int] -> [Int]
forall a. Ord a => [a] -> [a]
sort [ (Int
p Int -> Int -> Int
forall a. Num a => a -> a -> a
- PitchClass -> Int
unPitchClass PitchClass
parentPC) Int -> Int -> Int
forall a. Integral a => a -> a -> a
`mod` Int
12 | Int
p <- [Int]
parentPenta ])
              | Bool
otherwise = (Int
r, (Int -> Int) -> [Int] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map ([Int]
ivs [Int] -> Int -> Int
forall a. HasCallStack => [a] -> Int -> a
!!) [Int
0, Int
1, Int
2, Int
4, Int
5])
            sName :: NoteName
sName | Int
pentaRootPC Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
r = NoteName
tonic
                  | Bool
otherwise = PitchClass -> NoteName
sharp (Int -> PitchClass
mkPitchClass Int
pentaRootPC)
        in ((Int -> Int) -> [Int] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map ([Int]
ivs [Int] -> Int -> Int
forall a. HasCallStack => [a] -> Int -> a
!!) [Int
0, Int
2, Int
4], [Int]
pentaIvs, [Int]
ivs, NoteName
sName)

modeByName :: String -> Maybe Sc.ModeQuality
modeByName :: String -> Maybe ModeQuality
modeByName String
nm = case (Char -> Char) -> String -> String
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower String
nm of
  String
"major"          -> ModeQuality -> Maybe ModeQuality
forall a. a -> Maybe a
Just ModeQuality
Sc.Ionian
  String
"ionian"         -> ModeQuality -> Maybe ModeQuality
forall a. a -> Maybe a
Just ModeQuality
Sc.Ionian
  String
"minor"          -> ModeQuality -> Maybe ModeQuality
forall a. a -> Maybe a
Just ModeQuality
Sc.Aeolian
  String
"aeolian"        -> ModeQuality -> Maybe ModeQuality
forall a. a -> Maybe a
Just ModeQuality
Sc.Aeolian
  String
"dorian"         -> ModeQuality -> Maybe ModeQuality
forall a. a -> Maybe a
Just ModeQuality
Sc.Dorian
  String
"phrygian"       -> ModeQuality -> Maybe ModeQuality
forall a. a -> Maybe a
Just ModeQuality
Sc.Phrygian
  String
"lydian"         -> ModeQuality -> Maybe ModeQuality
forall a. a -> Maybe a
Just ModeQuality
Sc.Lydian
  String
"mixolydian"     -> ModeQuality -> Maybe ModeQuality
forall a. a -> Maybe a
Just ModeQuality
Sc.Mixolydian
  String
"locrian"        -> ModeQuality -> Maybe ModeQuality
forall a. a -> Maybe a
Just ModeQuality
Sc.Locrian
  String
"melodic minor"  -> ModeQuality -> Maybe ModeQuality
forall a. a -> Maybe a
Just ModeQuality
Sc.MelMin
  String
"harmonic minor" -> ModeQuality -> Maybe ModeQuality
forall a. a -> Maybe a
Just ModeQuality
Sc.HarmMin
  String
"harmonic major" -> ModeQuality -> Maybe ModeQuality
forall a. a -> Maybe a
Just ModeQuality
Sc.HarmMaj
  String
_                -> String -> Maybe ModeQuality
forall a. Read a => String -> Maybe a
readMaybe String
nm

-- | Scale degrees against a layer of the progression in @k@, at an octave.
-- Each degree reads the chord selected at its onset (the same rule as
-- 'Harmonic.Interface.Tidal.Bridge.arrange'); degree 0 is that bar's root at
-- the lattice's bass register (the root in [-12,-1]) and @n@ indexes the bar's
-- closed position above it, wrapping by octave — on a one-bar D major context
-- the M layer gives 0 → D3, 7 → D4, −7 → D2. The octave pattern shifts the
-- result by twelves and may carry a chord (@\"[1,2]\"@ sounds both octaves,
-- @\"[[1] [~]]\/16\"@ drops the notes under its rest).
degrees :: Layer -> Pattern Int -> IK -> Pattern Int -> Pattern Note
degrees :: Layer -> Pattern Int -> IK -> Pattern Int -> Pattern Note
degrees Layer
lyr Pattern Int
octv (Kinetics
kin, Pattern Int
chordPat) Pattern Int
degs =
  let scalesOf :: ProgressionContext -> ([[b]], Int)
scalesOf ProgressionContext
ctx =
        let sc :: [[b]]
sc = (CadenceState -> [b]) -> [CadenceState] -> [[b]]
forall a b. (a -> b) -> [a] -> [b]
map ((Int -> b) -> [Int] -> [b]
forall a b. (a -> b) -> [a] -> [b]
map Int -> b
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([Int] -> [b]) -> (CadenceState -> [Int]) -> CadenceState -> [b]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CadenceState -> [Int]
closedPosition) (Seq CadenceState -> [CadenceState]
forall a. Seq a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList (Progression -> Seq CadenceState
Pr.unProgression (Layer -> ProgressionContext -> Progression
PC.layer Layer
lyr ProgressionContext
ctx)))
        in ([[b]]
sc, [[b]] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [[b]]
sc)
      cache :: [(ProgressionContext, ([[Note]], Int))]
cache = [ (ProgressionContext
ctx, ProgressionContext -> ([[Note]], Int)
forall {b}. Num b => ProgressionContext -> ([[b]], Int)
scalesOf ProgressionContext
ctx) | ProgressionContext
ctx <- Kinetics -> [ProgressionContext]
kProgs Kinetics
kin ]
      lookupCache :: ProgressionContext -> ([[Note]], Int)
lookupCache ProgressionContext
ctx = ([[Note]], Int)
-> (([[Note]], Int) -> ([[Note]], Int))
-> Maybe ([[Note]], Int)
-> ([[Note]], Int)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (ProgressionContext -> ([[Note]], Int)
forall {b}. Num b => ProgressionContext -> ([[b]], Int)
scalesOf ProgressionContext
ctx) ([[Note]], Int) -> ([[Note]], Int)
forall a. a -> a
id (ProgressionContext
-> [(ProgressionContext, ([[Note]], Int))] -> Maybe ([[Note]], Int)
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup ProgressionContext
ctx [(ProgressionContext, ([[Note]], Int))]
cache)
      pitches :: Pattern Note
pitches = Pattern (Pattern Note) -> Pattern Note
forall b. Pattern (Pattern b) -> Pattern b
innerJoin (Pattern (Pattern Note) -> Pattern Note)
-> Pattern (Pattern Note) -> Pattern Note
forall a b. (a -> b) -> a -> b
$ (ProgressionContext -> Pattern Note)
-> Pattern ProgressionContext -> Pattern (Pattern Note)
forall a b. (a -> b) -> Pattern a -> Pattern b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\ProgressionContext
ctx -> ([[Note]], Int) -> Pattern Int -> Pattern Int -> Pattern Note
degreeLookup (ProgressionContext -> ([[Note]], Int)
lookupCache ProgressionContext
ctx) Pattern Int
chordPat Pattern Int
degs) (Kinetics -> Pattern ProgressionContext
kProg Kinetics
kin)
  in Pattern Note
pitches Pattern Note -> Pattern Note -> Pattern Note
forall a. Num a => Pattern a -> Pattern a -> Pattern a
|+ (Int -> Note) -> Pattern Int -> Pattern Note
forall a b. (a -> b) -> Pattern a -> Pattern b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (Int -> Note
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int -> Note) -> (Int -> Int) -> Int -> Note
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
12)) Pattern Int
octv

-- | Dynamic marks as amplitude, 'dynTable' looked up per event. A mark the
-- table does not know yields no event, so under @#@ the note it would have
-- carried is dropped: a misspelt mark is heard as a missing note.
dyn :: Pattern String -> Pattern Double
dyn :: Pattern String -> Pattern Double
dyn = Pattern (Maybe Double) -> Pattern Double
forall a. Pattern (Maybe a) -> Pattern a
filterJust (Pattern (Maybe Double) -> Pattern Double)
-> (Pattern String -> Pattern (Maybe Double))
-> Pattern String
-> Pattern Double
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String -> Maybe Double)
-> Pattern String -> Pattern (Maybe Double)
forall a b. (a -> b) -> Pattern a -> Pattern b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (String -> [(String, Double)] -> Maybe Double
forall a b. Eq a => a -> [(a, b)] -> Maybe b
`lookup` [(String, Double)]
dynTable)

-- | The amplitude of each dynamic mark, @ffff@ down to @pppp@.
dynTable :: [(String, Double)]
dynTable :: [(String, Double)]
dynTable =
  [ (String
"ffff", Double
1.00), (String
"fff", Double
0.90), (String
"ff", Double
0.75), (String
"f", Double
0.65), (String
"mf", Double
0.55)
  , (String
"mp", Double
0.45), (String
"p", Double
0.40), (String
"pp", Double
0.35), (String
"ppp", Double
0.30), (String
"pppp", Double
0.25) ]

-- | A straight line from @lo@ to @hi@ across one cycle in 64 steps; @slow n@
-- stretches it over @n@ cycles. Multiply a line by it (@|* vel (slow 8 $
-- ramp 0.9 1.3)@) for a crescendo over two bars; the form's dynamic nodes do
-- the same for the whole arc.
ramp :: Pattern Double -> Pattern Double -> Pattern Double
ramp :: Pattern Double -> Pattern Double -> Pattern Double
ramp Pattern Double
lo Pattern Double
hi = Pattern Time -> Pattern Double -> Pattern Double
forall a. Pattern Time -> Pattern a -> Pattern a
segment Pattern Time
64 (Pattern Double
-> Pattern Double -> Pattern Double -> Pattern Double
forall a. Num a => Pattern a -> Pattern a -> Pattern a -> Pattern a
range Pattern Double
lo Pattern Double
hi Pattern Double
forall a. (Fractional a, Real a) => Pattern a
saw)