-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
807 lines (682 loc) · 30.5 KB
/
main.cpp
File metadata and controls
807 lines (682 loc) · 30.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
/* Minecraft-Clone in C++ with OpenGL
----------------------------------
Next steps:
- Schleichmodus -> nicht herunterfallen im Schleichen
- Texturen richtig platzieren
- Texttur-File erweitern
- Texturen unterschiedlich auf verschiedenen Seiten
- Weltgenerierung mit "Perlin Noise" oder "Simplex Noise"
- Welt in Chunks (16x16x256) unterteilen
- unzerstörbare Bedrock-Blöcke
- Wasser (halbtransparente Blöcke) –> richtiges Fliessverhalten
- Laubblöcke
*/
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define GL_SILENCE_DEPRECATION
#include <OpenGL/gl3.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <vector>
#include <cmath>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <cstdlib> // Needed for rand() and srand()
#include <ctime> // Needed for time()
// Kamera Variablen (Global oder vor der main-loop)
glm::vec3 cameraPos = glm::vec3(0.0f, 20.0f, 0.0f);
glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f);
glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f);
float deltaTime = 0.0f; // Zeit zwischen aktuellem und letztem Frame
float lastFrame = 0.0f;
bool firstMouse = true;
float yaw = -90.0f; // Initial nach vorne (auf der Z-Achse)
float pitch = 0.0f;
float lastX = 400.0f;
float lastY = 400.0f;
// --- Variabeln für Bewegung, Gravitation und Kollision ---
glm::vec2 horizontalVel = glm::vec2(0.0f);
float verticalVelocity = 0.0f;
const float maxVertVelocity = -30.0f;
const float GRAVITY = -15.0f;
const float JUMP_FORCE = 6.0f;
bool isGrounded = false;
float playerSize = 2.3f;
// Alle möglichen Blocktypen
enum BlockType { GRASS = 1, DIRT = 2, COBBLESTONE = 3, STONE = 4, GRAVEL = 5, LOG = 6, PLANK = 7 };
const glm::vec2 textureArraySize = glm::vec2(7.0f, 3.0f);
// Speichert alle zusätzlichen Blöcke, die du baust
struct Block {
glm::vec3 position;
float health;
float maxHealth;
BlockType type;
int numDiffSides;
};
BlockType currentSelected = GRASS;
std::vector<Block> buildBlocks;
int targetBlockIndex = -1; // Welchen Block schauen wir gerade an?
bool mousePressed = false; // Verhindert "Dauerfeuer"
// --- Neuer Vertex Shader ---
const char* vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 aPos;\n"
"layout (location = 1) in vec2 aTexCoord;\n"
"layout (location = 2) in int aFaceID;\n"
"out vec2 TexCoord;\n"
"uniform mat4 transform;\n"
"uniform vec2 uvOffset;\n"
"uniform int numDiffSides;\n"
"uniform vec2 textureArraySize;\n"
"void main() {\n"
" float yOffset = 0.0f;\n"
" if (numDiffSides == 2) {\n"
" if (aFaceID == 0) yOffset = 1.0f / textureArraySize.y;\n"
" }\n"
" else if (numDiffSides == 3) {\n"
" if (aFaceID == 0) yOffset = 1.0f / textureArraySize.y;\n"
" else if (aFaceID == 2) yOffset = 2.0f / textureArraySize.y;\n"
" }\n"
" gl_Position = transform * vec4(aPos, 1.0);\n"
" TexCoord = vec2(aTexCoord.x / textureArraySize.x + uvOffset.x, aTexCoord.y / textureArraySize.y + uvOffset.y + yOffset);\n"
"}\0";
// --- Neuer Fragment Shader ---
const char* fragmentShaderSource = "#version 330 core\n"
"out vec4 FragColor;\n"
"in vec2 TexCoord;\n" // <--- Kommt vom Vertex Shader
"uniform sampler2D ourTexture;\n" // <--- Das "Bild"-Objekt
"uniform float alpha;\n" // <--- Transparenz
"void main() {\n"
" vec4 texColor = texture(ourTexture, TexCoord);\n"
" FragColor = vec4(texColor.rgb, texColor.a);\n" // <--- Liest die Farbe aus dem Bild an dieser Stelle
"}\n\0";
// --- Fadenkreuz Shader ---
const char* uiVertexShader = "#version 330 core\n"
"layout (location = 0) in vec2 aPos;\n"
"void main() { gl_Position = vec4(aPos, 0.0, 1.0); }\0";
const char* uiFragmentShader = "#version 330 core\n"
"out vec4 FragColor;\n"
"void main() { FragColor = vec4(1.0, 1.0, 1.0, 0.5); }\n\0";
// --- Shader für Block-Icon
const char* ui2VertexShader = "#version 330 core\n"
"layout (location = 0) in vec2 aPos;\n"
"layout (location = 1) in vec2 aTexCoord;\n" // UV-Koordinaten vom Quad
"out vec2 TexCoord;\n"
"uniform float aspectRatio;\n"
"uniform vec2 uvOffset;\n" // Dein Offset (0, 1/3, 2/3)
"uniform vec2 offsetPos;\n" // z.B. (-0.9, -0.9)
"uniform float size;\n" // z.B. 0.1
"uniform vec2 textureArraySize;\n"
"void main() {\n"
" float xPos = (aPos.x * size) / aspectRatio + offsetPos.x;\n"
" float yPos = (aPos.y * size) + offsetPos.y;\n"
" gl_Position = vec4(xPos, yPos, 0.0, 1.0);\n"
" TexCoord = vec2(aTexCoord.x / textureArraySize.x + uvOffset.x, aTexCoord.y / textureArraySize.y + uvOffset.y);\n"
"}\0";
const char* ui2FragmentShader = "#version 330 core\n"
"out vec4 FragColor;\n"
"in vec2 TexCoord;\n"
"uniform sampler2D textureAtlas;\n"
"void main() {\n"
" FragColor = texture(textureAtlas, TexCoord);\n"
"}\n\0";
// --- Block platzieren ---
void placeBlock() {
glm::vec3 rayPos = cameraPos;
glm::vec3 lastEmptyPos = cameraPos;
float stepSize = 0.1f; // Je kleiner, desto präziser
float maxDist = 6.0f; // Deine gewünschte Reichweite
for (float t = 0.0f; t < maxDist; t += stepSize) {
rayPos = cameraPos + cameraFront * t;
glm::vec3 snappedPos = glm::vec3(std::round(rayPos.x), std::round(rayPos.y), std::round(rayPos.z));
glm::vec3 roundedCamPos = glm::vec3(std::round(cameraPos.x), std::round(cameraPos.y), std::round(cameraPos.z));
// Prüfen, ob an snappedPos schon ein Block ist
bool hit = false;
// Check gesetzte Blöcke
for (auto& b : buildBlocks) {
if (glm::distance(b.position, snappedPos) < 0.1f && glm::distance(roundedCamPos,snappedPos) > 0.9f) {
hit = true;
break;
}
}
if (hit) {
if (glm::vec3(std::round(lastEmptyPos.x), std::round(lastEmptyPos.y), std::round(lastEmptyPos.z)) != roundedCamPos &&
glm::vec3(std::round(lastEmptyPos.x), std::round(lastEmptyPos.y) + 1, std::round(lastEmptyPos.z)) != roundedCamPos) {
// Wir haben etwas getroffen! Setze den Block an die LETZTE freie Position
Block newBlock;
newBlock.position = glm::vec3(std::round(lastEmptyPos.x), std::round(lastEmptyPos.y), std::round(lastEmptyPos.z));
newBlock.type = currentSelected;
switch (currentSelected) {
case GRASS:
newBlock.maxHealth = 1.0f;
newBlock.numDiffSides = 3;
break;
case DIRT:
newBlock.maxHealth = 1.0f;
newBlock.numDiffSides = 1;
break;
case COBBLESTONE:
newBlock.maxHealth = 2.0f;
newBlock.numDiffSides = 1;
break;
case STONE:
newBlock.maxHealth = 3.0f;
newBlock.numDiffSides = 1;
break;
case GRAVEL:
newBlock.maxHealth = 1.0f;
newBlock.numDiffSides = 1;
break;
case LOG:
newBlock.maxHealth = 3.0f;
newBlock.numDiffSides = 2;
break;
case PLANK:
newBlock.maxHealth = 2.0f;
newBlock.numDiffSides = 1;
break;
}
newBlock.health = newBlock.maxHealth;
buildBlocks.push_back(newBlock);
return;
} else return;
}
lastEmptyPos = rayPos;
}
}
// --- Betrachteten Block erkennen ---
int getTargetBlock() {
float maxDist = 6.0f;
float stepSize = 0.1f;
for (float t = 0.0f; t < maxDist; t += stepSize) {
glm::vec3 rayPos = cameraPos + cameraFront * t;
glm::vec3 snappedPos = glm::vec3(std::round(rayPos.x), std::round(rayPos.y), std::round(rayPos.z));
for (int i = 0; i < buildBlocks.size(); i++) {
if (glm::distance(buildBlocks[i].position, snappedPos) < 0.1f) {
return i; // Index des getroffenen Blocks
}
}
}
return -1; // Nichts getroffen
}
// --- Block erkennen ---
bool isBlockAt(glm::vec3 pos, const std::vector<Block>& buildBlocks) {
// Erstelle eine kleine Hitbox um den Spieler (z.B. 0.3 Einheiten breit)
float radius = 0.25f;
for (const auto& block : buildBlocks) {
// AABB Kollision: Prüfe ob Spieler-Box und Block-Box überlappen
bool collisionX = pos.x + radius > block.position.x - 0.5f && block.position.x + 0.5f > pos.x - radius;
bool collisionZ = pos.z + radius > block.position.z - 0.5f && block.position.z + 0.5f > pos.z - radius;
// Wir prüfen nur, ob wir in der Höhe des Blocks (y bis y+1) sind
bool collisionY = pos.y > block.position.y-0.5f && pos.y < block.position.y + 1.5f;
if (collisionX && collisionY && collisionZ) return true;
}
return false;
}
// Tastatureingabe (WASD)
void processInput(GLFWwindow *window) {
float playerSpeed;
bool inputActive = false;
glm::vec3 nextPos = cameraPos;
glm::vec3 moveDir;
if (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS) {
playerSize = 1.8f;
playerSpeed = 7.0f * deltaTime;
} else {
playerSize = 2.3f;
playerSpeed = 14.0f * deltaTime;
}
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) {
moveDir = glm::normalize(glm::vec3(cameraFront.x, 0.0f, cameraFront.z));
inputActive = true;
}
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) {
moveDir = glm::normalize(glm::vec3(-cameraFront.x, 0.0f, -cameraFront.z));
inputActive = true;
}
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) {
moveDir = glm::normalize(glm::cross(glm::vec3(-cameraFront.x, 0.0f, -cameraFront.z), cameraUp));
inputActive = true;
}
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) {
moveDir = glm::normalize(glm::cross(glm::vec3(cameraFront.x, 0.0f, cameraFront.z), cameraUp));
inputActive = true;
}
if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS && isGrounded)
verticalVelocity = JUMP_FORCE;
if (glfwGetKey(window, GLFW_KEY_1) == GLFW_PRESS)
currentSelected = GRASS;
if (glfwGetKey(window, GLFW_KEY_2) == GLFW_PRESS)
currentSelected = DIRT;
if (glfwGetKey(window, GLFW_KEY_3) == GLFW_PRESS)
currentSelected = COBBLESTONE;
if (glfwGetKey(window, GLFW_KEY_4) == GLFW_PRESS)
currentSelected = STONE;
if (glfwGetKey(window, GLFW_KEY_5) == GLFW_PRESS)
currentSelected = GRAVEL;
if (glfwGetKey(window, GLFW_KEY_6) == GLFW_PRESS)
currentSelected = LOG;
if (glfwGetKey(window, GLFW_KEY_7) == GLFW_PRESS)
currentSelected = PLANK;
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) {
if (!mousePressed) { // Nur ausführen, wenn vorher nicht gedrückt wurde
placeBlock();
mousePressed = true;
}
} else {
mousePressed = false; // Sperre aufheben, wenn Taste losgelassen wird
}
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS) {
int index = getTargetBlock();
if (index != -1) {
// Block wird abgebaut
buildBlocks[index].health -= deltaTime;
// Optisches Feedback (optional: Block könnte zittern)
// std::cout << "Abbau-Status: " << buildBlocks[index].health << std::endl;
if (buildBlocks[index].health <= 0.0f) {
buildBlocks.erase(buildBlocks.begin() + index); // Block entfernen
}
}
}
if (isGrounded) {
// Am Boden: Sofortige Reaktion auf Input
if (inputActive) horizontalVel = glm::vec2(moveDir.x, moveDir.z) * playerSpeed;
else horizontalVel = glm::vec2(0.0f); // Sofort stoppen (oder Reibung einbauen)
} else {
if (inputActive) {
horizontalVel += glm::vec2(moveDir.x, moveDir.z) * playerSpeed * deltaTime * 0.1f;
// Limitieren, damit man nicht unendlich schnell wird
if (glm::length(horizontalVel) > playerSpeed)
horizontalVel = glm::normalize(horizontalVel) * playerSpeed;
}
}
// X-Achse separat prüfen
glm::vec3 testX = cameraPos + glm::vec3(horizontalVel.x * playerSpeed, 0.0f, 0.0f);
if (!isBlockAt(testX, buildBlocks)) cameraPos.x = testX.x;
// Z-Achse separat prüfen
glm::vec3 testZ = cameraPos + glm::vec3(0.0f, 0.0f, horizontalVel.y * playerSpeed);
if (!isBlockAt(testZ, buildBlocks)) cameraPos.z = testZ.z;
}
// Nutzung der Maus zu Änderung der Sicht in der Welt
void mouse_callback(GLFWwindow* window, double xposIn, double yposIn) {
float xpos = static_cast<float>(xposIn);
float ypos = static_cast<float>(yposIn);
if (firstMouse) {
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
float xoffset = xpos - lastX;
float yoffset = lastY - ypos; // Umgekehrt, da y-Koordinaten von unten nach oben gehen
lastX = xpos;
lastY = ypos;
float sensitivity = 0.1f;
xoffset *= sensitivity;
yoffset *= sensitivity;
yaw += xoffset;
pitch += yoffset;
// Pitch begrenzen, damit man keinen "Überschlag" macht
if (pitch > 89.0f) pitch = 89.0f;
if (pitch < -89.0f) pitch = -89.0f;
// Den neuen Richtungsvektor aus den Winkeln berechnen
glm::vec3 front;
front.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch));
front.y = sin(glm::radians(pitch));
front.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch));
cameraFront = glm::normalize(front);
}
int main() {
if (!glfwInit()) return -1;
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
// Hol dir den primären Monitor und seine Video-Einstellungen
GLFWmonitor* primaryMonitor = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(primaryMonitor);
// Erstelle das Fenster mit der Auflösung deines Monitors
GLFWwindow* window = glfwCreateWindow(mode->width, mode->height, "Minecraft Clone", primaryMonitor, NULL);
if (!window) { glfwTerminate(); return -1; }
glfwMakeContextCurrent(window);
glViewport(0, 0, mode->width, mode->height);
//glViewport(0, 0, 900, 600);
// Versteckt den Cursor und fängt ihn im Fenster
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
// Registriert unsere Funktion
glfwSetCursorPosCallback(window, mouse_callback);
// Transparenz ermöglichen
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// --- Shader Kompilierung ---
unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
unsigned int shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
// --- Shader erstellen für Fadenkreuz ---
// UI Vertex Shader erstellen
unsigned int uiVertexShaderObj = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(uiVertexShaderObj, 1, &uiVertexShader, NULL);
glCompileShader(uiVertexShaderObj);
// UI Fragment Shader erstellen
unsigned int uiFragmentShaderObj = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(uiFragmentShaderObj, 1, &uiFragmentShader, NULL);
glCompileShader(uiFragmentShaderObj);
// UI Shader Program zusammenführen
unsigned int uiShaderProgram = glCreateProgram();
glAttachShader(uiShaderProgram, uiVertexShaderObj);
glAttachShader(uiShaderProgram, uiFragmentShaderObj);
glLinkProgram(uiShaderProgram);
// Die einzelnen Shader-Objekte können nun gelöscht werden
glDeleteShader(uiVertexShaderObj);
glDeleteShader(uiFragmentShaderObj);
// --- Shader erstellen für Block-Icon ---
// UI Vertex Shader erstellen
unsigned int ui2VertexShaderObj = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(ui2VertexShaderObj, 1, &ui2VertexShader, NULL);
glCompileShader(ui2VertexShaderObj);
// UI Fragment Shader erstellen
unsigned int ui2FragmentShaderObj = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(ui2FragmentShaderObj, 1, &ui2FragmentShader, NULL);
glCompileShader(ui2FragmentShaderObj);
// UI Shader Program zusammenführen
unsigned int ui2ShaderProgram = glCreateProgram();
glAttachShader(ui2ShaderProgram, ui2VertexShaderObj);
glAttachShader(ui2ShaderProgram, ui2FragmentShaderObj);
glLinkProgram(ui2ShaderProgram);
// Die einzelnen Shader-Objekte können nun gelöscht werden
glDeleteShader(ui2VertexShaderObj);
glDeleteShader(ui2FragmentShaderObj);
struct Vertex {
float x, y, z;
float u, v;
int faceID; // Echter Integer im Speicher
};
// --- Würfel Daten (Positionen X,Y,Z und Textur-Koord U, V) ---
Vertex vertices[] = {
// Positionen X,Y,Z ; Textur-Koord (U, V) ; Face-ID (0: Seite; 1: oben; 2: unten)
// Rückseite
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0,
-0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0,
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0,
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0,
// Vorderseite
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0,
// Linke Seite
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0,
-0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0,
-0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0,
// Rechte Seite
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0,
// Unterseite
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 2,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 2,
0.5f, -0.5f, 0.5f, 1.0f, 1.0f, 2,
-0.5f, -0.5f, 0.5f, 0.0f, 1.0f, 2,
// Oberseite
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, 1,
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 1,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 1,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 1
};
unsigned int indices[] = {
0, 1, 2, 2, 3, 0,
4, 5, 6, 6, 7, 4,
8, 9, 10, 10, 11, 8,
12, 13, 14, 14, 15, 12,
16, 17, 18, 18, 19, 16,
20, 21, 22, 22, 23, 20
};
unsigned int VBO, VAO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
// Position: 0, 3 Floats, Schrittweite 6
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// Textur: 1, 2 Floats
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
// Face-ID: 2, 1 Int
glVertexAttribIPointer(2, 1, GL_INT, 6 * sizeof(float), (void*)(5 * sizeof(float)));
glEnableVertexAttribArray(2);
glEnable(GL_DEPTH_TEST); // Wichtig für 3D!
unsigned int texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
// Textur-Parameter (Pixel-Look wie in Minecraft!)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
int width, height, nrChannels;
stbi_set_flip_vertically_on_load(true);
// Nutze STBI_rgb_alpha, um sicherzugehen, dass wir 4 Kanäle laden
unsigned char *data = stbi_load("texture.png", &width, &height, &nrChannels, STBI_rgb_alpha);
if (data) {
// Wenn wir STBI_rgb_alpha nutzen, müssen wir hier GL_RGBA verwenden
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
} else {
std::cout << "Fehler: Textur konnte nicht geladen werden! Pfad prüfen." << std::endl;
}
stbi_image_free(data);
// --- Fadenkreuz-Infos ---
float crosshairVertices[] = {
-0.02f, 0.0f, 0.02f, 0.0f, // Horizontale Linie
0.0f, -0.02f, 0.0f, 0.02f // Vertikale Linie
};
unsigned int uiVAO, uiVBO;
glGenVertexArrays(1, &uiVAO);
glGenBuffers(1, &uiVBO);
glBindVertexArray(uiVAO);
glBindBuffer(GL_ARRAY_BUFFER, uiVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(crosshairVertices), crosshairVertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// (Shader-Kompilierung für uiShaderProgram analog zum Haupt-Shader durchführen)
// --- Für Block-Icon ---
float uiVertices[] = {
// Position (x, y) // UV (u, v)
0.0f, 0.0f, 0.0f, 0.0f, // Unten Links
1.0f, 0.0f, 1.0f, 0.0f, // Unten Rechts
1.0f, 1.0f, 1.0f, 1.0f, // Oben Rechts
0.0f, 1.0f, 0.0f, 1.0f // Oben Links
};
unsigned int uiIconVAO, uiIconVBO;
glGenVertexArrays(1, &uiIconVAO);
glGenBuffers(1, &uiIconVBO);
glBindVertexArray(uiIconVAO);
glBindBuffer(GL_ARRAY_BUFFER, uiIconVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(uiVertices), uiVertices, GL_STATIC_DRAW);
// Location 0: Position (2 Floats)
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// Location 1: UV-Koordinaten (2 Floats)
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float)));
glEnableVertexAttribArray(1);
// (Shader-Kompilierung für uiShaderProgram analog zum Haupt-Shader durchführen)
// Start-Welt generieren (64x64 Ebene)
srand(time(0));
int numSides;
for (int x = -32; x < 32; x++) {
for (int z = -32; z < 32; z++) {
int randomNum = rand() % 7 + 1;
switch (randomNum) {
case 1:
currentSelected = GRASS;
numSides = 3;
break;
case 2:
currentSelected = DIRT;
numSides = 1;
break;
case 3:
currentSelected = COBBLESTONE;
numSides = 1;
break;
case 4:
currentSelected = STONE;
numSides = 1;
break;
case 5:
currentSelected = GRAVEL;
numSides = 1;
break;
case 6:
currentSelected = LOG;
numSides = 2;
break;
case 7:
currentSelected = PLANK;
numSides = 1;
break;
}
Block groundBlock;
groundBlock.position = glm::vec3((float)x, 0.0f, (float)z);
groundBlock.health = 1.0f; // 1 Sekunde zum Abbauen
groundBlock.maxHealth = 1.0f;
groundBlock.type = currentSelected;
groundBlock.numDiffSides = numSides;
buildBlocks.push_back(groundBlock);
// std::cout << currentSelected << ", " << numSides << std::endl;
}
}
currentSelected = GRASS;
while (!glfwWindowShouldClose(window)) {
// 1. Zeit-Logik für flüssige Bewegung
float currentFrame = (float)glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
// 2. Gravitation
// Schwerkraft anwenden
verticalVelocity += GRAVITY * deltaTime;
if (verticalVelocity < maxVertVelocity) verticalVelocity = maxVertVelocity;
cameraPos.y += verticalVelocity * deltaTime;
// Einfache Bodenkollision (sehr simpel für den Anfang)
isGrounded = false;
for (const auto& block : buildBlocks) {
// Wenn wir über einem Block sind und fast auf seiner Oberkante (y+1)
if (std::abs(cameraPos.x - block.position.x) < 0.7f &&
std::abs(cameraPos.z - block.position.z) < 0.7f &&
cameraPos.y <= block.position.y + playerSize && // playerSize ist die Augenhöhe
cameraPos.y >= block.position.y + 1.0f)
{
cameraPos.y = block.position.y + playerSize;
verticalVelocity = 0.0f;
isGrounded = true;
break;
}
}
// 3. Eingaben verarbeiten (W, A, S, D, Space, Shift, M & ESC)
processInput(window);
// 4. Rendering-Setup
glClearColor(0.5f, 0.8f, 0.9f, 1.0f); // Ein schönes Minecraft-Blau für den Himmel
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(shaderProgram); // Shader aktivieren
// Sagt dem Shader, dass 'ourTexture' den Textur-Slot 0 nutzen soll
glUniform1i(glGetUniformLocation(shaderProgram, "ourTexture"), 0);
// 5. Gemeinsame Matrizen (View & Projection gelten für alle Blöcke im Frame)
// Berechne das Seitenverhältnis dynamisch
float aspectRatio = (float)mode->width / (float)mode->height;
// In der while-Schleife anpassen:
glm::mat4 projection = glm::perspective(glm::radians(45.0f), aspectRatio, 0.1f, 100.0f);
glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp);
int transLoc = glGetUniformLocation(shaderProgram, "transform");
int alphaLoc = glGetUniformLocation(shaderProgram, "alpha");
// 6. Den Chunk zeichnen (64x64 Blöcke)
glBindVertexArray(VAO);
int uvLoc = glGetUniformLocation(shaderProgram, "uvOffset");
// --- Alle Blöcke zeichnen ---
// Wir iterieren jetzt über 'Block' (die Struktur)
for (const auto& block : buildBlocks) {
glm::mat4 model = glm::mat4(1.0f);
glm::vec2 offset = glm::vec2(0.0f, 0.0f);
// Atlas-Logik (X-Achse verschieben)
if (block.type == GRASS) offset.x = 0.0f;
if (block.type == DIRT) offset.x = 1.0f / textureArraySize.x;
if (block.type == COBBLESTONE) offset.x = 2.0f / textureArraySize.x;
if (block.type == STONE) offset.x = 3.0f / textureArraySize.x;
if (block.type == GRAVEL) offset.x = 4.0f / textureArraySize.x;
if (block.type == LOG) offset.x = 5.0f / textureArraySize.x;
if (block.type == PLANK) offset.x = 6.0f / textureArraySize.x;
offset.y = 0.0f;
glUniform2fv(uvLoc, 1, glm::value_ptr(offset));
// WICHTIG: Nutze block.position für die Verschiebung
model = glm::translate(model, block.position);
// Grösse des Textur-Arrays übergeben an Shader
int textureLoc = glGetUniformLocation(shaderProgram, "textureArraySize");
glUniform2fv(textureLoc, 1, glm::value_ptr(textureArraySize));
// Anzahl unterschiedlicher Blockseiten übergeben an Shader
int numSidesLoc = glGetUniformLocation(shaderProgram, "numDiffSides");
glUniform1i(numSidesLoc, block.numDiffSides);
// Alpha berechnen: 1.0 wenn gesund, geht gegen 0.0 beim Abbauen
float currentAlpha = block.health / block.maxHealth;
glUniform1f(alphaLoc, currentAlpha); // Wert an den Shader senden
glm::mat4 mvp = projection * view * model;
glUniformMatrix4fv(transLoc, 1, GL_FALSE, glm::value_ptr(mvp));
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0);
}
// 7. Fadenkreuz zeichnen
glUseProgram(uiShaderProgram);
glBindVertexArray(uiVAO);
glDrawArrays(GL_LINES, 0, 4); // Zeichnet das Kreuz fix in der Mitte
// 8. Block-Icon zeichnen
glUseProgram(ui2ShaderProgram);
glBindTexture(GL_TEXTURE_2D, texture);
glBindVertexArray(uiIconVAO);
// Offset berechnen wie bei den Welt-Blöcken
glm::vec2 offset = glm::vec2(0.0f, 0.0f);
if (currentSelected == GRASS) offset.x = 0.0f;
if (currentSelected == DIRT) offset.x = 1.0f / textureArraySize.x;
if (currentSelected == COBBLESTONE) offset.x = 2.0f / textureArraySize.x;
if (currentSelected == STONE) offset.x = 3.0f / textureArraySize.x;
if (currentSelected == GRAVEL) offset.x = 4.0f / textureArraySize.x;
if (currentSelected == LOG) offset.x = 5.0f / textureArraySize.x;
if (currentSelected == PLANK) offset.x = 6.0f / textureArraySize.x;
// Position übergeben an Shader
int iconLoc = glGetUniformLocation(ui2ShaderProgram, "offsetPos");
glUniform2f(iconLoc, -0.95f, -0.95f);
// Offset übergeben an Shader
int uvLocUI = glGetUniformLocation(ui2ShaderProgram, "uvOffset");
glUniform2fv(uvLocUI, 1, glm::value_ptr(offset));
// Aspect-Ratio übergeben an Shader
int aspectLoc = glGetUniformLocation(ui2ShaderProgram, "aspectRatio");
glUniform1f(aspectLoc, aspectRatio);
// Grösse des Icons übergeben an Shader
int iconSize = glGetUniformLocation(ui2ShaderProgram, "size");
glUniform1f(iconSize, 0.15f);
// Grösse des Textur-Arrays übergeben an Shader
int texture2Loc = glGetUniformLocation(ui2ShaderProgram, "textureArraySize");
glUniform2fv(texture2Loc, 1, glm::value_ptr(textureArraySize));
// WICHTIG: Tiefentest kurz aus, damit UI immer vorne ist
glDisable(GL_DEPTH_TEST);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glEnable(GL_DEPTH_TEST);
// 9. Buffer tauschen & Events abfragen
glfwSwapBuffers(window);
glfwPollEvents();
}
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &EBO);
glfwTerminate();
return 0;
}