-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple-cube.cpp
More file actions
1732 lines (1419 loc) · 51.5 KB
/
Copy pathsimple-cube.cpp
File metadata and controls
1732 lines (1419 loc) · 51.5 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
#include "globals.hpp"
#include <GLFW/glfw3.h>
#include <cstdio>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
// Handle platform-specific includes
#ifdef __EMSCRIPTEN__
#include <GLES3/gl3.h>
#include <emscripten.h>
#include <emscripten/em_asm.h>
#include <emscripten/html5.h>
#define USING_GLES
#else
#include <OpenGL/gl3.h>
#endif
// GLM includes for math operations
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/gtx/norm.hpp>
// Include our model loader
#include "modelloader.hpp"
// Include our model loader and spline deformation
#include "deform.hpp"
#include "modelloader.hpp"
#include "spline.hpp"
// Global variables
GLFWwindow *g_window = nullptr;
int g_window_width = 1280;
int g_window_height = 720;
float lastTime = 0.0f;
float deltaTime = 0.0f;
bool modelLoaded = false;
std::string currentModelFile = "";
UniformCache uniformCache;
// Shader program
GLuint program_id = 0;
GLuint mvp_location = 0;
GLuint model_matrix_location;
GLuint vertex_position_location;
GLuint vertex_normal_location;
GLuint vertex_uv_location;
GLuint normal_buffer = 0;
GLuint uv_buffer = 0;
GLuint vertex_buffers[2] = {0, 0};
GLfloat *vertexAttribPointers[2] = {nullptr, nullptr};
int current_vertex_buffer = 0;
GLuint index_buffer = 0;
GLuint vao = 0;
GLuint cached_program_id = 0;
// Food Shader
GLuint food_program_id = 0;
GLuint food_mvp_location = 0;
GLuint food_time_location = 0;
GLuint food_color_location = 0;
// Model data
std::vector<glm::vec3> vertices;
std::vector<glm::vec2> uvs;
std::vector<glm::vec3> normals;
std::vector<unsigned int> indices;
float snakeBodyRadius = 0.0f;
// Deformed vertex buffer (used with spline spine)
std::vector<VertexBinding> vertexBindings;
std::vector<glm::vec3> deformedVertices;
std::vector<glm::vec3> lastDeformedVertices; // Previous frame vertices
std::vector<bool> vertexChanged; // Tracks which vertices changed
std::vector<unsigned int> changedIndices; // Indices of changed vertices
float vertexChangeThreshold = 0.0001f; // Square distance threshold
bool firstDeformation = true; // Flag for first deformation
//
// Spline spine
Spline snakeSpine;
int segmentCount = 20; // Number of segments (tail length)
float segmentSpacing = 0.5f; // Distance between segments
std::vector<float> vertexArcLengths; // One float per vertex
int pendingGrowth = 0;
// Snake movement
bool snakeStarted = false;
glm::vec3 snakePosition(0.0f);
glm::vec3 snakeDirection(0.0f, 0.0f, -1.0f); // initially moving along X
glm::vec3 nextDirection = snakeDirection; // Store desired direction
float snakeSpeed = 5.0f; // units per second
float distanceSinceLastTurn =
0.0f; // How much the snake has traveled since last direction change
float distanceSinceLastSample = 0.0f;
bool spineControlPointsChanged = true; // Start dirty
std::vector<SplineFrame> cachedSpineFrames;
std::vector<glm::vec3> previousControlPoints;
// Grid
float gridSize = 1.0f;
std::vector<glm::vec3> gridVertices;
std::vector<glm::vec3> gridColors;
GLuint grid_vertex_buffer = 0;
GLuint grid_color_buffer = 0;
GLuint grid_vao = 0;
float gridScale = 1.0f; // Size of each grid cell
int mapGridSize = 20; // Number of cells (half-width)
// Camera and transformation matrices
glm::mat4 model_matrix = glm::mat4(1.0f);
glm::mat4 view_matrix;
glm::mat4 projection_matrix;
glm::mat4 mvp_matrix;
// Food
std::vector<FoodItem> foodItems;
int maxFoodItems = 10; // Maximum number of food items
float foodSpawnTimer = 0.0f; // Timer for spawning new food
float foodSpawnInterval = 2.0f; // Spawn new food every 2 seconds
GLuint food_vertex_buffer = 0; // Vertex buffer for food rendering
GLuint food_glow_buffer = 0; // Buffer for glow parameters
int foodsEaten = 0;
// Game State
float cameraHeight = 60.0f; // y position of your camera (static for now)
bool gameOver = false;
float fovY = 45.0f; // Your camera's field of view in degrees
float cameraDistance =
glm::length(glm::vec3(0.0f, 60.0f, 0.0f)); // From your camera position
// WebGL Persistent Memory
#ifdef __EMSCRIPTEN__
// For tracking WebAssembly memory
std::vector<float> vertexDataBuffer; // Use std::vector instead of raw pointer
#endif
// Vertex shader source
const char *vertex_shader_source = R"(
attribute vec3 vertexPosition;
attribute vec3 vertexNormal;
attribute vec2 vertexUV;
attribute vec3 vertexColor; // Add color attribute
uniform mat4 MVP;
uniform mat4 modelMatrix;
varying vec3 fragmentNormal;
varying vec2 fragmentUV;
varying vec3 fragmentPosition;
varying vec3 fragmentColor; // Add color varying
void main() {
gl_Position = MVP * vec4(vertexPosition, 1.0);
// Transform normal to world space
fragmentNormal = (modelMatrix * vec4(vertexNormal, 0.0)).xyz;
// Pass through UV coordinates
fragmentUV = vertexUV;
// Calculate world space position
fragmentPosition = (modelMatrix * vec4(vertexPosition, 1.0)).xyz;
// Pass color to fragment shader
fragmentColor = vertexColor;
}
)";
// Optimized fragment shader with early returns and efficient calculations
const char *fragment_shader_source = R"(
varying vec3 fragmentNormal;
varying vec2 fragmentUV;
varying vec3 fragmentPosition;
varying vec3 fragmentColor; // Add color varying
uniform float opacity; // Add opacity uniform
void main() {
// Check if color is set (non-zero)
bool hasColor = (fragmentColor.r > 0.0 || fragmentColor.g > 0.0 || fragmentColor.b > 0.0);
if (hasColor) {
// Use vertex color directly for grid lines, with the opacity uniform
gl_FragColor = vec4(fragmentColor, opacity);
} else {
// Basic diffuse lighting for model
vec3 lightDir = normalize(vec3(0.5, 1.0, 0.3));
float diffuse = max(dot(normalize(fragmentNormal), lightDir), 0.1);
// Create a pattern from UVs for visualization
vec3 baseColor = vec3(fragmentUV.x, fragmentUV.y, 1.0 - fragmentUV.x);
// Generate final color with lighting
vec3 color = baseColor * diffuse;
gl_FragColor = vec4(color, 1.0);
}
}
)";
// Food vertex shader with glow effect
const char *food_vertex_shader_source = R"(
precision mediump float;
attribute vec3 position;
attribute float glowFactor;
uniform mat4 MVP;
uniform float time;
varying float vGlowFactor;
varying vec3 vPosition;
varying float vPulseFactor;
void main() {
// Calculate pulse factor but DON'T apply it to position
float pulseFactor = 1.0 + 0.2 * sin(time * 2.0);
// Keep position unchanged
gl_Position = MVP * vec4(position, 1.0);
// Only apply pulsing to the point size
gl_PointSize = 15.0 + 10.0 * glowFactor * pulseFactor;
// Pass values to fragment shader
vGlowFactor = glowFactor;
vPosition = position;
vPulseFactor = pulseFactor; // Pass pulse factor to fragment shader
}
)";
// Food fragment shader with glow effect
const char *food_fragment_shader_source = R"(
precision mediump float;
uniform vec3 foodColor;
uniform float time;
varying float vGlowFactor;
varying vec3 vPosition;
varying float vPulseFactor;
void main() {
// Calculate distance from center of point sprite
vec2 center = vec2(0.5, 0.5);
vec2 coord = gl_PointCoord - center;
float dist = length(coord);
// Create circular point with soft edge
float alpha = 1.0 - smoothstep(0.3, 0.5, dist);
// Glow pulse effect - more pronounced
float glowPulse = 0.5 + 0.5 * sin(time * 3.0 + vPosition.x + vPosition.z);
// Enhanced glow
vec3 baseColor = foodColor;
vec3 glowColor = vec3(1.0, 1.0, 0.7) * 2.0; // Brighter yellow glow
// More dramatic mixing of color based on glow
vec3 finalColor = mix(baseColor, glowColor, vGlowFactor * glowPulse * vPulseFactor);
// Additional brightness around the edges for glow effect
float edgeGlow = 1.0 - smoothstep(0.3, 0.5, dist);
finalColor += glowColor * vGlowFactor * glowPulse * edgeGlow * 0.5;
// Make center brighter
float centerBrightness = 1.0 + vGlowFactor * 2.0 * vPulseFactor * (1.0 - dist * 2.0);
finalColor *= centerBrightness;
gl_FragColor = vec4(finalColor, alpha);
}
)";
// Function to compile shader
GLuint compile_shader(GLenum type, const char *source) {
GLuint shader = glCreateShader(type);
glShaderSource(shader, 1, &source, nullptr);
glCompileShader(shader);
GLint success;
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success) {
GLint info_log_length;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &info_log_length);
std::vector<char> info_log(info_log_length + 1);
glGetShaderInfoLog(shader, info_log_length, nullptr, &info_log[0]);
printf("Shader compilation error: %s\n", &info_log[0]);
return 0;
}
return shader;
}
GLuint create_food_program() {
// Compile shaders
GLuint vertex_shader =
compile_shader(GL_VERTEX_SHADER, food_vertex_shader_source);
GLuint fragment_shader =
compile_shader(GL_FRAGMENT_SHADER, food_fragment_shader_source);
if (!vertex_shader || !fragment_shader) {
printf("Failed to compile food shaders.\n");
return 0;
}
// Create and link program
GLuint program = glCreateProgram();
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
// Bind attribute locations
glBindAttribLocation(program, 0, "position");
glBindAttribLocation(program, 1, "glowFactor");
glLinkProgram(program);
// Check for linking errors
GLint success;
glGetProgramiv(program, GL_LINK_STATUS, &success);
if (!success) {
GLint info_log_length;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &info_log_length);
std::vector<char> info_log(info_log_length + 1);
glGetProgramInfoLog(program, info_log_length, nullptr, &info_log[0]);
printf("Food program linking error: %s\n", &info_log[0]);
return 0;
}
// Clean up shaders
glDetachShader(program, vertex_shader);
glDetachShader(program, fragment_shader);
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
return program;
}
// Function to create shader program
GLuint create_program() {
// Set the appropriate preamble based on platform
std::string vertex_preamble, fragment_preamble;
#ifdef USING_GLES
vertex_preamble = "#version 100\n"; // OpenGL ES 2.0
fragment_preamble =
"#version 100\nprecision mediump float;\n"; // Required for GLES
#else
vertex_preamble = "#version 120\n";
fragment_preamble = "#version 120\n";
#endif
// Combine preamble with shader source
std::string vertex_full = vertex_preamble + vertex_shader_source;
std::string fragment_full = fragment_preamble + fragment_shader_source;
// Compile shaders
GLuint vertex_shader = compile_shader(GL_VERTEX_SHADER, vertex_full.c_str());
GLuint fragment_shader =
compile_shader(GL_FRAGMENT_SHADER, fragment_full.c_str());
if (!vertex_shader || !fragment_shader) {
printf("Failed to compile shaders.\n");
return 0;
}
// Create and link program
GLuint program = glCreateProgram();
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);
// Check for linking errors
GLint success;
glGetProgramiv(program, GL_LINK_STATUS, &success);
if (!success) {
GLint info_log_length;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &info_log_length);
std::vector<char> info_log(info_log_length + 1);
glGetProgramInfoLog(program, info_log_length, nullptr, &info_log[0]);
printf("Program linking error: %s\n", &info_log[0]);
return 0;
}
// Clean up shaders
glDetachShader(program, vertex_shader);
glDetachShader(program, fragment_shader);
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
return program;
}
// Create grid vertices
void createGrid() {
int width, height;
glfwGetFramebufferSize(g_window, &width, &height);
float aspectRatio = (float)width / (float)height;
// Calculate visible area at camera's target plane
float visibleHeight = 2.0f * cameraDistance * tan(glm::radians(fovY * 0.5f));
float visibleWidth = visibleHeight * aspectRatio;
// Add 20% margin to ensure grid covers entire viewport
float margin = 1.0f;
mapGridSize = (int)std::ceil(std::max(visibleWidth, visibleHeight) * margin /
(2.0f * gridScale));
// Rest of your grid creation code...
gridVertices.clear();
gridColors.clear();
float gridExtent = mapGridSize * gridScale;
// Create grid lines along X and Z axes
for (int i = -mapGridSize; i <= mapGridSize; i++) {
float pos = i * gridScale;
// Lines along X-axis (vary Z)
gridVertices.push_back(glm::vec3(-gridExtent, 0.0f, pos));
gridVertices.push_back(glm::vec3(gridExtent, 0.0f, pos));
// Lines along Z-axis (vary X)
gridVertices.push_back(glm::vec3(pos, 0.0f, -gridExtent));
gridVertices.push_back(glm::vec3(pos, 0.0f, gridExtent));
// Colors - thin lines for regular grid
glm::vec3 lineColor =
(i == 0) ? glm::vec3(0.0f, 0.7f, 0.0f) : // Center axes (green)
glm::vec3(0.4f, 0.4f, 0.4f); // Regular grid (gray)
// Add colors for both pairs of vertices
gridColors.push_back(lineColor);
gridColors.push_back(lineColor);
gridColors.push_back(lineColor);
gridColors.push_back(lineColor);
}
// Add border lines with increased thickness and different color
// Bottom border (min Z)
gridVertices.push_back(glm::vec3(-gridExtent, 0.0f, -gridExtent));
gridVertices.push_back(glm::vec3(gridExtent, 0.0f, -gridExtent));
// Top border (max Z)
gridVertices.push_back(glm::vec3(-gridExtent, 0.0f, gridExtent));
gridVertices.push_back(glm::vec3(gridExtent, 0.0f, gridExtent));
// Left border (min X)
gridVertices.push_back(glm::vec3(-gridExtent, 0.0f, -gridExtent));
gridVertices.push_back(glm::vec3(-gridExtent, 0.0f, gridExtent));
// Right border (max X)
gridVertices.push_back(glm::vec3(gridExtent, 0.0f, -gridExtent));
gridVertices.push_back(glm::vec3(gridExtent, 0.0f, gridExtent));
// Red color for all border lines
glm::vec3 borderColor(0.8f, 0.1f, 0.1f); // Red
for (int i = 0; i < 8; i++) {
gridColors.push_back(borderColor);
}
printf("Created grid with %zu vertices\n", gridVertices.size());
}
// Spawn a new food item with a more dramatic color
void spawnFood() {
FoodItem food;
// Corrected: use camera parameters to calculate visible ground area
float fovY = 45.0f; // vertical field of view in degrees
float aspectRatio = (float)g_window_width / (float)g_window_height;
// Calculate half-extent of visible ground rectangle
float halfHeight = cameraHeight * tan(glm::radians(fovY * 0.5f));
float halfWidth = halfHeight * aspectRatio;
// Set spawn attempts limit
int attempts = 0;
const int MAX_ATTEMPTS = 25;
bool validPosition = false;
while (!validPosition && attempts < MAX_ATTEMPTS) {
// Random X and Z within ground view bounds
food.position.x = (((float)rand() / RAND_MAX) * 2.0f - 1.0f) * halfWidth;
food.position.z = (((float)rand() / RAND_MAX) * 2.0f - 1.0f) * halfHeight;
food.position.y = 0.2f; // Always a little above the ground
// Check for collisions with existing food
bool tooClose = false;
for (const auto &existingFood : foodItems) {
if (glm::distance(food.position, existingFood.position) <
2.0f * gridScale) {
tooClose = true;
break;
}
}
if (!tooClose) {
validPosition = true;
} else {
attempts++;
}
}
if (!validPosition) {
printf("Warning: Failed to find valid food position after %d attempts\n",
MAX_ATTEMPTS);
// Still place it at a random fallback
}
// Assign color randomly
const glm::vec3 vibrantColors[] = {
glm::vec3(1.0f, 0.2f, 0.2f), // Red
glm::vec3(0.2f, 1.0f, 0.2f), // Green
glm::vec3(0.2f, 0.2f, 1.0f), // Blue
glm::vec3(1.0f, 1.0f, 0.2f), // Yellow
glm::vec3(1.0f, 0.2f, 1.0f), // Magenta
glm::vec3(0.2f, 1.0f, 1.0f), // Cyan
glm::vec3(1.0f, 0.6f, 0.1f), // Orange
glm::vec3(0.7f, 0.2f, 1.0f) // Purple
};
int colorIndex = rand() % 8;
food.color = vibrantColors[colorIndex];
// Randomize glow intensity and size
food.size = 0.8f + (float)rand() / RAND_MAX * 0.5f;
food.glowIntensity = 0.7f + (float)rand() / RAND_MAX * 0.6f;
food.animationPhase =
(float)rand() / RAND_MAX * 6.28f; // Random phase [0, 2π]
foodItems.push_back(food);
}
// Initialize food rendering resources
void initializeFood() {
// Create shader program
food_program_id = create_food_program();
if (!food_program_id) {
printf("Failed to create food shader program\n");
return;
}
// Get uniform locations
food_mvp_location = glGetUniformLocation(food_program_id, "MVP");
food_time_location = glGetUniformLocation(food_program_id, "time");
food_color_location = glGetUniformLocation(food_program_id, "foodColor");
// Create buffers
if (food_vertex_buffer == 0) {
glGenBuffers(1, &food_vertex_buffer);
}
if (food_glow_buffer == 0) {
glGenBuffers(1, &food_glow_buffer);
}
// Check for WebGL point sprite support - FIXED VERSION
#ifdef __EMSCRIPTEN__
// Log WebGL capabilities using Module.ctx
EM_ASM({
console.log("WebGL: Checking capabilities");
// Use Module.ctx which is the pre-established WebGL context
if (Module.ctx) {
try {
console.log(
"Point size range: " +
Module.ctx.getParameter(Module.ctx.ALIASED_POINT_SIZE_RANGE));
console.log("Using standard WebGL point sprites");
} catch (e) {
console.log("Error checking WebGL capabilities: " + e);
}
} else {
console.log("WebGL context not available in Module.ctx");
}
});
#endif
// Spawn initial food
while (foodItems.size() < maxFoodItems) {
spawnFood();
}
}
void growSnake() {
std::vector<glm::vec3> controlPoints = snakeSpine.getControlPoints();
if (controlPoints.size() < 2) {
return;
}
size_t lastIndex = controlPoints.size() - 1;
const glm::vec3 &lastPoint = controlPoints[lastIndex];
const glm::vec3 &secondLastPoint = controlPoints[lastIndex - 1];
glm::vec3 direction = lastPoint - secondLastPoint;
if (glm::length(direction) > 0.001f) {
direction = glm::normalize(direction);
} else {
direction = glm::vec3(0.0f, 0.0f, 1.0f); // default
}
// Calculate spacing
float segmentLength = (controlPoints.size() > 1)
? glm::distance(controlPoints[0], controlPoints[1])
: 1.0f; // fallback
glm::vec3 newPoint = lastPoint + direction * segmentLength;
snakeSpine.addControlPoint(newPoint);
}
// Update food items
void updateFood(float deltaTime) {
// Skip if snake hasn't started
if (!snakeStarted || snakeSpine.getControlPoints().empty()) {
return;
}
// Get snake head position
// Update animation phases for all food items
for (auto &food : foodItems) {
food.animationPhase += deltaTime;
if (food.animationPhase > 6.28f) { // 2π
food.animationPhase -= 6.28f;
}
}
// Check for collisions with snake head
bool foodWasEaten = false;
auto it = foodItems.begin();
const glm::vec3 &snakeHead = deformedVertices[0];
while (it != foodItems.end()) {
glm::vec2 snakeXZ(snakeHead.x, snakeHead.z);
glm::vec2 foodXZ(it->position.x, it->position.z);
if (glm::distance(snakeXZ, foodXZ) < 1.0f) {
it = foodItems.erase(it);
foodWasEaten = true;
pendingGrowth += 2;
foodsEaten++;
snakeSpeed += 0.05;
printf("[Food] Eaten: %d\n", foodsEaten);
} else {
++it;
}
}
// CRITICAL: Always ensure we have exactly maxFoodItems on the map
int missingItems = maxFoodItems - static_cast<int>(foodItems.size());
if (missingItems > 0) {
// Spawn exactly missingItems new food items
for (int i = 0; i < missingItems; i++) {
spawnFood();
}
}
}
// Initialize grid rendering resources
void initializeGrid() {
// Create the grid data
createGrid();
// Generate buffers
if (grid_vertex_buffer == 0) {
glGenBuffers(1, &grid_vertex_buffer);
}
if (grid_color_buffer == 0) {
glGenBuffers(1, &grid_color_buffer);
}
// Create VAO for desktop OpenGL
#ifndef USING_GLES
if (grid_vao == 0) {
glGenVertexArrays(1, &grid_vao);
glBindVertexArray(grid_vao);
}
#endif
// Upload vertex data
glBindBuffer(GL_ARRAY_BUFFER, grid_vertex_buffer);
glBufferData(GL_ARRAY_BUFFER, gridVertices.size() * sizeof(glm::vec3),
gridVertices.data(), GL_STATIC_DRAW);
// Upload color data
glBindBuffer(GL_ARRAY_BUFFER, grid_color_buffer);
glBufferData(GL_ARRAY_BUFFER, gridColors.size() * sizeof(glm::vec3),
gridColors.data(), GL_STATIC_DRAW);
#ifndef USING_GLES
glBindVertexArray(0);
#endif
}
// Create vertex indices for a cube if no model is loaded
void createDefaultCube() {
vertices = {// Front face
{-0.5f, -0.5f, 0.5f},
{0.5f, -0.5f, 0.5f},
{0.5f, 0.5f, 0.5f},
{-0.5f, 0.5f, 0.5f},
// Back face
{-0.5f, -0.5f, -0.5f},
{0.5f, -0.5f, -0.5f},
{0.5f, 0.5f, -0.5f},
{-0.5f, 0.5f, -0.5f}};
indices = {// Front
0, 1, 2, 2, 3, 0,
// Right
1, 5, 6, 6, 2, 1,
// Back
5, 4, 7, 7, 6, 5,
// Left
4, 0, 3, 3, 7, 4,
// Top
3, 2, 6, 6, 7, 3,
// Bottom
4, 5, 1, 1, 0, 4};
// Create basic UVs
uvs.resize(vertices.size());
for (size_t i = 0; i < vertices.size(); i++) {
uvs[i] = glm::vec2((vertices[i].x + 0.5f), (vertices[i].y + 0.5f));
}
// Create basic normals
normals.resize(vertices.size());
for (size_t i = 0; i < vertices.size(); i++) {
normals[i] = glm::normalize(vertices[i]);
}
}
// Update GPU buffers with model data
void updateBuffers() {
// Update both vertex buffers
for (int i = 0; i < 2; i++) {
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffers[i]);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3),
vertices.data(), GL_DYNAMIC_DRAW);
}
// Initialize vertex change tracking
lastDeformedVertices.resize(vertices.size());
vertexChanged.resize(vertices.size());
changedIndices.reserve(vertices.size() / 4); // Reserve reasonable capacity
// Copy initial vertices
for (size_t i = 0; i < vertices.size(); i++) {
lastDeformedVertices[i] = vertices[i];
}
firstDeformation = true;
// Update normal buffer
glBindBuffer(GL_ARRAY_BUFFER, normal_buffer);
glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3),
normals.data(), GL_STATIC_DRAW);
// Update UV buffer
glBindBuffer(GL_ARRAY_BUFFER, uv_buffer);
glBufferData(GL_ARRAY_BUFFER, uvs.size() * sizeof(glm::vec2), uvs.data(),
GL_STATIC_DRAW);
// Update index buffer
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int),
indices.data(), GL_STATIC_DRAW);
// Reset current buffer to 0
current_vertex_buffer = 0;
modelLoaded = true;
}
void initializeSnakeSpine() {
// Clear any existing control points
snakeSpine.clear();
// === Calculate model bounds ===
glm::vec3 min(FLT_MAX), max(-FLT_MAX);
for (const auto &v : vertices) {
min = glm::min(min, v);
max = glm::max(max, v);
}
// === Calculate snake body radius ===
glm::vec3 extents = max - min;
int primaryAxis = 0;
float maxExtent = extents.x;
if (extents.y > maxExtent) {
primaryAxis = 1;
maxExtent = extents.y;
}
if (extents.z > maxExtent) {
primaryAxis = 2;
maxExtent = extents.z;
}
float minorExtent1, minorExtent2;
if (primaryAxis == 0) {
minorExtent1 = extents.y;
minorExtent2 = extents.z;
} else if (primaryAxis == 1) {
minorExtent1 = extents.x;
minorExtent2 = extents.z;
} else {
minorExtent1 = extents.x;
minorExtent2 = extents.y;
}
float bodyThickness = (minorExtent1 + minorExtent2) * 0.5f;
snakeBodyRadius = bodyThickness * 0.5f;
printf("[initializeSnakeSpine] Snake body radius calculated: %.3f\n",
snakeBodyRadius);
// === Create initial control points ===
const int numPoints = 20;
float modelLength = max.x - min.x; // Assuming X is the primary axis
float spacing = modelLength / (numPoints - 1);
for (int i = 0; i < numPoints; i++) {
float t = static_cast<float>(i) / (numPoints - 1);
float x = max.x - t * modelLength;
float y = (min.y + max.y) / 2.0f;
float z = (min.z + max.z) / 2.0f;
snakeSpine.addControlPoint(glm::vec3(x, y, z));
}
// === Reset state ===
deformedVertices.resize(vertices.size());
snakePosition = glm::vec3(0.0f);
snakeDirection = glm::vec3(1.0f, 0.0f, 0.0f);
nextDirection = snakeDirection;
distanceSinceLastSample = 0.0f;
snakeStarted = false;
spineControlPointsChanged = true;
cachedSpineFrames.clear();
previousControlPoints = snakeSpine.getControlPoints();
printf("Snake spine initialized with %zu control points\n",
snakeSpine.getControlPoints().size());
printf("Spacing between control points: %.2f\n", spacing);
}
// Enhanced function to calculate vertex arc lengths based on model geometry
void calculateVertexArcLengths() {
vertexArcLengths.clear();
vertexArcLengths.reserve(vertices.size());
// Find model bounds
glm::vec3 min(FLT_MAX), max(-FLT_MAX);
for (const auto &v : vertices) {
min = glm::min(min, v);
max = glm::max(max, v);
}
// Model dimensions
glm::vec3 dimensions = max - min;
printf("Model dimensions: X: %f, Y: %f, Z: %f\n", dimensions.x, dimensions.y,
dimensions.z);
// For a snake model, we need to determine which axis represents its length
// (usually the longest dimension)
int primaryAxis = 0; // 0=X, 1=Y, 2=Z
float maxDim = dimensions.x;
if (dimensions.y > maxDim) {
primaryAxis = 1;
maxDim = dimensions.y;
}
if (dimensions.z > maxDim) {
primaryAxis = 2;
maxDim = dimensions.z;
}
printf("Primary axis for snake length: %d (0=X, 1=Y, 2=Z)\n", primaryAxis);
// For each vertex, calculate its normalized position along the primary axis
for (const auto &vertex : vertices) {
float primaryCoord = 0.0f;
float primaryMin = 0.0f;
float primaryMax = 0.0f;
// Get the appropriate coordinate based on primary axis
switch (primaryAxis) {
case 0: // X-axis
primaryCoord = vertex.x;
primaryMin = min.x;
primaryMax = max.x;
break;
case 1: // Y-axis
primaryCoord = vertex.y;
primaryMin = min.y;
primaryMax = max.y;
break;
case 2: // Z-axis
primaryCoord = vertex.z;
primaryMin = min.z;
primaryMax = max.z;
break;
}
// Normalize position along the primary axis (0.0 to 1.0)
float normalizedPos =
(primaryCoord - primaryMin) / (primaryMax - primaryMin);
// We need to determine which end is the head and which is the tail
// For most models, the head should be at the HIGHER value of the primary
// axis For example, if Z is the primary axis, higher Z values would
// typically be the head
// Calculate arc length - invert the normalized position so that:
// - Head vertices (highest coordinate) map to LOW arc lengths (front of
// spine)
// - Tail vertices (lowest coordinate) map to HIGH arc lengths (back of
// spine)
float arcLength = (1.0f - normalizedPos) * segmentCount * segmentSpacing;
vertexArcLengths.push_back(arcLength);
}
// Find the min and max arc lengths assigned to verify our mapping
float minArc = FLT_MAX;
float maxArc = -FLT_MAX;
for (float arc : vertexArcLengths) {
minArc = std::min(minArc, arc);
maxArc = std::max(maxArc, arc);
}
printf("Arc length range: %f to %f\n", minArc, maxArc);
printf(
"Vertices mapped from head (arc length %.2f) to tail (arc length %.2f)\n",
minArc, maxArc);
// If we detect a potential issue with mapping direction, warn the user
if (maxArc - minArc < segmentCount * segmentSpacing * 0.5f) {
printf("WARNING: Arc length range seems too small. The snake model might "
"not deform properly.\n");
printf("Consider adjusting segmentCount (%d) or segmentSpacing (%.2f)\n",
segmentCount, segmentSpacing);
}
}
// Function to load a model
bool loadModel(const char *filename) {
printf("Loading model: %s\n", filename);
// Save the current file
currentModelFile = filename;
// Clear existing data
vertices.clear();
uvs.clear();
normals.clear();
indices.clear();
// Try to load the model
bool result = loadModelBase(filename, vertices, uvs, normals, indices);
if (!result || vertices.empty()) {
printf("Failed to load model or model was empty. Using default cube.\n");
createDefaultCube();
return false;
}
printf("Successfully loaded model with %zu vertices, %zu indices\n",
vertices.size(), indices.size());
// Update GPU buffers
updateBuffers();
firstDeformation = true;
lastDeformedVertices.resize(vertices.size());
vertexChanged.resize(vertices.size());
changedIndices.clear();
#ifdef __EMSCRIPTEN__
// Resize vertex data buffer to match new model
vertexDataBuffer.resize(vertices.size() * 3);
// Initialize with vertex data
for (size_t i = 0; i < vertices.size(); i++) {
vertexDataBuffer[i * 3] = vertices[i].x;
vertexDataBuffer[i * 3 + 1] = vertices[i].y;
vertexDataBuffer[i * 3 + 2] = vertices[i].z;
}
// Update the pointer and size in JavaScript
EM_ASM(
{
Module.vertexBufferPointer = $0;
Module.vertexBufferSize = $1;
},