-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
2531 lines (2161 loc) · 70.2 KB
/
app.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
const assert = require("assert"),
fs = require("fs"),
path = require("path");
//keyboard events
const keyboardEvent = require('lepikevents');
const cycle = require('cycle')
const { vec2, vec3, vec4, quat, mat2, mat2d, mat3, mat4} = require("gl-matrix")
const PNG = require("png-js");
// keep the 'ws' usage as well - coven requires this very spelling
const ws = require('ws')
const generateName = require('boring-name-generator');
let username = require('username')
const filename = path.basename(__filename)
const chroma = require("chroma-js")
const flags = require('flags')
let userSettings = JSON.parse(fs.readFileSync(path.join(__dirname, 'userData/userSettings.json')))
// temporary op spawning using keyboard input
let testOp = cycle.retrocycle(JSON.parse(fs.readFileSync(path.join(__dirname, 'developer/trainOp_for_testing.json'))));
// if user entered their name, use that, otherwise use system username
flags.defineString('username', username.sync() + '_' + generateName().dashed);
// default to running vr. if --disableVR set to true, run with mouse n keys
flags.defineBoolean('disableVR');
// default to new blank scene. if --patchFile contains the name of a file in /userData, load that file.
flags.defineString('patchFile', 'new')
flags.parse()
const nodeglpath = "../node-gles3"
const gl = require(path.join(nodeglpath, "gles3.js")),
glfw = require(path.join(nodeglpath, "glfw3.js")),
glutils = require(path.join(nodeglpath, "glutils.js"))
const componentPath = path.join(__dirname, 'Components')
// components
const Patch = require(path.join(componentPath, 'Patch/Patch.js'))
const Palette = require(path.join(componentPath, 'Palette/Palette.js'))
const Audio = require(path.join(componentPath, 'Audio/Audio.js'))
const PEER_ID = flags.get('username')
let patch = new Patch(PEER_ID, Audio)
keyboardEvent.events.on('keyDown', (data) => {
switch(data){
case "A":
patch.add('op', testOp)
break;
}
})
function prettyPrint(object){
console.log(JSON.stringify(object, null, 4))
}
let USEVR;
if(process.platform === "win32" && !flags.get('disableVR')){
USEVR = true
} else {
USEVR = false
}
// usevr if its specified on CLI & skip VR if on OSX:
console.log('using VR?', USEVR)
let vr = (USEVR) ? require(path.join(nodeglpath, "openvr.js")) : null
// const shaderpath = path.join(__dirname, "shaders")
// generate a random name for new object:
let gensym = (function() {
let nodeid = 0;
return function (prefix="node") {
//return `${prefix}_${nodeid++}_${userPose.id}`
//return `${prefix}_${nodeid++}`
return `${prefix}_${Date.now()}`
}
})();
function hashCode(str) { // java String#hashCode
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
return hash;
}
function colorFromString(str) {
return chroma.hsl(Math.abs(hashCode(str)) % 360, 0.35, 0.5).gl()
}
function opMenuColour(opCategory){
let num = hashCode(opCategory)
return chroma.hsl(Math.abs(num) % 360, 0.35, 0.5).gl()
}
function scale(t, ilo, ihi, olo, ohi) {
return (t-ilo)*(ohi-olo)/(ihi-ilo) + olo;
}
// p0, p1 are the min/max bounding points of the cube
// rayDir is assumed to be normalized to length 1
// boxPos, boxQuat, rayOrigin, rayDir are all assumed to be in world space
function intersectCube(boxPos, boxQuat, p0, p1, rayOrigin, rayDir) {
// convert ray origin/direction to object-space:
let origin = vec3.sub(vec3.create(), rayOrigin, boxPos);
glutils.quat_unrotate(origin, boxQuat, origin);
let dir = glutils.quat_unrotate(vec3.create(), boxQuat, rayDir);
// using p = origin + dir*t
// get ray `t` for each bounding plane of the cube:
let t0 = [
(p0[0]-origin[0])/dir[0],
(p0[1]-origin[1])/dir[1],
(p0[2]-origin[2])/dir[2],
];
let t1 = [
(p1[0]-origin[0])/dir[0],
(p1[1]-origin[1])/dir[1],
(p1[2]-origin[2])/dir[2],
];
// sort into first (entry) and second (exit) hits:
let tmin = vec3.min(vec3.create(), t0, t1);
let tmax = vec3.max(vec3.create(), t0, t1);
// ray is a hit if the last(furthest) entry plane is before the first(nearest) exit plane
let tentry = Math.max(tmin[0], tmin[1], tmin[2])
let texit = Math.min(tmax[0], tmax[1], tmax[2])
// hit if entry is before exit:
return [tentry <= texit && texit > 0, tentry];
}
function makeDelNodeDelta(deltas, node, path) {
for (let name of Object.keys(node)) {
if (name != "_props") {
makeDelNodeDelta(deltas, node[name], path+"."+name)
}
}
let delta = {op:"delnode", path:path}
Object.assign(delta, node._props)
deltas.push(delta)
}
////////////////////////////////////////////////////////////////
let nav = {
pos: [],
quat: []
}
const SHAPE_BOX = 0;
const SHAPE_BUTTON = 1;
const SHAPE_CYLINDER = 2;
const SHAPE_KNOB = 3;
const UI_DEFAULT_SCALE = 0.1;
const UI_DEPTH = 1/3;
const UI_NUDGE = 0.01;
const UI_SCROLL_SPEED = 1;
const UI_ROTATE_SPEED = 180;
const UI_TOUCH_DISTANCE = 0.1; // near enough to consider touch-based interaction
const UI_KNOB_ANGLE_LIMIT = Math.PI * 5./6.; // 7 o'clock through 5 o'clock
function value2angle(val) {
return scale(val, 0., 1., -UI_KNOB_ANGLE_LIMIT, UI_KNOB_ANGLE_LIMIT);
}
function angle2value(a) {
return scale(a, -UI_KNOB_ANGLE_LIMIT, UI_KNOB_ANGLE_LIMIT, 0., 1.);
}
const NEAR_CLIP = 0.01;
const FAR_CLIP = 20;
let mainScene = null
let menuScene = null
let currentScene = null
// GOT graph, local copy.
let localGraph = {
nodes: {},
arcs: []
}
let menuGraph = {
nodes: {},
arcs: []
}
let menu;
let viewmatrix = mat4.create();
let projmatrix = mat4.create();
let viewmatrix_inverse = mat4.create();
let projmatrix_inverse = mat4.create();
const renderer = {
}
let socket;
let incomingDeltas = [];
let outgoingDeltas = [];
const UI = {
keynav: {
pos: vec3.fromValues(0, 0, 1),
orient: quat.create(),
// unit vectors of orientation:
fwd: vec3.create(0, 0, -1),
strafe: vec3.create(1, 0, 0),
up: vec3.create(0, 1, 0),
azimuth: 0,
elevation: 0,
mouse: [0,0], // ndc
eyeHeight: 1.25,
fwdState: 0,
strafeState: 0,
turnState: 0,
speed: 1, // metres per second
keySpeed: 1,
patching: {
menuOpen: 0
},
handleKeys(key, down, mod) {
switch (key) {
case 87: // W
case 265: // up
this.fwdState = down ? 1 : 0; break;
case 83: // S
case 264: // down
this.fwdState = down ? -1 : 0; break;
case 68: // D
this.strafeState = down ? 1 : 0; break;
case 262: // right
this.turnState = down ? 1 : 0; break;
case 65: // A
this.strafeState = down ? -1 : 0; break;
case 263: // left
this.turnState = down ? -1 : 0; break;
}
// handle mod, e.g. shift for 'run' and ctrl for 'creep'
let shift = !!(mod % 2);
let ctrl = !!(mod % 4);
this.keySpeed = shift ? 4 : ctrl ? 1/4 : 1;
},
move(dt=1/60) {
// near plane point
let cam_near = vec3.transformMat4(vec3.create(), [this.mouse[0], this.mouse[1], -1], projmatrix_inverse);
let world_near = vec3.transformMat4(vec3.create(), cam_near, viewmatrix_inverse);
// far plane point
let cam_far = vec3.transformMat4(vec3.create(), [this.mouse[0], this.mouse[1], +1], projmatrix_inverse);
let world_far = vec3.transformMat4(vec3.create(), cam_far, viewmatrix_inverse);
let ray_dir = vec3.sub(vec3.create(), world_far, world_near);
vec3.normalize(ray_dir, ray_dir);
// compute a UI.hands[0] pos/orient/mat from the mouse & projview mat
vec3.scale(UI.hands[0].pos, ray_dir, 0.25);
vec3.add(UI.hands[0].pos, world_near, UI.hands[0].pos);
mat4.getRotation(UI.hands[0].orient, viewmatrix_inverse);
mat4.fromRotationTranslation(UI.hands[0].mat, UI.hands[0].orient, UI.hands[0].pos)
vec3.copy(UI.hands[0].dir, ray_dir)
// assign az/el for keynav:
let [az, el] = this.mouse;
// deadzone percentage, so that part of screen centre is at rest
let deadzone = 0.5;
let power = 2;
az = Math.abs(az) < 1 ? Math.sign(az) * Math.pow(Math.max(0, (Math.abs(az)-deadzone)/(1.-deadzone)), power) : 0;
el = Math.abs(el) < 1 ? Math.sign(el) * Math.pow(Math.max(0, Math.abs(el)), power) : 0;
el = Math.max(Math.min(el, 1.), -1.);
az = this.keySpeed * this.turnState;
this.azimuth += dt * az * -180;
this.elevation = el * 90;
quat.fromEuler(this.orient, this.elevation, this.azimuth, 0);
// get unit nav vectors:
vec3.transformQuat(this.fwd, [0, 0, -1], this.orient);
vec3.transformQuat(this.strafe, [1, 0, 0], this.orient);
vec3.transformQuat(this.up, [0, 1, 0], this.orient);
// compute velocity:
let fwd = vec3.scale(vec3.create(), this.fwd, this.speed * this.keySpeed * dt * this.fwdState);
let strafe = vec3.scale(vec3.create(), this.strafe, this.speed * this.keySpeed * dt * this.strafeState);
// integrate:
vec3.add(this.pos, this.pos, fwd);
vec3.add(this.pos, this.pos, strafe);
// fix eye height
this.pos[1] = this.eyeHeight;
return this;
},
updateViewMatrix(viewmatrix) {
let at = vec3.add(vec3.create(), this.pos, this.fwd);
return mat4.lookAt(viewmatrix, this.pos, at, this.up);
},
},
hmd: {
pos: [0, 1.4, 1],
orient: [0, 0, 0, 1],
mat: mat4.create(),
},
hands: [
{
name: "hand_left",
pos: [-0.5, -1, 0.5], dpos: [0,0,0],
orient: [0, 0, 0, 1],
mat: mat4.create(),
dir: vec3.fromValues(0, 0, -1),
// UI:
trigger: 0, trigger_pressed: 0,
pad_x: 0, pad_y: 0, pad_dx: 0, pad_dy: 0, pad_pressed: 0,
grip_pressed:0, menu_pressed: 0,
// state machine:
state: "default",
stateData: {},
},
{
name: "hand_right",
pos: [+0.5, -1, 0.5], dpos: [0,0,0],
orient: [0, 0, 0, 1],
mat: null,//mat4.create(),
dir: vec3.fromValues(0, 0, -1),
// UI:
trigger: 0, trigger_pressed: 0,
pad_x: 0, pad_y: 0, pad_dx: 0, pad_dy: 0, pad_pressed: 0,
grip_pressed:0, menu_pressed: 0,
// state machine:
state: "default",
stateData: {},
}
],
cables: {
arcs: [],
init(renderer, gl) {
// for temporary cables:
this.module_vao = glutils.createVao(gl, renderer.module_geom, renderer.module_program.id)
this.line_vao = glutils.createVao(gl, renderer.line_geom, renderer.line_program.id)
this.module_instances = glutils.createInstances(gl, [
{ name:"i_quat", components:4 },
{ name:"i_color", components:4 },
{ name:"i_pos", components:3 },
{ name:"i_bb0", components:3 },
{ name:"i_bb1", components:3 },
{ name:"i_value", components:1 },
{ name:"i_shape", components:1 },
{ name:"i_highlight", components:1 },
]),
this.line_instances = glutils.createInstances(gl, [
{ name:"i_color", components:4 },
{ name:"i_quat0", components:4 },
{ name:"i_quat1", components:4 },
{ name:"i_pos0", components:3 },
{ name:"i_pos1", components:3 },
]),
this.module_instances.attachTo(this.module_vao).allocate(4);
this.line_instances.attachTo(this.line_vao).allocate(2);
},
// from / to should be scene widget or a wand
// basically, all they need is an i_pos and i_quat
makeArc(from, to) {
let arc = {
from: from,
to: to,
// any other state?
}
this.arcs.push(arc);
return arc;
},
destroyArc(arc) {
const index = this.arcs.indexOf(arc);
assert(index >= 0, "attempt to destroy arc that wasn't in the list");
this.arcs.splice(index, 1)
return this;
},
updateInstances() {
this.module_instances.count = 0;
this.line_instances.count = 0;
for (let arc of this.arcs) {
let line = this.line_instances.instances[this.line_instances.count];
this.line_instances.count++;
let {from, to} = arc;
vec4.set(line.i_color, 1, 0.25, 1, 1);
quat.copy(line.i_quat0, from.i_quat)
quat.copy(line.i_quat1, to.i_quat)
vec3.copy(line.i_pos0, from.i_pos)
vec3.copy(line.i_pos1, to.i_pos)
for (let parent of [from, to]) {
let jack = this.module_instances.instances[this.module_instances.count];
this.module_instances.count++;
quat.copy(jack.i_quat, parent.i_quat)
vec3.copy(jack.i_pos, parent.i_pos)
vec4.set(jack.i_color, 0.5, 0.5, 0.5, 1)
let scale = UI_DEFAULT_SCALE
let dim = [1/4, 1/4, 1/2]
vec3.copy(jack.i_bb1, [
dim[0]*0.5*scale,
dim[1]*0.5*scale,
dim[2]*0.5*scale
])
vec3.negate(jack.i_bb0, jack.i_bb1)
jack.i_shape[0] = SHAPE_CYLINDER;
jack.i_value[0] = 0;
jack.i_highlight[0] = 1;
}
}
},
submit() {
this.module_instances.bind().submit().unbind()
this.line_instances.bind().submit().unbind()
},
draw(gl) {
renderer.module_program.begin();
renderer.module_program.uniform("u_viewmatrix", viewmatrix);
renderer.module_program.uniform("u_projmatrix", projmatrix);
this.module_vao.bind().drawInstanced(this.module_instances.count).unbind()
renderer.module_program.end();
renderer.line_program.begin();
renderer.line_program.uniform("u_viewmatrix", viewmatrix);
renderer.line_program.uniform("u_projmatrix", projmatrix);
renderer.line_program.uniform("u_stiffness", 0.5)
// consider gl.LINE_STRIP with simpler geometry
this.line_vao.bind().drawInstanced(this.line_instances.count, gl.LINES).unbind()
renderer.line_program.end();
},
},
updateStateMachines(scene) {
for (let hand of this.hands) this.updateHandStateMachine(hand, scene)
},
updateHandStateMachine(hand, mainScene) {
if (!hand.mat) return; // i.e. not tracking
let hits = rayTestModules(mainScene.module_instances, hand.pos, hand.dir)
hand.target = hits[0]
hand.line.i_len[0] = hand.target ? hand.target[1] : 1
let object, distance=Infinity;
if (hand.target) {
[object, distance] = hand.target
object.i_highlight[0] = 1
if(hand.state == "menu"){
// TODO use this to display a tooltip above the hovered op, see issue #173
// menu.getInfo(object.name)
}
if(hand.B_pressed == true){
console.log('selected op for module:', object.name)
}
}
let grip_squeeze = (hand.grip_pressed == 1); // rising edge only
// let pad_press = (hand.pad_press = 1)
switch(hand.state) {
case "menu": {
if (object && hand.trigger_pressed) {
// recurse up object parentage until we have a module:
let module = object;
while (module && !module.isModule) module = module.parent;
if (module && module.isModule) {
// add the module to patch.document
patch.add('op', module)
// exit menu:
hand.state = "default";
}
} else if (grip_squeeze) {
// exit menu for all controllers:
this.hands.forEach(hand=>{
if (hand.state == "menu") hand.state = "default";
})
}
} break;
case "dragging": {
// stick to what we picked:
if (object) object.i_highlight[0] = 0
object = hand.stateData.object
object.i_highlight[0] = 1
let oldPos = vec3.copy([], object.pos)
let oldQuat = quat.copy([], object.quat)
// use pad scroll to modify the module reel & rotate:
let v = mat4.getTranslation([0,0,0], hand.stateData.objectRelativeMat);
let q = mat4.getRotation([0,0,0,1], hand.stateData.objectRelativeMat);
v[2] = Math.min(0, v[2] - UI_SCROLL_SPEED * hand.pad_dy)
let r = quat.fromEuler([0, 0, 0, 1], 0, UI_ROTATE_SPEED*hand.pad_dx, 0)
quat.multiply(q, r, q)
mat4.fromRotationTranslation(hand.stateData.objectRelativeMat, q, v)
// apply hand pose to the dragged object:
let m = mat4.multiply(mat4.create(), hand.mat, hand.stateData.objectRelativeMat);
// handle translation and scaling ourselves so that object isn't being modified (we want the pos and quat to be written to patch.document, not directly)
// get translation of position
let newPos = [m[12], m[13], m[14]]
// get rotation of quat
let newQuat = [ 0, 0, 0, 0 ]
let scaling = [Math.hypot(m[0], m[1], m[2]), Math.hypot(m[4], m[5], m[6]), Math.hypot(m[8], m[9], m[10])]
let is1 = 1 / scaling[0];
let is2 = 1 / scaling[1];
let is3 = 1 / scaling[2];
let sm11 = m[0] * is1;
let sm12 = m[1] * is2;
let sm13 = m[2] * is3;
let sm21 = m[4] * is1;
let sm22 = m[5] * is2;
let sm23 = m[6] * is3;
let sm31 = m[8] * is1;
let sm32 = m[9] * is2;
let sm33 = m[10] * is3;
let trace = sm11 + sm22 + sm33;
let S = 0;
if (trace > 0) {
S = Math.sqrt(trace + 1.0) * 2;
newQuat[3] = 0.25 * S;
newQuat[0] = (sm23 - sm32) / S;
newQuat[1] = (sm31 - sm13) / S;
newQuat[2] = (sm12 - sm21) / S;
} else if (sm11 > sm22 && sm11 > sm33) {
S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2;
newQuat[3] = (sm23 - sm32) / S;
newQuat[0] = 0.25 * S;
newQuat[1] = (sm12 + sm21) / S;
newQuat[2] = (sm31 + sm13) / S;
} else if (sm22 > sm33) {
S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2;
newQuat[3] = (sm31 - sm13) / S;
newQuat[0] = (sm12 + sm21) / S;
newQuat[1] = 0.25 * S;
newQuat[2] = (sm23 + sm32) / S;
} else {
S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2;
newQuat[3] = (sm12 - sm21) / S;
newQuat[0] = (sm31 + sm13) / S;
newQuat[1] = (sm23 + sm32) / S;
newQuat[2] = 0.25 * S;
}
// mat4.getTranslation(object.pos, m)
// mat4.getRotation(object.quat, m)
// mat4.getTranslation(newPos, m)
// mat4.getRotation(object.quat, m)
// check for exit:
if (!hand.trigger_pressed) {
// delete?
if (object.i_pos[1] < 0) {
let objectName = object.name.split('_')[1]
patch.remove('op', objectName)
// send delete delta
// let deltas = []
// // first we need to check for arcs that reference this node:
// let pat = new RegExp(`^${object.path}(\\..*)?$`)
// for (let arc of localGraph.arcs) {
// if (pat.test(arc[0]) || pat.test(arc[1])) {
// deltas.push({op:"disconnect", paths:arc })
// }
// }
// // then remove modules; children first
// makeDelNodeDelta(deltas, object.node, object.path)
// // now send them:
// outgoingDeltas.push(deltas)
}
// release dragging:
hand.state = "default";
} else {
// send propchange data to patch
patch.update('pos', [object.path, newPos])
patch.update('quat', [object.path, newQuat])
// propchange!
// outgoingDeltas.push(
// // {
// // op:"propchange",
// // path: object.path,
// // name: "pos",
// // from: (oldPos),
// // to: object.pos
// // },
// {
// op:"propchange",
// path: object.path,
// name: "orient",
// from: (oldQuat),
// to: object.quat
// })
}
} break;
case "buttoning":
case "twiddling":
case "swinging": {
// stick to what we picked:
if (object) object.i_highlight[0] = 0
object = hand.stateData.object
object.i_highlight[0] = 1
if (hand.trigger_pressed) {
/*
project ray from hand to plane of knob to find a point 'p'
point the knob toward 'p'
that is, get relative angle in knob space from knob centre to p
(i.e. on the plane of the knob itself)
and set the value according to that angle
*/
let dir = glutils.quat_unrotate(vec3.create(), object.i_quat, hand.dir);
if (dir[2]) {
let origin = vec3.sub(vec3.create(), hand.pos, object.i_pos);
glutils.quat_unrotate(origin, object.i_quat, origin);
let t = -origin[2]/dir[2]
hand.line.i_len[0] = t
let p = vec3.create()
vec3.scale(p, dir, t)
vec3.add(p, p, origin);
// now want angle to this p:
vec2.normalize(p, p)
// angle of line to hand relative to knob face:
let angle = Math.atan2(p[0], p[1]);
let i_value = Math.min(1, Math.max(0, angle2value(angle)));
// update prop:
let props = object.node._props
let range = props.range || [0,1];
let oldval = object.value//range[0] + object.i_value[0]*(range[1]-range[0]);
let newval = range[0] + i_value*(range[1]-range[0]);
// post-processing:
if (props.type == "int") newval = Math.max(range[0], Math.floor(newval))
patch.update('param', [object, newval])
// immediate update for rendering:
object.i_value[0] = i_value;
object.value = newval;
}
} else {
hand.state = "default";
}
} break;
case "cabling": {
let {arc, cablingKind} = hand.stateData
// if object, and object is a valid target for cable
// TODO: consider allowing snap to floor to delete a cable?
let ok = object && object.cablingKind == cablingKind
if (ok) {
// a valid target for this cable
// snap jack to target
arc[cablingKind] = object;
// vec3.copy(jack.i_pos, object.i_pos)
// quat.copy(jack.i_quat, object.i_quat)
// e.g. seeking input, can cable to inlet, knob, and also a jack-inlet!
} else {
// snap jack to hand
arc[cablingKind] = hand.wand;
// vec3.copy(jack.i_pos, hand.pos)
// quat.copy(jack.i_quat, hand.orient)
}
if (!hand.trigger_pressed) {
this.cables.destroyArc(arc)
// releasing jack now:
if (ok) {
patch.add('cable', [arc.from.path, arc.to.path])
}
// now delete temporary local cable
hand.state = "default";
}
} break;
default: {
hand.state = "default"
// we are not currently performing an action;
// check for starting a new one:
if (object && hand.trigger_pressed) {
// what did we select?
switch(object.kind) {
case "knob": {
// mode depends on distance:
if (distance > UI_TOUCH_DISTANCE) {
hand.state = "swinging"
// cache initial hand & object values here
hand.stateData.object = object
} else {
hand.state = "twiddling";
// cache initial hand & object values here
hand.stateData.object = object
}
} break;
case "button": {
// can update button value immediately
// but need to go into a state that waits for release
hand.state = "buttoning"
hand.stateData.object = object
} break;
case "inlet":
case "outlet": {
// spawn a new cable
let target = object
let type = target.cablingKind;
assert(type, "nlet has no .cablingKind")
let from = (type == "from") ? target : hand.wand;
let to = (type == "to") ? target : hand.wand;
let arc = this.cables.makeArc(from, to);
// cache cabling state
hand.state = "cabling"
hand.stateData.arc = arc;
// what end of the arc this hand needs to satisfy:
hand.stateData.cablingKind = (type == "to") ? "from" : "to";
} break;
case "jack": {
// if the jack's cable was fully connected, remove it from document
let {line, parent} = object
if (line && line.name) {
let arc = line.name.split(">")
// remove cable from document
patch.remove('cable', arc)
// let delta = { op:"disconnect", paths: paths };
// outgoingDeltas.push(delta)
// get widgets this line was connected to
let {from, to} = line;
if (from == parent) {
from = hand.wand;
hand.stateData.cablingKind = "from"
} else {
to = hand.wand;
hand.stateData.cablingKind = "to"
}
// cache cabling state
hand.stateData.arc = this.cables.makeArc(from, to);
hand.state = "cabling"
}
} break;
default: {
if (object.isModule) {
// a module
hand.state = "dragging";
// cache initial hand & object transforms here
hand.stateData.object = object
let invHandMat = mat4.invert(mat4.create(), hand.mat)
// get pose of object relative to hand:
hand.stateData.objectRelativeMat = mat4.multiply(mat4.create(), invHandMat, object.mat)
}
} break;
}
} else if (grip_squeeze) {
// update menu positioning relative to user
menu.updatePosition(UI.hmd)
// rebuild the menu scene
menuScene.rebuild(menuGraph)
// call up the menu:
hand.state = "menu";
// when menu is loaded, check if the current scene does not have a speaker, if so add it now. reason is that at first I was adding a speaker on load, but most of the time the hmd was pointed down at load (off my head), and the speaker's orientation was funky. this way the speaker loads for the first time correctly
patch.ensureSpeaker(UI.hmd)
} else if(hand.pad_pressed){
}
}
}
},
init(renderer, gl) {
this.cables.init(renderer, gl)
this.ray_vao = glutils.createVao(gl, renderer.line_geom, renderer.ray_program.id)
this.ray_instances = glutils.createInstances(gl, [
{ name:"i_color", components:4 },
{ name:"i_pos", components:3 },
{ name:"i_len", components:1 },
{ name:"i_dir", components:3 },
]);
this.ray_instances.attachTo(this.ray_vao).allocate(16);
this.wand_vao = glutils.createVao(gl, renderer.wand_geom, renderer.wand_program.id)
this.wand_instances = glutils.createInstances(gl, [
{ name:"i_quat", components:4 },
{ name:"i_pos", components:3 },
]);
this.wand_instances.attachTo(this.wand_vao).allocate(16);
for (let hand of this.hands) {
let ray = this.ray_instances.instances[this.ray_instances.count];
this.ray_instances.count++;
hand.line = ray;
//vec4.set(line.i_color, 1, 1, 1, 1);
}
return this.updateInstances();
},
makeLocalCable() {
},
updateInstances() {
this.cables.updateInstances()
let i = 0;
for(; i<this.hands.length; i++) {
let hand = this.hands[i]
vec3.copy(hand.line.i_pos, hand.pos)
vec3.copy(hand.line.i_dir, hand.dir)
let wand = this.wand_instances.instances[i];
wand.name = hand.name
hand.wand = wand;
vec3.copy(wand.i_pos, hand.pos)
quat.copy(wand.i_quat, hand.orient)
}
this.wand_instances.count = i;
return this.submit()
},
submit() {
this.cables.submit();
this.ray_instances.bind().submit().unbind()
this.wand_instances.bind().submit().unbind()
return this;
},
draw(gl) {
this.cables.draw(gl);
renderer.wand_program.begin();
renderer.wand_program.uniform("u_viewmatrix", viewmatrix);
renderer.wand_program.uniform("u_projmatrix", projmatrix);
//renderer.wand_program.uniform("u_modelmatrix", hand.mat);
//renderer.wand_vao.bind().draw().unbind();
UI.wand_vao.bind().drawInstanced(UI.wand_instances.count).unbind()
renderer.wand_program.end();
renderer.ray_program.begin();
renderer.ray_program.uniform("u_viewmatrix", viewmatrix);
renderer.ray_program.uniform("u_projmatrix", projmatrix);
// consider gl.LINE_STRIP with simpler geometry
this.ray_vao.bind().drawInstanced(this.ray_instances.count, gl.LINES).unbind()
renderer.ray_program.end();
return this;
},
}
let vrdim = [4096, 4096];
// const menuModules = JSON.parse(fs.readFileSync(path.join("useful_for_2022","menu.json"), "utf-8"))
////////////////////////////////////////////////////////////////
// INIT DEPENDENT LIBRARIES:
////////////////////////////////////////////////////////////////
if (!glfw.init()) {
console.log("Failed to initialize GLFW");
process.exit(-1);
}
let version = glfw.getVersion();
console.log('glfw ' + version.major + '.' + version.minor + '.' + version.rev);
console.log('glfw version-string: ' + glfw.getVersionString());
if (USEVR) {
try{
assert(vr.connect(true), "vr failed to connect");
vr.update()
vrdim = [vr.getTextureWidth(), vr.getTextureHeight()]
} catch (e) {
console.error(e)
// graceful
vr = null;
}
}
function createSDFFont(gl, pngpath, jsonpath) {
let png = PNG.load(pngpath);
let json = JSON.parse(fs.readFileSync(jsonpath, "utf8"));
let font = {
png: png,
json: json,
texture: glutils.createPixelTexture(gl, png.width, png.height),
// add to json a quick lookup table by character:
lookup: {},
// add a quick scalar factor:
scale: 1 / json.info.size,
}
json.chars.forEach(char => {
font.lookup[char.char.toString()] = char;
// cache UVs here:
char.texCoords = vec4.set(vec4.create(),
char.x / json.common.scaleW,
char.y / json.common.scaleH,
(char.x + char.width) / json.common.scaleW,
(char.y + char.height) / json.common.scaleH
);
// cache quad bounds here:
char.quad = vec4.set(vec4.create(),
char.xoffset * font.scale,
(json.common.base - char.yoffset) * font.scale,
char.width * font.scale,
-char.height * font.scale
);
})
font.charwidth = font.lookup[" "].xadvance * font.scale;
font.charheight = font.json.common.lineHeight * font.scale;
png.decode(pixels => {
assert(pixels.length == font.texture.data.length);
font.texture.data = pixels;
font.texture.bind().submit()
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
font.texture.unbind();
})
return font;
}
function initWindow() {
// Open OpenGL window
glfw.defaultWindowHints();
glfw.windowHint(glfw.CONTEXT_VERSION_MAJOR, 3);
glfw.windowHint(glfw.CONTEXT_VERSION_MINOR, 3);
glfw.windowHint(glfw.OPENGL_FORWARD_COMPAT, 1);
glfw.windowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE);
let h = 1024;
let vraspect = vrdim[0]/vrdim[1];
if (vraspect > 1.5) vraspect /= 2;
let w = Math.floor(h * vraspect)
window = glfw.createWindow(w, h, "Test");
if (!window) {
console.log("Failed to open GLFW window");
glfw.terminate();