% Created 2024-06-10 Mon 16:00
% Intended LaTeX compiler: pdflatex
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{fixltx2e}
\usepackage{graphicx}
\usepackage{longtable}
\usepackage{float}
\usepackage{wrapfig}
\usepackage{rotating}
\usepackage[normalem]{ulem}
\usepackage{amsmath}
\usepackage{textcomp}
\usepackage{marvosym}
\usepackage{wasysym}
\usepackage{amssymb}
\usepackage[hidelinks]{hyperref}
\tolerance=1000

\setcounter{tocdepth}{2}
\setcounter{secnumdepth}{4}
\usepackage{fontspec}
\setmainfont[Ligatures={Common,TeX}]{CharisSIL}
\setmonofont{Inconsolata}
\usepackage{caption}
\captionsetup[figure]{font={it,footnotesize},labelfont={it,footnotesize},singlelinecheck=false}
\captionsetup[table]{font={it,footnotesize},labelfont={it,footnotesize},singlelinecheck=false}
\captionsetup[lstlisting]{font={it,footnotesize},labelfont={it,footnotesize},singlelinecheck=false}
\usepackage{sclang-prettifier}
\hyphenation{Synth-Def Synth-Defs}
\usepackage{environ}
\NewEnviron{boxnote}[1][]{\bigskip\noindent\framebox[1\textwidth]{\parbox[c]{0.95\textwidth}{\textbf{Note:} \BODY}}\bigskip}
\author{H. James Harkins}
\date{\today}
\title{Chucklib-Livecode Manual}
\hypersetup{
 pdfauthor={H. James Harkins},
 pdftitle={Chucklib-Livecode Manual},
 pdfkeywords={},
 pdfsubject={},
 pdfcreator={Typeset by TeX Live 2017; Edited in Emacs 24.3.1 (Org mode 8.3beta).}, 
 pdflang={English}}
\begin{document}

\maketitle
\tableofcontents


\label{sec:orgee241e7}

\section{Introduction}
\label{sec:org1db6306}
\frenchspacing
\subsection{Overview}
\label{sec:org46bbfe6}
\emph{Chucklib-livecode} (\emph{cll} for short) is a system of extremely compact
commands extending the SuperCollider programming language. The
commands manipulate musical processes in real time to facilitate
live-coding performances. ``Processes'' in this sense refers to my
\emph{chucklib} quark, introduced in \emph{The SuperCollider Book}.\footnote{Harkins, H. James. (2011). ``Composition for Live
Performance with dewdrop\textunderscore lib and chucklib.'' In Wilson,
S., Cottle, D., Collins N. [eds.] \emph{The SuperCollider
Book}. Cambridge, Mass.: MIT Press. pp. 589--612.}

I began implementing \emph{cll} in August 2014, and it reached a stage
where I could begin performing with it in March 2015. The public
extensions are hosted on github.\footnote{\url{http://github.com/jamshark70/chucklib-livecode}}

\emph{cll} consists of two main parts:

\begin{enumerate}
\item A chucklib \emph{process prototype} (PR) that implements the methods
that the musical processes need, in order to receive information
from live-coding statements.

\item A \emph{preprocessor} installed into the SuperCollider interpreter. The
preprocessor translates the \emph{cll} command syntax into standard
SuperCollider code.
\end{enumerate}

This document begins with a tutorial of usage examples. This is enough
to begin making music with it. To add your own sounds, there are two
ways. For pitched note-players, create a Voicer factory and use one of
the standard pitch processes (see Section \ref{sec:org6e70349}). Otherwise, you can
create all-new live-coding processes by cloning
\texttt{PR(\textbackslash{}abstractLiveCode)} (see Section \ref{sec:org32811c4}).

\subsection{Acknowledgments}
\label{sec:orga46880c}
Thanks are due to:

\begin{itemize}
\item James McCartney and all the other developers who contributed to
SuperCollider over the years. Without SuperCollider, none of this
would exist.

\item Alex McLean, for his work on the \emph{Tidal} live-coding language for
music.\footnote{McLean, Alex. ``Making Programming Languages to Dance to:
Live Coding with Tidal.'' Proceedings of the 2nd ACM SIGPLAN
international workshop on Functional art, music, modeling \&
design, September 6, 2014, Gothenburg, Sweden, pp. 63--70.} \emph{Tidal} demonstration videos online were the first to
capture my imagination about live coding, leading me in this
direction.

\item Thor Magnusson, whose \emph{ixilang} system\footnote{\url{http://www.ixi-audio.net/ixilang/}, accessed October
4, 2016.} provided some of
the inspiration for \emph{cll} syntax.

\item Canton Becker of \url{http://sampleswap.org} for granting permission to
redistribute some audio files from sampleswap's online collection.
These are used in the \texttt{ddwLivecodeInstruments} quark, referenced
in the Tutorial (Section \ref{sec:org79176df}).
\end{itemize}

\section{Installation}
\label{sec:org2279fee}
\emph{cll} requires SuperCollider 3.7 or later, and recommends v3.9+. (It
is released using the Quarks v2 system, which is not supported prior
to SC 3.7.)

2019/01/26: As before, it is recommended to update all of the \texttt{ddw*}
quarks.

\subsection{Installation with \emph{git}}
\label{sec:orgc8e3c65}
If you have installed the \emph{git} version-control system on your
machine, SuperCollider can automatically download and install Quark
extensions. Simply evaluate
\texttt{Quarks.install("ddwChucklib-livecode")}. If there are no error
messages, recompile the class library and you should be ready to
proceed.

Optionally, also evaluate \texttt{Quarks.install("ddwLivecodeInstruments")}
to install a pack of ready-to-play instruments. These are used in the
Tutorial (\ref{sec:org79176df}).

\subsection{Installation without \emph{git}}
\label{sec:org641dcd6}
If you haven't installed \emph{git} or don't want to, you can download the
required Quark directories manually. In each of these web pages, look
for the green ``Clone or Download'' menu. From here, you can download a
ZIP.

\begin{itemize}
\item ddwChucklib: \url{https://github.com/jamshark70/ddwChucklib}
\item ddwPrototype: \url{https://github.com/jamshark70/ddwPrototype}
\item ddwCommon: \url{https://github.com/jamshark70/ddwCommon}
\item ddwGUIEnhancements: \url{https://github.com/jamshark70/ddwGUIEnhancements}
\item ddwMixerChannel: \url{https://github.com/jamshark70/ddwMixerChannel}
\item ddwPatterns: \url{https://github.com/jamshark70/ddwPatterns}
\item ddwTemperament: \url{https://github.com/jamshark70/ddwTemperament}
\item ddwVoicer: \url{https://github.com/jamshark70/ddwVoicer}
\item crucial-library: \url{https://github.com/crucialfelix/crucial-library@tags/4.1.5}
\item\relax [optional] ddwLiveCodeInstruments: \url{https://github.com/jamshark70/ddwLivecodeInstruments}
\end{itemize}

After downloading these quarks, do the following:

\begin{enumerate}
\item In the SC IDE, go to File \(\to\) \emph{Open user support directory}.

\item In this location, if there is no folder called \texttt{downloaded-quarks},
create this empty folder now.

\item Unpack all the ZIP files into the directory. After this, you should have:
\begin{itemize}
\item \texttt{downloaded-quarks/ddwChucklib}
\item \texttt{downloaded-quarks/ddwPrototype}
\item \ldots{} and so on. If there is a \texttt{-master} suffix on the directory
names, please remove it.
\end{itemize}

\item In SC, run the statement
\texttt{Quarks.install("ddwChucklib-livecode")}. If it doesn't find the
quarks, try recompiling the class library and then run the
statement again.

\item If all is successful, recompile the class library and proceed.
\end{enumerate}

\subsection{Running \emph{cll} in a session}
\label{sec:orgd6dad84}

\emph{cll} adds convenience functions to load the environment:

\begin{itemize}
\item \texttt{\textbackslash{}loadCl.eval}: Load the \emph{cll} preprocessor and a few helper functions.
\item \texttt{\textbackslash{}loadClExtras.eval}: Load extra user-interface components:mobile
control with TouchOSC, and interactive code editor, and
ddwLivecodeInstruments if you have installed the quark.
\item \texttt{\textbackslash{}loadAllCl.eval}: Load both of these at once.
\item \texttt{\textbackslash{}makeController.eval}: Open a graphical window with reusable mixing
and parameter controls. (See Section \ref{sec:org9dbbaf0}.)
Arguments are: Control prototype (currently, either \texttt{\textbackslash{}mix16Touch} or
\texttt{\textbackslash{}nanoTouch}), and a MIDI device search string (relevant only for
\texttt{\textbackslash{}nanoTouch}).
\item \texttt{\textbackslash{}makeCodeWindow.eval}: Open a code editor window with
\emph{cll}-specific features.
\item \texttt{\textbackslash{}cllGui.eval}: Open both the controller and code windows. Accepts
the same arguments as \texttt{\textbackslash{}makeController}.
\end{itemize}

These are \emph{not} executed by default at SC startup, because you may not
want the preprocessor in every SC session. Once you load the
environment, the preprocessor is active until the next time you
recompile the class library.

\section{Tutorial}
\label{sec:org79176df}
First, if you didn't install the optional \texttt{ddwLivecodeInstruments}
quark, please do so now. Without these, you will have to learn the
mechanics of creating a live-coding process before playing any
music. See section \ref{sec:org2279fee} for installation details.

\texttt{ddwLivecodeInstruments} provides a set of standard electronic drums
(Section \ref{sec:org83fa03c}), and several synthesizers for pitched notes (Section
\ref{sec:org6e70349}).

I recommend working step-by-step, starting with the drums (because
there are fewer variables and moving parts) before moving on to
pitches. You will probably get more out of it by typing the code
examples yourself, rather than copying/pasting.\footnote{Copying from this PDF is likely to change the
code formatting and possibly break the code. If you must copy/paste,
use the file \texttt{cl-manual-examples.scd}.}
I've tried to make it easy to get started, but bear in mind that this
improvisational instrument has been in development since mid-2014. You
shouldn't expect to understand it all in 15 minutes (just as you
wouldn't expect to read a couple of tutorials about SuperCollider
itself and ``understand'' it in depth). Take your
time. Experiment. Start with the examples and change them.

If you encounter problems, you could post on the SuperCollider users
mailing list\footnote{\url{https://www.birmingham.ac.uk/facilities/ea-studios/research/supercollider/mailinglist.aspx}} or the ddwChucklib-livecode issue
tracker.\footnote{\url{https://github.com/jamshark70/ddwChucklib-livecode/issues}} (Also note that this is the first
version of the tutorial. Many things may be badly explained as
yet. Don't hesitate to raise an issue if something is confusing.)

\subsection{Starting a session}
\label{sec:orgf8fbee8}
\begin{figure}
\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=startup1,caption={Launching chucklib-livecode.},captionpos=b,numbers=none}
\begin{lstlisting}
\loadAllCl.eval;

// optional
\cllGui.eval;
\end{lstlisting}
\end{figure}

When you launch SuperCollider, \emph{cll} is not active. (For normal usage,
you want to use the standard parser as is.) To use \emph{cll}, you need to
load the environment. Optionally, you can open a graphical environment
with some additional features (see Section \ref{sec:org9dbbaf0}).

\subsection{Drums}
\label{sec:org83fa03c}
\begin{figure}
\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=drums1,caption={A quick techno-ish drumset.},captionpos=b,numbers=none}
\begin{lstlisting}
\loadAllCl.eval;
TempoClock.tempo = 124/60;

/hh.(\hardhh);
/hhh = ".-.-.-.-";
/hhh+

/drum.(\tightsnr);
/tsn = " - -";
/tsn+

/drum.(\deepkick);
/dk = "o| o| _o |";
/dk+

// mixing board
/makeEmptyMixer8.();
/hhh => MCG(0);
/tsn => MCG(1);
/dk => MCG(2);

/hhh/tsn/dk-
\end{lstlisting}
\end{figure}

We'll start with drums (Listing \ref{drums1}), because the notation is a
little simpler.

Kicks and snares are created by the convenience function
\texttt{/drum.(name)}; use \texttt{/hh.(name)} for hi-hats. Available names are:

\begin{itemize}
\item \texttt{/drum.(name)}
\begin{itemize}
\item \texttt{\textbackslash{}deepkick}: \texttt{BP(\textbackslash{}dk)}
\item \texttt{\textbackslash{}tightkick}: \texttt{BP(\textbackslash{}tk)}
\item \texttt{\textbackslash{}midkick}: \texttt{BP(\textbackslash{}mk)}
\item \texttt{\textbackslash{}tightsnr}: \texttt{BP(\textbackslash{}tsn)}
\item \texttt{\textbackslash{}fatsnr}: \texttt{BP(\textbackslash{}fsn)}
\item \texttt{\textbackslash{}pitchsnr}: \texttt{BP(\textbackslash{}psn)}
\item \texttt{\textbackslash{}snr80}: \texttt{BP(\textbackslash{}s8)}
\item \texttt{\textbackslash{}clap}: \texttt{BP(\textbackslash{}clp)}
\end{itemize}
\end{itemize}

\begin{itemize}
\item \texttt{/hh.(name)}
\begin{itemize}
\item \texttt{\textbackslash{}thickhh}: \texttt{BP(\textbackslash{}hh)}
\item \texttt{\textbackslash{}thinhh}: \texttt{BP(\textbackslash{}thh)}
\item \texttt{\textbackslash{}hardhh}: \texttt{BP(\textbackslash{}hhh)}
\item \texttt{\textbackslash{}synthhh}: \texttt{BP(\textbackslash{}shh)}
\end{itemize}
\end{itemize}

Note the pattern to use an instrument:

\begin{itemize}
\item Create it, using the \texttt{/drum.(\textbackslash{}name)} for drums and \texttt{/hh.(\textbackslash{}name)} for
hi-hats. The result is a \texttt{BP} object---a Chucklib ``bound process.''
You can access the process object globally by putting its name in
parentheses: \texttt{BP(\textbackslash{}dk)}, for instance. Many \emph{cll} commands use only
the name with a leading slash: \texttt{/dk}.

\item Give it some music to play (by assigning it a pattern string). More
about pattern strings below.

\item Start it (\texttt{+}). If \texttt{+} is start, \texttt{-} is stop. You can start and stop
several processes at once by listing them on the same line, each
name beginning with its slash: Listing \ref{drums1} stops all three
processes using one command, \texttt{/hhh/tsn/dk-}. By default, the
processes will start or stop on the next bar line
(\texttt{BP(\textbackslash{}name).beatsPerBar}). You can override this by putting a number
of beats after the \texttt{+} or \texttt{-}: \texttt{/dk+8} for the next even bar line.
\end{itemize}

\textbf{Mixing:} \texttt{loadAllCl} creates a few \texttt{MixerChannel} objects: \texttt{\textasciitilde{}hwOut}
(hardware output), \texttt{\textasciitilde{}master} (main output), \texttt{\textasciitilde{}rvbmc} (long-tail
reverb), \texttt{\textasciitilde{}longrvbmc} (long-tail reverb), and \texttt{\textasciitilde{}shortrvbmc}
(short-tail reverb).\footnote{The distinction between \texttt{\textasciitilde{}hwOut} and \texttt{\textasciitilde{}master}
is for multitrack recording of live sets, where you may wish to record
the main, dry mix (\texttt{\textasciitilde{}master}) separately from reverbs. In general,
processes and instruments should direct their signal to \texttt{\textasciitilde{}master};
reverbs and other separate channels (e.g., microphones) may connect
directly to \texttt{\textasciitilde{}hwOut}.} If you want to adjust the
mix, first run \texttt{/makeEmptyMixer8.()}. After that, you can ``chuck''
mixers, processes or Voicers into mixing board slots: \texttt{\textasciitilde{}master =>
MCG(7)}, e.g., for the rightmost slot. Later, when you create playing
objects, you can chuck them in as well. For instance, where Listing
\ref{drums1} creates a \texttt{tightsnr} player, you can do \texttt{/tsn => MCG(0)} and
its mixer will appear.

\subsection{Pattern strings}
\label{sec:org2037b1e}

Cll uses single characters for notes, and spaces for timing placeholders.

\begin{itemize}
\item Kick drums: \texttt{o} = normal weight, \texttt{\_} = ghost note
\item Snare drums: \texttt{-} = normal weight, \texttt{.} = ghost note\footnote{The characters for kicks and snares are
different, so that a kick and a snare could be combined into one
process: \texttt{/drum.(\#[tightkick, tightsnr]);}.}
\item Hi-hats: \texttt{-} = open hat, \texttt{.} = closed hat
\end{itemize}

By default, the unit of time is one bar (taken from the default
\texttt{TempoClock}, whose default \texttt{beatsPerBar} is 4). The characters and
placeholders divide this time span equally: \texttt{/hhh} has 8 characters,
splitting the bar into 8th-notes, while \texttt{/tsn} has 4. You might think
the spaces in \texttt{/tsn} are rests, but they aren't: they only specify the
passage of time, here forcing the two snare drum strokes onto beats 2
and 4.

The kick drum pattern is slightly more complicated. The vertical pipes
(\texttt{|}) are dividers. Dividers appear \emph{between}, but not surrounding,
the time spans; three dividers demarcate four divisions:
\texttt{"1|2|3|4"}. Each subdivision is divided equally by the
characters contained within. In \texttt{"o| o| \_o |"}, the
first beat is a quarter-note, the second divides into 8th-notes and
the third into 16ths. With a little practice, you can read the rhythm
directly from the ASCII notation.

\begin{itemize}
\item Exercise: Edit the given pattern strings to create more interesting
rhythms. After every change, reevaluate the line. This is the basic
process of improvising with \emph{cll}.
\end{itemize}

\subsection{Generators}
\label{sec:org8f9b2d2}
\begin{figure}
\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=drums2,caption={Generators for drums.},captionpos=b,numbers=none}
\begin{lstlisting}
/hhh/tsn/dk+

// A
/tsn = "[ - -]::\ins(".", 2, 0.25)";

// B
/tsn = "[ - -]::\ins(".", 2, 0.5)";

// C
/tsn = "[ - -]::\ins(".", 2, 0.5)::\shift(".", 2, 0.25)";

// D (empty source, so, omitted)
/hhh = "\ins("-", 1, 0.5)::\ins(".", 7, 0.5)";

// E (one closed HH to fill start of bar)
/hhh = "[.]::\ins("-", 1, 0.5)::\ins(".", 6, 0.5)";

// F
/hhh = "[.]::\ins("-", 1, 0.5)::\ins(".", 6, 0.5)::\ins(".", 2, 0.25)";

// G
/hhh = "\fork("|\ins("-", 1, 0.5)||x")::\ins(".", 7, 0.5)::\ins(".", 2, 0.25)";

/hhh/tsn/dk-
\end{lstlisting}
\end{figure}

\emph{Cll} can also generate new materials algorithmically. (The tutorial
can provide only a brief demonstration, not complete
documentation. See Section \ref{sec:org8f9b2d2} for more detail.)

Generators take a given pattern string as their initial input,
enclosed in brackets, and modify it by inserting, deleting or
replacing entries. (The initial pattern string can be empty, in which
case it may be omitted.) A few basic functions are:

\begin{itemize}
\item \texttt{\textbackslash{}ins("item pool", number, quant)}: Insert \emph{number} new
items, randomly chosen from the \emph{item pool}, at rhythmic intervals
given by \emph{quant} (e.g. 0.25 = quarter beats = 16th-notes).
\item \texttt{\textbackslash{}shift("item pool", number, quant)}: Locate \emph{number} of
the items in \emph{item pool}, and shift them earlier or later by the
rhythmic value given by \emph{quant}.
\item I will expand this list later.
\end{itemize}

For example, the snare drum would benefit from some ghost notes, and
it's more fun if they change from bar to bar. We could insert them
into any open 16th-note (Listing \ref{drums2}, example A). But if you play
this long enough, eventually you will hear some bars with too many
8th-notes. This sounds stilted. It would be better to force the ghost
notes onto off-beat 16ths. An easy way to do that is to place the
ghost notes onto 8th-notes (B), and then shift them (C). Note the \texttt{::}
syntax. This creates a \emph{generator chain}, where the result of the a
generator (or source) feeds into the the next. (Because the chain
provides the source string for \texttt{\textbackslash{}shift()}, you don't need to write a
source---but you still need the comma.)

For hi-hats, a musically sensible way to operate is to place one or
more open hats, and then fill the remaining spaces with closed hats
(D). Here too, eventually you will run into a musical problem: an open
hat on the downbeat sounds awkward. Instead, you can place a closed
hat explicitly in the first slot (E), ``protecting'' that space from
insertion. (The example adjusts the number of closed hats to insert at
the end, from 7 to 6. While formally correct, it isn't necessary in
the performance. \texttt{\textbackslash{}ins()} will add as many as it can, and not complain
if it doesn't reach the requested number.) Finally, for some more
spice, you can add a few 16th-notes.

Another way to ``protect'' part of the bar from a generator is to
\texttt{\textbackslash{}fork()} it. \texttt{\textbackslash{}fork()} takes a source string, and another string
placing generators in specific parts of the bar. In example G, the
fork string places an \texttt{\textbackslash{}ins()} on beat 2, and follows it with an \texttt{x}
on beat 4. The \texttt{\textbackslash{}ins()}, then, cannot operate before beat 2, and the
\texttt{x} ends the \texttt{\textbackslash{}ins()} generator's range of influence. So the open hat
can be inserted in positions 2, 2.5, 3 and 3.5 (not including 4, which
belongs to \texttt{x}). \texttt{x} is not a generator, so it does nothing in the
context of \texttt{\textbackslash{}fork()} except delimit time. After the \texttt{fork()}, the
remaining generators operate on the whole bar, as before. This is an
important technique to control the time over which generators may take
effect.

It isn't very useful for drums, but a typical generator usage is to
insert wildcards (usually \texttt{*} or \texttt{@}) to define the rhythm, and then
replace them using a number of generators inspired by SuperCollider
patterns: \texttt{\textbackslash{}seq()}, \texttt{\textbackslash{}rand()}, \texttt{\textbackslash{}shuf()}, \texttt{\textbackslash{}wrand()} and such. These
are more useful when you have a larger number of possible items to
choose from, such as when playing a pitched instrument.

\textbf{HINT:} If you have installed the ddwSnippets Quark, generator objects
will automatically add their own templates into the snippets
collection. The snippets can help you with the order of arguments:
press the snippet hotkey (which you configure using
\texttt{DDWSnippets.learn}), type a few letters of the generator name, and
the template will be inserted into your document.

\subsection{Sound effects}
\label{sec:org590390e}
\begin{figure}
\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=sfx1,caption={Adding sound effects to a simple beat.},captionpos=b,numbers=none}
\begin{lstlisting}
\loadAllCl.eval;  // If you haven't already done this
TempoClock.tempo = 124/60;

// The beat
BP(#[tk, clp, hhh, tsn]).free;  // Clean up first
/drum.(\tightkick); /drum.(\clap); /hh.(\hardhh);
/tk = "o|| o|";
/clp = " -  ";
/hhh = "........";

/tk/clp/hhh+

/drum.(\tightsnr);
/tsn = "|||.";

/tsn+

/clp = "|-|| .  ";
/tsn = "|||.  .";

// make the effects
/make(bufBP:mch(set:\machine));
/mch = "| -||";
/mch+

/mch = "| -| , ,|";

/tk/clp/hhh/tsn/mch-;
\end{lstlisting}
\end{figure}

The \texttt{bufBP} template provides some unusual percussion sounds, for
extra color.

The sounds are organized into ``sets,'' so that each resulting process
has a simpler interface. To choose a sound set, use the parameter
notation of the \texttt{/make} command: \texttt{/make(bufBP:name(set:\textbackslash{}setName))},
substituting your desired process name for \texttt{name} and the name of the
set for \texttt{setName}.

\begin{itemize}
\item \texttt{machine}: Servomotor clips (3)
\item \texttt{tink}: Metallic (2)
\item \texttt{whistle}: A sound reminiscent of a train whistle (3)
\item \texttt{wiggle}: A, well, ``wiggle'' (for lack of a better word) (3)
\end{itemize}

In pattern strings, you can use the following characters (chosen as a
visual approximation of pitch level and duration):

\begin{center}
\begin{tabular}{|c|c|c|}
\hline
\textbf{Pitch} & \textbf{Long} & \textbf{Short}\\
\hline
High & \texttt{\textasciicircum{}} & \texttt{!}\\
\hline
Middle & \texttt{-} & \texttt{.}\\
\hline
Low & \texttt{\_} & \texttt{,}\\
\hline
\end{tabular}
\end{center}

Note, however, that the \texttt{tink} set has only two sounds, omitting the
high pitch level. With this set, \texttt{\textasciicircum{}} and \texttt{!} are rests (silent).

Figure \ref{sfx1} is a simple example. You should play with the other sets
and make your own rhythms.

\subsection{Pitched notes}
\label{sec:org6e70349}
Pitched-note processes require a Voicer instrument and a BP process to
play the notes.

Available Voicers:

\begin{itemize}
\item \texttt{anapadVC}: Analog-style pad.
\item \texttt{distbsVC}: Distorted-sine bass.
\item \texttt{fmMelVC}: Maps notes onto FM modulator ratio, playing harmonics. A bit strange.
\item \texttt{fmbassVC}: FM bass.
\item \texttt{fmbrassVC}: Brassy FM tone.
\item \texttt{fmclavVC}: FM clav tone.
\item \texttt{fmpadVC}: FM pad.
\item \texttt{klankVC}: Detuned bell-like timbre. Not sustaining.
\item \texttt{pbsVC}: Pulse-wave bass.
\item \texttt{pulseLeadVC}: Pulse-wave synth lead.
\item \texttt{staccVC}: Analog-style staccato notes.
\end{itemize}

Available BP processes:

\begin{itemize}
\item \texttt{melBP}: Monophonic melody player. Use for basses and leads.
\item \texttt{chordBP}: Block-chord player.
\item \texttt{arpegBP}: Chord arpeggiator.
\end{itemize}

\subsubsection{Pitch: Overview}
\label{sec:org0752f72}

Using pitch in \emph{cll} requires a little preparation.

\begin{enumerate}
\item Set the tempo. (You should do this in every performance, as already
demonstrated in Listing \ref{drums1}.)
\item Set the \emph{mode} by \texttt{/changeKey.(\textbackslash{}name)}. \emph{ddwLivecodeInstruments}
defines a \texttt{Mode} object for all seven classical Western modes, for
all 12 chromatic steps. Modes are identified by the root pitch
(\texttt{c}, \texttt{cs} = c-sharp, \texttt{db} = d-flat, and so on) plus a modal
identifier (Table \ref{modes}). B-flat lydian is \texttt{Mode(\textbackslash{}bblyd)}; F-sharp
minor is \texttt{Mode(\textbackslash{}fsmin)}.

\begin{table}[htbp]
\caption{\label{modes}Modal identifiers.}
\centering
\begin{tabular}{|c|c|}
\hline
Mode & ID\\
\hline
Major (Ionian) & \texttt{maj}\\
Dorian & \texttt{dor}\\
Phrygian & \texttt{phr}\\
Lydian & \texttt{lyd}\\
Mixolydian & \texttt{mixo}\\
Minor (Aeolian) & \texttt{min}\\
Locrian & \texttt{loc}\\
\hline
\end{tabular}
\end{table}

\item Create instruments and players. Internally, this is a three-step
process: 1. Create the Voicer instrument. 2. Create the playing
process. 3. Connect the instrument to the player. \emph{Cll} provides a
shortcut: If you write a single \texttt{/make} command that creates the
instrument first (1), followed by the player process (2), then
\texttt{/make} will automatically assign the instrument to the player (3,
implicitly). Listing \ref{bass1} demonstrates with
\texttt{/make(pbsVC:pbs/melBP:bs(octave:3));}:

\begin{itemize}
\item \texttt{/make}
\begin{itemize}
\item \texttt{pbsVC:pbs}: Make the \texttt{pbsVC} instrument under the name \texttt{pbs}.
\item \texttt{melBP:bs}: Make the melody player \texttt{melBP} under the name \texttt{bs}.
\begin{itemize}
\item \texttt{(octave:3)}: A parameter to apply to the new \texttt{bs} process.
\end{itemize}
\item (Here, \emph{cll} does \texttt{VC(\textbackslash{}pbs) => BP(\textbackslash{}bs)} for you, but you don't
have to write anything for this!)
\end{itemize}
\end{itemize}

The general form is \texttt{/make(factoryID:instanceID(parameters...))} with
additional factory/instance pairs separated by slashes.
\end{enumerate}

\subsubsection{Pattern string pitch specification}
\label{sec:org882e943}

In pattern strings, the modal root is \texttt{1}.\footnote{In SuperCollider pattern terms, \texttt{1} translates into degree 0.} Each note
begins with a single digit, going up from there: 8 is an octave
higher, 9 is the 9th, and 0 is the 10th (octave above the
third).\footnote{Currently a diatonic scale (7 degrees) is assumed.} This follows the arrangement of digits on the
keyboard: the further right you go, the higher the pitch. You can also
attach various modifiers:

\begin{itemize}
\item \texttt{'} or \texttt{,}: Up or down one octave. \texttt{''} is up two
octaves, and so on.
\item \texttt{+} or \texttt{-}: Up or down a semitone (like sharp or flat). \textbf{NOTE:}
Flats are not completely working as of this writing.
\item \texttt{.} or \texttt{\_} or \texttt{\textasciitilde{}}: Staccato, legato or slurred articulation. A slur
will slide into the next note, if the instrument supports it.
\item \texttt{>}: Accent articulation. Always prevents a slur, and depending on
the instrument, it might hit the note a little harder. \texttt{>} may be
combined with other articulations.
\end{itemize}

The digit plus its modifiers becomes a single event---so, in Listing
\ref{bass1}, beat 3 contains five characters but four events (\texttt{7\textasciitilde{}} is
just one event). Timing is based on events, not characters.

Any event that does not begin with a digit---I often use \texttt{x}---is a
rest, which cuts off the preceding note (in contrast to a space, which
affects timing only).

\subsubsection{Basses and leads}
\label{sec:org65f49a9}
\begin{figure}
\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=bass1,caption={Bassline template.},captionpos=b,numbers=none}
\begin{lstlisting}
/changeKey.(\dmixo);
/make(pbsVC:pbs/melBP:bs(octave:3));

/bs = "1_| 1.|  7~4|x";

/bs+
/bs-
\end{lstlisting}
\end{figure}

Basses and leads should use the \texttt{melBP} melody player: one written
note produces one sounding note (Listing \ref{bass1}).

For basses in particular, get in the habit of assigning the
octave. This is the normal \texttt{octave} event parameter from the
SuperCollider pattern system. Assuming C as the modal root, octave 5
puts scale degree 0 at middle C. Octave 3 in the example pulls the
bass two octaves lower. If you forget, you can correct it later by
\texttt{/bs(setDefault(\textbackslash{}octave, 4))} or whichever octave number you need.

Leads follow the same principles, except in a higher octave.

Exercise: Modify the given template to add more notes. Try the
different articulation styles.

\subsubsection{Chords}
\label{sec:orga791124}
\begin{figure}
\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=chord1,caption={Chord-playing template.},captionpos=b,numbers=none}
\begin{lstlisting}
/make(anapadVC:pad/chordBP:ch(chords:\one));
/ch = "87~05";
/ch+

VC(\pad).gui

MBM(0)[\two] => BP(\ch);

MBM(0)[\smallch] => BP(\ch);

/ch-
\end{lstlisting}
\end{figure}

\texttt{chordBP} (Listing \ref{chord1}) uses the same pitch notation, but to
control the top note of a harmony. The harmonies come from chord
templates stored in a MIDI buffer object (\texttt{MIDIRecBuf}). Currently,
four are provided (later documentation: how to create your own chord
templates).

\begin{itemize}
\item \texttt{one}: Single notes (so that the chord player can start as a melody,
and grow into harmony).
\item \texttt{two}: Two-note chords, in all intervals from a second to an octave.
\item \texttt{smallch}: Three-note chords, not all standard triads.
\item \texttt{bigch}: Six-note chords.
\end{itemize}

The chord templates will be adapted to the top note and the current
chord root (later documentation: how to control the root).

Articulations (including slur!) are valid.

\subsubsection{Arpeggiator}
\label{sec:org475229d}
\begin{figure}
\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=arpeg1,caption={Example of arpeggiator usage.},captionpos=b,numbers=none}
\begin{lstlisting}
/make(fmclavVC:fmc/arpegBP:arp(chords:\bigch));

// These are indices, from the top down, into the current chord.
/arp = "1234";

/arp+

// Add some lower notes as a second layer.
// Accent articulates the start of the bar.
/arp = "[1>234]::\ins("456", 6, 0.25)";

// Extend the second layer higher.
/arp = "[1>234]::\ins("23456", 7, 0.25)";

// Use wildcards to substitute a sequential pattern.
/arp = "[1>234]::\ins("*", 7, 0.25)::\seq("65432")";

// Change the harmony's top note every bar.
/arp..top = "[*]::\seq("5'6'3'2'")";

// Skip: Play dyads instead of single notes.
/arp..skip = "2";

// Skip can also accent specific notes.
/arp..skip = "20  |20  |20  |20  ";

// same, but algorithmic
/arp..skip = "[2222]::\choke(0.25, "0")";

// Add a second process to change the chord root.
// After this, you should hear tonic, dominant
// and subdominant functions.
// No instrument -- this is for data only.
/make(melBP:root(bassID:\bass));
/root = "[*]::\seq("154")";
/root+

/arp/root-
\end{lstlisting}
\end{figure}

\textbf{NOTE:} The arpeggiator is a bit complex to use, and it isn't a high
priority for the first round of documentation. I'm providing an
example (Listing \ref{arpeg1}) to give you some hints, and I want to expand
the documentation later. For now, try it, and if you run into trouble,
file an issue at
\url{https://github.com/jamshark70/ddwChucklib-livecode/issues}.

The arpeggiator is a bit strange. It uses the same harmony-processing
logic as \texttt{chordBP}, but the pitches in the pattern string are indices
of chord notes, not the actual sounding pitches. 1 is the top note, 2
is the next lower, and so on proceeding down the chord to 7. 8, as a
normal pitch, is an octave higher than 1; in the arpeggiator, it takes
the top note of the chord and raises it by an octave (and all seven
indices do octave displacement in the same way).

To make best use of this process, you need to assign alternate
parameters: \texttt{top} for the top note of the harmony (which behaves like
\texttt{chordBP}) and \texttt{skip} for extra thickness. The default \texttt{skip} is 0,
meaning to play single notes. Try the other values (1--5). Note that
the harmony will not change unless \texttt{top} changes, so it's a good idea
to supply a slower-moving pattern for this parameter.

The double-dots are a syntax shortcut. Cll processes can store any
number of phrases and switch between them. So far, we are using only
the default phrase, \texttt{main}. The full form of the \texttt{skip} and \texttt{top}
statements in the example is, in fact, \texttt{/arp.main.top = "..."};
omitting \texttt{main} leaves \texttt{/arp..top}. (You can't leave out one of the
dots. If you do, \texttt{top} will be interpreted as a phrase name, and it
won't behave the way you want.)

\subsubsection{Pitched instrument parameters}
\label{sec:org338358e}
Voicer instruments have two types of parameters: ``global controls'' and
event parameters.

Global controls act like knobs on conventional synthesizers, by
affecting all playing notes. These can be displayed automatically in a
GUI window by running \texttt{VC(\textbackslash{}name).gui}. Alternately, you could load
Chucklib's performance GUI (\texttt{\textbackslash{}cllGui.eval}); for details, see Section
\ref{sec:org9dbbaf0}.

Event parameters should normally take care of themselves. If you need
to override, use the form \texttt{/processName(setDefault(\textbackslash{}parameter,
value))}. It should be rare to need to do this, but it's useful, for
instance, if you forget to set the octave of a bass process and it
starts playing in the middle register. Just do
\texttt{/process(setDefault(\textbackslash{}octave, 3))} (or other value) and the next note
will be lower.

(This is a tutorial, not reference documentation for all the
instruments. Documentation to be expanded later.)

\subsection{Phrases}
\label{sec:orgb1a1a43}
\begin{figure}
\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=fill1,caption={Phrase selection for drum fills.},captionpos=b,numbers=none}
\begin{lstlisting}
TempoClock.tempo = 124/60;

/drum.(\tightkick); /drum.(\tightsnr); /hh.(\thinhh);

/tk = "oooo";
/tsn = " - -";
/thh = "[.]::\ins("-", 1, 0.5)::\ins(".", 6, 0.5)";

/tk/tsn/thh+

/tk.fill = "o||   _|o __";

// mid-bar source string:
// in this position, it fills 3 eighth-notes
/tsn.fill = "|-| [ - ]::\ins(".", 4, 0.25)|";

/tk = (main*3.fill); /tsn = (main*3.fill);

/tk/tsn/thh-
\end{lstlisting}
\end{figure}

The examples so far repeat a single bar's worth of content. Cll
processes allow you to define multiple bars, and choose between them.

Each bar, or \emph{phrase}, has a name. Attach it after the process name,
with a dot: \texttt{/process.phrase = "content"}. Then, use a phrase
selection pattern (Section \ref{sec:orgaff87a2}) to choose the bars in
succession. Listing \ref{fill1} demonstrates with drum processes, playing
the basic pattern for three bars and a fill pattern for the fourth.

\begin{figure}
\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=qsphrases1,caption={Multi-bar bassline.},captionpos=b,numbers=none}
\begin{lstlisting}
// If the bass doesn't exist, first do this:
/make(pbsVC:pbs/melBP:bs(octave:3));

/bars.(\bs, 2, \a);

/bs.a0 = "1>|4~5~7 | 4~|3'~";
/bs.a1 = " 5>~|6| 4~| 3";

/setupbars.(\bs, 2, \b);

/bs.b0 = "9>.9.9 | 4'~|   3'|8~7~8~ ";
/bs.b1 = "  33.| 4.5~ | 431.|6.6. 6.";

// short form of /setm.(\bs, 2, \b)
/bs = (b**2);

/bs+
/bs-
\end{lstlisting}
\end{figure}

Alternately, you can create multi-bar structures using a few
convenience functions (Listing \ref{qsphrases1}):

\begin{itemize}
\item \texttt{/setupbars.(\textbackslash{}proc, n, \textbackslash{}prefix)}: Creates \emph{n} empty bars, named
\texttt{\textbackslash{}prefix0}, \texttt{\textbackslash{}prefix1} and so on.
\item \texttt{/setm.(\textbackslash{}proc, n, \textbackslash{}prefix)}: Tell the process to use a multi-bar
phrase set for playback.
\item \texttt{/bars.(\textbackslash{}proc, n, \textbackslash{}prefix)}: Do both at the same time.
\end{itemize}

\textbf{IMPORTANT:} Do not omit the \texttt{.} between the function name and the
arguments. Cll distinguishes between a \emph{function-call} shortcut
\texttt{/name.(args)} and a \emph{method-passthrough} shortcut
\texttt{/proc(method(args))}, with the dot to tell the difference.

Note that \texttt{/bars.()} will tell the process to start playing a silent
phrase structure. So, you should use it only when setting up a new
process. If you're already playing material, it's better to
\texttt{/setupbars.()} first, fill the bars with material, and then switch to
the material using \texttt{/setm.()}.

An alternate syntax for \texttt{/setm.()} is \texttt{/proc = (prefix**n)}. This
command also sets the process's \texttt{quant} to the same number of bars, so
that the process will start and stop on the boundaries of the entire
phrase set. Be careful when switching from a single-bar structure to
multiple bars: you should hit \texttt{/setm.()} or the alternate syntax
within the bar before the boundary.

For convenience, \texttt{/setupbars.()} will try to insert a code template
with the empty bars into the current SC-IDE document.

\subsection{Errors}
\label{sec:org9eb3970}
Cll syntax errors are reported in the form ``ERROR: \ldots{}'' (with a brief
explanation).

A common error is ``ERROR: clPatternSet: BP(`abc') does not exist,''
meaning that a cll command referred to a process that hasn't been
created. Look for a misspelled name. (Cll is a translator, converting
its own syntax into SC language code. Many of the translations depend
on information within the object. If the objects don't exist,
translation is impossible. So, it fails in the translation stage---but
the translation happens in SC language code, so it must be reported as
an execution error.)

If an error occurs within a process while it's playing, usually the
bottom of the stack trace will refer to \texttt{awake} or \texttt{prStart}. Please
report such errors to
\url{https://github.com/jamshark70/ddwChucklib-livecode/issues}; as much as
possible, cll should try to continue playing without stopping
processes. If this does happen to you, it should be possible to
recover by simply playing the process again. (Internally, the process
will try to reset itself. If this fails for some reason, you can
manually \texttt{stop} and \texttt{reset} before trying again to play it.)

\section{Process prototype}
\label{sec:org32811c4}
\emph{Cll} is not limited to the preset instruments. In theory, \emph{cll} can
play any \texttt{SynthDef} (or complex of synths!) by modifying a \emph{process
prototype}, \texttt{PR(\textbackslash{}clAbstractLiveCode)}. This prototype is the interface
between \emph{cll} patterns and your sounding material. We've seen how
pattern strings use single-character identifiers to denote
rhythm. \texttt{PR(\textbackslash{}clAbstractLiveCode)} translates these identifiers into
real parameter values, and provides hooks to supply other information
necessary for playing.

Before we get to the details, you should understand the data structure.

\subsection{Data structure}
\label{sec:orge26dafa}
\emph{cll} organizes musical behavior, and musical content, hierarchically:

\begin{itemize}
\item Chucklib \emph{processes} (BP) contain any number of \emph{phrases}. Every
process has its own variable scope (i.e., independent
namespace). Activity in one process does not interfere with other
processes.
\item Each \emph{phrase} contains multiple \emph{parameters}. (The phrase itself is
implemented as a \texttt{PbindProxy}, so that its contents can be changed at
any time.)
\item Each \emph{parameter} is defined by a pattern string, parsed and rendered
into SuperCollider pattern syntax by the \emph{Set pattern} statement
(Section \ref{sec:org3e10854}).
\item Parameter values are defined by the \emph{parameter map} (\texttt{parmMap}).
\end{itemize}

\emph{cll} processes create two phrases by default:

\begin{description}
\item[{\texttt{main}}] The default phrase, which plays if the user hasn't
specified a different phrase sequence. \texttt{main} is also the default
phrase that \emph{Set pattern} acts on---thus, a user can work with
single-bar loops using only \texttt{main}, and never specify a phrase
ID.
\item[{\texttt{rest}}] An empty phrase, which only occupies time.
\end{description}

\subsection{PR(\textbackslash abstractLiveCode)}
\label{sec:org8ec1746}
\begin{figure}
\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=instance1,caption={Defining a simple cll process as a factory.},captionpos=b,numbers=none}
\begin{lstlisting}
(
(
defaultName: \beep,
make: { |name|
   PR(\abstractLiveCode).chuck(BP(name), nil, (
      userprep: {
         ~buf = Buffer.read(
            s, Platform.resourceDir +/+ "sounds/a11wlk01.wav",
            4982, 10320
         );
         ~defaults[\bufnum] = ~buf;
         SynthDef(\buf1, { |out, bufnum, pan, amp, time = 1|
            var sig = PlayBuf.ar(1, bufnum),
            eg = EnvGen.kr(
               Env.linen(0.02,
                  min(time, BufDur.ir(bufnum) - 0.04), 0.02),
               doneAction: 2
            );
            Out.ar(out, Pan2.ar(sig, pan, amp * eg));
         }).add;
      },
      userfree: {
         ~buf.free;
      },
      defaultParm: \amp,
      parmMap: (
         amp: ($.: 0.1, $-: 0.4, $^: 0.8),
         pan: (
            $<: -0.9, $>: 0.9,
            $(: -0.4, $): 0.4,
            $-: 0
         )
      ),
      defaults: (instrument: \buf1),
      postDefaults: Pbind(
         \time, (Pkey(\dur) * 0.6 / Pfunc { ~clock.tempo }).clip(0.04, 0.2)
      )
   ));
}, type: \bp) => Fact(\beepBP);
)
\end{lstlisting}
\end{figure}

\begin{figure}
\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=instance2,caption={Using the cll process factory in a performance.},captionpos=b,numbers=none}
\begin{lstlisting}
\loadCl.eval;  // or \loadAllCl.eval;
TempoClock.tempo = 2;

/make(beepBP);  // defaultName is 'beep' so you get BP(\beep)
/beep = "^|.. .| .- | .  ";  // "Set pattern"
/beep+;  // start it

/beep..pan = "<><><><>";  // change something

/make(beepBP:beep2);  // ':' overrides defaultName
/beep2 = " ..-| .^ |. ..| .";
/beep2+

/beep..pan = "<";
/beep2..pan = ">";

/beep/beep2-;

/beep(free); /beep2(free);
\end{lstlisting}
\end{figure}

To create a \emph{cll} process, ``chuck'' \texttt{PR(\textbackslash{}abstractLiveCode)} into a BP
(``Bound Process''), with a parameter dictionary providing the
details. Parameters to include in the dictionary:

\begin{description}
\item[{\texttt{userprep}}] A function, called when the process is created. Use
this function to create any resources that the process will
require.
\item[{\texttt{userfree}}] A function, called when the process is
destroyed. Clean up any resources allocated in \texttt{userprep}.
\item[{\texttt{defaultParm}}] The name of the default parameter affected by \emph{Set
pattern} statements (Section \ref{sec:org3e10854}). The
default parameter also controls rhythm.
\item[{\texttt{parmMap}}] A nested dictionary of parameters, their allowed
values, and the characters that will identify these values in
pattern strings.
\item[{\texttt{defaults}}] An \texttt{Event} or event pattern providing default values
for the events that the process will play.
\item[{\texttt{postDefaults}}] (optional) An event pattern that can do further
calculations on the parameter values.
\end{description}

\begin{boxnote}
\emph{Chucklib} documentation says to place the initialization function
into \texttt{prep}, and cleanup into \texttt{freeCleanup}. \texttt{PR(\textbackslash{}abstractLiveCode)}
uses these functions for its own initialization and cleanup, and calls
\texttt{userprep} and \texttt{userfree} from there. Do not override \texttt{prep} and
\texttt{freeCleanup}, or your process will not work properly.
\end{boxnote}

This dictionary is not limited to these items. You may add any other
data and functions that you need, to define complex behavior in terms
of simpler functions and patterns.

In Listing \ref{instance1}, \texttt{userprep} loads a buffer and
\texttt{userfree} releases it. By default, \emph{Set pattern} will operate on
\texttt{amp}, and \texttt{parmMap} defines three values for it (soft, medium and
loud). \texttt{parmMap} also provides some panning options. The \texttt{defaults}
dictionary specifies the SynthDef to use (it may provide other synth
defaults as well, not needed in this example), and \texttt{postDefaults}
calculates the sounding duration of each note based on rhythm.

Note the line \texttt{\textasciitilde{}defaults[\textbackslash{}bufnum] = \textasciitilde{}buf}: You may add values into
\texttt{defaults} as part of \texttt{userprep}. That's necessary in this case
because the buffer number is not known in advance. The only way to
supply the buffer number as a default is to read the buffer first,
and put it into the defaults dictionary only after that.

After loading the definition, Listing \ref{instance2}
demonstrates how rapidly a performer can instantiate and use multiple
copies of the prototype.

\begin{boxnote}
Clearly, the code in Listing \ref{instance1} is too long to
be practical to type in the middle of a performance. For practical
purposes, you should place all of the process definitions into a
separate file, which you would load once at the beginning of a
performance. See also the \emph{Make} statement (Section \ref{sec:orgd9a68ec}),
which makes it easy to instantiate the processes as needed during the
performance, reducing the overhead of initial loading. (In fact,
Chucklib was designed from the beginning to ``package'' complex musical
behaviors into objects that are simpler to use, once defined. \emph{cll} is
an even more compact layer of control on top of this, following the
same design principle: \emph{definition} and \emph{performance usage} are
different, and call for different types of code.)

Listing \ref{instance1} illustrates how to wrap the
\texttt{PR(\textbackslash{}abstractLiveCode).chuck(...)} statement into a Chucklib \emph{factory}
object. I strongly recommend following this model; it ``publishes'' your
process for use with \texttt{/make()} and avoids the need to manage large,
complex code blocks in performance.
\end{boxnote}

\subsection{Parameter map}
\label{sec:orge0671b4}
The parameter map \texttt{parmMap} is easiest to write as a set of nested Events:

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=parmMap1,caption={Template for the parameter map.},captionpos=b,numbers=none}
\begin{lstlisting}
parmMap: (
   parmName: (
      char: value,
      char: value,
      char: value...
   ),
   parmName: (...)
)
\end{lstlisting}

\texttt{parmName} keys should be Symbols. The keys of the inner dictionaries
should be characters (\texttt{Char}), because the elements of the pattern
strings that represent ``notes'' are characters.

The inner dictionaries may contain two other items, optionally:

\begin{description}
\item[{\texttt{isPitch}}] If \texttt{true}, enables pitch notation for this parameter (Section \ref{sec:orgeb1cbe8}).
\item[{\texttt{alias}}] An alternate name for this parameter, to use in the
pattern. For example, if the parameter should choose from a
number of SynthDefs, it would be inconvenient to type
\texttt{instrument} in the performance every time you need to control
it, whereas \texttt{def} would be faster. You can do this as follows:
\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label= ,caption= ,captionpos=b,numbers=none}
\begin{lstlisting}
     parmMap: (
        def: (
           alias: \instrument,
           $s: \sawtooth, $p: \pulse, $f: \fm
        )
     )

     // Then you can set the "instrument" pattern:
     /proc.phrase.def = "s";
\end{lstlisting}
Written this way, \texttt{def} in the \emph{Set pattern} statement will be
populate \texttt{instrument} in the resulting events.
\end{description}

\subsubsection{Array arguments in the parameter map}
\label{sec:org14e8265}
Array arguments are valid, and will be placed into resulting events as
given in the parameter map. In Listing \ref{parmMapArray1}, \texttt{freqs} will
receive the array \texttt{[200, 300, 400]} and process that array according
to the event prototype's rules.

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=parmMapArray1,caption={How to write arrays in the parameter map.},captionpos=b,numbers=none}
\begin{lstlisting}
parmMap: (
   freqs: (
      $2: [200, 300, 400],
   ),
   parmName: (...)
)
\end{lstlisting}

Envelopes may be passed to arrayed Synth controls in the same way:
\texttt{Env.perc(0.01, 0.5).asArray}.

\begin{boxnote}
The above is valid for the event prototype used by default in
\texttt{PR(\textbackslash{}abstractLiveCode)}. This is not SuperCollider's default event;
it's a custom event prototype defined in \emph{chucklib} that plays single
nodes and integrates more easily with \texttt{MixerChannel}. Because each
such event plays only one node, array arguments are passed as is. The
normal default event expands one-dimensional arrays into multiple
nodes. The way to avoid this is to wrap the array in another array
level.

\begin{center}
\begin{tabular}{|p{0.2\textwidth}|p{0.3\textwidth}|p{0.3\textwidth}|}
\hline
\textbf{parmMap array format} & \textbf{singleSynthPlayer meaning} & \textbf{Default event meaning}\\
\hline
\texttt{[1, 2, 3]} & Pass the array to one node & Distribute the three values to three nodes\\
\hline
\texttt{[[1, 2, 3]]} & Invalid & Pass the array to one node\\
\hline
\end{tabular}
\end{center}
\end{boxnote}

One other use of the parameter map array is used to set disparate
Event keys using one \emph{cll} parameter. \texttt{Pbind} allows multiple keys to
be set at once by providing an array for a key. \emph{cll} supports this by
using an array for the alias!

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=parmMapArray2,caption={Arrays for multiple-parameter setting using one cll parameter.},captionpos=b,numbers=none}
\begin{lstlisting}
parmMap: (
   filt: (
      alias: [\ffreq, \rq],
      $x: [2000, 0.05]
   )
)
\end{lstlisting}

\subsection{Event processing}
\label{sec:org7b90400}
Every event produced by a \emph{cll} process goes through three stages:

\begin{enumerate}
\item Insert all the items from \texttt{defaults}.
\item Insert the values from the current phrase (defined by pattern strings).
\item Insert any values from \texttt{postDefaults}. This may be a \texttt{Pbind}, and
it has access to all the values from 1 and 2 by \texttt{Pkey}.
\end{enumerate}

Thus, you can use \texttt{postDefaults} to derive values from items defined
in the parameter map, or to check for invalid values.

\subsection{Phrase sequence}
\label{sec:org7c7c961}

\emph{cll} ``Set pattern'' statements put musical information into any number
of phrases. When you play the process, it chooses the phrases one by
one using a pattern stored as \texttt{phraseSeq}. ``Set pattern'' has a compact
way to express phrase sequences, allowing sequences, random selection
(with or without weights) and wildcard matching. See Phrase selection
for details (Section \ref{sec:orgaff87a2}).

This design supports musical contrast. The performer can create
divergent materials under different phrase identifiers. Then, during
the performance, she can change the phrase-selection pattern to switch
materials on the fly. Sudden textural changes require changing many
phrase-selection pattern at once. \sout{For this, Register commands can save sequences of statements to reuse quickly and easily.}

\section{Livecoding statement reference}
\label{sec:orgbd07b47}
\subsection{Statement types}
\label{sec:org48932dd}
\begin{t}[tb!]
\caption{\label{cllStatements}List of available chucklib-livecode statements.}
\centering
\begin{tabular}{|l|p{0.35\textwidth}|p{0.35\textwidth}|}
\hline
\textbf{Type} & \textbf{Function} & \textbf{Syntax outline}\\
\hline
Set pattern & Add new musical information into a process & \texttt{/proc.phrase.parm = "data"}\\
\hline
Start/stop & Start or stop one or more procesess & \texttt{/proc/proc/proc+} or \texttt{-}\\
\hline
Randomizer & Create several randomized patterns at once & \texttt{/proc.phrase.parm *n +ki "base"}\\
\hline
Make & Instantiate a process or voicer & \texttt{/make(factory/factory)}\\
\hline
Passthrough & Pass a method call to a \texttt{BP} & \texttt{/proc(method and arguments)}\\
\hline
Chuck & Pass a chuck \texttt{=>} operation to a BP & \texttt{/proc => target }\\
\hline
Func call & Call a function in chucklib's \texttt{Func} collection & \texttt{/funcname.(arguments)}\\
\hline
Copy & Copy a phrase or phrase set into a different name & \texttt{/proc.phrase*n -> new}\\
\hline
Transfer & Like ``Copy,'' but also uses the new phrase for play & \texttt{/proc.phrase*n ->> new}\\
\hline
Show pattern & Copies a phrase pattern's string into the document, for editing & \texttt{/proc.phrase.parm}\\
\hline
\end{tabular}
\end{t}

\emph{cll} supports the statements shown in Table \ref{cllStatements}, listed in
order of importance.

\emph{cll} statements begin with a slash: \texttt{/}. Statements may be separated
by semicolons and submitted as a batch.

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=cllStmt1,caption={Cll statements, one by one or as a batch.},captionpos=b,numbers=none}
\begin{lstlisting}
// run one at a time
/kick.fotf = "----";
/snare.bt24 = " - -";

// or as a batch
/kick.fotf = "----"; /snare.bt24 = " - -";
\end{lstlisting}

\subsection{Set pattern statement}
\label{sec:org3e10854}
\emph{Set pattern} is the primary interface for composing or improvising
musical materials. As such, it's the most complicated of all the
commands.

This statement type subdivides into two functions: phrase \emph{definition}
and phrase \emph{selection}.

\subsubsection{Phrase definition}
\label{sec:org1e11353}
Most ``Set pattern'' statements follow this format:

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=setpatternSyntax,caption={Syntax template for the Set pattern statement.},captionpos=b,numbers=none}
\begin{lstlisting}
/proc.phrase.parm = quant"string";
\end{lstlisting}

Syntax elements:

\begin{description}
\item[{\texttt{proc}}] The BP's name.
\item[{\texttt{phrase}}] (optional) The phrase name. If not given, \texttt{main} is assumed.
\item[{\texttt{parm}}] (optional) The parameter name. The BP must define a
default parameter name, to use if this is omitted.
\item[{\texttt{quant}}] (optional) Determines the phrase's length, in beats.
\begin{itemize}
\item A number, or numeric math expression, specifies the number of beats.
\item \texttt{+} followed by a number indicates ``additive rhythm.'' The number
is taken as a base note value. All items in the string are assumed
to occupy this note value, making it easier to create
fractional-length phrases. (If only \texttt{+} is given, the BP may
specify \texttt{division}; otherwise 0.25 is the default.)
\item If \texttt{quant} is omitted entirely, the BP's \texttt{beatsPerBar} is
used. Usually this is the \texttt{beatsPerBar} of the BP's assigned
clock.
\end{itemize}
\item[{\texttt{string}}] Specifies parameter values and rhythms.
\end{description}

\begin{boxnote}
Both the phrase and parameter names are optional. That allows
the following syntactic combinations:

\begin{center}
\begin{tabular}{|l|l|}
\hline
\textbf{Syntax} & \textbf{Behavior}\\
\hline
\texttt{/proc = "string"} & Set phrase ``main,'' default parameter\\
\hline
\texttt{/proc.x = "string"} & Set phrase ``x,'' default parameter\\
\hline
\texttt{/proc.x.y = "string"} & Set phrase ``x,'' parameter ``y''\\
\hline
\texttt{/proc..y = "string"} & Set phrase ``main,'' parameter ``y''\\
\hline
\end{tabular}
\end{center}

Of these, the last looks somewhat surprising. It makes sense if you
think of the double-dot as a delimiter for an empty phrase name.
\end{boxnote}

\subsubsection{Pattern string syntax}
\label{sec:org122441e}
Pattern strings place values at time points within the bar. The values
come from the parameter map. Timing comes from the items' positions
within the string, based on the general idea of equal division of the
bar.

Two characters are reserved: a space is a timing placeholder, and
a vertical bar, \textbar, is a divider.

If the string has no dividers, then the items within it (including
placeholders) are equally spaced throughout the bar. This holds true
even if it's a nonstandard division: \#4 (Figure
\ref{rhythmNotation1}) has seven characters in the string, producing
a septuplet.

If there are dividers, the measure's duration will be divided first:
\(n\) dividers produce \(n+1\) units. Then, within each division, items
will be equally spaced. The spacing is independent for each
division. For example, in \#6 below, the first division contains one
item, but the second contains two. For all the divisions to have the
same duration, then, \texttt{-} in the second division should be half as long
as in the first.

\begin{figure}[htbp]
\centering
\includegraphics[width=.9\linewidth]{./manual-supporting/rhythmic-notation-crop.pdf}
\caption{\label{rhythmNotation1}Some examples of cll rhythmic notation, with and without dividers.}
\end{figure}

\begin{boxnote}
It isn't exactly right to think of a space as a ``rest.''
\texttt{"- - "} is not really two quarter notes separated by
quarter rests; it's actually two half notes! If you need to silence
notes explicitly, then you should define an item in the parameter map
whose value is a \texttt{Rest} object.
\end{boxnote}

\subsubsection{Timing of multiple parameters}
\label{sec:org2ad4615}
Each parameter can have its own timing, but a \texttt{Pbind} can play with
only one rhythm, raising a potential conflict.

The \texttt{Pbind} rhythm is determined by the pattern string for the
\texttt{defaultParm} declared in the process. When you set the \texttt{defaultParm},
the rhythm defined in that string is assigned to the \texttt{\textbackslash{}dur} key, where
it drives the process's timing. Other parameters encode timing into a
\texttt{Pstep}, to preserve the values' positions within the bar. Think of
these as ``sample-and-hold'' values, where the control value \emph{changes}
at times given by its own rhythm, but is \emph{sampled} only at the times
given by the \texttt{defaultParm} rhythm.

For example, here, the default parameter's rhythm is two half
notes. At the same time, a filter parameter changes on beats 1, 2
and 4. The process will play two events, on beats 1 and 3. On beat 1,
the filter will use its \texttt{a} value; on beat 3, it will use the most
recent value, which is \texttt{b}. \emph{The filter will not change on beat 2},
because there is no event occurring on that beat!

What about \texttt{c}? There is no event coming on or after beat 4, so \texttt{c}
will be ignored in this case. But, if you add another note late in the
bar, then it will pick up \texttt{c}, without any other change needed.

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=setPatMulti1,caption={Multiple parameters with different timing.},captionpos=b,numbers=none}
\begin{lstlisting}
/x = "--";
/x.filt = "ab c";  // "c" is not heard

/x = "-|-  -";  // now "c" is heard on beat 4.5
\end{lstlisting}

\subsubsection{Pitch notation}
\label{sec:orgeb1cbe8}
\begin{figure}
\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=bassMelBP,caption={A retro acid-house bassline, demonstrating pitch notation.},captionpos=b,numbers=none}
\begin{lstlisting}
// Initialization code
(
SynthDef(\sqrbass, { |out, freq = 110, gate = 1,
   freqMul = 1.006, amp = 0.1,
   filtMul = 3, filtDecay = 0.12, ffreq = 2000, rq = 0.1,
   lagTime = 0.1|
   var sig = Mix(
      Pulse.ar(Lag.kr(freq, lagTime) * [1, freqMul], 0.5)
   ) * amp,
   filtEg = EnvGen.kr(
      Env([filtMul, filtMul, 1], [0.005, filtDecay], \exp),
      gate
   ),
   ampEg = EnvGen.kr(Env.adsr(0.01, 0.08, 0.5, 0.1),
      gate, doneAction: 2);
   sig = RLPF.ar(sig, (ffreq * filtEg).clip(20, 20000), rq);
   Out.ar(out, (sig * ampEg).dup);
}).add;

(
keys: #[master],  // ~master comes from \loadAllCl.eval
defaultName: \sqrbs,
initLevel: -12.dbamp,
argPairs: #[amp, 0.5],
make: { |name|
   var out;
   ~target = MixerChannel(name, s, 2, 2, ~initLevel, outbus: ~master);
   out = Voicer(5, \sqrbass, target: ~target);
   out.mapGlobal(\ffreq, nil, 300, \freq);
   out.mapGlobal(\rq, nil, 0.2, \myrq);
   out.mapGlobal(\filtMul, nil, 8, [1, 12]);
   out
},
free: { ~target.free },
type: \vc) => Fact(\sqrbsVC);
)

// Performance code:
\loadAllCl.eval;
TempoClock.tempo = 132/60;
Mode(\fsloc) => Mode(\default);

/make(sqrbsVC/melBP:bs(octave:3));
/bs = "1_  1.|5~3_9.4.|7.2~4_5'.|5_8~2_4.";
/bs+;

/bs-;
\end{lstlisting}
\end{figure}

If a parameter's map specifies \texttt{isPitch: true}, then it does not need
to specify any other values and the rules described in Section \ref{sec:org882e943} apply.


\begin{boxnote}
Items in pitch sequences may include more than one character: \texttt{3} is
one note, as is \texttt{6+,\textasciitilde{}}. They are converted into \texttt{SequenceNote}
objects in the pattern, because \texttt{SequenceNotes} can encode pitch and
articulation information. Post-processing in \texttt{PR(\textbackslash{}abstractLiveCode)}
extracts the articulation value and assigns it to \texttt{\textbackslash{}legato} (or
\texttt{\textbackslash{}sustain} for staccato notes).
\end{boxnote}

To use pitched notes, I strongly recommend installing the
\emph{ddwLivecodeInstruments} quark, and using the \texttt{melBP} process (or the
other pitched processes described in the tutorial), as demonstrated in
Listing \ref{bassMelBP}. The general procedure is:

\begin{itemize}
\item In your initialization script, package your instrument as a Voicer
factory, following the template shown. Note the following keys in
the factory's dictionary:
\begin{itemize}
\item \texttt{keys}: Import items from the top environment. In particular,
\texttt{\textbackslash{}loadAllCl.eval} creates mixer channels \texttt{\textasciitilde{}master}, \texttt{\textasciitilde{}rvbmc} and
\texttt{\textasciitilde{}shortrvbmc}. You can use these when creating the Voicer's
\texttt{\textasciitilde{}target} mixer.
\item \texttt{defaultName}: The name of the \texttt{VC} object that \texttt{/make()} will
create.
\item \texttt{initLevel}, \texttt{initRvb}: Not strictly necessary, but
\emph{ddwLivecodeInstruments} uses these as a convention to set the
levels of the mixer channel and reverb post-send.
\item \texttt{argPairs}: Parameters and defaults specific to this instrument,
to inject into the note player when using the instrument. One
convention in \emph{ddwLivecodeInstruments} is a default amplitude of
0.5, overriding the default event prototype's 0.1.
\end{itemize}
\item In performance, \texttt{/make} the instrument and a \texttt{melBP} process together.
\item Specify the key: \texttt{Mode(\textbackslash{}keyname) => Mode(\textbackslash{}default)}. The ``legacy
example'' below uses F-sharp Locrian, hence \texttt{Mode(\textbackslash{}fsloc)}. (This is
a global setting; you do not need to repeat this step for every
process.)
\end{itemize}

The particular benefit of a Voicer + \texttt{melBP} is that slurred notes
will tie across the bar line correctly. (\emph{cll} needs to evaluate
processes on every bar line, whether a note sounds at that time or
not. If a pitched note ties over the bar line, the last note in the
bar does not know when the next note in the bar will occur. This is
extremely difficult to handle using the default event
prototype. \emph{ddwLivecodeInstruments} pitched processes use a custom
event prototype, with features of Voicer, to make it transparent to
the user.)

\begin{figure}
\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=pitchSet1,caption={Pitch notation in PR(\textbackslash abstractLiveCode); not generally recommended.},captionpos=b,numbers=none}
\begin{lstlisting}
// Use the same SynthDef as in the previous example

BP(\acid).free;
PR(\abstractLiveCode).chuck(BP(\acid), nil, (
   event: (eventKey: \default),
   alwaysReset: true,
   defaultParm: \degree,
   parmMap: (
      degree: (isPitch: true),
   ),
   defaults: (
      ffreq: 300, filtMul: 8, rq: 0.2,
      octave: 3, root: 6, scale: Scale.locrian.semitones
   ),
   postDefaults: PmonoArtic(\sqrbass,
      \dummy, 1
   )
));

TempoClock.tempo = 132/60;
)

/acid = "1_  1.|5~3_9.4.|7.2~4_5'.|5_8~2_4.";

/acid+;
/acid-;
\end{lstlisting}
\end{figure}

If you must use only the basic features of \emph{cll} (\texttt{\textbackslash{}loadCl.eval}), you
can use \texttt{PR(\textbackslash{}abstractLiveCode)} and place a dummy \texttt{PmonoArtic} into
\texttt{postDefaults}, as in Listing \ref{pitchSet1}.\footnote{Note the trick to get monophonic synthesis. Assigning a
\texttt{PmonoArtic} into \texttt{postDefaults} effectively turns the entire
event-producing chain into a \texttt{PmonoArtic}---even if it adds no
musically useful information into the resulting events. \emph{Caveat}: If
you will have any notes slur across the barline, make sure to include
\texttt{alwaysReset: true} in the BP parameter dictionary.} If you do it
this way, you lose support for accents, and notes will not
automatically tie across the bar line. You can work around this by
explicitly repeating the note in the next bar. This is very difficult
to do with generators, however.\footnote{I present the \texttt{PmonoArtic} example only to
demonstrate that it is possible. This way, however, is not as powerful
as \texttt{melBP}, so I maintain the recommendation to use \texttt{melBP} instead.}

\subsubsection{Phrase selection}
\label{sec:orgaff87a2}
Statements to set the phrase sequence follow a different syntax:

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=phraseSel1,caption={Syntax template for ``Set pattern'' phrase selection.},captionpos=b,numbers=none}
\begin{lstlisting}
/proc = (group...);
\end{lstlisting}

\texttt{group} can consist of any of the following elements:

\begin{description}
\item[{Phrase ID}] The name of any phrase that's already defined, or a
regular expression in single quote marks. If more than one
existing phrase matches the regular expression, one of the
matches will be chosen at random; e.g., to choose randomly among
phrases beginning with \texttt{x}, write \texttt{'\textasciicircum{}x'}.
\item[{Name sequence}] Two or more of \emph{any} of these items, separated by
dots and enclosed in parentheses: \texttt{(a0.a1.a2)}. These will be
enclosed in \texttt{Pseq}.
\item[{Random selection}] Two or more of any of these items, separated by
vertical bars (\textbar) and enclosed in parentheses:
\texttt{(a0|a1|a2)}. These will be enclosed in \texttt{Prand}. \emph{One} will be
chosen before advancing to the next ID.
\item[{Phrase group}] A name, followed by two asterisks and a number of
bars in the phrase group. If a four-bar phrase is stored as \texttt{a0},
\texttt{a1}, \texttt{a2}, and \texttt{a3}, you can write it simply as \texttt{a**4}. The
preprocessor will expand this to regular expression matches, as
if you had written \texttt{('\textasciicircum{}a0'.'\textasciicircum{}a1'.'\textasciicircum{}a2'.'\textasciicircum{}a3')}. The use of
regular expression matching here is to make it easier to have
slight variations on the bars within the phrase group, while
keeping the same musical shape.
\end{description}

Any of these items may optionally attach a number of repeats \texttt{*n}:
\texttt{(a*3.b)} translates to \texttt{Pseq([Pn(\textbackslash{}a, 3), \textbackslash{}b], inf)}, and \texttt{(a*3|b)} to
\texttt{Prand([Pn(\textbackslash{}a, 3), \textbackslash{}b], inf)}.

Items in a random selection may also attach a weight \texttt{\%w}, which must
be given as an integer: \texttt{(a\%6|b\%4)} has a 60\% chance of choosing \texttt{a}
and a 40\% chance of \texttt{b}. If no weight is given, the default
is 1. Weights are ignored for sequences (separated by dots).

Groups may be nested, producing complex structures compactly. For
example, to have an 80\% chance of \texttt{a} for four bars, then an 80\%
chance of \texttt{b} for two bars, you would write:

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=phraseSel1,caption={Nested phrase-selection groups.},captionpos=b,numbers=none}
\begin{lstlisting}
((a%4|b)*4.(a|b%4)*2)
\end{lstlisting}

You may also include both \texttt{.} and \texttt{|} in a single set of
parentheses. The dot (for sequence) takes precedence: \texttt{(a.b|c)}
evaluates as \texttt{((a.b)|c)}.

\subsection{Start/stop statement}
\label{sec:orgbf11e86}
The start/stop statement takes the following form:

\begin{itemize}
\item Start: \texttt{/proc1/proc2/proc3+quant}
\item Stop: \texttt{/proc1/proc2/proc3-quant}
\end{itemize}

Any number of process names may be given, each with a leading slash.

\texttt{quant}, an integer, tells each process to start or stop on the next
multiple number of beats. In 4/4 time, \texttt{/proc+4} will start the
process on the next bar line; \texttt{/proc+8} will start on the next
event-numbered bar line (i.e., every other bar). \texttt{quant} is optional;
if not given, each process will use its own internal \texttt{quant}
setting. By default, this is one bar; however, the \texttt{setm}
helper function overrides this for the given number of bars.

\subsection{Make statement}
\label{sec:orgd9a68ec}
The make statement instantiates one or more \emph{chucklib} factories.

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=clMake1,caption={Syntax template for make statements.},captionpos=b,numbers=none}
\begin{lstlisting}
/make(factory0:targetName0(parameters0)/factory1:targetName1(parameters1)/...);

// Or, with autoGui
/make*(factory0:targetName0(parameters0)/factory1:targetName1(parameters1)/...);
\end{lstlisting}

\begin{description}
\item[{\texttt{factory}}] The name of a \texttt{Fact} object to create.
\item[{\texttt{targetName}}] (optional) The name under which to create the
instance. If not given, the make statement looks into the factory
for the \texttt{defaultName}. If not found, the factory's name will be
used.
\item[{\texttt{parameters}}] (optional) A dictionary of \texttt{key: value} pairs to
insert into the Factory prior to making the resulting object, to
override defaults. NOTE: It is up to the Factory to pass values
into the final object. \texttt{Fact()} does not scan for unknown keys
and automatically forward them.
\end{description}

Multiple \texttt{factory:targetName} pairs may be given, separated by
slashes. Both \texttt{BP} and \texttt{VC} factories are supported.

As noted earlier, the code to define \emph{cll} processes is not
performance-friendly. Instead, you can write this code into \texttt{Fact}
object, and then \texttt{/make} them as you need them in performance.

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=make1,caption={Example of the make statement.},captionpos=b,numbers=none}
\begin{lstlisting}
(
// THIS PART IN THE INIT FILE
(
defaultName: \demo,
octave: 5,  // a default octave
make: { |name|
	PR(\abstractLiveCode).chuck(BP(name), nil, (
		event: (eventKey: \default),
		defaultParm: \degree,
		parmMap: (degree: (isPitch: true)),
		// Here, the Factory transmits ~octave
		defaults: (octave: ~octave)
	));
}, type: \bp) => Fact(\demoBP);
)

// DO THIS IN PERFORMANCE
/make(demoBP:dm(octave:6));  // :dm overrides defaultName

/dm = "1353427,5,";
/dm+;
/dm-;

/dm(free);
\end{lstlisting}

\texttt{/make*} instead of \texttt{/make} will try to chuck process or voicer mixers
into chucklib \texttt{MCG} objects, for display in a mixing board, and
voicers into empty chucklib \texttt{VP} objects, for speed in setting up
players during performance. \texttt{MCG} and \texttt{VP} arrays are created by
\texttt{BP.loadGui}.

\textbf{Parameters:} \emph{ddwChucklib} has two ways to write a ``chuck'' operation:

\begin{itemize}
\item Simplified: \texttt{source =>.adverb target}, or
\item Complete: \texttt{source.chuck(target, adverb, parameters)} (\texttt{parameters}
is a dictionary, usually written in Event-style syntax).
\end{itemize}

Different object types may handle the parameters differently. The
\emph{cll} \texttt{/make} statement supports \texttt{Fact()} as a source, which imports
the parameters into the factory's environment before making the
result. The parameters are available to the factory, which may choose
to insert them into the resulting object in whatever way is
needed. Because Event-style syntax already encloses the names and
values in parentheses, the \texttt{/make} statement simply reads the
dictionary directly in the argument list.

\textbf{Voicers and BPs:} If a single \texttt{/make} statement produces first a
Voicer and then a BP, \texttt{/make} will additionally assign the Voicer to
play the BP's notes, saving the time in performance of writing an
additional \texttt{VC(\textbackslash{}name) => BP(\textbackslash{}name)} command.

\subsection{Passthrough statement}
\label{sec:org4003743}
The passthrough statement takes arbitrary SuperCollider code, enclosed
in parentheses, and applies it to any existing \emph{chucklib} object. If
no class is specified, \texttt{BP} is assumed. No syntax checking is done in
the preprocessor, apart from counting parentheses to know which one
really ends the statement.

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=clPass1,caption={Syntax template for passthrough statements.},captionpos=b,numbers=none}
\begin{lstlisting}
// This...
/snr(clock = ~myTempoClock);

// ... is the same as running:
BP(\snr).clock = ~myTempoClock;

// Or...
/VC.bass(releaseAll);  // VC(\bass).releaseAll;
\end{lstlisting}

\subsection{Chuck statement}
\label{sec:orgdefda16}
The chuck statement is a shortcut for chucking any existing \emph{chucklib}
object into some other object. If no class is given, \texttt{BP} is assumed.

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=clChuck1,caption={Syntax template for Chuck statements.},captionpos=b,numbers=none}
\begin{lstlisting}
// This...
/snr => MCG(0);

// ... is the same as running:
BP(\snr) => MCG(0);

// Or...
/VC.keys => MCG(0);  // VC(\keys) => MCG(0);
\end{lstlisting}

\subsection{Func call statement}
\label{sec:orgcf7fe08}
The \texttt{Func} call statement is a shortcut to evaluate a function saved
in \emph{chucklib}'s \texttt{Func} collection. This makes it easier to use helper
functions. No syntax checking is done in the preprocessor.

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=clFunc1,caption={Syntax template for func-call statements.},captionpos=b,numbers=none}
\begin{lstlisting}
/func.(arguments);

// e.g.:
/bars.(\proc, 2, \a);
\end{lstlisting}

\begin{boxnote}
The dot after the function name is critical! Without it, the statement
looks exactly like a passthrough, and the preprocessor will treat it
as such.
\end{boxnote}

\subsection{Copy or transfer statement}
\label{sec:org8fd4285}
Copy/transfer statements create additional copies of phrases, so that
you can transform the material while keeping the old copy. Then you
can switch between the old and new versions, setting up a musical
form.

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=clCopy1,caption={Syntax template for copy/transfer statements.},captionpos=b,numbers=none}
\begin{lstlisting}
/proc.phrase*n -> newPhrase;  // copy

/proc.phrase*n ->> newPhrase;  // transfer
\end{lstlisting}

\begin{description}
\item[{\texttt{proc}}] The process on which to operate.
\item[{\texttt{phrase}}] The phrase name to copy.
\item[{\texttt{n}}] (optional) If given, copy a multi-bar phrase group, treating \texttt{phrase} as the prefix. \texttt{/proc.a*2 -> b} will copy \texttt{a0} to \texttt{b0} and \texttt{a1} to \texttt{b1}. (If \texttt{n} is omitted, both \texttt{phrase} and \texttt{newPhrase} will be used literally.)
\item[{\texttt{newPhrase}}] The name under which to store a copy. If \texttt{n} is given, this is a phrase group prefix.
\end{description}

The difference between ``copy'' and ``transfer'' is:

\begin{itemize}
\item Copy (\texttt{->}) simply duplicates the phrase information, but continues
playing the original phrases. If you change the new copies, you
won't hear the changes until you change the phrase selection
pattern. This is good for preparing new material and switching to it
suddenly.

\item Transfer (\texttt{->>}) duplicates the phrase information \emph{and} modifies
the phrase selection pattern, replacing every instance of the old
phrase name with the new.\footnote{It does this by producing a \texttt{compileString} from the
phrase selection pattern, performing string replacement, and then
recompiling the pattern. This should work with all \emph{cll} phrase
selection strings (Section \ref{sec:orgaff87a2}). It is not guaranteed
to work with hand-written patterns that generate phrase names
algorithmically.} Changing the new copies will now be heard
immediately. This is good for slowly evolving new material, while
keeping the option to switch back to an older (presumably simpler)
version later.
\end{itemize}

\subsection{Show pattern statement}
\label{sec:org38e5b66}
Less a ``statement'' than an interface convenience, this feature looks
up the string for a given phrase and parameter, and inserts it into
the code document. Invoke this behavior by typing \texttt{/proc.phrase.parm}
and evaluating the line by itself. As in other contexts, \texttt{phrase} and
\texttt{parm} are optional and default to \texttt{main} and the process's
\texttt{defaultParm} respectively. For a multi-bar phrase group, type
\texttt{/proc.phrase*n.parm} (where \texttt{n} is the number of bars in the group.)

This is useful after a copy/transfer statement.

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=clShow1,caption={Demonstration of ``Show pattern'' statements.},captionpos=b,numbers=none}
\begin{lstlisting}
/snr.a = " - -";

/snr.a -> b;

/snr.b   // now hit ctrl-return at the end of this line

// the line magically changes to
/snr.b = " - -";
\end{lstlisting}

\begin{boxnote}
You must be using SuperCollider IDE 3.7 or above. Automatic code
insertion is not supported for other editors or older IDE versions.
\end{boxnote}

\subsection{Helper functions}
\label{sec:org7aaa8a3}
A few ``helper functions'' are defined, to simplify common tasks:

\begin{itemize}
\item \texttt{/changeMeter.(beatsPerBar, clock, barBeat, newBaseBarBeat)}: Set
the meter. The last three arguments are optional. If the last three
are omitted, it will set \texttt{beatsPerBar} on the default \texttt{TempoClock},
on the next barline.

\item \texttt{/changeTempo.(tempo, clock, barBeat)}: Set the tempo (beats per
second). The last two arguments are optional (default \texttt{TempoClock},
and the next barline). This is mainly to simplify group performances
using the Utopia quark's \texttt{BeaconClock}.

\item \texttt{/changeKey.(\textbackslash{}modeName)}: Assign the named Mode object to
\texttt{Mode(\textbackslash{}default)}. All processes using the default mode will switch
to the new key immediately.

\item \texttt{/globalSwing.(array)}: Set an array defining swing subdivisions. To
swing 16th-notes, the array's values should add up to 0.5
(eighth-note), e.g. \texttt{[0.3, 0.2]}. (Individual processes may override
the global swing: \texttt{/name(swing = array)}.
\end{itemize}

Also, three \texttt{Func} definitions are provided to make it easier to work
with multi-bar phrase groups. I will introduce them using \emph{cll} Func
call statement syntax (Section \ref{sec:orgcf7fe08}).

\begin{description}
\item[{\texttt{/setupbars.(\textbackslash{}proc, n, \textbackslash{}prefix)}}] Create empty phrases for
\texttt{prefix0}, \texttt{prefix1} up to \(n-1\). This also inserts \emph{Set pattern}
(Section \ref{sec:org3e10854}) templates into the code
document, for you to start filling in musical material.
\item[{\texttt{/setm.(\textbackslash{}proc, n, \textbackslash{}prefix)}}] Set the process's phrase selection
pattern to play this phrase group. It also changes \texttt{quant} in the
process, so that starting and stopping the process will align to
the proper number of bars.
\item[{\texttt{/bars.(\textbackslash{}proc, n, \textbackslash{}prefix)}}] Calls both \texttt{setupbars} and \texttt{setm} at
once.
\end{description}

A typical sequence of performance instructions for me is:

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=helper1,caption={Common initialization sequence, using helper functions.},captionpos=b,numbers=none}
\begin{lstlisting}
/make(kick);
/bars.(\kick, 2, \a);

// the following lines are automatically inserted
/kick.a0 = "";
/kick.a1 = "";
\end{lstlisting}

After the templates appear, I edit the strings to produce the rhythms
I want, and then launch the process with \texttt{/kick+}. In this example,
the phrase group occupies two bars. \texttt{setm} automatically sets the
process's \texttt{quant} to two bars, so the process will then launch on an
even-numbered barline.

\subsection{(Deprecated) Randomizer statement}
\label{sec:org014de7e}
Previous versions included a ``randomizer'' statement. Generators are
far more powerful. The code remains for backward compatibility, but it
will be undocumented and not officially supported going forward.

\section{Generators}
\label{sec:orgc190d6d}
The basic syntax of the \emph{Set pattern} statement (Section
\ref{sec:org3e10854}) denotes fixed note
sequences, which always play exactly the same events. \emph{Generators}
create phrases whose contents can change on each iteration, adding
another dimension of musical interest.

\subsection{Generator design}
\label{sec:org0e8d949}
Generators manipulate lists of events, provided by a ``chain'' operator,
one bar at a time.

\begin{boxnote}
January 2020: Generator syntax has changed from previous
versions. Previously, the source event list was specified as the first
argument to a generator. Now, the chain operator provides all
generator source lists; the first argument is removed. Old scripts
will have to be rewritten.
\end{boxnote}

At present, generators divide into these main categories:

\begin{itemize}
\item \emph{Rhythm generators} insert new items into the event list, or delete
them. New items may be event characters directly, or wildcards to be
replaced by the second category.

\item \emph{Content generators} replace wildcards with user-specified values.

\item \emph{Filter generators} alter the flow of control.
\end{itemize}

These are not the only possible generator types, and there is no
prescribed sequence for using them. However, it's been most successful
so far to use a rhythm generator to embellish a base rhythm, and then
apply a content generator to ``fill in'' the new rhythmic elements.

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language=SuperCollider,label=gencycle,caption={Isorhythmic cycles with generators.},captionpos=b,numbers=none}
\begin{lstlisting}
(
BP(\y).free;
PR(\abstractLiveCode).chuck(BP(\y), nil, (
	event: (eventKey: \default),
	defaultParm: \degree,
	parmMap: (degree: (isPitch: true))
));
)

TempoClock.tempo = 140/60;

/y = "12 4| 5 6| 12 |45";  // A

/y+;

/y = "[** *| * *| ** |**]::\seq("12456", "*")";  // B

/y = "[** *| * *| ** |**]::\seq("12456", "*")::\ins("*", 7, 0.25)";  // C

/y = "[** *| * *| ** |**]::\seq("12456", "*")::\ins("*", 7, 0.25)::\seq("6,214", "*")";  // D

/y-;
\end{lstlisting}

Listing \ref{gencycle} demonstrates one possibility. The initial idea is a
cycle of five pitches laid over nine notes within a bar. Without
generators, it's necessary to drop one pitch at the end of every bar
(A). But, using the \texttt{\textbackslash{}seq()} generator, we can specify the rhythm
using a \texttt{*} wildcard; \texttt{\textbackslash{}seq()} replaces each wildcard
with successive pitches. \texttt{\textbackslash{}seq} also remembers its state from one bar
to the next, so, in this example, the first bar will begin with \texttt{1}
and the second, with \texttt{6} (B).

To add the first generator, wrap the source string in square brackets
(indicating that it is a source), and ``chain'' (\texttt{::}) the generator
onto it. The \texttt{::} operator takes the previous result (here, the
source) and feeds it into the following generator.

Generators are ``composed'' by chaining further generators. \texttt{\textbackslash{}ins("*",
7, 0.25)} inserts seven wildcards at randomly chosen 1/4-beat
positions (C). (There are 16 per bar, and 9 are already occupied, so
this will fill all the empty rhythmic positions.)
\texttt{*} is not a valid pitch specifier, so these are
performed as rests. Chaining one more layer, another \texttt{\textbackslash{}seq()} (D),
overlays a new cycle, four notes this time. The result is a shifting
arpeggiation that should repeat every 20 bars---but written as a
single bar's pattern string.

\subsection{Generator usage}
\label{sec:org162a4cd}
\subsubsection{Generators and pattern strings}
\label{sec:orgcaafdd1}
\begin{figure}
\begin{center}
\begin{center}
\includegraphics[width=1.0\textwidth]{./manual-supporting/item-spans.pdf}
\end{center}
\end{center}
\caption{\label{itemSpans}Time spans of items in pattern strings.}
\end{figure}

Generators are invoked using the syntax \texttt{\textbackslash{}name(arguments)} within a
``set pattern'' string.

As noted earlier, every item in a pattern string occupies a span of
time within the bar, beginning at its metrical position and continuing
until the metrical position of the next item (or the end of the
bar). (Spaces in the pattern string are placeholders, not items.) In
Figure \ref{itemSpans}, example A, the first \texttt{-} begins on beat 2 and
extends until the next item, a \texttt{.} on beat 3.25, and so on until the
end of the bar. The pattern string puts nothing at the beginning of
the bar---remember, spaces and dividers are not items. During
generator processing, literally nothing is in this space. When it's
time to play the bar's contents, a rest event will be inserted, but
this does not affect playback.

A generator expression, from the opening backslash to the closing
parenthesis, counts as one item, whose span is determined in the same
way. The simplest case is Figure \ref{itemSpans}, example B, where a single
generator occupies the entire bar (there are no spaces or dividers
before it, and no items after it). In example C, the generator begins
on the second eighth-note, and its span is terminated by an \texttt{x} on
beat 4.

Metrical position is especially important for the insert \texttt{\textbackslash{}ins()}
generator. \texttt{\textbackslash{}ins()} chooses metrical positions randomly from a ``grid''
determined by the generator's starting position and the \texttt{quant}
argument (fourth in the list). In example B, \texttt{\textbackslash{}ins()} starts at the
beginning of the bar, and the grid is in half-beats
(eighth-notes). Example C's \texttt{\textbackslash{}ins()} grid is in quarter-notes, but
beginning off the beat---syncopation---and the generator ends at
beat 4. Beat 4.5 matches the ``syncopated quarter-note'' specification,
but it is outside the generator's bounds, so it is unavailable to this
\texttt{\textbackslash{}ins()} instance.

This poses a problem for chaining generators. You can \texttt{::} chain a
second generator only onto another generator, not normal items. But
the generator occupies beats 1.5--4 only; therefore, a chained
generator can apply only to this time span, not the entire
bar. \emph{Cll}'s solution is a filter generator, \texttt{\textbackslash{}fork()}, which
positions sub-generators within its own time span. In example D, the
same \texttt{\textbackslash{}ins()} generator occurs within a \texttt{\textbackslash{}fork()}. The \texttt{\textbackslash{}ins()} still
applies only to beats 1.5--4, but the \texttt{\textbackslash{}fork()} is the only item in
the bar and covers the entire span. If you chain additional generators
onto the \texttt{\textbackslash{}fork()}, they will likewise cover the entire bar.

Listing \ref{genRhythm} provides some playable examples. In Example 3, beat
2 contains four items: \texttt{6,}, \texttt{\textbackslash{}rand(...)}, space and
space. Thus beat 2 is subdivided into 16th-notes, and the generator
begins on the second of those.

\begin{figure}
\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=genRhythm,caption={Interaction between generator syntax and ``set pattern'' rhythmic notation.},captionpos=b,numbers=none}
\begin{lstlisting}
// 1. Chain starts on the downbeat and occupies the whole bar.
/y = "[1,]::\ins("*", 3, 0.5)::\rand("13467", "*")";

/y+;

// 2. Chain starts on beat 2
// Note that a generator source can appear
// anywhere within the bar!
/y = "1,|[6,]::\ins("*", 3, 0.5)::\rand("13467", "*")||";

// 3. Chain starts on the 2nd 16th-note of beat 2
// Here, '6,' occupies time and is not a generator source.
// So it is not bracketed.
/y = "1,|6,\ins("*", 3, 0.5)::\rand("13467", "*")  ||";

// 4. Chain starts on the 2nd 16th-note of beat 2
// and stop on the 'and' of 4
/y = "1,|6,\ins("*", 3, 0.5)::\rand("13467", "*")  || x";

/y-;
\end{lstlisting}
\end{figure}

\begin{boxnote}
\texttt{\textbackslash{}ins("new", num, quant)} inserts \emph{num} new items at possible time
points \emph{quant} beats apart. These time points are measured from the
beginning of the generator. In Listing \ref{genRhythm}, examples 3 and 4
offset the generator by one 16th-note---so \texttt{\textbackslash{}ins()} will syncopate by
a 16th.

Source strings will be compressed to fit into the available
duration. In example 2, from the source \texttt{[6,]} to the end of the bar
is 3 beats, so \texttt{[6,||7]} would be correct. \texttt{[6,|||7]} would divide
the 3 beats into 4 subdivisions.
\end{boxnote}

\subsubsection{Generator arguments}
\label{sec:org0bd6b67}
Every generator expression currently requires an argument list in
parentheses following the generator's name. (If a generator doesn't
require arguments, an empty pair of parentheses is currently still
required. I may remove this requirement later, but for now, it's not
optional.)

Arguments are separated by commas.

Simple arguments are as follows;

\begin{itemize}
\item A number, which may be written as follows:
\begin{itemize}
\item An integer (\texttt{12}) or floating-point number (\texttt{1.5}).
\item An integer range: \texttt{1..3}. Especially useful for arguments representing a number of notes to insert or process.
\item A fraction: \texttt{1/3}.
\item A tuplet: e.g., \texttt{3:4} means ``three notes in the space of a quarter note.''
\item A pass-through expression in curly braces: \texttt{\{rrand(1, 4) * 0.5\}} for 0.5, 1.0, 1.5, 2.0.
\end{itemize}

\begin{boxnote}
Currently, pass-through expressions in braces may not contain
backslashes.  If you need to refer to a symbol, use \texttt{'singlequote'}
symbol literal syntax.
\end{boxnote}

\item A Symbol, written in LISP style with an opening backtick: \texttt{`name}.
\end{itemize}

\emph{Pool} arguments provide collections of items. Currently, pools are used in two ways:

\begin{itemize}
\item A list of wildcards for matching. For instance, the source string
may include wildcards \texttt{*} and \texttt{@}. A wildcard string \texttt{"*"} means
that the generator will apply only to asterisks. (\texttt{"*@"} would match
both.)

\item A sequence of items with which to replace a wildcard (or, for rhythm
generators, to insert directly). This type of pool may be written as
an item string (where each item has equal probability of being
chosen, as in \texttt{Prand}) or as a subset of certain sequencing
generators:
\begin{itemize}
\item \texttt{\textbackslash{}seq()}
\item \texttt{\textbackslash{}ser()}
\item \texttt{\textbackslash{}rand()}
\item \texttt{\textbackslash{}wrand()}
\item \texttt{\textbackslash{}xrand()}
\item \texttt{\textbackslash{}shuf()}
\item See Listing \ref{genSequencers} for examples of complex sequences produced
by nested generators.
\item When used in a pool argument, a number of repeats may be specified
as follows: \texttt{\textbackslash{}seq*n(args)} where \texttt{n} is any of the numeric
expressions described above. For example, if you want to embed a
sequence of six notes, always starting from the beginning but
randomly embedding 3 to 6 steps, write \texttt{\textbackslash{}ins(\textbackslash{}ser*3..6("123456"),
    ...)} (where \texttt{\textbackslash{}ins()} or another one of the \ref{sec:org3314af5}
determines the rhythm).
\end{itemize}
\end{itemize}

Quotes for pool strings should \emph{not} be escaped with backslashes, even
though these quoted strings appear within quotes. The set pattern
parser reads the pattern string up to a closing quote that appears
\emph{outside} generator expressions.

\subsection{Wildcard matching}
\label{sec:orgc3b03dd}
Many generators include a \emph{wildcards} argument. If omitted, the
generator will apply to all items with its timespan. Otherwise, it
will operate only on items that were produced by that generator. For
example, if I want to choke off all open hi-hats after 0.25 beats, but
leave closed hi-hats alone, I can specify \texttt{"-"} for \emph{wildcards}.

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language=SuperCollider,label= ,caption= ,captionpos=b,numbers=none}
\begin{lstlisting}
TempoClock.tempo = 124/60;
/hh.(\synthhh);
/shh = "\ins("-", 2, 0.5)::\ins(".", 8, 0.5)::\choke(0.25, ".", "-")";
/shh+

/shh-
\end{lstlisting}

\subsection{Built-in generators}
\label{sec:orgb5dbcaa}
\subsubsection{Rhythm generators}
\label{sec:org3314af5}

\begin{description}
\item[{\texttt{\textbackslash{}ins("new items", numToAdd, quant)}}] Locates unoccupied
metric positions within the bar, every \emph{quant} beats apart
beginning with the generator's onset time, chooses \emph{numToAdd} of
them randomly, and inserts new items at those positions.

\item[{\texttt{\textbackslash{}shift("shiftable items", numToShift, quant)}}] Locates
\emph{numToShift} occurrences of the \emph{shiftable items} within the
source (they must already exist), and moves them forward or back
by \emph{quant} beats. A good way to get syncopation is to insert
items on a strong beat, and then shift them by a smaller
subdivision.

\item[{\texttt{\textbackslash{}rot(quant)}}] Add \emph{quant} to every item's onset time,
and wrap all the times into the generator's boundaries:
basically, a strict canon.
\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language=SuperCollider,label=rotExample,caption={Usage of \textbackslash rot() generator.},captionpos=b,numbers=none}
\begin{lstlisting}
// Reich, "Piano Phase"-ish

(
BP(\y).free;
PR(\abstractLiveCode).chuck(BP(\y), nil, (
   event: (eventKey: \default, pan: -0.6),
   defaultParm: \degree,
   parmMap: (degree: (isPitch: true))
));

BP(\z).free;
PR(\abstractLiveCode).chuck(BP(\z), nil, (
   event: (eventKey: \default, pan: 0.6),
   defaultParm: \degree,
   parmMap: (degree: (isPitch: true))
));
)

TempoClock.setMeterAtBeat(3, TempoClock.nextBar);
TempoClock.tempo = 112/60;

/y = "[*^*^*^*^*^*^]::\seq("268", "*")::\seq("37", "^")";

/z = "[*^*^*^*^*^*^]::\seq("268", "*")::\seq("37", "^")";

/y/z+;

/z = "[*^*^*^*^*^*^]::\seq("268", "*")::\seq("37", "^")::\rot(-0.25)";

/z = "[*^*^*^*^*^*^]::\seq("268", "*")::\seq("37", "^")::\rot(-0.5)";

/z = "[*^*^*^*^*^*^]::\seq("268", "*")::\seq("37", "^")::\rot(-0.75)";

/y/z-;
\end{lstlisting}

\item[{\texttt{\textbackslash{}delta("new items", quant, weights...)}}] Add items into the source
based on random selection of event deltas, as multiples of
\emph{quant}. If \emph{quant} is 0.25, then the first \emph{weight} is for 0.25,
the second for 0.5 and so on; \texttt{\textbackslash{}delta(, "*", 0.25, 3, 1, 2)}
would choose deltas according to \texttt{Pwrand(0.25 * [1, 2, 3], [3, 1,
     2].normalizeSum, inf)}. The next delta is added to the current
position to find the position for the next item, until reaching
the end of the timespan.

\item[{\texttt{\textbackslash{}pdelta("new items", quant, "deltapool")}}] Like \texttt{\textbackslash{}delta()},
except where \texttt{\textbackslash{}delta()} always uses \texttt{Pwrand} to produce the
durations, \texttt{\textbackslash{}pdelta()} allows you to sequence multiples of
\emph{quant}. A \texttt{1} in the deltapool string is 1 times quant; \texttt{2} is 2
times quant and so on. A standard hi-hat pattern that could then
be written \texttt{\textbackslash{}pdelta(\textbackslash{}seq("..-"), 0.25, \textbackslash{}seq("112"))}.

\item[{\texttt{\textbackslash{}rDelta("new items", maxDelta, factor, minNotes, maxNotes, distribution, parameters)}}] Like
\texttt{\textbackslash{}delta()}, but generates deltas from one of six random functions
(whereas \texttt{\textbackslash{}delta()} corresponds only to \texttt{Pwrand()}). It is, then,
non-metric.
\begin{itemize}
\item \texttt{"new items"}: A pool string supplying items to insert.
\item \texttt{maxDelta}: The largest duration allowed.
\item \texttt{factor}: Calculates the shortest duration = \texttt{maxDelta / factor}.
\item \texttt{minNotes}: Require a certain minimum number of notes.
\item \texttt{maxNotes}: Constrain to a certain maximum number of notes.
\item \texttt{distribution}: A symbol \texttt{`lin}, \texttt{`exp}, \texttt{`hp}, \texttt{`lp}, \texttt{`beta},
\texttt{`expb}. See the example.
\item \texttt{parameters}: Numbers supplied as additional arguments to the
delta pattern. Currently used only by \texttt{`beta} (supply \emph{alpha} and
\emph{beta}) and \texttt{`expb} (supply \emph{spread}).
\end{itemize}

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language=SuperCollider,label=rDeltaExample,caption={Usage of \textbackslash rDelta() generator.},captionpos=b,numbers=none}
\begin{lstlisting}
// equal distribution
// but more total time spent on longer notes
/y = "\rDelta("*", 1, 8, , , `lin)::\wrand("\xrand("12345")\xrand("3'4'5'6'")", 2, 1)";

/y+

// equal total time spent on longer notes vs shorter
/y = "\rDelta("*", 1, 8, , , `exp)::\wrand("\xrand("12345")\xrand("3'4'5'6'")", 2, 1)";

// Phprand
/y = "\rDelta("*", 1, 8, , , `hp)::\wrand("\xrand("12345")\xrand("3'4'5'6'")", 2, 1)";

// Plprand
/y = "\rDelta("*", 1, 8, , , `lp)::\wrand("\xrand("12345")\xrand("3'4'5'6'")", 2, 1)";

// beta distribution: similar problem as `lin
/y = "\rDelta("*", 1, 8, , , `beta, 0.2, 0.2)::\wrand("\xrand("12345")\xrand("3'4'5'6'")", 2, 1)";

// expb: "exponentialized" beta distribution
/y = "\rDelta("*", 1, 8, , , `expb, 0.2)::\wrand("\xrand("12345")\xrand("3'4'5'6'")", 2, 1)";

/y-
\end{lstlisting}

\item[{\texttt{\textbackslash{}ramp("new items", initDelta, midDelta, midpoint, curve)}}] Generates
accelerating and decelerating rhythms. To use this effectively,
think of the \texttt{\textbackslash{}ramp()} generator's time span as being normalized:
0 is the beginning of the span and 1 is the end. Within that
span, the generator will ramp from an initial duration to a
target, and back to the start duration.
\begin{itemize}
\item \texttt{"new items"}: A pool string supplying items to insert.
\item \texttt{initDelta}: The duration at the beginning of the time span.
\item \texttt{midDelta}: The target duration.
\item \texttt{midpoint}: Where, between 0 and 1, to arrive at \texttt{midDelta}. If 1,
\texttt{midDelta} is placed at the end, and the ramp will go from
\texttt{initDelta} to \texttt{midDelta} (the most common use case). If 0,
\texttt{midDelta} is at the beginning, and the ramp goes in the opposite
direction (so, you can choose randomly between acceleration and
deceleration by writing \texttt{\{2.rand\}} here). \texttt{0 < midpoint < 1}
creates a two-segment curve.
\item \texttt{curve}: Curvature types from \texttt{Env} are supported: numbers, or
\texttt{`lin}, \texttt{`exp} etc. A curvature number applies to the first
segment, and will be negated for the second.
\end{itemize}

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language=SuperCollider,label=rampExample,caption={Usage of \textbackslash ramp() generator.},captionpos=b,numbers=none}
\begin{lstlisting}
/y = "\ramp("*", 1, 0.2, 1, `exp)::\pitch("*", "2", 0, 0)";
/y+

// randomly choose accel or decel
/y = "\ramp("*", 1, 0.2, {2.rand}, `exp)::\pitch("*", "2", 0, 0)";

// alternate between accel and decel
/y = "\ramp("*", 1, 0.2, {Pseq([0, 1], inf)}, `exp)::\pitch("*", "2", 0, 0)";

/y = "\ramp("*", 1, 0.2, 0.5, `exp)::\pitch("*", "2", 0, 0)";

// pulls 1 -> 0.2 curve to the right, biasing long durations
/y = "\ramp("*", 1, 0.2, 0.5, 2)::\pitch("*", "2", 0, 0)";

// pulls 1 -> 0.2 curve to the left, biasing short durations
/y = "\ramp("*", 1, 0.2, 0.5, -2)::\pitch("*", "2", 0, 0)";

/y = "\ramp("*", 1, 0.2, 0.5, -4)::\pitch("*", "2", 0, 0)";

/y-
\end{lstlisting}

\item[{\texttt{\textbackslash{}choke(maxDur, "new items", "wildcards")}}] For every
item within the time span, insert an item \emph{maxDur} beats later
(unless the next item comes at that time point or
earlier). \texttt{\textbackslash{}choke("-||-.|", 1, ".")} will insert a \texttt{.} at beat 2,
because it is one beat later than the first item's position, and
there is no other item already ``choking off'' that note. Beat 4
does not receive an extra item, because the \texttt{-} on beat 3 is
already choked off a half beat later.

\item[{\texttt{\textbackslash{}stutt("new items", numToAdd, quant, prob, "insItem", "wildcards", "setWildcards")}}] Choose
up to \emph{numToAdd} matching items and stutter them according to
\emph{quant}. \emph{New items} determines the items to match (if omitted, it
matches any items, also taking \emph{wildcards} into account). At \emph{quant}
intervals, a new item is inserted if \texttt{prob.coin} is true. \emph{insItem}
specifies the item to insert; if omitted, it will insert a copy of
the existing item. \texttt{setWildcards} allows you to distinguish between
source items and stutt-inserted items in downstream processing.

\item[{\texttt{\textbackslash{}stuttDur("new items", numToAdd, quant, prob, addDur, "insItem", "wildcards", "setWildcards")}}] Like \texttt{\textbackslash{}stutt()}, except that \emph{addDur} is a maximum duration over
which to repeat/subdivide each item. This may produce jittery
patterns with empty space in between.

\item[{\texttt{\textbackslash{}stuttN(("new items", numToAdd, quant, prob, numInclusive, "insItem", "wildcards", "setWildcards")}}] Like \texttt{\textbackslash{}stutt()}, except that \emph{addDur} is a maximum number of new
items to add.

\item[{\texttt{\textbackslash{}stuttPitch("match items", numToAdd, quant, prob, numInclusive, "intervals", "articPool", wildcards, "setWildcards")}}] Like
\texttt{\textbackslash{}stuttN()}, except that new items are calculated from intervals,
similar to \texttt{\textbackslash{}pitch()}. The following expressions are equivalent:

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language=SuperCollider,label= ,caption= ,captionpos=b,numbers=none}
\begin{lstlisting}
  \ins("*", 1..2, 0.5)::\stuttN(, 1..2, 0.25, 1, 5, "@", "*")::\pitch("@", "6,7,23", -4, 4)
  
  \ins("*", 1..2, 0.5)::\stuttPitch(, 1..2, 0.25, 1, 5, "6,7,23", , "*", "@")
\end{lstlisting}

\item[{\texttt{\textbackslash{}div("new items", "replaceItems", numToAdd, quant, divisor, divisible)}}] Choose
up to \emph{numToAdd} matching items (taken from \emph{replaceItems}, which
must be at least \emph{quant} beats long, and divide their duration by
\emph{divisor}, inserting items from \emph{new items}. \emph{Divisible} can
further prevent short notes from being divided; if \emph{quant} is 0.5
and \emph{divisible} is 2.5, notes of duration 2.0 will not be
divided.

\item[{\texttt{\textbackslash{}euclid("new items", quant, increment, initial)}}] Euclidean
rhythm generator. Operating on a grid defined by \emph{quant},
\emph{increment} is the step size and \emph{initial} is the shift
amount. Both of these are numeric proxies, so you can randomize
them using range numbers or curly-brace-enclosed passthrough
expressions.

\item[{\texttt{\textbackslash{}golomb("new items", quant, minimum)}}] A Golomb ruler divides a
number into quantized steps, where each partition is unequal. The
total time to be partitioned comes from the generator's duration
and cannot be overridden. \emph{quant} is the rhythmic value to divide
into, and \emph{minimum} is the smallest integer number of \emph{quant}
steps that will be permitted. If \emph{quant} = 0.25 (16th-note), then
\emph{minimum} = 2 means that nothing shorter than an eighth note will
be produced. NOTE: If \emph{minimum} is too high, there may not be a
valid partition; in that case, it will fall back to the previous
successful minimum, or to 1.

\item[{\texttt{\textbackslash{}unis(`srcParm, "new items", srcBP)}}] Copy items, or rhythm, from
another process (``unison''). The other process should have
\texttt{leadTime > 0} to guarantee that it evaluates first (you can set
\texttt{leadTime} while a process is playing). \emph{SrcParm} is the
parameter name from the other process, as a symbol \texttt{`name};
\emph{srcBP} is the name of the other process. If you specify items in
\emph{new items}, they will replace the values from the other
process. For a fairly complex example, let's play block chords in
a pad, and then have an arpeggiator follow the top note's
rhythm. The first use of \texttt{\textbackslash{}unis()} here makes sure the
arpeggiator plays the highest note (\texttt{1}) at the same time the pad
moves to another chord. In \texttt{/arp..top}, the \texttt{\textbackslash{}unis()} follows the
top note's rhythm and pitch, and in \texttt{/arp..acc}, it adds an
accent to the top notes only.
\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language=SuperCollider,label=unisGen,caption={Using the unis() generator to coordinate two harmony processes.},captionpos=b,numbers=none}
\begin{lstlisting}
TempoClock.tempo = 124/60;
/make(anapadVC:pad/chordBP:ch(chords:\bigch));
/ch(leadTime = 0.01);
/ch = "\delta("*", 0.5, 0, 1, 2, 2)::\shuf("0976")";
/ch+

/make(pulseLeadVC:pl/arpegBP:arp(chords:\bigch));
/arp = "\unis(`note, "1", `ch)::\ins("*", 16, 0.25)::\seq("23456")::\artic(".")";
/arp..top = "\unis(`note, , `ch)";
/arp..acc = "\unis(`top, ">", `arp)::\choke(0.25, "-")";
/arp+

VC(\pad).v.gui; VC(\pl).v.gui;  // adjust filters
\end{lstlisting}

\item[{=\par(``rhythm'', ``replacer1'', ``replacer2''\ldots{})}] Produces multiple
parallel layers following the same rhythm template. For each
replacer, \texttt{"rhythm"} is evaluated once (to produce wildcards), and
then the replacer is evaluated to fill in that layer. Good for
minimalist textures, e.g.

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language=SuperCollider,label= ,caption= ,captionpos=b,numbers=none}
\begin{lstlisting}
  \par("\ins("*", 8..12, 0.25)", "\seq("785")", "\seq("237,")", "\seq("4,11,")")
\end{lstlisting}
\end{description}

\subsubsection{Wildcard-replacement generators}
\label{sec:org7061e27}
Note that \texttt{\textbackslash{}seq()}, \texttt{\textbackslash{}ser()}, \texttt{\textbackslash{}rand()}, \texttt{\textbackslash{}wrand()}, \texttt{\textbackslash{}xrand()}, and
\texttt{\textbackslash{}shuf()} are based on the corresponding SuperCollider patterns
\texttt{Pseq}, \texttt{Pser}, \texttt{Prand} etc., particularly for the number of repeats
(generally a number of single values to return, except for \texttt{\textbackslash{}seq()}).

\begin{description}
\item[{\texttt{\textbackslash{}seq("items", "wildcards", reset)}}] Replaces
\emph{wildcards} in the source with \emph{items}, one by one, preserving
order. \emph{Reset} is optional; if it's a number greater than 0, the
item sequence will reset on every bar.

\item[{\texttt{\textbackslash{}ser("items", "wildcards", reset)}}] Like \texttt{\textbackslash{}seq()}, but the number
of repeats determines how many notes will be output, not how many
repetitions of the entire phrase. When used for
wildcard-replacement, it is indistinguishable from \texttt{\textbackslash{}seq()}. Used
in a pool argument, however, compare the following (using \texttt{\textbackslash{}y}
defined in Listing \ref{gencycle}):
\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language=SuperCollider,label=serExample,caption={Usage of \textbackslash ser() generator.},captionpos=b,numbers=none}
\begin{lstlisting}
/y = "\ins("*", 8, 0.5)::\seq("\seq*2..4("1234")\seq("875")")";
/y+

/y = "\ins("*", 8, 0.5)::\seq("\ser*2..4("1234")\seq("875")")";

/y-
\end{lstlisting}

\item[{\texttt{\textbackslash{}rand("items", "wildcards")}}] Like \texttt{\textbackslash{}seq()}, but
chooses from \emph{items} randomly. (\emph{Reset} is not relevant, as there
is no order to preserve.)

\item[{\texttt{\textbackslash{}wrand("items", "wildcards", weight0, weight1, weight2...)}}] Weighted
random selection, like \texttt{Pwrand}. \emph{Weight0} is associated with the
first element of \emph{items}; \emph{weight1} with the second, and so
on. The generator automatically does \texttt{normalizeSum} on the
weights, so you don't have to worry about making them add up to
1.0. Do not enclose the weights in array brackets. (As in
\texttt{\textbackslash{}rand()}, \emph{reset} is irrelevant.)

\item[{\texttt{\textbackslash{}xrand("items", "wildcards", reset)}}] Reads the items
in random order without repeating the same item twice in a row,
like \texttt{Pxrand}.

\item[{\texttt{\textbackslash{}shuf("items", "wildcards", reset)}}] Shuffles the items into
random order, and returns each one before choosing a new order. If
embedded into a composite sequence with a finite number of repeats,
the shuffle-stream is maintained throughout. That is, in
\texttt{\textbackslash{}seq("1''\textbackslash{}shuf*3("12345")")}, all 5 items must be used exactly once
before repeating any, even though only 3 are streamed out at a
time. See \texttt{Pnshuf()} in the ddwPatterns quark.

\item[{\texttt{\textbackslash{}shufn("items", "wildcards", reset)}}] Shuffles \texttt{repeats} items
into random order. This is like \texttt{\textbackslash{}shuf()} except that, in a
composite sequence, every time the stream enters \texttt{\textbackslash{}shufn()}, the
order is chosen with no memory of past iterations.

\item[{\texttt{\textbackslash{}first("init items", "items", "wildcards", reset)}}] Like
\texttt{\textbackslash{}rand()}, but, when reset, it begins with a sequence of the ``init
items'': \texttt{Pseq([Pseq(init\_items, 1), Prand(items, inf)])}. Without
this, it can be difficult to start at a specific place at the
beginning of a bar. \textbf{IMPORTANT:} Per Section \ref{sec:org986a467},
if \texttt{\textbackslash{}first()} is embedded, then reset must be enabled in the generator
into which it's embedded. Currently there is no good way around this.
See Listing \ref{genReset}.

\item[{\texttt{\textbackslash{}pdefn(`pdefnKey, "wildcards")}}] Like \texttt{\textbackslash{}seq()},
but obtaining replacement items from a \texttt{Pdefn}. For non-pitched
parameters, the \texttt{Pdefn} should yield characters corresponding to
\texttt{parmMap} items. For pitched parameters, it should yield
e.g. \texttt{SequenceNote(degree, nil, length)} where \texttt{length} is 0.4
for staccato, 0.9 for legato (but rearticulating the next note)
and 1.01 for slurred.
\begin{itemize}
\item \texttt{Pdefn} streams are shared globally across all instances of this
generator \emph{for this process}. With care, you can create sequential
patterns spanning barlines.
\item The behavior of \texttt{reset > 0} is undefined.
\end{itemize}
\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language=SuperCollider,label=pdefnExample,caption={Usage of \textbackslash pdefn() generator.},captionpos=b,numbers=none}
\begin{lstlisting}
Pdefn(\y, Pn(Pseries(0, 1, 8), inf).collect { |d| SequenceNote(d, nil, 0.9) });

/y.a0 = "[*]::\ins("*", 2, 0.5)::\pdefn(`y, "*")";
/y.a1 = "\ins("*", 3, 0.5)::\pdefn(`y, "*")";
/y = (a**2);
\end{lstlisting}

\item[{\texttt{\textbackslash{}gdefn(`pdefnKey, "wildcards")}}] Like \texttt{\textbackslash{}pdefn()}, with
a difference: \texttt{\textbackslash{}pdefn()} keeps an independent repository of
streams for every BP, while \texttt{\textbackslash{}gdefn()} keeps a global repository
shared among all BPs. \emph{However}\ldots{} be careful; this does not work
the way you think. \emph{Cll} generates \emph{all} of the events for one
phrase at one time. In the following example, you might expect
values to alternate between \texttt{/x} and \texttt{/y}. Instead, four values
are assigned to \texttt{/x} first, and then four to \texttt{/y}, and these are
streamed out over the course of one bar.
\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language=SuperCollider,label=gdefnExample,caption={Usage of \textbackslash gdefn() generator.},captionpos=b,numbers=none}
\begin{lstlisting}
(
BP(\x).free;
PR(\abstractLiveCode).chuck(BP(\x), nil, (
   event: (play: { ~x.debug(~collIndex) }),
   defaultParm: \x,
   parmMap: (
      x: ($0: 0, $1: 1, $2: 2, $3: 3, $4: 4)
   ),
));

BP(\y).free;
PR(\abstractLiveCode).chuck(BP(\y), nil, (
   event: (play: { ~x.debug(~collIndex) }),
   defaultParm: \x,
   parmMap: (
      x: ($0: 0, $1: 1, $2: 2, $3: 3, $4: 4)
   ),
));

BP(\x).leadTime = 0.01;
Pdefn(\x, Pseq("01234", inf).trace(prefix: "pdefn: "));
)

/x = "[****]::\gdefn(`x, "*", 1)";
/y = "[****]::\gdefn(`x, "*", 1)";
/x/y+
/x/y-
\end{lstlisting}

\begin{center}
\begin{tabular}{|c|c|c|c|}
\hline
Expected x & Expected y & Actual x & Actual y\\
\hline
0 & 1 & 0 & 4\\
2 & 3 & 1 & 0\\
4 & 0 & 2 & 1\\
1 & 2 & 3 & 2\\
\hline
\end{tabular}
\end{center}

\item[{\texttt{\textbackslash{}prev("items", "wildcards", staccDur)}}] Replaces any
\emph{wildcards} with either: one of the \emph{items} (which is equivalent
to \texttt{\textbackslash{}rand()}; generally, you should leave \emph{items} empty), or the
previous item found in the bar. Useful for repeating notes. For
pitched parameters, if the repeated note's eventual duration
\texttt{<= staccDur}, its articulation will be made
staccato. NOTE: If a wildcard is the first item in the bar, then
there is no previous item. In this case, \texttt{\textbackslash{}prev()} will try to
determine the last item from the previous bar. If this fails, a
warning will be posted and the wildcard will become a rest
(silent).

\item[{\texttt{\textbackslash{}repeat1("items", "wildcards", reset, repeats)}}] Repeats every
value from the \texttt{"items"} stream. \texttt{\textbackslash{}repeat1(\textbackslash{}seq("1234"), "*", , 2)}
would output 1, 1, 2, 2, 3, 3, 4, 4 etc. the number of repeats may
be randomized.

\item[{\texttt{\textbackslash{}pitch("wildcards", "intervalPool", fallbackMin, fallbackMax, "articPool")}}] Valid
for pitched parameters only. Replaces \emph{wildcards} with ``Brownian
motion'' melody. Each wildcard will search backward for the
previous note. Then, one of the intervals will be chosen from
\emph{intervalPool} and added to the previous note. Intervals are
written relative to the scale root: \texttt{1} is unison (no movement),
\texttt{2} is up a second, \texttt{8} is up an octave, and
\texttt{6,} is a third down (e.g., in C major, \texttt{6} is
up a sixth = A, and \texttt{6,} lowers this by an
octave to be the A a third below the root). If there is no
previous note, a pitch will be chosen randomly between
\emph{fallbackMin} and \emph{fallbackMax} (given as integers, where 0 =
root). For each note, and articulation will be chosen randomly
from \emph{articPool}; if omitted, new notes will use the default
``unslurred, legato'' articulation.

\item[{\texttt{\textbackslash{}pitch2("wildcards", "intervalPool", fallbackMin, fallbackMax, "articPool", connect)}}] Like
\texttt{\textbackslash{}pitch()}, but it remembers the previous pitch \emph{that it
generated}, instead of looking back for every wildcard. This may
be used to produce multiple, interlocking lines. NOTE: This
generator resets every bar; unconstrained Brownian motion is
risky.

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language=SuperCollider,label=pitchExamples,caption={Usage of \textbackslash pitch() and \textbackslash pitch2() generators.},captionpos=b,numbers=none}
\begin{lstlisting}
TempoClock.tempo = 140/60;
Mode(\cphr) => Mode(\default);

/make(pulseLeadVC:pl/melBP:pl);

// Every "6,7," descending pattern starts at the previous given note
/pl = "[5'>| 3'>|4'>  2'>|]::\ins("*", 5..10, 0.25)::\pitch("*", "6,7,", 8, 10, ".")";
/pl+

// The first descent starts from "5'" and keeps going down through the bar
/pl = "[5'>| 3'>|4'>  2'>|]::\ins("*", 5..10, 0.25)::\pitch2("*", "6,7,", 8, 10, ".")";

// One \pitch() stream;
// another interlocking \pitch2() stream in a higher register
/pl = "[5'>| 3'>|4'>  2'>|]::\ins("*", 3..7, 0.25)::\ins("@", 3..8, 0.25)::\pitch("*", "6,7,", 8, 10, ".")::\pitch2("@", "6,7,23", 14, 18, ".", 0)";

/pl-
\end{lstlisting}

\item[{\texttt{\textbackslash{}walk("items", steps, "wildcards", offset, wrap)}}] A random
walk. \texttt{items} are taken in order (unlike other item pools). \texttt{steps}
should be either a number proxy, or a pitch-style string where \texttt{"2"}
steps forward by one, and \texttt{"7,"} steps backward one. \texttt{offset} is the
starting position in the pool string. If \texttt{wrap} is 0, the random
walk will reverse direction when it encounters a boundary; if
nonzero, it will wrap around to the other boundary in that
case. (\texttt{wrap} is reevaluated every time a boundary is crossed.) If
this pattern is embedded in a sequence with a finite number of
repeats, it will a/ remember its previous state and continue from
where it left off, and b/ re-evaluate \texttt{offset} each time.

\item[{\texttt{\textbackslash{}skip("sequence pattern", numToPlay, numToSkip, wildcards, reset)}}] From
the sequence pattern, alternately pass through \texttt{numToPlay} items,
then skip over \texttt{numToSkip} items. For example, a gapped scale
pattern could be written \texttt{\textbackslash{}skip("\textbackslash{}seq("12345678")", 2..5, 1..2)}.

\item[{\texttt{\textbackslash{}voss("weights", "wildcards")}}] 1/f noise, using a modified Voss
algorithm. The number of generators comes from the \texttt{weights} string,
which also controls the relative influence of each, where 1 or 2 is
a weight of 1, 3 is twice as powerful, 4 is 3 times as powerful,
etc. Standard Voss noise with eight generators would be
\texttt{\textbackslash{}voss("11111111")}.

\item[{\texttt{\textbackslash{}vossdiff("weights", "wildcards")}}] Generates a Voss noise
sequence, but returns the difference between pitches (the
intervals), suitable for use as a step stream in \texttt{\textbackslash{}pitch()}.

\item[{\texttt{\textbackslash{}replace("items", "wildcards")}}] Previously-filled items with a
prior wildcard (matching the wildcard list) are overwritten with new
values.

\item[{\texttt{\textbackslash{}rest("switch", "wildcards", "restItem")}}] For each wildcard
match, pull an item from the \texttt{switch} pool. If it is either \texttt{-} or
\texttt{.}, replace the wildcard with a rest; otherwise, leave the item
alone. This is meant to deactivate sounding events from an
already-populated stream.

\item[{\texttt{\textbackslash{}restn(numEvents, numRests, "wildcards", "restItem", reset)}}] Alternates
between preserving and suppressing notes---a nice way to introduce
space into a busy texture. In each cycle, first \texttt{numEvents} events
pass through unchanged; then \texttt{numRests} items are replaced with
rests. This should be done between inserting wildcards and filling
in their values.
\end{description}

Note also that \texttt{\textbackslash{}seq()}, \texttt{\textbackslash{}rand()}, \texttt{\textbackslash{}wrand()}, \texttt{\textbackslash{}xrand()}, \texttt{\textbackslash{}shuf()},
\texttt{\textbackslash{}first()} and \texttt{\textbackslash{}repeat1()} may be used in (or as!) pool strings
(Listing \ref{genSequencers}).

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language=SuperCollider,label=genSequencers,caption={Complex sequencing with sub-generators.},captionpos=b,numbers=none}
\begin{lstlisting}
(
BP(\y).free;
PR(\abstractLiveCode).chuck(BP(\y), nil, (
	event: (eventKey: \default),
	defaultParm: \degree,
	parmMap: (degree: (isPitch: true))
));
)

TempoClock.tempo = 140/60;

/y = "\ins("*", 8, 0.5)::\seq("123")";

/y+

// can repeat (like Prand)
/y = "\ins("*", 8, 0.5)::\rand("\seq("123")\seq("7854")\seq("26,")")";

// no repeats (like Pxrand)
/y = "\ins("*", 8, 0.5)::\xrand("\seq("123")\seq("7854")\seq("26,")")";

// 2-5random notes after 6,
// note here that articulation/transposition applies to sub-choices
/y = "\ins("*", 8, 0.5)::\xrand("\seq("123")\seq("7854")\seq("26,\xrand*2..5("34567")::\xpose("1'")::\artic(".")")")";

// also, articulations and transposition can be streamed this way
/y = "\ins("*", 8, 0.5)::\seq("123")::\artic(\seq("\seq*3("_")\seq*7(".")"))";

/y-
\end{lstlisting}

\subsubsection{Modifier generators}
\label{sec:org23ed310}

Modifiers may be part of the main generator chain, or included in
subsequences (Listing \ref{genSequencers}).

\begin{description}
\item[{\texttt{\textbackslash{}artic("articPool", "wildcards")}}] Replaces matching
notes' articulation with one of the items randomly chosen from
\emph{articPool}. If no \emph{wildcards} are given, all notes
match. Otherwise, only those notes with an association to one of
the given \emph{wildcards} will match.

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language=SuperCollider,label=articExample,caption={Usage of \textbackslash artic() generator.},captionpos=b,numbers=none}
\begin{lstlisting}
TempoClock.tempo = 140/60;
Mode(\cphr) => Mode(\default);
/make(pulseLeadVC:pl/melBP:pl);

// No wildcards, all notes match: All are staccato
/pl = "[1574]::\artic(".")";
/pl+

// Wildcard, but none of the notes came from a
// wildcard operation, so none of them match.
/pl = "[1574]::\artic(".", "*")";

// Notes were inserted by \seq operating on "*";
// all notes match.
/pl = "[****]::\seq("1574")::\artic(".", "*")";

// Two layers of notes with different articulations
/pl = "[****]::\seq("1574")::\ins("@", 4..8, 0.25)::\shuf("1'2'3'4'5'6'", "@")::\artic(">.", "*")::\artic("~", "@")";

/pl-
\end{lstlisting}

\item[{\texttt{\textbackslash{}articSplit("wildcards", dur1, "artic1", dur2, "artic2"... "defaultArtic")}}] Notes
of different durations will be given an articulation from the
matching articulation pool (instead of one global articulation
pool). Durations should be listed in ascending order. The note
duration matches if it is less than a written duration, so
\texttt{\textbackslash{}articSplit("*", 0.5, ".", "\_")} will assign staccato to anything
shorter than an eighth note, and normal articulation to eighth notes
or longer.

\item[{\texttt{\textbackslash{}xpose("intervalPool", "wildcards")}}] Transposition. For
each \emph{wildcard}-matching note, choose an interval from
\emph{intervalPool} and transpose the note accordingly.

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language=SuperCollider,label=xposeExample,caption={Usage of \textbackslash xpose() generator.},captionpos=b,numbers=none}
\begin{lstlisting}
TempoClock.tempo = 140/60;
Mode(\cphr) => Mode(\default);
/make(pulseLeadVC:pl/melBP:pl);

/pl = "\ins("*", 16, 0.25)::\seq("12345432")";
/pl+

// Easy octave displacement.
/pl = "\ins("*", 16, 0.25)::\seq("12345432")::\xpose("1111,1'1''")";
/pl-
\end{lstlisting}
\end{description}

\subsubsection{Filter generators}
\label{sec:org3279913}

\begin{description}
\item[{\texttt{\textbackslash{}fork("timed generators")}}] Applies different
generators to different segments of the bar. For instance, the
\emph{source} could insert \emph{n} wildcards throughout the bar, while
\emph{timed generators} could replace wildcards in the first half of
the bar with one value, and a different value in the second
half. Here, \emph{timed generators} includes two items, and \texttt{\textbackslash{}fork()}
occupies the entire bar. So both \texttt{\textbackslash{}seq()} instances get half a
bar. Source items in any portions of the bar not covered by one
of the \emph{timed generators} will pass through unchanged.
\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language=SuperCollider,label=forkExample,caption={Usage of \textbackslash fork() generator.},captionpos=b,numbers=none}
\begin{lstlisting}
/y = "\ins("*", 10, 0.25)::\fork("\seq("13", "*")\seq("14", "*")")";

/y = "\ins("1,", 10, 0.25)::\fork(" \seq("13", "1,")x\seq("14", "1,")")";
\end{lstlisting}

\item[{\texttt{\textbackslash{}chain(generator, generator...)}}] For internal use only.

\item[{\texttt{\textbackslash{}delete("wildcards", probability, negate)}}] Find existing items
produced by a given wildcard, and keep those items based on
probability. 0.75 probability means a 3/4 chance of keeping the
item; I felt that a higher probability should result in a more dense
texture. If the coin toss determines that the note should not be
kept, it is removed and its timepoint will be empty. A nonzero
\texttt{negate} value inverts the probability.

\item[{\texttt{\textbackslash{}wildcards("wildcards")}}] If an item had been produced by
wildcard replacement, ``undo'' this: replace the real value with
the original wildcard, so that a future wildcard replacement will
affect this item. This is especially useful when using \texttt{\textbackslash{}unis()}
to copy data from another process: you can overwrite the other
process's data, but keep the wildcards, and then substitute new
information in its place.
\end{description}

\subsection{Pool strings, pool streams}
\label{sec:org986a467}
January 2023 new feature!

Many generators include an argument for a ``pool'' of potential
values. A pool is written as a pattern string, from which values are
chosen randomly (like \texttt{Prand}). Section \ref{sec:org3314af5} in general
identifies pool arguments as \texttt{"new items"}, and Section
\ref{sec:org7061e27} as \texttt{"items"}.

Since 2020, a subset of wildcard-replacement generators (\texttt{\textbackslash{}seq()},
\texttt{\textbackslash{}ser()}, \texttt{\textbackslash{}rand()}, \texttt{\textbackslash{}wrand()}, \texttt{\textbackslash{}xrand()}, \texttt{\textbackslash{}shuf()}, \texttt{\textbackslash{}shufn()},
\texttt{\textbackslash{}first()}) can appear within pool strings. These are treated as
subpatterns in the SC pattern system: \linebreak
\texttt{\textbackslash{}rand("\textbackslash{}seq("123")\textbackslash{}seq("543")\textbackslash{}seq("678")")} will randomly choose
among the three phrases defined by the \texttt{\textbackslash{}seq()} members. See Listing
\ref{genSequencers}.

Except \texttt{\textbackslash{}wrand()}, these generators include a \texttt{reset} argument. If
this is > 0, the generator will reset to the beginning of its stream,
at the barline; if <= 0, it will continue from its last
position. (Note that \texttt{\textbackslash{}wrand()} doesn't need to reset, because the
random selections depend only on the weights, not on the previous
selection.)

The reset argument applies only when the generator is used as part of
a chain, fulfilling its original wildcard-replacement purpose. A
generator inside a pool string does not reset based on the reset
argument.

\begin{itemize}
\item \texttt{\textbackslash{}ins("*", 16, 0.25)::\textbackslash{}seq("12345", , 1)} \emph{does} reset on the bar
line.
\item \texttt{\textbackslash{}ins(\textbackslash{}seq("12345", , 1), 16, 0.25)} does \emph{not} reset.
\end{itemize}

This is because of SuperCollider's stream implementation. Patterns are
embedded into a stream, and a stream can reset only to the beginning
of the entire stream. There is no concept of resetting to a specific
pattern that is being embedded into the stream. ``Reset,'' then, belongs
properly to the generator that owns the pool stream, and is marked
with a \texttt{!} following the generator name.

\begin{itemize}
\item In \texttt{\textbackslash{}ins!(\textbackslash{}seq("12345"), 16, 0.25)}, the \texttt{!} tells \texttt{\textbackslash{}ins()} that its
pool should reset on the bar line.
\end{itemize}

\texttt{\textbackslash{}pdelta()} and \texttt{\textbackslash{}pitch()} are tricky cases because they have two pool
strings. In these cases, and only these cases, you may attach a \texttt{!}
reset flag to a generator inside the pool string itself. If a \texttt{!} is
present in one or both pool strings, it overrides the \texttt{\textbackslash{}pdelta()} or
\texttt{\textbackslash{}pitch()} generator's upper-level reset flag. This allows one or the
other to reset. Normally you will want both to reset; in that case, as
normal, add the reset flag to the parent generator.

\begin{center}
\begin{tabular}{|l|l|l|l}
 &  & Parent with ! & Parent without !\\
\hline
pool 1 with ! & pool 2 with ! & Both reset & Both reset\\
pool 1 with ! & pool 2 without ! & Only 1 resets & Only 1 resets\\
pool 1 without ! & pool 2 with ! & Only 2 resets & Only 2 resets\\
pool 1 without ! & pool 2 without ! & Both reset & Neither resets\\
\end{tabular}
\end{center}

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language=SuperCollider,label=genReset,caption={Behavior of pool-string reset flags.},captionpos=b,numbers=none}
\begin{lstlisting}
TempoClock.default.tempo = 2;

/make(pulseLeadVC:pl/melBP:pl);

// no reset: hear groups of 5 shifting off the barline
/pl = "\ins("*", 16, 0.25)::\seq("1>~2~3~4~5")";

// reset: extra C at end of bar
/pl = "\ins("*", 16, 0.25)::\seq("1>~2~3~4~5", , 1)";

// pool string generator without reset
/pl = "\ins(\seq("1>~2~3~4~5", , 1), 16, 0.25)";

// pool string generator with reset -- note usage on \ins!
/pl = "\ins!(\seq("1>~2~3~4~5"), 16, 0.25)";

// why can you not attach ! to the inner generator?
// here: should it always reset, or depending on which pattern is active?
// so we just disallow it. \ins() can reset its pool.
/pl = "\ins("\seq!("1>~2~3~4~5")\seq("9>~8~7~6~")", 16, 0.25)";

/pl = "\ins!("\seq("1>~2~3~4~5")\seq("9>~8~7~6~")", 16, 0.25)";

// double-pool generator
// intervals and artic don't reset (barline accent)
// note that \first() requires ! at the top-level generator
/pl = "\ins!(\first("@", "*"), 16, 0.25)::\seq("1>~", "@")::\pitch("*", \first("5'", "7,"), 0, 0, \first(">~", "~"))";

// normal reset: both intervals and artic reset (easy way, specify \pitch!)
/pl = "\ins!(\first("@", "*"), 16, 0.25)::\seq("1>~", "@")::\pitch!("*", \first("5'", "7,"), 0, 0, \first(">~", "~"))";

// intervals reset, artic doesn't (slur up after first bar)
/pl = "\ins!(\first("@", "*"), 16, 0.25)::\seq("1>~", "@")::\pitch("*", \first!("5'", "7,"), 0, 0, \first(">~", "~"))";

// artic resets, intervals don't (second bar starts at C and goes down)
/pl = "\ins!(\first("@", "*"), 16, 0.25)::\seq("1>~", "@")::\pitch("*", \first("5'", "7,"), 0, 0, \first!(">~", "~"))";
\end{lstlisting}

\subsection{Writing new generators}
\label{sec:org1f231ee}
Generators inherit from \texttt{PR(\textbackslash{}clGen)}.\footnote{In \texttt{Proto}, inheritance is handled by ``cloning'' the
Proto: \texttt{PR(\textbackslash{}clGen).clone \{ ... overrides... \}}.} They should implement:

\begin{description}
\item[{\texttt{\textasciitilde{}prep}}] Validate the entries in the \texttt{\textasciitilde{}args} array, and return the
\texttt{Proto} object by finishing with \texttt{currentEnvironment}. In
general, start with \texttt{\textasciitilde{}baseItems = \textasciitilde{}args[0]}.

\item[{\texttt{\textasciitilde{}process}}] Generally begins with \texttt{\textasciitilde{}items =
                \textasciitilde{}getUpstreamItems.();}. Following this, manipulate the
\texttt{\textasciitilde{}items} array and return it at the end. Be careful to
\texttt{copy} or \texttt{collect} the array (to avoid corrupting
\texttt{\textasciitilde{}baseItems}) and---important!---if you modify any of
the items, be sure to copy it first.
\end{description}

Generators should take care to respect their time span, given by
\texttt{\textasciitilde{}time} (the generator's onset within the bar) and \texttt{\textasciitilde{}dur} (the number
of beats occupied by this generator). Do not modify any items outside
this time span. See the definition of \texttt{PR(\textbackslash{}clGenRot)} for an example.

\texttt{\textasciitilde{}baseItems} and \texttt{\textasciitilde{}items} are arrays of Events, containing:

\begin{description}
\item[{\texttt{item}}] The entry to be played. For non-pitched parameters, these
will generally be characters. Otherwise, pitch strings are
parsed into \texttt{SequenceNote} objects.

\item[{\texttt{time}}] The event's onset time within the bar. This is relative to
the bar line, not the generator's onset time.

\item[{\texttt{dur}}] The number of beats until the next event. This may not be
reliable during processing. The top-level generator will
correct the \texttt{dur} values before streaming out the events.
\end{description}

This documentation may be expanded at a later date.

\section{Graphical interface windows}
\label{sec:org9dbbaf0}
\subsection{Code window features}
\label{sec:orgb88911e}
The GUI code window has two advantages for \emph{cll} over the
SuperCollider IDE:

\begin{itemize}
\item The IDE's syntax highlighter doesn't understand \emph{cll}. You may get
incorrect highlighting or indentation with \emph{cll} statements.

\item The default font size is larger, for projection in performance.
\end{itemize}

One limitation: Because of a SuperCollider bug,\footnote{\url{https://github.com/supercollider/supercollider/issues/3279}}
this window can evaluate single lines only. If you select a block of
code to evaluate at once, the selection is ignored and only the line
containing the cursor will be executed.

The ``autosave'' button at the top will save the contents to disk
automatically when the window is closed. The file location is
\texttt{Platform.userAppSupportDir +/+ "cll-sketches"} and files are
automatically named by date and time. (I preferred autosave over a
standard save dialog specifically because it's a GUI window rather
than a code document.) The ``load'' button allows you to choose a file
from \texttt{cll-sketches}.

If the cursor is on a \ref{sec:org3e10854}, pressing alt-shift enters
an intelligent navigation mode, where arrow keys move through
syntactic elements rather than characters:

\begin{itemize}
\item Left and right arrows move to the previous or next sibling.
\item The up arrow expands the selection to the syntactic unit containing
the current element.
\item The down arrow contracts the selection to one of the units contained
within the current element.
\end{itemize}

Press alt-shift again when the selection is what you want, to exit
navigation mode and retain the selection.

It takes a little time to learn to use this fluently, but it's very
effective, especially for selecting entire generators at once. (Note
also that, at present, the set pattern statement must be complete and
free of syntax errors.)

\subsection{Controller window features}
\label{sec:orgef0647d}
The controller window divides into two or three parts: controls, a
list of processes and instruments, and an optional cheatsheet.

\subsubsection{Controls}
\label{sec:orge8eee08}
The default layout is based on a Korg Nanoktl. (If a Nanoktl is
plugged in and configured with the default controller numbers, the
hardware knobs and sliders are connected automatically.) You may also
call \texttt{/cllGui.(\textbackslash{}mix16Touch)} for a layout based on TouchOSC's Mix16
preset.

Buttons behave as toggles. Sliders and knobs should be
self-explanatory.

Note the slight shading at the top of each control. This is to overlay
a text label. Unfortunately, I cannot find a way to add a label and
make the widget respond over its entire area. So, be careful to click
in the unshaded area at the bottom.

\subsubsection{Process list}
\label{sec:org2081085}
The process list collects all playable BPs (``bound processes'') and VCs
(``voicers'').

Any item in the list can be controlled-dragged into buttons:

\begin{itemize}
\item BPs: the toggle button is for play/stop and the associated
fader/knob is for mixing.

\item VCs: the toggle button is for mute and the fader is for mixing.
\end{itemize}

If a BP defines global controls, it will have a \texttt{+} to the left of its
name. Right-arrow expands to show the controls that belong to it;
left-arrow hides them. Individual controls can be dragged into a
button, where they will be attached to the associated fader.

You can use the keyboard to ``throw'' a list entry up into the GUI. Both
\texttt{\textbackslash{}nanoTouch} and \texttt{\textbackslash{}mix16Touch} have 16 button/fader pairs, identified
as 0-9 and A-F. To ``throw,'' type \texttt{\textasciicircum{}} and the index character
(e.g. \texttt{\textasciicircum{}0} for the first one).

\ks{Backspace} in the list will delete an entry if possible. A BP can
be deleted only if it is not playing; a VC, only if it is not attached
to an existing BP player.

\subsubsection{Cheatsheet}
\label{sec:orgcb3ab8f}
You can write notes to yourself about available instruments and
players and save them under \texttt{Platform.userAppSupportDir +/+
"cll-cheatsheet.txt"}. If this file exists, its contents will be
displayed at the bottom of the controller window. (You can edit the
text here and save as well.) This is free text, only for your
convenience.

\section{Presets}
\label{sec:orge96accc}
Presets are a way to maintain multiple variants of the same process or
instrument.

\subsection{'set'-ting extra parameters in a cll process}
\label{sec:org27c295f}
Presets are concerned with synthesis parameters that are \emph{not} defined
as sequencing parameters in \texttt{parmMap}. Some parameters are impractical
to encode into \texttt{parmMap} (or also, it can be impractical to encode
every possible parameter into \texttt{parmMap}).

Parameters external to \texttt{parmMap} can be changed by calling \texttt{.set} on
the BP object. The specific behavior varies, depending on the type of
process. In all cases, \texttt{defaults} and \texttt{postDefaults} are used; see the
section on \hyperref[sec:org8ec1746]{PR(\textbackslash abstractLiveCode)} for details.

If the process was made by cloning \texttt{PR(\textbackslash{}abstractLiveCode)}, then extra
parameters are placed into \texttt{postDefaults} (unless they are simple
constants, in which case they might be placed into \texttt{defaults}).

Pitched note-playing processes (such as \texttt{Fact(\textbackslash{}melBP)},
\texttt{Fact(\textbackslash{}chordBP)} and \texttt{Fact(\textbackslash{}arpegBP)} in the ddwLivecodeInstruments
quark) place a special object into the process's \texttt{defaults} slot, to
integrate parameters from multiple sources. \texttt{set} parameters become
``overrides.''

In general, the implementation details are less important than the
fact that you can insert new keys and values into the process's events
by using \texttt{set}.

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=setMethod1,caption={Changing the length of a drum by set().},captionpos=b,numbers=none}
\begin{lstlisting}
\loadCl.eval;
s.boot;

TempoClock.tempo = 124/60;

// prepare a SynthDef and a process to play it
(
SynthDef(\snare, { |out, freq = 1200, drop = 0.6, rq = 0.3,
   time = 0.15, amp = 0.1|
   var sig = PinkNoise.ar;
   var pitchEg = EnvGen.ar(Env([1, drop], [time], \exp),
      levelScale: freq);
   var ampEg = EnvGen.ar(Env([0, 1, 0.7, 0], [0.01, 0.4, 0.5, 0.09], -4),
      timeScale: time, doneAction: 2);
   sig = BPF.ar(sig, pitchEg.clip(20, 20000), rq) / rq;
   Out.ar(out, (sig * amp * ampEg).dup);
}).add;

PR(\abstractLiveCode).clone {
   ~event = (eventKey: \default);
   ~initLevel = 0.7;
   ~userprep = {
      ~chan = MixerChannel(~collIndex, s, 2, 2, ~initLevel);
      ~defaults.put(\out, ~chan.inbus).put(\group, ~chan.synthgroup);
   };
   ~userfree = {
      ~chan.free;
   };
   ~defaultParm = \amp;
   ~parmMap = (amp: ($-: 0.7, $.: 0.3));
   ~defaults = (instrument: \snare)
} => PR(\ksnr);
)

// play it
PR(\ksnr) => BP(\ksnr);

/ksnr = " - -";
/ksnr+;

/ksnr(set(\freq, 1200, \time, 0.11));  // one sound

/ksnr(set(\freq, 3200, \time, 0.35));  // other sound

/ksnr-;
\end{lstlisting}

\begin{boxnote}
Because \texttt{set()} parameters are embedded into the process's pattern,
the parameter can itself be a pattern. For instance, you could
randomize a filter frequency by \texttt{/process(set(\textbackslash{}ffreq, Pexprand(1000,
5000, inf)));}.
\end{boxnote}

\subsection{Presets and (post)defaults}
\label{sec:org8902ab6}

Presets are a way to store, and automatically apply, \texttt{set}-style extra
parameters.

For \texttt{abstractLiveCode} clone processes, it is relatively
simple. Presets belong to the process, stored in the \texttt{presets}
variable. If you begin with Listing \ref{setMethod1}, you can define local
presets as follows.

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=presets1,caption={Defining and applying local presets.},captionpos=b,numbers=none}
\begin{lstlisting}
/ksnr(presets = (
   short: (freq: 1200, time: 0.11),
   long: (freq 3200, time: 0.35)
));

// Use a preset
/ksnr(preset(\long));
\end{lstlisting}

Note-playing processes, which go through a VC (voicer) instrument,
define presets with the VC instrument rather than the process. That
will be explained shortly.

\subsection{Global, persistent presets}
\label{sec:org3b95e4d}
Presets are especially relevant at the moment of creating a process,
from a Factory object. For this reason, you can add presets to
Factories, save them to disk, and reload them at any time. Then they
are globally available.

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=presets2,caption={Defining and applying global presets.},captionpos=b,numbers=none}
\begin{lstlisting}
// First we need a factory for the ksnr process.
(
make: { |name|
   PR(\ksnr) => BP(name);
},
type: \bp) => Fact(\ksnr);

// Then define presets for the factory
Fact(\ksnr).addPreset(\short, (time: 0.11, freq: 1200))
.addPreset(\long, (time: 0.35, freq: 3200));

Fact.savePresets;

// later, when loading the system, you can do:
Fact.loadPresets;

// Use a preset
/make(ksnr:sn(preset:\short));
\end{lstlisting}

\begin{boxnote}
For saving, values or patterns within presets need to be possible to
archive (Object methods \texttt{writeArchive}, \texttt{readArchive}). In particular,
avoid \emph{open functions} (those which refer to variables outside the
function's own scope).
\end{boxnote}

\subsection{Presets for note players}
\label{sec:orgd0bb951}
The examples so far have concerned a process that is tailored to a
specific SynthDef. Note-playing processes are different in that the
process encapsulates generic pitch-handling logic, leaving the sound
definition to a voicer (VC) instrument.

Presets define sonic parameters. Therefore, presets for new players
should be defined with the instrument, not with the process.

The procedure, however, is much the same as in the last section:
\texttt{addPreset} populates the data, exactly as shown earlier, but applied
to a voicer factory instead of a process factory. Then the presets
will follow the instrument into whichever note-playing process you use
with it. (Preset parameters go into the process, so you can use the
same voicer factory with different processes, and each process can use
a different preset.)

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=presets3,caption={Defining and applying global presets.},captionpos=b,numbers=none}
\begin{lstlisting}
// Add presets to one of the livecodeInstruments voicers
Fact(\staccVC).addPreset(\short, (ffreq: 90, fAtk: 0.01, fDcy: 0.1))
.addPreset(\brassy, (ffreq: 453, fAtk: 0.22, fDcy: 0.97));

// Create a note-player with one of these presets
/make(staccVC:st(preset:\short)/melBP:st);

/st = "\ins("*", 8, 0.5)::\seq("13569")";
/st+;

/st(preset(\brassy));  // apply a different preset

/st-;
\end{lstlisting}

\subsection{\texttt{makeParms}}
\label{sec:orgb9f0bd7}
Some preset parameters may need to be applied at the time of
Factory-building. For instance, a sample-player instrument (Listing
\ref{samplePlayer}) loads audio files while initializing. A preset should be
able to specify which file(s), but normal preset parameters are
applied after initializing. This is too late for this case.

The \texttt{makeParms} key within the preset dictionary contains items that
will be inserted into the \texttt{make} statement's initialization
parameters. 

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=samplePlayer,caption={Using makeParms to set initialization parameters.},captionpos=b,numbers=none}
\begin{lstlisting}
\loadAllCl.eval;

(
SynthDef(\bufPan, { |gate = 1, start, bufnum, pan, freq = 440, amp = 1,
      attack = 0.001, decay = 0.02, out, baseFreq = 440|
   var sig;
   sig = PlayBuf.ar(1, bufnum, freq / baseFreq * BufRateScale.kr(bufnum), 1, start, 0)
      * EnvGen.kr(Env.asr(attack, 1, decay), gate, doneAction:2);
   Out.ar(out, Pan2.ar(sig, pan, amp));
}).add;

// sample-player Voicer
(
keys: #[master, rvbmc],
initLevel: -12.dbamp,
// user should specify path at creation time
baseFreq: 60.midicps,
make: { |name|
   ~target = MixerChannel(name, s, 2, 2, ~initLevel);
   ~buf = Buffer.read(s, ~path);
   Voicer(10, \bufPan, [bufnum: ~buf.bufnum, baseFreq: ~baseFreq], target: ~target);
},
free: { ~target.free; ~buf.free },
type: \vc) => Fact(\sampleVC);

Fact(\sampleVC).addPreset(\houston, (
   makeParms: (
      path: Platform.resourceDir +/+ "sounds/a11wlk01.wav",
      baseFreq: 71.midicps
   ),
   start: 87205, amp: 0.5
));
)

/make(sampleVC:hou(preset:\houston)/melBP:hou);

/hou = "\ins("*", 8, 0.5)::\seq("12345678")";

/hou+
/hou-
\end{lstlisting}

For curious readers: the \texttt{make} statement in Listing \ref{samplePlayer}
translates into the following four SuperCollider statements, to show
how \texttt{makeParms} are applied. (The file path is for Linux and will be
different in Mac or Windows.)

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=makeTranslation,caption={makeParms translation into SuperCollider code.},captionpos=b,numbers=none}
\begin{lstlisting}
Fact('sampleVC').chuck(VC('hou'), nil, (path: "/usr/local/share/SuperCollider/sounds/a11wlk01.wav", baseFreq: 493.88330125612));
Fact('melBP').chuck(BP('hou'));
VC('hou') => BP('hou');
BP('hou').preset('houston')
\end{lstlisting}

\section{Extending cll}
\label{sec:orgbfbac20}
\emph{cll} is designed to be extensible: adding new statements is
relatively straightforward.

Processing a \emph{cll} statement goes through two main steps:

\begin{enumerate}
\item \texttt{PR(\textbackslash{}chucklibLiveCode)} tests the statement against a number of
regular expressions, to determine what type of statement it is.

\item Then, a \texttt{PR} object to handle the statement is instantiated, and
the statement is passed to that object's \texttt{process} method.
\end{enumerate}

So, to implement a new statement type, you need to do two things,
matching the above stages.

\subsection{Statement regular expression}
\label{sec:orgee86970}
First, add a statement ID and regular expression into
\texttt{PR(\textbackslash{}chucklibLiveCode)}. Within this object, \texttt{\textasciitilde{}statements} is an array
of Associations: \texttt{\textbackslash statementID -> "regexp"}.

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=regexp1,caption={Cll statement regular expression templates.},captionpos=b,numbers=none}
\begin{lstlisting}
   ~statements = [
      \clMake -> "^ *make\\(.*\\)",
      \clFuncCall -> "^ *`id\\.\\(.*\\)",
      \clPassThru -> "^ *([A-Z][A-Za-z0-9_]*\\.)?`id\\(.*\\)",
      \clChuck -> "^ *([A-Z][A-Za-z0-9_]*\\.)?`id *=>.*",
      \clPatternSet -> "^ *`id(\\.|`id|`id\\*[0-9]+)* = .*",
      \clGenerator -> "^ *`id(\\.|`id)* \\*.*",
      // harder match should come first
      \clXferPattern -> "^ *`id(\\.`id)?(\\*`int)? ->>",
      \clCopyPattern -> "^ *`id(\\.`id)?(\\*`int)? ->",
      \clStartStop -> "^([/`spc]*`id)+[`spc]*[+-]",
      \clPatternToDoc -> "^ *`id(\\.|`id)*[`spc]*$"
   ];
\end{lstlisting}

More restrictive matches should come first. For instance,
\texttt{\textbackslash{}clXferPattern} comes before \texttt{\textbackslash{}clCopyPattern}. If they were reversed,
\texttt{->} in the ``copy'' regular expression would match the
``xfer'' statement as well as the ``copy'' statement. Checking
\texttt{->>} first ensures that the more permissive test
takes place only after the stricter test fails.

Within these strings, a backtick (\texttt{`}) introduces a macro that will be
expanded into part of a regular expression. Available macros are:

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=regexp2,caption={Regular expression macros for SC language tokens.},captionpos=b,numbers=none}
\begin{lstlisting}
   ~tokens = (
      al: "A-Za-z",
      dig: "0-9",
      id: "[A-Za-z][A-Za-z0-9_]*",
      int: "(-[0-9]+|[0-9]+)",
      // http://www.regular-expressions.info/floatingpoint.html
      float: "[\\-+]?[0-9]*\\.?[0-9]+([eE][\\-+]?[0-9]+)?",
      spc: "    "  // space, tab, return
   );
\end{lstlisting}

You should match only as much of the syntax as you need to determine
the statement type. This is not the place for syntax validation. For
example, the \texttt{\textbackslash{}clGenerator} statement has a fairly complex syntax, but
the matching regular expression is looking only for one or more IDs
separated by dots, followed by a space and then an asterisk. This will
dispatch to \texttt{PR(\textbackslash{}clGenerator)}; it is this object's responsibility to
report syntax errors (generally by throwing descriptive \texttt{Error}
objects).

\begin{boxnote}
The leading slash is stripped from the statement before regular
expression matching. Don't include the slash in your regular
expression.
\end{boxnote}

\subsection{Handler object}
\label{sec:org0daa3f9}
Usually, a statement handler is a \texttt{PR} object, containing a \texttt{Proto}
object prototype. The \texttt{PR}'s name must match the statement ID created
in the last step.

The \texttt{Proto} must implement \texttt{process}, which takes \texttt{code} (the
statement, as a String) as its argument. It should return a string
containing the SuperCollider language syntax to perform the right
action.

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=cllTemplate1,caption={Template for cll statement handlers.},captionpos=b,numbers=none}
\begin{lstlisting}
Proto {
   ~process = { |code|
      // parse 'code' and build the SC language statement(s)...
      translatedStatement  // return value
   };
} => PR(\clMyNewStatement);
\end{lstlisting}

Very simple statements may be implemented as functions added into
\texttt{PR(\textbackslash{}chucklibLiveCode)}.

\lstset{style=SuperCollider-IDE,basicstyle=\ttfamily\small,captionpos=b,tabsize=3,language={SuperCollider},label=cllTemplate2,caption={Adding a function into PR(\textbackslash chucklibLiveCode) for simple statement types.},captionpos=b,numbers=none}
\begin{lstlisting}
PR(\chucklibLiveCode).clMyNewStatement = { |code|
   // parse 'code' and build the SC language statement(s)...
   translatedStatement  // return value
};
\end{lstlisting}

\section{Code examples}
\label{sec:org27d4b0a}
\renewcommand{\lstlistlistingname}{}
\lstlistoflistings

\section{Typesetting}
\label{sec:org6191b47}
Typeset by TeX Live 2017; Edited in Emacs 24.3.1 (Org mode 8.3beta).
\end{document}