]> Git — Sourcephile - tmp/julm/arpeggigon.git/blob - RMCA/Semantics.hs
System producing notes but no sound.
[tmp/julm/arpeggigon.git] / RMCA / Semantics.hs
1 -- Basic Semantics V2 for a Reactive Music Cellular Automaton.
2 -- Inspired by the reacTogon.
3 -- Written by Henrik Nilsson, 2016-05-27
4 -- Based on an earlier version.
5 --
6 -- This gives the semantics of a single RMCA 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.
13
14 -- ToDo:
15 -- * Add boolean flag to change direction to indicate start tile
16 -- DONE!
17 -- * Change main routine to generate start play heads from board
18 -- DONE!
19 -- * Add an optional restart facility: Maybe Int, restart every n
20 -- bars.
21 -- DONE!
22 -- * Interpret a negative repeat as repeat indefinitely.
23 -- DONE!
24 -- * Interpret a non-positve duration as mute: don't emit any note.
25 -- DONE!
26 -- * Eliminate Ignore as now almost the same as Absorb with duration 0?
27 -- The only difference is that Absorb mostly overrides the repeat count.
28 -- Absorb = Stop {duration 0, repeat 1}
29 -- And as absorb might be a common case, it might be useful to have
30 -- a distinct graphical representation?
31 -- DECIDED AGAINST FOR NOW
32
33 module RMCA.Semantics where
34
35 import Data.Array
36 import Data.List (intersperse, nub)
37 import Data.Maybe (catMaybes)
38 import Data.Ratio
39
40
41 ------------------------------------------------------------------------------
42 -- Basic Type Synonyms
43 ------------------------------------------------------------------------------
44
45 -- Unipolar control value; [0, 1]
46 type UCtrl = Double
47
48 -- Bipolar control value; [-1, 1]
49 type BCtrl = Double
50
51 -- Unipolar control values are usually between 0 and 127.
52 toUCtrl :: Int -> UCtrl
53 toUCtrl x = fromIntegral x / 127
54
55 fromUCtrl :: UCtrl -> Int
56 fromUCtrl x = floor $ x * 127
57
58 -- Bipolar control values are usually between -127 and 127.
59 toBCtrl :: Int -> BCtrl
60 toBCtrl = toUCtrl
61
62 fromBCtrl :: BCtrl -> Int
63 fromBCtrl = fromUCtrl
64
65 ------------------------------------------------------------------------------
66 -- Tempo
67 ------------------------------------------------------------------------------
68
69 type Tempo = Int
70
71 -- LTempo designates a layer tempo. Useful for not transforming twice
72 -- a tempo.
73 type LTempo = Tempo
74
75 ------------------------------------------------------------------------------
76 -- Time and Beats
77 ------------------------------------------------------------------------------
78
79 -- The assumption is that the automaton is clocked by a beat clock and
80 -- thus advances one step per beat. For an automaton working in real time,
81 -- the beat clock would be defined externally, synchronized with other
82 -- layers and possibly external MIDI, and account for tempo, any swing, etc.
83
84 -- Beats and Bars
85
86 -- A beat as such is nothing.
87 type Beat = ()
88
89 -- Beats per Bar: number of beats per bar in the time signature of a layer.
90 -- Non-negative.
91 type BeatsPerBar = Int
92
93 -- The beat number in the time signature of the layer. The first beat is 1.
94 type BeatNo = Int
95
96 nextBeatNo :: BeatsPerBar -> BeatNo -> BeatNo
97 nextBeatNo bpb bn = bn `mod` bpb + 1
98
99
100 {-
101 -- Not needed for individual layers (at present)
102
103 -- Time; [0,+inf)
104 type Time = Double
105 -}
106
107
108 ------------------------------------------------------------------------------
109 -- MIDI
110 ------------------------------------------------------------------------------
111
112 -- This semantics mainly works with a high-level represemntation of notes.
113 -- But it is convenient to express some of the high-level aspects directly
114 -- in the corresponding MIDI terms to facilitate the translation.
115
116 -- MIDI note number; [0,127]
117 type MIDINN = Int
118
119
120 -- Assume MIDI convetion: 60 = "Middle C" = C4
121 middleC = 60
122 middleCOct = 4
123
124
125 -- MIDI velocity; [0,127]
126 type MIDIVel = Int
127
128
129 -- MIDI Program Change: Program Number; [0,127]
130 type MIDIPN = Int
131
132
133 -- MIDI Control Change: Control Number and Control Value; [0,127]
134 type MIDICN = Int
135 type MIDICV = Int
136
137 -- MIDICVRnd gives the option to pick a control value at random.
138 -- (Handled through subsequent translation to low-level MIDI events.)
139 data MIDICVRnd = MIDICV MIDICV | MIDICVRnd deriving (Eq, Show)
140
141 -- TEMPORARY
142 data Controller = Lol
143 --
144 ------------------------------------------------------------------------------
145 -- Notes
146 ------------------------------------------------------------------------------
147
148 -- Pitch
149
150 -- We chose to represent pitch by MIDI note number
151 newtype Pitch = Pitch MIDINN deriving Eq
152
153 pitchToMNN :: Pitch -> MIDINN
154 pitchToMNN (Pitch nn) = nn
155
156 instance Show Pitch where
157 show (Pitch nn) = names !! note ++ show oct
158 where
159 nn' = nn - middleC
160 note = nn' `mod` 12
161 oct = nn' `div` 12 + middleCOct
162 names = ["C", "C#", "D", "D#", "E", "F",
163 "F#", "G", "G#", "A", "A#", "B"]
164
165 -- Relative pitch in semi tones. Used for e.g. transposition.
166 type RelPitch = Int
167
168
169 -- Articulation
170
171 -- Each layer has a setting that indicate how strongly the notes
172 -- should normally be played as a percentage of full strength.
173 -- (In the real application, this settig can be set to a fixed value
174 -- or set to be derived from teh last input note, "as played").
175 -- Individual notes can tehn be accented (played more strongly),
176 -- either unconditionally or as a function of the beat count.
177
178 type Strength = UCtrl
179
180 -- This could of course be generalised, e.g. a list of beat numbers to
181 -- accentuate. But this is simple and accounts for the most common patterns.
182 data Articulation = NoAccent
183 | Accent
184 | Accent1
185 | Accent13
186 | Accent14
187 | Accent24
188 deriving (Eq, Show)
189
190 accentStrength = 1.2
191
192 -- Articulated strength
193 articStrength :: Strength -> BeatNo -> Articulation -> Strength
194 articStrength st bn art
195 | accentedBeat = st * accentStrength
196 | otherwise = st
197 where
198 accentedBeat =
199 case (bn, art) of
200 (_, NoAccent) -> False
201 (_, Accent) -> True
202 (1, Accent1) -> True
203 (1, Accent13) -> True
204 (3, Accent13) -> True
205 (1, Accent14) -> True
206 (4, Accent14) -> True
207 (1, Accent24) -> True
208 (4, Accent24) -> True
209 _ -> False
210
211
212 -- Duration
213
214 -- Duration in terms of a whole note at the *system* tempo. (Each layer
215 -- is clocked at a layer beat that is a fraction/multiple of the system
216 -- tempo). Note that notes are played a little shorter than their nominal
217 -- duration. This is taken care of by the translation into low-level
218 -- MIDI events. (One might consider adding indications of staccato or
219 -- tenuto.)
220 --
221 -- A non-positive duration is interpreted as mute: no note emitted.
222 type Duration = Rational
223
224
225 -- Ornamentation
226
227 -- Notes can be ornamented. Traditionnally, ornamenting refers to modifications
228 -- of the pitch, such as a trill or a grace note. Here we use the term in
229 -- a generalised sense.
230 -- * A MIDI program change (to be sent before the note).
231 -- * A MIDI Continuous Controler Change (to be sent before the note).
232 -- * A Slide
233 -- One might also consider adding trills, grace notes, MIDI after touch ...
234
235 data Ornaments = Ornaments {
236 ornPC :: Maybe MIDIPN,
237 ornCC :: [(MIDICN, MIDICVRnd)],
238 ornSlide :: SlideType
239 } deriving Show
240
241 data SlideType = NoSlide | SlideUp | SlideDn deriving (Eq, Show)
242
243 noOrn :: Ornaments
244 noOrn = Ornaments { ornPC = Nothing
245 , ornCC = []
246 , ornSlide = NoSlide
247 }
248
249 -- Notes
250
251 -- Attributes needed to generate a note.
252 -- * The pitch of a note is given by the position on the board
253 -- * The strength is given by the layer strength, beat no., and articulation
254 -- * Duratio and Ornamentatio are stored
255 data NoteAttr = NoteAttr {
256 naArt :: Articulation,
257 naDur :: Duration,
258 naOrn :: Ornaments
259 } deriving Show
260
261
262 -- High level note representation emitted form a layer
263 data Note = Note {
264 notePch :: Pitch,
265 noteStr :: Strength,
266 noteDur :: Duration,
267 noteOrn :: Ornaments
268 } deriving Show
269
270
271 ------------------------------------------------------------------------------
272 -- Board
273 ------------------------------------------------------------------------------
274
275 -- Numbering; row number inside tile, column number below:
276 -- _ _
277 -- _/2\_/2\_
278 -- / \_/1\_/1\
279 -- \_/1\_/1\_/
280 -- / \_/0\_/0\
281 -- \_/0\_/0\_/
282 -- \_/ \_/
283 -- -1 0 1 2
284
285
286 -- Angle measured in multiples of 60 degrees.
287 type Angle = Int
288
289 data Dir = N | NE | SE | S | SW | NW deriving (Enum, Eq, Show)
290
291
292 turn :: Dir -> Angle -> Dir
293 turn d a = toEnum ((fromEnum d + a) `mod` 6)
294
295
296 type Pos = (Int, Int)
297
298 -- Position of neighbour in given direction
299 neighbor :: Dir -> Pos -> Pos
300 neighbor N (x,y) = (x, y + 1)
301 neighbor NE (x,y) = (x + 1, y + 1 - x `mod` 2)
302 neighbor SE (x,y) = (x + 1, y - x `mod` 2)
303 neighbor S (x,y) = (x, y - 1)
304 neighbor SW (x,y) = (x - 1, y - x `mod` 2)
305 neighbor NW (x,y) = (x - 1, y + 1 - x `mod` 2)
306
307
308 -- Position and transposition to pitch:
309 -- * Harmonic Table" layout: N = +7; NE = +4; SE = -3
310 -- * (0,0) assumed to be "Middle C"
311 posToPitch :: Pos -> RelPitch -> Pitch
312 posToPitch (x,y) tr =
313 Pitch (y * 7 + x `div` 2 - 3 * (x `mod` 2) + middleC + tr)
314
315
316 -- Actions
317 -- A ChDir counter is optionally a start counter if the Boolean flag is
318 -- set to true.
319 -- Any counter can be made silent by setting the note duration to a
320 -- non-positive number.
321
322 data Action = Inert -- No action, play heads move through.
323 | Absorb -- Remove play head silently.
324 | Stop NoteAttr -- Play note then remove play head.
325 | ChDir Bool NoteAttr Dir -- Play note then change direction.
326 | Split NoteAttr -- Play note then split head into five.
327 deriving Show
328
329
330 -- Cells
331 -- A cell stores an action and a repetition number.
332 -- 0: the cell is completely bypassed, as if it wasn't there.
333 -- 1: the action is carried out once (default)
334 -- n > 1: any note output of the action is repeated (n-1) times before the
335 -- action is carried out.
336 -- n < 0: any note output of the action is repeated indefinitely (oo).
337
338 type Cell = (Action, Int)
339
340
341 -- Make a cell with a default repeat count of 1.
342 mkCell :: Action -> Cell
343 mkCell a = mkCellRpt a 1
344
345
346 -- Make a cell with a non-default repeition number.
347 mkCellRpt :: Action -> Int -> Cell
348 mkCellRpt a n = (a, n)
349
350
351 -- Board extent: south-west corner and north-east corner.
352 -- This covers most of the MIDI range: A#-1 (10) to G7 (103).
353 swc, nec :: Pos
354 swc = (-9, -6)
355 nec = (9, 6)
356
357
358 -- Test if a position is on the board as defined by swc and nec.
359 -- The assumption is that odd columns contain one more cell, as per the
360 -- picture above. Of course, one could opt for a "zig-zag" layout
361 -- with each column having the same number of cells which would be slightly
362 -- simpler.
363 onBoard :: Pos -> Bool
364 onBoard (x,y) = xMin <= x && x <= xMax
365 && yMin <= y
366 && (if even x then
367 y < yMax
368 else
369 y <= yMax)
370 where
371 (xMin, yMin) = swc
372 (xMax, yMax) = case nec of
373 (x, y) | even x -> (x, y + 1)
374 | otherwise -> (x, y)
375
376
377 type Board = Array Pos Cell
378
379
380 -- Build a board from a list specifying the non-empty cells.
381 makeBoard :: [(Pos, Cell)] -> Board
382 makeBoard pcs =
383 array (swc,nec')
384 ([(p, if onBoard p then mkCell Inert else mkCell Absorb)
385 | p <- range (swc, nec')]
386 ++ [(p,c) | (p, c) <- pcs, onBoard p])
387 where
388 -- This is to ensure (neighbor NW nec) is included on the board,
389 -- regardless of whether the column of nec is even or odd.
390 -- Otherwise, due to the "jagged" upper edge, the top row would
391 -- be missing, but every other cell of that *is* on the board.
392 -- The "superfluous" cells are set to Absorb above.
393 nec' = neighbor N nec
394
395
396 -- Look up a cell
397 lookupCell :: Board -> Pos -> Cell
398 lookupCell b p = if onBoard p then (b ! p) else (Absorb, 1)
399
400
401 ------------------------------------------------------------------------------
402 -- Play Head
403 ------------------------------------------------------------------------------
404
405 -- A play head is characterised by:
406 -- * Current position
407 -- * Number of beats before moving
408 -- * Direction of travel
409 -- If an action involves playing a note, this is repeated once for
410 -- each beat the play head is staying, with the rest of the action
411 -- carried out at the last beat.
412
413 data PlayHead =
414 PlayHead {
415 phPos :: Pos,
416 phBTM :: Int,
417 phDir :: Dir
418 }
419 deriving (Eq, Show)
420
421
422 ------------------------------------------------------------------------------
423 -- Start Heads
424 ------------------------------------------------------------------------------
425
426 startHeads :: Board -> [PlayHead]
427 startHeads bd =
428 [ PlayHead {
429 phPos = p,
430 phBTM = n,
431 phDir = d
432 }
433 | (p, (ChDir True _ d, n)) <- assocs bd ]
434
435
436 ------------------------------------------------------------------------------
437 -- State transition
438 ------------------------------------------------------------------------------
439
440 -- Advance the state of a single play head.
441 --
442 -- The result is a list of heads to be actioned at the *next* beat
443 -- later) and possibly a note to be played at *this* beat.
444
445 advanceHead :: Board -> BeatNo -> RelPitch -> Strength -> PlayHead
446 -> ([PlayHead], Maybe Note)
447 advanceHead bd bn tr st ph = ahAux (moveHead bd ph)
448 where
449 ahAux ph@PlayHead {phPos = p, phBTM = btm, phDir = d} =
450 case fst (lookupCell bd p) of
451 Inert -> ([ph], Nothing)
452 Absorb -> ([], Nothing) -- No point waiting until BTM=0
453 Stop na -> (newPHs [], mkNote p bn tr st na)
454 ChDir _ na d' -> (newPHs [ph {phDir = d'}],
455 mkNote p bn tr st na)
456 Split na -> (newPHs [ PlayHead {
457 phPos = p,
458 phBTM = 0,
459 phDir = d'
460 }
461 | a <- [-2 .. 2],
462 let d' = turn d a
463 ],
464 mkNote p bn tr st na)
465 where
466 newPHs phs = if btm == 0 then phs else [ph]
467
468
469 -- Moves a play head if the BTM counter has reached 0, otherwise decrement BTM.
470 -- Any encountered cells where the repeat count is < 1 are skipped.
471 moveHead :: Board -> PlayHead -> PlayHead
472 moveHead bd (ph@PlayHead {phPos = p, phBTM = btm, phDir = d})
473 | btm == 0 = let
474 p' = neighbor d p
475 btm' = snd (lookupCell bd p')
476 in
477 moveHead bd (ph {phPos = p', phBTM = btm'})
478 | btm > 0 = ph {phBTM = btm - 1}
479 | otherwise = ph -- Repeat indefinitely
480
481 mkNote :: Pos -> BeatNo -> RelPitch -> Strength -> NoteAttr -> Maybe Note
482 mkNote p bn tr st na@(NoteAttr {naDur = d})
483 | d <= 0 = Nothing -- Notes of non-positive length are silent.
484 | otherwise = Just $
485 Note {
486 notePch = posToPitch p tr,
487 noteStr = articStrength st bn (naArt na),
488 noteDur = naDur na,
489 noteOrn = naOrn na
490 }
491
492
493 -- Advance a list of heads, collecting all resulting heads and notes.
494 -- Any duplicate play heads are eliminated (or their number may uselessly
495 -- grow very quickly), and a cap (50, arbitrary, but should be plenty,
496 -- expecially given the board size) on the number of simultaneous playheads
497 -- per layer is imposed.
498 advanceHeads :: Board -> BeatNo -> RelPitch -> Strength -> [PlayHead]
499 -> ([PlayHead], [Note])
500 advanceHeads bd bn tr st phs =
501 let
502 (phss, mns) = unzip (map (advanceHead bd bn tr st) phs)
503 in
504 (take 50 (nub (concat phss)), catMaybes mns)
505
506
507 -- Given a board with start counters, run a board indefinitely, optionally
508 -- restarting every ri bars.
509 --
510 -- Arguments:
511 -- (1) Board (bd)
512 -- (2) Beats Per Bar (bpb); > 0
513 -- (3) Optioal repeat Interval (mri); In bars.
514 -- (4) Transposition (tr)
515 -- (5) Strength (st)
516 --
517 -- Returns:
518 -- Stream of notes played at each beat.
519 --
520 -- In the real implementation:
521 -- * A layer beat clock would be derived from the system beat (as a
522 -- fraction/multiple, adding any swing) and each clock event be tagged
523 -- with the beat number.
524 -- * The board (bd) would not necessarily be a constant input. (One might
525 -- consider allowing editing a layer while the machine is running)
526 -- * The time signature, and thus the beats per par (bpb), along with
527 -- repeat interval (ri) would likely be static (only changeable while
528 -- automaton is stopped).
529 -- * The transposition (tr) would be dynamic, the sum of a per layer
530 -- transposition that can be set through the user interface and the
531 -- difference between the MIDI note number of the last external
532 -- note received for the layer and middle C (say).
533 -- * The strength (st) would be dynamic, configurable as either the strength
534 -- set through the user interface or the strength of the last external
535 -- note received for the layer (derived from its MIDI velocity).
536
537 runRMCA :: Board -> BeatsPerBar -> Maybe Int -> RelPitch -> Strength
538 -> [[Note]]
539 runRMCA bd bpb mri tr st
540 | bpb > 0 =
541 case mri of
542 Nothing -> nss
543 Just ri
544 | ri > 0 -> cycle (take (ri * bpb) nss)
545 | otherwise -> error "The repeat interval must be at \
546 \least 1 bar."
547 | otherwise = error "The number of beats per bar must be at least 1."
548 where
549 nss = runAux 1 (startHeads bd)
550
551 runAux bn phs = ns : runAux (nextBeatNo bpb bn) phs'
552 where
553 (phs', ns) = advanceHeads bd bn tr st phs
554
555
556 -- Print played notes in a time-stamped (bar, beat), easy-to-read format.
557
558 ppNotes :: BeatsPerBar -> [[Note]] -> IO ()
559 ppNotes bpb nss = ppnAux (zip [(br,bn) | br <- [1..], bn <- [1..bpb]] nss)
560 where
561 ppnAux [] = return ()
562 ppnAux ((_, []) : tnss) = ppnAux tnss
563 ppnAux ((t, ns) : tnss) = do
564 putStrLn ((leftJustify 10 (show t)) ++ ": "
565 ++ concat (intersperse ", " (map show ns)))
566 ppnAux tnss
567
568
569 leftJustify :: Int -> String -> String
570 leftJustify w s = take (w - length s) (repeat ' ') ++ s
571
572 {-
573 ------------------------------------------------------------------------------
574 -- Simple tests
575 ------------------------------------------------------------------------------
576
577 testBoard1 =
578 makeBoard [((0,0), mkCell (ChDir True na1 N)),
579 ((0,1), mkCell (ChDir False na1 SE)),
580 ((1,1), mkCell (Split na1)),
581 ((1,-1), mkCell (Split na1)),
582 ((-1,0), mkCell (ChDir False na2 NE))]
583
584 testBoard1a =
585 makeBoard [((0,0), mkCell (ChDir False na1 N)),
586 ((0,1), mkCell (ChDir False na1 SE)),
587 ((1,1), mkCell (Split na1)),
588 ((1,-1), mkCell (Split na1)),
589 ((-1,0), mkCell (ChDir False na2 NE))]
590
591 testBoard2 =
592 makeBoard [((0,0), mkCell (ChDir True na1 N)),
593 ((0,2), mkCellRpt (ChDir False na2 SE) 3),
594 ((2,1), mkCell (ChDir False na1 SW)),
595 ((1,1), mkCellRpt (ChDir False na1 N) 0) {- Skipped! -},
596 ((0,4), mkCellRpt (ChDir True na1 N) (-1)) {- Rpt indef. -},
597 ((0, -6), mkCell (ChDir True na1 N)),
598 ((0, -2), mkCell (ChDir False na3 S) {- Silent -})]
599
600 testBoard3 =
601 makeBoard [((0,0), mkCell (ChDir True na1 N))]
602
603 na1 = NoteAttr {
604 naArt = Accent13,
605 naDur = 1 % 4,
606 naOrn = Ornaments Nothing [] NoSlide
607 }
608
609 na2 = NoteAttr {
610 naArt = NoAccent,
611 naDur = 1 % 16,
612 naOrn = Ornaments Nothing [(10, MIDICVRnd)] SlideUp
613 }
614
615 na3 = NoteAttr {
616 naArt = Accent13,
617 naDur = 0,
618 naOrn = Ornaments Nothing [] NoSlide
619 }
620
621
622 bpb :: Int
623 bpb = 4
624
625 main = ppNotes bpb (take 50 (runRMCA testBoard3 bpb (Just 2) 0 0.8))
626 -}