46256e7Marimba lab: per-key tuned bars, coupled resonator tubes, SoundFont exportJeremy Magland 1// three.js view of one bar with its resonator tube: click the top face to strike.
3import * as THREE from 'three';
4import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
5import { thickness } from './bar.js';
7const S = 0.004; // scene units per mm
9function rosewoodTexture() {
10 const c = document.createElement('canvas');
11 c.width = 1024; c.height = 256;
12 const g = c.getContext('2d');
13 g.fillStyle = '#6a2c1c';
14 g.fillRect(0, 0, c.width, c.height);
15 for (let y = 0; y < c.height; y++) {
16 const v = Math.sin(y * 0.21 + Math.sin(y * 0.031) * 4) * 0.5 + 0.5;
17 g.fillStyle = `rgba(35,10,5,${0.06 + 0.3 * v * v * v})`;
18 g.fillRect(0, y, c.width, 1);
19 }
20 for (let i = 0; i < 90; i++) {
21 g.strokeStyle = `rgba(${i % 3 ? '25,8,4' : '150,80,50'},${0.05 + Math.random() * 0.12})`;
22 g.lineWidth = 1 + Math.random() * 1.5;
23 g.beginPath();
24 const y = Math.random() * c.height;
25 g.moveTo(0, y);
26 for (let x = 0; x <= c.width; x += 32) g.lineTo(x, y + Math.sin(x * 0.006 + i) * 5);
27 g.stroke();
28 }
29 const t = new THREE.CanvasTexture(c);
30 t.colorSpace = THREE.SRGBColorSpace;
31 t.wrapS = t.wrapT = THREE.RepeatWrapping;
32 return t;
33}
35export class BarView {
36 constructor(container, onPick) {
37 this.container = container;
38 this.onPick = onPick;
39 const r = (this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }));
40 r.setPixelRatio(Math.min(2, window.devicePixelRatio));
41 container.appendChild(r.domElement);
42 this.scene = new THREE.Scene();
43 this.camera = new THREE.PerspectiveCamera(35, 1, 0.01, 100);
44 this.camera.position.set(0.9, 1.1, 2.4);
45 this.controls = new OrbitControls(this.camera, r.domElement);
46 this.controls.enableDamping = true;
47 this.scene.add(new THREE.HemisphereLight(0xffffff, 0x404050, 1.3));
48 const sun = new THREE.DirectionalLight(0xffffff, 2.4);
49 sun.position.set(2, 4, 3);
50 this.scene.add(sun);
51 const fill = new THREE.DirectionalLight(0xffffff, 0.6);
52 fill.position.set(-3, -1, -2);
53 this.scene.add(fill);
54 this.tex = rosewoodTexture();
55 this.group = new THREE.Group();
56 this.scene.add(this.group);
58 // mallet: yarn head on a rattan stick
59 this.mallet = new THREE.Group();
60 const R = 17 * S;
61 const head = new THREE.Mesh(new THREE.SphereGeometry(R, 24, 16), new THREE.MeshStandardMaterial({ color: 0x5b6f8f, roughness: 0.95 }));
62 head.position.y = R;
63 const stick = new THREE.Mesh(new THREE.CylinderGeometry(4 * S, 4 * S, 380 * S, 12), new THREE.MeshStandardMaterial({ color: 0xd8c39a }));
64 stick.position.set(0, R + 80 * S, -175 * S);
65 stick.rotation.x = -Math.PI / 2.6;
66 this.mallet.add(head, stick);
67 this.scene.add(this.mallet);
68 this.mic = new THREE.Mesh(new THREE.SphereGeometry(9 * S, 16, 12), new THREE.MeshStandardMaterial({ color: 0x3d8bfd, emissive: 0x112244 }));
69 this.scene.add(this.mic);
70 this.hitT = -1;
72 const ray = new THREE.Raycaster();
73 let down = null;
74 r.domElement.addEventListener('pointerdown', (e) => (down = [e.clientX, e.clientY]));
75 r.domElement.addEventListener('pointerup', (e) => {
76 if (!down || Math.hypot(e.clientX - down[0], e.clientY - down[1]) > 4 || !this.topPick) return;
77 const rect = r.domElement.getBoundingClientRect();
78 const ndc = new THREE.Vector2(((e.clientX - rect.left) / rect.width) * 2 - 1, -((e.clientY - rect.top) / rect.height) * 2 + 1);
79 ray.setFromCamera(ndc, this.camera);
80 const hit = ray.intersectObject(this.topPick)[0];
81 if (hit) {
82 const p = this.toBar(hit.point);
83 this.onPick(p[0], p[1]);
84 }
85 });
86 new ResizeObserver(() => this.resize()).observe(container);
87 this.resize();
88 const loop = () => {
89 requestAnimationFrame(loop);
90 this.animate();
91 this.controls.update();
92 r.render(this.scene, this.camera);
93 };
94 loop();
95 }
97 // bar mm -> scene (bar centre at the origin)
98 toScene(x, y, z) {
99 const b = this.bar;
100 return new THREE.Vector3((x - b.L / 2) * S, (z - b.h0 / 2) * S, (b.W / 2 - y) * S);
101 }
102 toBar(v) {
103 const b = this.bar;
104 return [v.x / S + b.L / 2, b.W / 2 - v.z / S, v.y / S + b.h0 / 2];
105 }
107 /**
108 * bar: design; tube: { a, L (mm), gap } or null; mic: [x,y,z] mm; nodes: x positions (mm)
109 */
110 setScene(bar, tube, mic, nodes = []) {
111 const first = !this.bar;
112 const resized = !this.bar || Math.abs(this.bar.L - bar.L) > 1;
113 this.bar = bar;
114 this.group.clear();
115 // side profile in the x-z plane, extruded across the width
116 const sh = new THREE.Shape();
117 const P = (x, z) => [(x - bar.L / 2) * S, (z - bar.h0 / 2) * S];
118 sh.moveTo(...P(0, bar.h0));
119 sh.lineTo(...P(bar.L, bar.h0));
120 const n = 160;
121 for (let i = n; i >= 0; i--) {
122 const x = (i / n) * bar.L;
123 sh.lineTo(...P(x, bar.h0 - thickness(bar, x)));
124 }
125 sh.closePath();
126 const geo = new THREE.ExtrudeGeometry(sh, { depth: bar.W * S, bevelEnabled: false, curveSegments: 1 });
127 geo.translate(0, 0, (-bar.W * S) / 2);
128 const tex = this.tex.clone();
129 tex.repeat.set(1.2, 4);
130 tex.needsUpdate = true;
131 const mesh = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ map: tex, roughness: 0.45 }));
132 this.group.add(mesh);
134 // support cords at the f1 nodes
135 const cordMat = new THREE.MeshStandardMaterial({ color: 0x222222, roughness: 0.9 });
136 for (const x of nodes) {
137 const c = new THREE.Mesh(new THREE.CylinderGeometry(1.6 * S, 1.6 * S, (bar.W + 60) * S, 8), cordMat);
138 c.rotation.x = Math.PI / 2;
139 c.position.copy(this.toScene(x, bar.W / 2, -1.6));
140 this.group.add(c);
141 }
143 // resonator
144 if (tube) {
145 const metal = new THREE.MeshStandardMaterial({ color: 0xc9a75a, metalness: 0.85, roughness: 0.32, side: THREE.DoubleSide });
146 const pipe = new THREE.Mesh(new THREE.CylinderGeometry(tube.a * S, tube.a * S, tube.L * S, 48, 1, true), metal);
147 pipe.position.copy(this.toScene(bar.L / 2, bar.W / 2, -tube.gap - tube.L / 2));
148 const inner = new THREE.Mesh(
149 new THREE.CylinderGeometry(tube.a * S * 0.985, tube.a * S * 0.985, tube.L * S, 48, 1, true),
150 new THREE.MeshStandardMaterial({ color: 0x1b140c, roughness: 1, side: THREE.BackSide }),
151 );
152 inner.position.copy(pipe.position);
153 const cap = new THREE.Mesh(new THREE.CircleGeometry(tube.a * S, 48), metal);
154 cap.rotation.x = Math.PI / 2;
155 cap.position.copy(this.toScene(bar.L / 2, bar.W / 2, -tube.gap - tube.L));
156 this.group.add(pipe, inner, cap);
157 }
159 // invisible pick plane + mode overlay on the top face
160 this.topPick = new THREE.Mesh(new THREE.PlaneGeometry(bar.L * S, bar.W * S), new THREE.MeshBasicMaterial({ visible: false }));
161 this.topPick.rotation.x = -Math.PI / 2;
162 this.topPick.position.copy(this.toScene(bar.L / 2, bar.W / 2, bar.h0 + 0.2));
163 this.group.add(this.topPick);
164 this.overlay = new THREE.Mesh(
165 new THREE.PlaneGeometry(bar.L * S, bar.W * S),
166 new THREE.MeshBasicMaterial({ transparent: true, opacity: 0.85, depthWrite: false }),
167 );
168 this.overlay.rotation.x = -Math.PI / 2;
169 this.overlay.position.copy(this.toScene(bar.L / 2, bar.W / 2, bar.h0 + 0.3));
170 this.overlay.visible = false;
171 this.group.add(this.overlay);
172 this.mic.position.copy(this.toScene(...mic));
173 if (this.strike) this.setStrike(...this.strike);
174 if (resized) this.frame(first);
175 }
177 // keep the camera direction, set the distance so the bar fills the view
178 frame(first) {
179 const target = new THREE.Vector3(0, -40 * S, 0);
180 const d = Math.max(0.8, this.bar.L * S * 2.0) * Math.max(1, 1.3 / this.camera.aspect);
181 const dir = first ? new THREE.Vector3(0.3, 0.85, 1).normalize() : this.camera.position.clone().sub(this.controls.target).normalize();
182 this.controls.target.copy(target);
183 this.camera.position.copy(target).addScaledVector(dir, d);
184 }
186 setStrike(x, y) {
187 this.strike = [x, y];
188 if (!this.bar) return;
189 this.malletRest = this.toScene(x, y, this.bar.h0);
190 this.mallet.position.copy(this.malletRest).add(new THREE.Vector3(0, 60 * S, 0));
191 }
193 hit() { this.hitT = performance.now(); }
195 animate() {
196 if (!this.malletRest) return;
197 const lift = 60 * S;
198 let h = lift;
199 if (this.hitT > 0) {
200 const t = (performance.now() - this.hitT) / 1000;
201 h = t < 0.03 ? lift * (1 - t / 0.03) : t < 0.25 ? lift * Math.sin(((t - 0.03) / 0.22) * Math.PI / 2) : lift;
202 }
203 this.mallet.position.copy(this.malletRest).add(new THREE.Vector3(0, h, 0));
204 }
206 // values[ny][nx] in [-1,1] (row j = y from the front edge), or null to hide
207 setOverlay(nx, ny, values) {
208 if (!values) { this.overlay.visible = false; return; }
209 const c = document.createElement('canvas');
210 c.width = nx; c.height = ny;
211 const g = c.getContext('2d');
212 const img = g.createImageData(nx, ny);
213 for (let j = 0; j < ny; j++) {
214 for (let i = 0; i < nx; i++) {
215 const v = values[j * nx + i];
216 // canvas row 0 is the plane's far (back) edge, i.e. y = W
217 const o = ((ny - 1 - j) * nx + i) * 4;
218 const [r, gg, b] = colormap(v);
219 img.data[o] = r; img.data[o + 1] = gg; img.data[o + 2] = b; img.data[o + 3] = 255;
220 }
221 }
222 g.putImageData(img, 0, 0);
223 const t = new THREE.CanvasTexture(c);
224 t.colorSpace = THREE.SRGBColorSpace;
225 t.magFilter = THREE.LinearFilter;
226 this.overlay.material.map?.dispose();
227 this.overlay.material.map = t;
228 this.overlay.material.needsUpdate = true;
229 this.overlay.visible = true;
230 }
232 resize() {
233 const w = this.container.clientWidth, h = this.container.clientHeight;
234 if (!w || !h) return;
235 this.renderer.setSize(w, h);
236 this.camera.aspect = w / h;
237 this.camera.updateProjectionMatrix();
238 if (this.bar) this.frame(false);
239 }
240}
242// signed value in [-1,1] -> blue / white / red
243function colormap(v) {
244 const a = Math.min(1, Math.abs(v));
245 return v >= 0 ? [255, 255 * (1 - a), 255 * (1 - a)] : [255 * (1 - a), 255 * (1 - a), 255];
246}