-
Notifications
You must be signed in to change notification settings - Fork 1
/
physics-util.js
1003 lines (916 loc) · 26.4 KB
/
physics-util.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as THREE from 'three';
import * as BufferGeometryUtils from 'three/examples/jsm/utils/BufferGeometryUtils.js';
import {IdAllocator} from './id-allocator.js';
//
const localVector = new THREE.Vector3();
const localMatrix2 = new THREE.Matrix4();
//
const physicsIdAllcator = new IdAllocator();
export const getNextPhysicsId = physicsIdAllcator.alloc.bind(physicsIdAllcator);
export const freePhysicsId = physicsIdAllcator.free.bind(physicsIdAllcator);
export function convertMeshToPhysicsMesh(topMesh) {
const oldParent = topMesh.parent;
oldParent && oldParent.remove(topMesh);
topMesh.updateMatrixWorld();
const meshes = [];
topMesh.traverse((o) => {
if (o.isMesh) {
meshes.push(o);
}
});
const newGeometries = meshes.map((mesh) => {
const {geometry} = mesh;
const newGeometry = new THREE.BufferGeometry();
if (mesh.isSkinnedMesh) {
localMatrix2.identity();
} else {
localMatrix2.copy(mesh.matrixWorld);
}
if (geometry.attributes.position.isInterleavedBufferAttribute) {
const positions = new Float32Array(
geometry.attributes.position.count * 3
);
for (
let i = 0, j = 0;
i < positions.length;
i += 3, j += geometry.attributes.position.data.stride
) {
localVector
.fromArray(geometry.attributes.position.data.array, j)
.applyMatrix4(localMatrix2)
.toArray(positions, i);
}
newGeometry.setAttribute(
'position',
new THREE.BufferAttribute(positions, 3)
);
} else {
const positions = new Float32Array(
geometry.attributes.position.array.length
);
for (let i = 0; i < positions.length; i += 3) {
localVector
.fromArray(geometry.attributes.position.array, i)
.applyMatrix4(localMatrix2)
.toArray(positions, i);
}
newGeometry.setAttribute(
'position',
new THREE.BufferAttribute(positions, 3)
);
}
if (geometry.index) {
newGeometry.setIndex(geometry.index);
}
return newGeometry;
});
if (oldParent) {
oldParent.add(topMesh);
topMesh.updateMatrixWorld();
}
let physicsMesh;
if (newGeometries.length > 0) {
const newGeometry =
BufferGeometryUtils.mergeBufferGeometries(newGeometries);
physicsMesh = new THREE.Mesh(newGeometry);
} else {
physicsMesh = new THREE.Mesh();
}
physicsMesh.visible = false;
if (topMesh.parent) {
topMesh.parent.matrixWorld.decompose(
physicsMesh.position,
physicsMesh.quaternion,
physicsMesh.scale
);
physicsMesh.updateMatrixWorld();
}
return physicsMesh;
}
export const align = (v, N) => {
const r = v % N;
return r === 0 ? v : v - r + N;
};
export const align4 = v => align(v, 4);
export const getClosestPowerOf2 = size => Math.ceil(Math.log2(size));
/* import * as THREE from 'three';
import * as BufferGeometryUtils from 'three/examples/jsm/utils/BufferGeometryUtils.js';
import {
playersMapName,
tokensHost,
storageHost,
audioTimeoutTime,
} from './constants.js';
import {IdAllocator} from './id-allocator.js';
import {isWorker} from './env.js';
const localVector = new THREE.Vector3();
const localVector2 = new THREE.Vector3();
const localVector3 = new THREE.Vector3();
const localVector4 = new THREE.Vector3();
const localVector5 = new THREE.Vector3();
const localMatrix = new THREE.Matrix4();
const localMatrix2 = new THREE.Matrix4();
export function jsonParse(s, d = null) {
try {
return JSON.parse(s);
} catch (err) {
return d;
}
}
export function parseQuery(queryString) {
const query = {};
const pairs = (
queryString[0] === '?' ? queryString.substr(1) : queryString
).split('&');
for (let i = 0; i < pairs.length; i++) {
const pair = pairs[i].split('=');
const k = decodeURIComponent(pair[0]);
if (k) {
const v = decodeURIComponent(pair[1] || '');
query[k] = v;
}
}
return query;
}
export function getRandomString() {
return Math.random().toString(36).substring(7);
}
export function hex2Uint8Array(hex) {
return new Uint8Array(hex.match(/[\da-f]{2}/gi).map((h) => parseInt(h, 16)));
}
export function uint8Array2hex(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
export function getExt(fileName) {
const match = fileName
.replace(/^[a-z]+:\/\/[^\/]+\//, '')
.match(/\.([^\.]+|t\.js|rtf\.js)(?:\?.*)?$/);
return match ? match[1].toLowerCase() : '';
}
export function downloadFile(file, filename) {
const blobURL = URL.createObjectURL(file);
const tempLink = document.createElement('a');
tempLink.style.display = 'none';
tempLink.href = blobURL;
tempLink.setAttribute('download', filename);
document.body.appendChild(tempLink);
tempLink.click();
document.body.removeChild(tempLink);
}
export function readFile(file) {
return new Promise((accept, reject) => {
const fr = new FileReader();
fr.onload = () => {
accept(new Uint8Array(fr.result));
};
fr.onerror = reject;
fr.readAsArrayBuffer(file);
});
}
export function snapPosition(o, positionSnap) {
if (positionSnap > 0) {
o.position.x =
Math.round((o.position.x + positionSnap / 2) / positionSnap) *
positionSnap -
positionSnap / 2;
o.position.y =
Math.round((o.position.y + positionSnap / 2) / positionSnap) *
positionSnap -
positionSnap / 2;
o.position.z =
Math.round((o.position.z + positionSnap / 2) / positionSnap) *
positionSnap -
positionSnap / 2;
}
}
export function snapRotation(o, rotationSnap) {
o.rotation.x = Math.round(o.rotation.x / rotationSnap) * rotationSnap;
o.rotation.y = Math.round(o.rotation.y / rotationSnap) * rotationSnap;
o.rotation.z = Math.round(o.rotation.z / rotationSnap) * rotationSnap;
}
export function makePromise() {
let accept, reject;
const p = new Promise((a, r) => {
accept = a;
reject = r;
});
p.accept = accept;
p.reject = reject;
return p;
}
export function clone(o) {
return JSON.parse(JSON.stringify(o));
}
export class WaitQueue {
constructor() {
this.locked = false;
this.waiterCbs = [];
}
async lock() {
if (!this.locked) {
this.locked = true;
} else {
const p = makePromise();
this.waiterCbs.push(p.accept);
await p;
}
}
async unlock() {
if (this.waiterCbs.length > 0) {
this.waiterCbs.pop()();
} else {
this.locked = false;
}
}
clearQueue() {
this.waiterCbs.length = 0;
}
}
export function parseCoord(s) {
if (s) {
const split = s.match(/^\[(-?[0-9\.]+),(-?[0-9\.]+),(-?[0-9\.]+)\]$/);
let x, y, z;
if (
split &&
!isNaN((x = parseFloat(split[1]))) &&
!isNaN((y = parseFloat(split[2]))) &&
!isNaN((z = parseFloat(split[3])))
) {
return new THREE.Vector3(x, y, z);
} else {
return null;
}
} else {
return null;
}
}
export function parseExtents(s) {
if (s) {
const split = s.match(
/^\[\[(-?[0-9\.]+),(-?[0-9\.]+),(-?[0-9\.]+)\],\[(-?[0-9\.]+),(-?[0-9\.]+),(-?[0-9\.]+)\]\]$/
);
let x1, y1, z1, x2, y2, z2;
if (
split &&
!isNaN((x1 = parseFloat(split[1]))) &&
!isNaN((y1 = parseFloat(split[2]))) &&
!isNaN((z1 = parseFloat(split[3]))) &&
!isNaN((x2 = parseFloat(split[4]))) &&
!isNaN((y2 = parseFloat(split[5]))) &&
!isNaN((z2 = parseFloat(split[6])))
) {
return new THREE.Box3(
new THREE.Vector3(x1, y1, z1),
new THREE.Vector3(x2, y2, z2)
);
} else {
return null;
}
} else {
return null;
}
}
export function isInIframe() {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
export async function contentIdToFile(contentId) {
let token = null;
if (typeof contentId === 'number') {
const res = await fetch(`${tokensHost}/${contentId}`);
token = await res.json();
const {hash, name, ext} = token.properties;
const res2 = await fetch(`${storageHost}/${hash}`);
const file = await res2.blob();
file.name = `${name}.${ext}`;
file.token = token;
return file;
} else if (typeof contentId === 'string') {
let url, name;
if (/blob:/.test(contentId)) {
const match = contentId.match(/^(.+)\/([^\/]+)$/);
if (match) {
url = match[1];
name = match[2];
} else {
console.warn(
'blob url not appended with /filename.ext and cannot be interpreted',
contentId
);
return null;
}
} else {
url = contentId;
name = contentId;
}
return {
url,
name,
token,
};
} else {
console.warn('unknown content id type', contentId);
return null;
}
}
export const addDefaultLights = (scene) => {
const ambientLight = new THREE.AmbientLight(0xffffff, 1);
scene.add(ambientLight);
scene.ambientLight = ambientLight;
const directionalLight = new THREE.DirectionalLight(0xffffff, 4);
directionalLight.position.set(1, 2, 3);
scene.add(directionalLight);
scene.directionalLight = directionalLight;
};
export const unFrustumCull = (o) => {
o.traverse((o) => {
if (o.isMesh) {
o.frustumCulled = false;
}
});
};
export const capitalize = (s) => s[0].toUpperCase() + s.slice(1);
export const epochStartTime = Date.now();
export const flipGeomeryUvs = (geometry) => {
for (let i = 0; i < geometry.attributes.uv.array.length; i += 2) {
const j = i + 1;
geometry.attributes.uv.array[j] = 1 - geometry.attributes.uv.array[j];
}
};
export const updateRaycasterFromMouseEvent = (() => {
const localVector2D = new THREE.Vector2();
return (renderer, camera, e, raycaster) => {
const mouse = localVector2D;
mouse.x =
(e.clientX / renderer.domElement.width) * renderer.getPixelRatio() * 2 -
1;
mouse.y =
-((e.clientY / renderer.domElement.height) * renderer.getPixelRatio()) *
2 +
1;
raycaster.setFromCamera(mouse, camera);
};
})();
export const getCameraUiPlane = (camera, distance, plane) => {
plane.setFromNormalAndCoplanarPoint(
localVector3.set(0, 0, 1).applyQuaternion(camera.quaternion),
localVector4
.copy(camera.position)
.add(localVector5.set(0, 0, -distance).applyQuaternion(camera.quaternion))
);
return plane;
};
export const getUiForwardIntersection = (() => {
const localRaycaster = new THREE.Raycaster();
const localPlane = new THREE.Plane();
return (renderer, camera, e, v) => {
updateRaycasterFromMouseEvent(renderer, camera, e, localRaycaster);
// project mesh outwards
const cameraUiPlane = getCameraUiPlane(camera, 2, localPlane);
const intersection = localRaycaster.ray.intersectPlane(cameraUiPlane, v);
return intersection;
};
})();
export function makeId(length) {
let result = '';
const characters =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
}
export function getLockChunkId(chunkPosition) {
return `chunk:${chunkPosition.x}, ${chunkPosition.y}, ${chunkPosition.z}}`;
}
export function mod(a, n) {
return ((a % n) + n) % n;
}
export const modUv = (uv) => {
uv.x = mod(uv.x, 1);
uv.y = mod(uv.y, 1);
return uv;
};
export function angleDifference(angle1, angle2) {
let a = angle2 - angle1;
a = mod(a + Math.PI, Math.PI * 2) - Math.PI;
return a;
}
export function getVelocityDampingFactor(dampingPer60Hz, timeDiff) {
return Math.pow(dampingPer60Hz, timeDiff / 60);
}
export function getPlayerPrefix(playerId) {
return playersMapName + '.' + playerId;
}
export function fitCameraToBoundingBox(camera, box, fitOffset = 1) {
const size = box.getSize(localVector);
const center = box.getCenter(localVector2);
const maxSize = Math.max(size.x, size.y, size.z);
const fitHeightDistance =
maxSize / (2 * Math.atan((Math.PI * camera.fov) / 360));
const fitWidthDistance = fitHeightDistance / camera.aspect;
const distance = fitOffset * Math.max(fitHeightDistance, fitWidthDistance);
const direction = center
.clone()
.sub(camera.position)
.normalize()
.multiplyScalar(distance);
camera.position.copy(center).add(direction);
camera.quaternion.setFromRotationMatrix(
localMatrix.lookAt(camera.position, center, camera.up)
);
}
export function applyVelocity(position, velocity, timeDiffS) {
position.add(localVector.copy(velocity).multiplyScalar(timeDiffS));
}
export function copyPQS(dst, src) {
dst.position.copy(src.position);
dst.quaternion.copy(src.quaternion);
dst.scale.copy(src.scale);
}
export async function loadJson(u) {
const res = await fetch(u);
return await res.json();
}
export async function loadImageBitmap(u) {
const res = await fetch(u);
const blob = await res.blob();
const imageBitmap = await createImageBitmap(blob);
return imageBitmap;
}
export async function loadAudio(u) {
const audio = new Audio();
const p = new Promise((accept, reject) => {
const timeout = setTimeout(() => {
console.warn('audio load seems hung', audio);
}, audioTimeoutTime);
const _cleanup = () => {
clearTimeout(timeout);
};
audio.oncanplay = () => {
_cleanup();
accept();
};
audio.onerror = (err) => {
_cleanup();
reject(err);
};
});
// console.log('got src', `../sounds/${soundType}/${fileName}`);
audio.crossOrigin = 'Anonymous';
audio.src = u;
audio.load();
await p;
// document.body.appendChild(audio);
return audio;
}
export async function loadAudioBuffer(audioContext, url) {
const res = await fetch(url);
const arrayBuffer = await res.arrayBuffer();
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
return audioBuffer;
}
export const memoize = (fn) => {
let loaded = false;
let cache = null;
return () => {
if (!loaded) {
cache = fn();
loaded = true;
}
return cache;
};
};
export function shuffle(array, rng = Math.random) {
let currentIndex = array.length;
let randomIndex;
// While there remain elements to shuffle...
while (currentIndex !== 0) {
// Pick a remaining element...
randomIndex = Math.floor(rng() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex],
array[currentIndex],
];
}
return array;
}
export const waitForFrame = () =>
new Promise((accept) => {
requestAnimationFrame(() => {
accept();
});
});
const doUpload = async (u, f, {onProgress = null} = {}) => {
var xhr = new XMLHttpRequest();
xhr.open('POST', u, true);
xhr.responseType = 'json';
xhr.upload.onprogress = (e) => {
onProgress && onProgress(e);
};
const j = await new Promise((accept, reject) => {
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
accept(xhr.response);
} else {
const err = new Error('invalid status code: ' + xhr.status);
reject(err);
}
};
xhr.onerror = reject;
xhr.send(f);
});
return j;
};
export const proxifyUrl = (u) => {
const match = u.match(/^([a-z0-9]+):\/\/([a-z0-9\-\.]+)(.+)$/i);
if (match) {
return (
'https://' +
match[1] +
'-' +
match[2].replace(/\-/g, '--').replace(/\./g, '-') +
'.proxy.webaverse.com' +
match[3]
);
} else {
return u;
}
};
export const createRelativeUrl = (u, baseUrl) => {
if (/^(?:[\.\/]|([a-z0-9]+):\/\/)/i.test(u)) {
return u;
} else {
if (!/([a-z0-9]+):\/\//i.test(baseUrl)) {
baseUrl = new URL(baseUrl, window.location.href).href;
}
return new URL(u, baseUrl).href;
}
};
export const getDropUrl = (o) => {
let u = null;
if (typeof o?.start_url === 'string') {
u = o.start_url;
}
return u;
};
export const handleDropJsonItem = async (item) => {
if (item?.kind === 'string') {
const s = await new Promise((accept, reject) => {
item.getAsString(accept);
});
const j = jsonParse(s);
if (j) {
const u = getDropUrl(j);
return u;
}
}
return null;
};
export const handleUpload = async (item, {onProgress = null} = {}) => {
console.log('uploading...', item);
const _handleFileList = async (item) => {
const formData = new FormData();
formData.append(
'',
new Blob([], {
type: 'application/x-directory',
}),
''
);
const files = item;
for (let i = 0; i < files.length; i++) {
const file = files[i];
formData.append(file.name, file, file.name);
}
const hashes = await doUpload(`https://ipfs.webaverse.com/`, formData, {
onProgress,
});
const rootDirectory = hashes.find((h) => h.name === '');
const rootDirectoryHash = rootDirectory.hash;
return `https://ipfs.webaverse.com/ipfs/${rootDirectoryHash}/`;
};
const _handleString = (item) => handleDropJsonItem(item);
const _handleDirectory = async (entry) => {
const formData = new FormData();
const rootEntry = entry;
const _recurse = async (entry) => {
function getFullPath(entry) {
return entry.fullPath.slice(rootEntry.fullPath.length);
}
const fullPath = getFullPath(entry);
// console.log('directory full path', entry.fullPath, rootEntry.fullPath, fullPath);
formData.append(
fullPath,
new Blob([], {
type: 'application/x-directory',
}),
fullPath
);
const reader = entry.createReader();
async function readEntries() {
const entries = await new Promise((accept, reject) => {
reader.readEntries((entries) => {
if (entries.length > 0) {
accept(entries);
} else {
accept(null);
}
}, reject);
});
return entries;
}
let entriesArray;
while ((entriesArray = await readEntries())) {
for (const entry of entriesArray) {
if (entry.isFile) {
const file = await new Promise((accept, reject) => {
entry.file(accept, reject);
});
const fullPath = getFullPath(entry);
formData.append(fullPath, file, fullPath);
} else if (entry.isDirectory) {
await _recurse(entry);
}
}
}
};
await _recurse(rootEntry);
const hashes = await doUpload(`https://ipfs.webaverse.com/`, formData, {
onProgress,
});
const rootDirectory = hashes.find((h) => h.name === '');
const rootDirectoryHash = rootDirectory.hash;
return `https://ipfs.webaverse.com/ipfs/${rootDirectoryHash}/`;
};
const _handleFile = async (file) => {
const j = await doUpload(`https://ipfs.webaverse.com/`, file, {
onProgress,
});
const {hash} = j;
const {name} = file;
return `${storageHost}/${hash}/${name}`;
};
const _uploadObject = async (item) => {
let u = null;
if (item instanceof FileList) {
u = _handleFileList(item);
} else {
if (item.kind === 'string') {
u = await _handleString(item);
} else {
const entry = item.webkitGetAsEntry();
if (entry.isDirectory) {
u = await _handleDirectory(entry);
} else {
const file = item.getAsFile();
u = await _handleFile(file);
}
}
}
return u;
};
const u = await _uploadObject(item);
console.log('upload complete:', u);
return u;
};
export const loadImage = (u) => new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
resolve(img);
};
img.onerror = reject;
img.crossOrigin = 'Anonymous';
img.src = u;
});
export const blob2img = async blob => {
const url = URL.createObjectURL(blob);
try {
const img = await loadImage(url);
return img;
} finally {
URL.revokeObjectURL(url);
}
};
export const img2canvas = img => {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
return canvas;
};
export const canvas2blob = async (canvas, type, quality) => new Promise((resolve, reject) => {
canvas.toBlob(resolve, type, quality);
});
export const drawImageContain = (ctx, img) => {
const imgWidth = img.width;
const imgHeight = img.height;
const canvasWidth = ctx.canvas.width;
const canvasHeight = ctx.canvas.height;
const imgAspect = imgWidth / imgHeight;
const canvasAspect = canvasWidth / canvasHeight;
let x, y, width, height;
if (imgAspect > canvasAspect) {
// image is wider than canvas
width = canvasWidth;
height = width / imgAspect;
x = 0;
y = (canvasHeight - height) / 2;
} else {
// image is taller than canvas
height = canvasHeight;
width = height * imgAspect;
x = (canvasWidth - width) / 2;
y = 0;
}
ctx.drawImage(img, x, y, width, height);
};
export const canvasHasContent = canvas => {
if (canvas) {
const ctx = canvas.getContext('2d');
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
return imageData.data.some(n => n !== 0);
} else {
return true;
}
};
export const makeSquareImage = img => {
const newSize = img.width >= img.height ? img.width : img.height;
const canvas = document.createElement('canvas');
canvas.width = newSize;
canvas.height = newSize;
// get the top left color of the image
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, 1, 1, 0, 0, 1, 1);
const imageData = ctx.getImageData(0, 0, 1, 1);
// fill the canvas with the top left color
ctx.fillStyle = imageData.data[4] > 0 ?
`rgb(${imageData.data[0]}, ${imageData.data[1]}, ${imageData.data[2]})`
:
'#fff';
ctx.fillRect(0, 0, newSize, newSize);
// draw the image in the center
drawImageContain(ctx, img);
return canvas;
};
export const imageToCanvas = (img, w, h) => {
const canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext('2d');
drawImageContain(ctx, img);
return canvas;
};
export function createCanvas(width, height) {
if (isWorker) {
return new OffscreenCanvas(width, height);
} else {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
return canvas;
}
}
export const isTransferable = (o) => {
const ctor = o?.constructor;
return (
ctor === MessagePort ||
ctor === ImageBitmap ||
ctor === ImageData ||
// ctor === AudioData ||
// ctor === OffscreenCanvas ||
ctor === ArrayBuffer ||
ctor === Uint8Array ||
ctor === Int8Array ||
ctor === Uint16Array ||
ctor === Int16Array ||
ctor === Uint32Array ||
ctor === Int32Array ||
ctor === Float32Array ||
ctor === Float64Array
);
};
export const getTransferables = (o) => {
const result = [];
const _recurse = (o) => {
if (Array.isArray(o)) {
for (const e of o) {
_recurse(e);
}
} else if (o && typeof o === 'object') {
if (isTransferable(o)) {
result.push(o);
} else {
for (const k in o) {
_recurse(o[k]);
}
}
}
};
_recurse(o);
return result;
};
export const selectVoice = (voicer) => {
const weightedRandom = (weights) => {
let totalWeight = 0;
for (let i = 0; i < weights.length; i++) {
totalWeight += weights[i];
}
let random = Math.random() * totalWeight;
for (let i = 0; i < weights.length; i++) {
if (random < weights[i]) {
return i;
}
random -= weights[i];
}
return -1;
};
// the weight of each voice is proportional to the inverse of the number of times it has been used
const maxNonce = voicer.reduce((max, voice) => Math.max(max, voice.nonce), 0);
const weights = voicer.map(({nonce}) => {
return 1 - nonce / (maxNonce + 1);
});
const selectionIndex = weightedRandom(weights);
const voiceSpec = voicer[selectionIndex];
voiceSpec.nonce++;
while (voicer.every((voice) => voice.nonce > 0)) {
for (const voiceSpec of voicer) {
voiceSpec.nonce--;
}
}
return voiceSpec;
};
export const splitLinesToWidth = (() => {
let tempCanvas = null;
const _getTempCanvas = () => {
if (tempCanvas === null) {
tempCanvas = document.createElement('canvas');
tempCanvas.width = 0;
tempCanvas.height = 0;
}
return tempCanvas;
};
return (text, font, maxWidth) => {
const canvas = _getTempCanvas();
const ctx = canvas.getContext('2d');
ctx.font = font;
let lines = [];
const words = text.split(' ');
// We'll be constantly removing words from our words array to build our lines. Once we're out of words, we can stop
while (words.length > 0) {
let tmp = words[0]; // Capture the current word, in case we need to re-add it to array
let line = words.shift(); // Start our line with the first word available to us
// Now we'll continue adding words to our line until we've exceeded our budget
while (words.length && ctx.measureText(line).width < maxWidth) {
tmp = words[0];
line += ' ' + words.shift();
}
// If the line is too long, remove the last word and replace it in words array.
// This will happen on all but the last line, as we anticipate exceeding the length to break out of our second while loop
if (ctx.measureText(line).width > maxWidth) {
const lastSpaceIndex = line.lastIndexOf(' ');
if (lastSpaceIndex !== -1) {
line = line.substring(0, lastSpaceIndex);
words.unshift(tmp);
} else {
const part1 = line.substring(0, 12) + '-';
const part2 = line.substring(12);
line = part1;
words.push(part2);
}
}
// Push the finshed line into the array
lines.push(line);
}
return lines;
};
})();
export const getJsDataUrl = src => `data:application/javascript;charset=utf-8,${encodeURIComponent(src)}`
export const fetchArrayBuffer = async srcUrl => {
const res = await fetch(srcUrl);
if (res.ok) {
const arrayBuffer = await res.arrayBuffer();
return arrayBuffer;
} else {
throw new Error('failed to load: ' + res.status + ' ' + srcUrl);
}
};
export const getBoundingSize = boundingType => {
switch (boundingType) {
case 'sphere': return 4;
case 'box': return 6;
default: return 0;
}
};
export const lookAtQuaternion = (dirVec)=>{