-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcannonWebGL.html
More file actions
1642 lines (1414 loc) · 68.4 KB
/
cannonWebGL.html
File metadata and controls
1642 lines (1414 loc) · 68.4 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cannon Game (WebGL)</title>
<style>
/* Basic reset and font */
body {
margin: 0;
padding: 0;
font-family: "Inter", sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
background-color: #f0f4f8; /* Light background for the page */
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-height: 100vh;
overflow: hidden; /* Prevent body scroll bars */
color: #333;
}
/* Main container for the game and controls */
.game-container {
position: relative;
width: 95%; /* Responsive width */
max-width: 900px; /* Max width for larger screens */
background-color: #ffffff;
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
padding: 20px;
display: flex; /* Use flexbox for layout */
flex-direction: column; /* Default to column for small screens */
align-items: center;
gap: 20px; /* Space between canvas and controls */
}
@media (min-width: 768px) { /* For larger screens, arrange side-by-side */
.game-container {
flex-direction: row;
justify-content: center;
align-items: flex-start; /* Align items to the top */
}
}
h1 {
font-size: 2.25rem; /* 36px */
font-weight: 700; /* bold */
margin-bottom: 1.5rem; /* 24px */
color: #2d3748; /* gray-800 */
}
canvas {
background-color: transparent; /* Background will be drawn by JS */
display: block;
border-radius: 10px; /* Rounded corners for the canvas */
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* Subtle shadow for canvas */
width: 100%; /* Make canvas fill its container width */
max-width: 600px; /* Max width for canvas */
aspect-ratio: 1 / 1; /* Maintain 1:1 aspect ratio */
}
@media (min-width: 768px) {
canvas {
width: calc(100% - 250px); /* Adjust width to make space for settings */
}
}
/* Message box for audio prompt */
#messageBox {
position: absolute;
inset: 0; /* Cover the entire parent */
background-color: rgba(0, 0, 0, 0.75);
display: flex;
align-items: center;
justify-content: center;
border-radius: 10px;
z-index: 10; /* Ensure it's on top */
text-align: center;
}
#messageBox p {
color: #ffffff;
font-size: 1.25rem; /* 20px */
font-weight: 600; /* semibold */
padding: 1rem; /* 16px */
border-radius: 6px;
background-color: #4a5568; /* gray-700 */
}
/* Settings controls */
.settings-container {
width: 100%;
max-width: 220px; /* Max width for settings column */
display: flex;
flex-direction: column;
gap: 15px;
padding-top: 10px;
padding-left: 10px; /* Add some padding if next to canvas */
}
.setting-item {
display: flex;
flex-direction: column;
align-items: flex-start;
width: 100%;
}
.setting-item label {
font-size: 1rem;
font-weight: 500;
margin-bottom: 5px;
display: flex;
align-items: center;
gap: 8px;
}
.setting-item input[type="range"] {
width: 100%;
-webkit-appearance: none; /* Remove default slider styles */
height: 8px;
background: #d1d5db; /* light gray */
border-radius: 5px;
outline: none;
opacity: 0.7;
transition: opacity .2s;
}
.setting-item input[type="range"]:hover {
opacity: 1;
}
.setting-item input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 20px;
height: 20px;
border-radius: 50%;
background: #4f46e5; /* indigo-600 */
cursor: pointer;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.setting-item input[type="range"]::-moz-range-thumb {
width: 20px;
height: 20px;
border-radius: 50%;
background: #4f46e5; /* indigo-600 */
cursor: pointer;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.setting-item span {
font-size: 0.9rem;
color: #6b7280; /* gray-500 */
margin-top: 5px;
}
.setting-item input[type="checkbox"] {
width: 18px;
height: 18px;
cursor: pointer;
accent-color: #4f46e5; /* indigo-600 */
}
.action-button {
background-color: #ef4444; /* Red color for delete */
color: white;
padding: 10px 15px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 1rem;
font-weight: 600;
transition: background-color 0.2s ease;
width: 100%;
margin-top: 10px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.action-button:hover {
background-color: #dc2626; /* Darker red on hover */
}
</style>
</head>
<body>
<h1>Cannon Game (WebGL)</h1>
<div class="game-container">
<canvas id="gameCanvas"></canvas>
<div id="messageBox" style="display: none;">
<p>Please click anywhere to start the game and enable sound!</p>
</div>
<div class="settings-container">
<div class="setting-item">
<label for="muteAudioToggle">
<input type="checkbox" id="muteAudioToggle">
Mute Audio
</label>
</div>
<div class="setting-item">
<label for="shotPowerSlider">Shot Power:</label>
<input type="range" id="shotPowerSlider" min="1" max="20" value="6.5" step="0.5">
<span id="shotPowerValue">6.5</span>
</div>
<div class="setting-item">
<label for="fireRateSlider">Fire Rate:</label>
<input type="range" id="fireRateSlider" min="100" max="2000" value="200" step="100">
<span id="fireRateValue">0.2 sec</span>
</div>
<div class="setting-item">
<label for="gravitySlider">Gravity:</label>
<input type="range" id="gravitySlider" min="0.01" max="0.2" value="0.05" step="0.01">
<span id="gravityValue">0.05</span>
</div>
<div class="setting-item">
<label for="mortarToggle">
<input type="checkbox" id="mortarToggle" checked>
Mortars
</label>
</div>
<div class="setting-item">
<label for="bombToggle">
<input type="checkbox" id="bombToggle">
Bombs
</label>
</div>
<div class="setting-item">
<label for="darkModeToggle">
<input type="checkbox" id="darkModeToggle">
Dark Mode
</label>
</div>
<button id="restartBtn" class="action-button">Restart</button>
</div>
</div>
<script>
const canvas = document.getElementById("gameCanvas");
let gl = canvas.getContext("webgl"); // Get WebGL context
const messageBox = document.getElementById("messageBox");
// Settings elements
const muteAudioToggle = document.getElementById("muteAudioToggle");
const shotPowerSlider = document.getElementById("shotPowerSlider");
const shotPowerValueSpan = document.getElementById("shotPowerValue");
const fireRateSlider = document.getElementById("fireRateSlider");
const fireRateValueSpan = document.getElementById("fireRateValue");
const gravitySlider = document.getElementById("gravitySlider");
const gravityValueSpan = document.getElementById("gravityValue");
const mortarToggle = document.getElementById("mortarToggle");
const bombToggle = document.getElementById("bombToggle");
const darkModeToggle = document.getElementById("darkModeToggle");
const restartBtn = document.getElementById("restartBtn");
// Game State Variables
let mousePos = null;
let angle = null;
let canShoot = true;
let shotPower = parseFloat(shotPowerSlider.value);
let gravityValue = parseFloat(gravitySlider.value);
let fireRateDelay = parseInt(fireRateSlider.value); // Milliseconds
let isMuted = muteAudioToggle.checked;
let isMortarMode = mortarToggle.checked;
let isBombMode = bombToggle.checked;
let isDarkMode = darkModeToggle.checked;
// Cannon movement
let cannonMoveSpeed = 5; // Pixels per frame
let keysPressed = {}; // To track multiple key presses
// Arrays for game objects
let cannonBalls = [];
let explosionPieces = [];
// --- Performance Optimization ---
const MAX_EXPLOSION_PIECES = 500; // Limit the total number of explosion pieces
// --- Web Audio API for Sound Effects ---
let audioContext;
let cannonOscillator;
let cannonGain;
let collisionOscillator1, collisionOscillator2;
let collisionGain;
let explosionOscillator;
let explosionGain;
let sizzleNoiseBuffer; // For bomb fuse sizzle (reusable buffer)
let sizzleFilter;
let sizzleGain;
let sizzleBufferSource = null; // To control start/stop of sizzle
/**
* Initializes the Web Audio API context and nodes.
* This must be called after a user gesture.
*/
function initializeAudio() {
if (!audioContext) {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
// Cannon Sound (low tone beep)
cannonOscillator = audioContext.createOscillator();
cannonOscillator.type = 'sine';
cannonOscillator.frequency.setValueAtTime(100, audioContext.currentTime);
cannonOscillator.start();
cannonGain = audioContext.createGain();
cannonGain.gain.setValueAtTime(0, audioContext.currentTime);
cannonOscillator.connect(cannonGain);
cannonGain.connect(audioContext.destination);
// Collision Sound (metallic percussive)
collisionOscillator1 = audioContext.createOscillator();
collisionOscillator1.type = 'triangle';
collisionOscillator1.frequency.setValueAtTime(200, audioContext.currentTime);
collisionOscillator1.start();
collisionOscillator2 = audioContext.createOscillator();
collisionOscillator2.type = 'square';
collisionOscillator2.frequency.setValueAtTime(400, audioContext.currentTime);
collisionOscillator2.start();
collisionGain = audioContext.createGain();
collisionGain.gain.setValueAtTime(0, audioContext.currentTime);
collisionOscillator1.connect(collisionGain);
collisionOscillator2.connect(collisionGain);
collisionGain.connect(audioContext.destination);
// Explosion Sound (short, noisy burst)
explosionOscillator = audioContext.createOscillator();
explosionOscillator.type = 'sawtooth';
explosionOscillator.frequency.setValueAtTime(60, audioContext.currentTime);
explosionOscillator.start();
explosionGain = audioContext.createGain();
explosionGain.gain.setValueAtTime(0, audioContext.currentTime);
explosionOscillator.connect(explosionGain);
explosionGain.connect(audioContext.destination);
// Sizzling Fuse Sound (white noise through bandpass filter)
// Create a reusable noise buffer
const bufferSize = audioContext.sampleRate * 0.5; // 0.5 seconds of noise
sizzleNoiseBuffer = audioContext.createBuffer(1, bufferSize, audioContext.sampleRate);
const output = sizzleNoiseBuffer.getChannelData(0);
for (let i = 0; i < bufferSize; i++) {
output[i] = Math.random() * 2 - 1; // White noise
}
sizzleFilter = audioContext.createBiquadFilter();
sizzleFilter.type = 'bandpass';
sizzleFilter.frequency.setValueAtTime(8000, audioContext.currentTime);
sizzleFilter.Q.setValueAtTime(1, audioContext.currentTime);
sizzleGain = audioContext.createGain();
sizzleGain.gain.setValueAtTime(0, audioContext.currentTime);
sizzleGain.connect(audioContext.destination);
isAudioInitialized = true;
messageBox.style.display = 'none'; // Hide message box
}
}
/**
* Plays the cannon firing sound.
*/
function playCannonSound() {
if (!isAudioInitialized || isMuted) return;
const now = audioContext.currentTime;
cannonGain.gain.cancelScheduledValues(now);
cannonGain.gain.setValueAtTime(0.5, now);
cannonGain.gain.exponentialRampToValueAtTime(0.001, now + 0.3);
}
/**
* Plays the collision sound.
*/
function playCollisionSound() {
if (!isAudioInitialized || isMuted) return;
const now = audioContext.currentTime;
collisionGain.gain.cancelScheduledValues(now);
collisionGain.gain.setValueAtTime(0.3, now);
collisionGain.gain.exponentialRampToValueAtTime(0.001, now + 0.1);
}
/**
* Plays the explosion sound.
*/
function playExplosionSound() {
if (!isAudioInitialized || isMuted) return;
const now = audioContext.currentTime;
explosionGain.gain.cancelScheduledValues(now);
explosionGain.gain.setValueAtTime(0.8, now); // Louder for explosion
explosionGain.gain.exponentialRampToValueAtTime(0.001, now + 0.5); // Slightly longer decay
}
/**
* Starts the sizzling fuse sound for a bomb.
* @param {number} duration - The duration over which the sizzle should fade out.
*/
function startSizzleSound(duration) {
if (!isAudioInitialized || isMuted) return;
// Stop any existing sizzle sound before starting a new one
if (sizzleBufferSource) {
try {
sizzleBufferSource.stop();
sizzleBufferSource.disconnect();
} catch (e) {
// Already stopped or disconnected
}
}
sizzleBufferSource = audioContext.createBufferSource();
sizzleBufferSource.buffer = sizzleNoiseBuffer; // Use the pre-generated buffer
sizzleBufferSource.loop = true;
sizzleBufferSource.connect(sizzleFilter);
sizzleFilter.connect(sizzleGain); // Connect filter to gain
sizzleBufferSource.start();
const now = audioContext.currentTime;
sizzleGain.gain.cancelScheduledValues(now);
sizzleGain.gain.setValueAtTime(0.4, now); // Start loud
sizzleGain.gain.linearRampToValueAtTime(0.001, now + duration); // Fade out over bomb duration
// Stop the buffer source after the duration + a small buffer
sizzleBufferSource.stop(now + duration + 0.1);
}
// Show message box until user interacts to enable audio
messageBox.style.display = 'flex';
document.body.addEventListener('click', initializeAudio, { once: true });
// --- WebGL Setup ---
let shaderProgram;
let positionBuffer;
let colorBuffer;
let u_resolution;
let u_transformMatrix;
// Vertex shader program
const vsSource = `
attribute vec2 a_position;
attribute vec4 a_color;
uniform vec2 u_resolution;
uniform mat3 u_transformMatrix; // 3x3 matrix for 2D transformations
varying vec4 v_color;
void main() {
// Apply transformation matrix
vec3 transformedPosition = u_transformMatrix * vec3(a_position, 1.0);
// convert the rectangle from pixels to clip space
vec2 clipSpace = ((transformedPosition.xy / u_resolution) * 2.0) - 1.0;
gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); // Flip Y
v_color = a_color;
}
`;
// Fragment shader program
const fsSource = `
precision mediump float;
varying vec4 v_color;
void main() {
gl_FragColor = v_color;
}
`;
/**
* Initializes a shader program, so WebGL knows how to draw our data.
* @param {WebGLRenderingContext} gl The WebGL rendering context.
* @param {string} vsSource The vertex shader source code.
* @param {string} fsSource The fragment shader source code.
* @returns {WebGLProgram} The compiled and linked shader program.
*/
function initShaderProgram(gl, vsSource, fsSource) {
const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
// Create the shader program
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
// If creating the shader program failed, alert
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
console.error('Unable to initialize the shader program: ' + gl.getProgramInfoLog(shaderProgram));
return null;
}
return shaderProgram;
}
/**
* Creates a shader of the given type, uploads the source and compiles it.
* @param {WebGLRenderingContext} gl The WebGL rendering context.
* @param {number} type The type of shader (gl.VERTEX_SHADER or gl.FRAGMENT_SHADER).
* @param {string} source The shader source code.
* @returns {WebGLShader} The compiled shader.
*/
function loadShader(gl, type, source) {
const shader = gl.createShader(type);
// Send the source to the shader object
gl.shaderSource(shader, source);
// Compile the shader program
gl.compileShader(shader);
// See if it compiled successfully
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
console.error('An error occurred compiling the shaders: ' + gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
return null;
}
return shader;
}
/**
* Initializes WebGL, creates shaders, and sets up buffers.
* @returns {boolean} True if WebGL initialized successfully, false otherwise.
*/
function initWebGL() {
if (!gl) {
console.error('Unable to initialize WebGL. Your browser or machine may not support it.');
return false;
}
shaderProgram = initShaderProgram(gl, vsSource, fsSource);
if (!shaderProgram) return false;
gl.useProgram(shaderProgram);
// Look up attribute and uniform locations
shaderProgram.a_position = gl.getAttribLocation(shaderProgram, 'a_position');
shaderProgram.a_color = gl.getAttribLocation(shaderProgram, 'a_color');
u_resolution = gl.getUniformLocation(shaderProgram, 'u_resolution');
u_transformMatrix = gl.getUniformLocation(shaderProgram, 'u_transformMatrix');
// Create buffers
positionBuffer = gl.createBuffer();
colorBuffer = gl.createBuffer();
gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); // Enable alpha blending
return true;
}
/**
* Sets up the buffers with vertex data for drawing.
* @param {Float32Array} positions - Array of vertex positions.
* @param {Float32Array} colors - Array of vertex colors (RGBA).
*/
function setGeometry(positions, colors) {
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, positions, gl.DYNAMIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, colors, gl.DYNAMIC_DRAW);
}
/**
* Draws a rectangle using WebGL.
* @param {number} x - Top-left X coordinate.
* @param {number} y - Top-left Y coordinate.
* @param {number} width - Width of the rectangle.
* @param {number} height - Height of the rectangle.
* @param {number[]} color - RGBA color array [r, g, b, a].
* @param {number} [rotation=0] - Rotation angle in radians around the center of the rectangle.
* @param {number} [pivotX=x + width/2] - X coordinate of the rotation pivot.
* @param {number} [pivotY=y + height/2] - Y coordinate of the rotation pivot.
*/
function drawRect(x, y, width, height, color, rotation = 0, pivotX = x + width / 2, pivotY = y + height / 2) {
const positions = new Float32Array([
0, 0,
width, 0,
0, height,
0, height,
width, 0,
width, height,
]);
const colors = new Float32Array([
color[0], color[1], color[2], color[3],
color[0], color[1], color[2], color[3],
color[0], color[1], color[2], color[3],
color[0], color[1], color[2], color[3],
color[0], color[1], color[2], color[3],
color[0], color[1], color[2], color[3],
]);
setGeometry(positions, colors);
// Set up attributes
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.vertexAttribPointer(shaderProgram.a_position, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(shaderProgram.a_position);
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
gl.vertexAttribPointer(shaderProgram.a_color, 4, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(shaderProgram.a_color);
// Set the resolution uniform
gl.uniform2f(u_resolution, gl.canvas.width, gl.canvas.height);
// Create and set the transform matrix
let matrix = [
1, 0, 0,
0, 1, 0,
x, y, 1, // Translate to position
];
// Translate to pivot, rotate, translate back
matrix = multiply(matrix, translation(-pivotX, -pivotY));
matrix = multiply(matrix, rotationMatrix(rotation));
matrix = multiply(matrix, translation(pivotX, pivotY));
gl.uniformMatrix3fv(u_transformMatrix, false, matrix);
gl.drawArrays(gl.TRIANGLES, 0, 6);
}
/**
* Draws a circle using WebGL.
* @param {number} x - Center X coordinate.
* @param {number} y - Center Y coordinate.
* @param {number} radius - Radius of the circle.
* @param {number[]} color - RGBA color array [r, g, b, a].
* @param {number} [segments=32] - Number of segments to approximate the circle.
*/
function drawCircle(x, y, radius, color, segments = 32) {
const positions = [];
const colors = [];
// Center vertex
positions.push(0, 0);
colors.push(color[0], color[1], color[2], color[3]);
for (let i = 0; i <= segments; i++) {
const angle = (i / segments) * Math.PI * 2;
positions.push(radius * Math.cos(angle), radius * Math.sin(angle));
colors.push(color[0], color[1], color[2], color[3]);
}
setGeometry(new Float32Array(positions), new Float32Array(colors));
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.vertexAttribPointer(shaderProgram.a_position, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(shaderProgram.a_position);
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
gl.vertexAttribPointer(shaderProgram.a_color, 4, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(shaderProgram.a_color);
gl.uniform2f(u_resolution, gl.canvas.width, gl.canvas.height);
// Translate matrix to center of circle
const matrix = [
1, 0, 0,
0, 1, 0,
x, y, 1,
];
gl.uniformMatrix3fv(u_transformMatrix, false, matrix);
gl.drawArrays(gl.TRIANGLE_FAN, 0, segments + 2);
}
// --- 2D Matrix Functions (for WebGL transformations) ---
function translation(tx, ty) {
return [
1, 0, 0,
0, 1, 0,
tx, ty, 1
];
}
function rotationMatrix(angleInRadians) {
const c = Math.cos(angleInRadians);
const s = Math.sin(angleInRadians);
return [
c, -s, 0,
s, c, 0,
0, 0, 1
];
}
function multiply(a, b) {
const a00 = a[0 * 3 + 0];
const a01 = a[0 * 3 + 1];
const a02 = a[0 * 3 + 2];
const a10 = a[1 * 3 + 0];
const a11 = a[1 * 3 + 1];
const a12 = a[1 * 3 + 2];
const a20 = a[2 * 3 + 0];
const a21 = a[2 * 3 + 1];
const a22 = a[2 * 3 + 2];
const b00 = b[0 * 3 + 0];
const b01 = b[0 * 3 + 1];
const b02 = b[0 * 3 + 2];
const b10 = b[1 * 3 + 0];
const b11 = b[1 * 3 + 1];
const b12 = b[1 * 3 + 2];
const b20 = b[2 * 3 + 0];
const b21 = b[2 * 3 + 1];
const b22 = b[2 * 3 + 2];
return [
a00 * b00 + a01 * b10 + a02 * b20,
a00 * b01 + a01 * b11 + a02 * b21,
a00 * b02 + a01 * b12 + a02 * b22,
a10 * b00 + a11 * b10 + a12 * b20,
a10 * b01 + a11 * b11 + a12 * b21,
a10 * b02 + a11 * b12 + a12 * b22,
a20 * b00 + a21 * b10 + a22 * b20,
a20 * b01 + a21 * b11 + a22 * b21,
a20 * b02 + a21 * b12 + a22 * b22,
];
}
// --- Utility Functions ---
/**
* Resizes the canvas to fit its parent container and maintain aspect ratio.
*/
function resizeCanvas() {
const parent = canvas.parentElement;
const aspectRatio = 1; // 1:1 aspect ratio (600/600)
let newWidth = parent.clientWidth;
let newHeight = newWidth / aspectRatio;
// Constrain height if it's too large for the window
const maxAllowedHeight = window.innerHeight * 0.7; // Max 70% of window height
if (newHeight > maxAllowedHeight) {
newHeight = maxAllowedHeight;
newWidth = newHeight * aspectRatio;
}
canvas.width = newWidth;
canvas.height = newHeight;
// Scale factor for drawing elements
// We'll scale all coordinates and sizes based on the new canvas size.
// Using a base size of 600 for scaling, as original logic was for 600x600.
const baseSize = 600;
window.scaleFactor = canvas.width / baseSize;
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
}
/**
* Converts an HSL color string to an RGBA array [r, g, b, a].
* @param {string} hsl - HSL color string (e.g., "hsl(120, 100%, 50%)").
* @param {number} [alpha=1] - Alpha value (0-1).
* @returns {number[]} RGBA color array.
*/
function hslToRgbA(hsl, alpha = 1) {
const parts = hsl.match(/hsl\((\d+),\s*(\d+)%,\s*(\d+)%\)/);
if (!parts) return [1, 0, 0, alpha]; // Default to red if invalid
let h = parseInt(parts[1]);
let s = parseInt(parts[2]) / 100;
let l = parseInt(parts[3]) / 100;
let c = (1 - Math.abs(2 * l - 1)) * s;
let x = c * (1 - Math.abs((h / 60) % 2 - 1));
let m = l - c / 2;
let r = 0;
let g = 0;
let b = 0;
if (0 <= h && h < 60) {
r = c; g = x; b = 0;
} else if (60 <= h && h < 120) {
r = x; g = c; b = 0;
} else if (120 <= h && h < 180) {
r = 0; g = c; b = x;
} else if (180 <= h && h < 240) {
r = 0; g = x; b = c;
} else if (240 <= h && h < 300) {
r = x; g = 0; b = c;
} else if (300 <= h && h < 360) {
r = c; g = 0; b = x;
}
r = (r + m);
g = (g + m);
b = (b + m);
return [r, g, b, alpha];
}
/**
* Converts an RGB hex string to an RGBA array [r, g, b, a].
* @param {string} hex - Hex color string (e.g., "#RRGGBB").
* @param {number} [alpha=1] - Alpha value (0-1).
* @returns {number[]} RGBA color array.
*/
function hexToRgbA(hex, alpha = 1) {
let r = 0, g = 0, b = 0;
// Handle #RGB and #RRGGBB
if (hex.length === 4) {
r = parseInt(hex[1] + hex[1], 16);
g = parseInt(hex[2] + hex[2], 16);
b = parseInt(hex[3] + hex[3], 16);
} else if (hex.length === 7) {
r = parseInt(hex.substring(1, 3), 16);
g = parseInt(hex.substring(3, 5), 16);
b = parseInt(hex.substring(5, 7), 16);
}
return [r / 255, g / 255, b / 255, alpha];
}
/**
* Draws the game background: cyan/black sky and green/dark gray grass.
*/
function drawBackground() {
const grassHeightRatio = 0.2; // 20% of canvas height for grass
const grassHeight = canvas.height * grassHeightRatio;
const skyHeight = canvas.height - grassHeight;
let skyColor, grassColor;
if (isDarkMode) {
skyColor = hexToRgbA("#000000"); // Black
grassColor = hexToRgbA("#1a1a1a"); // Dark gray
} else {
skyColor = hexToRgbA("#00FFFF"); // Cyan
grassColor = hexToRgbA("#7CFC00"); // Green
}
// Draw sky
drawRect(0, 0, canvas.width, skyHeight, skyColor);
// Draw grass
drawRect(0, skyHeight, canvas.width, grassHeight, grassColor);
}
/**
* Draws a dark gray border around the playable area.
*/
function drawBorder() {
const borderWidth = 20 * window.scaleFactor; // Scaled border width
const playableAreaX = borderWidth;
const playableAreaY = borderWidth;
const playableAreaWidth = canvas.width - (2 * borderWidth);
const playableAreaHeight = canvas.height - (2 * borderWidth);
const borderColor = hexToRgbA("#666666");
// Draw top border
drawRect(0, 0, canvas.width, playableAreaY, borderColor);
// Draw bottom border
drawRect(0, canvas.height - playableAreaY, canvas.width, playableAreaY, borderColor);
// Draw left border
drawRect(0, playableAreaY, playableAreaX, playableAreaHeight, borderColor);
// Draw right border
drawRect(canvas.width - playableAreaX, playableAreaY, playableAreaX, playableAreaHeight, borderColor);
// Redraw the inner playable area to ensure correct background colors are visible
const grassHeightRatio = 0.2;
const grassHeight = canvas.height * grassHeightRatio;
const skyHeight = canvas.height - grassHeight;
let skyColor, grassColor;
if (isDarkMode) {
skyColor = hexToRgbA("#000000"); // Black
grassColor = hexToRgbA("#1a1a1a"); // Dark gray
} else {
skyColor = hexToRgbA("#00FFFF"); // Cyan
grassColor = hexToRgbA("#7CFC00"); // Green
}
// Draw sky for playable area
drawRect(playableAreaX, playableAreaY, playableAreaWidth, skyHeight - playableAreaY, skyColor);
// Draw grass for playable area
drawRect(playableAreaX, skyHeight, playableAreaWidth, playableAreaHeight - (skyHeight - playableAreaY), grassColor);
}
/**
* Calculates the new position of a point after rotation around a pivot.
* Used to find the cannonball's starting position correctly.
* @param {number} x - Original X coordinate of the point (unscaled).
* @param {number} y - Original Y coordinate of the point (unscaled).
* @returns {{x: number, y: number}} The new rotated and scaled coordinates.
*/
function sortBallPos(x, y) {
let rotatedAngle = angle; // Use the original angle for physics calculation
// Cannon pivot is (cannon.x, cannon.y) in unscaled coordinates (center of barrel)
const pivotX_unscaled = cannon.x;
const pivotY_unscaled = cannon.y;
// Scale the original point to be rotated and the pivot
const scaledX = x * window.scaleFactor;
const scaledY = y * window.scaleFactor;
const pivotX_scaled = pivotX_unscaled * window.scaleFactor;
const pivotY_scaled = pivotY_unscaled * window.scaleFactor;
// Apply rotation to the point around the scaled pivot
let dx = scaledX - pivotX_scaled;
let dy = scaledY - pivotY_scaled;
let newX = pivotX_scaled + dx * Math.cos(rotatedAngle) - dy * Math.sin(rotatedAngle);
let newY = pivotY_scaled + dx * Math.sin(rotatedAngle) + dy * Math.cos(rotatedAngle);
return {
x: newX,
y: newY
};
}
// --- Cannon Class ---
class Cannon {
constructor(x, y) {
this.x = x; // Center X of the cannon barrel (unscaled)
this.y = y; // Center Y of the cannon barrel (unscaled)
this.width = 100; // Unscaled width
this.height = 50; // Unscaled height
}
/**
* Draws the cannon barrel with a dithered pattern and a light tan firing end.
*/
draw() {
const scaledWidth = this.width * window.scaleFactor;
const scaledHeight = this.height * window.scaleFactor;
const pivotX_scaled = this.x * window.scaleFactor;
const pivotY_scaled = this.y * window.scaleFactor;
if (mousePos) {
// Revert to original angle calculation for correct physics
angle = Math.atan2(mousePos.y - pivotY_scaled, mousePos.x - pivotX_scaled);
}
// Main barrel (solid brown for WebGL simplification)
const barrelColor = hexToRgbA("#A0522D"); // SaddleBrown
drawRect(
pivotX_scaled - scaledWidth / 2, // X for top-left corner
pivotY_scaled - scaledHeight / 2, // Y for top-left corner
scaledWidth, scaledHeight,
barrelColor,
-angle, // Negate angle for visual rotation to correct for Y-axis inversion
pivotX_scaled, pivotY_scaled // Pivot at its center
);
// Light tan firing end
const tanLength = 15 * window.scaleFactor;
const tanColor = hexToRgbA("#F5DEB3"); // Light tan
// The tan piece's top-left corner, relative to the cannon's pivot (this.x, this.y)
// Its left edge should align with the right edge of the barrel (scaledWidth / 2)
// Its top edge should align with the barrel's top edge (-scaledHeight / 2)
const tanLocalX = scaledWidth / 2;
const tanLocalY = -scaledHeight / 2;
drawRect(
pivotX_scaled + tanLocalX, // X for top-left corner (relative to pivot, then add pivot)
pivotY_scaled + tanLocalY, // Y for top-left corner (relative to pivot, then add pivot)
tanLength, scaledHeight,
tanColor,
-angle, // Negate angle for visual rotation to correct for Y-axis inversion
pivotX_scaled, pivotY_scaled // Pivot at the cannon's main center
);
}
/**
* Updates the cannon's position based on keyboard input.
*/
update() {
// Cannon's X position is the center of the barrel
const minCannonX = 20 + this.width / 2; // Left border + half width
const maxCannonX = 600 - 20 - this.width / 2; // Right border - half width
if (keysPressed['arrowleft'] || keysPressed['a']) {
this.x -= cannonMoveSpeed / window.scaleFactor; // Unscale speed for internal logic
}
if (keysPressed['arrowright'] || keysPressed['d']) {
this.x += cannonMoveSpeed / window.scaleFactor; // Unscale speed for internal logic
}
// Clamp cannon position to stay within bounds
this.x = Math.max(minCannonX, Math.min(maxCannonX, this.x));
}
}
// Initialize cannon:
// Cannon width = 100, height = 50 (unscaled)
// Canvas height = 600, border = 20 (unscaled)
// Bottom of playable area = 600 - 20 = 580 (unscaled)
// Cannon's center Y (this.y) = 580 - (cannon.height / 2) - 12 (gap) = 580 - 25 - 12 = 543 (unscaled)
let cannon = new Cannon(130, 543);