jevstrudel.git / packages / hydra / hydra.mjs
1import { getDrawContext } from '@strudel/draw';
2import { controls, getTime, reify } from '@strudel/core';
3
4let latestOptions;
5let hydra;
6
7export async function initHydra(options = {}) {
8  // reset if options have changed since last init
9  if (latestOptions && JSON.stringify(latestOptions) !== JSON.stringify(options)) {
10    document.getElementById('hydra-canvas')?.remove();
11  }
12  latestOptions = options;
13  //load and init hydra
14  if (!document.getElementById('hydra-canvas')) {
15    const {
16      src = 'https://unpkg.com/hydra-synth',
17      feedStrudel = false,
18      contextType = 'webgl',
19      pixelRatio = 1,
20      pixelated = true,
21      ...hydraConfig
22    } = {
23      detectAudio: false,
24      ...options,
25    };
26    const { canvas } = getDrawContext('hydra-canvas', { contextType, pixelRatio, pixelated });
27    hydraConfig.canvas = canvas;
28
29    await import(/* @vite-ignore */ src);
30    /* eslint-disable-next-line */
31    hydra = new Hydra(hydraConfig);
32    if (feedStrudel) {
33      const { canvas } = getDrawContext();
34      canvas.style.display = 'none';
35      hydra.synth.s0.init({ src: canvas });
36    }
37  }
38  return hydra;
39}
40
41export function clearHydra() {
42  if (hydra) {
43    hydra.hush();
44  }
45  globalThis.s0?.clear();
46  document.getElementById('hydra-canvas')?.remove();
47  globalThis.speed = controls.speed;
48  globalThis.shape = controls.shape;
49}
50
51export const H = (p) => () => reify(p).queryArc(getTime(), getTime())[0].value;