-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwhat.cpp
More file actions
831 lines (721 loc) · 26.8 KB
/
Copy pathwhat.cpp
File metadata and controls
831 lines (721 loc) · 26.8 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
#include <iostream>
// ⠞⠕⠎⠎ ⠽⠕⠥⠗ ⠙⠊⠗⠞⠽ ⠎⠓⠕⠑⠎ ⠃⠑⠉⠁⠥⠎⠑ ⠎⠓⠥⠞ ⠽⠕⠥⠗ ⠋⠗⠊⠉⠅ ⠥⠏ ⠁⠝⠙ ⠓⠁⠧⠑ ⠎⠑⠭⠥⠁⠇ ⠃⠇⠕⠕⠙ ⠊⠝ ⠽⠕⠥⠗ ⠃⠕⠙⠽ ⠃⠑⠉⠁⠥⠎⠑ ⠽⠕⠥ ⠺⠊⠇⠇ ⠺⠁⠞⠉⠓ ⠕⠇⠙ ⠠⠁⠥⠍⠠⠎⠥⠍ ⠁⠝⠙ ⠃⠇⠑⠝⠙⠑⠗ ⠞⠥⠞⠕⠗⠊⠁⠇⠎
你好世界("Goodbye World")
// SSAO_Pipeline.cpp
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <thread>
#include <chrono>
#include <vector>
#include "Shader.h" // Helper class for shader compile/link
#include "GLUtils.h" // FBO/texture creation helpers
// Target FPS by device class
enum DeviceClass { PC, TABLET, HIGH_END_PHONE, PHONE };
int getTargetFPS(DeviceClass dc) {
switch(dc) {
case PC: return 60;
case TABLET: return 45;
case HIGH_END_PHONE: return 45;
case PHONE: return 25;
}
return 60;
}
int main() {
// Initialize GLFW + GLEW
glfwInit();
GLFWwindow* win = glfwCreateWindow(1280, 720, "SSAO Pipeline", nullptr, nullptr);
glfwMakeContextCurrent(win);
glewInit();
// 1. Create 4-color 1D palette: black, yellow, green, red
GLuint paletteTex;
GLubyte paletteData[4*3] = {
0, 0, 0, // black
255, 255, 0, // yellow
0, 255, 0, // green
255, 0, 0 // red
};
glGenTextures(1, &paletteTex);
glBindTexture(GL_TEXTURE_1D, paletteTex);
glTexImage1D(GL_TEXTURE_1D, 0, GL_RGB8, 4, 0, GL_RGB, GL_UNSIGNED_BYTE, paletteData);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// 2. Allocate FBOs + textures for each pass
GLuint fboCanvas, texCanvas;
GLuint fboBlur, texBlur;
GLuint fboSSAO, texSSAO;
GLuint fboScatter,texScatter;
GLuint fboSheen, texSheen;
GLuint fboShadows,texShadows;
GLuint fboGloss, texGloss;
createColorFBO(1280, 720, fboCanvas, texCanvas);
createColorFBO(1280, 720, fboBlur, texBlur);
createColorFBO(1280, 720, fboSSAO, texSSAO);
createColorFBO(1280, 720, fboScatter, texScatter);
createColorFBO(1280, 720, fboSheen, texSheen);
createColorFBO(1280, 720, fboShadows, texShadows);
createColorFBO(1280, 720, fboGloss, texGloss);
// 3. Compile shaders for each stage
Shader canvasShader("canvas.vert", "canvas.frag"); // just clears white
Shader blurShader( "quad.vert", "gaussian.frag");
Shader ssaoShader( "quad.vert", "ssao.frag");
Shader scatterShader("quad.vert", "scatter.frag");
Shader sheenShader( "quad.vert", "sheen.frag");
Shader shadowShader("quad.vert", "shadow_comp.frag");
Shader glossShader( "quad.vert", "gloss.frag");
// Choose device class; could be detected or set at runtime
DeviceClass devClass = PC;
int targetFPS = getTargetFPS(devClass);
double frameDuration = 1.0 / targetFPS;
// Fullscreen quad VAO
GLuint quadVAO = createScreenQuad();
while (!glfwWindowShouldClose(win)) {
// Frame‐rate limiter
auto t0 = std::chrono::high_resolution_clock::now();
// PASS 1: White Canvas
glBindFramebuffer(GL_FRAMEBUFFER, fboCanvas);
canvasShader.use();
glClearColor(1,1,1,1);
glClear(GL_COLOR_BUFFER_BIT);
glBindVertexArray(quadVAO);
glDrawArrays(GL_TRIANGLES, 0, 6);
// PASS 2: Blur on white canvas
glBindFramebuffer(GL_FRAMEBUFFER, fboBlur);
blurShader.use();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texCanvas);
blurShader.setInt("uInputTex", 0);
glDrawArrays(GL_TRIANGLES, 0, 6);
// PASS 3: SSAO
glBindFramebuffer(GL_FRAMEBUFFER, fboSSAO);
ssaoShader.use();
ssaoShader.setInt("uNormalDepthTex", 0);
// bind depth+normal if available...
glDrawArrays(GL_TRIANGLES, 0, 6);
// PASS 4: Scattering
glBindFramebuffer(GL_FRAMEBUFFER, fboScatter);
scatterShader.use();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texBlur);
scatterShader.setInt("uBaseTex", 0);
glDrawArrays(GL_TRIANGLES, 0, 6);
// PASS 5: Sheen
glBindFramebuffer(GL_FRAMEBUFFER, fboSheen);
sheenShader.use();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texSSAO);
sheenShader.setInt("uOcclTex", 0);
glDrawArrays(GL_TRIANGLES, 0, 6);
// PASS 6: Sheen → Blur map
glBindFramebuffer(GL_FRAMEBUFFER, fboBlur);
blurShader.use();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texSheen);
blurShader.setInt("uInputTex", 0);
glDrawArrays(GL_TRIANGLES, 0, 6);
// PASS 7: Shadows & composite
glBindFramebuffer(GL_FRAMEBUFFER, fboShadows);
shadowShader.use();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texScatter);
shadowShader.setInt("uColorTex", 0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texBlur);
shadowShader.setInt("uSheenBlurTex", 1);
glDrawArrays(GL_TRIANGLES, 0, 6);
// PASS 8: Glossiness spreading
glBindFramebuffer(GL_FRAMEBUFFER, fboGloss);
glossShader.use();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texShadows);
glossShader.setInt("uBaseTex", 0);
glossShader.setFloat("uGlossSpread", 1.0f); // tune per GPU
glDrawArrays(GL_TRIANGLES, 0, 6);
// Final: Present to screen
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClear(GL_COLOR_BUFFER_BIT);
blurShader.use(); // re‐use simple quad shader
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texGloss);
blurShader.setInt("uInputTex", 0);
glDrawArrays(GL_TRIANGLES, 0, 6);
glfwSwapBuffers(win);
glfwPollEvents();
// Frame‐rate lock
auto t1 = std::chrono::high_resolution_clock::now();
double elapsed = std::chrono::duration<double>(t1 - t0).count();
if (elapsed < frameDuration) {
std::this_thread::sleep_for(
std::chrono::duration<double>(frameDuration - elapsed)
);
}
}
// Cleanup
glfwDestroyWindow(win);
glfwTerminate();
return 0;
}
// main.cpp
#include <cstdio>
#include <vector>
#include <cmath>
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
// Window dimensions
static const int WIDTH = 800;
static const int HEIGHT = 600;
// Perlin noise helper (Ken Perlin’s improved noise)
float perlinNoise(float x, float y) {
static int p[512], permutation[256] = {
151,160,137,91,90,15, // … fill in the standard 256 perm array …
// (complete with values 0–255 in a scrambled order)
};
static bool initialized = false;
if (!initialized) {
for (int i = 0; i < 256; ++i)
p[256 + i] = p[i] = permutation[i];
initialized = true;
}
auto fade = [](float t) { return t * t * t * (t * (t * 6 - 15) + 10); };
auto lerp = [](float a, float b, float t) { return a + t * (b - a); };
auto grad = [](int hash, float x, float y) {
switch (hash & 3) {
case 0: return x + y;
case 1: return -x + y;
case 2: return x - y;
case 3: return -x - y;
}
return 0.0f; // never happens
};
int xi = (int)std::floor(x) & 255;
int yi = (int)std::floor(y) & 255;
float xf = x - std::floor(x), yf = y - std::floor(y);
float u = fade(xf), v = fade(yf);
int aa = p[p[xi] + yi], ab = p[p[xi] + yi + 1];
int ba = p[p[xi + 1] + yi], bb = p[p[xi + 1] + yi + 1];
float x1 = lerp(grad(aa, xf, yf),
grad(ba, xf-1, yf), u);
float x2 = lerp(grad(ab, xf, yf-1),
grad(bb, xf-1, yf-1), u);
return (lerp(x1, x2, v) + 1.0f) * 0.5f; // normalize to [0,1]
}
// Shader sources
const char* vertSrc = R"glsl(
#version 330 core
layout(location=0) in vec3 aPos;
layout(location=1) in vec3 aNormal;
out vec3 FragPos;
out vec3 Normal;
uniform mat4 model, view, projection;
void main(){
FragPos = vec3(model * vec4(aPos,1.0));
Normal = mat3(transpose(inverse(model))) * aNormal;
gl_Position = projection * view * vec4(FragPos,1.0);
}
)glsl";
const char* fragSrc = R"glsl(
#version 330 core
in vec3 FragPos;
in vec3 Normal;
out vec4 color;
uniform vec3 lightPos, viewPos;
void main(){
// ambient
vec3 ambient = 0.1 * vec3(0.2,0.7,0.3);
// diffuse
vec3 norm = normalize(Normal);
vec3 lightDir = normalize(lightPos - FragPos);
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = diff * vec3(0.2,0.7,0.3);
// specular
float specStrength = 0.5;
vec3 viewDir = normalize(viewPos - FragPos);
vec3 reflectDir = reflect(-lightDir, norm);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), 32);
vec3 specular = specStrength * spec * vec3(1.0);
vec3 result = ambient + diffuse + specular;
color = vec4(result, 1.0);
}
)glsl";
// Build and compile shaders
GLuint compileShader(GLenum type, const char* src) {
GLuint shader = glCreateShader(type);
glShaderSource(shader, 1, &src, nullptr);
glCompileShader(shader);
GLint ok;
glGetShaderiv(shader, GL_COMPILE_STATUS, &ok);
if (!ok) {
char buf[512];
glGetShaderInfoLog(shader, 512, nullptr, buf);
std::fprintf(stderr, "Shader compile error: %s\n", buf);
}
return shader;
}
int main(){
if (!glfwInit()) return -1;
GLFWwindow* win = glfwCreateWindow(WIDTH, HEIGHT, "Perlin Terrain", nullptr, nullptr);
if (!win) { glfwTerminate(); return -1; }
glfwMakeContextCurrent(win);
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK) return -1;
// Generate terrain grid
const int SIZE = 200;
const float SCALE = 0.1f;
std::vector<glm::vec3> positions;
std::vector<glm::vec3> normals;
std::vector<unsigned> indices;
positions.reserve(SIZE * SIZE);
normals .reserve(SIZE * SIZE);
// compute positions & normals placeholder
for (int z = 0; z < SIZE; ++z) {
for (int x = 0; x < SIZE; ++x) {
float fx = x * SCALE, fz = z * SCALE;
float y = perlinNoise(fx, fz) * 10.0f;
positions.emplace_back(fx, y, fz);
normals.emplace_back(0,1,0); // temp; we’ll recalc
}
}
// build index list & compute normals
for (int z = 0; z < SIZE - 1; ++z) {
for (int x = 0; x < SIZE - 1; ++x) {
int i0 = z * SIZE + x;
int i1 = i0 + 1;
int i2 = i0 + SIZE;
int i3 = i2 + 1;
// two triangles: (i0,i2,i1) and (i1,i2,i3)
indices.push_back(i0); indices.push_back(i2); indices.push_back(i1);
indices.push_back(i1); indices.push_back(i2); indices.push_back(i3);
// calc normals for both
auto addNormal = [&](int a, int b, int c){
glm::vec3 U = positions[b] - positions[a];
glm::vec3 V = positions[c] - positions[a];
glm::vec3 N = glm::normalize(glm::cross(U, V));
normals[a] += N;
normals[b] += N;
normals[c] += N;
};
addNormal(i0,i2,i1);
addNormal(i1,i2,i3);
}
}
for (auto& n : normals) n = glm::normalize(n);
// upload to GPU
GLuint VAO, VBO[2], EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(2, VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO[0]);
glBufferData(GL_ARRAY_BUFFER, positions.size() * sizeof(glm::vec3),
positions.data(), GL_STATIC_DRAW);
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,0,nullptr);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, VBO[1]);
glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3),
normals.data(), GL_STATIC_DRAW);
glVertexAttribPointer(1,3,GL_FLOAT,GL_FALSE,0,nullptr);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
indices.size()*sizeof(unsigned),
indices.data(), GL_STATIC_DRAW);
// compile & link
GLuint vs = compileShader(GL_VERTEX_SHADER, vertSrc);
GLuint fs = compileShader(GL_FRAGMENT_SHADER, fragSrc);
GLuint prog = glCreateProgram();
glAttachShader(prog, vs);
glAttachShader(prog, fs);
glLinkProgram(prog);
glUseProgram(prog);
// uniforms
GLint modelLoc = glGetUniformLocation(prog, "model");
GLint viewLoc = glGetUniformLocation(prog, "view");
GLint projLoc = glGetUniformLocation(prog, "projection");
GLint lightPosLoc = glGetUniformLocation(prog, "lightPos");
GLint viewPosLoc = glGetUniformLocation(prog, "viewPos");
// camera setup
glm::vec3 camPos(10,20,30), camTarget(10,0,10);
glm::mat4 view = glm::lookAt(camPos, camTarget, glm::vec3(0,1,0));
glm::mat4 proj = glm::perspective(glm::radians(45.0f),
float(WIDTH)/HEIGHT, 0.1f, 100.0f);
glm::mat4 model = glm::mat4(1.0f);
glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(proj));
glUniform3f(lightPosLoc, 30.0f, 50.0f, 30.0f);
glUniform3fv(viewPosLoc, 1, glm::value_ptr(camPos));
glEnable(GL_DEPTH_TEST);
while (!glfwWindowShouldClose(win)) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES,
static_cast<GLsizei>(indices.size()),
GL_UNSIGNED_INT, nullptr);
glfwSwapBuffers(win);
glfwPollEvents();
}
glfwTerminate();
return 0;
}
// main.cpp
// TerraVoxel: voxel terrain without <iostream>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/noise.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <thread>
#include <chrono>
// Window dimensions
const unsigned int WIN_W = 1280;
const unsigned int WIN_H = 720;
// Size of the giant cube in world units
const float WORLD_SIZE = 7880.0f;
// Number of voxels per side (adjust for performance)
const int RESOLUTION = 200;
// Noise parameters
const float NOISE_SCALE = 0.0015f;
const float NOISE_AMPLITUDE = 200.0f;
const float BASE_HEIGHT = 50.0f;
// Color thresholds
const float GRASS_H = 80.0f;
const float ROCK_H = 160.0f;
// Simple AABB for collisions
struct AABB {
glm::vec3 min, max;
};
std::vector<AABB> collisionBoxes;
// Mesh data
std::vector<float> vertices; // x,y,z, nx,ny,nz, r,g,b
std::vector<unsigned int> indices;
// Cube face definitions
static const int FACE_IDX[6][4] = {
{0,1,2,3}, {4,5,6,7}, {1,5,6,2},
{0,4,7,3}, {3,2,6,7}, {0,1,5,4}
};
static const glm::vec3 FACE_NORMALS[6] = {
{ 0, 0, 1}, { 0, 0, -1},
{ 1, 0, 0}, {-1, 0, 0},
{ 0, 1, 0}, { 0,-1, 0}
};
static const glm::vec3 CUBE_VERTS[8] = {
{-0.5f,-0.5f,-0.5f},{ 0.5f,-0.5f,-0.5f},
{ 0.5f, 0.5f,-0.5f},{-0.5f, 0.5f,-0.5f},
{-0.5f,-0.5f, 0.5f},{ 0.5f,-0.5f, 0.5f},
{ 0.5f, 0.5f, 0.5f},{-0.5f, 0.5f, 0.5f}
};
// Add one colored cube at 'center', size 's'
void addCube(const glm::vec3& center, float s, const glm::vec3& color) {
glm::vec3 half = glm::vec3(s * 0.5f);
unsigned int baseIndex = vertices.size() / 9;
// Build vertices per face
for (int f = 0; f < 6; ++f) {
glm::vec3 normal = FACE_NORMALS[f];
int i0 = FACE_IDX[f][0], i1 = FACE_IDX[f][1],
i2 = FACE_IDX[f][2], i3 = FACE_IDX[f][3];
glm::vec3
// continuation of main.cpp
// Push one cube into the global mesh and collision list
void addCube(const glm::vec3& center, float s, const glm::vec3& color) {
glm::vec3 half = glm::vec3(s * 0.5f);
unsigned int startIndex = vertices.size() / 9;
// For each of the 6 faces
for (int f = 0; f < 6; ++f) {
glm::vec3 normal = FACE_NORMALS[f];
int i0 = FACE_IDX[f][0],
i1 = FACE_IDX[f][1],
i2 = FACE_IDX[f][2],
i3 = FACE_IDX[f][3];
// Push 4 verts: position, normal, color
glm::vec3 p0 = center + half * CUBE_VERTS[i0];
glm::vec3 p1 = center + half * CUBE_VERTS[i1];
glm::vec3 p2 = center + half * CUBE_VERTS[i2];
glm::vec3 p3 = center + half * CUBE_VERTS[i3];
for (auto& p : {p0, p1, p2, p3}) {
vertices.push_back(p.x);
vertices.push_back(p.y);
vertices.push_back(p.z);
vertices.push_back(normal.x);
vertices.push_back(normal.y);
vertices.push_back(normal.z);
vertices.push_back(color.r);
vertices.push_back(color.g);
vertices.push_back(color.b);
}
// Two triangles per face
indices.push_back(startIndex + 0);
indices.push_back(startIndex + 1);
indices.push_back(startIndex + 2);
indices.push_back(startIndex + 0);
indices.push_back(startIndex + 2);
indices.push_back(startIndex + 3);
startIndex += 4;
}
// Add collision AABB
AABB box;
box.min = center - half;
box.max = center + half;
collisionBoxes.push_back(box);
}
// Compile a single shader
GLuint compileShader(GLenum type, const char* src) {
GLuint sh = glCreateShader(type);
glShaderSource(sh, 1, &src, nullptr);
glCompileShader(sh);
GLint ok = 0;
glGetShaderiv(sh, GL_COMPILE_STATUS, &ok);
if (!ok) std::exit(EXIT_FAILURE);
return sh;
}
// Link vertex and fragment into a program
GLuint makeProgram(const char* vsSrc, const char* fsSrc) {
GLuint vs = compileShader(GL_VERTEX_SHADER, vsSrc);
GLuint fs = compileShader(GL_FRAGMENT_SHADER, fsSrc);
GLuint prog = glCreateProgram();
glAttachShader(prog, vs);
glAttachShader(prog, fs);
glLinkProgram(prog);
GLint ok = 0;
glGetProgramiv(prog, GL_LINK_STATUS, &ok);
if (!ok) std::exit(EXIT_FAILURE);
glDeleteShader(vs);
glDeleteShader(fs);
return prog;
}
// Simple GLSL shaders
const char* vertexShaderSrc = R"GLSL(
#version 330 core
layout(location=0) in vec3 aPos;
layout(location=1) in vec3 aNormal;
layout(location=2) in vec3 aColor;
uniform mat4 uMVP;
out vec3 vColor;
void main() {
vColor = aColor;
gl_Position = uMVP * vec4(aPos, 1.0);
}
)GLSL";
const char* fragmentShaderSrc = R"GLSL(
#version 330 core
in vec3 vColor;
out vec4 FragColor;
void main() {
FragColor = vec4(vColor, 1.0);
}
)GLSL";
int main() {
// Initialize GLFW
if (!glfwInit()) return EXIT_FAILURE;
// Request OpenGL 3.3 core
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GLFWwindow* win = glfwCreateWindow(WIN_W, WIN_H, "TerraVoxel", nullptr, nullptr);
if (!win) { glfwTerminate(); return EXIT_FAILURE; }
glfwMakeContextCurrent(win);
// Load GL functions
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) std::exit(EXIT_FAILURE);
// Lock FPS: use swap interval 1 or 2 depending on refresh rate
const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
int interval = (mode->refreshRate >= 60 ? 1 : 2);
glfwSwapInterval(interval);
glEnable(GL_DEPTH_TEST);
// Generate terrain
float step = WORLD_SIZE / RESOLUTION;
float halfWorld = WORLD_SIZE * 0.5f;
srand((unsigned)time(nullptr));
for (int x = 0; x < RESOLUTION; ++x) {
for (int z = 0; z < RESOLUTION; ++z) {
float wx = -halfWorld + x * step + step * 0.5f;
float wz = -halfWorld + z * step + step * 0.5f;
float n = glm::perlin(glm::vec2(wx, wz) * NOISE_SCALE);
float h = BASE_HEIGHT + n * NOISE_AMPLITUDE;
glm::vec3 col;
if (h < GRASS_H) col = glm::vec3(0.1f, 0.8f, 0.1f);
else if (h < ROCK_H) col = glm::vec3(0.5f, 0.4f, 0.3f);
else col = glm::vec3(0.6f, 0.6f, 0.6f);
// center y is half the cube height
glm::vec3 center(wx, h * 0.5f, wz);
addCube(center, step, col);
}
}
// Upload mesh to GPU
GLuint vao, vbo, ebo;
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
glGenBuffers(1, &ebo);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER,
vertices.size() * sizeof(float),
vertices.data(),
GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
indices.size() * sizeof(unsigned int),
indices.data(),
GL_STATIC_DRAW);
// layout: 0=pos,1=normal,2=color
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(float),
(void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(float),
(void*)(6 * sizeof(float)));
glEnableVertexAttribArray(2);
GLuint shaderProg = makeProgram(vertexShaderSrc, fragmentShaderSrc);
glUseProgram(shaderProg);
// Uniform location
GLint uMVPLoc = glGetUniformLocation(shaderProg, "uMVP");
// Main render loop
while (!glfwWindowShouldClose(win)) {
glClearColor(0.53f, 0.81f, 0.92f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Camera matrices
float ratio = float(WIN_W) / float(WIN_H);
glm::mat4 proj = glm::perspective(glm::radians(45.0f), ratio, 0.1f, 20000.0f);
glm::mat4 view = glm::lookAt(glm::vec3(0, 500, 1500),
glm::vec3(0, 0, 0),
glm::vec3(0, 1, 0));
glm::mat4 model = glm::mat4(1.0f);
glm::mat4 mvp = proj * view * model;
glUniformMatrix4fv(uMVPLoc, 1, GL_FALSE, &mvp[0][0]);
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, (GLsizei)indices.size(), GL_UNSIGNED_INT, 0);
glfwSwapBuffers(win);
glfwPollEvents();
}
glfwTerminate();
return EXIT_SUCCESS;
}
```[43dcd9a7-70db-4a1f-b0ae-981daa162054](https://github.com/menandro/opensor/tree/959353155150cb15e37e93105d1e5c5166745f0a/opensor_viewer%2FCgObject.cpp?citationMarker=43dcd9a7-70db-4a1f-b0ae-981daa162054&citationId=1&citationId=2&citationId=3 "github.com")
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <cmath>
// Vertex structure
struct Vertex {
float position[3];
float normal[3];
};
// Shader sources
const char* vertexShaderSource = R"glsl(
#version 330 core
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec3 aNormal;
out vec3 FragPos;
out vec3 Normal;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main() {
FragPos = vec3(model * vec4(aPos, 1.0));
Normal = mat3(transpose(inverse(model))) * aNormal;
gl_Position = projection * view * vec4(FragPos, 1.0);
}
)glsl";
const char* fragmentShaderSource = R"glsl(
#version 330 core
in vec3 FragPos;
in vec3 Normal;
out vec4 FragColor;
uniform vec3 lightPos;
uniform vec3 viewPos;
uniform vec3 lightColor;
uniform vec3 objectColor;
void main() {
// Ambient
float ambientStrength = 0.3;
vec3 ambient = ambientStrength * lightColor;
// Diffuse
vec3 norm = normalize(Normal);
vec3 lightDir = normalize(lightPos - FragPos);
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = diff * lightColor;
// Specular
float specularStrength = 0.2;
vec3 viewDir = normalize(viewPos - FragPos);
vec3 reflectDir = reflect(-lightDir, norm);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), 32);
vec3 specular = specularStrength * spec * lightColor;
// Combine
vec3 result = (ambient + diffuse + specular) * objectColor;
FragColor = vec4(result, 1.0);
}
)glsl";
// Shader compilation
GLuint compileShader(GLenum type, const char* source) {
GLuint shader = glCreateShader(type);
glShaderSource(shader, 1, &source, nullptr);
glCompileShader(shader);
return shader;
}
GLuint createShaderProgram() {
GLuint vertexShader = compileShader(GL_VERTEX_SHADER, vertexShaderSource);
GLuint fragmentShader = compileShader(GL_FRAGMENT_SHADER, fragmentShaderSource);
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
return shaderProgram;
}
// Setup lighting and model
void setupScene(GLuint shaderProgram) {
glUseProgram(shaderProgram);
GLint lightPosLoc = glGetUniformLocation(shaderProgram, "lightPos");
GLint viewPosLoc = glGetUniformLocation(shaderProgram, "viewPos");
GLint lightColorLoc = glGetUniformLocation(shaderProgram, "lightColor");
GLint objectColorLoc = glGetUniformLocation(shaderProgram, "objectColor");
glUniform3f(lightPosLoc, 1.2f, 1.0f, 2.0f);
glUniform3f(viewPosLoc, 0.0f, 0.0f, 3.0f);
glUniform3f(lightColorLoc, 1.0f, 1.0f, 1.0f);
glUniform3f(objectColorLoc, 0.6f, 0.6f, 0.6f);
}
// Main rendering loop
void renderLoop(GLFWwindow* window, GLuint VAO, GLuint shaderProgram) {
while (!glfwWindowShouldClose(window)) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(shaderProgram);
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
glfwSwapBuffers(window);
glfwPollEvents();
}
}
// Entry point
int main() {
glfwInit();
GLFWwindow* window = glfwCreateWindow(800, 600, "Smooth Lighting", nullptr, nullptr);
glfwMakeContextCurrent(window);
glewInit();
glEnable(GL_DEPTH_TEST);
GLuint shaderProgram = createShaderProgram();
setupScene(shaderProgram);
// Setup geometry (cube example)
Vertex vertices[] = {
// Define cube vertices with normals here...
};
GLuint VAO, VBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(float) * 3));
glEnableVertexAttribArray(1);
renderLoop(window, VAO, shaderProgram);
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glfwTerminate();
return 0;
}