forked from VkumarStack/Balloon_Pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBalloon_Pop.js
1878 lines (1657 loc) · 85.9 KB
/
Balloon_Pop.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 {defs, tiny} from './examples/common.js';
import {Color_Phong_Shader, Shadow_Textured_Phong_Shader,
Depth_Texture_Shader_2D, Buffered_Texture, LIGHT_DEPTH_TEX_SIZE} from './examples/shadow-demo-shaders.js'
import { Shape_From_File } from "./examples/obj-file-demo.js"
import { Text_Line } from './examples/text-demo.js';
import {
HandLandmarker,
FilesetResolver
} from "https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.0";
let {KalmanFilter} = kalmanFilter;
const {
Vector, Vector3, vec, vec3, vec4, color, hex_color, Shader, Matrix, Mat4, Light, Shape, Material, Scene, Texture,
} = tiny;
const {Cube, Axis_Arrows, Textured_Phong, Subdivision_Sphere, Phong_Shader, Cone_Tip, Square} = defs
const white = new Material(new defs.Basic_Shader())
// Mouse movements
let dx = 0;
let dy = 0;
// Mouse sensitivity
const sensitivity = 5;
let origin = vec3(0, 0, 0); // Location of camera matrix (aka the player)
let camera_matrix = Mat4.look_at(vec3(0, 0, 0), vec3(0, 0, -1), vec3(0, 1, 0)); // Camera matrix in terms of only rotations - handle translations separately
let front = vec3(0, 0, 1); // Vector facing the direction that the player can walk in (w or s movements)
let right = vec3(1, 0, 0); // Vector facing the right of the direction that the player can walk in (d or a movements)
let pitch = 0; // Variables representing camera angle (left and right)
let yaw = 0; // Up and down
const TERRAIN_BOUNDS = vec3(100, 0, 100);
// Colors for balloons at various positions of health (by their index)
const BALLOON_HEALTH = [hex_color("#ff0000"), hex_color("#ff0000"), hex_color("#0092e3"), hex_color("#63a800"), hex_color("#ffd100"), hex_color("#FF00FF"), hex_color("#141414") ]
const WAVE_INFORMATION = [
{ balloons: [{1: 10}], balloon_speed: 0.5, spawn_interval: 3000 },
{ balloons: [{1: 10}, {2: 5}], balloon_speed: 0.6, spawn_interval: 2500 },
{ balloons: [{1: 20}, {2: 15}, {3: 5}], balloon_speed: 0.7, spawn_interval: 2000 },
{ balloons: [{1: 30}, {2: 25}, {3: 15}, {4: 5}], balloon_speed: 0.8, spawn_interval: 2000},
{ balloons: [{1: 50}, {2: 40}, {3: 40}, {4: 40}, {5: 20}], balloon_speed: 0.9, spawn_interval: 1500 },
{ balloons: [{1: 100}, {2: 80}, {3: 80}, {4: 60}, {5: 40}, {6: 30}], balloon_speed: 1, spawn_interval: 1000 },
{ balloons: [{1: 100}, {2: 100}, {3: 100}, {4: 100}, {5: 100}, {6: 100}], balloon_speed: 1.5, spawn_interval: 1000}
]
const INITIAL_POSITION = vec3(0, 0, 8)
let player; // Create player object on scene initialization to deal with collisions
// Filter for smoothing hand tracking
let previousCorrected = null;
const kFilter = new KalmanFilter({
observation: {
sensorDimension: 3,
name: 'sensor'
},
dynamic: {
name: 'constant-speed',
timeStep: 0.1,
covariance: [1, 1, 1, 0.01, 0.01, 0.01],
}
})
// Mediapipe Variables and setup
let previousPos = null
let handLandmarker = undefined;
let runningMode = "VIDEO";
let webcamRunning = false;
let activatedBefore = false;
let video = document.createElement("video")
video.autoplay = true;
const createHandLandmarker = async () => {
const vision = await FilesetResolver.forVisionTasks(
"https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.0/wasm"
);
handLandmarker = await HandLandmarker.createFromOptions(vision, {
baseOptions: {
modelAssetPath: `https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task`,
delegate: "GPU"
},
runningMode: runningMode,
numHands: 1,
min_tracking_confidence: 0.3
});
};
createHandLandmarker();
// Collision Statistics
let collisionTimes = 0
// Check if webcam access is supported.
const hasGetUserMedia = () => !!navigator.mediaDevices?.getUserMedia;
let eventToRemove = null;
// Enable the live webcam view and start detection.
function enableCam(event, shootFunction) {
if (!handLandmarker) {
console.log("Wait! objectDetector not loaded yet.");
return;
}
if (webcamRunning === true) {
webcamRunning = false;
} else {
webcamRunning = true;
}
if (eventToRemove != null)
video.removeEventListener("loadeddata", eventToRemove)
// getUsermedia parameters.
const constraints = {
video: true
};
// Activate the webcam stream.
navigator.mediaDevices.getUserMedia(constraints).then((stream) => {
video.srcObject = stream;
eventToRemove = () => predictWebcam(shootFunction)
video.addEventListener("loadeddata", eventToRemove);
});
}
function inFiringPosition(landmarks) {
// Firing position if all fingers except for index and thumb are closed
let tips = [12, 16, 20]
let mcps = [9, 13, 17]
let totalDistance = 0;
for (let i = 0; i < tips.length; i++)
{
let MCPlength = 0;
let tipLength = 0;
let tip = landmarks[0][tips[i]]
let MCP = landmarks[0][mcps[i]]
let reference = landmarks[0][0] // wrist reference
// Iterate through each x, y, z component and calculate distance
Object.keys(tip).forEach((key) => {
MCPlength += (MCP[key] - reference[key])**2
tipLength += (tip[key] - reference[key])**2
})
MCPlength = Math.sqrt(MCPlength);
tipLength = Math.sqrt(tipLength) / MCPlength;
totalDistance += tipLength
}
return totalDistance <= 4.0
}
function isFiring(landmarks) {
let thumbTip = landmarks[0][4]
let middlePIP = landmarks[0][10]
let distance = 0
Object.keys(thumbTip).forEach((key) => {
distance += (middlePIP[key] - thumbTip[key])**2
})
return distance * 100 <= 0.5
}
function isFist(landmarks) {
let thumbTip = landmarks[0][4]
let indexDIP = landmarks[0][7]
let distance = 0
Object.keys(thumbTip).forEach((key) => {
distance += (indexDIP[key] - thumbTip[key])**2
})
console.log("DISTANCE " + distance * 100)
return distance * 100 <= .8
}
function isFiringAlternate(landmarks) {
let middleFingerTip = landmarks[0][12]
let middleFingerMCP = landmarks[0][9]
let wrist = landmarks[0][0]
let MCPlength = 0;
let tipLength = 0;
Object.keys(middleFingerTip).forEach((key) => {
MCPlength += (middleFingerMCP[key] - wrist[key])**2
tipLength += (middleFingerTip[key] - wrist[key])**2
})
return Math.sqrt(tipLength) / Math.sqrt(MCPlength) <= 1.0
}
let framesHandsNotVisible = 0;
let framesInFiringPosition = 0;
let lastVideoTime = -1;
let results = undefined;
async function predictWebcam(shootFunction) {
// Now let's start detecting the stream.
if (runningMode === "IMAGE") {
runningMode = "VIDEO";
await handLandmarker.setOptions({ runningMode: "VIDEO" });
}
let startTimeMs = performance.now();
if (lastVideoTime !== video.currentTime) {
lastVideoTime = video.currentTime;
results = handLandmarker.detectForVideo(video, startTimeMs);
}
if (results.landmarks.length != 0) {
framesHandsNotVisible = 0;
const index = results.landmarks[0]["8"]
const observation = [index.x, index.y, index.z]
const predicted = kFilter.predict({
previousCorrected
});
const correctedState = kFilter.correct({
predicted,
observation
})
if (inFiringPosition(results.landmarks) && (isFiring(results.landmarks)))
{
framesInFiringPosition += 1;
if (framesInFiringPosition >= 3)
shootFunction()
}
else
{
framesInFiringPosition = 0;
}
if (previousCorrected !== null && inFiringPosition(results.landmarks))
{
dx = (correctedState.mean[0] - previousCorrected.mean[0]) * -3000
dy = (correctedState.mean[1] - previousCorrected.mean[1]) * 3000
}
else
{
dx = 0;
dy = 0;
}
previousCorrected = correctedState;
}
else
{
framesHandsNotVisible += 1;
if (framesHandsNotVisible >= 5) {
dx = 0;
dy = 0;
}
}
// Call this function again to keep predicting when the browser is ready.
if (webcamRunning === true) {
window.requestAnimationFrame(() => predictWebcam(shootFunction));
}
}
function fpsLook(radians_per_frame) {
pitch = pitch + sensitivity * dx * radians_per_frame;
// Limit how much the player can look up, as in traditional fps games
yaw = Math.max(- Math.PI / 2, Math.min(yaw + sensitivity * dy * radians_per_frame, Math.PI / 2))
camera_matrix = Mat4.identity();
camera_matrix = camera_matrix.times(Mat4.rotation(-pitch, 0, 1, 0)); // Rotate by pitch
camera_matrix = camera_matrix.times(Mat4.rotation(-yaw, 1, 0, 0)); // Rotate by yaw
// Recalculate front and right vectors every time player changes where they look so they move accordingly
front = Mat4.rotation(-pitch, 0, 1, 0).times(vec3(0, 0, 1))
front = vec3(front[0], front[1], front[2])
right = vec3(0, 1, 0).cross(front)
}
// Overriding original movement and mouse controller to create fps controller
const Movement =
class Movement extends defs.Movement_Controls {
constructor(click_handler) {
super();
this.click_handler = click_handler
}
add_mouse_controls (canvas) {
this.mouse = { "from_center": vec( 0,0 ) };
const mouse_position = (e, rect = canvas.getBoundingClientRect()) =>
vec( e.clientX - (rect.left + rect.right)/2, e.clientY - (rect.bottom + rect.top)/2 );
document.addEventListener( "mouseup", e => { this.mouse.anchor = undefined; } );
canvas.addEventListener( "mousedown", e => {
e.preventDefault(); this.mouse.anchor = mouse_position(e);
this.click_handler();
} );
canvas.addEventListener( "mousemove", e => { e.preventDefault(); this.mouse.from_center = mouse_position(e); } );
canvas.addEventListener( "mouseout", e => { if( !this.mouse.anchor ) this.mouse.from_center.scale_by(0) } );
canvas.onclick = () => canvas.requestPointerLock();
let timer;
let updatePosition = (e) => {
dx = e.movementX;
dy = e.movementY;
clearTimeout(timer);
timer = setTimeout(() => {
dx = 0;
dy = 0;
}, 50)
};
let lockChangeAlert = () => {
if (document.pointerLockElement === canvas) {
document.addEventListener("mousemove", updatePosition, false);
} else {
document.removeEventListener("mousemove", updatePosition, false);
dx = dy = 0;
}
};
document.addEventListener('pointerlockchange', lockChangeAlert, false);
}
first_person_flyaround (radians_per_frame, meters_per_frame, leeway = 70) {
// thrust contains the keyboard WASD input controls
if (this.thrust[2] !== 0 || this.thrust[0] !== 0)
{
let newOrigin;
if (this.thrust[2] !== 0) { // Forward/Backward movement (W and S)
newOrigin = origin.plus(front.times(meters_per_frame * this.thrust[2] * -1));
}
if (this.thrust[0] !== 0) { // Left and right movement (A and D)
newOrigin = origin.plus(right.times(meters_per_frame * this.thrust[0] * - 1))
}
// Checking if player is going out of bounds
newOrigin[0] = Math.max(-TERRAIN_BOUNDS[0], Math.min(newOrigin[0], TERRAIN_BOUNDS[0]))
newOrigin[2] = Math.max(-TERRAIN_BOUNDS[2], Math.min(newOrigin[2], TERRAIN_BOUNDS[2]))
// Check if player collides with anything, if they don't, then update their position but otherwise keep it the same
if (player.canMove(Mat4.translation(...newOrigin)))
origin = newOrigin;
}
}
// Overriding mouse controls here to allow for first person movement
third_person_arcball (radians_per_frame) {
fpsLook(radians_per_frame);
}
make_control_panel() {
// make_control_panel(): Sets up a panel of interactive HTML elements, including
// The facing directions are surprisingly affected by the left hand rule:
this.key_triggered_button("Forward", ["w"], () => this.thrust[2] = 1, undefined, () => this.thrust[2] = 0);
this.new_line();
this.key_triggered_button("Left", ["a"], () => this.thrust[0] = 1, undefined, () => this.thrust[0] = 0);
this.new_line();
this.key_triggered_button("Back", ["s"], () => this.thrust[2] = -1, undefined, () => this.thrust[2] = 0);
this.new_line();
this.key_triggered_button("Right", ["d"], () => this.thrust[0] = -1, undefined, () => this.thrust[0] = 0);
this.new_line();
}
display (context, graphics_state, dt= graphics_state.animation_delta_time / 1000) {
const m = this.speed_multiplier * this.meters_per_frame,
r = this.speed_multiplier * this.radians_per_frame
if (this.will_take_over_uniforms) {
this.reset ();
this.will_take_over_uniforms = false;
}
if (!this.mouse_enabled_canvases.has(context.canvas))
{
this.add_mouse_controls(context.canvas);
this.mouse_enabled_canvases.add(context.canvas);
}
this.first_person_flyaround (dt * r, dt * m);
if (!this.mouse.anchor)
this.third_person_arcball(dt * r);
}
}
// Dedicated class to describe movements of objects on scenes
// Remark: for now this is a rough prototype with NO ERROR HANDLING and optimization.
class Path {
constructor(initial_pos) {
this.intervals = [];
this.initial_pos = initial_pos;
}
// formula returns Mat4.transformation
addInterval(start, end, formula) {
this.intervals.push(new Interval(start, end, formula));
}
// For now the method assumes intervals are consecutive and sorted
pick(progress) {
let matrix = this.initial_pos;
for (let i = 0; i < this.intervals.length; i++) {
matrix = this.intervals[i].pick(progress, matrix).times(matrix);
if (progress <= this.intervals[i].end)
return matrix;
}
}
start() {
return this.intervals[0].start;
}
end() {
return this.intervals[this.intervals.length - 1].end;
}
// Higher dp guarantees higher precision
buildCluster(dp = .05, error = 0.0001) {
if (this.intervals.length == 0)
return null;
let progress = this.start();
let intervalID = 0;
let clusters = [];
let min_x = Number.POSITIVE_INFINITY,
max_x = Number.NEGATIVE_INFINITY,
min_y = Number.POSITIVE_INFINITY,
max_y = Number.NEGATIVE_INFINITY,
min_z = Number.POSITIVE_INFINITY,
max_z = Number.NEGATIVE_INFINITY;
let matrix = this.initial_pos;
while (progress + error <= this.end()) {
const temp_tran = this.intervals[intervalID].pick(progress + error, matrix);
const temp_matrix = temp_tran.times(matrix);
min_x = Math.min(min_x, temp_matrix[0][3]);
min_y = Math.min(min_y, temp_matrix[1][3]);
min_z = Math.min(min_z, temp_matrix[2][3]);
max_x = Math.max(max_x, temp_matrix[0][3]);
max_y = Math.max(max_y, temp_matrix[1][3]);
max_z = Math.max(max_z, temp_matrix[2][3]);
progress += dp;
if (progress + error > this.intervals[intervalID].end) {
intervalID += 1;
matrix = temp_tran.times(matrix); // Cache the matrix
clusters.push(new BalloonCluster([
min_x - .7, max_x + .7, min_y - .7, max_y + .7, min_z - .7, max_z + .7
]));
min_x = Number.POSITIVE_INFINITY;
max_x = Number.NEGATIVE_INFINITY;
min_y = Number.POSITIVE_INFINITY;
max_y = Number.NEGATIVE_INFINITY;
min_z = Number.POSITIVE_INFINITY;
max_z = Number.NEGATIVE_INFINITY;
}
}
return clusters;
}
}
// A subpath
class Interval {
constructor(start, end, formula) {
this.start = start;
this.end = end;
this.formula = formula;
}
pick(progress, matrix) {
if (progress < this.start)
console.error("Incorrect progress: %.3f, %.3f-%.3f", progress, this.start, this.end);
else {
const stageTime =
Math.min(this.end - this.start, progress - this.start);
const compute = this.formula(stageTime, matrix);
return compute;
}
}
}
// Objects that have a collision box should extend this class
// Matrix is the Mat4 matrix that represents the object's position, scaling, rotation, etc.
// Size is the size of the bounding box of the object, represented as a Mat4 scale only (do not rotate or translate the size matrix)
// For any object that is intended to have collision, the size matrix passed in should be adjusted
// to appropriately bound the object itself
class Collidable {
constructor(matrix, size) {
this.collidedObjects = new Set(); // Keeps track of all other objects that have collided with this object
this.matrix = matrix;
this.size = size; // Size is a scale matrix; if the bound is a box then this represents the dimensions of the box otherwise if the bound is a sphere
// it represents the radius
this.boundingBox = true; // Determines whether the bound type being used is a bounding box or a bounding sphere
this.pierceable = false // Determines whether the object can be pierced (only balloons)
this.updateBoundBox();
}
// Use this function whenever the matrix is updated since it is necessary to retranslate the bounding box
updateMatrix(newMatrix) {
this.matrix = newMatrix;
this.updateBoundBox();
}
updateBoundBox() {
this.min_x = this.matrix[0][3] - this.size[0][0];
this.max_x = this.matrix[0][3] + this.size[0][0];
this.min_y = this.matrix[1][3] - this.size[1][1];
this.max_y = this.matrix[1][3] + this.size[1][1];
this.min_z = this.matrix[2][3] - this.size[2][2];
this.max_z = this.matrix[2][3] + this.size[2][2];
}
checkCollision(other) {
collisionTimes += 1
let test;
if (this.boundingBox && other.boundingBox) // Box-Box collision
{
test = (
this.min_x <= other.max_x &&
this.max_x >= other.min_x &&
this.min_y <= other.max_y &&
this.max_y >= other.min_y &&
this.min_z <= other.max_z &&
this.max_z >= other.min_z
);
}
else if (!this.boundingBox && !other.boundingBox) // Sphere-Sphere collision
{
const distance = Math.sqrt(
(this.matrix[0][3] - other.matrix[0][3]) * (this.matrix[0][3] - other.matrix[0][3]) +
(this.matrix[1][3] - other.matrix[1][3]) * (this.matrix[1][3] - other.matrix[1][3]) +
(this.matrix[2][3] - other.matrix[2][3]) * (this.matrix[2][3] - other.matrix[2][3]));
test = distance < sphere.size[0][0] + other.size[0][0];
}
else if ((this.boundingBox && !other.boundingBox) || (!this.boundingBox && other.boundingBox)) // Sphere-Box collision
{
const box = this.boundingBox ? this : other;
const sphere = !this.boundingBox ? this : other;
// get box closest point to sphere center by clamping
const x = Math.max(box.min_x, Math.min(sphere.matrix[0][3], box.max_x));
const y = Math.max(box.min_y, Math.min(sphere.matrix[1][3], box.max_y));
const z = Math.max(box.min_z, Math.min(sphere.matrix[2][3], box.max_z));
// this is the same as isPointInsideSphere
const distance = Math.sqrt(
(x - sphere.matrix[0][3]) * (x - sphere.matrix[0][3]) +
(y - sphere.matrix[1][3]) * (y - sphere.matrix[1][3]) +
(z - sphere.matrix[2][3]) * (z - sphere.matrix[2][3]));
test = distance < sphere.size[0][0];
}
// Add the collided object to the list of collided objects (and this object to the other object's list of collided objects)
if (test) {
if (!this.collidedObjects.has(other)) {
this.collidedObjects.add(other);
other.collidedObjects.add(this);
this.handleCollision(other);
}
}
return test;
}
// If anything beyond checking whether a collision has occurred, override this method
handleCollision(other) {
}
}
// Player should only collide with nature objects (its fine if they pass through balloons)
class Player extends Collidable {
constructor(matrix, collidables) {
super(matrix, Mat4.scale(1, 1, 1))
this.collidables = collidables;
}
canMove(newPosition) {
const oldPosition = this.matrix;
this.updateMatrix(newPosition) // Update the matrix with the new position to check if the player can move
let collided = false;
this.collidables.forEach((collidable) => {
if (!collidable.passable && this.checkCollision(collidable)) {
collided = true;
}
})
if (collided) // If there was a collision, revert the player's position matrix to the previous
this.updateMatrix(oldPosition);
return !collided;
}
}
class Projectile extends Collidable {
constructor(durability, matrix, size, velocity, pitch, yaw, shape, material, shadow) {
super(matrix, size);
this.durability = durability;
this.velocity = velocity;
this.pitch = pitch;
this.yaw = yaw;
this.out_of_bounds = false;
this.shape = shape;
this.material = material;
this.shadow = shadow;
}
// There is no need to pass in collidables for projectiles because the other objects it should collide with can just check for
// collision with the projectile (instead of having every projectile check for collision with every balloon, we can just have every
// balloon check for collision with every projectile)
draw(context, program_state, dt, shadow_pass) {
const posChange = this.velocity.times(dt * -1 * 0.75);
this.updateMatrix(this.matrix.times(Mat4.translation(...posChange)))
if ((this.matrix[1][3] + this.size[1][1] <= TERRAIN_BOUNDS[1]) || (Math.abs(this.matrix[0][3] + this.size[0][0]) >= TERRAIN_BOUNDS[0]) || (Math.abs(this.matrix[2][3] + this.size[2][2]) >= TERRAIN_BOUNDS[2]))
this.out_of_bounds = true;
// No need to check collisions with the projectiles and the balloons because it is already checked by the balloons
this.shape.draw(context, program_state, this.matrix.times(Mat4.rotation(-1 * this.pitch, 0, 1, 0)).times(Mat4.rotation(-1 * this.yaw, 1, 0, 0)).times(this.size), shadow_pass ? this.material : this.shadow)
this.velocity[1] = this.velocity[1] + (9.8 * dt * 0.75)
}
}
// Clusters generation
let matrices = [
[-100.7, -94.320408, -0.7, 10.618534594585608, -0.7, 0.7],
[-95.66775, -81.84021999999997, 9.3, 10.7, -0.7, 0.7],
[
-83.15690999999998, -3.356424999999919, 9.3, 10.7,
-3.1999920102026698, 3.199973888841944,
],
[
-4.699907794741054, 46.69988392120507, 9.3, 10.7,
-25.739604294753025, 25.66014936880033,
],
[
-4.699998781059446, 21.609522329090687, 9.3, 10.7,
24.26040620567531, 75.66002161878498,
],
[20.3, 21.7, 9.3, 10.7, 74.28086134350032, 85.62312134350042],
[
-69.67243200000088, 21.670167999999318, 9.3, 10.7,
83.26019702864511, 86.66018525678675,
],
[-69.7, -68.3, 9.3, 10.7, 85.14988886803475, 96.49405286803527],
[
-69.64838399999861, 91.68417600000141, 9.3, 10.7, 94.11109684383285,
97.51108836709231,
],
[
90.3, 91.7, 7.300026230675379, 12.699999999945643,
-94.3612157858916, 95.46632021410906,
],
[
90.32259600000104, 96.6935760000007, -0.6698797261497436,
10.704236549277036, -94.38279978588952, -92.98279978588951,
],
];
// Auxillary Class to optimize Collisions
class BalloonCluster extends Collidable {
static clusters = [
new BalloonCluster(matrices[0]),
new BalloonCluster(matrices[1]),
new BalloonCluster(matrices[2]),
new BalloonCluster(matrices[3]),
new BalloonCluster(matrices[4]),
new BalloonCluster(matrices[5]),
new BalloonCluster(matrices[6]),
new BalloonCluster(matrices[7]),
new BalloonCluster(matrices[8]),
new BalloonCluster(matrices[9]),
new BalloonCluster(matrices[10]),
];
static progressLookup(progress) {
for (let i = 0; i < this.path.intervals.length; i++) {
const interval = this.path.intervals[i];
if (progress >= interval.start && progress <= interval.end)
return this.clusters[i];
}
// If progress is larger than path.end(), it should have reanched the end
}
static setClusters(path) {
this.path = path;
this.clusters = path.buildCluster();
}
constructor(matrix, collidables=[]) {
super(matrix, 0);
this.balloons = new Set()
this.collidables = collidables;
this.updateBoundBox();
}
updateBoundBox() {
this.min_x = this.matrix[0];
this.max_x = this.matrix[1];
this.min_y = this.matrix[2];
this.max_y = this.matrix[3];
this.min_z = this.matrix[4];
this.max_z = this.matrix[5];
}
addChild(child) {
this.balloons.add(child);
}
updateCollidables(collidables) {
this.collidables = collidables
}
checkCollisions() {
this.collidables.forEach((collidable) => {
this.checkCollision(collidable);
});
}
checkCollision(other) {
// Check for collision with any projectiles
let test = false;
test = super.checkCollision(other);
// Test balloons boxes if hit
if (test) {
this.balloons.forEach((balloon) => {
balloon.checkCollision(other);
});
}
}
clear() {
// Clear the current array
this.balloons.length = 0;
}
}
class Balloon extends Collidable {
constructor(size, initial_pos, durability, speed, shape, material, shadow)
{
super(Mat4.identity(), size);
this.originalHealth = durability;
this.durability = durability;
this.speed = speed;
this.pierceable = true;
this.reachedEnd = false;
this.initial_pos = initial_pos;
this.boundingBox = false; // Sphere bound
this.shape = shape;
this.material = material;
this.shadow = shadow;
// Balloons will follow a fixed path, and how exactly it moves on this path will be based on this progress range
this.progress = 0;
// Update Path
const stage1 = (stageTime, matrix) =>
Mat4.translation(stageTime, (stageTime * stageTime * 10) / 25, 0);
const stage2 = (stageTime, matrix) =>
Mat4.translation(2.5 * stageTime, 0, 0);
const stage3 = (stageTime, matrix) =>
Mat4.translation(2.5 * stageTime, 0, 2.5 * Math.sin(stageTime));
const stage4 = (stageTime, matrix) => {
let n_stageTime = stageTime * (Math.PI * 3 / 2 / (60 - 41.4));
return Mat4.translation(matrix[0][3] + 25, matrix[1][3], matrix[2][3]).times(Mat4.rotation(-n_stageTime, 0, 1, 0))
.times(
Mat4.translation(
-(matrix[0][3] + 25),
-matrix[1][3],
-matrix[2][3]
)
);
}
const stage5 = (stageTime, matrix) => {
let n_stageTime = stageTime * (Math.PI / (80 - 60));
return Mat4.translation(matrix[0][3], matrix[1][3], matrix[2][3] + 25)
.times(Mat4.rotation(n_stageTime, 0, 1, 0))
.times(
Mat4.translation(
-matrix[0][3],
-matrix[1][3],
-(matrix[2][3] + 25)
)
);
}
const stage6 = (stageTime, matrix) =>
Mat4.translation(0, 0, stageTime * 2);
const stage7 = (stageTime, matrix) =>
Mat4.translation(-stageTime * 2, 0, Math.sin(stageTime));
const stage8 = (stageTime, matrix) =>
Mat4.translation(0, 0, stageTime * 2);
const stage9 = (stageTime, matrix) =>
Mat4.translation(stageTime * 2, 0, Math.sin(stageTime));
const stage10 = (stageTime, matrix) =>
Mat4.translation(0, 2 * Math.sin(stageTime), -2 * stageTime);
const stage11 = (stageTime, matrix) =>
Mat4.translation(
stageTime,
(-stageTime * stageTime * 10) / 25,
0
);
this.path = new Path(this.initial_pos);
this.path.addInterval(0, 5, stage1);
this.path.addInterval(5, 10, stage2);
this.path.addInterval(10, 41.4, stage3);
this.path.addInterval(41.4, 60, stage4);
this.path.addInterval(60, 80, stage5);
this.path.addInterval(80, 85, stage6);
this.path.addInterval(85, 130, stage7);
this.path.addInterval(130, 135, stage8);
this.path.addInterval(135, 207.5, stage9);
this.path.addInterval(207.5, 301.75, stage10);
this.path.addInterval(301.75, 306.75, stage11);
BalloonCluster.setClusters(this.path);
}
draw(context, program_state, dt, collidables, shadow_pass)
{
this.progress += dt * this.speed;
// Stages represent its stages of motion - i.e. parabolic, sinusoidal, circular, etc.
if (this.progress + 0.001 > this.path.end()) {
this.reachedEnd = true;
}
if (!this.reachedEnd) {
const matrix = this.path.pick(this.progress);
this.updateMatrix(matrix);
// Add to Balloon Clusters
BalloonCluster.progressLookup(this.progress).addChild(this);
}
this.shape.draw(context, program_state, this.matrix.times(this.size), shadow_pass ? this.material.override(BALLOON_HEALTH[this.durability]) : this.shadow)
}
handleCollision(projectile) {
const numPierces = Math.min(this.durability, projectile.durability)
projectile.durability -= numPierces;
this.durability -= numPierces;
}
}
class Nature extends Collidable {
constructor(matrix, size, shape, material, shadow, boundOffset = Mat4.identity(), passable = false)
{
super(matrix, size);
this.shape = shape;
this.material = material;
this.shadow = shadow;
this.boundOffset = boundOffset;
this.passable = passable;
this.updateBoundBox()
}
updateBoundBox() {
if (this.boundOffset)
{
this.min_x = this.matrix[0][3] - this.size[0][0] - (this.boundOffset[0][3] * this.size[0][0]);
this.max_x = this.matrix[0][3] + this.size[0][0] - (this.boundOffset[0][3] * this.size[0][0]);
this.min_y = this.matrix[1][3] - this.size[1][1] - (this.boundOffset[1][3] * this.size[1][1]);
this.max_y = this.matrix[1][3] + this.size[1][1] - (this.boundOffset[1][3] * this.size[1][1]);
this.min_z = this.matrix[2][3] - this.size[2][2] - (this.boundOffset[2][3] * this.size[2][2]);
this.max_z = this.matrix[2][3] + this.size[2][2] - (this.boundOffset[2][3] * this.size[2][2]);
}
}
// Check for collision with projectiles
draw(context, program_state, collidables, shadow_pass, boundBox = null, boundBoxMaterial = null)
{
if (boundBox !== null)
{
boundBox.draw(context, program_state, Mat4.translation((this.min_x + this.max_x) / 2, (this.min_y + this.max_y) / 2, (this.min_z + this.max_z) / 2).times(this.size), white, "LINES")
}
if (!this.passable)
{
// Check the collision to update the collided object index for darts
collidables.forEach((collidable) => {
this.checkCollision(collidable);
});
}
this.shape.draw(context, program_state, this.matrix, shadow_pass ? this.material : this.shadow)
}
handleCollision(projectile) {
projectile.durability = 0;
}
}
function drawTerrain(context, program_state, shape, material) {
// Have the terrain by a large cube with its top face being stood on
shape.draw(context, program_state, Mat4.translation(0, -2, 0).times(Mat4.scale(100, 1, 100)), material);
}
function drawSkybox(context, program_state, shape, materials, shadow_pass) {
if (shadow_pass)
{
shape.draw(context, program_state, Mat4.translation(0, 100, 0).times(Mat4.scale(100, 1, 100)).times(Mat4.rotation(Math.PI / 2, 1, 0 ,0)), materials[0])
shape.draw(context, program_state, Mat4.translation(0, 0, -100).times(Mat4.scale(100, 100, 1)), materials[1])
shape.draw(context, program_state, Mat4.translation(-100, 0, 0).times(Mat4.rotation(Math.PI / 2, 0, 1, 0)).times(Mat4.scale(100, 100, 1)), materials[2])
shape.draw(context, program_state, Mat4.translation(100, 0, 0).times(Mat4.rotation(-Math.PI / 2, 0, 1, 0)).times(Mat4.scale(100, 100, 1)), materials[3])
shape.draw(context, program_state, Mat4.translation(0, 0, 100).times(Mat4.scale(100, 100, 1)).times(Mat4.rotation(Math.PI, 0, 1, 0)), materials[4])
}
}
function drawWall(context, program_state, shape,wallMaterial) {
shape.draw(context, program_state, Mat4.translation(0, -0.2, -100).times(Mat4.scale(100, 10, 1)), wallMaterial); // Front wall
shape.draw(context, program_state, Mat4.translation(0, -0.2, 100).times(Mat4.scale(100, 10, 1)), wallMaterial); // Back wall
shape.draw(context, program_state, Mat4.translation(-100, -0.2, 0).times(Mat4.scale(1, 10, 100)), wallMaterial); // left wall
shape.draw(context, program_state, Mat4.translation(100, -0.2, 0).times(Mat4.scale(1, 10, 100)), wallMaterial); // right wall
}
// Debugging
class Cube_Outline extends Shape {
constructor() {
super("position", "color");
// TODO (Requirement 5).
// When a set of lines is used in graphics, you should think of the list entries as
// broken down into pairs; each pair of vertices will be drawn as a line segment.
// Note: since the outline is rendered with Basic_shader, you need to redefine the position and color of each vertex
const white = color(1, 1, 1, 1);
this.arrays.position = Vector3.cast(
[1, -1, 1], [1, -1, -1], [1, -1, 1], [-1, -1, 1], [-1, -1, 1], [-1, -1, -1], [-1, -1, -1], [1, -1, -1], // bottom vertices
[1, 1, 1], [1, 1, -1], [1, 1, 1], [-1, 1, 1], [-1, 1, 1], [-1, 1, -1], [-1, 1, -1], [1, 1, -1], // top vertices
[1, -1, 1], [1, 1, 1], [1, -1, -1], [1, 1, -1], [-1, -1, 1], [-1, 1, 1], [-1, -1, -1], [-1, 1, -1] // bottom-top connection vertices
);
for (let i = 0; i < this.arrays.position.length; i++) {
this.arrays.color.push(white);
}
this.indices = false;
}
}
class ZoomedOutTextureCube extends Cube {
constructor() {
super(); // Call the constructor of the Cube class
this.arrays.texture_coord = [
...this.arrays.texture_coord.map(coord => vec(coord[0] *20, coord[1] *2))
];
}
}
export class Balloon_Pop extends Scene {
constructor() {
super();
this.shapes = {
projectile: new defs.Cone_Tip(5, 5),
sphere: new Subdivision_Sphere(4),
healthBall : new Subdivision_Sphere(4),
bounding_box: new Cube_Outline(),
ground: new Cube(),
zoomedSquare : new ZoomedOutTextureCube(),
axis: new Axis_Arrows(),
square: new Square(),
tree: new Shape_From_File("assets/CommonTree_1.obj"),
tree2: new Shape_From_File("assets/CommonTree_2.obj"),
tree3: new Shape_From_File("assets/CommonTree_3.obj"),
tree4: new Shape_From_File("assets/CommonTree_4.obj"),
tree5: new Shape_From_File("assets/CommonTree_5.obj"),
willow: new Shape_From_File("assets/Willow_5.obj"),
birch: new Shape_From_File("assets/BirchTree_2.obj"),
rock: new Shape_From_File("assets/Rock_3.obj"),
log: new Shape_From_File("assets/WoodLog.obj"),
flower: new Shape_From_File("assets/Plant_1.obj"),
flower2: new Shape_From_File("assets/Plant_2.obj"),
bush: new Shape_From_File("assets/Bush_2.obj"),
castle: new Shape_From_File("assets/Castle_Tower.obj"),
health: new Text_Line(12),
money: new Text_Line(15),
round: new Text_Line(20),
powerup_pierce: new Text_Line(50),
pierce_price: new Text_Line(50),
powerup_speed: new Text_Line(50),
speed_price: new Text_Line(50),
powerup_throw: new Text_Line(50),
throw_price: new Text_Line(50),
powerup_multishot: new Text_Line(50),
game_complete: new Text_Line(50),
crosshair: new Text_Line(1),
}
// this.wallDimensions = [10, 10, 10];
this.materials = {
balloon: new Material(new Phong_Shader(), {
color: hex_color("#0000FF"), ambient: 0.8, diffusivity: 0.5, specularity: 0.8
}),
bound_box: new Material(new Phong_Shader(), {
color: hex_color("#FFFFFF", 0.1), ambient: 1.0, diffusivity: 1.0,
}),
terrain: new Material(new Shadow_Textured_Phong_Shader(1), {
color: hex_color("#009a17"), ambient: .3, diffusivity: 0.6, specularity: 0, smoothness: 64,
color_texture: null,
light_depth_texture: null
}),
pure: new Material(new Color_Phong_Shader(), {
color: hex_color("#0000FF"), ambient: 1.0, diffusivity: 1.0,
}),