@polarfront-lab/ionian 1.0.0

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.
@@ -0,0 +1,3479 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+ import * as THREE from "three";
5
+ import { Mesh, OrthographicCamera, BufferGeometry, Float32BufferAttribute, NearestFilter, ShaderMaterial, WebGLRenderTarget, FloatType, RGBAFormat, DataTexture, ClampToEdgeWrapping } from "three";
6
+ const linear = (n) => n;
7
+ function mitt(n) {
8
+ return { all: n = n || /* @__PURE__ */ new Map(), on: function(t, e) {
9
+ var i = n.get(t);
10
+ i ? i.push(e) : n.set(t, [e]);
11
+ }, off: function(t, e) {
12
+ var i = n.get(t);
13
+ i && (e ? i.splice(i.indexOf(e) >>> 0, 1) : n.set(t, []));
14
+ }, emit: function(t, e) {
15
+ var i = n.get(t);
16
+ i && i.slice().map(function(n2) {
17
+ n2(e);
18
+ }), (i = n.get("*")) && i.slice().map(function(n2) {
19
+ n2(t, e);
20
+ });
21
+ } };
22
+ }
23
+ class DefaultEventEmitter {
24
+ constructor() {
25
+ __publicField(this, "emitter", mitt());
26
+ }
27
+ emit(type, payload) {
28
+ this.emitter.emit(type, payload);
29
+ }
30
+ off(type, handler) {
31
+ this.emitter.off(type, handler);
32
+ }
33
+ on(type, handler) {
34
+ this.emitter.on(type, handler);
35
+ }
36
+ once(type, handler) {
37
+ this.emitter.on(type, (payload) => {
38
+ this.emitter.off(type, handler);
39
+ handler(payload);
40
+ });
41
+ }
42
+ dispose() {
43
+ this.emitter.all.clear();
44
+ }
45
+ }
46
+ /**
47
+ * @license
48
+ * Copyright 2019 Google LLC
49
+ * SPDX-License-Identifier: Apache-2.0
50
+ */
51
+ const proxyMarker = Symbol("Comlink.proxy");
52
+ const createEndpoint = Symbol("Comlink.endpoint");
53
+ const releaseProxy = Symbol("Comlink.releaseProxy");
54
+ const finalizer = Symbol("Comlink.finalizer");
55
+ const throwMarker = Symbol("Comlink.thrown");
56
+ const isObject = (val) => typeof val === "object" && val !== null || typeof val === "function";
57
+ const proxyTransferHandler = {
58
+ canHandle: (val) => isObject(val) && val[proxyMarker],
59
+ serialize(obj) {
60
+ const { port1, port2 } = new MessageChannel();
61
+ expose(obj, port1);
62
+ return [port2, [port2]];
63
+ },
64
+ deserialize(port) {
65
+ port.start();
66
+ return wrap(port);
67
+ }
68
+ };
69
+ const throwTransferHandler = {
70
+ canHandle: (value) => isObject(value) && throwMarker in value,
71
+ serialize({ value }) {
72
+ let serialized;
73
+ if (value instanceof Error) {
74
+ serialized = {
75
+ isError: true,
76
+ value: {
77
+ message: value.message,
78
+ name: value.name,
79
+ stack: value.stack
80
+ }
81
+ };
82
+ } else {
83
+ serialized = { isError: false, value };
84
+ }
85
+ return [serialized, []];
86
+ },
87
+ deserialize(serialized) {
88
+ if (serialized.isError) {
89
+ throw Object.assign(new Error(serialized.value.message), serialized.value);
90
+ }
91
+ throw serialized.value;
92
+ }
93
+ };
94
+ const transferHandlers = /* @__PURE__ */ new Map([
95
+ ["proxy", proxyTransferHandler],
96
+ ["throw", throwTransferHandler]
97
+ ]);
98
+ function isAllowedOrigin(allowedOrigins, origin) {
99
+ for (const allowedOrigin of allowedOrigins) {
100
+ if (origin === allowedOrigin || allowedOrigin === "*") {
101
+ return true;
102
+ }
103
+ if (allowedOrigin instanceof RegExp && allowedOrigin.test(origin)) {
104
+ return true;
105
+ }
106
+ }
107
+ return false;
108
+ }
109
+ function expose(obj, ep = globalThis, allowedOrigins = ["*"]) {
110
+ ep.addEventListener("message", function callback(ev) {
111
+ if (!ev || !ev.data) {
112
+ return;
113
+ }
114
+ if (!isAllowedOrigin(allowedOrigins, ev.origin)) {
115
+ console.warn(`Invalid origin '${ev.origin}' for comlink proxy`);
116
+ return;
117
+ }
118
+ const { id, type, path } = Object.assign({ path: [] }, ev.data);
119
+ const argumentList = (ev.data.argumentList || []).map(fromWireValue);
120
+ let returnValue;
121
+ try {
122
+ const parent = path.slice(0, -1).reduce((obj2, prop) => obj2[prop], obj);
123
+ const rawValue = path.reduce((obj2, prop) => obj2[prop], obj);
124
+ switch (type) {
125
+ case "GET":
126
+ {
127
+ returnValue = rawValue;
128
+ }
129
+ break;
130
+ case "SET":
131
+ {
132
+ parent[path.slice(-1)[0]] = fromWireValue(ev.data.value);
133
+ returnValue = true;
134
+ }
135
+ break;
136
+ case "APPLY":
137
+ {
138
+ returnValue = rawValue.apply(parent, argumentList);
139
+ }
140
+ break;
141
+ case "CONSTRUCT":
142
+ {
143
+ const value = new rawValue(...argumentList);
144
+ returnValue = proxy(value);
145
+ }
146
+ break;
147
+ case "ENDPOINT":
148
+ {
149
+ const { port1, port2 } = new MessageChannel();
150
+ expose(obj, port2);
151
+ returnValue = transfer(port1, [port1]);
152
+ }
153
+ break;
154
+ case "RELEASE":
155
+ {
156
+ returnValue = void 0;
157
+ }
158
+ break;
159
+ default:
160
+ return;
161
+ }
162
+ } catch (value) {
163
+ returnValue = { value, [throwMarker]: 0 };
164
+ }
165
+ Promise.resolve(returnValue).catch((value) => {
166
+ return { value, [throwMarker]: 0 };
167
+ }).then((returnValue2) => {
168
+ const [wireValue, transferables] = toWireValue(returnValue2);
169
+ ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);
170
+ if (type === "RELEASE") {
171
+ ep.removeEventListener("message", callback);
172
+ closeEndPoint(ep);
173
+ if (finalizer in obj && typeof obj[finalizer] === "function") {
174
+ obj[finalizer]();
175
+ }
176
+ }
177
+ }).catch((error) => {
178
+ const [wireValue, transferables] = toWireValue({
179
+ value: new TypeError("Unserializable return value"),
180
+ [throwMarker]: 0
181
+ });
182
+ ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);
183
+ });
184
+ });
185
+ if (ep.start) {
186
+ ep.start();
187
+ }
188
+ }
189
+ function isMessagePort(endpoint) {
190
+ return endpoint.constructor.name === "MessagePort";
191
+ }
192
+ function closeEndPoint(endpoint) {
193
+ if (isMessagePort(endpoint))
194
+ endpoint.close();
195
+ }
196
+ function wrap(ep, target) {
197
+ const pendingListeners = /* @__PURE__ */ new Map();
198
+ ep.addEventListener("message", function handleMessage(ev) {
199
+ const { data } = ev;
200
+ if (!data || !data.id) {
201
+ return;
202
+ }
203
+ const resolver = pendingListeners.get(data.id);
204
+ if (!resolver) {
205
+ return;
206
+ }
207
+ try {
208
+ resolver(data);
209
+ } finally {
210
+ pendingListeners.delete(data.id);
211
+ }
212
+ });
213
+ return createProxy(ep, pendingListeners, [], target);
214
+ }
215
+ function throwIfProxyReleased(isReleased) {
216
+ if (isReleased) {
217
+ throw new Error("Proxy has been released and is not useable");
218
+ }
219
+ }
220
+ function releaseEndpoint(ep) {
221
+ return requestResponseMessage(ep, /* @__PURE__ */ new Map(), {
222
+ type: "RELEASE"
223
+ }).then(() => {
224
+ closeEndPoint(ep);
225
+ });
226
+ }
227
+ const proxyCounter = /* @__PURE__ */ new WeakMap();
228
+ const proxyFinalizers = "FinalizationRegistry" in globalThis && new FinalizationRegistry((ep) => {
229
+ const newCount = (proxyCounter.get(ep) || 0) - 1;
230
+ proxyCounter.set(ep, newCount);
231
+ if (newCount === 0) {
232
+ releaseEndpoint(ep);
233
+ }
234
+ });
235
+ function registerProxy(proxy2, ep) {
236
+ const newCount = (proxyCounter.get(ep) || 0) + 1;
237
+ proxyCounter.set(ep, newCount);
238
+ if (proxyFinalizers) {
239
+ proxyFinalizers.register(proxy2, ep, proxy2);
240
+ }
241
+ }
242
+ function unregisterProxy(proxy2) {
243
+ if (proxyFinalizers) {
244
+ proxyFinalizers.unregister(proxy2);
245
+ }
246
+ }
247
+ function createProxy(ep, pendingListeners, path = [], target = function() {
248
+ }) {
249
+ let isProxyReleased = false;
250
+ const proxy2 = new Proxy(target, {
251
+ get(_target, prop) {
252
+ throwIfProxyReleased(isProxyReleased);
253
+ if (prop === releaseProxy) {
254
+ return () => {
255
+ unregisterProxy(proxy2);
256
+ releaseEndpoint(ep);
257
+ pendingListeners.clear();
258
+ isProxyReleased = true;
259
+ };
260
+ }
261
+ if (prop === "then") {
262
+ if (path.length === 0) {
263
+ return { then: () => proxy2 };
264
+ }
265
+ const r = requestResponseMessage(ep, pendingListeners, {
266
+ type: "GET",
267
+ path: path.map((p) => p.toString())
268
+ }).then(fromWireValue);
269
+ return r.then.bind(r);
270
+ }
271
+ return createProxy(ep, pendingListeners, [...path, prop]);
272
+ },
273
+ set(_target, prop, rawValue) {
274
+ throwIfProxyReleased(isProxyReleased);
275
+ const [value, transferables] = toWireValue(rawValue);
276
+ return requestResponseMessage(ep, pendingListeners, {
277
+ type: "SET",
278
+ path: [...path, prop].map((p) => p.toString()),
279
+ value
280
+ }, transferables).then(fromWireValue);
281
+ },
282
+ apply(_target, _thisArg, rawArgumentList) {
283
+ throwIfProxyReleased(isProxyReleased);
284
+ const last = path[path.length - 1];
285
+ if (last === createEndpoint) {
286
+ return requestResponseMessage(ep, pendingListeners, {
287
+ type: "ENDPOINT"
288
+ }).then(fromWireValue);
289
+ }
290
+ if (last === "bind") {
291
+ return createProxy(ep, pendingListeners, path.slice(0, -1));
292
+ }
293
+ const [argumentList, transferables] = processArguments(rawArgumentList);
294
+ return requestResponseMessage(ep, pendingListeners, {
295
+ type: "APPLY",
296
+ path: path.map((p) => p.toString()),
297
+ argumentList
298
+ }, transferables).then(fromWireValue);
299
+ },
300
+ construct(_target, rawArgumentList) {
301
+ throwIfProxyReleased(isProxyReleased);
302
+ const [argumentList, transferables] = processArguments(rawArgumentList);
303
+ return requestResponseMessage(ep, pendingListeners, {
304
+ type: "CONSTRUCT",
305
+ path: path.map((p) => p.toString()),
306
+ argumentList
307
+ }, transferables).then(fromWireValue);
308
+ }
309
+ });
310
+ registerProxy(proxy2, ep);
311
+ return proxy2;
312
+ }
313
+ function myFlat(arr) {
314
+ return Array.prototype.concat.apply([], arr);
315
+ }
316
+ function processArguments(argumentList) {
317
+ const processed = argumentList.map(toWireValue);
318
+ return [processed.map((v) => v[0]), myFlat(processed.map((v) => v[1]))];
319
+ }
320
+ const transferCache = /* @__PURE__ */ new WeakMap();
321
+ function transfer(obj, transfers) {
322
+ transferCache.set(obj, transfers);
323
+ return obj;
324
+ }
325
+ function proxy(obj) {
326
+ return Object.assign(obj, { [proxyMarker]: true });
327
+ }
328
+ function toWireValue(value) {
329
+ for (const [name, handler] of transferHandlers) {
330
+ if (handler.canHandle(value)) {
331
+ const [serializedValue, transferables] = handler.serialize(value);
332
+ return [
333
+ {
334
+ type: "HANDLER",
335
+ name,
336
+ value: serializedValue
337
+ },
338
+ transferables
339
+ ];
340
+ }
341
+ }
342
+ return [
343
+ {
344
+ type: "RAW",
345
+ value
346
+ },
347
+ transferCache.get(value) || []
348
+ ];
349
+ }
350
+ function fromWireValue(value) {
351
+ switch (value.type) {
352
+ case "HANDLER":
353
+ return transferHandlers.get(value.name).deserialize(value.value);
354
+ case "RAW":
355
+ return value.value;
356
+ }
357
+ }
358
+ function requestResponseMessage(ep, pendingListeners, msg, transfers) {
359
+ return new Promise((resolve) => {
360
+ const id = generateUUID();
361
+ pendingListeners.set(id, resolve);
362
+ if (ep.start) {
363
+ ep.start();
364
+ }
365
+ ep.postMessage(Object.assign({ id }, msg), transfers);
366
+ });
367
+ }
368
+ function generateUUID() {
369
+ return new Array(4).fill(0).map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)).join("-");
370
+ }
371
+ function getDefaultExportFromCjs(x) {
372
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
373
+ }
374
+ var events = { exports: {} };
375
+ var hasRequiredEvents;
376
+ function requireEvents() {
377
+ if (hasRequiredEvents) return events.exports;
378
+ hasRequiredEvents = 1;
379
+ var R = typeof Reflect === "object" ? Reflect : null;
380
+ var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply2(target, receiver, args) {
381
+ return Function.prototype.apply.call(target, receiver, args);
382
+ };
383
+ var ReflectOwnKeys;
384
+ if (R && typeof R.ownKeys === "function") {
385
+ ReflectOwnKeys = R.ownKeys;
386
+ } else if (Object.getOwnPropertySymbols) {
387
+ ReflectOwnKeys = function ReflectOwnKeys2(target) {
388
+ return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target));
389
+ };
390
+ } else {
391
+ ReflectOwnKeys = function ReflectOwnKeys2(target) {
392
+ return Object.getOwnPropertyNames(target);
393
+ };
394
+ }
395
+ function ProcessEmitWarning(warning) {
396
+ if (console && console.warn) console.warn(warning);
397
+ }
398
+ var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) {
399
+ return value !== value;
400
+ };
401
+ function EventEmitter() {
402
+ EventEmitter.init.call(this);
403
+ }
404
+ events.exports = EventEmitter;
405
+ events.exports.once = once;
406
+ EventEmitter.EventEmitter = EventEmitter;
407
+ EventEmitter.prototype._events = void 0;
408
+ EventEmitter.prototype._eventsCount = 0;
409
+ EventEmitter.prototype._maxListeners = void 0;
410
+ var defaultMaxListeners = 10;
411
+ function checkListener(listener) {
412
+ if (typeof listener !== "function") {
413
+ throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
414
+ }
415
+ }
416
+ Object.defineProperty(EventEmitter, "defaultMaxListeners", {
417
+ enumerable: true,
418
+ get: function() {
419
+ return defaultMaxListeners;
420
+ },
421
+ set: function(arg) {
422
+ if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) {
423
+ throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + ".");
424
+ }
425
+ defaultMaxListeners = arg;
426
+ }
427
+ });
428
+ EventEmitter.init = function() {
429
+ if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) {
430
+ this._events = /* @__PURE__ */ Object.create(null);
431
+ this._eventsCount = 0;
432
+ }
433
+ this._maxListeners = this._maxListeners || void 0;
434
+ };
435
+ EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
436
+ if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) {
437
+ throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + ".");
438
+ }
439
+ this._maxListeners = n;
440
+ return this;
441
+ };
442
+ function _getMaxListeners(that) {
443
+ if (that._maxListeners === void 0)
444
+ return EventEmitter.defaultMaxListeners;
445
+ return that._maxListeners;
446
+ }
447
+ EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
448
+ return _getMaxListeners(this);
449
+ };
450
+ EventEmitter.prototype.emit = function emit(type) {
451
+ var args = [];
452
+ for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
453
+ var doError = type === "error";
454
+ var events2 = this._events;
455
+ if (events2 !== void 0)
456
+ doError = doError && events2.error === void 0;
457
+ else if (!doError)
458
+ return false;
459
+ if (doError) {
460
+ var er;
461
+ if (args.length > 0)
462
+ er = args[0];
463
+ if (er instanceof Error) {
464
+ throw er;
465
+ }
466
+ var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : ""));
467
+ err.context = er;
468
+ throw err;
469
+ }
470
+ var handler = events2[type];
471
+ if (handler === void 0)
472
+ return false;
473
+ if (typeof handler === "function") {
474
+ ReflectApply(handler, this, args);
475
+ } else {
476
+ var len = handler.length;
477
+ var listeners = arrayClone(handler, len);
478
+ for (var i = 0; i < len; ++i)
479
+ ReflectApply(listeners[i], this, args);
480
+ }
481
+ return true;
482
+ };
483
+ function _addListener(target, type, listener, prepend) {
484
+ var m;
485
+ var events2;
486
+ var existing;
487
+ checkListener(listener);
488
+ events2 = target._events;
489
+ if (events2 === void 0) {
490
+ events2 = target._events = /* @__PURE__ */ Object.create(null);
491
+ target._eventsCount = 0;
492
+ } else {
493
+ if (events2.newListener !== void 0) {
494
+ target.emit(
495
+ "newListener",
496
+ type,
497
+ listener.listener ? listener.listener : listener
498
+ );
499
+ events2 = target._events;
500
+ }
501
+ existing = events2[type];
502
+ }
503
+ if (existing === void 0) {
504
+ existing = events2[type] = listener;
505
+ ++target._eventsCount;
506
+ } else {
507
+ if (typeof existing === "function") {
508
+ existing = events2[type] = prepend ? [listener, existing] : [existing, listener];
509
+ } else if (prepend) {
510
+ existing.unshift(listener);
511
+ } else {
512
+ existing.push(listener);
513
+ }
514
+ m = _getMaxListeners(target);
515
+ if (m > 0 && existing.length > m && !existing.warned) {
516
+ existing.warned = true;
517
+ var w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit");
518
+ w.name = "MaxListenersExceededWarning";
519
+ w.emitter = target;
520
+ w.type = type;
521
+ w.count = existing.length;
522
+ ProcessEmitWarning(w);
523
+ }
524
+ }
525
+ return target;
526
+ }
527
+ EventEmitter.prototype.addListener = function addListener(type, listener) {
528
+ return _addListener(this, type, listener, false);
529
+ };
530
+ EventEmitter.prototype.on = EventEmitter.prototype.addListener;
531
+ EventEmitter.prototype.prependListener = function prependListener(type, listener) {
532
+ return _addListener(this, type, listener, true);
533
+ };
534
+ function onceWrapper() {
535
+ if (!this.fired) {
536
+ this.target.removeListener(this.type, this.wrapFn);
537
+ this.fired = true;
538
+ if (arguments.length === 0)
539
+ return this.listener.call(this.target);
540
+ return this.listener.apply(this.target, arguments);
541
+ }
542
+ }
543
+ function _onceWrap(target, type, listener) {
544
+ var state = { fired: false, wrapFn: void 0, target, type, listener };
545
+ var wrapped = onceWrapper.bind(state);
546
+ wrapped.listener = listener;
547
+ state.wrapFn = wrapped;
548
+ return wrapped;
549
+ }
550
+ EventEmitter.prototype.once = function once2(type, listener) {
551
+ checkListener(listener);
552
+ this.on(type, _onceWrap(this, type, listener));
553
+ return this;
554
+ };
555
+ EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) {
556
+ checkListener(listener);
557
+ this.prependListener(type, _onceWrap(this, type, listener));
558
+ return this;
559
+ };
560
+ EventEmitter.prototype.removeListener = function removeListener(type, listener) {
561
+ var list, events2, position, i, originalListener;
562
+ checkListener(listener);
563
+ events2 = this._events;
564
+ if (events2 === void 0)
565
+ return this;
566
+ list = events2[type];
567
+ if (list === void 0)
568
+ return this;
569
+ if (list === listener || list.listener === listener) {
570
+ if (--this._eventsCount === 0)
571
+ this._events = /* @__PURE__ */ Object.create(null);
572
+ else {
573
+ delete events2[type];
574
+ if (events2.removeListener)
575
+ this.emit("removeListener", type, list.listener || listener);
576
+ }
577
+ } else if (typeof list !== "function") {
578
+ position = -1;
579
+ for (i = list.length - 1; i >= 0; i--) {
580
+ if (list[i] === listener || list[i].listener === listener) {
581
+ originalListener = list[i].listener;
582
+ position = i;
583
+ break;
584
+ }
585
+ }
586
+ if (position < 0)
587
+ return this;
588
+ if (position === 0)
589
+ list.shift();
590
+ else {
591
+ spliceOne(list, position);
592
+ }
593
+ if (list.length === 1)
594
+ events2[type] = list[0];
595
+ if (events2.removeListener !== void 0)
596
+ this.emit("removeListener", type, originalListener || listener);
597
+ }
598
+ return this;
599
+ };
600
+ EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
601
+ EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) {
602
+ var listeners, events2, i;
603
+ events2 = this._events;
604
+ if (events2 === void 0)
605
+ return this;
606
+ if (events2.removeListener === void 0) {
607
+ if (arguments.length === 0) {
608
+ this._events = /* @__PURE__ */ Object.create(null);
609
+ this._eventsCount = 0;
610
+ } else if (events2[type] !== void 0) {
611
+ if (--this._eventsCount === 0)
612
+ this._events = /* @__PURE__ */ Object.create(null);
613
+ else
614
+ delete events2[type];
615
+ }
616
+ return this;
617
+ }
618
+ if (arguments.length === 0) {
619
+ var keys = Object.keys(events2);
620
+ var key;
621
+ for (i = 0; i < keys.length; ++i) {
622
+ key = keys[i];
623
+ if (key === "removeListener") continue;
624
+ this.removeAllListeners(key);
625
+ }
626
+ this.removeAllListeners("removeListener");
627
+ this._events = /* @__PURE__ */ Object.create(null);
628
+ this._eventsCount = 0;
629
+ return this;
630
+ }
631
+ listeners = events2[type];
632
+ if (typeof listeners === "function") {
633
+ this.removeListener(type, listeners);
634
+ } else if (listeners !== void 0) {
635
+ for (i = listeners.length - 1; i >= 0; i--) {
636
+ this.removeListener(type, listeners[i]);
637
+ }
638
+ }
639
+ return this;
640
+ };
641
+ function _listeners(target, type, unwrap) {
642
+ var events2 = target._events;
643
+ if (events2 === void 0)
644
+ return [];
645
+ var evlistener = events2[type];
646
+ if (evlistener === void 0)
647
+ return [];
648
+ if (typeof evlistener === "function")
649
+ return unwrap ? [evlistener.listener || evlistener] : [evlistener];
650
+ return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
651
+ }
652
+ EventEmitter.prototype.listeners = function listeners(type) {
653
+ return _listeners(this, type, true);
654
+ };
655
+ EventEmitter.prototype.rawListeners = function rawListeners(type) {
656
+ return _listeners(this, type, false);
657
+ };
658
+ EventEmitter.listenerCount = function(emitter, type) {
659
+ if (typeof emitter.listenerCount === "function") {
660
+ return emitter.listenerCount(type);
661
+ } else {
662
+ return listenerCount.call(emitter, type);
663
+ }
664
+ };
665
+ EventEmitter.prototype.listenerCount = listenerCount;
666
+ function listenerCount(type) {
667
+ var events2 = this._events;
668
+ if (events2 !== void 0) {
669
+ var evlistener = events2[type];
670
+ if (typeof evlistener === "function") {
671
+ return 1;
672
+ } else if (evlistener !== void 0) {
673
+ return evlistener.length;
674
+ }
675
+ }
676
+ return 0;
677
+ }
678
+ EventEmitter.prototype.eventNames = function eventNames() {
679
+ return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
680
+ };
681
+ function arrayClone(arr, n) {
682
+ var copy = new Array(n);
683
+ for (var i = 0; i < n; ++i)
684
+ copy[i] = arr[i];
685
+ return copy;
686
+ }
687
+ function spliceOne(list, index) {
688
+ for (; index + 1 < list.length; index++)
689
+ list[index] = list[index + 1];
690
+ list.pop();
691
+ }
692
+ function unwrapListeners(arr) {
693
+ var ret = new Array(arr.length);
694
+ for (var i = 0; i < ret.length; ++i) {
695
+ ret[i] = arr[i].listener || arr[i];
696
+ }
697
+ return ret;
698
+ }
699
+ function once(emitter, name) {
700
+ return new Promise(function(resolve, reject) {
701
+ function errorListener(err) {
702
+ emitter.removeListener(name, resolver);
703
+ reject(err);
704
+ }
705
+ function resolver() {
706
+ if (typeof emitter.removeListener === "function") {
707
+ emitter.removeListener("error", errorListener);
708
+ }
709
+ resolve([].slice.call(arguments));
710
+ }
711
+ eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
712
+ if (name !== "error") {
713
+ addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
714
+ }
715
+ });
716
+ }
717
+ function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
718
+ if (typeof emitter.on === "function") {
719
+ eventTargetAgnosticAddListener(emitter, "error", handler, flags);
720
+ }
721
+ }
722
+ function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
723
+ if (typeof emitter.on === "function") {
724
+ if (flags.once) {
725
+ emitter.once(name, listener);
726
+ } else {
727
+ emitter.on(name, listener);
728
+ }
729
+ } else if (typeof emitter.addEventListener === "function") {
730
+ emitter.addEventListener(name, function wrapListener(arg) {
731
+ if (flags.once) {
732
+ emitter.removeEventListener(name, wrapListener);
733
+ }
734
+ listener(arg);
735
+ });
736
+ } else {
737
+ throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
738
+ }
739
+ }
740
+ return events.exports;
741
+ }
742
+ var factoryValidator;
743
+ var hasRequiredFactoryValidator;
744
+ function requireFactoryValidator() {
745
+ if (hasRequiredFactoryValidator) return factoryValidator;
746
+ hasRequiredFactoryValidator = 1;
747
+ factoryValidator = function(factory) {
748
+ if (typeof factory.create !== "function") {
749
+ throw new TypeError("factory.create must be a function");
750
+ }
751
+ if (typeof factory.destroy !== "function") {
752
+ throw new TypeError("factory.destroy must be a function");
753
+ }
754
+ if (typeof factory.validate !== "undefined" && typeof factory.validate !== "function") {
755
+ throw new TypeError("factory.validate must be a function");
756
+ }
757
+ };
758
+ return factoryValidator;
759
+ }
760
+ var PoolDefaults_1;
761
+ var hasRequiredPoolDefaults;
762
+ function requirePoolDefaults() {
763
+ if (hasRequiredPoolDefaults) return PoolDefaults_1;
764
+ hasRequiredPoolDefaults = 1;
765
+ class PoolDefaults {
766
+ constructor() {
767
+ this.fifo = true;
768
+ this.priorityRange = 1;
769
+ this.testOnBorrow = false;
770
+ this.testOnReturn = false;
771
+ this.autostart = true;
772
+ this.evictionRunIntervalMillis = 0;
773
+ this.numTestsPerEvictionRun = 3;
774
+ this.softIdleTimeoutMillis = -1;
775
+ this.idleTimeoutMillis = 3e4;
776
+ this.acquireTimeoutMillis = null;
777
+ this.destroyTimeoutMillis = null;
778
+ this.maxWaitingClients = null;
779
+ this.min = null;
780
+ this.max = null;
781
+ this.Promise = Promise;
782
+ }
783
+ }
784
+ PoolDefaults_1 = PoolDefaults;
785
+ return PoolDefaults_1;
786
+ }
787
+ var PoolOptions_1;
788
+ var hasRequiredPoolOptions;
789
+ function requirePoolOptions() {
790
+ if (hasRequiredPoolOptions) return PoolOptions_1;
791
+ hasRequiredPoolOptions = 1;
792
+ const PoolDefaults = requirePoolDefaults();
793
+ class PoolOptions {
794
+ /**
795
+ * @param {Object} opts
796
+ * configuration for the pool
797
+ * @param {Number} [opts.max=null]
798
+ * Maximum number of items that can exist at the same time. Default: 1.
799
+ * Any further acquire requests will be pushed to the waiting list.
800
+ * @param {Number} [opts.min=null]
801
+ * Minimum number of items in pool (including in-use). Default: 0.
802
+ * When the pool is created, or a resource destroyed, this minimum will
803
+ * be checked. If the pool resource count is below the minimum, a new
804
+ * resource will be created and added to the pool.
805
+ * @param {Number} [opts.maxWaitingClients=null]
806
+ * maximum number of queued requests allowed after which acquire calls will be rejected
807
+ * @param {Boolean} [opts.testOnBorrow=false]
808
+ * should the pool validate resources before giving them to clients. Requires that
809
+ * `factory.validate` is specified.
810
+ * @param {Boolean} [opts.testOnReturn=false]
811
+ * should the pool validate resources before returning them to the pool.
812
+ * @param {Number} [opts.acquireTimeoutMillis=null]
813
+ * Delay in milliseconds after which the an `acquire` call will fail. optional.
814
+ * Default: undefined. Should be positive and non-zero
815
+ * @param {Number} [opts.destroyTimeoutMillis=null]
816
+ * Delay in milliseconds after which the an `destroy` call will fail, causing it to emit a factoryDestroyError event. optional.
817
+ * Default: undefined. Should be positive and non-zero
818
+ * @param {Number} [opts.priorityRange=1]
819
+ * The range from 1 to be treated as a valid priority
820
+ * @param {Boolean} [opts.fifo=true]
821
+ * Sets whether the pool has LIFO (last in, first out) behaviour with respect to idle objects.
822
+ * if false then pool has FIFO behaviour
823
+ * @param {Boolean} [opts.autostart=true]
824
+ * Should the pool start creating resources etc once the constructor is called
825
+ * @param {Number} [opts.evictionRunIntervalMillis=0]
826
+ * How often to run eviction checks. Default: 0 (does not run).
827
+ * @param {Number} [opts.numTestsPerEvictionRun=3]
828
+ * Number of resources to check each eviction run. Default: 3.
829
+ * @param {Number} [opts.softIdleTimeoutMillis=-1]
830
+ * amount of time an object may sit idle in the pool before it is eligible
831
+ * for eviction by the idle object evictor (if any), with the extra condition
832
+ * that at least "min idle" object instances remain in the pool. Default -1 (nothing can get evicted)
833
+ * @param {Number} [opts.idleTimeoutMillis=30000]
834
+ * the minimum amount of time that an object may sit idle in the pool before it is eligible for eviction
835
+ * due to idle time. Supercedes "softIdleTimeoutMillis" Default: 30000
836
+ * @param {typeof Promise} [opts.Promise=Promise]
837
+ * What promise implementation should the pool use, defaults to native promises.
838
+ */
839
+ constructor(opts) {
840
+ const poolDefaults = new PoolDefaults();
841
+ opts = opts || {};
842
+ this.fifo = typeof opts.fifo === "boolean" ? opts.fifo : poolDefaults.fifo;
843
+ this.priorityRange = opts.priorityRange || poolDefaults.priorityRange;
844
+ this.testOnBorrow = typeof opts.testOnBorrow === "boolean" ? opts.testOnBorrow : poolDefaults.testOnBorrow;
845
+ this.testOnReturn = typeof opts.testOnReturn === "boolean" ? opts.testOnReturn : poolDefaults.testOnReturn;
846
+ this.autostart = typeof opts.autostart === "boolean" ? opts.autostart : poolDefaults.autostart;
847
+ if (opts.acquireTimeoutMillis) {
848
+ this.acquireTimeoutMillis = parseInt(opts.acquireTimeoutMillis, 10);
849
+ }
850
+ if (opts.destroyTimeoutMillis) {
851
+ this.destroyTimeoutMillis = parseInt(opts.destroyTimeoutMillis, 10);
852
+ }
853
+ if (opts.maxWaitingClients !== void 0) {
854
+ this.maxWaitingClients = parseInt(opts.maxWaitingClients, 10);
855
+ }
856
+ this.max = parseInt(opts.max, 10);
857
+ this.min = parseInt(opts.min, 10);
858
+ this.max = Math.max(isNaN(this.max) ? 1 : this.max, 1);
859
+ this.min = Math.min(isNaN(this.min) ? 0 : this.min, this.max);
860
+ this.evictionRunIntervalMillis = opts.evictionRunIntervalMillis || poolDefaults.evictionRunIntervalMillis;
861
+ this.numTestsPerEvictionRun = opts.numTestsPerEvictionRun || poolDefaults.numTestsPerEvictionRun;
862
+ this.softIdleTimeoutMillis = opts.softIdleTimeoutMillis || poolDefaults.softIdleTimeoutMillis;
863
+ this.idleTimeoutMillis = opts.idleTimeoutMillis || poolDefaults.idleTimeoutMillis;
864
+ this.Promise = opts.Promise != null ? opts.Promise : poolDefaults.Promise;
865
+ }
866
+ }
867
+ PoolOptions_1 = PoolOptions;
868
+ return PoolOptions_1;
869
+ }
870
+ var Deferred_1;
871
+ var hasRequiredDeferred;
872
+ function requireDeferred() {
873
+ if (hasRequiredDeferred) return Deferred_1;
874
+ hasRequiredDeferred = 1;
875
+ class Deferred {
876
+ constructor(Promise2) {
877
+ this._state = Deferred.PENDING;
878
+ this._resolve = void 0;
879
+ this._reject = void 0;
880
+ this._promise = new Promise2((resolve, reject) => {
881
+ this._resolve = resolve;
882
+ this._reject = reject;
883
+ });
884
+ }
885
+ get state() {
886
+ return this._state;
887
+ }
888
+ get promise() {
889
+ return this._promise;
890
+ }
891
+ reject(reason) {
892
+ if (this._state !== Deferred.PENDING) {
893
+ return;
894
+ }
895
+ this._state = Deferred.REJECTED;
896
+ this._reject(reason);
897
+ }
898
+ resolve(value) {
899
+ if (this._state !== Deferred.PENDING) {
900
+ return;
901
+ }
902
+ this._state = Deferred.FULFILLED;
903
+ this._resolve(value);
904
+ }
905
+ }
906
+ Deferred.PENDING = "PENDING";
907
+ Deferred.FULFILLED = "FULFILLED";
908
+ Deferred.REJECTED = "REJECTED";
909
+ Deferred_1 = Deferred;
910
+ return Deferred_1;
911
+ }
912
+ var errors;
913
+ var hasRequiredErrors;
914
+ function requireErrors() {
915
+ if (hasRequiredErrors) return errors;
916
+ hasRequiredErrors = 1;
917
+ class ExtendableError extends Error {
918
+ constructor(message) {
919
+ super(message);
920
+ this.name = this.constructor.name;
921
+ this.message = message;
922
+ if (typeof Error.captureStackTrace === "function") {
923
+ Error.captureStackTrace(this, this.constructor);
924
+ } else {
925
+ this.stack = new Error(message).stack;
926
+ }
927
+ }
928
+ }
929
+ class TimeoutError extends ExtendableError {
930
+ constructor(m) {
931
+ super(m);
932
+ }
933
+ }
934
+ errors = {
935
+ TimeoutError
936
+ };
937
+ return errors;
938
+ }
939
+ var ResourceRequest_1;
940
+ var hasRequiredResourceRequest;
941
+ function requireResourceRequest() {
942
+ if (hasRequiredResourceRequest) return ResourceRequest_1;
943
+ hasRequiredResourceRequest = 1;
944
+ const Deferred = requireDeferred();
945
+ const errors2 = requireErrors();
946
+ function fbind(fn, ctx) {
947
+ return function bound() {
948
+ return fn.apply(ctx, arguments);
949
+ };
950
+ }
951
+ class ResourceRequest extends Deferred {
952
+ /**
953
+ * [constructor description]
954
+ * @param {Number} ttl timeout
955
+ */
956
+ constructor(ttl, Promise2) {
957
+ super(Promise2);
958
+ this._creationTimestamp = Date.now();
959
+ this._timeout = null;
960
+ if (ttl !== void 0) {
961
+ this.setTimeout(ttl);
962
+ }
963
+ }
964
+ setTimeout(delay) {
965
+ if (this._state !== ResourceRequest.PENDING) {
966
+ return;
967
+ }
968
+ const ttl = parseInt(delay, 10);
969
+ if (isNaN(ttl) || ttl <= 0) {
970
+ throw new Error("delay must be a positive int");
971
+ }
972
+ const age = Date.now() - this._creationTimestamp;
973
+ if (this._timeout) {
974
+ this.removeTimeout();
975
+ }
976
+ this._timeout = setTimeout(
977
+ fbind(this._fireTimeout, this),
978
+ Math.max(ttl - age, 0)
979
+ );
980
+ }
981
+ removeTimeout() {
982
+ if (this._timeout) {
983
+ clearTimeout(this._timeout);
984
+ }
985
+ this._timeout = null;
986
+ }
987
+ _fireTimeout() {
988
+ this.reject(new errors2.TimeoutError("ResourceRequest timed out"));
989
+ }
990
+ reject(reason) {
991
+ this.removeTimeout();
992
+ super.reject(reason);
993
+ }
994
+ resolve(value) {
995
+ this.removeTimeout();
996
+ super.resolve(value);
997
+ }
998
+ }
999
+ ResourceRequest_1 = ResourceRequest;
1000
+ return ResourceRequest_1;
1001
+ }
1002
+ var ResourceLoan_1;
1003
+ var hasRequiredResourceLoan;
1004
+ function requireResourceLoan() {
1005
+ if (hasRequiredResourceLoan) return ResourceLoan_1;
1006
+ hasRequiredResourceLoan = 1;
1007
+ const Deferred = requireDeferred();
1008
+ class ResourceLoan extends Deferred {
1009
+ /**
1010
+ *
1011
+ * @param {any} pooledResource the PooledResource this loan belongs to
1012
+ * @return {any} [description]
1013
+ */
1014
+ constructor(pooledResource, Promise2) {
1015
+ super(Promise2);
1016
+ this._creationTimestamp = Date.now();
1017
+ this.pooledResource = pooledResource;
1018
+ }
1019
+ reject() {
1020
+ }
1021
+ }
1022
+ ResourceLoan_1 = ResourceLoan;
1023
+ return ResourceLoan_1;
1024
+ }
1025
+ var PooledResourceStateEnum_1;
1026
+ var hasRequiredPooledResourceStateEnum;
1027
+ function requirePooledResourceStateEnum() {
1028
+ if (hasRequiredPooledResourceStateEnum) return PooledResourceStateEnum_1;
1029
+ hasRequiredPooledResourceStateEnum = 1;
1030
+ const PooledResourceStateEnum = {
1031
+ ALLOCATED: "ALLOCATED",
1032
+ // In use
1033
+ IDLE: "IDLE",
1034
+ // In the queue, not in use.
1035
+ INVALID: "INVALID",
1036
+ // Failed validation
1037
+ RETURNING: "RETURNING",
1038
+ // Resource is in process of returning
1039
+ VALIDATION: "VALIDATION"
1040
+ // Currently being tested
1041
+ };
1042
+ PooledResourceStateEnum_1 = PooledResourceStateEnum;
1043
+ return PooledResourceStateEnum_1;
1044
+ }
1045
+ var PooledResource_1;
1046
+ var hasRequiredPooledResource;
1047
+ function requirePooledResource() {
1048
+ if (hasRequiredPooledResource) return PooledResource_1;
1049
+ hasRequiredPooledResource = 1;
1050
+ const PooledResourceStateEnum = requirePooledResourceStateEnum();
1051
+ class PooledResource {
1052
+ constructor(resource) {
1053
+ this.creationTime = Date.now();
1054
+ this.lastReturnTime = null;
1055
+ this.lastBorrowTime = null;
1056
+ this.lastIdleTime = null;
1057
+ this.obj = resource;
1058
+ this.state = PooledResourceStateEnum.IDLE;
1059
+ }
1060
+ // mark the resource as "allocated"
1061
+ allocate() {
1062
+ this.lastBorrowTime = Date.now();
1063
+ this.state = PooledResourceStateEnum.ALLOCATED;
1064
+ }
1065
+ // mark the resource as "deallocated"
1066
+ deallocate() {
1067
+ this.lastReturnTime = Date.now();
1068
+ this.state = PooledResourceStateEnum.IDLE;
1069
+ }
1070
+ invalidate() {
1071
+ this.state = PooledResourceStateEnum.INVALID;
1072
+ }
1073
+ test() {
1074
+ this.state = PooledResourceStateEnum.VALIDATION;
1075
+ }
1076
+ idle() {
1077
+ this.lastIdleTime = Date.now();
1078
+ this.state = PooledResourceStateEnum.IDLE;
1079
+ }
1080
+ returning() {
1081
+ this.state = PooledResourceStateEnum.RETURNING;
1082
+ }
1083
+ }
1084
+ PooledResource_1 = PooledResource;
1085
+ return PooledResource_1;
1086
+ }
1087
+ var DefaultEvictor_1;
1088
+ var hasRequiredDefaultEvictor;
1089
+ function requireDefaultEvictor() {
1090
+ if (hasRequiredDefaultEvictor) return DefaultEvictor_1;
1091
+ hasRequiredDefaultEvictor = 1;
1092
+ class DefaultEvictor {
1093
+ evict(config, pooledResource, availableObjectsCount) {
1094
+ const idleTime = Date.now() - pooledResource.lastIdleTime;
1095
+ if (config.softIdleTimeoutMillis > 0 && config.softIdleTimeoutMillis < idleTime && config.min < availableObjectsCount) {
1096
+ return true;
1097
+ }
1098
+ if (config.idleTimeoutMillis < idleTime) {
1099
+ return true;
1100
+ }
1101
+ return false;
1102
+ }
1103
+ }
1104
+ DefaultEvictor_1 = DefaultEvictor;
1105
+ return DefaultEvictor_1;
1106
+ }
1107
+ var DoublyLinkedList_1;
1108
+ var hasRequiredDoublyLinkedList;
1109
+ function requireDoublyLinkedList() {
1110
+ if (hasRequiredDoublyLinkedList) return DoublyLinkedList_1;
1111
+ hasRequiredDoublyLinkedList = 1;
1112
+ class DoublyLinkedList {
1113
+ constructor() {
1114
+ this.head = null;
1115
+ this.tail = null;
1116
+ this.length = 0;
1117
+ }
1118
+ insertBeginning(node) {
1119
+ if (this.head === null) {
1120
+ this.head = node;
1121
+ this.tail = node;
1122
+ node.prev = null;
1123
+ node.next = null;
1124
+ this.length++;
1125
+ } else {
1126
+ this.insertBefore(this.head, node);
1127
+ }
1128
+ }
1129
+ insertEnd(node) {
1130
+ if (this.tail === null) {
1131
+ this.insertBeginning(node);
1132
+ } else {
1133
+ this.insertAfter(this.tail, node);
1134
+ }
1135
+ }
1136
+ insertAfter(node, newNode) {
1137
+ newNode.prev = node;
1138
+ newNode.next = node.next;
1139
+ if (node.next === null) {
1140
+ this.tail = newNode;
1141
+ } else {
1142
+ node.next.prev = newNode;
1143
+ }
1144
+ node.next = newNode;
1145
+ this.length++;
1146
+ }
1147
+ insertBefore(node, newNode) {
1148
+ newNode.prev = node.prev;
1149
+ newNode.next = node;
1150
+ if (node.prev === null) {
1151
+ this.head = newNode;
1152
+ } else {
1153
+ node.prev.next = newNode;
1154
+ }
1155
+ node.prev = newNode;
1156
+ this.length++;
1157
+ }
1158
+ remove(node) {
1159
+ if (node.prev === null) {
1160
+ this.head = node.next;
1161
+ } else {
1162
+ node.prev.next = node.next;
1163
+ }
1164
+ if (node.next === null) {
1165
+ this.tail = node.prev;
1166
+ } else {
1167
+ node.next.prev = node.prev;
1168
+ }
1169
+ node.prev = null;
1170
+ node.next = null;
1171
+ this.length--;
1172
+ }
1173
+ // FIXME: this should not live here and has become a dumping ground...
1174
+ static createNode(data) {
1175
+ return {
1176
+ prev: null,
1177
+ next: null,
1178
+ data
1179
+ };
1180
+ }
1181
+ }
1182
+ DoublyLinkedList_1 = DoublyLinkedList;
1183
+ return DoublyLinkedList_1;
1184
+ }
1185
+ var DoublyLinkedListIterator_1;
1186
+ var hasRequiredDoublyLinkedListIterator;
1187
+ function requireDoublyLinkedListIterator() {
1188
+ if (hasRequiredDoublyLinkedListIterator) return DoublyLinkedListIterator_1;
1189
+ hasRequiredDoublyLinkedListIterator = 1;
1190
+ class DoublyLinkedListIterator {
1191
+ /**
1192
+ * @param {Object} doublyLinkedList a node that is part of a doublyLinkedList
1193
+ * @param {Boolean} [reverse=false] is this a reverse iterator? default: false
1194
+ */
1195
+ constructor(doublyLinkedList, reverse) {
1196
+ this._list = doublyLinkedList;
1197
+ this._direction = reverse === true ? "prev" : "next";
1198
+ this._startPosition = reverse === true ? "tail" : "head";
1199
+ this._started = false;
1200
+ this._cursor = null;
1201
+ this._done = false;
1202
+ }
1203
+ _start() {
1204
+ this._cursor = this._list[this._startPosition];
1205
+ this._started = true;
1206
+ }
1207
+ _advanceCursor() {
1208
+ if (this._started === false) {
1209
+ this._started = true;
1210
+ this._cursor = this._list[this._startPosition];
1211
+ return;
1212
+ }
1213
+ this._cursor = this._cursor[this._direction];
1214
+ }
1215
+ reset() {
1216
+ this._done = false;
1217
+ this._started = false;
1218
+ this._cursor = null;
1219
+ }
1220
+ remove() {
1221
+ if (this._started === false || this._done === true || this._isCursorDetached()) {
1222
+ return false;
1223
+ }
1224
+ this._list.remove(this._cursor);
1225
+ }
1226
+ next() {
1227
+ if (this._done === true) {
1228
+ return { done: true };
1229
+ }
1230
+ this._advanceCursor();
1231
+ if (this._cursor === null || this._isCursorDetached()) {
1232
+ this._done = true;
1233
+ return { done: true };
1234
+ }
1235
+ return {
1236
+ value: this._cursor,
1237
+ done: false
1238
+ };
1239
+ }
1240
+ /**
1241
+ * Is the node detached from a list?
1242
+ * NOTE: you can trick/bypass/confuse this check by removing a node from one DoublyLinkedList
1243
+ * and adding it to another.
1244
+ * TODO: We can make this smarter by checking the direction of travel and only checking
1245
+ * the required next/prev/head/tail rather than all of them
1246
+ * @return {Boolean} [description]
1247
+ */
1248
+ _isCursorDetached() {
1249
+ return this._cursor.prev === null && this._cursor.next === null && this._list.tail !== this._cursor && this._list.head !== this._cursor;
1250
+ }
1251
+ }
1252
+ DoublyLinkedListIterator_1 = DoublyLinkedListIterator;
1253
+ return DoublyLinkedListIterator_1;
1254
+ }
1255
+ var DequeIterator_1;
1256
+ var hasRequiredDequeIterator;
1257
+ function requireDequeIterator() {
1258
+ if (hasRequiredDequeIterator) return DequeIterator_1;
1259
+ hasRequiredDequeIterator = 1;
1260
+ const DoublyLinkedListIterator = requireDoublyLinkedListIterator();
1261
+ class DequeIterator extends DoublyLinkedListIterator {
1262
+ next() {
1263
+ const result = super.next();
1264
+ if (result.value) {
1265
+ result.value = result.value.data;
1266
+ }
1267
+ return result;
1268
+ }
1269
+ }
1270
+ DequeIterator_1 = DequeIterator;
1271
+ return DequeIterator_1;
1272
+ }
1273
+ var Deque_1;
1274
+ var hasRequiredDeque;
1275
+ function requireDeque() {
1276
+ if (hasRequiredDeque) return Deque_1;
1277
+ hasRequiredDeque = 1;
1278
+ const DoublyLinkedList = requireDoublyLinkedList();
1279
+ const DequeIterator = requireDequeIterator();
1280
+ class Deque {
1281
+ constructor() {
1282
+ this._list = new DoublyLinkedList();
1283
+ }
1284
+ /**
1285
+ * removes and returns the first element from the queue
1286
+ * @return {any} [description]
1287
+ */
1288
+ shift() {
1289
+ if (this.length === 0) {
1290
+ return void 0;
1291
+ }
1292
+ const node = this._list.head;
1293
+ this._list.remove(node);
1294
+ return node.data;
1295
+ }
1296
+ /**
1297
+ * adds one elemts to the beginning of the queue
1298
+ * @param {any} element [description]
1299
+ * @return {any} [description]
1300
+ */
1301
+ unshift(element) {
1302
+ const node = DoublyLinkedList.createNode(element);
1303
+ this._list.insertBeginning(node);
1304
+ }
1305
+ /**
1306
+ * adds one to the end of the queue
1307
+ * @param {any} element [description]
1308
+ * @return {any} [description]
1309
+ */
1310
+ push(element) {
1311
+ const node = DoublyLinkedList.createNode(element);
1312
+ this._list.insertEnd(node);
1313
+ }
1314
+ /**
1315
+ * removes and returns the last element from the queue
1316
+ */
1317
+ pop() {
1318
+ if (this.length === 0) {
1319
+ return void 0;
1320
+ }
1321
+ const node = this._list.tail;
1322
+ this._list.remove(node);
1323
+ return node.data;
1324
+ }
1325
+ [Symbol.iterator]() {
1326
+ return new DequeIterator(this._list);
1327
+ }
1328
+ iterator() {
1329
+ return new DequeIterator(this._list);
1330
+ }
1331
+ reverseIterator() {
1332
+ return new DequeIterator(this._list, true);
1333
+ }
1334
+ /**
1335
+ * get a reference to the item at the head of the queue
1336
+ * @return {any} [description]
1337
+ */
1338
+ get head() {
1339
+ if (this.length === 0) {
1340
+ return void 0;
1341
+ }
1342
+ const node = this._list.head;
1343
+ return node.data;
1344
+ }
1345
+ /**
1346
+ * get a reference to the item at the tail of the queue
1347
+ * @return {any} [description]
1348
+ */
1349
+ get tail() {
1350
+ if (this.length === 0) {
1351
+ return void 0;
1352
+ }
1353
+ const node = this._list.tail;
1354
+ return node.data;
1355
+ }
1356
+ get length() {
1357
+ return this._list.length;
1358
+ }
1359
+ }
1360
+ Deque_1 = Deque;
1361
+ return Deque_1;
1362
+ }
1363
+ var Queue_1;
1364
+ var hasRequiredQueue;
1365
+ function requireQueue() {
1366
+ if (hasRequiredQueue) return Queue_1;
1367
+ hasRequiredQueue = 1;
1368
+ const DoublyLinkedList = requireDoublyLinkedList();
1369
+ const Deque = requireDeque();
1370
+ class Queue extends Deque {
1371
+ /**
1372
+ * Adds the obj to the end of the list for this slot
1373
+ * we completely override the parent method because we need access to the
1374
+ * node for our rejection handler
1375
+ * @param {any} resourceRequest [description]
1376
+ */
1377
+ push(resourceRequest) {
1378
+ const node = DoublyLinkedList.createNode(resourceRequest);
1379
+ resourceRequest.promise.catch(this._createTimeoutRejectionHandler(node));
1380
+ this._list.insertEnd(node);
1381
+ }
1382
+ _createTimeoutRejectionHandler(node) {
1383
+ return (reason) => {
1384
+ if (reason.name === "TimeoutError") {
1385
+ this._list.remove(node);
1386
+ }
1387
+ };
1388
+ }
1389
+ }
1390
+ Queue_1 = Queue;
1391
+ return Queue_1;
1392
+ }
1393
+ var PriorityQueue_1;
1394
+ var hasRequiredPriorityQueue;
1395
+ function requirePriorityQueue() {
1396
+ if (hasRequiredPriorityQueue) return PriorityQueue_1;
1397
+ hasRequiredPriorityQueue = 1;
1398
+ const Queue = requireQueue();
1399
+ class PriorityQueue {
1400
+ constructor(size) {
1401
+ this._size = Math.max(+size | 0, 1);
1402
+ this._slots = [];
1403
+ for (let i = 0; i < this._size; i++) {
1404
+ this._slots.push(new Queue());
1405
+ }
1406
+ }
1407
+ get length() {
1408
+ let _length = 0;
1409
+ for (let i = 0, slots = this._slots.length; i < slots; i++) {
1410
+ _length += this._slots[i].length;
1411
+ }
1412
+ return _length;
1413
+ }
1414
+ enqueue(obj, priority) {
1415
+ priority = priority && +priority | 0 || 0;
1416
+ if (priority) {
1417
+ if (priority < 0 || priority >= this._size) {
1418
+ priority = this._size - 1;
1419
+ }
1420
+ }
1421
+ this._slots[priority].push(obj);
1422
+ }
1423
+ dequeue() {
1424
+ for (let i = 0, sl = this._slots.length; i < sl; i += 1) {
1425
+ if (this._slots[i].length) {
1426
+ return this._slots[i].shift();
1427
+ }
1428
+ }
1429
+ return;
1430
+ }
1431
+ get head() {
1432
+ for (let i = 0, sl = this._slots.length; i < sl; i += 1) {
1433
+ if (this._slots[i].length > 0) {
1434
+ return this._slots[i].head;
1435
+ }
1436
+ }
1437
+ return;
1438
+ }
1439
+ get tail() {
1440
+ for (let i = this._slots.length - 1; i >= 0; i--) {
1441
+ if (this._slots[i].length > 0) {
1442
+ return this._slots[i].tail;
1443
+ }
1444
+ }
1445
+ return;
1446
+ }
1447
+ }
1448
+ PriorityQueue_1 = PriorityQueue;
1449
+ return PriorityQueue_1;
1450
+ }
1451
+ var utils = {};
1452
+ var hasRequiredUtils;
1453
+ function requireUtils() {
1454
+ if (hasRequiredUtils) return utils;
1455
+ hasRequiredUtils = 1;
1456
+ function noop() {
1457
+ }
1458
+ utils.reflector = function(promise) {
1459
+ return promise.then(noop, noop);
1460
+ };
1461
+ return utils;
1462
+ }
1463
+ var Pool_1;
1464
+ var hasRequiredPool;
1465
+ function requirePool() {
1466
+ if (hasRequiredPool) return Pool_1;
1467
+ hasRequiredPool = 1;
1468
+ const EventEmitter = requireEvents().EventEmitter;
1469
+ const factoryValidator2 = requireFactoryValidator();
1470
+ const PoolOptions = requirePoolOptions();
1471
+ const ResourceRequest = requireResourceRequest();
1472
+ const ResourceLoan = requireResourceLoan();
1473
+ const PooledResource = requirePooledResource();
1474
+ requireDefaultEvictor();
1475
+ requireDeque();
1476
+ const Deferred = requireDeferred();
1477
+ requirePriorityQueue();
1478
+ requireDequeIterator();
1479
+ const reflector = requireUtils().reflector;
1480
+ const FACTORY_CREATE_ERROR = "factoryCreateError";
1481
+ const FACTORY_DESTROY_ERROR = "factoryDestroyError";
1482
+ class Pool extends EventEmitter {
1483
+ /**
1484
+ * Generate an Object pool with a specified `factory` and `config`.
1485
+ *
1486
+ * @param {typeof DefaultEvictor} Evictor
1487
+ * @param {typeof Deque} Deque
1488
+ * @param {typeof PriorityQueue} PriorityQueue
1489
+ * @param {Object} factory
1490
+ * Factory to be used for generating and destroying the items.
1491
+ * @param {Function} factory.create
1492
+ * Should create the item to be acquired,
1493
+ * and call it's first callback argument with the generated item as it's argument.
1494
+ * @param {Function} factory.destroy
1495
+ * Should gently close any resources that the item is using.
1496
+ * Called before the items is destroyed.
1497
+ * @param {Function} factory.validate
1498
+ * Test if a resource is still valid .Should return a promise that resolves to a boolean, true if resource is still valid and false
1499
+ * If it should be removed from pool.
1500
+ * @param {Object} options
1501
+ */
1502
+ constructor(Evictor, Deque, PriorityQueue, factory, options) {
1503
+ super();
1504
+ factoryValidator2(factory);
1505
+ this._config = new PoolOptions(options);
1506
+ this._Promise = this._config.Promise;
1507
+ this._factory = factory;
1508
+ this._draining = false;
1509
+ this._started = false;
1510
+ this._waitingClientsQueue = new PriorityQueue(this._config.priorityRange);
1511
+ this._factoryCreateOperations = /* @__PURE__ */ new Set();
1512
+ this._factoryDestroyOperations = /* @__PURE__ */ new Set();
1513
+ this._availableObjects = new Deque();
1514
+ this._testOnBorrowResources = /* @__PURE__ */ new Set();
1515
+ this._testOnReturnResources = /* @__PURE__ */ new Set();
1516
+ this._validationOperations = /* @__PURE__ */ new Set();
1517
+ this._allObjects = /* @__PURE__ */ new Set();
1518
+ this._resourceLoans = /* @__PURE__ */ new Map();
1519
+ this._evictionIterator = this._availableObjects.iterator();
1520
+ this._evictor = new Evictor();
1521
+ this._scheduledEviction = null;
1522
+ if (this._config.autostart === true) {
1523
+ this.start();
1524
+ }
1525
+ }
1526
+ _destroy(pooledResource) {
1527
+ pooledResource.invalidate();
1528
+ this._allObjects.delete(pooledResource);
1529
+ const destroyPromise = this._factory.destroy(pooledResource.obj);
1530
+ const wrappedDestroyPromise = this._config.destroyTimeoutMillis ? this._Promise.resolve(this._applyDestroyTimeout(destroyPromise)) : this._Promise.resolve(destroyPromise);
1531
+ this._trackOperation(
1532
+ wrappedDestroyPromise,
1533
+ this._factoryDestroyOperations
1534
+ ).catch((reason) => {
1535
+ this.emit(FACTORY_DESTROY_ERROR, reason);
1536
+ });
1537
+ this._ensureMinimum();
1538
+ }
1539
+ _applyDestroyTimeout(promise) {
1540
+ const timeoutPromise = new this._Promise((resolve, reject) => {
1541
+ setTimeout(() => {
1542
+ reject(new Error("destroy timed out"));
1543
+ }, this._config.destroyTimeoutMillis).unref();
1544
+ });
1545
+ return this._Promise.race([timeoutPromise, promise]);
1546
+ }
1547
+ /**
1548
+ * Attempt to move an available resource into test and then onto a waiting client
1549
+ * @return {Boolean} could we move an available resource into test
1550
+ */
1551
+ _testOnBorrow() {
1552
+ if (this._availableObjects.length < 1) {
1553
+ return false;
1554
+ }
1555
+ const pooledResource = this._availableObjects.shift();
1556
+ pooledResource.test();
1557
+ this._testOnBorrowResources.add(pooledResource);
1558
+ const validationPromise = this._factory.validate(pooledResource.obj);
1559
+ const wrappedValidationPromise = this._Promise.resolve(validationPromise);
1560
+ this._trackOperation(
1561
+ wrappedValidationPromise,
1562
+ this._validationOperations
1563
+ ).then((isValid) => {
1564
+ this._testOnBorrowResources.delete(pooledResource);
1565
+ if (isValid === false) {
1566
+ pooledResource.invalidate();
1567
+ this._destroy(pooledResource);
1568
+ this._dispense();
1569
+ return;
1570
+ }
1571
+ this._dispatchPooledResourceToNextWaitingClient(pooledResource);
1572
+ });
1573
+ return true;
1574
+ }
1575
+ /**
1576
+ * Attempt to move an available resource to a waiting client
1577
+ * @return {Boolean} [description]
1578
+ */
1579
+ _dispatchResource() {
1580
+ if (this._availableObjects.length < 1) {
1581
+ return false;
1582
+ }
1583
+ const pooledResource = this._availableObjects.shift();
1584
+ this._dispatchPooledResourceToNextWaitingClient(pooledResource);
1585
+ return false;
1586
+ }
1587
+ /**
1588
+ * Attempt to resolve an outstanding resource request using an available resource from
1589
+ * the pool, or creating new ones
1590
+ *
1591
+ * @private
1592
+ */
1593
+ _dispense() {
1594
+ const numWaitingClients = this._waitingClientsQueue.length;
1595
+ if (numWaitingClients < 1) {
1596
+ return;
1597
+ }
1598
+ const resourceShortfall = numWaitingClients - this._potentiallyAllocableResourceCount;
1599
+ const actualNumberOfResourcesToCreate = Math.min(
1600
+ this.spareResourceCapacity,
1601
+ resourceShortfall
1602
+ );
1603
+ for (let i = 0; actualNumberOfResourcesToCreate > i; i++) {
1604
+ this._createResource();
1605
+ }
1606
+ if (this._config.testOnBorrow === true) {
1607
+ const desiredNumberOfResourcesToMoveIntoTest = numWaitingClients - this._testOnBorrowResources.size;
1608
+ const actualNumberOfResourcesToMoveIntoTest = Math.min(
1609
+ this._availableObjects.length,
1610
+ desiredNumberOfResourcesToMoveIntoTest
1611
+ );
1612
+ for (let i = 0; actualNumberOfResourcesToMoveIntoTest > i; i++) {
1613
+ this._testOnBorrow();
1614
+ }
1615
+ }
1616
+ if (this._config.testOnBorrow === false) {
1617
+ const actualNumberOfResourcesToDispatch = Math.min(
1618
+ this._availableObjects.length,
1619
+ numWaitingClients
1620
+ );
1621
+ for (let i = 0; actualNumberOfResourcesToDispatch > i; i++) {
1622
+ this._dispatchResource();
1623
+ }
1624
+ }
1625
+ }
1626
+ /**
1627
+ * Dispatches a pooledResource to the next waiting client (if any) else
1628
+ * puts the PooledResource back on the available list
1629
+ * @param {PooledResource} pooledResource [description]
1630
+ * @return {Boolean} [description]
1631
+ */
1632
+ _dispatchPooledResourceToNextWaitingClient(pooledResource) {
1633
+ const clientResourceRequest = this._waitingClientsQueue.dequeue();
1634
+ if (clientResourceRequest === void 0 || clientResourceRequest.state !== Deferred.PENDING) {
1635
+ this._addPooledResourceToAvailableObjects(pooledResource);
1636
+ return false;
1637
+ }
1638
+ const loan = new ResourceLoan(pooledResource, this._Promise);
1639
+ this._resourceLoans.set(pooledResource.obj, loan);
1640
+ pooledResource.allocate();
1641
+ clientResourceRequest.resolve(pooledResource.obj);
1642
+ return true;
1643
+ }
1644
+ /**
1645
+ * tracks on operation using given set
1646
+ * handles adding/removing from the set and resolve/rejects the value/reason
1647
+ * @param {Promise} operation
1648
+ * @param {Set} set Set holding operations
1649
+ * @return {Promise} Promise that resolves once operation has been removed from set
1650
+ */
1651
+ _trackOperation(operation, set) {
1652
+ set.add(operation);
1653
+ return operation.then(
1654
+ (v) => {
1655
+ set.delete(operation);
1656
+ return this._Promise.resolve(v);
1657
+ },
1658
+ (e) => {
1659
+ set.delete(operation);
1660
+ return this._Promise.reject(e);
1661
+ }
1662
+ );
1663
+ }
1664
+ /**
1665
+ * @private
1666
+ */
1667
+ _createResource() {
1668
+ const factoryPromise = this._factory.create();
1669
+ const wrappedFactoryPromise = this._Promise.resolve(factoryPromise).then((resource) => {
1670
+ const pooledResource = new PooledResource(resource);
1671
+ this._allObjects.add(pooledResource);
1672
+ this._addPooledResourceToAvailableObjects(pooledResource);
1673
+ });
1674
+ this._trackOperation(wrappedFactoryPromise, this._factoryCreateOperations).then(() => {
1675
+ this._dispense();
1676
+ return null;
1677
+ }).catch((reason) => {
1678
+ this.emit(FACTORY_CREATE_ERROR, reason);
1679
+ this._dispense();
1680
+ });
1681
+ }
1682
+ /**
1683
+ * @private
1684
+ */
1685
+ _ensureMinimum() {
1686
+ if (this._draining === true) {
1687
+ return;
1688
+ }
1689
+ const minShortfall = this._config.min - this._count;
1690
+ for (let i = 0; i < minShortfall; i++) {
1691
+ this._createResource();
1692
+ }
1693
+ }
1694
+ _evict() {
1695
+ const testsToRun = Math.min(
1696
+ this._config.numTestsPerEvictionRun,
1697
+ this._availableObjects.length
1698
+ );
1699
+ const evictionConfig = {
1700
+ softIdleTimeoutMillis: this._config.softIdleTimeoutMillis,
1701
+ idleTimeoutMillis: this._config.idleTimeoutMillis,
1702
+ min: this._config.min
1703
+ };
1704
+ for (let testsHaveRun = 0; testsHaveRun < testsToRun; ) {
1705
+ const iterationResult = this._evictionIterator.next();
1706
+ if (iterationResult.done === true && this._availableObjects.length < 1) {
1707
+ this._evictionIterator.reset();
1708
+ return;
1709
+ }
1710
+ if (iterationResult.done === true && this._availableObjects.length > 0) {
1711
+ this._evictionIterator.reset();
1712
+ continue;
1713
+ }
1714
+ const resource = iterationResult.value;
1715
+ const shouldEvict = this._evictor.evict(
1716
+ evictionConfig,
1717
+ resource,
1718
+ this._availableObjects.length
1719
+ );
1720
+ testsHaveRun++;
1721
+ if (shouldEvict === true) {
1722
+ this._evictionIterator.remove();
1723
+ this._destroy(resource);
1724
+ }
1725
+ }
1726
+ }
1727
+ _scheduleEvictorRun() {
1728
+ if (this._config.evictionRunIntervalMillis > 0) {
1729
+ this._scheduledEviction = setTimeout(() => {
1730
+ this._evict();
1731
+ this._scheduleEvictorRun();
1732
+ }, this._config.evictionRunIntervalMillis).unref();
1733
+ }
1734
+ }
1735
+ _descheduleEvictorRun() {
1736
+ if (this._scheduledEviction) {
1737
+ clearTimeout(this._scheduledEviction);
1738
+ }
1739
+ this._scheduledEviction = null;
1740
+ }
1741
+ start() {
1742
+ if (this._draining === true) {
1743
+ return;
1744
+ }
1745
+ if (this._started === true) {
1746
+ return;
1747
+ }
1748
+ this._started = true;
1749
+ this._scheduleEvictorRun();
1750
+ this._ensureMinimum();
1751
+ }
1752
+ /**
1753
+ * Request a new resource. The callback will be called,
1754
+ * when a new resource is available, passing the resource to the callback.
1755
+ * TODO: should we add a seperate "acquireWithPriority" function
1756
+ *
1757
+ * @param {Number} [priority=0]
1758
+ * Optional. Integer between 0 and (priorityRange - 1). Specifies the priority
1759
+ * of the caller if there are no available resources. Lower numbers mean higher
1760
+ * priority.
1761
+ *
1762
+ * @returns {Promise}
1763
+ */
1764
+ acquire(priority) {
1765
+ if (this._started === false && this._config.autostart === false) {
1766
+ this.start();
1767
+ }
1768
+ if (this._draining) {
1769
+ return this._Promise.reject(
1770
+ new Error("pool is draining and cannot accept work")
1771
+ );
1772
+ }
1773
+ if (this.spareResourceCapacity < 1 && this._availableObjects.length < 1 && this._config.maxWaitingClients !== void 0 && this._waitingClientsQueue.length >= this._config.maxWaitingClients) {
1774
+ return this._Promise.reject(
1775
+ new Error("max waitingClients count exceeded")
1776
+ );
1777
+ }
1778
+ const resourceRequest = new ResourceRequest(
1779
+ this._config.acquireTimeoutMillis,
1780
+ this._Promise
1781
+ );
1782
+ this._waitingClientsQueue.enqueue(resourceRequest, priority);
1783
+ this._dispense();
1784
+ return resourceRequest.promise;
1785
+ }
1786
+ /**
1787
+ * [use method, aquires a resource, passes the resource to a user supplied function and releases it]
1788
+ * @param {Function} fn [a function that accepts a resource and returns a promise that resolves/rejects once it has finished using the resource]
1789
+ * @return {Promise} [resolves once the resource is released to the pool]
1790
+ */
1791
+ use(fn, priority) {
1792
+ return this.acquire(priority).then((resource) => {
1793
+ return fn(resource).then(
1794
+ (result) => {
1795
+ this.release(resource);
1796
+ return result;
1797
+ },
1798
+ (err) => {
1799
+ this.destroy(resource);
1800
+ throw err;
1801
+ }
1802
+ );
1803
+ });
1804
+ }
1805
+ /**
1806
+ * Check if resource is currently on loan from the pool
1807
+ *
1808
+ * @param {Function} resource
1809
+ * Resource for checking.
1810
+ *
1811
+ * @returns {Boolean}
1812
+ * True if resource belongs to this pool and false otherwise
1813
+ */
1814
+ isBorrowedResource(resource) {
1815
+ return this._resourceLoans.has(resource);
1816
+ }
1817
+ /**
1818
+ * Return the resource to the pool when it is no longer required.
1819
+ *
1820
+ * @param {Object} resource
1821
+ * The acquired object to be put back to the pool.
1822
+ */
1823
+ release(resource) {
1824
+ const loan = this._resourceLoans.get(resource);
1825
+ if (loan === void 0) {
1826
+ return this._Promise.reject(
1827
+ new Error("Resource not currently part of this pool")
1828
+ );
1829
+ }
1830
+ this._resourceLoans.delete(resource);
1831
+ loan.resolve();
1832
+ const pooledResource = loan.pooledResource;
1833
+ pooledResource.deallocate();
1834
+ this._addPooledResourceToAvailableObjects(pooledResource);
1835
+ this._dispense();
1836
+ return this._Promise.resolve();
1837
+ }
1838
+ /**
1839
+ * Request the resource to be destroyed. The factory's destroy handler
1840
+ * will also be called.
1841
+ *
1842
+ * This should be called within an acquire() block as an alternative to release().
1843
+ *
1844
+ * @param {Object} resource
1845
+ * The acquired resource to be destoyed.
1846
+ */
1847
+ destroy(resource) {
1848
+ const loan = this._resourceLoans.get(resource);
1849
+ if (loan === void 0) {
1850
+ return this._Promise.reject(
1851
+ new Error("Resource not currently part of this pool")
1852
+ );
1853
+ }
1854
+ this._resourceLoans.delete(resource);
1855
+ loan.resolve();
1856
+ const pooledResource = loan.pooledResource;
1857
+ pooledResource.deallocate();
1858
+ this._destroy(pooledResource);
1859
+ this._dispense();
1860
+ return this._Promise.resolve();
1861
+ }
1862
+ _addPooledResourceToAvailableObjects(pooledResource) {
1863
+ pooledResource.idle();
1864
+ if (this._config.fifo === true) {
1865
+ this._availableObjects.push(pooledResource);
1866
+ } else {
1867
+ this._availableObjects.unshift(pooledResource);
1868
+ }
1869
+ }
1870
+ /**
1871
+ * Disallow any new acquire calls and let the request backlog dissapate.
1872
+ * The Pool will no longer attempt to maintain a "min" number of resources
1873
+ * and will only make new resources on demand.
1874
+ * Resolves once all resource requests are fulfilled and all resources are returned to pool and available...
1875
+ * Should probably be called "drain work"
1876
+ * @returns {Promise}
1877
+ */
1878
+ drain() {
1879
+ this._draining = true;
1880
+ return this.__allResourceRequestsSettled().then(() => {
1881
+ return this.__allResourcesReturned();
1882
+ }).then(() => {
1883
+ this._descheduleEvictorRun();
1884
+ });
1885
+ }
1886
+ __allResourceRequestsSettled() {
1887
+ if (this._waitingClientsQueue.length > 0) {
1888
+ return reflector(this._waitingClientsQueue.tail.promise);
1889
+ }
1890
+ return this._Promise.resolve();
1891
+ }
1892
+ // FIXME: this is a horrific mess
1893
+ __allResourcesReturned() {
1894
+ const ps = Array.from(this._resourceLoans.values()).map((loan) => loan.promise).map(reflector);
1895
+ return this._Promise.all(ps);
1896
+ }
1897
+ /**
1898
+ * Forcibly destroys all available resources regardless of timeout. Intended to be
1899
+ * invoked as part of a drain. Does not prevent the creation of new
1900
+ * resources as a result of subsequent calls to acquire.
1901
+ *
1902
+ * Note that if factory.min > 0 and the pool isn't "draining", the pool will destroy all idle resources
1903
+ * in the pool, but replace them with newly created resources up to the
1904
+ * specified factory.min value. If this is not desired, set factory.min
1905
+ * to zero before calling clear()
1906
+ *
1907
+ */
1908
+ clear() {
1909
+ const reflectedCreatePromises = Array.from(
1910
+ this._factoryCreateOperations
1911
+ ).map(reflector);
1912
+ return this._Promise.all(reflectedCreatePromises).then(() => {
1913
+ for (const resource of this._availableObjects) {
1914
+ this._destroy(resource);
1915
+ }
1916
+ const reflectedDestroyPromises = Array.from(
1917
+ this._factoryDestroyOperations
1918
+ ).map(reflector);
1919
+ return reflector(this._Promise.all(reflectedDestroyPromises));
1920
+ });
1921
+ }
1922
+ /**
1923
+ * Waits until the pool is ready.
1924
+ * We define ready by checking if the current resource number is at least
1925
+ * the minimum number defined.
1926
+ * @returns {Promise} that resolves when the minimum number is ready.
1927
+ */
1928
+ ready() {
1929
+ return new this._Promise((resolve) => {
1930
+ const isReady = () => {
1931
+ if (this.available >= this.min) {
1932
+ resolve();
1933
+ } else {
1934
+ setTimeout(isReady, 100);
1935
+ }
1936
+ };
1937
+ isReady();
1938
+ });
1939
+ }
1940
+ /**
1941
+ * How many resources are available to allocated
1942
+ * (includes resources that have not been tested and may faul validation)
1943
+ * NOTE: internal for now as the name is awful and might not be useful to anyone
1944
+ * @return {Number} number of resources the pool has to allocate
1945
+ */
1946
+ get _potentiallyAllocableResourceCount() {
1947
+ return this._availableObjects.length + this._testOnBorrowResources.size + this._testOnReturnResources.size + this._factoryCreateOperations.size;
1948
+ }
1949
+ /**
1950
+ * The combined count of the currently created objects and those in the
1951
+ * process of being created
1952
+ * Does NOT include resources in the process of being destroyed
1953
+ * sort of legacy...
1954
+ * @return {Number}
1955
+ */
1956
+ get _count() {
1957
+ return this._allObjects.size + this._factoryCreateOperations.size;
1958
+ }
1959
+ /**
1960
+ * How many more resources does the pool have room for
1961
+ * @return {Number} number of resources the pool could create before hitting any limits
1962
+ */
1963
+ get spareResourceCapacity() {
1964
+ return this._config.max - (this._allObjects.size + this._factoryCreateOperations.size);
1965
+ }
1966
+ /**
1967
+ * see _count above
1968
+ * @return {Number} [description]
1969
+ */
1970
+ get size() {
1971
+ return this._count;
1972
+ }
1973
+ /**
1974
+ * number of available resources
1975
+ * @return {Number} [description]
1976
+ */
1977
+ get available() {
1978
+ return this._availableObjects.length;
1979
+ }
1980
+ /**
1981
+ * number of resources that are currently acquired
1982
+ * @return {Number} [description]
1983
+ */
1984
+ get borrowed() {
1985
+ return this._resourceLoans.size;
1986
+ }
1987
+ /**
1988
+ * number of waiting acquire calls
1989
+ * @return {Number} [description]
1990
+ */
1991
+ get pending() {
1992
+ return this._waitingClientsQueue.length;
1993
+ }
1994
+ /**
1995
+ * maximum size of the pool
1996
+ * @return {Number} [description]
1997
+ */
1998
+ get max() {
1999
+ return this._config.max;
2000
+ }
2001
+ /**
2002
+ * minimum size of the pool
2003
+ * @return {Number} [description]
2004
+ */
2005
+ get min() {
2006
+ return this._config.min;
2007
+ }
2008
+ }
2009
+ Pool_1 = Pool;
2010
+ return Pool_1;
2011
+ }
2012
+ var genericPool$1;
2013
+ var hasRequiredGenericPool;
2014
+ function requireGenericPool() {
2015
+ if (hasRequiredGenericPool) return genericPool$1;
2016
+ hasRequiredGenericPool = 1;
2017
+ const Pool = requirePool();
2018
+ const Deque = requireDeque();
2019
+ const PriorityQueue = requirePriorityQueue();
2020
+ const DefaultEvictor = requireDefaultEvictor();
2021
+ genericPool$1 = {
2022
+ Pool,
2023
+ Deque,
2024
+ PriorityQueue,
2025
+ DefaultEvictor,
2026
+ createPool: function(factory, config) {
2027
+ return new Pool(DefaultEvictor, Deque, PriorityQueue, factory, config);
2028
+ }
2029
+ };
2030
+ return genericPool$1;
2031
+ }
2032
+ var genericPoolExports = requireGenericPool();
2033
+ const genericPool = /* @__PURE__ */ getDefaultExportFromCjs(genericPoolExports);
2034
+ const workerFactory = {
2035
+ create: async () => {
2036
+ const workerPath = new URL("data:video/mp2t;base64,aW1wb3J0IHsgTWVzaERhdGEgfSBmcm9tICdAL3R5cGVzJzsKaW1wb3J0ICogYXMgQ29tbGluayBmcm9tICdjb21saW5rJzsKaW1wb3J0ICogYXMgVEhSRUUgZnJvbSAndGhyZWUnOwppbXBvcnQgeyBNZXNoU3VyZmFjZVNhbXBsZXIgfSBmcm9tICd0aHJlZS9leGFtcGxlcy9qc20vbWF0aC9NZXNoU3VyZmFjZVNhbXBsZXInOwoKZXhwb3J0IGludGVyZmFjZSBNZXNoU2FtcGxlckFQSSB7CiAgc2FtcGxlTWVzaDogKG1lc2hEYXRhOiBNZXNoRGF0YSwgc2l6ZTogbnVtYmVyKSA9PiBQcm9taXNlPEZsb2F0MzJBcnJheT47Cn0KCmNvbnN0IGFwaSA9IHsKICBzYW1wbGVNZXNoOiAobWVzaERhdGE6IE1lc2hEYXRhLCBzaXplOiBudW1iZXIpOiBGbG9hdDMyQXJyYXkgPT4gewogICAgY29uc3QgZ2VvbWV0cnkgPSBuZXcgVEhSRUUuQnVmZmVyR2VvbWV0cnkoKTsKICAgIGdlb21ldHJ5LnNldEF0dHJpYnV0ZSgncG9zaXRpb24nLCBuZXcgVEhSRUUuQnVmZmVyQXR0cmlidXRlKG5ldyBGbG9hdDMyQXJyYXkobWVzaERhdGEucG9zaXRpb24pLCAzKSk7CiAgICBpZiAobWVzaERhdGEubm9ybWFsKSB7CiAgICAgIGdlb21ldHJ5LnNldEF0dHJpYnV0ZSgnbm9ybWFsJywgbmV3IFRIUkVFLkJ1ZmZlckF0dHJpYnV0ZShuZXcgRmxvYXQzMkFycmF5KG1lc2hEYXRhLm5vcm1hbCksIDMpKTsKICAgIH0KICAgIGNvbnN0IG1hdGVyaWFsID0gbmV3IFRIUkVFLk1lc2hCYXNpY01hdGVyaWFsKCk7CiAgICBjb25zdCBtZXNoID0gbmV3IFRIUkVFLk1lc2goZ2VvbWV0cnksIG1hdGVyaWFsKTsKICAgIG1lc2guc2NhbGUuc2V0KG1lc2hEYXRhLnNjYWxlLngsIG1lc2hEYXRhLnNjYWxlLnksIG1lc2hEYXRhLnNjYWxlLnopOwoKICAgIGNvbnN0IHNhbXBsZXIgPSBuZXcgTWVzaFN1cmZhY2VTYW1wbGVyKG1lc2gpLmJ1aWxkKCk7CiAgICBjb25zdCBkYXRhID0gbmV3IEZsb2F0MzJBcnJheShzaXplICogc2l6ZSAqIDQpOwogICAgY29uc3QgcG9zaXRpb24gPSBuZXcgVEhSRUUuVmVjdG9yMygpOwoKICAgIGZvciAobGV0IGkgPSAwOyBpIDwgc2l6ZTsgaSsrKSB7CiAgICAgIGZvciAobGV0IGogPSAwOyBqIDwgc2l6ZTsgaisrKSB7CiAgICAgICAgY29uc3QgaW5kZXggPSBpICogc2l6ZSArIGo7CiAgICAgICAgc2FtcGxlci5zYW1wbGUocG9zaXRpb24pOwogICAgICAgIGRhdGFbNCAqIGluZGV4XSA9IHBvc2l0aW9uLnggKiBtZXNoRGF0YS5zY2FsZS54OwogICAgICAgIGRhdGFbNCAqIGluZGV4ICsgMV0gPSBwb3NpdGlvbi55ICogbWVzaERhdGEuc2NhbGUueTsKICAgICAgICBkYXRhWzQgKiBpbmRleCArIDJdID0gcG9zaXRpb24ueiAqIG1lc2hEYXRhLnNjYWxlLno7CiAgICAgICAgZGF0YVs0ICogaW5kZXggKyAzXSA9IChNYXRoLnJhbmRvbSgpIC0gMC41KSAqIDAuMDE7CiAgICAgIH0KICAgIH0KCiAgICByZXR1cm4gZGF0YTsKICB9LAp9OwoKQ29tbGluay5leHBvc2UoYXBpKTsK", import.meta.url);
2037
+ const worker = new Worker(workerPath, { type: "module" });
2038
+ return wrap(worker);
2039
+ },
2040
+ destroy: async (worker) => {
2041
+ return worker[releaseProxy]();
2042
+ }
2043
+ };
2044
+ const pool = genericPool.createPool(workerFactory, {
2045
+ max: navigator.hardwareConcurrency || 4,
2046
+ min: 2
2047
+ });
2048
+ function createDataTexture(data, size) {
2049
+ const texture = new THREE.DataTexture(data, size, size, THREE.RGBAFormat, THREE.FloatType);
2050
+ texture.needsUpdate = true;
2051
+ return texture;
2052
+ }
2053
+ function createBlankDataTexture(size) {
2054
+ return createDataTexture(new Float32Array(4 * size * size), size);
2055
+ }
2056
+ function createSpherePoints(size) {
2057
+ const data = new Float32Array(size * size * 4);
2058
+ for (let i = 0; i < size; i++) {
2059
+ for (let j = 0; j < size; j++) {
2060
+ const index = i * size + j;
2061
+ let theta = Math.random() * Math.PI * 2;
2062
+ let phi = Math.acos(Math.random() * 2 - 1);
2063
+ let x = Math.sin(phi) * Math.cos(theta);
2064
+ let y = Math.sin(phi) * Math.sin(theta);
2065
+ let z = Math.cos(phi);
2066
+ data[4 * index] = x;
2067
+ data[4 * index + 1] = y;
2068
+ data[4 * index + 2] = z;
2069
+ data[4 * index + 3] = (Math.random() - 0.5) * 0.01;
2070
+ }
2071
+ }
2072
+ return createDataTexture(data, size);
2073
+ }
2074
+ function copyOf(source) {
2075
+ const map = /* @__PURE__ */ new Map();
2076
+ if (source) {
2077
+ if (Array.isArray(source)) {
2078
+ source.forEach(({ id, item }) => map.set(id, item));
2079
+ } else {
2080
+ map.set(source.id, source.item);
2081
+ }
2082
+ }
2083
+ return map;
2084
+ }
2085
+ function clamp(value, min, max) {
2086
+ value = Math.min(value, max);
2087
+ value = Math.max(value, min);
2088
+ return value;
2089
+ }
2090
+ class DataTextureService {
2091
+ /**
2092
+ * Creates a new DataTextureManager instance.
2093
+ * @param eventEmitter
2094
+ * @param textureSize
2095
+ * @param meshes Optional initial meshes.
2096
+ */
2097
+ constructor(eventEmitter, textureSize, meshes) {
2098
+ __publicField(this, "textureSize");
2099
+ __publicField(this, "meshes");
2100
+ __publicField(this, "dataTextures");
2101
+ __publicField(this, "eventEmitter");
2102
+ this.eventEmitter = eventEmitter;
2103
+ this.textureSize = textureSize;
2104
+ this.meshes = copyOf(meshes);
2105
+ this.dataTextures = /* @__PURE__ */ new Map();
2106
+ this.updateServiceState("ready");
2107
+ }
2108
+ /**
2109
+ * Registers a mesh.
2110
+ * @param id The ID of the mesh.
2111
+ * @param mesh The mesh to register.
2112
+ */
2113
+ async register(id, mesh) {
2114
+ this.meshes.set(id, mesh);
2115
+ }
2116
+ setTextureSize(textureSize) {
2117
+ if (this.textureSize === textureSize) return;
2118
+ this.textureSize = textureSize;
2119
+ this.dataTextures.forEach((texture) => texture.dispose());
2120
+ this.dataTextures.clear();
2121
+ }
2122
+ getMesh(id) {
2123
+ return this.meshes.get(id);
2124
+ }
2125
+ /**
2126
+ * Gets the data texture for the specified mesh ID and current texture size.
2127
+ * Returns the fallback data texture if the specified mesh ID is not found.
2128
+ * @param id The ID of the mesh.
2129
+ * @returns The data texture, or undefined if not found and no fallback is available.
2130
+ */
2131
+ async getDataTexture(id) {
2132
+ return await this.prepareMesh(id);
2133
+ }
2134
+ /**
2135
+ * Prepares a mesh for sampling.
2136
+ * @param id The ID of the mesh to prepare.
2137
+ */
2138
+ async prepareMesh(id) {
2139
+ if (!this.meshes.has(id)) {
2140
+ throw new Error(`Mesh with id "${id}" does not exist.`);
2141
+ }
2142
+ const texture = this.dataTextures.get(id);
2143
+ if (texture) {
2144
+ return texture;
2145
+ }
2146
+ const mesh = this.meshes.get(id);
2147
+ const meshData = parseMeshData(mesh);
2148
+ const worker = await pool.acquire();
2149
+ try {
2150
+ const data = await worker.sampleMesh(meshData, this.textureSize);
2151
+ const texture2 = createDataTexture(data, this.textureSize);
2152
+ texture2.name = id;
2153
+ return texture2;
2154
+ } finally {
2155
+ await pool.release(worker);
2156
+ }
2157
+ }
2158
+ async dispose() {
2159
+ this.meshes.clear();
2160
+ this.dataTextures.clear();
2161
+ this.updateServiceState("disposed");
2162
+ }
2163
+ updateServiceState(serviceState) {
2164
+ this.eventEmitter.emit("serviceStateUpdated", { type: "data-texture", state: serviceState });
2165
+ }
2166
+ }
2167
+ function parseMeshData(mesh) {
2168
+ var _a;
2169
+ return {
2170
+ position: mesh.geometry.attributes.position.array,
2171
+ normal: (_a = mesh.geometry.attributes.normal) == null ? void 0 : _a.array,
2172
+ scale: { x: mesh.scale.x, y: mesh.scale.y, z: mesh.scale.z }
2173
+ };
2174
+ }
2175
+ const instanceFragmentShader = `
2176
+ varying vec2 vUv;
2177
+ uniform sampler2D uTexture;
2178
+
2179
+ uniform sampler2D uSourceMatcap;
2180
+ uniform sampler2D uTargetMatcap;
2181
+
2182
+ uniform float uProgress;
2183
+ varying vec3 vNormal;
2184
+ varying vec3 vViewPosition;
2185
+ void main() {
2186
+ vec3 viewDir = normalize( vViewPosition );
2187
+ vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );
2188
+ vec3 y = cross( viewDir, x );
2189
+ vec2 uv = vec2( dot( x, vNormal ), dot( y, vNormal ) ) * 0.495 + 0.5; // 0.495 to remove artifacts caused by undersized matcap disks
2190
+
2191
+ vec4 sourceMatcap = texture2D( uSourceMatcap, uv );
2192
+ vec4 targetMatcap = texture2D( uTargetMatcap, uv );
2193
+
2194
+ vec4 matcap = mix(sourceMatcap, targetMatcap, uProgress);
2195
+ gl_FragColor = matcap;
2196
+ }
2197
+ `;
2198
+ const instanceVertexShader = `
2199
+ varying vec2 vUv;
2200
+ uniform sampler2D uTexture;
2201
+ uniform sampler2D uVelocity;
2202
+ uniform float uTime;
2203
+ varying vec3 vNormal;
2204
+ attribute vec2 uvRef;
2205
+ varying vec3 vViewPosition;
2206
+
2207
+ vec3 rotate3D(vec3 v, vec3 vel) {
2208
+ vec3 pos = v;
2209
+ vec3 up = vec3(0, 1, 0);
2210
+ vec3 axis = normalize(cross(up, vel));
2211
+ float angle = acos(dot(up, normalize(vel)));
2212
+ pos = pos * cos(angle) + cross(axis, pos) * sin(angle) + axis * dot(axis, pos) * (1. - cos(angle));
2213
+ return pos;
2214
+ }
2215
+
2216
+ void main() {
2217
+ vUv = uv;
2218
+ vNormal = normal;
2219
+
2220
+ vec4 color = texture2D(uTexture, uvRef);
2221
+ vec4 velocity = texture2D(uVelocity, uvRef);
2222
+ vec3 pos = color.xyz;// apply the texture to the vertex distribution.
2223
+
2224
+ vec3 localPosition = position.xyz;
2225
+ if (length (velocity.xyz) < 0.0001) {
2226
+ velocity.xyz = vec3(0.0, 0.0001, 0.0001);
2227
+ }
2228
+ localPosition.y *= max(1.0, length(velocity.xyz) * 1000.0);
2229
+ localPosition = rotate3D(localPosition, velocity.xyz);
2230
+ vNormal = rotate3D(normal, velocity.xyz);
2231
+
2232
+ mat4 instanceMat = instanceMatrix;
2233
+ instanceMat[3].xyz = pos.xyz;
2234
+
2235
+ // unlike the traditional mvMatrix * position, we need to additional multiplication with the instance matrix.
2236
+ vec4 modelViewPosition = modelViewMatrix * instanceMat * vec4(localPosition, 1.0);
2237
+
2238
+ vViewPosition = - modelViewPosition.xyz;
2239
+
2240
+ gl_Position = projectionMatrix * modelViewPosition;
2241
+ }
2242
+ `;
2243
+ class InstancedMeshManager {
2244
+ /**
2245
+ * Creates a new InstancedMeshManager instance.
2246
+ * @param initialSize The initial size of the instanced mesh.
2247
+ */
2248
+ constructor(initialSize) {
2249
+ __publicField(this, "size");
2250
+ __publicField(this, "mesh");
2251
+ __publicField(this, "matcapMaterial");
2252
+ __publicField(this, "fallbackMaterial");
2253
+ __publicField(this, "fallbackGeometry");
2254
+ __publicField(this, "materials");
2255
+ __publicField(this, "geometries");
2256
+ __publicField(this, "uvRefsCache");
2257
+ __publicField(this, "previousScale");
2258
+ this.size = initialSize;
2259
+ this.materials = /* @__PURE__ */ new Map();
2260
+ this.geometries = /* @__PURE__ */ new Map();
2261
+ this.uvRefsCache = /* @__PURE__ */ new Map();
2262
+ this.previousScale = { x: 1, y: 1, z: 1 };
2263
+ this.matcapMaterial = new THREE.ShaderMaterial({
2264
+ uniforms: {
2265
+ uTime: { value: 0 },
2266
+ uProgress: { value: 0 },
2267
+ uTexture: { value: null },
2268
+ uVelocity: { value: null },
2269
+ uSourceMatcap: { value: null },
2270
+ uTargetMatcap: { value: null }
2271
+ },
2272
+ vertexShader: instanceVertexShader,
2273
+ fragmentShader: instanceFragmentShader
2274
+ });
2275
+ this.fallbackMaterial = new THREE.MeshBasicMaterial({ color: 16777215 });
2276
+ this.fallbackGeometry = new THREE.BoxGeometry(1e-3, 1e-3, 1e-3);
2277
+ this.mesh = this.createInstancedMesh(initialSize, this.fallbackGeometry, this.fallbackMaterial);
2278
+ }
2279
+ /**
2280
+ * Gets the instanced mesh.
2281
+ * @returns The instanced mesh.
2282
+ */
2283
+ getMesh() {
2284
+ return this.mesh;
2285
+ }
2286
+ /**
2287
+ * Updates the instanced mesh.
2288
+ * @param elapsedTime The elapsed time.
2289
+ */
2290
+ update(elapsedTime) {
2291
+ const material = this.mesh.material;
2292
+ if (material instanceof THREE.ShaderMaterial || material instanceof THREE.RawShaderMaterial) {
2293
+ material.uniforms.uTime.value = elapsedTime;
2294
+ }
2295
+ }
2296
+ /**
2297
+ * Sets the matcap texture.
2298
+ * @param matcap The matcap texture to set.
2299
+ */
2300
+ setOriginMatcap(matcap) {
2301
+ console.log("set source matcap", matcap);
2302
+ this.matcapMaterial.uniforms.uSourceMatcap.value = matcap;
2303
+ }
2304
+ setDestinationMatcap(matcap) {
2305
+ console.log("set target matcap", matcap);
2306
+ this.matcapMaterial.uniforms.uTargetMatcap.value = matcap;
2307
+ }
2308
+ setProgress(float) {
2309
+ float = Math.max(0, float);
2310
+ float = Math.min(1, float);
2311
+ this.matcapMaterial.uniforms.uProgress.value = float;
2312
+ }
2313
+ setGeometrySize(size) {
2314
+ this.mesh.geometry.scale(1 / this.previousScale.x, 1 / this.previousScale.y, 1 / this.previousScale.z);
2315
+ this.mesh.geometry.scale(size.x, size.y, size.z);
2316
+ this.previousScale = size;
2317
+ }
2318
+ /**
2319
+ * Use the matcap material for the instanced mesh.
2320
+ */
2321
+ useMatcapMaterial() {
2322
+ console.log("Using matcap material");
2323
+ this.mesh.material = this.matcapMaterial;
2324
+ }
2325
+ /**
2326
+ * Use the specified material for the instanced mesh.
2327
+ * @param id The ID of the material to use.
2328
+ */
2329
+ useMaterial(id) {
2330
+ const material = this.materials.get(id);
2331
+ if (material) {
2332
+ this.mesh.material = material;
2333
+ } else {
2334
+ console.warn(`material with id "${id}" not found`);
2335
+ }
2336
+ }
2337
+ /**
2338
+ * Use the specified geometry for the instanced mesh.
2339
+ * @param id The ID of the geometry to use.
2340
+ */
2341
+ useGeometry(id) {
2342
+ const geometry = this.geometries.get(id);
2343
+ if (geometry) {
2344
+ this.mesh.geometry = geometry;
2345
+ } else {
2346
+ console.warn(`geometry with id "${id}" not found`);
2347
+ }
2348
+ }
2349
+ /**
2350
+ * Updates the velocity texture.
2351
+ * @param texture The velocity texture to update with.
2352
+ */
2353
+ updateVelocityTexture(texture) {
2354
+ this.matcapMaterial.uniforms.uVelocity.value = texture;
2355
+ }
2356
+ /**
2357
+ * Updates the position texture.
2358
+ * @param texture The position texture to update with.
2359
+ */
2360
+ updatePositionTexture(texture) {
2361
+ this.matcapMaterial.uniforms.uTexture.value = texture;
2362
+ }
2363
+ /**
2364
+ * Resizes or replaces the instanced mesh.
2365
+ * @param size The new size of the instanced mesh.
2366
+ * @returns An object containing the updated mesh, the previous mesh, and a boolean indicating whether the mesh was updated.
2367
+ */
2368
+ resize(size) {
2369
+ if (this.size === size) return { current: this.mesh, previous: this.mesh };
2370
+ this.size = size;
2371
+ const prev = this.mesh;
2372
+ this.mesh = this.createInstancedMesh(size, prev.geometry, prev.material);
2373
+ return { current: this.mesh, previous: prev };
2374
+ }
2375
+ /**
2376
+ * Disposes the resources used by the InstancedMeshManager.
2377
+ */
2378
+ dispose() {
2379
+ this.mesh.dispose();
2380
+ this.geometries.forEach((geometry) => geometry.dispose());
2381
+ this.materials.forEach((material) => material.dispose());
2382
+ this.uvRefsCache.clear();
2383
+ this.geometries.clear();
2384
+ this.materials.clear();
2385
+ }
2386
+ /**
2387
+ * Registers a geometry.
2388
+ * @param id The ID of the geometry to register.
2389
+ * @param geometry The geometry to register.
2390
+ */
2391
+ registerGeometry(id, geometry) {
2392
+ const previous = this.geometries.get(id);
2393
+ if (previous) {
2394
+ if (previous === geometry) {
2395
+ return;
2396
+ }
2397
+ console.log(`geometry with id "${id}" already exists. replacing...`);
2398
+ }
2399
+ const uvRefs = this.getUVRefs(this.size);
2400
+ geometry.setAttribute("uvRef", uvRefs);
2401
+ this.geometries.set(id, geometry);
2402
+ if (this.mesh.geometry === previous) {
2403
+ this.mesh.geometry = geometry;
2404
+ }
2405
+ previous == null ? void 0 : previous.dispose();
2406
+ }
2407
+ /**
2408
+ * Registers a material.
2409
+ * @param id The ID of the material to register.
2410
+ * @param material The material to register.
2411
+ */
2412
+ registerMaterial(id, material) {
2413
+ const previous = this.materials.get(id);
2414
+ if (previous) {
2415
+ if (previous === material) {
2416
+ return;
2417
+ }
2418
+ console.log(`material with id "${id}" already exists. replacing...`);
2419
+ }
2420
+ if (this.mesh.material === previous) {
2421
+ this.mesh.material = material;
2422
+ }
2423
+ this.materials.set(id, material);
2424
+ previous == null ? void 0 : previous.dispose();
2425
+ }
2426
+ /**
2427
+ * Gets the UV references for the specified size.
2428
+ * @param size The size for which to generate UV references.
2429
+ * @returns The UV references.
2430
+ */
2431
+ getUVRefs(size) {
2432
+ const cached = this.uvRefsCache.get(size);
2433
+ if (cached) {
2434
+ return cached;
2435
+ }
2436
+ const uvRefs = new Float32Array(size * size * 2);
2437
+ for (let i = 0; i < size; i++) {
2438
+ for (let j = 0; j < size; j++) {
2439
+ const index = i * size + j;
2440
+ uvRefs[2 * index] = j / (size - 1);
2441
+ uvRefs[2 * index + 1] = i / (size - 1);
2442
+ }
2443
+ }
2444
+ const attr = new THREE.InstancedBufferAttribute(uvRefs, 2);
2445
+ this.uvRefsCache.set(size, attr);
2446
+ return attr;
2447
+ }
2448
+ /**
2449
+ * Creates a new instanced mesh.
2450
+ * @param size The size of the instanced mesh.
2451
+ * @param geometry The geometry to use for the instanced mesh.
2452
+ * @param material The material to use for the instanced mesh.
2453
+ * @returns The created instanced mesh.
2454
+ */
2455
+ createInstancedMesh(size, geometry, material) {
2456
+ geometry = geometry || this.fallbackGeometry;
2457
+ geometry.setAttribute("uvRef", this.getUVRefs(size));
2458
+ const count = size * size;
2459
+ return new THREE.InstancedMesh(geometry, material, count);
2460
+ }
2461
+ }
2462
+ class IntersectionService {
2463
+ /**
2464
+ * Creates a new IntersectionService instance.
2465
+ * @param eventEmitter The event emitter used for emitting events.
2466
+ * @param camera The camera used for raycasting.
2467
+ * @param originGeometry The origin geometry.
2468
+ * @param destinationGeometry The destination geometry.
2469
+ */
2470
+ constructor(eventEmitter, camera, originGeometry, destinationGeometry) {
2471
+ __publicField(this, "raycaster", new THREE.Raycaster());
2472
+ __publicField(this, "mousePosition", new THREE.Vector2());
2473
+ __publicField(this, "mouseEntered", false);
2474
+ __publicField(this, "mousePositionChanged", false);
2475
+ __publicField(this, "camera");
2476
+ __publicField(this, "originGeometry");
2477
+ __publicField(this, "destinationGeometry");
2478
+ __publicField(this, "progress", 0);
2479
+ __publicField(this, "intersectionMesh", new THREE.Mesh());
2480
+ __publicField(this, "geometryNeedsUpdate");
2481
+ __publicField(this, "eventEmitter");
2482
+ __publicField(this, "blendedGeometry");
2483
+ __publicField(this, "intersection");
2484
+ __publicField(this, "lastKnownOriginMeshID");
2485
+ __publicField(this, "lastKnownDestinationMeshID");
2486
+ this.camera = camera;
2487
+ this.originGeometry = originGeometry;
2488
+ this.eventEmitter = eventEmitter;
2489
+ this.destinationGeometry = destinationGeometry;
2490
+ this.geometryNeedsUpdate = true;
2491
+ }
2492
+ /**
2493
+ * Set the camera used for raycasting.
2494
+ * @param camera
2495
+ */
2496
+ setCamera(camera) {
2497
+ this.camera = camera;
2498
+ }
2499
+ /**
2500
+ * Set the origin geometry.
2501
+ * @param source
2502
+ */
2503
+ setOriginGeometry(source) {
2504
+ if (this.lastKnownOriginMeshID === source.uuid) return;
2505
+ if (this.originGeometry) this.originGeometry.dispose();
2506
+ this.lastKnownOriginMeshID = source.uuid;
2507
+ this.originGeometry = source.geometry.clone();
2508
+ this.originGeometry.applyMatrix4(source.matrixWorld);
2509
+ this.geometryNeedsUpdate = true;
2510
+ }
2511
+ /**
2512
+ * Set the destination geometry.
2513
+ * @param source
2514
+ */
2515
+ setDestinationGeometry(source) {
2516
+ if (this.lastKnownDestinationMeshID === source.uuid) return;
2517
+ if (this.destinationGeometry) this.destinationGeometry.dispose();
2518
+ this.lastKnownDestinationMeshID = source.uuid;
2519
+ this.destinationGeometry = source.geometry.clone();
2520
+ this.destinationGeometry.applyMatrix4(source.matrixWorld);
2521
+ this.geometryNeedsUpdate = true;
2522
+ }
2523
+ /**
2524
+ * Set the progress of the morphing animation.
2525
+ * @param progress
2526
+ */
2527
+ setProgress(progress) {
2528
+ this.progress = progress;
2529
+ this.geometryNeedsUpdate = true;
2530
+ }
2531
+ /**
2532
+ * Set the mouse position.
2533
+ * @param mousePosition
2534
+ */
2535
+ setMousePosition(mousePosition) {
2536
+ if (mousePosition) {
2537
+ if (!this.mousePosition.equals(mousePosition)) {
2538
+ this.mousePosition.copy(mousePosition);
2539
+ this.mousePositionChanged = true;
2540
+ }
2541
+ this.mouseEntered = true;
2542
+ } else {
2543
+ this.mouseEntered = false;
2544
+ this.mousePositionChanged = false;
2545
+ }
2546
+ }
2547
+ /**
2548
+ * Calculate the intersection.
2549
+ * @returns The intersection point or undefined if no intersection was found.
2550
+ */
2551
+ calculate() {
2552
+ if (!this.camera) return;
2553
+ if (!this.mouseEntered) return;
2554
+ if (this.geometryNeedsUpdate) {
2555
+ this.geometryNeedsUpdate = false;
2556
+ this.blendedGeometry = this.getBlendedGeometry();
2557
+ this.mousePositionChanged = true;
2558
+ }
2559
+ if (this.mousePositionChanged) {
2560
+ this.mousePositionChanged = false;
2561
+ if (this.blendedGeometry) {
2562
+ this.intersection = this.getFirstIntersection(this.blendedGeometry, this.camera);
2563
+ } else {
2564
+ this.intersection = void 0;
2565
+ }
2566
+ }
2567
+ if (this.intersection) {
2568
+ this.eventEmitter.emit("interactionPositionUpdated", { position: this.intersection });
2569
+ } else {
2570
+ this.eventEmitter.emit("interactionPositionUpdated", { position: { x: 0, y: 0, z: 0, w: 0 } });
2571
+ }
2572
+ return this.intersection;
2573
+ }
2574
+ /**
2575
+ * Dispose the resources used by the IntersectionService.
2576
+ */
2577
+ dispose() {
2578
+ var _a;
2579
+ (_a = this.blendedGeometry) == null ? void 0 : _a.dispose();
2580
+ this.intersectionMesh.geometry.dispose();
2581
+ }
2582
+ getFirstIntersection(geometry, camera) {
2583
+ this.raycaster.setFromCamera(this.mousePosition, camera);
2584
+ this.intersectionMesh.geometry = geometry;
2585
+ const intersection = this.raycaster.intersectObject(this.intersectionMesh, false)[0];
2586
+ if (intersection) {
2587
+ return new THREE.Vector4(intersection.point.x, intersection.point.y, intersection.point.z, 1);
2588
+ }
2589
+ }
2590
+ getBlendedGeometry() {
2591
+ if (this.progress === 0) {
2592
+ return this.originGeometry;
2593
+ }
2594
+ if (this.progress === 1) {
2595
+ return this.destinationGeometry;
2596
+ }
2597
+ if (!this.originGeometry || !this.destinationGeometry) {
2598
+ return;
2599
+ }
2600
+ if (this.originGeometry === this.destinationGeometry) {
2601
+ return this.originGeometry;
2602
+ }
2603
+ return this.blendGeometry(this.originGeometry, this.destinationGeometry, this.progress);
2604
+ }
2605
+ blendGeometry(from, to, progress) {
2606
+ const blended = new THREE.BufferGeometry();
2607
+ const originPositions = from.attributes.position.array;
2608
+ const destinationPositions = to.attributes.position.array;
2609
+ const blendedPositions = new Float32Array(originPositions.length);
2610
+ for (let i = 0; i < originPositions.length; i += 3) {
2611
+ const originVert = new THREE.Vector3(originPositions[i], originPositions[i + 1], originPositions[i + 2]);
2612
+ const destinationVert = new THREE.Vector3(destinationPositions[i], destinationPositions[i + 1], destinationPositions[i + 2]);
2613
+ const blendedVert = new THREE.Vector3().lerpVectors(originVert, destinationVert, progress);
2614
+ blendedPositions[i] = blendedVert.x;
2615
+ blendedPositions[i + 1] = blendedVert.y;
2616
+ blendedPositions[i + 2] = blendedVert.z;
2617
+ }
2618
+ blended.setAttribute("position", new THREE.BufferAttribute(blendedPositions, 3));
2619
+ if (from.attributes.normal) blended.setAttribute("normal", from.attributes.normal.clone());
2620
+ if (from.attributes.uv) blended.setAttribute("uv", from.attributes.uv.clone());
2621
+ if (from.index) blended.setIndex(from.index.clone());
2622
+ return blended;
2623
+ }
2624
+ }
2625
+ class MatcapService {
2626
+ constructor(eventEmitter, matcaps) {
2627
+ __publicField(this, "matcaps", /* @__PURE__ */ new Map());
2628
+ __publicField(this, "eventEmitter");
2629
+ __publicField(this, "fallbackMatcap", new THREE.DataTexture(new Uint8Array([127, 127, 127, 255]), 1, 1, THREE.RGBAFormat));
2630
+ this.eventEmitter = eventEmitter;
2631
+ if (matcaps) {
2632
+ matcaps.forEach(({ id, item }) => this.setMatcap(id, item));
2633
+ }
2634
+ this.updateServiceState("ready");
2635
+ }
2636
+ getMatcap(id) {
2637
+ const texture = this.matcaps.get(id);
2638
+ if (!texture) {
2639
+ this.eventEmitter.emit("invalidRequest", { message: `invalid matcap request: ${id}` });
2640
+ return this.fallbackMatcap;
2641
+ } else {
2642
+ return texture;
2643
+ }
2644
+ }
2645
+ setMatcap(id, texture) {
2646
+ const previous = this.matcaps.get(id);
2647
+ if (previous === texture) return;
2648
+ this.matcaps.set(id, texture);
2649
+ if (previous) {
2650
+ this.eventEmitter.emit("matcapReplaced", { id });
2651
+ previous.dispose();
2652
+ } else {
2653
+ this.eventEmitter.emit("matcapRegistered", { id });
2654
+ }
2655
+ }
2656
+ dispose() {
2657
+ this.updateServiceState("disposed");
2658
+ this.matcaps.forEach((texture) => texture.dispose());
2659
+ this.matcaps.clear();
2660
+ }
2661
+ updateServiceState(serviceState) {
2662
+ this.eventEmitter.emit("serviceStateUpdated", { type: "matcap", state: serviceState });
2663
+ }
2664
+ }
2665
+ const _camera = new OrthographicCamera(-1, 1, 1, -1, 0, 1);
2666
+ class FullscreenTriangleGeometry extends BufferGeometry {
2667
+ constructor() {
2668
+ super();
2669
+ this.setAttribute("position", new Float32BufferAttribute([-1, 3, 0, -1, -1, 0, 3, -1, 0], 3));
2670
+ this.setAttribute("uv", new Float32BufferAttribute([0, 2, 0, 0, 2, 0], 2));
2671
+ }
2672
+ }
2673
+ const _geometry = new FullscreenTriangleGeometry();
2674
+ class FullScreenQuad {
2675
+ constructor(material) {
2676
+ this._mesh = new Mesh(_geometry, material);
2677
+ }
2678
+ dispose() {
2679
+ this._mesh.geometry.dispose();
2680
+ }
2681
+ render(renderer) {
2682
+ renderer.render(this._mesh, _camera);
2683
+ }
2684
+ get material() {
2685
+ return this._mesh.material;
2686
+ }
2687
+ set material(value) {
2688
+ this._mesh.material = value;
2689
+ }
2690
+ }
2691
+ class GPUComputationRenderer {
2692
+ /**
2693
+ * @param {Number} sizeX Computation problem size is always 2d: sizeX * sizeY elements.
2694
+ * @param {Number} sizeY Computation problem size is always 2d: sizeX * sizeY elements.
2695
+ * @param {WebGLRenderer} renderer The renderer
2696
+ */
2697
+ constructor(sizeX, sizeY, renderer) {
2698
+ this.variables = [];
2699
+ this.currentTextureIndex = 0;
2700
+ let dataType = FloatType;
2701
+ const passThruUniforms = {
2702
+ passThruTexture: { value: null }
2703
+ };
2704
+ const passThruShader = createShaderMaterial(getPassThroughFragmentShader(), passThruUniforms);
2705
+ const quad = new FullScreenQuad(passThruShader);
2706
+ this.setDataType = function(type) {
2707
+ dataType = type;
2708
+ return this;
2709
+ };
2710
+ this.addVariable = function(variableName, computeFragmentShader, initialValueTexture) {
2711
+ const material = this.createShaderMaterial(computeFragmentShader);
2712
+ const variable = {
2713
+ name: variableName,
2714
+ initialValueTexture,
2715
+ material,
2716
+ dependencies: null,
2717
+ renderTargets: [],
2718
+ wrapS: null,
2719
+ wrapT: null,
2720
+ minFilter: NearestFilter,
2721
+ magFilter: NearestFilter
2722
+ };
2723
+ this.variables.push(variable);
2724
+ return variable;
2725
+ };
2726
+ this.setVariableDependencies = function(variable, dependencies) {
2727
+ variable.dependencies = dependencies;
2728
+ };
2729
+ this.init = function() {
2730
+ if (renderer.capabilities.maxVertexTextures === 0) {
2731
+ return "No support for vertex shader textures.";
2732
+ }
2733
+ for (let i = 0; i < this.variables.length; i++) {
2734
+ const variable = this.variables[i];
2735
+ variable.renderTargets[0] = this.createRenderTarget(sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter);
2736
+ variable.renderTargets[1] = this.createRenderTarget(sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter);
2737
+ this.renderTexture(variable.initialValueTexture, variable.renderTargets[0]);
2738
+ this.renderTexture(variable.initialValueTexture, variable.renderTargets[1]);
2739
+ const material = variable.material;
2740
+ const uniforms = material.uniforms;
2741
+ if (variable.dependencies !== null) {
2742
+ for (let d = 0; d < variable.dependencies.length; d++) {
2743
+ const depVar = variable.dependencies[d];
2744
+ if (depVar.name !== variable.name) {
2745
+ let found = false;
2746
+ for (let j = 0; j < this.variables.length; j++) {
2747
+ if (depVar.name === this.variables[j].name) {
2748
+ found = true;
2749
+ break;
2750
+ }
2751
+ }
2752
+ if (!found) {
2753
+ return "Variable dependency not found. Variable=" + variable.name + ", dependency=" + depVar.name;
2754
+ }
2755
+ }
2756
+ uniforms[depVar.name] = { value: null };
2757
+ material.fragmentShader = "\nuniform sampler2D " + depVar.name + ";\n" + material.fragmentShader;
2758
+ }
2759
+ }
2760
+ }
2761
+ this.currentTextureIndex = 0;
2762
+ return null;
2763
+ };
2764
+ this.compute = function() {
2765
+ const currentTextureIndex = this.currentTextureIndex;
2766
+ const nextTextureIndex = this.currentTextureIndex === 0 ? 1 : 0;
2767
+ for (let i = 0, il = this.variables.length; i < il; i++) {
2768
+ const variable = this.variables[i];
2769
+ if (variable.dependencies !== null) {
2770
+ const uniforms = variable.material.uniforms;
2771
+ for (let d = 0, dl = variable.dependencies.length; d < dl; d++) {
2772
+ const depVar = variable.dependencies[d];
2773
+ uniforms[depVar.name].value = depVar.renderTargets[currentTextureIndex].texture;
2774
+ }
2775
+ }
2776
+ this.doRenderTarget(variable.material, variable.renderTargets[nextTextureIndex]);
2777
+ }
2778
+ this.currentTextureIndex = nextTextureIndex;
2779
+ };
2780
+ this.getCurrentRenderTarget = function(variable) {
2781
+ return variable.renderTargets[this.currentTextureIndex];
2782
+ };
2783
+ this.getAlternateRenderTarget = function(variable) {
2784
+ return variable.renderTargets[this.currentTextureIndex === 0 ? 1 : 0];
2785
+ };
2786
+ this.dispose = function() {
2787
+ quad.dispose();
2788
+ const variables = this.variables;
2789
+ for (let i = 0; i < variables.length; i++) {
2790
+ const variable = variables[i];
2791
+ if (variable.initialValueTexture) variable.initialValueTexture.dispose();
2792
+ const renderTargets = variable.renderTargets;
2793
+ for (let j = 0; j < renderTargets.length; j++) {
2794
+ const renderTarget = renderTargets[j];
2795
+ renderTarget.dispose();
2796
+ }
2797
+ }
2798
+ };
2799
+ function addResolutionDefine(materialShader) {
2800
+ materialShader.defines.resolution = "vec2( " + sizeX.toFixed(1) + ", " + sizeY.toFixed(1) + " )";
2801
+ }
2802
+ this.addResolutionDefine = addResolutionDefine;
2803
+ function createShaderMaterial(computeFragmentShader, uniforms) {
2804
+ uniforms = uniforms || {};
2805
+ const material = new ShaderMaterial({
2806
+ name: "GPUComputationShader",
2807
+ uniforms,
2808
+ vertexShader: getPassThroughVertexShader(),
2809
+ fragmentShader: computeFragmentShader
2810
+ });
2811
+ addResolutionDefine(material);
2812
+ return material;
2813
+ }
2814
+ this.createShaderMaterial = createShaderMaterial;
2815
+ this.createRenderTarget = function(sizeXTexture, sizeYTexture, wrapS, wrapT, minFilter, magFilter) {
2816
+ sizeXTexture = sizeXTexture || sizeX;
2817
+ sizeYTexture = sizeYTexture || sizeY;
2818
+ wrapS = wrapS || ClampToEdgeWrapping;
2819
+ wrapT = wrapT || ClampToEdgeWrapping;
2820
+ minFilter = minFilter || NearestFilter;
2821
+ magFilter = magFilter || NearestFilter;
2822
+ const renderTarget = new WebGLRenderTarget(sizeXTexture, sizeYTexture, {
2823
+ wrapS,
2824
+ wrapT,
2825
+ minFilter,
2826
+ magFilter,
2827
+ format: RGBAFormat,
2828
+ type: dataType,
2829
+ depthBuffer: false
2830
+ });
2831
+ return renderTarget;
2832
+ };
2833
+ this.createTexture = function() {
2834
+ const data = new Float32Array(sizeX * sizeY * 4);
2835
+ const texture = new DataTexture(data, sizeX, sizeY, RGBAFormat, FloatType);
2836
+ texture.needsUpdate = true;
2837
+ return texture;
2838
+ };
2839
+ this.renderTexture = function(input, output) {
2840
+ passThruUniforms.passThruTexture.value = input;
2841
+ this.doRenderTarget(passThruShader, output);
2842
+ passThruUniforms.passThruTexture.value = null;
2843
+ };
2844
+ this.doRenderTarget = function(material, output) {
2845
+ const currentRenderTarget = renderer.getRenderTarget();
2846
+ const currentXrEnabled = renderer.xr.enabled;
2847
+ const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;
2848
+ renderer.xr.enabled = false;
2849
+ renderer.shadowMap.autoUpdate = false;
2850
+ quad.material = material;
2851
+ renderer.setRenderTarget(output);
2852
+ quad.render(renderer);
2853
+ quad.material = passThruShader;
2854
+ renderer.xr.enabled = currentXrEnabled;
2855
+ renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;
2856
+ renderer.setRenderTarget(currentRenderTarget);
2857
+ };
2858
+ function getPassThroughVertexShader() {
2859
+ return "void main() {\n\n gl_Position = vec4( position, 1.0 );\n\n}\n";
2860
+ }
2861
+ function getPassThroughFragmentShader() {
2862
+ return "uniform sampler2D passThruTexture;\n\nvoid main() {\n\n vec2 uv = gl_FragCoord.xy / resolution.xy;\n\n gl_FragColor = texture2D( passThruTexture, uv );\n\n}\n";
2863
+ }
2864
+ }
2865
+ }
2866
+ const mixShader = `
2867
+ uniform sampler2D uPositionA;
2868
+ uniform sampler2D uPositionB;
2869
+ uniform float uProgress;
2870
+
2871
+ void main() {
2872
+ vec2 uv = gl_FragCoord.xy / resolution.xy;
2873
+ vec3 positionA = texture2D(uPositionA, uv).xyz;
2874
+ vec3 positionB = texture2D(uPositionB, uv).xyz;
2875
+ vec3 mixedPosition = mix(positionA, positionB, uProgress);
2876
+ gl_FragColor = vec4(mixedPosition, 1.0);
2877
+ }
2878
+ `;
2879
+ const positionShader = `
2880
+ uniform float uProgress;
2881
+ uniform vec4 uInteractionPosition;
2882
+ uniform float uTime;
2883
+ uniform float uTractionForce;
2884
+
2885
+ float rand(vec2 co) {
2886
+ return fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453);
2887
+ }
2888
+
2889
+ void main() {
2890
+
2891
+ // in GPGPU, we calculate the uv on each fragment shader, not using the static varying passed over from the v shader.
2892
+ vec2 uv = gl_FragCoord.xy / resolution.xy;
2893
+ float offset = rand(uv);
2894
+
2895
+ vec3 position = texture2D(uCurrentPosition, uv).xyz;
2896
+ vec3 velocity = texture2D(uCurrentVelocity, uv).xyz;
2897
+ vec3 mixedPosition = texture2D(uMixedPosition, uv).xyz;
2898
+
2899
+ // particle attraction to original position.
2900
+ vec3 direction = normalize(mixedPosition - position); // direction vector
2901
+ float dist = length ( mixedPosition - position ); // distance from where it was supposed to be, and currently are.
2902
+
2903
+ if (dist > 0.01) {
2904
+ position = mix(position, mixedPosition, 0.1 * uTractionForce); // 0.1 ~ 0.001 (faster, slower)
2905
+ }
2906
+
2907
+ position += velocity;
2908
+ gl_FragColor = vec4(position, 1.0);
2909
+ }
2910
+ `;
2911
+ const velocityShader = `
2912
+ uniform float uProgress;
2913
+ uniform vec4 uInteractionPosition;
2914
+ uniform float uTime;
2915
+ uniform float uTractionForce;
2916
+ uniform float uMaxRepelDistance;
2917
+
2918
+ float rand(vec2 co) {
2919
+ return fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453);
2920
+ }
2921
+
2922
+ void main() {
2923
+ vec2 uv = gl_FragCoord.xy / resolution.xy;
2924
+ float offset = rand(uv);
2925
+
2926
+ vec3 position = texture2D(uCurrentPosition, uv).xyz;
2927
+ vec3 velocity = texture2D(uCurrentVelocity, uv).xyz;
2928
+ vec3 mixedPosition = texture2D(uMixedPosition, uv).xyz;
2929
+
2930
+ velocity *= 0.9;
2931
+
2932
+ // particle traction
2933
+ vec3 direction = normalize(mixedPosition - position); // direction vector
2934
+ float dist = length ( mixedPosition - position ); // distance from where it was supposed to be, and currently are.
2935
+ if (dist > 0.01) {
2936
+ position += direction * 0.1 * uTractionForce; // uTractionForce defaults to 0.1
2937
+ }
2938
+
2939
+ // mouse repel force
2940
+ float pointerDistance = distance(position, uInteractionPosition.xyz);
2941
+ float mouseRepelModifier = clamp(uMaxRepelDistance - pointerDistance, 0.0, 1.0);
2942
+ float normalizedDistance = pointerDistance / uMaxRepelDistance;
2943
+ float repulsionStrength = (1.0 - normalizedDistance) * uInteractionPosition.w;
2944
+ direction = normalize(position - uInteractionPosition.xyz);
2945
+ velocity += (direction * 0.01 * repulsionStrength) * mouseRepelModifier;
2946
+
2947
+ float lifespan = 20.0;
2948
+ float age = mod(uTime + lifespan * offset, lifespan);
2949
+
2950
+ if (age < 0.1) {
2951
+ position.xyz = mixedPosition;
2952
+ }
2953
+
2954
+ gl_FragColor = vec4(velocity, 1.0);
2955
+ }
2956
+ `;
2957
+ class SimulationRenderer {
2958
+ /**
2959
+ * Creates a new SimulationRenderer instance.
2960
+ * @param size The size of the simulation textures.
2961
+ * @param webGLRenderer The WebGL renderer.
2962
+ * @param initialPosition The initial position data texture. If not provided, a default sphere will be used.
2963
+ */
2964
+ constructor(size, webGLRenderer, initialPosition) {
2965
+ __publicField(this, "gpuComputationRenderer");
2966
+ __publicField(this, "webGLRenderer");
2967
+ // calculations
2968
+ __publicField(this, "positionDataTexture");
2969
+ __publicField(this, "velocityDataTexture");
2970
+ // GPUComputationRenderer variables
2971
+ __publicField(this, "mixPositionsVar");
2972
+ __publicField(this, "velocityVar");
2973
+ __publicField(this, "positionVar");
2974
+ __publicField(this, "interactionPosition");
2975
+ __publicField(this, "lastKnownPositionDataTexture");
2976
+ __publicField(this, "lastKnownVelocityDataTexture");
2977
+ __publicField(this, "lastKnownMixProgress");
2978
+ __publicField(this, "initialDataTexture");
2979
+ this.initialDataTexture = initialPosition ?? createSpherePoints(size);
2980
+ this.positionDataTexture = this.initialDataTexture;
2981
+ this.webGLRenderer = webGLRenderer;
2982
+ this.gpuComputationRenderer = new GPUComputationRenderer(size, size, this.webGLRenderer);
2983
+ this.lastKnownMixProgress = 0;
2984
+ if (!webGLRenderer.capabilities.isWebGL2) {
2985
+ this.gpuComputationRenderer.setDataType(THREE.HalfFloatType);
2986
+ }
2987
+ this.velocityDataTexture = createBlankDataTexture(size);
2988
+ this.interactionPosition = new THREE.Vector4(0, 0, 0, 0);
2989
+ this.mixPositionsVar = this.gpuComputationRenderer.addVariable("uMixedPosition", mixShader, this.positionDataTexture);
2990
+ this.velocityVar = this.gpuComputationRenderer.addVariable("uCurrentVelocity", velocityShader, this.velocityDataTexture);
2991
+ this.positionVar = this.gpuComputationRenderer.addVariable("uCurrentPosition", positionShader, this.positionDataTexture);
2992
+ this.mixPositionsVar.material.uniforms.uProgress = { value: 0 };
2993
+ this.mixPositionsVar.material.uniforms.uPositionA = { value: this.initialDataTexture };
2994
+ this.mixPositionsVar.material.uniforms.uPositionB = { value: this.initialDataTexture };
2995
+ this.velocityVar.material.uniforms.uTime = { value: 0 };
2996
+ this.velocityVar.material.uniforms.uInteractionPosition = { value: this.interactionPosition };
2997
+ this.velocityVar.material.uniforms.uCurrentPosition = { value: this.positionDataTexture };
2998
+ this.velocityVar.material.uniforms.uTractionForce = { value: 0.1 };
2999
+ this.velocityVar.material.uniforms.uMaxRepelDistance = { value: 0.3 };
3000
+ this.positionVar.material.uniforms.uTime = { value: 0 };
3001
+ this.positionVar.material.uniforms.uProgress = { value: 0 };
3002
+ this.positionVar.material.uniforms.uTractionForce = { value: 0.1 };
3003
+ this.positionVar.material.uniforms.uInteractionPosition = { value: this.interactionPosition };
3004
+ this.positionVar.material.uniforms.uCurrentPosition = { value: this.positionDataTexture };
3005
+ this.gpuComputationRenderer.setVariableDependencies(this.positionVar, [this.velocityVar, this.positionVar, this.mixPositionsVar]);
3006
+ this.gpuComputationRenderer.setVariableDependencies(this.velocityVar, [this.velocityVar, this.positionVar, this.mixPositionsVar]);
3007
+ const err = this.gpuComputationRenderer.init();
3008
+ if (err) {
3009
+ throw new Error("failed to initialize SimulationRenderer: " + err);
3010
+ }
3011
+ this.lastKnownVelocityDataTexture = this.getVelocityTexture();
3012
+ this.lastKnownPositionDataTexture = this.getPositionTexture();
3013
+ }
3014
+ /**
3015
+ * Sets the source data texture for morphing.
3016
+ * @param texture The source data texture.
3017
+ */
3018
+ setMorphSourceDataTexture(texture) {
3019
+ this.mixPositionsVar.material.uniforms.uPositionA.value = texture;
3020
+ }
3021
+ /**
3022
+ * Sets the destination data texture for morphing.
3023
+ * @param texture The destination data texture.
3024
+ */
3025
+ setMorphDestinationDataTexture(texture) {
3026
+ this.mixPositionsVar.material.uniforms.uPositionB.value = texture;
3027
+ }
3028
+ setMaxRepelDistance(distance) {
3029
+ this.velocityVar.material.uniforms.uMaxRepelDistance.value = distance;
3030
+ }
3031
+ /**
3032
+ * Sets the progress of the morphing animation.
3033
+ * @param progress The progress value, between 0 and 1.
3034
+ */
3035
+ setProgress(progress) {
3036
+ this.lastKnownMixProgress = clamp(progress, 0, 1);
3037
+ this.mixPositionsVar.material.uniforms.uProgress.value = this.lastKnownMixProgress;
3038
+ }
3039
+ setVelocityTractionForce(force) {
3040
+ this.velocityVar.material.uniforms.uTractionForce.value = force;
3041
+ }
3042
+ setPositionalTractionForce(force) {
3043
+ this.positionVar.material.uniforms.uTractionForce.value = force;
3044
+ }
3045
+ setInteractionPosition(position) {
3046
+ this.interactionPosition.copy(position);
3047
+ }
3048
+ /**
3049
+ * Disposes the resources used by the simulation renderer.
3050
+ */
3051
+ dispose() {
3052
+ this.mixPositionsVar.renderTargets.forEach((rtt) => rtt.dispose());
3053
+ this.positionVar.renderTargets.forEach((rtt) => rtt.dispose());
3054
+ this.velocityVar.renderTargets.forEach((rtt) => rtt.dispose());
3055
+ this.positionDataTexture.dispose();
3056
+ this.velocityDataTexture.dispose();
3057
+ this.gpuComputationRenderer.dispose();
3058
+ }
3059
+ /**
3060
+ * Computes the next step of the simulation.
3061
+ * @param elapsedTime The elapsed time since the simulation started.
3062
+ */
3063
+ compute(elapsedTime) {
3064
+ this.velocityVar.material.uniforms.uTime.value = elapsedTime;
3065
+ this.positionVar.material.uniforms.uTime.value = elapsedTime;
3066
+ this.gpuComputationRenderer.compute();
3067
+ }
3068
+ /**
3069
+ * Gets the current velocity texture.
3070
+ * @returns The current velocity texture.
3071
+ */
3072
+ getVelocityTexture() {
3073
+ this.lastKnownVelocityDataTexture = this.gpuComputationRenderer.getCurrentRenderTarget(this.velocityVar).texture;
3074
+ return this.lastKnownVelocityDataTexture;
3075
+ }
3076
+ /**
3077
+ * Gets the current position texture.
3078
+ * @returns The current position texture.
3079
+ */
3080
+ getPositionTexture() {
3081
+ this.lastKnownPositionDataTexture = this.gpuComputationRenderer.getCurrentRenderTarget(this.positionVar).texture;
3082
+ return this.lastKnownPositionDataTexture;
3083
+ }
3084
+ }
3085
+ class SimulationRendererService {
3086
+ constructor(eventEmitter, size, webGLRenderer) {
3087
+ __publicField(this, "state");
3088
+ __publicField(this, "textureSize");
3089
+ __publicField(this, "dataTextureTransitionProgress");
3090
+ __publicField(this, "velocityTractionForce");
3091
+ __publicField(this, "positionalTractionForce");
3092
+ __publicField(this, "simulationRenderer");
3093
+ __publicField(this, "webGLRenderer");
3094
+ __publicField(this, "eventEmitter");
3095
+ __publicField(this, "lastKnownVelocityDataTexture");
3096
+ __publicField(this, "lastKnownPositionDataTexture");
3097
+ this.eventEmitter = eventEmitter;
3098
+ this.webGLRenderer = webGLRenderer;
3099
+ this.textureSize = size;
3100
+ this.dataTextureTransitionProgress = 0;
3101
+ this.velocityTractionForce = 0.1;
3102
+ this.positionalTractionForce = 0.1;
3103
+ this.updateServiceState("initializing");
3104
+ this.simulationRenderer = new SimulationRenderer(this.textureSize, this.webGLRenderer);
3105
+ this.lastKnownVelocityDataTexture = this.simulationRenderer.getVelocityTexture();
3106
+ this.lastKnownPositionDataTexture = this.simulationRenderer.getPositionTexture();
3107
+ this.updateServiceState("ready");
3108
+ }
3109
+ setTextureSize(size) {
3110
+ this.updateServiceState("initializing");
3111
+ this.simulationRenderer.dispose();
3112
+ this.textureSize = size;
3113
+ this.simulationRenderer = new SimulationRenderer(size, this.webGLRenderer);
3114
+ this.updateServiceState("ready");
3115
+ }
3116
+ setOriginDataTexture(entry) {
3117
+ if (this.textureSize !== entry.textureSize) {
3118
+ this.eventEmitter.emit("invalidRequest", { message: `Texture size mismatch: ${entry.textureSize} vs ${this.textureSize}` });
3119
+ } else {
3120
+ this.simulationRenderer.setMorphSourceDataTexture(entry.dataTexture);
3121
+ }
3122
+ }
3123
+ setDestinationDataTexture(entry) {
3124
+ if (this.textureSize !== entry.textureSize) {
3125
+ this.eventEmitter.emit("invalidRequest", { message: `Texture size mismatch: ${entry.textureSize} vs ${this.textureSize}` });
3126
+ } else {
3127
+ this.simulationRenderer.setMorphDestinationDataTexture(entry.dataTexture);
3128
+ }
3129
+ }
3130
+ setDataTextureTransitionProgress(progress) {
3131
+ this.dataTextureTransitionProgress = progress;
3132
+ this.simulationRenderer.setProgress(this.dataTextureTransitionProgress);
3133
+ }
3134
+ setVelocityTractionForce(force) {
3135
+ this.velocityTractionForce = force;
3136
+ this.simulationRenderer.setVelocityTractionForce(this.velocityTractionForce);
3137
+ }
3138
+ setPositionalTractionForce(force) {
3139
+ this.positionalTractionForce = force;
3140
+ this.simulationRenderer.setPositionalTractionForce(this.positionalTractionForce);
3141
+ }
3142
+ compute(elapsedTime) {
3143
+ this.simulationRenderer.compute(elapsedTime);
3144
+ }
3145
+ getVelocityTexture() {
3146
+ if (this.state === "ready") this.lastKnownVelocityDataTexture = this.simulationRenderer.getVelocityTexture();
3147
+ return this.lastKnownVelocityDataTexture;
3148
+ }
3149
+ getPositionTexture() {
3150
+ if (this.state === "ready") this.lastKnownPositionDataTexture = this.simulationRenderer.getPositionTexture();
3151
+ return this.lastKnownPositionDataTexture;
3152
+ }
3153
+ dispose() {
3154
+ this.updateServiceState("disposed");
3155
+ this.simulationRenderer.dispose();
3156
+ this.lastKnownVelocityDataTexture.dispose();
3157
+ this.lastKnownPositionDataTexture.dispose();
3158
+ }
3159
+ updateServiceState(serviceState) {
3160
+ this.state = serviceState;
3161
+ this.eventEmitter.emit("serviceStateUpdated", { type: "simulation", state: serviceState });
3162
+ }
3163
+ setInteractionPosition(position) {
3164
+ this.simulationRenderer.setInteractionPosition(position);
3165
+ }
3166
+ setMaxRepelDistance(distance) {
3167
+ this.simulationRenderer.setMaxRepelDistance(distance);
3168
+ }
3169
+ }
3170
+ class ExecutionStatusMap {
3171
+ constructor() {
3172
+ __publicField(this, "execStatus", /* @__PURE__ */ new Map());
3173
+ }
3174
+ get(type) {
3175
+ const status = this.execStatus.get(type);
3176
+ if (!status) {
3177
+ this.execStatus.set(type, "idle");
3178
+ return "idle";
3179
+ }
3180
+ return status;
3181
+ }
3182
+ set(type, status) {
3183
+ this.execStatus.set(type, status);
3184
+ }
3185
+ }
3186
+ class TransitionService {
3187
+ constructor(eventEmitter) {
3188
+ __publicField(this, "eventEmitter");
3189
+ __publicField(this, "transitions", /* @__PURE__ */ new Map());
3190
+ __publicField(this, "execStatus");
3191
+ __publicField(this, "ongoingTransitions", /* @__PURE__ */ new Map());
3192
+ this.eventEmitter = eventEmitter;
3193
+ this.execStatus = new ExecutionStatusMap();
3194
+ this.eventEmitter.on("transitionCancelled", this.handleTransitionCancelledEvent.bind(this));
3195
+ }
3196
+ /**
3197
+ * Enqueues a transition.
3198
+ * @param type - The type of transition.
3199
+ * @param transition - The transition details.
3200
+ * @param options - Optional transition options.
3201
+ */
3202
+ enqueue(type, transition, options = {}) {
3203
+ const transitionQueueItem = {
3204
+ ...transition,
3205
+ ...options,
3206
+ cancelled: false,
3207
+ duration: transition.duration * 1e-3
3208
+ // convert to seconds
3209
+ };
3210
+ this.getQueue(type).push(transitionQueueItem);
3211
+ }
3212
+ compute(elapsedTime) {
3213
+ this.transitions.forEach((queue, type) => {
3214
+ var _a;
3215
+ if (queue.length && !this.ongoingTransitions.has(type)) {
3216
+ const transition = queue.shift();
3217
+ if (transition) {
3218
+ this.ongoingTransitions.set(type, { ...transition, startTime: elapsedTime });
3219
+ (_a = transition.onTransitionBegin) == null ? void 0 : _a.call(transition);
3220
+ }
3221
+ }
3222
+ });
3223
+ this.ongoingTransitions.forEach((transition, type) => {
3224
+ var _a, _b, _c;
3225
+ if (transition.cancelled) {
3226
+ (_a = transition.onTransitionCancelled) == null ? void 0 : _a.call(transition);
3227
+ this.ongoingTransitions.delete(type);
3228
+ return;
3229
+ }
3230
+ const { startTime, duration, easing } = transition;
3231
+ const timeDistance = elapsedTime - startTime;
3232
+ const progress = clamp(easing(Math.min(1, timeDistance / duration)), 0, 1);
3233
+ this.emitTransitionProgress(type, progress);
3234
+ (_b = transition.onTransitionProgress) == null ? void 0 : _b.call(transition, progress);
3235
+ if (progress >= 1) {
3236
+ this.emitTransitionFinished(type);
3237
+ (_c = transition.onTransitionFinished) == null ? void 0 : _c.call(transition);
3238
+ this.ongoingTransitions.delete(type);
3239
+ }
3240
+ });
3241
+ }
3242
+ getQueue(type) {
3243
+ const queue = this.transitions.get(type);
3244
+ if (!queue) {
3245
+ this.transitions.set(type, []);
3246
+ return this.transitions.get(type) ?? [];
3247
+ }
3248
+ return queue;
3249
+ }
3250
+ handleTransitionCancelledEvent({ type }) {
3251
+ var _a;
3252
+ const transitions = this.getQueue(type);
3253
+ while (transitions.length) transitions.pop();
3254
+ const ongoingTransition = this.ongoingTransitions.get(type);
3255
+ if (ongoingTransition) {
3256
+ ongoingTransition.cancelled = true;
3257
+ (_a = ongoingTransition.onTransitionCancelled) == null ? void 0 : _a.call(ongoingTransition);
3258
+ }
3259
+ }
3260
+ emitTransitionProgress(type, progress) {
3261
+ this.eventEmitter.emit("transitionProgressed", { type, progress });
3262
+ }
3263
+ emitTransitionFinished(type) {
3264
+ this.eventEmitter.emit("transitionFinished", { type });
3265
+ }
3266
+ }
3267
+ class ParticlesEngine {
3268
+ /**
3269
+ * Creates a new ParticlesEngine instance.
3270
+ * @param params The parameters for creating the instance.
3271
+ */
3272
+ constructor(params) {
3273
+ __publicField(this, "simulationRendererService");
3274
+ __publicField(this, "eventEmitter");
3275
+ __publicField(this, "renderer");
3276
+ __publicField(this, "scene");
3277
+ __publicField(this, "serviceStates");
3278
+ // assets
3279
+ __publicField(this, "dataTextureManager");
3280
+ __publicField(this, "matcapService");
3281
+ __publicField(this, "instancedMeshManager");
3282
+ __publicField(this, "transitionService");
3283
+ __publicField(this, "engineState");
3284
+ __publicField(this, "intersectionService");
3285
+ this.eventEmitter = new DefaultEventEmitter();
3286
+ this.serviceStates = this.initialServiceStates();
3287
+ this.eventEmitter.on("serviceStateUpdated", this.handleServiceStateUpdated.bind(this));
3288
+ this.scene = params.scene;
3289
+ this.renderer = params.renderer;
3290
+ this.engineState = this.initialEngineState(params.textureSize);
3291
+ this.transitionService = new TransitionService(this.eventEmitter);
3292
+ this.dataTextureManager = new DataTextureService(this.eventEmitter, params.textureSize, params.meshes);
3293
+ this.matcapService = new MatcapService(this.eventEmitter, params.matcaps);
3294
+ this.simulationRendererService = new SimulationRendererService(this.eventEmitter, params.textureSize, this.renderer);
3295
+ this.instancedMeshManager = new InstancedMeshManager(params.textureSize);
3296
+ this.instancedMeshManager.useMatcapMaterial();
3297
+ this.scene.add(this.instancedMeshManager.getMesh());
3298
+ this.intersectionService = new IntersectionService(this.eventEmitter, params.camera);
3299
+ this.eventEmitter.on("transitionProgressed", this.handleTransitionProgress.bind(this));
3300
+ this.eventEmitter.on("interactionPositionUpdated", this.handleInteractionPositionUpdated.bind(this));
3301
+ }
3302
+ /**
3303
+ * Renders the scene.
3304
+ * @param elapsedTime The elapsed time since the last frame.
3305
+ */
3306
+ render(elapsedTime) {
3307
+ this.intersectionService.calculate();
3308
+ this.transitionService.compute(elapsedTime);
3309
+ this.simulationRendererService.compute(elapsedTime);
3310
+ this.instancedMeshManager.update(elapsedTime);
3311
+ this.instancedMeshManager.updateVelocityTexture(this.simulationRendererService.getVelocityTexture());
3312
+ this.instancedMeshManager.updatePositionTexture(this.simulationRendererService.getPositionTexture());
3313
+ }
3314
+ setOriginDataTexture(meshID, override = false) {
3315
+ if (override) this.eventEmitter.emit("transitionCancelled", { type: "data-texture" });
3316
+ this.dataTextureManager.getDataTexture(meshID).then((texture) => {
3317
+ this.engineState.originMeshID = meshID;
3318
+ this.simulationRendererService.setOriginDataTexture({
3319
+ dataTexture: texture,
3320
+ textureSize: this.engineState.textureSize
3321
+ });
3322
+ this.intersectionService.setOriginGeometry(this.dataTextureManager.getMesh(meshID));
3323
+ });
3324
+ }
3325
+ setDestinationDataTexture(meshID, override = false) {
3326
+ if (override) this.eventEmitter.emit("transitionCancelled", { type: "data-texture" });
3327
+ this.dataTextureManager.getDataTexture(meshID).then((texture) => {
3328
+ this.engineState.destinationMeshID = meshID;
3329
+ this.simulationRendererService.setDestinationDataTexture({
3330
+ dataTexture: texture,
3331
+ textureSize: this.engineState.textureSize
3332
+ });
3333
+ this.intersectionService.setDestinationGeometry(this.dataTextureManager.getMesh(meshID));
3334
+ });
3335
+ }
3336
+ setDataTextureTransitionProgress(progress, override = false) {
3337
+ if (override) this.eventEmitter.emit("transitionCancelled", { type: "data-texture" });
3338
+ this.engineState.dataTextureTransitionProgress = progress;
3339
+ this.simulationRendererService.setDataTextureTransitionProgress(progress);
3340
+ this.intersectionService.setProgress(progress);
3341
+ }
3342
+ setOriginMatcap(matcapID, override = false) {
3343
+ if (override) this.eventEmitter.emit("transitionCancelled", { type: "matcap" });
3344
+ this.engineState.originMatcapID = matcapID;
3345
+ this.instancedMeshManager.setOriginMatcap(this.matcapService.getMatcap(matcapID));
3346
+ }
3347
+ setDestinationMatcap(matcapID, override = false) {
3348
+ if (override) this.eventEmitter.emit("transitionCancelled", { type: "matcap" });
3349
+ this.engineState.destinationMatcapID = matcapID;
3350
+ this.instancedMeshManager.setDestinationMatcap(this.matcapService.getMatcap(matcapID));
3351
+ }
3352
+ setMatcapProgress(progress, override = false) {
3353
+ if (override) this.eventEmitter.emit("transitionCancelled", { type: "matcap" });
3354
+ this.engineState.matcapTransitionProgress = progress;
3355
+ this.instancedMeshManager.setProgress(progress);
3356
+ }
3357
+ async setTextureSize(size) {
3358
+ this.engineState.textureSize = size;
3359
+ this.dataTextureManager.setTextureSize(size);
3360
+ this.simulationRendererService.setTextureSize(size);
3361
+ this.instancedMeshManager.resize(size);
3362
+ this.dataTextureManager.getDataTexture(this.engineState.originMeshID).then((texture) => this.simulationRendererService.setOriginDataTexture({ dataTexture: texture, textureSize: size }));
3363
+ this.dataTextureManager.getDataTexture(this.engineState.destinationMeshID).then(
3364
+ (texture) => this.simulationRendererService.setDestinationDataTexture({
3365
+ dataTexture: texture,
3366
+ textureSize: size
3367
+ })
3368
+ );
3369
+ this.simulationRendererService.setDataTextureTransitionProgress(this.engineState.dataTextureTransitionProgress);
3370
+ this.simulationRendererService.setVelocityTractionForce(this.engineState.velocityTractionForce);
3371
+ this.simulationRendererService.setPositionalTractionForce(this.engineState.positionalTractionForce);
3372
+ this.instancedMeshManager.setOriginMatcap(this.matcapService.getMatcap(this.engineState.originMatcapID));
3373
+ this.instancedMeshManager.setDestinationMatcap(this.matcapService.getMatcap(this.engineState.destinationMatcapID));
3374
+ this.instancedMeshManager.setProgress(this.engineState.matcapTransitionProgress);
3375
+ this.instancedMeshManager.setGeometrySize(this.engineState.instanceGeometryScale);
3376
+ }
3377
+ setPointerPosition(position) {
3378
+ this.engineState.pointerPosition = position;
3379
+ this.intersectionService.setMousePosition(position);
3380
+ }
3381
+ setGeometrySize(geometrySize) {
3382
+ this.engineState.instanceGeometryScale = geometrySize;
3383
+ this.instancedMeshManager.setGeometrySize(geometrySize);
3384
+ }
3385
+ setVelocityTractionForce(force) {
3386
+ this.engineState.velocityTractionForce = force;
3387
+ this.simulationRendererService.setVelocityTractionForce(force);
3388
+ }
3389
+ setPositionalTractionForce(force) {
3390
+ this.engineState.positionalTractionForce = force;
3391
+ this.simulationRendererService.setPositionalTractionForce(force);
3392
+ }
3393
+ setMaxRepelDistance(distance) {
3394
+ this.engineState.maxRepelDistance = distance;
3395
+ this.simulationRendererService.setMaxRepelDistance(distance);
3396
+ }
3397
+ scheduleMeshTransition(originMeshID, destinationMeshID, easing = linear, duration = 1e3, override = false) {
3398
+ this.transitionService.enqueue(
3399
+ "data-texture",
3400
+ { easing, duration },
3401
+ {
3402
+ onTransitionBegin: () => {
3403
+ this.setOriginDataTexture(originMeshID, override);
3404
+ this.setDestinationDataTexture(destinationMeshID, override);
3405
+ this.setDataTextureTransitionProgress(0);
3406
+ }
3407
+ }
3408
+ );
3409
+ }
3410
+ scheduleMatcapTransition(originMatcapID, destinationMatcapID, easing = linear, duration = 1e3, override = false) {
3411
+ this.transitionService.enqueue(
3412
+ "matcap",
3413
+ { easing, duration },
3414
+ {
3415
+ onTransitionBegin: () => {
3416
+ this.setOriginMatcap(originMatcapID, override);
3417
+ this.setDestinationMatcap(destinationMatcapID, override);
3418
+ this.setMatcapProgress(0);
3419
+ }
3420
+ }
3421
+ );
3422
+ }
3423
+ handleServiceStateUpdated({ type, state }) {
3424
+ console.log("service state updated", type, state);
3425
+ this.serviceStates[type] = state;
3426
+ }
3427
+ /**
3428
+ * Disposes the resources used by the engine.
3429
+ */
3430
+ dispose() {
3431
+ this.scene.remove(this.instancedMeshManager.getMesh());
3432
+ this.matcapService.dispose();
3433
+ this.simulationRendererService.dispose();
3434
+ this.instancedMeshManager.dispose();
3435
+ this.intersectionService.dispose();
3436
+ this.dataTextureManager.dispose().then(() => console.log("engine disposed"));
3437
+ }
3438
+ initialEngineState(textureSize) {
3439
+ return {
3440
+ textureSize,
3441
+ originMeshID: "",
3442
+ destinationMeshID: "",
3443
+ dataTextureTransitionProgress: 0,
3444
+ originMatcapID: "",
3445
+ destinationMatcapID: "",
3446
+ matcapTransitionProgress: 0,
3447
+ velocityTractionForce: 0.1,
3448
+ positionalTractionForce: 0.1,
3449
+ maxRepelDistance: 0.3,
3450
+ pointerPosition: { x: 0, y: 0 },
3451
+ instanceGeometryScale: { x: 1, y: 1, z: 1 }
3452
+ };
3453
+ }
3454
+ initialServiceStates() {
3455
+ return {
3456
+ "data-texture": "created",
3457
+ "instanced-mesh": "created",
3458
+ matcap: "created",
3459
+ simulation: "created"
3460
+ };
3461
+ }
3462
+ handleTransitionProgress({ type, progress }) {
3463
+ switch (type) {
3464
+ case "data-texture":
3465
+ this.setDataTextureTransitionProgress(progress);
3466
+ break;
3467
+ case "matcap":
3468
+ this.setMatcapProgress(progress);
3469
+ break;
3470
+ }
3471
+ }
3472
+ handleInteractionPositionUpdated({ position }) {
3473
+ this.simulationRendererService.setInteractionPosition(position);
3474
+ }
3475
+ }
3476
+ export {
3477
+ ParticlesEngine
3478
+ };
3479
+ //# sourceMappingURL=index.es.js.map