forked from webaverse/app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
1994 lines (1828 loc) · 65.8 KB
/
game.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
/*
this file contains the main game logic tying together the managers.
general game logic goes here.
*/
import * as THREE from 'three';
// import {GLTFLoader} from 'three/examples/jsm/loaders/GLTFLoader.js';
import * as BufferGeometryUtils from 'three/examples/jsm/utils/BufferGeometryUtils.js';
import physx from './physx.js';
import cameraManager from './camera-manager.js';
// import uiManager from './ui-manager.js';
import ioManager from './io-manager.js';
// import {loginManager} from './login.js';
// import physicsManager from './physics-manager.js';
import dioramaManager from './diorama.js';
import {world} from './world.js';
import * as universe from './universe.js';
import {buildMaterial, highlightMaterial, selectMaterial, hoverMaterial, hoverEquipmentMaterial} from './shaders.js';
import {teleportMeshes} from './teleport.js';
import {getPlayerCrouchFactor} from './character-controller.js';
import {waitForLoad as rendererWaitForLoad, getRenderer, scene, sceneLowPriority, camera} from './renderer.js';
import {snapPosition} from './util.js';
import {maxGrabDistance, storageHost, minFov, maxFov} from './constants.js';
import easing from './easing.js';
import {VoicePack} from './voice-pack-voicer.js';
import {VoiceEndpoint} from './voice-endpoint-voicer.js';
import metaversefileApi from './metaversefile-api.js';
import metaversefileConstants from 'metaversefile/constants.module.js';
import * as metaverseModules from './metaverse-modules.js';
// import soundManager from './sound-manager.js';
const {contractNames} = metaversefileConstants;
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 localVector6 = new THREE.Vector3();
const localVector2D = new THREE.Vector2();
const localQuaternion = new THREE.Quaternion();
const localQuaternion2 = new THREE.Quaternion();
const localQuaternion3 = new THREE.Quaternion();
const localEuler = new THREE.Euler();
const localMatrix = new THREE.Matrix4();
const localMatrix2 = new THREE.Matrix4();
const localMatrix3 = new THREE.Matrix4();
// const localBox = new THREE.Box3();
const localRay = new THREE.Ray();
const localRaycaster = new THREE.Raycaster();
const oneVector = new THREE.Vector3(1, 1, 1);
const leftHandOffset = new THREE.Vector3(0.2, -0.2, -0.4);
const rightHandOffset = new THREE.Vector3(-0.2, -0.2, -0.4);
// const cubicBezier = easing(0, 1, 0, 1);
const _getGrabAction = i => {
const targetHand = i === 0 ? 'left' : 'right';
const localPlayer = metaversefileApi.useLocalPlayer();
const grabAction = localPlayer.findAction(action => action.type === 'grab' && action.hand === targetHand);
return grabAction;
};
const _getGrabbedObject = i => {
const grabAction = _getGrabAction(i);
const grabbedObjectInstanceId = grabAction?.instanceId;
const result = grabbedObjectInstanceId ? metaversefileApi.getAppByInstanceId(grabbedObjectInstanceId) : null;
return result;
};
// returns whether we actually snapped
function updateGrabbedObject(o, grabMatrix, offsetMatrix, {collisionEnabled, handSnapEnabled, physx, gridSnap}) {
grabMatrix.decompose(localVector, localQuaternion, localVector2);
offsetMatrix.decompose(localVector3, localQuaternion2, localVector4);
const offset = localVector3.length();
localMatrix.multiplyMatrices(grabMatrix, offsetMatrix)
.decompose(localVector5, localQuaternion3, localVector6);
/* const grabbedObject = _getGrabbedObject(0);
const grabbedPhysicsObjects = grabbedObject ? grabbedObject.getPhysicsObjects() : [];
for (const physicsObject of grabbedPhysicsObjects) {
physx.physxWorker.disableGeometryQueriesPhysics(physx.physics, physicsObject.physicsId);
} */
let collision = collisionEnabled && physx.physxWorker.raycastPhysics(physx.physics, localVector, localQuaternion);
if (collision) {
// console.log('got collision', collision);
const {point} = collision;
o.position.fromArray(point)
// .add(localVector2.set(0, 0.01, 0));
if (o.position.distanceTo(localVector) > offset) {
collision = null;
}
}
if (!collision) {
o.position.copy(localVector5);
}
/* for (const physicsObject of grabbedPhysicsObjects) {
physx.physxWorker.enableGeometryQueriesPhysics(physx.physics, physicsObject.physicsId);
} */
const handSnap = !handSnapEnabled || offset >= maxGrabDistance || !!collision;
if (handSnap) {
snapPosition(o, gridSnap);
o.quaternion.setFromEuler(o.savedRotation);
} else {
o.quaternion.copy(localQuaternion3);
}
return {
handSnap,
};
}
const _makeTargetMesh = (() => {
const targetMeshGeometry = (() => {
const targetGeometry = BufferGeometryUtils.mergeBufferGeometries([
new THREE.BoxBufferGeometry(0.03, 0.2, 0.03)
.applyMatrix4(new THREE.Matrix4().makeTranslation(0, -0.1, 0)),
new THREE.BoxBufferGeometry(0.03, 0.2, 0.03)
.applyMatrix4(new THREE.Matrix4().makeRotationFromQuaternion(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, -1, 0), new THREE.Vector3(0, 0, 1))))
.applyMatrix4(new THREE.Matrix4().makeTranslation(0, 0, 0.1)),
new THREE.BoxBufferGeometry(0.03, 0.2, 0.03)
.applyMatrix4(new THREE.Matrix4().makeRotationFromQuaternion(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, -1, 0), new THREE.Vector3(1, 0, 0))))
.applyMatrix4(new THREE.Matrix4().makeTranslation(0.1, 0, 0)),
]);
return BufferGeometryUtils.mergeBufferGeometries([
targetGeometry.clone()
.applyMatrix4(new THREE.Matrix4().makeTranslation(-0.5, 0.5, -0.5)),
targetGeometry.clone()
.applyMatrix4(new THREE.Matrix4().makeRotationFromQuaternion(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 0, -1), new THREE.Vector3(0, -1, 0))))
.applyMatrix4(new THREE.Matrix4().makeTranslation(-0.5, -0.5, -0.5)),
targetGeometry.clone()
.applyMatrix4(new THREE.Matrix4().makeRotationFromQuaternion(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), new THREE.Vector3(0, 0, 1))))
.applyMatrix4(new THREE.Matrix4().makeTranslation(-0.5, 0.5, 0.5)),
targetGeometry.clone()
.applyMatrix4(new THREE.Matrix4().makeRotationFromQuaternion(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), new THREE.Vector3(1, 0, 0))))
.applyMatrix4(new THREE.Matrix4().makeTranslation(0.5, 0.5, -0.5)),
targetGeometry.clone()
.applyMatrix4(new THREE.Matrix4().makeRotationFromQuaternion(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), new THREE.Vector3(1, 0, 0))))
.applyMatrix4(new THREE.Matrix4().makeRotationFromQuaternion(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), new THREE.Vector3(0, 0, 1))))
.applyMatrix4(new THREE.Matrix4().makeTranslation(0.5, 0.5, 0.5)),
targetGeometry.clone()
.applyMatrix4(new THREE.Matrix4().makeRotationFromQuaternion(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), new THREE.Vector3(0, 0, 1))))
.applyMatrix4(new THREE.Matrix4().makeRotationFromQuaternion(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(-1, 0, 0), new THREE.Vector3(0, -1, 0))))
.applyMatrix4(new THREE.Matrix4().makeTranslation(-0.5, -0.5, 0.5)),
targetGeometry.clone()
.applyMatrix4(new THREE.Matrix4().makeRotationFromQuaternion(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), new THREE.Vector3(1, 0, 0))))
.applyMatrix4(new THREE.Matrix4().makeRotationFromQuaternion(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(1, 0, 0), new THREE.Vector3(0, -1, 0))))
.applyMatrix4(new THREE.Matrix4().makeTranslation(0.5, -0.5, -0.5)),
targetGeometry.clone()
.applyMatrix4(new THREE.Matrix4().makeRotationFromQuaternion(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(-1, 1, 0).normalize(), new THREE.Vector3(1, 1, 0).normalize())))
.applyMatrix4(new THREE.Matrix4().makeRotationFromQuaternion(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, -1, 0).normalize(), new THREE.Vector3(0, 0, -1).normalize())))
.applyMatrix4(new THREE.Matrix4().makeRotationFromQuaternion(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(-1, 0, 0).normalize(), new THREE.Vector3(0, 1, 0).normalize())))
.applyMatrix4(new THREE.Matrix4().makeTranslation(0.5, -0.5, 0.5)),
])// .applyMatrix4(new THREE.Matrix4().makeTranslation(0, 0.5, 0));
})();
const targetVsh = `
#define M_PI 3.1415926535897932384626433832795
uniform float uTime;
// varying vec2 vUv;
void main() {
float f = 1.0 + sign(uTime) * pow(sin(abs(uTime) * M_PI), 0.5) * 0.2;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position * f, 1.);
}
`;
const targetFsh = `
uniform float uHighlight;
uniform float uTime;
const vec3 c = vec3(${new THREE.Color(0x29b6f6).toArray().join(', ')});
void main() {
float f = max(1.0 - sign(uTime) * pow(abs(uTime), 0.5), 0.1);
gl_FragColor = vec4(vec3(c * f * uHighlight), 1.0);
}
`;
return p => {
const geometry = targetMeshGeometry;
const material = new THREE.ShaderMaterial({
uniforms: {
uHighlight: {
type: 'f',
value: 0,
needsUpdate: true,
},
uTime: {
type: 'f',
value: 0,
needsUpdate: true,
},
},
vertexShader: targetVsh,
fragmentShader: targetFsh,
// transparent: true,
});
const mesh = new THREE.Mesh(geometry, material);
mesh.frustumCulled = false;
return mesh;
};
})();
const _makeHighlightPhysicsMesh = material => {
const geometry = new THREE.BoxBufferGeometry(1, 1, 1);
material = material.clone();
const mesh = new THREE.Mesh(geometry, material);
mesh.frustumCulled = false;
mesh.physicsId = 0;
return mesh;
};
/* const highlightMesh = _makeTargetMesh();
highlightMesh.visible = false;
sceneLowPriority.add(highlightMesh);
let highlightedObject = null; */
const highlightPhysicsMesh = _makeHighlightPhysicsMesh(buildMaterial);
highlightPhysicsMesh.visible = false;
sceneLowPriority.add(highlightPhysicsMesh);
let highlightedPhysicsObject = null;
let highlightedPhysicsId = 0;
const mouseHighlightPhysicsMesh = _makeHighlightPhysicsMesh(highlightMaterial);
mouseHighlightPhysicsMesh.visible = false;
sceneLowPriority.add(mouseHighlightPhysicsMesh);
let mouseHoverObject = null;
let mouseHoverPhysicsId = 0;
let mouseHoverPosition = null;
const mouseSelectPhysicsMesh = _makeHighlightPhysicsMesh(selectMaterial);
mouseSelectPhysicsMesh.visible = false;
sceneLowPriority.add(mouseSelectPhysicsMesh);
let mouseSelectedObject = null;
let mouseSelectedPhysicsId = 0;
let mouseSelectedPosition = null;
const mouseDomHoverPhysicsMesh = _makeHighlightPhysicsMesh(hoverMaterial);
mouseDomHoverPhysicsMesh.visible = false;
sceneLowPriority.add(mouseDomHoverPhysicsMesh);
let mouseDomHoverObject = null;
let mouseDomHoverPhysicsId = 0;
const mouseDomEquipmentHoverPhysicsMesh = _makeHighlightPhysicsMesh(hoverEquipmentMaterial);
mouseDomEquipmentHoverPhysicsMesh.visible = false;
sceneLowPriority.add(mouseDomEquipmentHoverPhysicsMesh);
let mouseDomEquipmentHoverObject = null;
let mouseDomEquipmentHoverPhysicsId = 0;
let selectedLoadoutIndex = -1;
let selectedLoadoutObject = null;
const _selectLoadout = index => {
if (index !== selectedLoadoutIndex) {
selectedLoadoutIndex = index;
} else {
selectedLoadoutIndex = -1;
}
};
const _use = () => {
if (gameManager.getMenu() === 3) {
const itemSpec = itemSpecs3[selectedItemIndex];
let {start_url, filename, content} = itemSpec;
if (start_url) {
// start_url = new URL(start_url, srcUrl).href;
// filename = start_url;
} else if (filename && content) {
const blob = new Blob([content], {
type: 'application/octet-stream',
});
start_url = URL.createObjectURL(blob);
start_url += '/' + filename;
}
world.appManager.addTrackedApp(start_url, null, deployMesh.position, deployMesh.quaternion, deployMesh.scale);
gameManager.setMenu(0);
cameraManager.requestPointerLock();
} else if (highlightedObject /* && !editedObject */) {
_grab(highlightedObject);
highlightedObject = null;
gameManager.setMenu(0);
cameraManager.requestPointerLock();
} else if (gameManager.getMenu() === 1) {
const itemSpec = itemSpecs1[selectedItemIndex];
itemSpec.cb();
} else if (gameManager.getMenu() === 2) {
const inventory = loginManager.getInventory();
const itemSpec = inventory[selectedItemIndex];
world.appManager.addTrackedApp(itemSpec.id, null, deployMesh.position, deployMesh.quaternion, deployMesh.scale);
gameManager.setMenu(0);
cameraManager.requestPointerLock();
}
};
const _delete = () => {
const grabbedObject = _getGrabbedObject(0);
if (grabbedObject) {
const localPlayer = metaversefileApi.useLocalPlayer();
localPlayer.ungrab();
world.appManager.removeTrackedApp(grabbedObject.instanceId);
} else if (highlightedPhysicsObject) {
world.appManager.removeTrackedApp(highlightedPhysicsObject.instanceId);
highlightedPhysicsObject = null;
} else if (mouseSelectedObject) {
world.appManager.removeTrackedApp(mouseSelectedObject.instanceId);
if (mouseHoverObject === mouseSelectedObject) {
gameManager.setMouseHoverObject(null);
}
gameManager.setMouseSelectedObject(null);
}
};
const _click = () => {
if (_getGrabbedObject(0)) {
const localPlayer = metaversefileApi.useLocalPlayer();
localPlayer.ungrab();
} else {
if (highlightedPhysicsObject) {
_grab(highlightedPhysicsObject);
}
}
};
let lastUseIndex = 0;
const _getNextUseIndex = animation => {
if (Array.isArray(animation)) {
return (lastUseIndex++) % animation.length;
} else {
return 0;
}
};
let lastPistolUseStartTime = -Infinity;
const _handleNewLocalUseAction = (app, action) => {
// console.log('got action animation', action);
if (action.ik === 'pistol') {
lastPistolUseStartTime = performance.now();
}
app.use();
};
const _startUse = () => {
const localPlayer = metaversefileApi.useLocalPlayer();
const wearApps = Array.from(localPlayer.getActionsState())
.filter(action => action.type === 'wear')
.map(({instanceId}) => metaversefileApi.getAppByInstanceId(instanceId));
for (const wearApp of wearApps) {
const useComponent = wearApp.getComponent('use');
if (useComponent) {
const useAction = localPlayer.getAction('use');
if (!useAction) {
const {instanceId} = wearApp;
const {boneAttachment, animation, ik, behavior, position, quaternion, scale} = useComponent;
const index = _getNextUseIndex(animation);
// console.log('index', index, swordTopDownSlash);
const newUseAction = {
type: 'use',
instanceId,
animation,
ik,
behavior,
boneAttachment,
index,
position,
quaternion,
scale,
};
localPlayer.addAction(newUseAction);
_handleNewLocalUseAction(wearApp, newUseAction);
}
break;
}
}
};
const _endUse = () => {
const localPlayer = metaversefileApi.useLocalPlayer();
const useAction = localPlayer.getAction('use');
if (useAction) {
const app = metaversefileApi.getAppByInstanceId(useAction.instanceId);
app.dispatchEvent({
type: 'use',
use: false,
});
localPlayer.removeAction('use');
}
};
const _mousedown = () => {
_startUse();
};
const _mouseup = () => {
_endUse();
};
const _uploadFile = async (u, f) => {
const res = await fetch(u, {
method: 'POST',
body: f,
});
const j = await res.json();
const {hash} = j;
const {name} = f;
return {
name,
hash,
};
};
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;
}
};
const _handleUpload = async (item, transform = null) => {
console.log('uploading...');
const _uploadObject = async item => {
let u;
const file = item.getAsFile();
const entry = item.webkitGetAsEntry();
if (item.kind === 'string') {
const s = await new Promise((accept, reject) => {
item.getAsString(accept);
});
const j = JSON.parse(s);
const {token_id, asset_contract} = j;
const {address} = asset_contract;
if (contractNames[address]) {
u = `/@proxy/` + encodeURI(`eth://${address}/${token_id}`);
} else {
console.log('got j', j);
const {traits} = j;
// cryptovoxels wearables
const voxTrait = traits.find(t => t.trait_type === 'vox'); // XXX move to a loader
if (voxTrait) {
const {value} = voxTrait;
u = _proxifyUrl(value) + '?type=vox';
} else {
const {token_metadata} = j;
// console.log('proxify', token_metadata);
const res = await fetch(_proxifyUrl(token_metadata), {
mode: 'cors',
});
const j2 = await res.json();
// console.log('got metadata', j2);
// dcl wearables
if (j2.id?.startsWith('urn:decentraland:')) {
// 'urn:decentraland:ethereum:collections-v1:mch_collection:mch_enemy_upper_body'
const res = await fetch(`https://peer-lb.decentraland.org/lambdas/collections/wearables?wearableId=${j2.id}`, { // XXX move to a loader
mode: 'cors',
});
const j3 = await res.json();
const {wearables} = j3;
const wearable = wearables[0];
const representation = wearable.data.representations[0];
const {mainFile, contents} = representation;
const file = contents.find(f => f.key === mainFile);
const match = mainFile.match(/\.([a-z0-9]+)$/i);
const type = match && match[1];
// console.log('got wearable', {mainFile, contents, file, type});
u = '/@proxy/' + encodeURI(file.url) + (type ? ('?type=' + type) : '');
} else {
// avatar
const {avatar_url, asset} = j2;
const avatarUrl = avatar_url || asset;
if (avatarUrl) {
u = '/@proxy/' + encodeURI(avatarUrl) + '?type=vrm';
} else {
// default
const {image} = j2;
u = '/@proxy/' + encodeURI(image);
}
}
}
}
} else if (entry.isDirectory) {
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);
console.log('file full path', entry.fullPath, rootEntry.fullPath, fullPath);
formData.append(fullPath, file, fullPath);
} else if (entry.isDirectory) {
await _recurse(entry);
}
}
}
};
await _recurse(rootEntry);
const uploadFilesRes = await fetch(`https://ipfs.webaverse.com/`, {
method: 'POST',
body: formData,
});
const hashes = await uploadFilesRes.json();
const rootDirectory = hashes.find(h => h.name === '');
const rootDirectoryHash = rootDirectory.hash;
u = `https://ipfs.webaverse.com/ipfs/${rootDirectoryHash}/`;
console.log(u);
} else {
const {name, hash} = await _uploadFile(`https://ipfs.webaverse.com/`, file);
u = `${storageHost}/${hash}/${name}`;
}
return u;
};
const u = await _uploadObject(item);
console.log('upload complete:', u);
if (!transform) {
const {leftHand: {position, quaternion}} = metaversefileApi.useLocalPlayer();
const position2 = position.clone()
.add(localVector2.set(0, 0, -1).applyQuaternion(quaternion));
const quaternion2 = quaternion.clone();
transform = {
position: position2,
quaternion: quaternion2,
};
}
const {position, quaternion} = transform;
world.appManager.addTrackedApp(u, position, quaternion, oneVector);
};
/* const bindUploadFileInput = uploadFileInput => {
bindUploadFileButton(uploadFileInput, _handleUpload);
}; */
const _upload = () => {
const uploadFileInput = document.getElementById('upload-file-input');
uploadFileInput.click();
};
const _grab = object => {
const localPlayer = metaversefileApi.useLocalPlayer();
localPlayer.grab(object);
gameManager.gridSnap = 0;
gameManager.editMode = false;
};
const hitRadius = 1;
const hitHeight = 0.2;
const hitHalfHeight = hitHeight * 0.5;
const hitboxOffsetDistance = 0.3;
const damageMeshOffsetDistance = 1.5;
/* const cylinderMesh = (() => {
const radius = 1;
const height = 0.2;
const halfHeight = height/2;
const cylinderMesh = new THREE.Mesh(
new THREE.CylinderBufferGeometry(radius, radius, height),
new THREE.MeshBasicMaterial({
color: 0x00FFFF,
})
);
cylinderMesh.radius = radius;
cylinderMesh.halfHeight = halfHeight;
return cylinderMesh;
})(); */
let grabUseMesh = null;
const _gameInit = () => {
{
grabUseMesh = metaversefileApi.createApp();
(async () => {
await metaverseModules.waitForLoad();
const {modules} = metaversefileApi.useDefaultModules();
const m = modules['button'];
await grabUseMesh.addModule(m);
})();
grabUseMesh.targetApp = null;
sceneLowPriority.add(grabUseMesh);
}
};
Promise.resolve()
.then(_gameInit);
let lastDraggingRight = false;
let dragRightSpec = null;
let fovFactor = 0;
let lastActivated = false;
let lastHitTimes = new WeakMap();
const _gameUpdate = (timestamp, timeDiff) => {
const now = timestamp;
const renderer = getRenderer();
const localPlayer = metaversefileApi.useLocalPlayer();
const _updateFakeHands = () => {
const session = renderer.xr.getSession();
if (!session) {
localMatrix.copy(localPlayer.matrixWorld)
.decompose(localVector, localQuaternion, localVector2);
const avatarHeight = localPlayer.avatar ? localPlayer.avatar.height : 0;
const handOffsetScale = localPlayer.avatar ? avatarHeight / 1.5 : 1;
{
const leftGamepadPosition = localVector2.copy(localVector)
.add(localVector3.copy(leftHandOffset).multiplyScalar(handOffsetScale).applyQuaternion(localQuaternion));
const leftGamepadQuaternion = localQuaternion;
const leftGamepadPointer = 0;
const leftGamepadGrip = 0;
const leftGamepadEnabled = false;
localPlayer.leftHand.position.copy(leftGamepadPosition);
localPlayer.leftHand.quaternion.copy(leftGamepadQuaternion);
}
{
const rightGamepadPosition = localVector2.copy(localVector)
.add(localVector3.copy(rightHandOffset).multiplyScalar(handOffsetScale).applyQuaternion(localQuaternion));
const rightGamepadQuaternion = localQuaternion;
const rightGamepadPointer = 0;
const rightGamepadGrip = 0;
const rightGamepadEnabled = false;
localPlayer.rightHand.position.copy(rightGamepadPosition);
localPlayer.rightHand.quaternion.copy(rightGamepadQuaternion);
}
if (lastPistolUseStartTime >= 0) {
const lastUseTimeDiff = timestamp - lastPistolUseStartTime;
const kickbackTime = 300;
const kickbackExponent = 0.05;
const f = Math.min(Math.max(lastUseTimeDiff / kickbackTime, 0), 1);
const v = Math.sin(Math.pow(f, kickbackExponent) * Math.PI);
const fakeArmLength = 0.2;
localQuaternion.setFromRotationMatrix(
localMatrix.lookAt(
localVector.copy(localPlayer.leftHand.position),
localVector2.copy(localPlayer.leftHand.position)
.add(
localVector3.set(0, 1, -1)
.applyQuaternion(localPlayer.leftHand.quaternion)
),
localVector3.set(0, 0, 1)
.applyQuaternion(localPlayer.leftHand.quaternion)
)
)// .multiply(localPlayer.leftHand.quaternion);
localPlayer.leftHand.position.sub(
localVector.set(0, 0, -fakeArmLength)
.applyQuaternion(localPlayer.leftHand.quaternion)
);
localPlayer.leftHand.quaternion.slerp(localQuaternion, v);
localPlayer.leftHand.position.add(
localVector.set(0, 0, -fakeArmLength)
.applyQuaternion(localPlayer.leftHand.quaternion)
);
}
}
};
_updateFakeHands();
const _handlePush = () => {
if (gameManager.canPush()) {
if (ioManager.keys.forward) {
gameManager.menuPush(-1);
} else if (ioManager.keys.backward) {
gameManager.menuPush(1);
}
}
};
_handlePush();
const _updateActivateAnimation = grabUseMeshPosition => {
let currentDistance = 100;
let currentAnimation = "grab_forward";
// Forward
{
localVector.set(0, -0.5, -0.5).applyQuaternion(localPlayer.quaternion)
.add(localPlayer.position);
const distance = grabUseMeshPosition.distanceTo(localVector);
currentDistance = distance;
}
// Down
{
localVector.set(0, -1.2, -0.5).applyQuaternion(localPlayer.quaternion)
.add(localPlayer.position);
const distance = grabUseMeshPosition.distanceTo(localVector);
if (distance < currentDistance) {
currentDistance = distance;
currentAnimation = "grab_down";
}
}
// Up
{
localVector.set(0, 0.0, -0.5).applyQuaternion(localPlayer.quaternion)
.add(localPlayer.position);
const distance = grabUseMeshPosition.distanceTo(localVector);
if (distance < currentDistance) {
currentDistance = distance;
currentAnimation = "grab_up";
}
}
// Left
{
localVector.set(-0.8, -0.5, -0.5).applyQuaternion(localPlayer.quaternion)
.add(localPlayer.position);
const distance = grabUseMeshPosition.distanceTo(localVector);
if (distance < currentDistance) {
currentDistance = distance;
currentAnimation = "grab_left";
}
}
// Right
{
localVector.set(0.8, -0.5, -0.5).applyQuaternion(localPlayer.quaternion)
.add(localPlayer.position);
const distance = grabUseMeshPosition.distanceTo(localVector);
if (distance < currentDistance) {
currentDistance = distance;
currentAnimation = "grab_right";
}
}
if (localPlayer.getAction('activate')) {
localPlayer.getAction('activate').animationName = currentAnimation;
}
// return (currentDistance < 0.8);
};
const _updateGrab = () => {
// moveMesh.visible = false;
const _isWear = o => localPlayer.findAction(action => action.type === 'wear' && action.instanceId === o.instanceId);
for (let i = 0; i < 2; i++) {
const grabAction = _getGrabAction(i);
const grabbedObject = _getGrabbedObject(i);
if (grabbedObject && !_isWear(grabbedObject)) {
const {position, quaternion} = localPlayer.hands[i];
localMatrix.compose(position, quaternion, localVector.set(1, 1, 1));
grabbedObject.updateMatrixWorld();
/* const {handSnap} = */updateGrabbedObject(grabbedObject, localMatrix, localMatrix3.fromArray(grabAction.matrix), {
collisionEnabled: true,
handSnapEnabled: true,
physx,
gridSnap: gameManager.getGridSnap(),
});
grabbedObject.updateMatrixWorld();
grabUseMesh.position.copy(camera.position)
.add(
localVector.copy(grabbedObject.position)
.sub(camera.position)
.normalize()
.multiplyScalar(3)
);
grabUseMesh.quaternion.copy(camera.quaternion);
grabUseMesh.updateMatrixWorld();
// grabUseMesh.visible = true;
grabUseMesh.targetApp = grabbedObject;
grabUseMesh.setComponent('value', localPlayer.actionInterpolants.activate.getNormalized());
}
}
grabUseMesh.visible = false;
if (!gameManager.editMode) {
const avatarHeight = localPlayer.avatar ? localPlayer.avatar.height : 0;
localVector.copy(localPlayer.position)
.add(localVector2.set(0, avatarHeight * (1 - getPlayerCrouchFactor(localPlayer)) * 0.5, -0.3).applyQuaternion(localPlayer.quaternion));
const radius = 1;
const halfHeight = 0.1;
const collision = physx.physxWorker.getCollisionObjectPhysics(physx.physics, radius, halfHeight, localVector, localPlayer.quaternion);
if (collision) {
const physicsId = collision.objectId;
const object = metaversefileApi.getAppByPhysicsId(physicsId);
const physicsObject = metaversefileApi.getPhysicsObjectByPhysicsId(physicsId);
// console.log('got object', physicsId, object);
if (object && !_isWear(object) && physicsObject) {
grabUseMesh.position.setFromMatrixPosition(physicsObject.physicsMesh.matrixWorld);
grabUseMesh.quaternion.copy(camera.quaternion);
// grabUseMesh.scale.copy(grabbedObject.scale);
grabUseMesh.updateMatrixWorld();
//grabUseMesh.visible = true;
grabUseMesh.targetApp = object;
grabUseMesh.setComponent('value', localPlayer.actionInterpolants.activate.getNormalized());
_updateActivateAnimation(grabUseMesh.position);
grabUseMesh.visible = true;
}
}
}
};
_updateGrab();
const _handlePhysicsHighlight = () => {
highlightedPhysicsObject = null;
if (gameManager.editMode) {
/* const grabbedObject = _getGrabbedObject(0);
const grabbedPhysicsIds = (grabbedObject && grabbedObject.getPhysicsIds) ? grabbedObject.getPhysicsIds() : [];
for (const physicsId of grabbedPhysicsIds) {
// physx.physxWorker.disableGeometryPhysics(physx.physics, physicsId);
physx.physxWorker.disableGeometryQueriesPhysics(physx.physics, physicsId);
} */
const {position, quaternion} = renderer.xr.getSession() ? metaversefileApi.useLocalPlayer().leftHand : camera;
const collision = physx.physxWorker.raycastPhysics(physx.physics, position, quaternion);
if (collision) {
const physicsId = collision.objectId;
highlightedPhysicsObject = metaversefileApi.getAppByPhysicsId(physicsId);
highlightedPhysicsId = physicsId;
}
/* for (const physicsId of grabbedPhysicsIds) {
// physx.physxWorker.enableGeometryPhysics(physx.physics, physicsId);
physx.physxWorker.enableGeometryQueriesPhysics(physx.physics, physicsId);
} */
}
};
_handlePhysicsHighlight();
const _updatePhysicsHighlight = () => {
highlightPhysicsMesh.visible = false;
if (highlightedPhysicsObject) {
const physicsId = highlightedPhysicsId;
highlightedPhysicsObject.updateMatrixWorld();
const physicsObject = /*window.lolPhysicsObject ||*/ metaversefileApi.getPhysicsObjectByPhysicsId(physicsId);
if (physicsObject) {
const {physicsMesh} = physicsObject;
highlightPhysicsMesh.geometry = physicsMesh.geometry;
// highlightPhysicsMesh.matrix.copy(physicsObject.matrix);
highlightPhysicsMesh.matrixWorld.copy(physicsMesh.matrixWorld)
.decompose(highlightPhysicsMesh.position, highlightPhysicsMesh.quaternion, highlightPhysicsMesh.scale);
// highlightPhysicsMesh.updateMatrixWorld();
// window.highlightPhysicsMesh = highlightPhysicsMesh;
highlightPhysicsMesh.material.uniforms.uTime.value = (now%1500)/1500;
highlightPhysicsMesh.material.uniforms.uTime.needsUpdate = true;
highlightPhysicsMesh.material.uniforms.uColor.value.setHex(buildMaterial.uniforms.uColor.value.getHex());
highlightPhysicsMesh.material.uniforms.uColor.needsUpdate = true;
highlightPhysicsMesh.visible = true;
highlightPhysicsMesh.updateMatrixWorld();
}
}
};
_updatePhysicsHighlight();
const _updateMouseHighlight = () => {
mouseHighlightPhysicsMesh.visible = false;
const h = mouseHoverObject;
if (h && !gameManager.dragging) {
const physicsId = mouseHoverPhysicsId;
const physicsObject = metaversefileApi.getPhysicsObjectByPhysicsId(physicsId);
if (physicsObject) {
const {physicsMesh} = physicsObject;
mouseHighlightPhysicsMesh.geometry = physicsMesh.geometry;
localMatrix2.copy(physicsMesh.matrixWorld)
// .premultiply(localMatrix3.copy(mouseHoverObject.matrixWorld).invert())
.decompose(mouseHighlightPhysicsMesh.position, mouseHighlightPhysicsMesh.quaternion, mouseHighlightPhysicsMesh.scale);
mouseHighlightPhysicsMesh.material.uniforms.uTime.value = (now%1500)/1500;
mouseHighlightPhysicsMesh.material.uniforms.uTime.needsUpdate = true;
mouseHighlightPhysicsMesh.visible = true;
mouseHighlightPhysicsMesh.updateMatrixWorld();
}
}
};
_updateMouseHighlight();
const _updateMouseSelect = () => {
mouseSelectPhysicsMesh.visible = false;
const o = mouseSelectedObject;
if (o) {
const physicsId = mouseSelectedPhysicsId;
const physicsObject = metaversefileApi.getPhysicsObjectByPhysicsId(physicsId);
if (physicsObject) {
const {physicsMesh} = physicsObject;
mouseSelectPhysicsMesh.geometry = physicsMesh.geometry;
// window.geometry = mouseSelectPhysicsMesh.geometry;
// update matrix
{
localMatrix2.copy(physicsMesh.matrixWorld)
// .premultiply(localMatrix3.copy(mouseSelectedObject.matrixWorld).invert())
.decompose(mouseSelectPhysicsMesh.position, mouseSelectPhysicsMesh.quaternion, mouseSelectPhysicsMesh.scale);
// console.log('decompose', mouseSelectPhysicsMesh.position.toArray().join(','), mouseSelectPhysicsMesh.quaternion.toArray().join(','), mouseSelectPhysicsMesh.scale.toArray().join(','));
// debugger;
// mouseSelectPhysicsMesh.position.set(0, 0, 0);
// mouseSelectPhysicsMesh.quaternion.identity();
// mouseSelectPhysicsMesh.scale.set(1, 1, 1);
mouseSelectPhysicsMesh.visible = true;
mouseSelectPhysicsMesh.updateMatrixWorld();
}
// update uniforms
{
mouseSelectPhysicsMesh.material.uniforms.uTime.value = (now%1500)/1500;
mouseSelectPhysicsMesh.material.uniforms.uTime.needsUpdate = true;
}
} /* else {
console.warn('no physics transform for object', o, physicsId, physicsTransform);
} */
}
};
_updateMouseSelect();
const _updateMouseDomHover = () => {
mouseDomHoverPhysicsMesh.visible = false;
if (mouseDomHoverObject && !mouseSelectedObject) {
const physicsId = mouseDomHoverPhysicsId;
const physicsObject = metaversefileApi.getPhysicsObjectByPhysicsId(physicsId);
if (physicsObject) {
const {physicsMesh} = physicsObject;
mouseDomHoverPhysicsMesh.geometry = physicsMesh.geometry;
localMatrix2.copy(physicsMesh.matrixWorld)
// .premultiply(localMatrix3.copy(mouseHoverObject.matrixWorld).invert())
.decompose(mouseDomHoverPhysicsMesh.position, mouseDomHoverPhysicsMesh.quaternion, mouseDomHoverPhysicsMesh.scale);
mouseDomHoverPhysicsMesh.material.uniforms.uTime.value = (now%1500)/1500;
mouseDomHoverPhysicsMesh.material.uniforms.uTime.needsUpdate = true;
mouseDomHoverPhysicsMesh.visible = true;
mouseDomHoverPhysicsMesh.updateMatrixWorld();
}
}
};
_updateMouseDomHover();
const _updateMouseDomEquipmentHover = () => {
mouseDomEquipmentHoverPhysicsMesh.visible = false;
if (mouseDomEquipmentHoverObject && !mouseSelectedObject) {
const physicsId = mouseDomEquipmentHoverPhysicsId;
const physicsObject = metaversefileApi.getPhysicsObjectByPhysicsId(physicsId);
if (physicsObject) {
const {physicsMesh} = physicsObject;
mouseDomEquipmentHoverPhysicsMesh.geometry = physicsMesh.geometry;
localMatrix2.copy(physicsMesh.matrixWorld)
// .premultiply(localMatrix3.copy(mouseHoverObject.matrixWorld).invert())
.decompose(mouseDomEquipmentHoverPhysicsMesh.position, mouseDomEquipmentHoverPhysicsMesh.quaternion, mouseDomEquipmentHoverPhysicsMesh.scale);
mouseDomEquipmentHoverPhysicsMesh.material.uniforms.uTime.value = (now%1500)/1500;
mouseDomEquipmentHoverPhysicsMesh.material.uniforms.uTime.needsUpdate = true;
mouseDomEquipmentHoverPhysicsMesh.visible = true;