@kairotic/app 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +9 -2
  2. package/index.html +1101 -0
  3. package/kairotic/api.cljs +362 -0
  4. package/kairotic/assistant.cljs +505 -0
  5. package/kairotic/backends/gun-backend.js +371 -0
  6. package/kairotic/canvas.cljs +751 -0
  7. package/kairotic/code.cljs +108 -0
  8. package/kairotic/components.cljs +838 -0
  9. package/kairotic/core.cljs +96 -0
  10. package/kairotic/corefns.cljs +473 -0
  11. package/kairotic/docs.mjs +2 -0
  12. package/kairotic/engine.cljs +482 -0
  13. package/kairotic/examples.mjs +96 -0
  14. package/kairotic/faust.cljs +225 -0
  15. package/kairotic/help.cljs +1036 -0
  16. package/kairotic/hiccup.cljs +566 -0
  17. package/kairotic/input.cljs +271 -0
  18. package/kairotic/kfile.mjs +138 -0
  19. package/kairotic/library.cljs +214 -0
  20. package/kairotic/links.cljs +41 -0
  21. package/kairotic/mt.cljs +1604 -0
  22. package/kairotic/mtboxes.cljs +276 -0
  23. package/kairotic/packages/analysis.mjs +64 -0
  24. package/kairotic/packages/controls.mjs +28 -0
  25. package/kairotic/packages/data.mjs +22 -0
  26. package/kairotic/packages/faust-units/cmaes.mjs +82 -0
  27. package/kairotic/packages/faust-units/graph.mjs +212 -0
  28. package/kairotic/packages/faust-units/listen.mjs +125 -0
  29. package/kairotic/packages/faust-units/notation.mjs +139 -0
  30. package/kairotic/packages/faust-units/parse.mjs +439 -0
  31. package/kairotic/packages/faust-units/recipe.mjs +195 -0
  32. package/kairotic/packages/faust-units/render.mjs +69 -0
  33. package/kairotic/packages/faust-units/units.mjs +130 -0
  34. package/kairotic/packages/faust-units/view.mjs +353 -0
  35. package/kairotic/packages/faust-units.mjs +9 -0
  36. package/kairotic/packages/io.mjs +58 -0
  37. package/kairotic/packages/net.mjs +28 -0
  38. package/kairotic/packages/patterns.mjs +34 -0
  39. package/kairotic/packages/spatial.mjs +22 -0
  40. package/kairotic/packages/spectral/shift.mjs +169 -0
  41. package/kairotic/packages/spectral.mjs +16 -0
  42. package/kairotic/packages/synth.mjs +28 -0
  43. package/kairotic/packages/theory/counterpoint.mjs +798 -0
  44. package/kairotic/packages/theory/mirror.mjs +221 -0
  45. package/kairotic/packages/theory.mjs +46 -0
  46. package/kairotic/patterns.cljs +538 -0
  47. package/kairotic/presets.cljs +227 -0
  48. package/kairotic/quantize.cljs +782 -0
  49. package/kairotic/record.cljs +169 -0
  50. package/kairotic/release.cljs +90 -0
  51. package/kairotic/ring.cljs +129 -0
  52. package/kairotic/ringaudio.cljs +232 -0
  53. package/kairotic/ringcore.mjs +270 -0
  54. package/kairotic/score.cljs +176 -0
  55. package/kairotic/shapes.cljs +283 -0
  56. package/kairotic/signal.cljs +327 -0
  57. package/kairotic/sounds.cljs +565 -0
  58. package/kairotic/sounds.mjs +108 -0
  59. package/kairotic/span.cljs +129 -0
  60. package/kairotic/spell.cljs +281 -0
  61. package/kairotic/structure.cljs +145 -0
  62. package/kairotic/talk.cljs +115 -0
  63. package/kairotic/tempo.cljs +226 -0
  64. package/kairotic/treecanvas.cljs +299 -0
  65. package/kairotic/tutorials.mjs +1283 -0
  66. package/kairotic/vendor/codemirror.mjs +23 -0
  67. package/package.json +23 -4
  68. package/page/00-work.cljs +862 -0
  69. package/page/01-commands.cljs +1219 -0
  70. package/page/02-patch-view.cljs +1051 -0
  71. package/page/03-history-view.cljs +481 -0
  72. package/page/04-panels.cljs +448 -0
  73. package/page/05-gestures.cljs +1247 -0
  74. package/page/06-connection.cljs +219 -0
  75. package/page/07-claude.cljs +430 -0
  76. package/page/08-sessions.cljs +423 -0
  77. package/page/09-learn.cljs +602 -0
  78. package/page/10-embed.cljs +469 -0
  79. package/page/11-startup.cljs +61 -0
  80. package/page/12-feedback.cljs +172 -0
  81. package/page/13-perform.cljs +325 -0
  82. package/page/14-editor.cljs +656 -0
  83. package/page/15-presets.cljs +230 -0
  84. package/page/16-release.cljs +242 -0
  85. package/page/17-sounds.cljs +147 -0
  86. package/page/18-lines.cljs +594 -0
  87. package/page/19-files.cljs +247 -0
  88. package/page/19-html.cljs +152 -0
  89. package/page/20-talk.cljs +527 -0
  90. package/page/21-net.cljs +110 -0
  91. package/page/22-learn.cljs +303 -0
  92. package/page/23-ids.cljs +233 -0
  93. package/page/24-clipboard.cljs +136 -0
  94. package/page/25-tidy.cljs +74 -0
  95. package/page/26-probes.cljs +111 -0
  96. package/sources.mjs +2 -0
@@ -0,0 +1,482 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · engine
3
+ ;; Makes the patch work without knowing anything about concrete classes: it asks everything of the
4
+ ;; component registry (kairotic.components). It routes outlets along the lines, keeps a queue of
5
+ ;; future messages and processes everything a little ahead of the AudioContext clock, so that
6
+ ;; sound effects are scheduled at the exact instant (`at`).
7
+ ;; What is sounding lives in this tab and does not enter the history of the work.
8
+ ;;
9
+ ;; Messages and time (Study 21): messages travel whenever something sends them — a click, a gesture,
10
+ ;; a data box that changed — with or without ▶. ▶ starts what needs a clock: the sound (audio nodes) and
11
+ ;; time (the queue of future messages: metro, ramp, mt play, loadbang). A message that comes back to
12
+ ;; the same box too many times in one instant is a loop without time: it is cut, and said so.
13
+
14
+ (ns kairotic.engine
15
+ (:require [clojure.string :as str]
16
+ [kairotic.components :as comp]
17
+ [kairotic.canvas :as cv]
18
+ [kairotic.span :as span]))
19
+
20
+ (defonce ctx* (atom nil))
21
+ (defn ctx [] (or @ctx* (reset! ctx* (js/AudioContext.))))
22
+ (defn now [] (.-currentTime (ctx)))
23
+
24
+ (defonce rt (atom {:on false :shows {} :prints []}))
25
+
26
+ (def lookahead 0.12)
27
+
28
+ ;; compatibility with code that already used these functions from the engine
29
+ (def klass comp/klass)
30
+ (def args-of comp/args-of)
31
+ (def num-of comp/num-of)
32
+
33
+ (defn def-of [p id] (comp/lookup (comp/klass (get-in p [:boxes id :text]))))
34
+ (defn audio? [p id] (boolean (:audio (def-of p id))))
35
+
36
+ ;; ───────── sub-patches: the engine works on a flat patch ─────────
37
+ ;; Every embedded `patch` box and every instance of an abstraction is replaced by its boxes, with
38
+ ;; ids prefixed by the path (:b5 inside :b2 → :b2.b5). A line to port i of a sub-patch goes to its
39
+ ;; i-th inlet box, and a line from port o comes from its o-th outlet box.
40
+
41
+ (def max-depth 8)
42
+
43
+ (defn flat-id
44
+ "The id of box `id` of the sub-patch at `path` in the flat patch."
45
+ [path id]
46
+ (if (empty? path) id (keyword (str (str/join "." (map name path)) "." (name id)))))
47
+
48
+ (defn substitute
49
+ "$1 $2 … in a box text → the words written after the class of the instance."
50
+ [text words]
51
+ (str/replace (str text) #"\$(\d)"
52
+ (fn [[_ n]] (or (get words (dec (js/parseInt n 10))) "0"))))
53
+
54
+ (defn line-ref
55
+ "The line a `patch @name` box uses (discussion #117): name, or nil for any other box."
56
+ [b]
57
+ (let [[k r] (str/split (str/trim (str (:text b))) #"\s+")]
58
+ (when (and (= k "patch") r (str/starts-with? r "@") (> (count r) 1)) (subs r 1))))
59
+
60
+ ;; how the page reads a line used as a sub-patch: (fn [box] patch) — the page knows the lines and their
61
+ ;; histories; the engine only asks
62
+ (defonce line-resolver (atom nil))
63
+
64
+ (defn inner-patch
65
+ "The patch inside a box: the data of an embedded `patch`, the line a `patch @name` uses, or the :patch
66
+ of an abstraction with its $-arguments filled in. nil for any other box."
67
+ [b]
68
+ (let [k (comp/klass (:text b)) d (comp/lookup k)]
69
+ (cond
70
+ (and (= k "patch") (line-ref b)) (or (when-let [f @line-resolver] (f b)) {:boxes {} :lines []})
71
+ (= k "patch") (or (:data b) {:boxes {} :lines []})
72
+ (map? (:patch d)) (let [words (vec (rest (str/split (str/trim (str (:text b))) #"\s+")))]
73
+ (update (:patch d) :boxes
74
+ (fn [bs] (into {} (for [[id ib] bs] [id (update ib :text substitute words)])))))
75
+ :else nil)))
76
+
77
+ (defn flatten-patch
78
+ ([p] (flatten-patch p [] 0))
79
+ ([p path depth]
80
+ (let [subs (into {} (for [[id b] (:boxes p) :let [inner (when (< depth max-depth) (inner-patch b))] :when inner]
81
+ [id inner]))
82
+ ports (into {} (for [[id inner] subs] [id (comp/patch-ports inner)]))
83
+ flats (for [[id inner] subs] (flatten-patch inner (conj path id) (inc depth)))
84
+ own (into {} (for [[id b] (:boxes p) :when (not (contains? subs id))] [(flat-id path id) b]))
85
+ from (fn [a o] (if-let [pt (get ports a)]
86
+ (when-let [x (get (:outlets pt) o)] [(flat-id (conj path a) x) 0])
87
+ [(flat-id path a) o]))
88
+ to (fn [b i] (if-let [pt (get ports b)]
89
+ (when-let [x (get (:inlets pt) i)] [(flat-id (conj path b) x) 0])
90
+ [(flat-id path b) i]))]
91
+ {:boxes (apply merge own (map :boxes flats))
92
+ :lines (vec (concat (keep (fn [[a o b i]] (let [s (from a o) t (to b i)] (when (and s t) (into s t)))) (:lines p))
93
+ (mapcat :lines flats)))})))
94
+
95
+ (defonce flat-cache (atom [nil nil]))
96
+
97
+ (defn flat
98
+ "flatten-patch, remembered for the last patch (the engine asks for it on every tick)."
99
+ [p]
100
+ (let [[k v] @flat-cache]
101
+ (if (identical? k p) v (let [f (flatten-patch p)] (reset! flat-cache [p f]) f))))
102
+
103
+ (defn patch [] (if-let [f (:patch-fn @rt)] (flat (f)) {:boxes {} :lines []}))
104
+
105
+ ;; ───────── audio ─────────
106
+
107
+ (defn dispose! [node]
108
+ (try (when-let [f (get-in node [:def :audio :dispose])] (f node)) (catch :default e (js/console.error e)))
109
+ (doseq [[n _] (:outlets node)] (try (.disconnect n) (catch :default _ nil))))
110
+
111
+ (defn updates? [d] (fn? (get-in d [:audio :update])))
112
+
113
+ (defn signature
114
+ "What the audio graph depends on: [boxes lines texts]. A box whose class can :update itself is known
115
+ by its class (and :key), so a new text does not rebuild it; its text goes in `texts` instead."
116
+ [p]
117
+ (let [audio (for [[id b] (:boxes p) :let [d (comp/lookup (comp/klass (:text b)))] :when (:audio d)] [id b d])]
118
+ [(into (sorted-map)
119
+ (for [[id b d] audio]
120
+ [id [(if (updates? d) (comp/klass (:text b)) (:text b))
121
+ (when-let [f (get-in d [:audio :key])] (f (comp/box-info b)))]]))
122
+ (vec (filter (fn [[a _ b _]] (and (audio? p a) (audio? p b))) (:lines p)))
123
+ (into (sorted-map) (for [[id b d] audio :when (updates? d)] [id (:text b)]))]))
124
+
125
+ (defn forget!
126
+ "Forgets what a box holds while it sounds (its state and what it showed): after its text changes,
127
+ the text is what counts."
128
+ [id]
129
+ (swap! rt (fn [r] (-> r (update :states dissoc id) (update :shows dissoc id)))))
130
+
131
+ (defn sync!
132
+ "Fits the audio nodes to the patch: creates the missing ones, removes those left over or changed,
133
+ redoes the connections, and tells the nodes that :update themselves about a new text."
134
+ []
135
+ (let [p (patch) [boxes lines texts :as s] (signature p) old (:signature @rt)]
136
+ (when (not= (take 2 s) (take 2 old))
137
+ (doseq [[id node] (:nodes @rt) :when (not= (get boxes id) (:signature node))]
138
+ (dispose! node)
139
+ (swap! rt update :nodes dissoc id))
140
+ (doseq [[id sig] boxes :when (not (get-in @rt [:nodes id]))]
141
+ (let [b (get-in p [:boxes id]) d (comp/lookup (comp/klass (:text b)))]
142
+ (try
143
+ ;; :create gets the box (text, args, data) with its id and its current state
144
+ (when-let [node ((get-in d [:audio :create]) (ctx) (assoc (comp/box-info b) :id id :state (get-in @rt [:states id])) (:env @rt))]
145
+ (swap! rt assoc-in [:nodes id] (assoc node :signature sig :def d :text (:text b))))
146
+ (catch :default e (js/console.error "could not create the audio of" (str id) e)))))
147
+ (doseq [[_ node] (:nodes @rt) [n _] (:outlets node)] (try (.disconnect n) (catch :default _ nil)))
148
+ (doseq [[a o b i] lines]
149
+ (let [[sn so] (get-in @rt [:nodes a :outlets o]) [dn di] (get-in @rt [:nodes b :inlets i])]
150
+ ;; an inlet can also be an AudioParam (a frequency, a gain): the signal is added to its value
151
+ (when (and sn dn) (try (if (instance? js/AudioParam dn) (.connect sn dn so) (.connect sn dn so di))
152
+ (catch :default e (js/console.error e))))))
153
+ ;; every node learns which of its inlets receive a signal (osc~ and gain~ then let it take over)
154
+ (doseq [[id node] (:nodes @rt) :let [f (get-in node [:def :audio :wired])] :when f]
155
+ ;; only lines that carry a signal: a message line (a msg, a number) into gain~'s right inlet sets it, it does not take over
156
+ (try (f node (set (keep (fn [[a o b i]] (when (and (= b id) (get-in @rt [:nodes a :outlets o])) i)) lines))) (catch :default e (js/console.error e))))
157
+ (swap! rt update :states (fn [ss] (into {} (filter (fn [[id _]] (get-in p [:boxes id])) ss)))))
158
+ ;; a new text for a node that updates itself: no new node, the node takes the new arguments
159
+ (when (not= (nth s 2) (nth old 2 nil))
160
+ (doseq [[id text] texts :let [node (get-in @rt [:nodes id])] :when (and node (not= text (:text node)))]
161
+ (forget! id)
162
+ (swap! rt assoc-in [:nodes id :text] text)
163
+ (try ((get-in node [:def :audio :update]) node (assoc (comp/box-info (get-in p [:boxes id])) :id id) (now))
164
+ (catch :default e (js/console.error e)))))
165
+ (swap! rt assoc :signature s)))
166
+
167
+ (defn print!
168
+ "Something to write in the REPL at instant at; label: the name of the print box that wrote it (print out0)."
169
+ ([at x] (print! at x nil))
170
+ ([at x label] (swap! rt update :prints (fn [ps] (conj (vec (take-last 200 ps)) (if label [at x label] [at x]))))))
171
+
172
+ ;; ───────── tasks: what a box asks of the world, outside its pure logic ─────────
173
+ ;; A component declares :tasks {k (fn [x box] promise)}, as an audio component declares :audio :effects.
174
+ ;; Its :receive asks for one with the effect [k x]; the engine runs it and the outcome comes back to the
175
+ ;; same box on inlet :task, as {:task k :arg x :value v} or {:task k :arg x :error "…"}, one more
176
+ ;; message: what the box does with it (:out, :show, :state, :effects [[:keep d]]) stays in its pure logic.
177
+ ;; It works with or without ▶, and what it finds lives in this tab, like what is sounding: only [:keep d]
178
+ ;; turns it into a gesture of the work (the data of the box, in the history, the same for everyone).
179
+
180
+ (def ^:dynamic *remote*
181
+ "True while a message that another performer played (a jam) is delivered here: what it makes is
182
+ theirs to keep, so [:keep …] from it is not written again by this tab."
183
+ false)
184
+
185
+ (declare inject!)
186
+
187
+ (defn arrive!
188
+ "The outcome of a task reaches its box on inlet :task, now (it came from outside: there is no instant
189
+ of the score to wait for). A box that was deleted meanwhile gets nothing."
190
+ [id value remote?]
191
+ (when-let [f (:patch-fn @rt)]
192
+ (binding [*remote* remote?]
193
+ (try (inject! f id :task value) (catch :default e (js/console.error e))))))
194
+
195
+ (defn task-of
196
+ "The task k of box id, or nil. Only a class that declares a task of that name sends the engine to the
197
+ patch to find out (an effect of an audio box while ■ falls here too, and often)."
198
+ [id k]
199
+ (when (some (fn [d] (contains? (:tasks d) k)) (vals @comp/registry))
200
+ (get-in (def-of (patch) id) [:tasks k])))
201
+
202
+ (defn wired
203
+ "What the outlets of box id reach in patch p: [{:outlet o :inlet i :id to :class \"faust~\" :text … :data …} …],
204
+ for a task that needs to know what it drives (realize~ learns the faust~ it plays)."
205
+ [p id]
206
+ (vec (for [[a o b i] (:lines p) :when (= a id) :let [t (get-in p [:boxes b])] :when t]
207
+ (assoc (comp/box-info t) :outlet o :inlet i :id b :class (comp/klass (:text t))))))
208
+
209
+ (defn run-task! [id f k x]
210
+ (let [remote? *remote*
211
+ p (patch)
212
+ box (assoc (comp/box-info (get-in p [:boxes id])) :id id :state (get-in @rt [:states id]) :wired (wired p id))]
213
+ (-> (js/Promise.resolve nil)
214
+ (.then (fn [_] (f x box)))
215
+ (.then (fn [v] (arrive! id {:task k :arg x :value v} remote?))
216
+ (fn [e] (arrive! id {:task k :arg x :error (str (or (.-message e) e))} remote?))))))
217
+
218
+ (defn effect! [id [k x label] at]
219
+ (cond
220
+ (= k :print) (print! at x label)
221
+ ;; a box keeps what it found (a task's outcome) as its data: a gesture of whoever made it happen
222
+ (= k :keep) (when-not *remote* (when-let [f (:effect-hook @rt)] (f id [k x] at)))
223
+ ;; effects for the page (a tree box asked to change its data: that is a gesture of the work; a presets
224
+ ;; box asked to recall, morph or generate: issue #35)
225
+ (#{:tree-edit :tree-set :canvas-edit :presets :sample} k) (when-let [f (:effect-hook @rt)] (f id [k x] at))
226
+ ;; on its audio node (the common case, many per second: looked up first)
227
+ (get-in @rt [:nodes id :def :audio :effects k])
228
+ (let [node (get-in @rt [:nodes id])]
229
+ (try ((get-in node [:def :audio :effects k]) node x at) (catch :default e (js/console.error e))))
230
+ :else
231
+ (when-let [f (task-of id k)] (run-task! id f k x))))
232
+
233
+ ;; ───────── messages ─────────
234
+
235
+ (defonce tree-bufs (atom {})) ; box → [tree buffer]: a tree turned into a buffer once, not on every tick
236
+
237
+ (defn tree-buffer
238
+ "The buffer of the musical tree a canvas, freqt or score shows (Study 23): one stroke per note."
239
+ [id tree]
240
+ (let [[t b] (get @tree-bufs id)]
241
+ (if (identical? t tree)
242
+ b
243
+ (let [b (when-let [f @comp/tree-buffer] (try (f tree) (catch :default _ nil)))]
244
+ (swap! tree-bufs assoc id [tree b])
245
+ b))))
246
+
247
+ (defn buffer-of
248
+ "The canvas (or freqt) connected to the right inlet of a box: [id data]. A box that shows a musical
249
+ tree gives that tree as its buffer, so a reader~ plays what the score shows."
250
+ [p id]
251
+ (some (fn [[a _ b i]]
252
+ (cond
253
+ (not (and (= b id) (= i 1))) nil
254
+ ;; a ring is what it keeps now (the state of its box), for the boxes that read messages from it
255
+ (= "ring" (comp/klass (get-in p [:boxes a :text])))
256
+ (when (#{"reader" "writer"} (comp/klass (get-in p [:boxes id :text])))
257
+ [a (or (get-in @rt [:states a])
258
+ (span/ring (comp/num-of (first (comp/args-of (get-in p [:boxes a :text]))))))])
259
+ ;; a ring~ is its node (kairotic.ringaudio): the reader~ and writer~ on it take a slot there
260
+ (= "ring~" (comp/klass (get-in p [:boxes a :text])))
261
+ (when (#{"reader~" "writer~"} (comp/klass (get-in p [:boxes id :text])))
262
+ [a (get-in @rt [:nodes a :ring])])
263
+ (#{"canvas" "freqt" "sample" "tree"} (comp/klass (get-in p [:boxes a :text])))
264
+ ;; a tree box is its tree (discussion #92); a canvas or freqt, the tree it shows, else its buffer
265
+ (let [k (comp/klass (get-in p [:boxes a :text]))
266
+ tree (if (= "tree" k)
267
+ (:tree (get-in p [:boxes a :data]))
268
+ (get-in @rt [:states a :tree]))]
269
+ [a (or (when tree (tree-buffer a tree))
270
+ (when (= "tree" k) cv/empty)
271
+ (get-in p [:boxes a :data]) (:empty (comp/model-of (get-in p [:boxes a]))) cv/empty)])))
272
+ (:lines p)))
273
+
274
+ (defn show! [id at v]
275
+ (swap! rt update-in [:shows id] (fn [q] (conj (vec (take-last 31 q)) [at v]))))
276
+
277
+ (defn shown-at
278
+ "The last thing a box showed up to instant `t`: [at value] or nil."
279
+ [id t]
280
+ (last (filter (fn [[at _]] (<= at t)) (get-in @rt [:shows id]))))
281
+
282
+ (defn enqueue! [at id inlet value]
283
+ (swap! rt update :queue (fn [q] (vec (sort-by first (conj (or q []) [at id inlet value]))))))
284
+
285
+ (defonce counter (atom 0))
286
+ (defonce visits (atom {})) ; box → messages it got in this instant
287
+ (def loop-limit 100)
288
+
289
+ (defn fresh-instant! [] (reset! counter 0) (reset! visits {}))
290
+
291
+ (defn loop-cut!
292
+ "Stops a message that came back to the same box too many times in one instant (a loop without time)."
293
+ [id at]
294
+ (when-not (contains? (:loops @rt) id)
295
+ (swap! rt update :loops (fnil conj #{}) id)
296
+ (print! at (str "loop cut at " (name id) ": a message came back to it " loop-limit
297
+ " times in one instant. A loop needs time (metro, a delay) or a box that only sends what changed."))))
298
+
299
+ ;; ───── probes (discussion #183): what goes out of the outlets someone is watching ─────
300
+ ;; The page puts a probe on a wire; what is watched is the outlet it leaves from ([box outlet], flat ids), since
301
+ ;; every wire from one outlet carries the same messages. With no probe, nothing is kept.
302
+
303
+ (defonce probes (atom #{})) ; #{[flat-id outlet]}
304
+ (defonce probe-seen (atom {})) ; [flat-id outlet] → {:v last value :at its instant :n how many :times [ms …]}
305
+
306
+ (defn probe!
307
+ "Something left outlet o of box id: kept if that outlet is watched."
308
+ [id o v at]
309
+ (when (and (seq @probes) (contains? @probes [id o]))
310
+ (let [t (.now js/performance)]
311
+ (swap! probe-seen update [id o]
312
+ (fn [s] {:v v :at at :n (inc (:n s 0))
313
+ ;; the times of the last ones, for a rate over the last second
314
+ :times (conj (vec (take-last 99 (:times s))) t)})))))
315
+
316
+ (defn deliver! [p id inlet value at]
317
+ (cond
318
+ (>= (swap! counter inc) 20000)
319
+ (when (= 20000 @counter) (print! at "too many messages in one instant (20000): the rest are not delivered"))
320
+ (> (get (swap! visits update id (fnil inc 0)) id) loop-limit)
321
+ (loop-cut! id at)
322
+ :else
323
+ (when-let [b (get-in p [:boxes id])]
324
+ (let [d (comp/lookup (comp/klass (:text b)))]
325
+ (when-let [f (:receive d)]
326
+ (let [[bid bdata] (when (:reads-buffer d) (buffer-of p id))
327
+ r (try (f {:id id :state (get-in @rt [:states id]) :args (comp/args-for d (:text b)) :data (:data b)
328
+ :inlet inlet :value value :at at :buffer bdata :buffer-id bid})
329
+ (catch :default e
330
+ {:effects [[:print (str (comp/klass (:text b)) " " (name id) ": " (or (.-message e) e))]]}))]
331
+ (when (map? r)
332
+ (when (contains? r :state) (swap! rt assoc-in [:states id] (:state r)))
333
+ (when (contains? r :show) (show! id at (:show r)))
334
+ (doseq [e (:effects r)] (effect! id e at))
335
+ (doseq [[at2 inl v] (:later r)] (enqueue! at2 id inl v))
336
+ (doseq [[o v] (:out r)]
337
+ (probe! id o v at)
338
+ (doseq [[a oo bb ii] (:lines p)
339
+ :when (and (= a id) (= oo o))]
340
+ (deliver! p bb ii v at))))))))))
341
+
342
+ (defn report!
343
+ "From the sound back to the messages: an audio node gives its own box a value it found (a level, a
344
+ block of samples, an error). It reaches the box's :receive on inlet :audio at instant `at` (the time
345
+ of the sound it was found in), as one more message of the queue, so what the box does with it (:out,
346
+ :show, :state) stays in its pure logic. Only while the engine runs, and only for a box that sounds."
347
+ [id value at]
348
+ (when (and (:on @rt) (get-in @rt [:nodes id]))
349
+ (enqueue! (if (number? at) at (now)) id :audio value)))
350
+
351
+ (reset! comp/audio-report report!)
352
+
353
+ ;; an audio node asks the page for something itself (a recording to keep as the data of its box), even
354
+ ;; when the engine has just stopped and no message can reach its box any more
355
+ (reset! comp/audio-effect (fn [id e] (effect! id e (now))))
356
+
357
+ (defn feed!
358
+ "Audio nodes that read a buffer (:audio :feed) get it again whenever it changes."
359
+ []
360
+ (let [p (patch)]
361
+ (doseq [[id node] (:nodes @rt) :let [f (get-in node [:def :audio :feed])] :when (and f (:fed node))]
362
+ (let [[_ data] (buffer-of p id)]
363
+ ;; by value: the same canvas rebuilt (the history recomputed after any change) is not new
364
+ (when-not (or (identical? data @(:fed node)) (= data @(:fed node)))
365
+ (reset! (:fed node) data)
366
+ (try (f node data) (catch :default e (js/console.error e))))))))
367
+
368
+ (defn tick! []
369
+ (when (:on @rt)
370
+ (try
371
+ (sync!)
372
+ (feed!)
373
+ (when-let [f @comp/after-feed] (try (f (patch) (:nodes @rt) (:signature @rt)) (catch :default e (js/console.error e))))
374
+ (fresh-instant!)
375
+ (let [limit (+ (now) lookahead) p (patch)]
376
+ (loop []
377
+ (let [e (first (:queue @rt))]
378
+ (when (and e (<= (first e) limit) (< @counter 20000))
379
+ (swap! rt update :queue (fn [q] (vec (rest q))))
380
+ (let [[at id inl v] e] (deliver! p id inl v (max at (now))))
381
+ (recur)))))
382
+ (catch :default ex (js/console.error ex)))))
383
+
384
+ (defn running? [] (boolean (:on @rt)))
385
+
386
+ ;; ───────── output: one input per channel of the sound card ─────────
387
+ ;; Every channel has its own mono input (dac~ 1 → channel 1); they meet in a merger, go through the
388
+ ;; master gain and, in stereo, through a gentle compressor. The sound card's channels are used if it
389
+ ;; has more than two.
390
+
391
+ (defn explicit! [node n interpretation]
392
+ (set! (.-channelCount node) n)
393
+ (set! (.-channelCountMode node) "explicit")
394
+ (set! (.-channelInterpretation node) interpretation))
395
+
396
+ (defn output! [ac]
397
+ (let [dest (.-destination ac)
398
+ n (max 2 (min 32 (or (.-maxChannelCount dest) 2)))]
399
+ (try (explicit! dest n "discrete") (catch :default _ nil))
400
+ (let [n (or (.-channelCount dest) 2)
401
+ merger (.createChannelMerger ac n)
402
+ master (.createGain ac)
403
+ silent (.createGain ac)
404
+ ins (vec (for [i (range n)]
405
+ (let [g (.createGain ac)] (explicit! g 1 "speakers") (.connect g merger 0 i) g)))]
406
+ (set! (.. master -gain -value) 0.8)
407
+ (set! (.. silent -gain -value) 0)
408
+ (explicit! master n "discrete")
409
+ (.connect merger master)
410
+ (if (= n 2)
411
+ (let [c (.createDynamicsCompressor ac)] (.connect master c) (.connect c dest) {:master master :comp c :ins ins :n n :silent silent})
412
+ (do (.connect master dest) {:master master :ins ins :n n :silent silent})))))
413
+
414
+ (defn start!
415
+ "Starts the engine (if it was not running). With `loadbang?`, fires the loadbang boxes."
416
+ [patch-fn loadbang?]
417
+ (let [ac (ctx)]
418
+ (.resume ac)
419
+ (when-not (:on @rt)
420
+ (let [{:keys [master] :as out} (output! ac)]
421
+ ;; the state boxes got from messages before ▶ (a tree kept by mt play) stays
422
+ (swap! rt assoc :on true :patch-fn patch-fn :nodes {} :queue [] :signature nil
423
+ :master master :out out :prints []
424
+ :env {:master master :channels (:n out) :silent (:silent out)
425
+ :channel (fn [i] (get (:ins out) i))})
426
+ (sync!)
427
+ (swap! rt assoc :timer (js/setInterval tick! 25))))
428
+ (when loadbang?
429
+ (let [p (patch) at (+ (now) 0.05)]
430
+ (fresh-instant!)
431
+ (doseq [[id b] (:boxes p) :when (= "loadbang" (comp/klass (:text b)))]
432
+ (deliver! p id 0 :bang at))))))
433
+
434
+ (defn stop! []
435
+ (when (:on @rt)
436
+ (js/clearInterval (:timer @rt))
437
+ (doseq [[_ node] (:nodes @rt)] (dispose! node))
438
+ (try (.disconnect (:master @rt)) (catch :default _ nil))
439
+ (swap! rt assoc :on false :queue [] :nodes {} :states {} :signature nil)))
440
+
441
+ (defn message-time [] (if (:on @rt) (+ (now) 0.03) (now)))
442
+
443
+ (defn inject!
444
+ "A gesture (or the REPL) sends a message to a box right now. It travels with or without ▶; without it
445
+ there is no sound and no time (what a box asks for later only happens with ▶ on)."
446
+ [patch-fn id inlet value]
447
+ (swap! rt assoc :patch-fn patch-fn :loops #{})
448
+ (when (:on @rt) (sync!))
449
+ (fresh-instant!)
450
+ (deliver! (patch) id inlet value (message-time)))
451
+
452
+ (defn emit!
453
+ "A box sends a value out of its outlet o, as if it had produced it (a data box that changed)."
454
+ [patch-fn id o value]
455
+ (swap! rt assoc :patch-fn patch-fn)
456
+ (when (:on @rt) (sync!))
457
+ (fresh-instant!)
458
+ (let [p (patch) at (message-time)]
459
+ (probe! id o value at)
460
+ (doseq [[a oo bb ii] (:lines p) :when (and (= a id) (= oo o))]
461
+ (deliver! p bb ii value at))))
462
+
463
+ (defn emit-to!
464
+ "Like emit!, but only along the lines from outlet o that reach one of `targets` ([box inlet] pairs):
465
+ a value sent again only where it is needed (a new line, a box that changed)."
466
+ [patch-fn id o value targets]
467
+ (swap! rt assoc :patch-fn patch-fn)
468
+ (when (:on @rt) (sync!))
469
+ (fresh-instant!)
470
+ (let [p (patch) at (message-time)]
471
+ (probe! id o value at)
472
+ (doseq [[a oo bb ii] (:lines p) :when (and (= a id) (= oo o) (contains? targets [bb ii]))]
473
+ (deliver! p bb ii value at))))
474
+
475
+ (defn node [id] (get-in @rt [:nodes id]))
476
+
477
+ (defn take-prints!
478
+ "The prints whose instant has already arrived (and removes them from the queue)."
479
+ []
480
+ (let [t (now) [due later] ((juxt filter remove) (fn [[at _]] (<= at t)) (:prints @rt))]
481
+ (when (seq due) (swap! rt assoc :prints (vec later)))
482
+ due))