roamwright 0.4.0 → 0.20.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 (139) hide show
  1. package/CONTRIBUTING.md +3 -1
  2. package/README.md +11 -34
  3. package/geometry/bedding.js +141 -0
  4. package/geometry/builder-cells.js +42 -0
  5. package/geometry/builder-frame.js +47 -0
  6. package/geometry/builder.js +189 -177
  7. package/geometry/cell-mask.js +25 -0
  8. package/geometry/creased-sheet.js +34 -34
  9. package/geometry/ear.js +36 -36
  10. package/geometry/erosion.js +65 -42
  11. package/geometry/face-grid.js +65 -65
  12. package/geometry/foliage.js +10 -10
  13. package/geometry/hair-gathers.js +41 -41
  14. package/geometry/hair-locks.js +41 -41
  15. package/geometry/hair-patch.js +18 -18
  16. package/geometry/hair-shell.js +31 -31
  17. package/geometry/head-profile.js +15 -15
  18. package/geometry/head-shape.js +77 -77
  19. package/geometry/heightfield.js +27 -18
  20. package/geometry/index-parts.js +2 -2
  21. package/geometry/instance-visibility.js +12 -12
  22. package/geometry/instances.js +15 -15
  23. package/geometry/outline-grid.js +7 -7
  24. package/geometry/part-ranges.js +3 -3
  25. package/geometry/path-field.js +63 -33
  26. package/geometry/placement.js +52 -52
  27. package/geometry/point-buckets.js +50 -0
  28. package/geometry/primitives.js +63 -47
  29. package/geometry/sagging-tube.js +27 -27
  30. package/geometry/sampled-surface.js +109 -77
  31. package/geometry/scatter-grid.js +46 -6
  32. package/geometry/sculpt.js +93 -93
  33. package/geometry/shore-grid.js +77 -34
  34. package/geometry/strata-field.js +92 -92
  35. package/geometry/strata-tiles.js +91 -91
  36. package/geometry/stream.js +70 -48
  37. package/geometry/terrain-chunks.js +87 -82
  38. package/geometry/terrain-extension.js +6 -6
  39. package/index.js +5 -0
  40. package/math/cell-edge.js +16 -16
  41. package/math/cell-key.js +6 -0
  42. package/math/circle-clearances.js +19 -0
  43. package/math/cloth-textures.js +6 -6
  44. package/math/cloud-textures.js +20 -20
  45. package/math/color.js +14 -14
  46. package/math/curve.js +22 -22
  47. package/math/mountain-ranges.js +216 -165
  48. package/math/noise.js +101 -49
  49. package/math/particle-noise.js +28 -28
  50. package/math/periodic.js +5 -5
  51. package/math/random.js +24 -15
  52. package/math/rectangles.js +52 -0
  53. package/math/rock-texture.js +7 -7
  54. package/math/scalar.js +5 -5
  55. package/math/surface-textures.js +54 -54
  56. package/motion/arm-reach.js +24 -24
  57. package/motion/ballistic-arc.js +11 -0
  58. package/motion/biped-cycle.js +44 -0
  59. package/motion/biped-leg.js +37 -0
  60. package/motion/biped-stride.js +98 -122
  61. package/motion/contact-transition.js +33 -0
  62. package/motion/crowd-alarms.js +39 -39
  63. package/motion/crowd-routine.js +94 -65
  64. package/motion/daily-clock.js +9 -9
  65. package/motion/deck-surface.js +38 -0
  66. package/motion/ground-lookahead.js +5 -5
  67. package/motion/instance-sight.js +8 -8
  68. package/motion/player.js +36 -28
  69. package/motion/quadruped.js +155 -155
  70. package/motion/spaces.js +32 -32
  71. package/motion/weather.js +73 -24
  72. package/motion/wind.js +32 -13
  73. package/package.json +7 -3
  74. package/rendering/caster-motion.js +5 -5
  75. package/rendering/cell-lod.js +138 -82
  76. package/rendering/cloud-dome.js +28 -28
  77. package/rendering/cloud-field.js +2 -2
  78. package/rendering/compilation-schedule.js +68 -11
  79. package/rendering/contact-shadows.js +2 -2
  80. package/rendering/context.js +12 -0
  81. package/rendering/crowd-skinning.js +13 -13
  82. package/rendering/crust.js +18 -12
  83. package/rendering/daylight.js +3 -3
  84. package/rendering/detail-range.js +28 -0
  85. package/rendering/dispose-meshes.js +18 -0
  86. package/rendering/dof.js +9 -9
  87. package/rendering/eye-adapt.js +14 -14
  88. package/rendering/far-shadow.js +8 -8
  89. package/rendering/flocks.js +78 -78
  90. package/rendering/garment-material.js +17 -17
  91. package/rendering/glow-lines.js +13 -13
  92. package/rendering/hair-strands.js +20 -20
  93. package/rendering/height-probe.js +149 -19
  94. package/rendering/label-layout.js +46 -0
  95. package/rendering/label-range.js +38 -0
  96. package/rendering/light-budget.js +52 -52
  97. package/rendering/light-shafts.js +23 -23
  98. package/rendering/local-lights.js +15 -4
  99. package/rendering/material-lod.js +49 -49
  100. package/rendering/particle-emitters.js +90 -90
  101. package/rendering/particles.js +78 -67
  102. package/rendering/piece-batch.js +17 -6
  103. package/rendering/planar-reflection.js +38 -38
  104. package/rendering/post-shaders.js +17 -13
  105. package/rendering/post.js +71 -71
  106. package/rendering/rain-streaks.js +67 -0
  107. package/rendering/road-surface.js +11 -11
  108. package/rendering/sea-shaders.js +11 -11
  109. package/rendering/shader-warmup.js +29 -16
  110. package/rendering/shadow-alignment.js +4 -4
  111. package/rendering/shadow-depth.js +7 -7
  112. package/rendering/sky-occlusion.js +16 -16
  113. package/rendering/sky.js +16 -6
  114. package/rendering/stage-lights.js +6 -6
  115. package/rendering/static-point-shadow.js +3 -3
  116. package/rendering/still-casters.js +1 -1
  117. package/rendering/strata-material.js +10 -10
  118. package/rendering/stream-flow.js +10 -10
  119. package/rendering/taa.js +26 -26
  120. package/rendering/talus.js +15 -15
  121. package/rendering/terrain-rock.js +7 -7
  122. package/rendering/texture-fills.js +8 -8
  123. package/rendering/textures.js +28 -28
  124. package/rendering/wakes.js +24 -24
  125. package/rendering/water-material.js +36 -23
  126. package/rendering/world-matrices.js +38 -38
  127. package/runtime/diagnostic-log.js +2 -2
  128. package/runtime/first-use.js +33 -28
  129. package/runtime/frame-pacing.js +33 -0
  130. package/runtime/gpu-timing.js +7 -7
  131. package/runtime/grid-cache.js +1 -1
  132. package/runtime/grid-rows.js +44 -5
  133. package/runtime/hand-over.js +41 -23
  134. package/runtime/pool.js +58 -16
  135. package/runtime/quality-fit.js +1 -1
  136. package/runtime/search.js +22 -22
  137. package/runtime/spatial-audio.js +13 -13
  138. package/runtime/withdrawable-task.js +35 -0
  139. package/runtime/worker.js +7 -0
@@ -29,31 +29,36 @@ export function createHandOver({ painted, frameShare }) {
29
29
  if (drawn === was) handed = 0;
30
30
  }
31
31
 
32
- const heldBytes = geometry => Object.values(geometry.attributes).reduce((sum, a) => sum + (a.array?.byteLength ?? 0), 0);
33
- const letsGo = geometry => Object.values(geometry.attributes).some(a => Object.hasOwn(a, 'onUploadCallback'));
32
+ const heldBytes = geometry => Object.values(geometry.attributes).reduce((sum, attribute) => sum + (attribute.array?.byteLength ?? 0), 0);
33
+ const letsGo = geometry => Object.values(geometry.attributes).some(attribute => Object.hasOwn(attribute, 'onUploadCallback'));
34
34
 
35
- function handToCard(roots) {
35
+ function handToCard(roots, signal) {
36
+ const turn = handing.then(() => handOver(roots, signal));
37
+ handing = turn.catch(() => {});
38
+ return turn;
39
+ }
40
+ async function handOver(roots, signal) {
41
+ signal?.throwIfAborted();
36
42
  const found = new Map();
37
43
  for (const root of roots)
38
44
  root.traverse(o => {
39
45
  if (o.isMesh && !o.isSkinnedMesh && !inHand.has(o.geometry) && heldBytes(o.geometry) && letsGo(o.geometry))
40
46
  found.set(o.geometry, [...(found.get(o.geometry) ?? []), o]);
41
47
  });
42
- const turn = handing.then(() => handOver(found));
43
- handing = turn.catch(() => {});
44
- return turn;
45
- }
46
- async function handOver(found) {
47
- let batch = [];
48
+
49
+ const batch = [];
50
+ const restoreBatch = () => { restore(batch); batch.length = 0; };
48
51
  const flush = async () => {
52
+ signal?.addEventListener('abort', restoreBatch, { once: true });
49
53
  try {
50
54
  await nextShare();
51
55
  } finally {
52
- restore(batch);
53
- batch = [];
56
+ signal?.removeEventListener('abort', restoreBatch);
57
+ restoreBatch();
54
58
  }
55
59
  };
56
60
  for (const [geometry, meshes] of found) {
61
+ signal?.throwIfAborted();
57
62
  if (inHand.has(geometry)) continue;
58
63
  inHand.add(geometry);
59
64
  const range = { ...geometry.drawRange },
@@ -64,7 +69,7 @@ export function createHandOver({ painted, frameShare }) {
64
69
  m.frustumCulled = false;
65
70
  }
66
71
  // The first render uploads everything queued before the render loop started.
67
- if (!drawn) {
72
+ if (!drawn && !signal) {
68
73
  beforeFirst.push([geometry, meshes, range, was]);
69
74
  continue;
70
75
  }
@@ -73,6 +78,7 @@ export function createHandOver({ painted, frameShare }) {
73
78
  if (frameFull()) await flush();
74
79
  }
75
80
  if (batch.length) await flush();
81
+ signal?.throwIfAborted();
76
82
  }
77
83
  function restore(handedOver) {
78
84
  for (const [geometry, meshes, range, was] of handedOver) {
@@ -82,19 +88,31 @@ export function createHandOver({ painted, frameShare }) {
82
88
  }
83
89
  }
84
90
 
85
- async function paced(steps) {
86
- let step;
87
- while (!(step = steps.next()).done) {
88
- countHanded(step.value);
89
- if (frameFull()) await nextShare();
91
+ async function paced(steps, signal) {
92
+ try {
93
+ while (true) {
94
+ signal?.throwIfAborted();
95
+ const step = steps.next();
96
+ if (step.done) return step.value;
97
+ countHanded(step.value);
98
+ if (frameFull()) await nextShare();
99
+ }
100
+ } catch (error) {
101
+ steps.return?.();
102
+ throw error;
90
103
  }
91
- return step.value;
92
104
  }
93
- function drain(steps) {
94
- let step;
95
- do step = steps.next();
96
- while (!step.done);
97
- return step.value;
105
+ function drain(steps, signal) {
106
+ try {
107
+ while (true) {
108
+ signal?.throwIfAborted();
109
+ const step = steps.next();
110
+ if (step.done) return step.value;
111
+ }
112
+ } catch (error) {
113
+ steps.return?.();
114
+ throw error;
115
+ }
98
116
  }
99
117
 
100
118
  const anyFrameDrawn = () => drawn > 0;
package/runtime/pool.js CHANGED
@@ -1,12 +1,36 @@
1
+ /**
2
+ * Schedule jobs across workers, prepare per-worker data and release idle workers.
3
+ * @module
4
+ */
5
+
6
+ /** The pool can use every logical processor the browser exposes beyond its main thread. */
7
+ export function workerCapacity(cores = globalThis.navigator?.hardwareConcurrency) {
8
+ return Number.isFinite(cores) ? Math.max(1, Math.floor(cores) - 1) : 1;
9
+ }
10
+
1
11
  /**
2
12
  * Route weighted jobs to FIFO workers. Each worker receives { job, input } and
3
13
  * replies in order with { result } or { error }. Supply prestarted workers to
4
- * adopt them immediately, and a synchronous factory to restart after idle.
14
+ * adopt them immediately. Supply startWorkers for a fixed pool, or createWorker
15
+ * for a pool that grows with concurrent work up to maxWorkers. A broadcast
16
+ * initializes every worker, so later jobs see the state it set.
17
+ * @param {object} [options] - Worker factories and scheduling settings.
18
+ * @param {() => Worker} [options.createWorker] - Synchronously create one worker when demand grows.
19
+ * @param {() => Worker[]} [options.startWorkers] - Start the fixed pool on first use.
20
+ * @param {Worker[]} [options.initialWorkers] - Adopt already running workers.
21
+ * @param {number} [options.maxWorkers] - Upper bound for an elastic pool.
22
+ * @param {number} [options.idleMs] - Milliseconds before idle workers terminate.
23
+ * @param {(message: string) => void} [options.warn] - Receive worker startup and job failure messages.
5
24
  */
6
- export function createPool({ startWorkers, initialWorkers, idleMs = 4000, warn = message => console.warn(message) } = {}) {
25
+ export function createPool({
26
+ startWorkers, createWorker, initialWorkers, maxWorkers = workerCapacity(),
27
+ idleMs = 4000, warn = message => console.warn(message),
28
+ } = {}) {
7
29
  const slots = [];
8
30
  const preparations = new Map();
9
- let broken = typeof startWorkers !== 'function',
31
+ const elastic = typeof createWorker === 'function';
32
+ let capacity = Number.isFinite(maxWorkers) ? Math.max(1, Math.floor(maxWorkers)) : 1;
33
+ let broken = !elastic && typeof startWorkers !== 'function',
10
34
  idle = 0,
11
35
  held = 0;
12
36
 
@@ -29,14 +53,24 @@ export function createPool({ startWorkers, initialWorkers, idleMs = 4000, warn =
29
53
  rest();
30
54
  for (const task of waiting) task.refuse(new Error('pool: ' + reason));
31
55
  }
32
- function adopt(workers) {
33
- for (const worker of workers) {
34
- const slot = { worker, tasks: [], holds: new Set() };
35
- worker.onmessage = ({ data }) => finish(slot, data);
36
- worker.onerror = event => giveUp(event.message || 'a worker could not start');
37
- worker.onmessageerror = () => giveUp('an answer could not be read');
38
- slots.push(slot);
56
+ function attach(worker) {
57
+ const slot = { worker, tasks: [], holds: new Set() };
58
+ worker.onmessage = ({ data }) => finish(slot, data);
59
+ worker.onerror = event => giveUp(event.message || 'a worker could not start');
60
+ worker.onmessageerror = () => giveUp('an answer could not be read');
61
+ slots.push(slot);
62
+ }
63
+ function grow() {
64
+ if (!elastic || broken || slots.length >= capacity) return;
65
+ try {
66
+ attach(createWorker());
67
+ } catch (error) {
68
+ if (!slots.length) giveUp(error.message);
69
+ else capacity = slots.length; // A browser resource limit can be lower than its hardware count.
39
70
  }
71
+ }
72
+ function adopt(workers) {
73
+ for (const worker of workers) attach(worker);
40
74
  if (!workers.length || workers.some(worker => worker.failed)) giveUp('the workers could not start');
41
75
  else restWhenIdle();
42
76
  }
@@ -89,7 +123,8 @@ export function createPool({ startWorkers, initialWorkers, idleMs = 4000, warn =
89
123
  function awake() {
90
124
  if (!broken && !slots.length) {
91
125
  try {
92
- adopt(startWorkers());
126
+ if (elastic) grow();
127
+ else adopt(startWorkers());
93
128
  } catch (error) {
94
129
  giveUp(error.message);
95
130
  }
@@ -101,7 +136,7 @@ export function createPool({ startWorkers, initialWorkers, idleMs = 4000, warn =
101
136
  const unheard = () => {};
102
137
  const load = slot => slot.tasks.reduce((sum, task) => sum + task.cost, 0);
103
138
  // Costs include both running and queued jobs. Dispatch immediately, even when the main thread is busy.
104
- const leastBusy = list => list.reduce((a, b) => (load(b) < load(a) ? b : a));
139
+ const leastBusy = list => list.reduce((leastLoaded, candidate) => (load(candidate) < load(leastLoaded) ? candidate : leastLoaded));
105
140
  // Register the input to send once per worker before a job that names this preparation.
106
141
  function prepare(name, input, cost = 1) {
107
142
  preparations.set(name, { input, cost });
@@ -109,6 +144,7 @@ export function createPool({ startWorkers, initialWorkers, idleMs = 4000, warn =
109
144
  }
110
145
  function run(job, input, transfer = [], needs = null, cost = 1) {
111
146
  if (!awake().length) return noWorkers();
147
+ if (elastic && slots.every(slot => slot.tasks.length)) grow();
112
148
  let least = leastBusy(slots);
113
149
  if (needs && !least.holds.has(needs)) {
114
150
  const holding = slots.filter(slot => slot.holds.has(needs)),
@@ -129,9 +165,11 @@ export function createPool({ startWorkers, initialWorkers, idleMs = 4000, warn =
129
165
  function spread(name, count) {
130
166
  const preparation = preparations.get(name);
131
167
  if (!preparation) return;
132
- const others = awake().filter(slot => !slot.holds.has(name)),
168
+ if (!awake().length) return;
169
+ while (elastic && slots.length < Math.min(count, capacity)) grow();
170
+ const others = slots.filter(slot => !slot.holds.has(name)),
133
171
  more = Math.min(count, slots.length) - (slots.length - others.length);
134
- for (const slot of others.sort((a, b) => load(a) - load(b)).slice(0, Math.max(0, more))) {
172
+ for (const slot of others.sort((firstSlot, secondSlot) => load(firstSlot) - load(secondSlot)).slice(0, Math.max(0, more))) {
135
173
  slot.holds.add(name);
136
174
  send(slot, name, preparation.input, [], preparation.cost, null, name).catch(unheard);
137
175
  }
@@ -144,8 +182,12 @@ export function createPool({ startWorkers, initialWorkers, idleMs = 4000, warn =
144
182
  slot.holds.add(job);
145
183
  }
146
184
  }
147
- function runOnEach(job, input) {
148
- if (!awake().length) return noWorkers();
185
+ /** Broadcast a job to every worker. Set `activeOnly` to reach existing workers without creating more. */
186
+ function runOnEach(job, input, { activeOnly = false } = {}) {
187
+ if (!activeOnly) {
188
+ if (!awake().length) return noWorkers();
189
+ while (elastic && slots.length < capacity) grow();
190
+ }
149
191
  return Promise.all(slots.map(slot => send(slot, job, input, [])));
150
192
  }
151
193
  if (!broken && initialWorkers) adopt(initialWorkers);
@@ -155,7 +155,7 @@ export function createQualityFit({ state, post, cardBlocks, cardDone, store, dev
155
155
  fit.costs.push(frameCost);
156
156
  fit.next = now + PROBE_MS;
157
157
  if (fit.costs.length < WINDOW) return;
158
- const cost = fit.costs.sort((a, b) => a - b)[WINDOW >> 1],
158
+ const cost = fit.costs.sort((firstCost, secondCost) => firstCost - secondCost)[WINDOW >> 1],
159
159
  fps = ((fit.frames - 1) * 1000) / (now - fit.since),
160
160
  at = LEVELS.indexOf(state.quality);
161
161
  fit.costs.length = 0;
package/runtime/search.js CHANGED
@@ -18,48 +18,48 @@ const searchWords = text =>
18
18
  // The slips a word of `n` letters may have and still match: none under four letters, one up to six, two from seven
19
19
  const slipsAllowed = n => (n < 4 ? 0 : n < 7 ? 1 : 2);
20
20
 
21
- // Edits (a letter changed, added, dropped, or two swapped) between a and b, or most + 1 once it is sure to be more than most
22
- function slips(a, b, most) {
23
- if (Math.abs(a.length - b.length) > most) return most + 1;
21
+ // Edits (a letter changed, added, dropped, or two swapped) between the source and target words, or most + 1 once it is sure to be more than most
22
+ function slips(source, target, most) {
23
+ if (Math.abs(source.length - target.length) > most) return most + 1;
24
24
  let prev2 = null,
25
- prev = Array.from({ length: b.length + 1 }, (_, j) => j);
26
- for (let i = 1; i <= a.length; i++) {
25
+ prev = Array.from({ length: target.length + 1 }, (_, j) => j);
26
+ for (let i = 1; i <= source.length; i++) {
27
27
  const row = [i];
28
28
  let least = i;
29
- for (let j = 1; j <= b.length; j++) {
30
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
31
- let d = Math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + cost);
32
- if (prev2 && i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d = Math.min(d, prev2[j - 2] + 1);
33
- row.push(d);
34
- if (d < least) least = d;
29
+ for (let j = 1; j <= target.length; j++) {
30
+ const cost = source[i - 1] === target[j - 1] ? 0 : 1;
31
+ let editCost = Math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + cost);
32
+ if (prev2 && i > 1 && j > 1 && source[i - 1] === target[j - 2] && source[i - 2] === target[j - 1]) editCost = Math.min(editCost, prev2[j - 2] + 1);
33
+ row.push(editCost);
34
+ if (editCost < least) least = editCost;
35
35
  }
36
36
  if (least > most) return most + 1;
37
37
  prev2 = prev;
38
38
  prev = row;
39
39
  }
40
- return prev[b.length];
40
+ return prev[target.length];
41
41
  }
42
42
 
43
43
  // How well one query word matches one word of the text: 0 for not at all
44
- function wordMatch(q, w) {
45
- if (w === q) return EXACT;
46
- if (w.startsWith(q)) return START;
47
- if (q.length >= INSIDE_LEAST && w.includes(q)) return INSIDE;
48
- const most = slipsAllowed(q.length);
44
+ function wordMatch(queryWord, word) {
45
+ if (word === queryWord) return EXACT;
46
+ if (word.startsWith(queryWord)) return START;
47
+ if (queryWord.length >= INSIDE_LEAST && word.includes(queryWord)) return INSIDE;
48
+ const most = slipsAllowed(queryWord.length);
49
49
  if (!most) return 0;
50
50
  // against the whole word, and against its start as long as the query (a word still being typed)
51
- const d = Math.min(slips(q, w, most), w.length > q.length ? slips(q, w.slice(0, q.length), most) : most + 1);
52
- return d <= most ? NEAR - SLIP * (d - 1) : 0;
51
+ const distance = Math.min(slips(queryWord, word, most), word.length > queryWord.length ? slips(queryWord, word.slice(0, queryWord.length), most) : most + 1);
52
+ return distance <= most ? NEAR - SLIP * (distance - 1) : 0;
53
53
  }
54
54
 
55
55
  // How well a query matches a text given as its title's words and the rest's (from searchWords): 0 when some word of the query
56
56
  // matches nothing; else the sum over the query's words of each one's best match, a match in the title counting twice.
57
57
  function fuzzyScore(query, titleWords, restWords) {
58
58
  let total = 0;
59
- for (const q of query) {
59
+ for (const queryWord of query) {
60
60
  let best = 0;
61
- for (const w of titleWords) best = Math.max(best, 2 * wordMatch(q, w));
62
- if (best < 2 * EXACT) for (const w of restWords) best = Math.max(best, wordMatch(q, w));
61
+ for (const word of titleWords) best = Math.max(best, 2 * wordMatch(queryWord, word));
62
+ if (best < 2 * EXACT) for (const word of restWords) best = Math.max(best, wordMatch(queryWord, word));
63
63
  if (!best) return 0;
64
64
  total += best;
65
65
  }
@@ -1,10 +1,10 @@
1
1
  // Noise every bed is cut from, its end blended into its start so it loops unheard: pink (Kellet's filter, as much in each octave,
2
2
  // normalised) for the wind, or brown (a leaky sum, with a little white) for water, crowds and rain, at the level they were set to.
3
- export function createNoiseLoop(c, { pink = false, seconds = 8, crossfade = 0.25, random = Math.random } = {}) {
4
- const n = Math.floor(c.sampleRate * seconds),
5
- seam = Math.min(n, Math.floor(c.sampleRate * crossfade)),
6
- buf = c.createBuffer(1, n, c.sampleRate),
7
- d = buf.getChannelData(0);
3
+ export function createNoiseLoop(audioContext, { pink = false, seconds = 8, crossfade = 0.25, random = Math.random } = {}) {
4
+ const n = Math.floor(audioContext.sampleRate * seconds),
5
+ seam = Math.min(n, Math.floor(audioContext.sampleRate * crossfade)),
6
+ buffer = audioContext.createBuffer(1, n, audioContext.sampleRate),
7
+ samples = buffer.getChannelData(0);
8
8
  let b0 = 0,
9
9
  b1 = 0,
10
10
  b2 = 0,
@@ -15,22 +15,22 @@ export function createNoiseLoop(c, { pink = false, seconds = 8, crossfade = 0.25
15
15
  b0 = 0.99765 * b0 + w * 0.099046;
16
16
  b1 = 0.963 * b1 + w * 0.2965164;
17
17
  b2 = 0.57 * b2 + w * 1.0526913;
18
- d[i] = b0 + b1 + b2 + w * 0.1848;
18
+ samples[i] = b0 + b1 + b2 + w * 0.1848;
19
19
  } else {
20
20
  b0 = (b0 + 0.03 * w) / 1.03;
21
- d[i] = b0 * 3.2 + w * 0.05;
21
+ samples[i] = b0 * 3.2 + w * 0.05;
22
22
  }
23
- peak = Math.max(peak, Math.abs(d[i]));
23
+ peak = Math.max(peak, Math.abs(samples[i]));
24
24
  }
25
25
  for (let i = 0; i < seam; i++) {
26
26
  const k = i / seam;
27
- d[i] = d[i] * k + d[n - seam + i] * (1 - k);
27
+ samples[i] = samples[i] * k + samples[n - seam + i] * (1 - k);
28
28
  }
29
- if (pink && peak > 0) for (let i = 0; i < n; i++) d[i] *= 0.9 / peak;
30
- return buf;
29
+ if (pink && peak > 0) for (let i = 0; i < n; i++) samples[i] *= 0.9 / peak;
30
+ return buffer;
31
31
  }
32
- export function createSpatialPanner(c, x, y, z, referenceDistance = 10) {
33
- const pan = c.createPanner();
32
+ export function createSpatialPanner(audioContext, x, y, z, referenceDistance = 10) {
33
+ const pan = audioContext.createPanner();
34
34
  pan.panningModel = 'equalpower';
35
35
  pan.distanceModel = 'inverse';
36
36
  pan.refDistance = referenceDistance;
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Share the first input and promise among overlapping requests. Call
3
+ * `request(input, true)` to pin that attempt. Withdrawing an unpinned attempt
4
+ * aborts its signal. A subsequent request waits for the old work to settle.
5
+ * @param work - Receives the first caller’s input and an AbortSignal. The caller owns a successful result.
6
+ */
7
+ export function createWithdrawableTask(work) {
8
+ let current = null;
9
+ let tail = Promise.resolve();
10
+ function request(input, pinned = false) {
11
+ if (current) {
12
+ if (pinned) current.pinned = true;
13
+ return current.done;
14
+ }
15
+ const controller = new AbortController();
16
+ const attempt = { controller, pinned, done: null };
17
+ current = attempt;
18
+ attempt.done = tail.then(() => {
19
+ controller.signal.throwIfAborted();
20
+ return work(input, controller.signal);
21
+ }).finally(() => {
22
+ if (current === attempt) current = null;
23
+ });
24
+ tail = attempt.done.then(() => {}, () => {});
25
+ return attempt.done;
26
+ }
27
+ function withdraw() {
28
+ if (!current || current.pinned) return false;
29
+ const { controller } = current;
30
+ current = null;
31
+ controller.abort();
32
+ return true;
33
+ }
34
+ return { request, withdraw, get pending() { return !!current; } };
35
+ }
package/runtime/worker.js CHANGED
@@ -1,3 +1,8 @@
1
+ /**
2
+ * Handle named jobs on the worker side of the Roamwright pool protocol.
3
+ * @module
4
+ */
5
+
1
6
  // Transfer backing stores once, including when several views share a buffer.
2
7
  function transferList(result) {
3
8
  const buffers = new Set();
@@ -21,6 +26,8 @@ function transferList(result) {
21
26
  * Bind a pool worker to a message port. Jobs receive the input carried in the
22
27
  * request. A loader returns a module exposing a jobs object, which may supply
23
28
  * several handlers at once. Requests, including asynchronous work, finish FIFO.
29
+ * ArrayBuffers in a successful result transfer to the caller. A handler that
30
+ * needs its own copy must keep a separate buffer before returning the result.
24
31
  */
25
32
  export function attachWorker({ port, jobs = {}, loaders = {} }) {
26
33
  const handlers = new Map(Object.entries(jobs));