1 -- Basic Semantics for a Reactive Music Cellular Automaton.
2 -- Inspired by the reacTogon.
3 -- Written by Henrik Nilsson, 2016-05-03
4 -- Based on an earlier version.
6 -- This gives the semantics of a single Reactogon layer. The output is
7 -- a high-level representation of notes for each beat. This is to be
8 -- translated to low-level MIDI message by a subsequent translator
9 -- responsible for merging notes from different layers, ensuring that
10 -- a note off message corresponding to each note on message is always
11 -- emitted after the appropriate time, rendering any embellismnets
12 -- such as slides (while not generating too much MIDI data), etc.
14 module Reactogon.Semantics where
17 import Data.Maybe (catMaybes)
18 import Data.List (nub, intersperse)
22 ------------------------------------------------------------------------------
23 -- Basic Type Synonyms
24 ------------------------------------------------------------------------------
26 -- Unipolar control value; [0, 1]
29 -- Bipolar control value; [-1, 1]
33 ------------------------------------------------------------------------------
35 ------------------------------------------------------------------------------
37 -- The assumption is that the automaton is clocked by a beat clock and
38 -- thus advances one step per beat. For an automaton working in real time,
39 -- the beat clock would be defined externally, synchronized with other
40 -- layers and possibly external MIDI, and account for tempo, any swing, etc.
44 -- The tempo is the number of beats per minute.
49 -- A beat in itself is not important.
52 -- Beats per Bar: number of beats per bar in the time signature of a layer.
54 type BeatsPerBar = Int
56 -- The beat number in the time signature of the layer. The first beat is 1.
59 nextBeatNo :: BeatsPerBar -> BeatNo -> BeatNo
60 nextBeatNo bpb bn = bn `mod` bpb + 1
64 -- Not needed for individual layers (at present)
71 ------------------------------------------------------------------------------
73 ------------------------------------------------------------------------------
75 -- This semantics mainly works with a high-level represemntation of notes.
76 -- But it is convenient to express some of the high-level aspects directly
77 -- in the corresponding MIDI terms to facilitate the translation.
79 -- MIDI note number; [0,127]
83 -- Assume MIDI convetion: 60 = "Middle C" = C4
88 -- MIDI velocity; [0,127]
92 -- MIDI Program Change: Program Number; [0,127]
96 -- MIDI Control Change: Control Number and Control Value; [0,127]
100 -- MIDICVRnd gives the option to pick a control value at random.
101 -- (Handled through subsequent translation to low-level MIDI events.)
102 data MIDICVRnd = MIDICV MIDICV | MIDICVRnd deriving (Eq, Show)
105 ------------------------------------------------------------------------------
107 ------------------------------------------------------------------------------
111 -- We chose to represent pitch by MIDI note number
112 newtype Pitch = Pitch MIDINN deriving Eq
114 pitchToMNN :: Pitch -> MIDINN
115 pitchToMNN (Pitch nn) = nn
117 instance Show Pitch where
118 show (Pitch nn) = names !! note ++ show oct
122 oct = nn' `div` 12 + middleCOct
123 names = ["C", "C#", "D", "D#", "E", "F",
124 "F#", "G", "G#", "A", "A#", "B"]
126 -- Relative pitch in semi tones. Used for e.g. transposition.
132 -- Each layer has a setting that indicate how strongly the notes
133 -- should normally be played as a percentage of full strength.
134 -- (In the real application, this settig can be set to a fixed value
135 -- or set to be derived from teh last input note, "as played").
136 -- Individual notes can tehn be accented (played more strongly),
137 -- either unconditionally or as a function of the beat count.
139 type Strength = UCtrl
141 -- This could of course be generalised, e.g. a list of beat numbers to
142 -- accentuate. But this is simple and accounts for the most common patterns.
143 data Articulation = NoAccent
153 -- Articulated strength
154 articStrength :: Strength -> BeatNo -> Articulation -> Strength
155 articStrength st bn art
156 | accentedBeat = st * accentStrength
161 (_, NoAccent) -> False
164 (1, Accent13) -> True
165 (3, Accent13) -> True
166 (1, Accent14) -> True
167 (4, Accent14) -> True
168 (1, Accent24) -> True
169 (4, Accent24) -> True
175 -- Duration in terms of a whole note at the *system* tempo. (Each
176 -- layer is clocked at a layer beat that is a fraction/multiple of the
177 -- system tempo). Note that notes are played a little shorter than
178 -- their nominal duration. This is taken care of by the translation
179 -- into low-level MIDI events. (One might consider adding indications
180 -- of staccato or tenuto.)
181 type Duration = Rational
186 -- Notes can be ornamented. Traditionnally, ornamenting refers to modifications
187 -- of the pitch, such as a trill or a grace note. Here we use the term in
188 -- a generalised sense.
189 -- * A MIDI program change (to be sent before the note).
190 -- * A MIDI Continuous Controler Change (to be sent before the note).
192 -- One might also consider adding trills, grace notes, MIDI after touch ...
194 data Ornaments = Ornaments {
195 ornPC :: Maybe MIDIPN,
196 ornCC :: [(MIDICN, MIDICVRnd)],
197 ornSlide :: SlideType
200 data SlideType = NoSlide | SlideUp | SlideDn deriving (Eq, Show)
205 -- Attributes needed to generate a note.
206 -- * The pitch of a note is given by the position on the board
207 -- * The strength is given by the layer strength, beat no., and articulation
208 -- * Duratio and Ornamentatio are stored
209 data NoteAttr = NoteAttr {
210 naArt :: Articulation,
216 -- High level note representation emitted from a layer
225 ------------------------------------------------------------------------------
227 ------------------------------------------------------------------------------
229 -- Numbering; row number inside tile, column number below:
240 -- Angle measured in multiples of 60 degrees.
243 data Dir = N | NE | SE | S | SW | NW deriving (Enum, Eq, Show)
246 turn :: Dir -> Angle -> Dir
247 turn d a = toEnum ((fromEnum d + a) `mod` 6)
250 type Pos = (Int, Int)
252 -- Position of neighbour in given direction
253 neighbor :: Dir -> Pos -> Pos
254 neighbor N (x,y) = (x, y + 1)
255 neighbor NE (x,y) = (x + 1, y + 1 - x `mod` 2)
256 neighbor SE (x,y) = (x + 1, y - x `mod` 2)
257 neighbor S (x,y) = (x, y - 1)
258 neighbor SW (x,y) = (x - 1, y - x `mod` 2)
259 neighbor NW (x,y) = (x - 1, y + 1 - x `mod` 2)
262 -- Position and transposition to pitch:
263 -- * Harmonic Table" layout: N = +7; NE = +4; SE = -3
264 -- * (0,0) assumed to be "Middle C"
265 posToPitch :: Pos -> RelPitch -> Pitch
266 posToPitch (x,y) tr =
267 Pitch (y * 7 + x `div` 2 - 3 * (x `mod` 2) + middleC + tr)
271 -- Maybe this could be refined: some of the actions might be useful
272 -- both in note playing and silent versions: e.g. changing direction without
273 -- playing a note; playing a note without changing direction.
275 data Action = Inert -- No action, play heads just move through.
276 | Absorb -- Remove play head silently.
277 | Stop NoteAttr -- Play note then remove play head.
278 | ChDir NoteAttr Dir -- Play note then change direction.
279 | Split NoteAttr -- Play note then split head into five new.
284 -- A cell stores an action and a repetition number.
285 -- 0: the cell is completely bypassed, as if it wasn't there.
286 -- 1: the action is carried out once (default)
287 -- n > 1: any note output of the action is repeated (n-1) times before the
288 -- action is carried out.
290 type Cell = (Action, Int)
293 -- Make a cell with a default repeat count of 1.
294 mkCell :: Action -> Cell
295 mkCell a = mkCellRpt a 1
298 -- Make a cell with a non-default repeition number.
299 mkCellRpt :: Action -> Int -> Cell
300 mkCellRpt a n | n >= 0 = (a, n)
301 | otherwise = error "The repetition number of a cell must be \
305 -- Board extent: south-west corner and north-east corner.
306 -- This covers most of the MIDI range: A#-1 (10) to G7 (103).
312 -- Test if a position is on the board as defined by swc and nec.
313 -- The assumption is that odd columns contain one more cell, as per the
314 -- picture above. Of course, one could opt for a "zig-zag" layout
315 -- with each column having the same number of cells which would be slightly
317 onBoard :: Pos -> Bool
318 onBoard (x,y) = xMin <= x && x <= xMax
326 (xMax, yMax) = case nec of
327 (x, y) | even x -> (x, y + 1)
328 | otherwise -> (x, y)
331 type Board = Array Pos Cell
334 -- Build a board from a list specifying the non-empty cells.
335 makeBoard :: [(Pos, Cell)] -> Board
338 ([(p, if onBoard p then mkCell Inert else mkCell Absorb)
339 | p <- range (swc, nec')]
340 ++ [(p,c) | (p, c) <- pcs, onBoard p])
342 -- This is to ensure (neighbor NW nec) is included on the board,
343 -- regardless of whether the column of nec is even or odd.
344 -- Otherwise, due to the "jagged" upper edge, the top row would
345 -- be missing, but every other cell of that *is* on the board.
346 -- The "superfluous" cells are set to Absorb above.
347 nec' = neighbor N nec
351 lookupCell :: Board -> Pos -> Cell
352 lookupCell b p = if onBoard p then (b ! p) else (Absorb, 1)
355 ------------------------------------------------------------------------------
357 ------------------------------------------------------------------------------
359 -- A play head is characterised by:
360 -- * Current position
361 -- * Number of beats before moving
362 -- * Direction of travel
363 -- If an action involves playing a note, this is repeated once for
364 -- each beat the play head is staying, with the rest of the action
365 -- carried out at the last beat.
376 ------------------------------------------------------------------------------
378 ------------------------------------------------------------------------------
380 -- Advance the state of a single play head.
382 -- The result is a list of heads to be actioned at the *next* beat
383 -- later) and possibly a note to be played at *this* beat.
385 advanceHead :: Board -> BeatNo -> RelPitch -> Strength -> PlayHead
386 -> ([PlayHead], Maybe Note)
387 advanceHead bd bn tr st ph = ahAux (moveHead bd ph)
389 ahAux ph@PlayHead {phPos = p, phBTM = btm, phDir = d} =
390 case fst (lookupCell bd p) of
391 Inert -> ([ph], Nothing)
392 Absorb -> ([], Nothing) -- No point waiting until BTM=0
393 Stop na -> (newPHs [], Just (mkNote p bn tr st na))
394 ChDir na d' -> (newPHs [ph {phDir = d'}],
395 Just (mkNote p bn tr st na))
396 Split na -> (newPHs [ PlayHead {
404 Just (mkNote p bn tr st na))
406 newPHs phs = if btm > 0 then [ph] else phs
409 -- Moves a play head if the BTM counter has reached 0, otherwise decrement BTM.
410 -- Any encountered cells where the repeat count is < 1 are skipped.
411 moveHead :: Board -> PlayHead -> PlayHead
412 moveHead bd (ph@PlayHead {phPos = p, phBTM = btm, phDir = d})
415 btm' = snd (lookupCell bd p')
417 moveHead bd (ph {phPos = p', phBTM = btm'})
418 | otherwise = ph {phBTM = btm - 1}
421 mkNote :: Pos -> BeatNo -> RelPitch -> Strength -> NoteAttr -> Note
422 mkNote p bn tr st na =
424 notePch = posToPitch p tr,
425 noteStr = articStrength st bn (naArt na),
431 -- Advance a list of heads, collecting all resulting heads and notes.
432 -- Any duplicate play heads are eliminated (or their number may uselessly
433 -- grow very quickly), and a cap (50, arbitrary, but should be plenty,
434 -- expecially given the board size) on the number of simultaneous playheads
435 -- per layer is imposed.
436 advanceHeads :: Board -> BeatNo -> RelPitch -> Strength -> [PlayHead]
437 -> ([PlayHead], [Note])
438 advanceHeads bd bn tr st phs =
440 (phss, mns) = unzip (map (advanceHead bd bn tr st) phs)
442 (take 50 (nub (concat phss)), catMaybes mns)
445 -- Given an initial list of play heads, run a board until there are no
446 -- more heads (or "forever", if that does not happen). The result is
447 -- a list of all notes played for each pulse.
449 -- Note: The original reactogon has special start counters. An "internal"
450 -- board as defined here along with a list of inital read heads could
451 -- be derived from an "external" board representation more closely aligned
452 -- with the GUI represenatation.
454 -- In the real implementation:
455 -- * A layer beat clock would be derived from the system beat (as a
456 -- fraction/multiple, adding any swing) and each clock event be tagged
457 -- with the beat number.
458 -- * The board would not necessarily be a constant input. (One might
459 -- consider allowing editing a layer while the machine is running)
460 -- * The time signature and thus the beats per par would not necessarily
461 -- be a constant input (one might consider allowing changing it while
462 -- the machine is running, but perhaps not very useful).
463 -- * The transposition would be dynamic, the sum of a per layer
464 -- transposition that can be set through the user interface and the
465 -- difference between the MIDI note number of the last external
466 -- note received for the layer and middle C (say).
467 -- * The strength would be dynamic, configurable as either the strength
468 -- set through the user interface or the strength of the last external
469 -- note received for the layer (derived from its MIDI velocity).
471 runRMCA :: Board -> BeatsPerBar -> RelPitch -> Strength -> [PlayHead]
473 runRMCA _ _ _ _ [] = []
474 runRMCA bd bpb tr st phs = runAux 1 phs
476 runAux bn phs = ns : runAux (nextBeatNo bpb bn) phs'
478 (phs', ns) = advanceHeads bd bn tr st phs
481 -- Print played notes in a time-stamped (bar, beat), easy-to-read format.
483 ppNotes :: BeatsPerBar -> [[Note]] -> IO ()
484 ppNotes bpb nss = ppnAux (zip [(br,bn) | br <- [1..], bn <- [1..bpb]] nss)
486 ppnAux [] = return ()
487 ppnAux ((_, []) : tnss) = ppnAux tnss
488 ppnAux ((t, ns) : tnss) = do
489 putStrLn ((leftJustify 10 (show t)) ++ ": "
490 ++ concat (intersperse ", " (map show ns)))
494 leftJustify :: Int -> String -> String
495 leftJustify w s = take (w - length s) (repeat ' ') ++ s
498 ------------------------------------------------------------------------------
500 ------------------------------------------------------------------------------
502 -- testBoard = makeBoard [((0,0), mkCell (ChDir na1 N)),
503 -- ((0,1), mkCell (ChDir na1 SE)),
504 -- ((1,1), mkCell (Split na1)),
505 -- ((1,-1), mkCell (Split na1)),
506 -- ((-1,0), mkCell (ChDir na2 NE))]
508 testBoard = makeBoard [((0,0), mkCell (ChDir na1 N)),
509 ((0,2), mkCellRpt (ChDir na2 SE) 3),
510 ((2,1), mkCell (ChDir na1 SW)),
511 ((1,1), mkCellRpt (ChDir na1 N) 0) {- Skipped! -}]
516 naOrn = Ornaments Nothing [] NoSlide
522 naOrn = Ornaments Nothing [(10, MIDICVRnd)] SlideUp
528 main = ppNotes bpb (take 50 (runRMCA testBoard
532 [PlayHead (0,0) 1 N]))