@vim3d/threejs 0.2.0 → 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.
package/esm/audio.js ADDED
@@ -0,0 +1,449 @@
1
+ export const DEFAULT_AUDIO_BANDS = Object.freeze({
2
+ bass: Object.freeze([20, 250]),
3
+ mid: Object.freeze([250, 2000]),
4
+ treble: Object.freeze([2000, 16000]),
5
+ });
6
+ export const DEFAULT_AUDIO_FEATURE_PORTS = Object.freeze([
7
+ 'loudness', 'bass', 'mid', 'treble', 'onset', 'travel',
8
+ ]);
9
+ function clampUnit(value) {
10
+ if (!Number.isFinite(value))
11
+ return 0;
12
+ return Math.max(0, Math.min(1, value));
13
+ }
14
+ function createAudioContext(provided) {
15
+ if (provided)
16
+ return { context: provided };
17
+ const AudioCtx = globalThis.AudioContext
18
+ ?? globalThis.webkitAudioContext;
19
+ if (!AudioCtx)
20
+ throw new Error('Web Audio AudioContext is not available in this environment');
21
+ const context = new AudioCtx();
22
+ return { context, owned: context };
23
+ }
24
+ function configureAnalyser(context, options) {
25
+ const analyser = context.createAnalyser();
26
+ if (options.fftSize !== undefined)
27
+ analyser.fftSize = options.fftSize;
28
+ if (options.smoothingTimeConstant !== undefined) {
29
+ analyser.smoothingTimeConstant = options.smoothingTimeConstant;
30
+ }
31
+ return analyser;
32
+ }
33
+ function validateBands(bands) {
34
+ const entries = Object.entries(bands);
35
+ for (const [name, range] of entries) {
36
+ if (!name || name === 'loudness' || name === 'onset' || name === 'travel') {
37
+ throw new RangeError('Invalid audio band name: ' + name);
38
+ }
39
+ if (!Array.isArray(range) || range.length !== 2 || !Number.isFinite(range[0]) || !Number.isFinite(range[1]) || range[0] < 0 || range[0] >= range[1]) {
40
+ throw new RangeError('Invalid frequency band range for ' + name);
41
+ }
42
+ }
43
+ return entries;
44
+ }
45
+ export class WebAudioChannelSource {
46
+ ports;
47
+ analyser;
48
+ context;
49
+ bands;
50
+ sampleRateOverride;
51
+ onsetGain;
52
+ smoothing;
53
+ freqData;
54
+ prevSpectrum;
55
+ floatTimeData;
56
+ byteTimeData;
57
+ ownedContext;
58
+ cleanup;
59
+ starter;
60
+ hasPrevious = false;
61
+ prevTimestamp;
62
+ prevValues;
63
+ travel = 0;
64
+ recording;
65
+ recordedFrames = new Map();
66
+ disposed = false;
67
+ constructor(analyser, options = {}) {
68
+ if (!analyser || typeof analyser.getByteFrequencyData !== 'function') {
69
+ throw new TypeError('An AnalyserNode-compatible analyser is required');
70
+ }
71
+ if (!Number.isInteger(analyser.frequencyBinCount) || analyser.frequencyBinCount <= 0) {
72
+ throw new RangeError('Analyser frequencyBinCount must be a positive integer');
73
+ }
74
+ const smoothing = options.smoothing ?? 0;
75
+ if (!Number.isFinite(smoothing) || smoothing < 0 || smoothing >= 1) {
76
+ throw new RangeError('Smoothing must be in [0, 1)');
77
+ }
78
+ const onsetGain = options.onsetGain ?? 4;
79
+ if (!Number.isFinite(onsetGain) || onsetGain <= 0) {
80
+ throw new RangeError('onsetGain must be finite and positive');
81
+ }
82
+ if (options.sampleRate !== undefined && (!Number.isFinite(options.sampleRate) || options.sampleRate <= 0)) {
83
+ throw new RangeError('sampleRate must be finite and positive');
84
+ }
85
+ this.analyser = analyser;
86
+ this.context = options.audioContext;
87
+ this.ownedContext = options.ownedContext;
88
+ this.cleanup = options.cleanup;
89
+ this.starter = options.starter;
90
+ this.sampleRateOverride = options.sampleRate;
91
+ this.onsetGain = onsetGain;
92
+ this.smoothing = smoothing;
93
+ this.recording = options.record ?? false;
94
+ const bandMap = options.bands ?? DEFAULT_AUDIO_BANDS;
95
+ this.bands = validateBands(bandMap);
96
+ this.ports = Object.freeze(['loudness', ...this.bands.map(([name]) => name), 'onset', 'travel']);
97
+ this.freqData = new Uint8Array(analyser.frequencyBinCount);
98
+ this.prevSpectrum = new Float32Array(analyser.frequencyBinCount);
99
+ const timeSize = Math.max(1, analyser.fftSize || analyser.frequencyBinCount * 2);
100
+ if (typeof analyser.getFloatTimeDomainData === 'function') {
101
+ this.floatTimeData = new Float32Array(timeSize);
102
+ }
103
+ else if (typeof analyser.getByteTimeDomainData === 'function') {
104
+ this.byteTimeData = new Uint8Array(timeSize);
105
+ }
106
+ }
107
+ static fromMediaElement(element, options = {}) {
108
+ const { context, owned } = createAudioContext(options.audioContext);
109
+ const monitor = options.monitor ?? true;
110
+ const analyser = configureAnalyser(context, options);
111
+ const node = context.createMediaElementSource(element);
112
+ node.connect(analyser);
113
+ if (monitor)
114
+ analyser.connect(context.destination);
115
+ const restoreOutput = () => {
116
+ try {
117
+ node.disconnect();
118
+ }
119
+ catch { /* ignore */ }
120
+ try {
121
+ analyser.disconnect();
122
+ }
123
+ catch { /* ignore */ }
124
+ if (!owned && monitor) {
125
+ try {
126
+ node.connect(context.destination);
127
+ }
128
+ catch { /* ignore */ }
129
+ }
130
+ };
131
+ try {
132
+ return new WebAudioChannelSource(analyser, {
133
+ ...options,
134
+ audioContext: context,
135
+ ownedContext: owned,
136
+ starter: () => { void element.play(); },
137
+ cleanup: restoreOutput,
138
+ });
139
+ }
140
+ catch (error) {
141
+ restoreOutput();
142
+ if (owned)
143
+ void owned.close();
144
+ throw error;
145
+ }
146
+ }
147
+ static fromAudioBuffer(buffer, options = {}) {
148
+ const { context, owned } = createAudioContext(options.audioContext);
149
+ return WebAudioChannelSource.connectBuffer(buffer, context, owned, options);
150
+ }
151
+ static connectBuffer(buffer, context, owned, options) {
152
+ const analyser = configureAnalyser(context, options);
153
+ const source = context.createBufferSource();
154
+ source.buffer = buffer;
155
+ source.loop = options.loop ?? false;
156
+ source.connect(analyser);
157
+ if (options.monitor ?? true)
158
+ analyser.connect(context.destination);
159
+ let started = false;
160
+ const startBuffer = (when, offset) => {
161
+ if (started)
162
+ return;
163
+ started = true;
164
+ source.start(when, offset);
165
+ };
166
+ const disconnect = () => {
167
+ if (started) {
168
+ try {
169
+ source.stop();
170
+ }
171
+ catch { /* ignore */ }
172
+ }
173
+ try {
174
+ source.disconnect();
175
+ }
176
+ catch { /* ignore */ }
177
+ try {
178
+ analyser.disconnect();
179
+ }
180
+ catch { /* ignore */ }
181
+ };
182
+ try {
183
+ const channel = new WebAudioChannelSource(analyser, {
184
+ ...options,
185
+ audioContext: context,
186
+ ownedContext: owned,
187
+ starter: startBuffer,
188
+ cleanup: disconnect,
189
+ });
190
+ if (options.autoplay)
191
+ channel.start();
192
+ return channel;
193
+ }
194
+ catch (error) {
195
+ disconnect();
196
+ if (owned)
197
+ void owned.close();
198
+ throw error;
199
+ }
200
+ }
201
+ static async fromFile(file, options = {}) {
202
+ const { context, owned } = createAudioContext(options.audioContext);
203
+ try {
204
+ let bytes;
205
+ if (typeof file === 'string') {
206
+ const response = await fetch(file);
207
+ if (!response.ok)
208
+ throw new Error(`Failed to fetch audio file (${response.status}): ${file}`);
209
+ bytes = await response.arrayBuffer();
210
+ }
211
+ else if (file instanceof ArrayBuffer) {
212
+ bytes = file.slice(0);
213
+ }
214
+ else {
215
+ bytes = await file.arrayBuffer();
216
+ }
217
+ const buffer = await context.decodeAudioData(bytes);
218
+ return WebAudioChannelSource.connectBuffer(buffer, context, owned, options);
219
+ }
220
+ catch (error) {
221
+ if (owned)
222
+ void owned.close();
223
+ throw error;
224
+ }
225
+ }
226
+ static fromMediaStream(stream, options = {}) {
227
+ const { context, owned } = createAudioContext(options.audioContext);
228
+ const analyser = configureAnalyser(context, options);
229
+ const node = context.createMediaStreamSource(stream);
230
+ node.connect(analyser);
231
+ if (options.monitor ?? false)
232
+ analyser.connect(context.destination);
233
+ return new WebAudioChannelSource(analyser, {
234
+ ...options,
235
+ audioContext: context,
236
+ ownedContext: owned,
237
+ cleanup: () => {
238
+ try {
239
+ node.disconnect();
240
+ }
241
+ catch { /* ignore */ }
242
+ try {
243
+ analyser.disconnect();
244
+ }
245
+ catch { /* ignore */ }
246
+ },
247
+ });
248
+ }
249
+ static async fromMicrophone(options = {}) {
250
+ const mediaDevices = globalThis.navigator?.mediaDevices;
251
+ if (!mediaDevices || typeof mediaDevices.getUserMedia !== 'function') {
252
+ throw new Error('Microphone capture (navigator.mediaDevices.getUserMedia) is not available');
253
+ }
254
+ const stream = await mediaDevices.getUserMedia({ audio: options.constraints ?? true });
255
+ let owned;
256
+ let node;
257
+ let analyser;
258
+ try {
259
+ const ctx = createAudioContext(options.audioContext);
260
+ owned = ctx.owned;
261
+ analyser = configureAnalyser(ctx.context, options);
262
+ node = ctx.context.createMediaStreamSource(stream);
263
+ node.connect(analyser);
264
+ if (options.monitor ?? false)
265
+ analyser.connect(ctx.context.destination);
266
+ const connectedNode = node;
267
+ const connectedAnalyser = analyser;
268
+ return new WebAudioChannelSource(connectedAnalyser, {
269
+ ...options,
270
+ audioContext: ctx.context,
271
+ ownedContext: owned,
272
+ cleanup: () => {
273
+ try {
274
+ connectedNode.disconnect();
275
+ }
276
+ catch { /* ignore */ }
277
+ try {
278
+ connectedAnalyser.disconnect();
279
+ }
280
+ catch { /* ignore */ }
281
+ for (const track of stream.getTracks())
282
+ track.stop();
283
+ },
284
+ });
285
+ }
286
+ catch (error) {
287
+ try {
288
+ node?.disconnect();
289
+ }
290
+ catch { /* ignore */ }
291
+ try {
292
+ analyser?.disconnect();
293
+ }
294
+ catch { /* ignore */ }
295
+ for (const track of stream.getTracks())
296
+ track.stop();
297
+ if (owned)
298
+ void owned.close();
299
+ throw error;
300
+ }
301
+ }
302
+ async resume() {
303
+ this.assertActive();
304
+ if (this.context && this.context.state === 'suspended') {
305
+ await this.context.resume();
306
+ }
307
+ }
308
+ start(when, offset) {
309
+ this.assertActive();
310
+ this.starter?.(when, offset);
311
+ }
312
+ startRecording() {
313
+ this.recording = true;
314
+ }
315
+ stopRecording() {
316
+ this.recording = false;
317
+ }
318
+ reset() {
319
+ this.hasPrevious = false;
320
+ this.prevTimestamp = undefined;
321
+ this.prevValues = undefined;
322
+ this.travel = 0;
323
+ this.prevSpectrum.fill(0);
324
+ this.recordedFrames.clear();
325
+ }
326
+ sample(frame = 0, time) {
327
+ this.assertActive();
328
+ this.analyser.getByteFrequencyData(this.freqData);
329
+ const binCount = this.freqData.length;
330
+ const sampleRate = this.sampleRateOverride ?? this.analyser.context?.sampleRate ?? 48000;
331
+ const nyquist = sampleRate / 2;
332
+ const hzPerBin = nyquist / binCount;
333
+ const rawValues = {};
334
+ for (const [name, [lowHz, highHz]] of this.bands) {
335
+ const startBin = Math.max(0, Math.min(binCount - 1, Math.ceil(lowHz / hzPerBin)));
336
+ const rawEnd = highHz / hzPerBin;
337
+ const endBin = Math.max(startBin, Math.min(binCount - 1, Number.isInteger(rawEnd) ? rawEnd - 1 : Math.floor(rawEnd)));
338
+ let sumSq = 0;
339
+ for (let i = startBin; i <= endBin; i++) {
340
+ const m = this.freqData[i] / 255;
341
+ sumSq += m * m;
342
+ }
343
+ rawValues[name] = clampUnit(Math.sqrt(sumSq / (endBin - startBin + 1)));
344
+ }
345
+ let loudness = 0;
346
+ if (this.floatTimeData && this.analyser.getFloatTimeDomainData) {
347
+ this.analyser.getFloatTimeDomainData(this.floatTimeData);
348
+ let sumSq = 0;
349
+ for (let i = 0; i < this.floatTimeData.length; i++) {
350
+ const v = this.floatTimeData[i];
351
+ sumSq += v * v;
352
+ }
353
+ loudness = clampUnit(Math.sqrt(sumSq / this.floatTimeData.length));
354
+ }
355
+ else if (this.byteTimeData && this.analyser.getByteTimeDomainData) {
356
+ this.analyser.getByteTimeDomainData(this.byteTimeData);
357
+ let sumSq = 0;
358
+ for (let i = 0; i < this.byteTimeData.length; i++) {
359
+ const v = (this.byteTimeData[i] - 128) / 128;
360
+ sumSq += v * v;
361
+ }
362
+ loudness = clampUnit(Math.sqrt(sumSq / this.byteTimeData.length));
363
+ }
364
+ else {
365
+ let sumSq = 0;
366
+ for (let i = 0; i < binCount; i++) {
367
+ const m = this.freqData[i] / 255;
368
+ sumSq += m * m;
369
+ }
370
+ loudness = clampUnit(Math.sqrt(sumSq / binCount));
371
+ }
372
+ rawValues.loudness = loudness;
373
+ let fluxSum = 0;
374
+ for (let i = 0; i < binCount; i++) {
375
+ const current = this.freqData[i] / 255;
376
+ if (this.hasPrevious) {
377
+ const diff = current - this.prevSpectrum[i];
378
+ if (diff > 0)
379
+ fluxSum += diff;
380
+ }
381
+ this.prevSpectrum[i] = current;
382
+ }
383
+ rawValues.onset = this.hasPrevious ? clampUnit((fluxSum / binCount) * this.onsetGain) : 0;
384
+ this.hasPrevious = true;
385
+ const timestamp = time !== undefined && Number.isFinite(time)
386
+ ? time
387
+ : this.analyser.context?.currentTime ?? 0;
388
+ const dt = this.prevTimestamp !== undefined ? Math.max(0, timestamp - this.prevTimestamp) : 0;
389
+ this.prevTimestamp = timestamp;
390
+ this.travel += loudness * dt;
391
+ rawValues.travel = this.travel;
392
+ const values = {};
393
+ for (const port of this.ports) {
394
+ const raw = rawValues[port];
395
+ if (port === 'travel' || this.smoothing === 0 || !this.prevValues) {
396
+ values[port] = raw;
397
+ }
398
+ else {
399
+ values[port] = this.prevValues[port] * this.smoothing + raw * (1 - this.smoothing);
400
+ }
401
+ }
402
+ this.prevValues = values;
403
+ if (this.recording && Number.isSafeInteger(frame) && frame >= 0 && !this.recordedFrames.has(frame)) {
404
+ this.recordedFrames.set(frame, { ...values });
405
+ }
406
+ return { timestamp, values };
407
+ }
408
+ toChannelTable(sampleRate = 30) {
409
+ if (!Number.isFinite(sampleRate) || sampleRate <= 0) {
410
+ throw new RangeError('Channel table sampleRate must be finite and positive');
411
+ }
412
+ if (!this.recordedFrames.size)
413
+ throw new Error('No recorded audio samples to export');
414
+ let maxFrame = 0;
415
+ for (const frame of this.recordedFrames.keys()) {
416
+ if (frame > maxFrame)
417
+ maxFrame = frame;
418
+ }
419
+ const channels = {};
420
+ for (const port of this.ports)
421
+ channels[port] = [];
422
+ let last;
423
+ for (let f = 0; f <= maxFrame; f++) {
424
+ const entry = this.recordedFrames.get(f) ?? last;
425
+ if (entry)
426
+ last = entry;
427
+ for (const port of this.ports)
428
+ channels[port].push(entry ? entry[port] : 0);
429
+ }
430
+ return {
431
+ sampleRate,
432
+ boundary: 'clamp',
433
+ interpolation: 'linear',
434
+ channels,
435
+ };
436
+ }
437
+ dispose() {
438
+ if (this.disposed)
439
+ return;
440
+ this.disposed = true;
441
+ this.cleanup?.();
442
+ if (this.ownedContext)
443
+ void this.ownedContext.close();
444
+ }
445
+ assertActive() {
446
+ if (this.disposed)
447
+ throw new Error('WebAudioChannelSource has been disposed');
448
+ }
449
+ }
package/esm/geometry.js CHANGED
@@ -1,4 +1,4 @@
1
- import { BoxGeometry, BufferGeometry, CircleGeometry, PlaneGeometry, RingGeometry, SphereGeometry, Vector3, } from 'three';
1
+ import { BoxGeometry, BufferGeometry, CircleGeometry, Group, Mesh, PlaneGeometry, RingGeometry, SphereGeometry, Vector3, } from 'three';
2
2
  export function isLine(primitive) {
3
3
  return primitive === 'curve' || primitive === 'ellipse' || primitive === 'circle';
4
4
  }
@@ -62,3 +62,76 @@ export function createGeometry({ primitive, args, vertices }) {
62
62
  default: throw new Error('Unsupported Vim3D geometry: ' + primitive);
63
63
  }
64
64
  }
65
+ function numbers(value, count) {
66
+ return Array.isArray(value) && value.length === count && Array.from(value).every(Number.isFinite);
67
+ }
68
+ export function disposeProceduralGeometry(root) {
69
+ root.traverse(object => {
70
+ if (object instanceof Mesh)
71
+ object.geometry.dispose();
72
+ });
73
+ root.clear();
74
+ }
75
+ export function updateProceduralGeometry(root, descriptor, material) {
76
+ const ancestors = new Set();
77
+ function updateChildren(group, descriptors) {
78
+ const previous = [...group.children];
79
+ const next = [];
80
+ for (const child of descriptors) {
81
+ const object = update(previous[next.length], child);
82
+ if (object)
83
+ next.push(object);
84
+ }
85
+ if (previous.length === next.length && previous.every((object, i) => object === next[i]))
86
+ return;
87
+ group.clear();
88
+ for (let i = 0; i < previous.length; i++) {
89
+ if (previous[i] !== next[i])
90
+ disposeProceduralGeometry(previous[i]);
91
+ }
92
+ for (const object of next)
93
+ group.add(object);
94
+ }
95
+ function update(previous, value) {
96
+ if (!value || typeof value !== 'object' || Array.isArray(value) || ancestors.has(value))
97
+ return;
98
+ const { kind, primitive, args, geometry, geometries, translate, scale } = value;
99
+ if (primitive === 'box' && numbers(args, 3)) {
100
+ const [width, height, depth] = args;
101
+ if (previous instanceof Mesh && previous.geometry instanceof BoxGeometry) {
102
+ const p = previous.geometry.parameters;
103
+ if (p.width === width && p.height === height && p.depth === depth)
104
+ return previous;
105
+ }
106
+ return new Mesh(new BoxGeometry(width, height, depth), material);
107
+ }
108
+ if (primitive === 'sphere' && numbers(args, 3)) {
109
+ const [radius, , detail] = args;
110
+ const widthSegments = segments(detail, 3), heightSegments = segments(detail / 2, 2);
111
+ if (previous instanceof Mesh && previous.geometry instanceof SphereGeometry) {
112
+ const p = previous.geometry.parameters;
113
+ if (p.radius === radius && p.widthSegments === widthSegments && p.heightSegments === heightSegments)
114
+ return previous;
115
+ }
116
+ return new Mesh(new SphereGeometry(radius, widthSegments, heightSegments), material);
117
+ }
118
+ const transform = kind === 'transform' && numbers(translate, 3) && numbers(scale, 3);
119
+ const merge = kind === 'merge' && Array.isArray(geometries);
120
+ if (!transform && !merge)
121
+ return;
122
+ const group = previous instanceof Group ? previous : new Group();
123
+ if (transform) {
124
+ group.position.fromArray(translate);
125
+ group.scale.fromArray(scale);
126
+ }
127
+ else {
128
+ group.position.set(0, 0, 0);
129
+ group.scale.setScalar(1);
130
+ }
131
+ ancestors.add(value);
132
+ updateChildren(group, transform ? [geometry] : geometries);
133
+ ancestors.delete(value);
134
+ return group;
135
+ }
136
+ updateChildren(root, [descriptor]);
137
+ }
package/esm/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export const name = '@vim3d/threejs';
2
- export { Vim3DThreeScene } from './scene.js';
2
+ export { DEFAULT_AUDIO_BANDS, DEFAULT_AUDIO_FEATURE_PORTS, WebAudioChannelSource, } from './audio.js';
3
3
  export { Vim3DPlayer } from './player.js';
4
+ export { Vim3DThreeScene } from './scene.js';
package/esm/player.js CHANGED
@@ -17,6 +17,7 @@ export class Vim3DPlayer {
17
17
  ownedRenderer;
18
18
  scheduler;
19
19
  rendererSize = new Vector2();
20
+ liveChannels = new Map();
20
21
  fps;
21
22
  loop;
22
23
  frame = 0;
@@ -39,6 +40,16 @@ export class Vim3DPlayer {
39
40
  this.ownedRenderer = new WebGLRenderer({ canvas: options.canvas, antialias: true });
40
41
  }
41
42
  this.renderer = options.renderer ?? this.ownedRenderer;
43
+ for (const [name, provider] of Object.entries(options.liveChannels ?? {})) {
44
+ this.liveChannels.set(name, provider);
45
+ }
46
+ }
47
+ setLiveChannel(name, provider) {
48
+ this.assertActive();
49
+ if (provider)
50
+ this.liveChannels.set(name, provider);
51
+ else
52
+ this.liveChannels.delete(name);
42
53
  }
43
54
  getFrame() {
44
55
  return this.frame;
@@ -118,7 +129,18 @@ export class Vim3DPlayer {
118
129
  return ((frame % count) + count) % count;
119
130
  }
120
131
  draw(frame) {
121
- const result = evaluateFrame(this.scene, frame);
132
+ let evaluateOptions;
133
+ const validFrame = Number.isSafeInteger(frame) && frame >= 0
134
+ && (this.scene.frameCount === undefined || frame < this.scene.frameCount);
135
+ if (validFrame && this.liveChannels.size) {
136
+ const time = frame / this.scene.fps;
137
+ const sampled = {};
138
+ for (const [name, provider] of this.liveChannels) {
139
+ sampled[name] = provider.sample(frame, time);
140
+ }
141
+ evaluateOptions = { liveChannels: sampled };
142
+ }
143
+ const result = evaluateFrame(this.scene, frame, evaluateOptions);
122
144
  if ('diagnostics' in result) {
123
145
  this.options.onDiagnostics?.(result.diagnostics);
124
146
  return result;
package/esm/scene.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import { DirectionalLight, DoubleSide, Group, Line, LineBasicMaterial, Mesh, MeshPhongMaterial, PerspectiveCamera, PointLight, Scene, SpotLight, Vector3, } from 'three';
2
- import { createGeometry, isLine } from './geometry.js';
2
+ import { createGeometry, disposeProceduralGeometry, isLine, updateProceduralGeometry } from './geometry.js';
3
3
  function renderType(snapshot) {
4
4
  if (snapshot.camera)
5
5
  return 'camera';
6
6
  if (snapshot.light)
7
7
  return snapshot.light.kind;
8
+ if (snapshot.proceduralGeometry !== undefined)
9
+ return 'procedural';
8
10
  if (!snapshot.geometry)
9
11
  return 'group';
10
12
  return isLine(snapshot.geometry.primitive) ? 'line' : 'mesh';
@@ -59,9 +61,13 @@ function applyMaterial(material, sample) {
59
61
  material.shininess = sample?.shininess ?? 0;
60
62
  }
61
63
  }
62
- function disposeEntry(object) {
64
+ function disposeEntry({ object, proceduralMaterial }) {
63
65
  object.removeFromParent();
64
- if (object instanceof Mesh || object instanceof Line) {
66
+ if (proceduralMaterial) {
67
+ disposeProceduralGeometry(object);
68
+ proceduralMaterial.dispose();
69
+ }
70
+ else if (object instanceof Mesh || object instanceof Line) {
65
71
  object.geometry.dispose();
66
72
  object.material.dispose();
67
73
  }
@@ -97,14 +103,15 @@ export class Vim3DThreeScene {
97
103
  if (!entry || entry.type !== type) {
98
104
  const object = createObject(type, geometry);
99
105
  if (entry)
100
- disposeEntry(entry.object);
106
+ disposeEntry(entry);
101
107
  object.name = path;
102
108
  object.matrixAutoUpdate = false;
103
109
  object.matrixWorldAutoUpdate = false;
104
110
  this.scene.add(object);
105
111
  if (object instanceof SpotLight || object instanceof DirectionalLight)
106
112
  this.scene.add(object.target);
107
- entry = { object, type, geometry };
113
+ entry = { object, type, geometry,
114
+ ...(type === 'procedural' && { proceduralMaterial: new MeshPhongMaterial({ side: DoubleSide }) }) };
108
115
  this.entries.set(path, entry);
109
116
  }
110
117
  const { object } = entry;
@@ -117,7 +124,11 @@ export class Vim3DThreeScene {
117
124
  object.matrixWorld.copy(object.matrix);
118
125
  object.matrixWorldNeedsUpdate = true;
119
126
  object.visible = sample.visible;
120
- if (object instanceof Mesh || object instanceof Line) {
127
+ if (entry.proceduralMaterial && object instanceof Group) {
128
+ applyMaterial(entry.proceduralMaterial, sample.material);
129
+ updateProceduralGeometry(object, sample.proceduralGeometry, entry.proceduralMaterial);
130
+ }
131
+ else if (object instanceof Mesh || object instanceof Line) {
121
132
  if (geometry !== entry.geometry) {
122
133
  const next = createGeometry(geometry);
123
134
  object.geometry.dispose();
@@ -142,16 +153,16 @@ export class Vim3DThreeScene {
142
153
  }
143
154
  }
144
155
  }
145
- for (const [path, { object }] of this.entries) {
156
+ for (const [path, entry] of this.entries) {
146
157
  if (!seen.has(path)) {
147
- disposeEntry(object);
158
+ disposeEntry(entry);
148
159
  this.entries.delete(path);
149
160
  }
150
161
  }
151
162
  }
152
163
  dispose() {
153
- for (const { object } of this.entries.values())
154
- disposeEntry(object);
164
+ for (const entry of this.entries.values())
165
+ disposeEntry(entry);
155
166
  this.entries.clear();
156
167
  }
157
168
  }
package/geometry.d.ts CHANGED
@@ -1,4 +1,6 @@
1
- import { BufferGeometry } from 'three';
1
+ import { BufferGeometry, Group, MeshPhongMaterial, Object3D } from 'three';
2
2
  import type { GeometrySnapshot } from '@vim3d/core';
3
3
  export declare function isLine(primitive: string): boolean;
4
4
  export declare function createGeometry({ primitive, args, vertices }: GeometrySnapshot): BufferGeometry;
5
+ export declare function disposeProceduralGeometry(root: Object3D): void;
6
+ export declare function updateProceduralGeometry(root: Group, descriptor: unknown, material: MeshPhongMaterial): void;