@kairotic/app 0.0.0-stage → 0.2.2

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,283 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · shapes
3
+ ;; A component's own view is described with data, not HTML: a list of shapes in box
4
+ ;; coordinates (0,0 top left). This way a class written by anyone can be drawn in the patch
5
+ ;; without being able to inject markup into the page, and it follows its light or dark theme.
6
+ ;;
7
+ ;; [:rect {:x :y :w :h :r}]
8
+ ;; [:circle {:cx :cy :r}]
9
+ ;; [:line {:x1 :y1 :x2 :y2}]
10
+ ;; [:arc {:cx :cy :r :from :to}] degrees: 0 up, clockwise
11
+ ;; [:needle {:cx :cy :r :angle :r0}] a radial line from radius r0 (default 0) to r at `angle` degrees
12
+ ;; [:path {:points [[x y] …] :closed true}] a polyline (a waveform, an envelope…)
13
+ ;; [:text {:x :y :anchor :start|:middle|:end :size 11} "text"]
14
+ ;; [:curve {:points [[x y] …]}] a smooth path through the points (Catmull–Rom)
15
+ ;; [:group {:x :y :rotate :scale} [shape …]] shapes moved (x y), turned (degrees, clockwise) and scaled
16
+ ;; together; groups can hold groups (4 deep)
17
+ ;;
18
+ ;; All accept :stroke and :fill with a palette colour, :weight in pixels and :opacity (0…1).
19
+ ;; Any shape can also carry :hit k (a keyword or a number): pressing it, the component learns k (in the
20
+ ;; m of its :gesture, as :hit), so a view can have parts to click: the nodes of a graph, the keys of
21
+ ;; a scale. The last shape with :hit under the press wins (the one drawn on top).
22
+ ;; Palette: :ink :soft :accent :kairos :bg :grid (nil = no stroke or no fill).
23
+ ;; nils in the list are ignored, so you can write (when cond [:text …]).
24
+ ;;
25
+ ;; Templates: a component's :view is a list of shapes where any value can be a hole, a keyword
26
+ ;; that starts with $ (:$angle, :$label). `fill` replaces each hole with the value of the same
27
+ ;; key (without the $) in a map: the one its :derive returns, merged over the declared args and
28
+ ;; the box context (:shown :w :h). A hole with no value becomes nil.
29
+
30
+ (ns kairotic.shapes
31
+ (:require [clojure.string :as str]
32
+ [clojure.walk :as walk]))
33
+
34
+ (def palette #{:ink :soft :accent :kairos :bg :grid})
35
+ (def max-shapes 600) ; shapes per box
36
+
37
+ (defn esc [s]
38
+ (-> (str s) (str/replace "&" "&amp;") (str/replace "<" "&lt;") (str/replace ">" "&gt;") (str/replace "\"" "&quot;")))
39
+
40
+ (defn n
41
+ "A safe number for an SVG attribute (with two decimals)."
42
+ [x]
43
+ (if (and (number? x) (js/isFinite x)) (/ (js/Math.round (* x 100)) 100) 0))
44
+
45
+ (defn classes [o stroke fill]
46
+ (let [s (if (contains? o :stroke) (:stroke o) stroke)
47
+ f (if (contains? o :fill) (:fill o) fill)]
48
+ (str " class=\"shape" (when (palette s) (str " s-" (name s))) (when (palette f) (str " f-" (name f))) "\""
49
+ (when (number? (:weight o)) (str " stroke-width=\"" (n (max 0 (min 24 (:weight o)))) "\""))
50
+ (when (number? (:opacity o)) (str " opacity=\"" (n (max 0 (min 1 (:opacity o)))) "\"")))))
51
+
52
+ (defn polar
53
+ "Point at distance r from the centre, with the angle in degrees (0 up, clockwise)."
54
+ [cx cy r a]
55
+ (let [t (* a (/ js/Math.PI 180))]
56
+ [(+ cx (* r (js/Math.sin t))) (- cy (* r (js/Math.cos t)))]))
57
+
58
+ (defn arc-d [cx cy r from to]
59
+ (let [span (- to from)]
60
+ (when (> (js/Math.abs span) 0.01)
61
+ (if (>= (js/Math.abs span) 359.99)
62
+ (str "M" (n (- cx r)) " " (n cy) "a" (n r) " " (n r) " 0 1 0 " (n (* 2 r)) " 0a" (n r) " " (n r) " 0 1 0 " (n (* -2 r)) " 0")
63
+ (let [[x1 y1] (polar cx cy r from) [x2 y2] (polar cx cy r to)]
64
+ (str "M" (n x1) " " (n y1) "A" (n r) " " (n r) " 0 " (if (> (js/Math.abs span) 180) 1 0) " " (if (pos? span) 1 0)
65
+ " " (n x2) " " (n y2)))))))
66
+
67
+ (defn curve-d
68
+ "The SVG path of a smooth curve through the points (Catmull–Rom as cubic Béziers)."
69
+ [ps]
70
+ (let [ps (vec ps) c (count ps) P (fn [i] (nth ps (max 0 (min (dec c) i))))]
71
+ (when (>= c 2)
72
+ (str "M" (n (first (P 0))) " " (n (second (P 0)))
73
+ (apply str (for [i (range (dec c))]
74
+ (let [[x0 y0] (P (dec i)) [x1 y1] (P i) [x2 y2] (P (inc i)) [x3 y3] (P (+ i 2))]
75
+ (str " C" (n (+ x1 (/ (- x2 x0) 6))) " " (n (+ y1 (/ (- y2 y0) 6)))
76
+ " " (n (- x2 (/ (- x3 x1) 6))) " " (n (- y2 (/ (- y3 y1) 6)))
77
+ " " (n x2) " " (n y2)))))))))
78
+
79
+ (defn points-of [o] (filter (fn [p] (and (sequential? p) (= 2 (count p)))) (take 2000 (:points o))))
80
+
81
+ (declare shapes-str)
82
+
83
+ (defn shape
84
+ ([f] (shape f 0))
85
+ ([f depth]
86
+ (if-not (and (vector? f) (keyword? (first f)))
87
+ ""
88
+ (let [[kind o text] f o (if (map? o) o {})]
89
+ (case kind
90
+ :curve (if-let [d (curve-d (points-of o))] (str "<path d=\"" d "\"" (classes o :ink nil) "></path>") "")
91
+ :group (if (or (> depth 3) (not (sequential? text)))
92
+ ""
93
+ (str "<g transform=\"translate(" (n (:x o 0)) "," (n (:y o 0)) ") rotate(" (n (:rotate o 0)) ") scale("
94
+ (n (let [k (:scale o 1)] (if (and (number? k) (pos? k)) (min 20 k) 1))) ")\""
95
+ (when (number? (:opacity o)) (str " opacity=\"" (n (max 0 (min 1 (:opacity o)))) "\"")) ">"
96
+ (shapes-str text (inc depth)) "</g>"))
97
+ :rect (str "<rect x=\"" (n (:x o)) "\" y=\"" (n (:y o)) "\" width=\"" (n (max 0 (:w o 0))) "\" height=\"" (n (max 0 (:h o 0)))
98
+ "\" rx=\"" (n (:r o 0)) "\"" (classes o :ink nil) "></rect>")
99
+ :circle (str "<circle cx=\"" (n (:cx o)) "\" cy=\"" (n (:cy o)) "\" r=\"" (n (max 0 (:r o 0))) "\"" (classes o :ink nil) "></circle>")
100
+ :line (str "<line x1=\"" (n (:x1 o)) "\" y1=\"" (n (:y1 o)) "\" x2=\"" (n (:x2 o)) "\" y2=\"" (n (:y2 o)) "\"" (classes o :ink nil) "></line>")
101
+ :arc (if-let [d (arc-d (n (:cx o)) (n (:cy o)) (n (:r o)) (n (:from o 0)) (n (:to o 360)))]
102
+ (str "<path d=\"" d "\"" (classes o :ink nil) "></path>")
103
+ "")
104
+ :needle (let [cx (n (:cx o)) cy (n (:cy o)) a (n (:angle o 0))
105
+ [x1 y1] (polar cx cy (n (:r0 o 0)) a)
106
+ [x2 y2] (polar cx cy (n (:r o 0)) a)]
107
+ (str "<line x1=\"" (n x1) "\" y1=\"" (n y1) "\" x2=\"" (n x2) "\" y2=\"" (n y2) "\"" (classes o :ink nil) "></line>"))
108
+ :path (let [ps (filter (fn [p] (and (sequential? p) (= 2 (count p)))) (take 2000 (:points o)))]
109
+ (if (< (count ps) 2)
110
+ ""
111
+ (str "<" (if (:closed o) "polygon" "polyline") " points=\""
112
+ (str/join " " (map (fn [[x y]] (str (n x) "," (n y))) ps)) "\"" (classes o :ink nil) "></"
113
+ (if (:closed o) "polygon" "polyline") ">")))
114
+ :text (str "<text x=\"" (n (:x o)) "\" y=\"" (n (:y o)) "\" text-anchor=\""
115
+ (case (:anchor o) :middle "middle" :end "end" "start") "\""
116
+ " font-size=\"" (n (max 7 (min 28 (or (:size o) 11)))) "\"" (classes o nil :ink) ">"
117
+ (esc (let [s (str text)] (if (> (count s) 80) (subs s 0 80) s))) "</text>")
118
+ "")))))
119
+
120
+ (defn shapes-str [shapes depth]
121
+ (if (sequential? shapes)
122
+ (apply str (map (fn [f] (shape f depth)) (take max-shapes (remove nil? shapes))))
123
+ ""))
124
+
125
+ (defn svg
126
+ "The SVG (as text) of a list of shapes."
127
+ [shapes]
128
+ (shapes-str shapes 0))
129
+
130
+ ;; ───────── pressing a shape (:hit) ─────────
131
+ ;; Where a press lands is worked out from the shapes themselves (the view is drawn above the patch and
132
+ ;; does not take the pointer), in the coordinates of the box.
133
+
134
+ (defn- num [x d] (if (and (number? x) (js/isFinite x)) x d))
135
+
136
+ (defn- seg-dist [[px py] [ax ay] [bx by]]
137
+ (let [dx (- bx ax) dy (- by ay) L2 (+ (* dx dx) (* dy dy))
138
+ u (if (zero? L2) 0 (max 0 (min 1 (/ (+ (* (- px ax) dx) (* (- py ay) dy)) L2))))]
139
+ (js/Math.hypot (- px (+ ax (* u dx))) (- py (+ ay (* u dy))))))
140
+
141
+ (defn- inside-polygon? [[x y] ps]
142
+ (let [ps (vec ps) c (count ps)]
143
+ (loop [i 0 j (dec c) in false]
144
+ (if (>= i c)
145
+ in
146
+ (let [[xi yi] (nth ps i) [xj yj] (nth ps j)
147
+ cross (and (not= (> yi y) (> yj y))
148
+ (< x (+ xi (/ (* (- xj xi) (- y yi)) (- yj yi)))))]
149
+ (recur (inc i) i (if cross (not in) in)))))))
150
+
151
+ (defn covers?
152
+ "Whether shape f (not a group) covers the point [x y] of its own coordinates (strokes within 4 px)."
153
+ [f [x y :as p]]
154
+ (let [[kind o text] f o (if (map? o) o {})]
155
+ (case kind
156
+ :rect (and (<= (num (:x o) 0) x (+ (num (:x o) 0) (num (:w o) 0))) (<= (num (:y o) 0) y (+ (num (:y o) 0) (num (:h o) 0))))
157
+ :circle (<= (js/Math.hypot (- x (num (:cx o) 0)) (- y (num (:cy o) 0))) (max 4 (num (:r o) 0)))
158
+ :arc (let [d (js/Math.hypot (- x (num (:cx o) 0)) (- y (num (:cy o) 0)))] (< (js/Math.abs (- d (num (:r o) 0))) 5))
159
+ :line (< (seg-dist p [(num (:x1 o) 0) (num (:y1 o) 0)] [(num (:x2 o) 0) (num (:y2 o) 0)]) 4)
160
+ :needle (let [cx (num (:cx o) 0) cy (num (:cy o) 0) a (num (:angle o) 0)]
161
+ (< (seg-dist p (polar cx cy (num (:r0 o) 0) a) (polar cx cy (num (:r o) 0) a)) 4))
162
+ (:path :curve) (let [ps (vec (points-of o))]
163
+ (or (and (:closed o) (> (count ps) 2) (inside-polygon? p ps))
164
+ (some (fn [[a b]] (< (seg-dist p a b) 4)) (map vector ps (rest ps)))))
165
+ :text (let [sz (max 7 (min 28 (num (:size o) 11))) w (* 0.62 sz (count (str text)))
166
+ x0 (case (:anchor o) :middle (- (num (:x o) 0) (/ w 2)) :end (- (num (:x o) 0) w) (num (:x o) 0))]
167
+ (and (<= x0 x (+ x0 w)) (<= (- (num (:y o) 0) sz) y (+ (num (:y o) 0) 3))))
168
+ false)))
169
+
170
+ (defn- into-group
171
+ "The point p of the outside, in the coordinates inside a group (its translate, rotate and scale undone)."
172
+ [o [x y]]
173
+ (let [x (- x (num (:x o) 0)) y (- y (num (:y o) 0))
174
+ t (* (- (num (:rotate o) 0)) (/ js/Math.PI 180))
175
+ k (let [k (:scale o 1)] (if (and (number? k) (pos? k)) k 1))
176
+ xr (- (* x (js/Math.cos t)) (* y (js/Math.sin t)))
177
+ yr (+ (* x (js/Math.sin t)) (* y (js/Math.cos t)))]
178
+ [(/ xr k) (/ yr k)]))
179
+
180
+ (defn- group-covers?
181
+ "Whether any shape of a group (or of the groups inside it) covers the point."
182
+ [kids p depth]
183
+ (and (sequential? kids) (< depth 4)
184
+ (some (fn [f]
185
+ (when (and (vector? f) (keyword? (first f)))
186
+ (let [[kind o ks] f o (if (map? o) o {})]
187
+ (if (= kind :group) (group-covers? ks (into-group o p) (inc depth)) (covers? f p)))))
188
+ (take max-shapes (remove nil? kids)))))
189
+
190
+ (defn hit-at
191
+ "The :hit of the shape drawn on top at [x y] (box coordinates), or nil. A group with :hit is hit
192
+ wherever one of its shapes is; a :hit inside it, more precise, wins."
193
+ ([shapes p] (hit-at shapes p 0))
194
+ ([shapes p depth]
195
+ (when (sequential? shapes)
196
+ (reduce (fn [found f]
197
+ (if-not (and (vector? f) (keyword? (first f)))
198
+ found
199
+ (let [[kind o kids] f o (if (map? o) o {})
200
+ inner (when (and (= kind :group) (< depth 4)) (hit-at kids (into-group o p) (inc depth)))
201
+ own (when (and (some? (:hit o)) (not= kind :group) (covers? f p)) (:hit o))
202
+ g (when (and (= kind :group) (some? (:hit o)) (group-covers? kids (into-group o p) depth)) (:hit o))]
203
+ (or inner g own found))))
204
+ nil (take max-shapes (remove nil? shapes))))))
205
+
206
+ (defn dist-to
207
+ "How far the point [x y] is from shape f (not a group): 0 when it covers it."
208
+ [f [x y :as p]]
209
+ (if (covers? f p)
210
+ 0
211
+ (let [[kind o text] f o (if (map? o) o {})]
212
+ (case kind
213
+ :rect (let [x0 (num (:x o) 0) y0 (num (:y o) 0) x1 (+ x0 (num (:w o) 0)) y1 (+ y0 (num (:h o) 0))]
214
+ (js/Math.hypot (max (- x0 x) 0 (- x x1)) (max (- y0 y) 0 (- y y1))))
215
+ :circle (max 0 (- (js/Math.hypot (- x (num (:cx o) 0)) (- y (num (:cy o) 0))) (max 4 (num (:r o) 0))))
216
+ :arc (js/Math.abs (- (js/Math.hypot (- x (num (:cx o) 0)) (- y (num (:cy o) 0))) (num (:r o) 0)))
217
+ :line (seg-dist p [(num (:x1 o) 0) (num (:y1 o) 0)] [(num (:x2 o) 0) (num (:y2 o) 0)])
218
+ :needle (let [cx (num (:cx o) 0) cy (num (:cy o) 0) a (num (:angle o) 0)]
219
+ (seg-dist p (polar cx cy (num (:r0 o) 0) a) (polar cx cy (num (:r o) 0) a)))
220
+ (:path :curve) (let [ps (vec (points-of o))]
221
+ (if (< (count ps) 2) js/Infinity (apply min (map (fn [[a b]] (seg-dist p a b)) (map vector ps (rest ps))))))
222
+ :text (let [sz (max 7 (min 28 (num (:size o) 11))) w (* 0.62 sz (count (str text)))
223
+ x0 (case (:anchor o) :middle (- (num (:x o) 0) (/ w 2)) :end (- (num (:x o) 0) w) (num (:x o) 0))
224
+ y0 (- (num (:y o) 0) sz) y1 (+ (num (:y o) 0) 3)]
225
+ (js/Math.hypot (max (- x0 x) 0 (- x (+ x0 w))) (max (- y0 y) 0 (- y y1))))
226
+ js/Infinity))))
227
+
228
+ (defn- hit-dists
229
+ "[[hit distance] …] of every shape with :hit (a group with :hit: its nearest shape), in the outside
230
+ coordinates (a scaled group scales its distances)."
231
+ [shapes p depth k]
232
+ (when (and (sequential? shapes) (< depth 5))
233
+ (mapcat (fn [f]
234
+ (when (and (vector? f) (keyword? (first f)))
235
+ (let [[kind o kids] f o (if (map? o) o {})]
236
+ (if (= kind :group)
237
+ (let [q (into-group o p)
238
+ gk (* k (let [s (:scale o 1)] (if (and (number? s) (pos? s)) s 1)))
239
+ inner (hit-dists kids q (inc depth) gk)]
240
+ (concat inner
241
+ (when (some? (:hit o))
242
+ (let [ds (keep (fn [g] (when (and (vector? g) (keyword? (first g)) (not= :group (first g)))
243
+ (* gk (dist-to g q))))
244
+ (take max-shapes (remove nil? kids)))]
245
+ (when (seq ds) [[(:hit o) (apply min ds)]])))))
246
+ (when (some? (:hit o)) [[(:hit o) (* k (dist-to f p))]])))))
247
+ (take max-shapes (remove nil? shapes)))))
248
+
249
+ (defn hit-near
250
+ "Like hit-at, but forgiving: when no shape with :hit is under [x y], the nearest one within tol px
251
+ (10 by default), so small parts (a node, a key, a point) are easy to press."
252
+ ([shapes p] (hit-near shapes p 10))
253
+ ([shapes p tol]
254
+ (or (hit-at shapes p)
255
+ (let [[h d] (first (sort-by second (hit-dists shapes p 0 1)))]
256
+ (when (and (some? h) (<= d tol)) h)))))
257
+
258
+ (defn only-hit
259
+ "The shapes that make the part k of a view (those with :hit k, inside their groups), to draw it again
260
+ highlighted; a group with :hit k keeps all its shapes."
261
+ [shapes k]
262
+ (when (sequential? shapes)
263
+ (vec (keep (fn [f]
264
+ (when (and (vector? f) (keyword? (first f)))
265
+ (let [[kind o kids] f o (if (map? o) o {})]
266
+ (cond
267
+ (= (:hit o) k) f
268
+ (= kind :group) (let [ks (only-hit kids k)] (when (seq ks) [:group o ks]))
269
+ :else nil))))
270
+ (take max-shapes (remove nil? shapes))))))
271
+
272
+ ;; ───────── templates ─────────
273
+
274
+ (defn hole
275
+ "The key a hole stands for (:$angle → :angle), or nil if x is not a hole."
276
+ [x]
277
+ (when (and (keyword? x) (nil? (namespace x)) (str/starts-with? (name x) "$") (> (count (name x)) 1))
278
+ (keyword (subs (name x) 1))))
279
+
280
+ (defn fill
281
+ "Replaces the holes of a shapes template with the values in `vals`."
282
+ [template vals]
283
+ (walk/postwalk (fn [x] (if-let [k (hole x)] (get vals k) x)) template))
@@ -0,0 +1,327 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · signal
3
+ ;; Reading at audio rate. A reader reads a canvas once per message; reader~ reads it once per sample,
4
+ ;; driven by a signal position (usually a phasor~). The canvas is sampled into a table that is sent to
5
+ ;; an AudioWorklet whenever it changes, and the worklet interpolates the table while it plays.
6
+ ;;
7
+ ;; phasor~ [hz] a ramp signal from 0 to 1, hz times per second (a number changes hz)
8
+ ;; reader~ [x|y|path] [voices] [gate]
9
+ ;; position signal on the left (the buffer's units; 0…1 with norm),
10
+ ;; buffer on the right:
11
+ ;; · x (default): along X, one outlet per voice
12
+ ;; · y: along Y, the same
13
+ ;; · path [stroke]: along a stroke, two outlets x and y
14
+ ;; · gate: then one more outlet per voice (one for path): 1 where the
15
+ ;; voice has something, 0 where not (into an adsr~ of @kairotic/synth)
16
+ ;; sig~ [value] a constant signal; a number changes it
17
+ ;;
18
+ ;; With norm, the position 0…1 covers the X axis of a canvas, or a freqt from 0 to its last point (y: the Y axis,
19
+ ;; or the lowest … highest frequency). Where nothing passes a voice keeps its last value (so an
20
+ ;; oscillator it drives does not fall to 0 Hz); the gate says whether it sounds. Voices are given like
21
+ ;; a synth gives them: a stroke keeps its voice while it lasts, and a new one takes the first free voice.
22
+
23
+ (ns kairotic.signal
24
+ (:require [kairotic.components :as comp]
25
+ [kairotic.canvas :as cv]
26
+ [kairotic.api :as api]
27
+ [kairotic.sounds :as snd]
28
+ [kairotic.ringaudio :as ringa]))
29
+
30
+ (def table-size 1024)
31
+
32
+ (def worklet-source
33
+ "class KairoticReader extends AudioWorkletProcessor {
34
+ // tab: V value channels of n points (NaN where nothing passes), sampled over span [lo, hi] (log: on a log
35
+ // scale). The position is in the span's units, or 0…1 with norm (and always along a path). Outputs: the V
36
+ // values, held where nothing passes, then G gates (gate g follows value channel g): 1 where it has something.
37
+ constructor(o) {
38
+ super();
39
+ this.tab = null; this.n = 0; this.V = 0; this.G = 0; this.span = null; this.norm = true;
40
+ this.last = [];
41
+ this.port.onmessage = (e) => {
42
+ const { tab, n, V, G, span, norm } = e.data;
43
+ this.tab = tab; this.n = n; this.V = V; this.G = G; this.span = span || null; this.norm = norm !== false;
44
+ for (let c = 0; c < V; c++) {
45
+ if (this.last[c] === undefined || isNaN(this.last[c])) {
46
+ let v = NaN; for (let i = 0; i < n; i++) { const x = tab[c * n + i]; if (!isNaN(x)) { v = x; break; } }
47
+ this.last[c] = isNaN(v) ? 0 : v;
48
+ }
49
+ }
50
+ };
51
+ }
52
+ process(inputs, outputs) {
53
+ const inp = inputs[0] && inputs[0][0];
54
+ const out = outputs[0];
55
+ const C = out.length, L = out[0].length, n = this.n, tab = this.tab, V = this.V, G = this.G;
56
+ for (let i = 0; i < L; i++) {
57
+ if (!tab || n < 2) { for (let c = 0; c < C; c++) out[c][i] = 0; continue; }
58
+ let p = inp ? inp[i] : 0;
59
+ const sp = this.span;
60
+ if (!this.norm && sp) {
61
+ p = sp[2] && sp[0] > 0 && sp[1] > 0 ? (p > 0 ? Math.log(p / sp[0]) / Math.log(sp[1] / sp[0]) : 0)
62
+ : (sp[1] !== sp[0] ? (p - sp[0]) / (sp[1] - sp[0]) : 0);
63
+ }
64
+ p = p < 0 ? 0 : (p > 1 ? 1 : p);
65
+ const f = p * (n - 1), k = Math.min(Math.floor(f), n - 2), r = f - k;
66
+ for (let c = 0; c < V && c < C; c++) {
67
+ const a = tab[c * n + k], b = tab[c * n + k + 1];
68
+ if (!isNaN(a)) this.last[c] = isNaN(b) ? a : a + (b - a) * r;
69
+ out[c][i] = this.last[c];
70
+ if (c < G && V + c < C) out[V + c][i] = isNaN(a) ? 0 : 1;
71
+ }
72
+ }
73
+ return true;
74
+ }
75
+ }
76
+ class KairoticPhasor extends AudioWorkletProcessor {
77
+ static get parameterDescriptors() { return [{ name: 'freq', defaultValue: 1 }]; }
78
+ constructor() { super(); this.ph = 0; }
79
+ process(inputs, outputs, params) {
80
+ const o = outputs[0][0], f = params.freq;
81
+ for (let i = 0; i < o.length; i++) {
82
+ o[i] = this.ph;
83
+ this.ph += (f.length > 1 ? f[i] : f[0]) / sampleRate;
84
+ this.ph -= Math.floor(this.ph);
85
+ }
86
+ return true;
87
+ }
88
+ }
89
+ registerProcessor('kairotic-reader', KairoticReader);
90
+ registerProcessor('kairotic-phasor', KairoticPhasor);
91
+ ")
92
+
93
+ (defonce modules (atom {}))
94
+
95
+ (defn ready
96
+ "Promise that resolves when the worklet module is loaded in this AudioContext."
97
+ [ac]
98
+ (or (get @modules ac)
99
+ (let [url (js/URL.createObjectURL (js/Blob. #js [worklet-source] #js {:type "application/javascript"}))
100
+ p (.addModule (.-audioWorklet ac) url)]
101
+ (swap! modules assoc ac p)
102
+ p)))
103
+
104
+ ;; ───────── tables ─────────
105
+
106
+ (defn mode-of [args] (cond (some #{:path} args) :path (some #{:y} args) :y :else :x))
107
+
108
+ (defn voices-of
109
+ "How many voices: the first number that is not the value of a word (d 1, speed 0.5, jump 1 are a head's on a
110
+ ring~)."
111
+ [args]
112
+ (let [free (keep-indexed (fn [i x] (when (and (number? x) (not (#{:d :speed :jump :mix} (get (vec args) (dec i))))) x)) args)]
113
+ (if (= :path (mode-of args)) 2 (max 1 (min 16 (or (comp/num-of (first free)) 1))))))
114
+
115
+ (defn gate? [args] (boolean (some #{:gate} args)))
116
+
117
+ (defn gates-of [args] (if (gate? args) (if (= :path (mode-of args)) 1 (voices-of args)) 0))
118
+
119
+ (defn stroke-of
120
+ "The stroke a reader~ path follows: its word that is not one of reader~'s own (nor of a head's on a ring~)."
121
+ [args]
122
+ (first (remove #{:path :x :y :gate :norm :d :speed :jump :mix} (filter keyword? args))))
123
+
124
+ (defn allocate
125
+ "Voices for a run of readings [[[id v] …] …]: a reading keeps the voice its id had at the step
126
+ before, a new id takes the first free voice (none if all V are taken). [{voice v} …]"
127
+ [readings V]
128
+ (first
129
+ (reduce (fn [[acc held] rd]
130
+ (let [ids (set (map first rd))
131
+ kept (into {} (filter (fn [[vid _]] (ids vid)) held))
132
+ held (reduce (fn [h [vid _]]
133
+ (if (contains? h vid) h
134
+ (if-let [free (first (remove (set (vals h)) (range V)))] (assoc h vid free) h)))
135
+ kept rd)]
136
+ [(conj acc (into {} (keep (fn [[vid v]] (when-let [c (held vid)] [c v])) rd))) held]))
137
+ [[] {}] readings)))
138
+
139
+ (defn readings
140
+ "What the canvas holds at each of n points of the span (as cv/read-along gives it, in stroke order), but
141
+ each stroke is only asked where it can pass: between its lowest and highest coordinate on that axis.
142
+ A canvas of short notes is crossed by one or two strokes at a time, not by all of them."
143
+ [d mode span n]
144
+ (let [k (if (= mode :y) 1 0)
145
+ logs [(cv/x-log? d) (cv/y-log? d)]
146
+ strokes (vec (for [[id s] (cv/sorted-strokes d) :let [cs (map (fn [p] (nth p k)) (:pts s))]]
147
+ [id (:pts s) (apply min cs) (apply max cs)]))]
148
+ (vec (for [i (range n)]
149
+ (let [v (cv/at-unit span (/ i (dec n)))]
150
+ (vec (mapcat (fn [[id pts lo hi]]
151
+ (when (and (<= lo v) (<= v hi))
152
+ (map-indexed (fn [j val] [(if (zero? j) id (keyword (str (name id) "-" (inc j)))) val])
153
+ (cv/crossings pts k v logs))))
154
+ strokes)))))))
155
+
156
+ (defn compute-table
157
+ "The buffer d sampled for reader~: a Float32Array of voices × table-size (NaN where nothing passes)."
158
+ [d mode V sid]
159
+ (let [n table-size tab (js/Float32Array. (* V n))]
160
+ (.fill tab js/NaN)
161
+ (case mode
162
+ :path (when-let [pts (cv/stroke-for d sid)]
163
+ (dotimes [i n]
164
+ (when-let [[x y] (cv/point-along d pts (/ i (dec n)))]
165
+ (aset tab i x)
166
+ (aset tab (+ n i) y))))
167
+ (let [span (if (= mode :y) (cv/y-range d) (cv/x-range d))]
168
+ (doseq [[i vs] (map-indexed vector (allocate (readings d mode span n) V)) [c v] vs]
169
+ (aset tab (+ (* c n) i) v))))
170
+ tab))
171
+
172
+ ;; Several reader~ often read the same canvas the same way, and a canvas that has not changed must not
173
+ ;; be sampled again: the tables are kept by what they depend on (the buffer compared by value).
174
+ (defonce tables (atom [])) ; [[key table] …], the newest last
175
+ (def tables-kept 16)
176
+
177
+ (defn table [d mode V sid]
178
+ (let [k [d mode V sid]]
179
+ (or (some (fn [[k2 t]] (when (= k k2) t)) @tables)
180
+ (let [t (compute-table d mode V sid)]
181
+ (swap! tables (fn [ts] (vec (take-last tables-kept (conj ts [k t])))))
182
+ t))))
183
+
184
+ (defn send-table! [node]
185
+ (when-let [w @(:worklet node)]
186
+ (when-let [t @(:pending node)]
187
+ (.postMessage (.-port w) #js {:tab t :n table-size :V (:V node) :G (:G node)
188
+ :span (some-> @(:span node) clj->js) :norm (or (:norm node) (= :path (:mode node)))})
189
+ (reset! (:pending node) nil))))
190
+
191
+ ;; ───────── a reader~ that reads a sound ─────────
192
+ ;; A sample box (kairotic.sounds) is a buffer too: then the reader~ plays it, the position 0…1 going from
193
+ ;; its start to its end, through a player worklet that takes the place of the table reader.
194
+
195
+ (defn route!
196
+ "Puts the table reader (:table), the player (:sound) or a ring~ (:ring: the position goes to the slot of the
197
+ ring this reader~ has, and what it reads comes back) between the position and the outlets."
198
+ [node which]
199
+ (let [w @(:worklet node) pl @(:player node) in (:in node)]
200
+ (doseq [x [w pl (:m node)] :when x]
201
+ (try (.disconnect in x) (catch :default _ nil)))
202
+ (doseq [x [w pl] :when x]
203
+ (try (.disconnect x) (catch :default _ nil)))
204
+ (when (and (= :ring @(:route node)) (not= which :ring)) (ringa/hook! node nil nil))
205
+ (if (= which :ring)
206
+ (.connect in (:m node) 0 1)
207
+ (when-let [x (if (= which :sound) pl w)]
208
+ (.connect in x) (.connect x (:split node))))
209
+ (reset! (:route node) which)))
210
+
211
+ (defn play-sound!
212
+ "Gives a reader~ the sound described by d: from this browser's store (or fetched from its URL), into
213
+ its player."
214
+ [node d]
215
+ (reset! (:route node) :sound)
216
+ (-> (snd/sound-for d)
217
+ (.then (fn [s]
218
+ (when (and @(:alive node) (= d @(:fed node)))
219
+ (if-not s
220
+ (api/report! (:id node) {:error (str "reader~: the sound of the sample is not in this browser"
221
+ " (recorded elsewhere): (load-sound! :bN) brings a file into it")} nil)
222
+ (-> (or @(:player node) (snd/player (:ac node) (:V node) (:G node)))
223
+ (js/Promise.resolve)
224
+ (.then (fn [pl]
225
+ (when @(:alive node)
226
+ (reset! (:player node) pl)
227
+ (snd/give! pl s (:norm node))
228
+ (when (= :sound @(:route node)) (route! node :sound))))))))))
229
+ (.catch (fn [e] (api/report! (:id node) {:error (str "reader~: " (or (.-message e) e))} nil)))))
230
+
231
+ ;; ───────── classes ─────────
232
+
233
+ (comp/define! "reader~"
234
+ {:doc "Reads a buffer at audio rate, as reader does once per message: a position signal on the left, the buffer on the right. The position is in the buffer's own units — the X axis of a canvas (Y with `reader~ y`), the time of a freqt, the seconds of a sample or a ring~ — or, with `norm`, from 0 to 1 (a phasor~ straight in); along a stroke (`reader~ path`) it is always 0…1. On a canvas or freqt: one signal outlet per voice, or x and y with path; where nothing passes a voice keeps its last value; with `gate`, one more outlet per voice, 1 where it has something. A sample: it plays it. A ring~: it reads there, or, with nothing on its left, follows the ring's head d behind, then a speed (reader~ d 1 speed 0.5; msg :d, :speed, :jump, :gain)."
235
+ :usage "reader~ [x|y|path [stroke]] [voices] [gate] [norm] [d s] [speed x] [jump s]"
236
+ :io (fn [b] [2 (+ (voices-of (:args b)) (gates-of (:args b)))]) :dynamic-io true
237
+ :reads-buffer true
238
+ :receive (fn [{:keys [inlet value]}]
239
+ (cond
240
+ (and (= inlet :audio) (:error value)) {:effects [[:print (:error value)]]}
241
+ ;; on a ring~: msg :d 2, :speed 0.5, :jump 1, :gain 0.5
242
+ (and (= inlet 0) (ringa/head-message value)) {:effects [[:head (ringa/head-message value)]]}
243
+ :else {}))
244
+ :audio {:create (fn [ac b _]
245
+ (let [args (:args b) V (voices-of args) G (gates-of args) C (+ V G)
246
+ in (.createGain ac)
247
+ split (.createChannelSplitter ac C)
248
+ node {:in in :split split :V V :G G :mode (mode-of args) :stroke (stroke-of args)
249
+ :ac ac :id (:id b) :player (atom nil) :route (atom :table)
250
+ :worklet (atom nil) :pending (atom nil) :fed (atom ::none) :alive (atom true)
251
+ ;; the position: in the buffer's units (the canvas's axis, seconds…) or, with norm, 0…1
252
+ :span (atom nil) :norm (boolean (some #{:norm} args))
253
+ ;; as a head of a ring~: the position into channel 1 of its slot, what it reads into the outlets
254
+ :m (.createChannelMerger ac 2) :out split :ring (atom nil) :slot (atom nil)
255
+ :opts (atom (merge {:mode "follow"} (ringa/head-args args)))
256
+ :inlets [[in 0]]
257
+ :outlets (vec (for [c (range C)] [split c]))}]
258
+ (-> (ready ac)
259
+ (.then (fn [_]
260
+ (when @(:alive node)
261
+ (let [w (js/AudioWorkletNode. ac "kairotic-reader"
262
+ #js {:numberOfInputs 1 :numberOfOutputs 1
263
+ :outputChannelCount #js [C]
264
+ :channelCount 1 :channelCountMode "explicit"})]
265
+ (reset! (:worklet node) w)
266
+ (when (= :table @(:route node)) (route! node :table))
267
+ (send-table! node)))))
268
+ (.catch (fn [e] (js/console.error "reader~" e))))
269
+ node))
270
+ :feed (fn [node d]
271
+ (cond
272
+ (ringa/handle? d) (do (route! node :ring) (ringa/hook! node d "read"))
273
+ (snd/sample? d) (do (when (= :ring @(:route node)) (route! node :table)) (play-sound! node d))
274
+ :else
275
+ (do (when (#{:sound :ring} @(:route node)) (route! node :table))
276
+ (reset! (:span node) (let [d (or d cv/empty)]
277
+ (case (:mode node) :path nil :y (cv/y-range d) (cv/x-range d))))
278
+ (reset! (:pending node) (table (or d cv/empty) (:mode node) (:V node) (:stroke node)))
279
+ (send-table! node))))
280
+ ;; on a ring~: a position signal on the left, it reads there; without one, it follows the ring's head
281
+ :wired (fn [node ins] (ringa/set-head! node {:mode (if (contains? ins 0) "pos" "follow")}))
282
+ :effects {:head (fn [node x _] (ringa/set-head! node x))}
283
+ :dispose (fn [node]
284
+ (reset! (:alive node) false)
285
+ (ringa/hook! node nil nil)
286
+ (doseq [x [@(:worklet node) @(:player node)] :when x] (try (.disconnect x) (catch :default _ nil))))}})
287
+
288
+ (comp/define! "phasor~"
289
+ {:doc "A ramp signal from 0 to 1, repeated hz times per second (0.25 = once every 4 seconds). A number on the left changes hz."
290
+ :usage "phasor~ [hz]"
291
+ :io [1 1]
292
+ :receive (fn [{:keys [value]}] (if (comp/num-of value) {:effects [[:freq (comp/num-of value)]]} {}))
293
+ :audio {:create (fn [ac b _]
294
+ (let [out (.createGain ac)
295
+ hz (atom (or (comp/num-of (first (:args b))) 1))
296
+ node {:out out :hz hz :worklet (atom nil) :alive (atom true) :outlets [[out 0]]}]
297
+ (-> (ready ac)
298
+ (.then (fn [_]
299
+ (when @(:alive node)
300
+ (let [w (js/AudioWorkletNode. ac "kairotic-phasor" #js {:numberOfInputs 0 :numberOfOutputs 1
301
+ :outputChannelCount #js [1]})]
302
+ (set! (.-value (.get (.-parameters w) "freq")) @hz)
303
+ (.connect w out)
304
+ (reset! (:worklet node) w)))))
305
+ (.catch (fn [e] (js/console.error "phasor~" e))))
306
+ node))
307
+ :effects {:freq (fn [node x at]
308
+ (reset! (:hz node) x)
309
+ (when-let [w @(:worklet node)] (.setValueAtTime (.get (.-parameters w) "freq") x at)))}
310
+ :dispose (fn [node]
311
+ (reset! (:alive node) false)
312
+ (when-let [w @(:worklet node)] (try (.disconnect w) (catch :default _ nil))))}})
313
+
314
+ (comp/define! "sig~"
315
+ {:doc "A constant signal (a frequency for osc~, a factor for gain~, a position for reader~). A number on the left changes it."
316
+ :usage "sig~ [value]"
317
+ :io [1 1]
318
+ :receive (fn [{:keys [value]}] (if (comp/num-of value) {:effects [[:value (comp/num-of value)]] :show (comp/num-of value)} {}))
319
+ :audio {:create (fn [ac b _]
320
+ (let [c (.createConstantSource ac)]
321
+ (set! (.. c -offset -value) (or (comp/num-of (first (:args b))) 0))
322
+ (.start c)
323
+ {:c c :outlets [[c 0]]}))
324
+ :effects {:value (fn [node x at] (.setValueAtTime (.-offset (:c node)) x at))}
325
+ :dispose (fn [node] (try (.stop (:c node)) (catch :default _ nil)))}})
326
+
327
+ ;; adsr~ moved to the package @kairotic/synth (Study 14)