-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
364 lines (307 loc) · 14.5 KB
/
Copy pathmain.cpp
File metadata and controls
364 lines (307 loc) · 14.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
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <cmath>
#include <cstdio>
#include <cstddef> // offsetof
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
// ── Minimal math ──────────────────────────────────────────────────────────────
static const float PI = 3.14159265358979f;
struct vec3 {
float x = 0, y = 0, z = 0;
vec3() = default;
vec3(float x, float y, float z) : x(x), y(y), z(z) {}
vec3 operator+(const vec3& b) const { return {x+b.x, y+b.y, z+b.z}; }
vec3 operator-(const vec3& b) const { return {x-b.x, y-b.y, z-b.z}; }
vec3 operator*(float t) const { return {x*t, y*t, z*t}; }
};
static float dot(vec3 a, vec3 b) { return a.x*b.x + a.y*b.y + a.z*b.z; }
static float vlen(vec3 v) { return sqrtf(dot(v, v)); }
static vec3 normalize(vec3 v) { return v * (1.f / vlen(v)); }
static vec3 cross(vec3 a, vec3 b) {
return { a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x };
}
// Column-major 4x4 matrix: element (row r, col c) lives at m[c*4 + r]
struct mat4 {
float m[16] = {};
float& at(int r, int c) { return m[c*4+r]; }
float at(int r, int c) const { return m[c*4+r]; }
};
static mat4 identity() {
mat4 r;
r.at(0,0) = r.at(1,1) = r.at(2,2) = r.at(3,3) = 1.f;
return r;
}
static mat4 perspective(float fovy, float aspect, float zn, float zf) {
mat4 r;
float f = 1.f / tanf(fovy * 0.5f);
r.at(0,0) = f / aspect;
r.at(1,1) = f;
r.at(2,2) = (zf + zn) / (zn - zf);
r.at(3,2) = -1.f;
r.at(2,3) = (2.f * zf * zn) / (zn - zf);
return r;
}
static mat4 lookAt(vec3 eye, vec3 center, vec3 up) {
vec3 f = normalize(center - eye);
vec3 s = normalize(cross(f, up));
vec3 u = cross(s, f);
mat4 r;
r.at(0,0) = s.x; r.at(0,1) = s.y; r.at(0,2) = s.z; r.at(0,3) = -dot(s, eye);
r.at(1,0) = u.x; r.at(1,1) = u.y; r.at(1,2) = u.z; r.at(1,3) = -dot(u, eye);
r.at(2,0) = -f.x; r.at(2,1) = -f.y; r.at(2,2) = -f.z; r.at(2,3) = dot(f, eye);
r.at(3,3) = 1.f;
return r;
}
// ── Sphere geometry ───────────────────────────────────────────────────────────
struct Vertex { float pos[3], norm[3], uv[2], tangent[3]; };
static void buildSphere(int stacks, int sectors,
std::vector<Vertex>& verts, std::vector<unsigned>& idx)
{
for (int i = 0; i <= stacks; ++i) {
float phi = PI * i / stacks; // 0 -> π (top -> bottom)
for (int j = 0; j <= sectors; ++j) {
float theta = 2.f * PI * j / sectors;
float x = sinf(phi) * cosf(theta);
float y = cosf(phi);
float z = sinf(phi) * sinf(theta);
Vertex v;
v.pos[0] = x; v.pos[1] = y; v.pos[2] = z;
v.norm[0] = x; v.norm[1] = y; v.norm[2] = z; // unit sphere: pos == normal
v.uv[0] = (float)j / sectors;
v.uv[1] = (float)i / stacks;
// Tangent: dPos/dTheta normalised = (-sinθ, 0, cosθ)
v.tangent[0] = -sinf(theta);
v.tangent[1] = 0.f;
v.tangent[2] = cosf(theta);
verts.push_back(v);
}
}
for (int i = 0; i < stacks; ++i) {
for (int j = 0; j < sectors; ++j) {
unsigned a = i * (sectors+1) + j;
unsigned b = a + sectors + 1;
idx.push_back(a); idx.push_back(a+1); idx.push_back(b);
idx.push_back(b); idx.push_back(a+1); idx.push_back(b+1);
}
}
}
// ── Shader helpers ────────────────────────────────────────────────────────────
static std::string readFile(const char* path) {
std::ifstream f(path);
if (!f) { fprintf(stderr, "Cannot open shader: %s\n", path); return ""; }
std::ostringstream ss;
ss << f.rdbuf();
return ss.str();
}
static GLuint compileShader(GLenum type, const char* src) {
GLuint s = glCreateShader(type);
glShaderSource(s, 1, &src, nullptr);
glCompileShader(s);
GLint ok;
glGetShaderiv(s, GL_COMPILE_STATUS, &ok);
if (!ok) {
char log[1024];
glGetShaderInfoLog(s, sizeof(log), nullptr, log);
fprintf(stderr, "Shader compile error:\n%s\n", log);
}
return s;
}
static GLuint createProgram(const char* vertPath, const char* fragPath) {
std::string vs = readFile(vertPath);
std::string fs = readFile(fragPath);
GLuint vert = compileShader(GL_VERTEX_SHADER, vs.c_str());
GLuint frag = compileShader(GL_FRAGMENT_SHADER, fs.c_str());
GLuint prog = glCreateProgram();
glAttachShader(prog, vert);
glAttachShader(prog, frag);
glLinkProgram(prog);
GLint ok;
glGetProgramiv(prog, GL_LINK_STATUS, &ok);
if (!ok) {
char log[1024];
glGetProgramInfoLog(prog, sizeof(log), nullptr, log);
fprintf(stderr, "Program link error:\n%s\n", log);
}
glDeleteShader(vert);
glDeleteShader(frag);
return prog;
}
// ── Texture loader ────────────────────────────────────────────────────────────
static GLuint loadTexture(const char* path, bool srgb) {
int w, h, ch;
stbi_set_flip_vertically_on_load(true);
unsigned char* data = stbi_load(path, &w, &h, &ch, 0);
if (!data) { fprintf(stderr, "Cannot load texture: %s\n", path); return 0; }
GLenum fmt = (ch == 4) ? GL_RGBA : (ch == 3) ? GL_RGB : GL_RED;
GLenum internalFmt = (ch == 4) ? (srgb ? GL_SRGB_ALPHA : GL_RGBA)
: (ch == 3) ? (srgb ? GL_SRGB : GL_RGB)
: GL_R8;
GLuint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, internalFmt, w, h, 0, fmt, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_image_free(data);
return tex;
}
static float camYaw = 0.5f;
static float camPitch = 0.4f;
static float camRadius = 4.0f;
static double lastX = 0, lastY = 0;
static bool dragging = false;
static void cb_mouseButton(GLFWwindow* win, int btn, int action, int) {
if (btn == GLFW_MOUSE_BUTTON_LEFT) {
dragging = (action == GLFW_PRESS);
if (dragging) glfwGetCursorPos(win, &lastX, &lastY);
}
}
static void cb_cursorPos(GLFWwindow*, double x, double y) {
if (dragging) {
camYaw += (float)(x - lastX) * 0.01f;
camPitch += (float)(y - lastY) * 0.01f;
// Clamp pitch to avoid gimbal lock near poles
if (camPitch > 1.4f) camPitch = 1.4f;
if (camPitch < -1.4f) camPitch = -1.4f;
}
lastX = x; lastY = y;
}
static void cb_scroll(GLFWwindow*, double, double dy) {
camRadius -= (float)dy * 0.3f;
if (camRadius < 1.5f) camRadius = 1.5f;
if (camRadius > 12.f) camRadius = 12.f;
}
// ── Main ──────────────────────────────────────────────────────────────────────
int main() {
if (!glfwInit()) { fprintf(stderr, "glfwInit failed\n"); return 1; }
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_SAMPLES, 4); // 4x MSAA
GLFWwindow* win = glfwCreateWindow(1280, 720, "PBR Demo", nullptr, nullptr);
if (!win) { fprintf(stderr, "Window creation failed\n"); glfwTerminate(); return 1; }
glfwMakeContextCurrent(win);
glfwSwapInterval(1); // vsync
glfwSetMouseButtonCallback(win, cb_mouseButton);
glfwSetCursorPosCallback(win, cb_cursorPos);
glfwSetScrollCallback(win, cb_scroll);
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK) { fprintf(stderr, "glewInit failed\n"); return 1; }
glEnable(GL_DEPTH_TEST);
glEnable(GL_MULTISAMPLE);
// ── Build sphere GPU buffers ──────────────────────────────────────────────
std::vector<Vertex> verts;
std::vector<unsigned> idx;
buildSphere(64, 64, verts, idx);
GLuint VAO, VBO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER,
(GLsizeiptr)(verts.size() * sizeof(Vertex)),
verts.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
(GLsizeiptr)(idx.size() * sizeof(unsigned)),
idx.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
(void*)offsetof(Vertex, pos));
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
(void*)offsetof(Vertex, norm));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex),
(void*)offsetof(Vertex, uv));
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
(void*)offsetof(Vertex, tangent));
glBindVertexArray(0);
// ── Compile shaders ───────────────────────────────────────────────────────
GLuint prog = createProgram("pbr.vert", "pbr.frag");
// ── Load PBR textures ─────────────────────────────────────────────────────
// Albedo is sRGB; normal/metallic/roughness are linear data.
GLuint texAlbedo = loadTexture("rusted_metal_albedo.png", true);
GLuint texNormal = loadTexture("rusted_metal_normal.png", false);
GLuint texMetallic = loadTexture("rusted_metal_metallic.png", false);
GLuint texRoughness = loadTexture("rusted_metal_roughness.png", false);
glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texAlbedo);
glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texNormal);
glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, texMetallic);
glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, texRoughness);
// ── Single point light ────────────────────────────────────────────────────
const float lightPos[3] = { 5.f, 5.f, 5.f };
const float lightCol[3] = { 300.f, 300.f, 300.f };
// Upload uniforms that never change
glUseProgram(prog);
glUniform1i(glGetUniformLocation(prog, "texAlbedo"), 0);
glUniform1i(glGetUniformLocation(prog, "texNormal"), 1);
glUniform1i(glGetUniformLocation(prog, "texMetallic"), 2);
glUniform1i(glGetUniformLocation(prog, "texRoughness"), 3);
glUniform3fv(glGetUniformLocation(prog, "lightPosition"), 1, lightPos);
glUniform3fv(glGetUniformLocation(prog, "lightColor"), 1, lightCol);
mat4 model = identity();
glUniformMatrix4fv(glGetUniformLocation(prog, "model"), 1, GL_FALSE, model.m);
// Normal matrix = transpose(inverse(model 3x3)).
// For identity/rotation this equals the model 3x3 directly (since R^{-T} = R).
// NOTE: would need a proper matrix inverse for non-uniform scaling.
float nm[9] = {
model.at(0,0), model.at(1,0), model.at(2,0),
model.at(0,1), model.at(1,1), model.at(2,1),
model.at(0,2), model.at(1,2), model.at(2,2),
};
glUniformMatrix3fv(glGetUniformLocation(prog, "normalMatrix"), 1, GL_FALSE, nm);
// Cache per-frame uniform locations
GLint locView = glGetUniformLocation(prog, "view");
GLint locProj = glGetUniformLocation(prog, "projection");
GLint locCamPos = glGetUniformLocation(prog, "camPos");
// ── Render loop ───────────────────────────────────────────────────────────
while (!glfwWindowShouldClose(win)) {
glfwPollEvents();
if (glfwGetKey(win, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(win, GLFW_TRUE);
int w, h;
glfwGetFramebufferSize(win, &w, &h);
if (w == 0 || h == 0) { glfwSwapBuffers(win); continue; }
glViewport(0, 0, w, h);
glClearColor(0.08f, 0.08f, 0.08f, 1.f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Camera position from spherical coordinates
vec3 camPos = {
camRadius * cosf(camPitch) * sinf(camYaw),
camRadius * sinf(camPitch),
camRadius * cosf(camPitch) * cosf(camYaw)
};
mat4 view = lookAt(camPos, {0.f, 0.f, 0.f}, {0.f, 1.f, 0.f});
mat4 proj = perspective(0.7854f /*45°*/, (float)w / (float)h, 0.1f, 100.f);
glUseProgram(prog);
glUniformMatrix4fv(locView, 1, GL_FALSE, view.m);
glUniformMatrix4fv(locProj, 1, GL_FALSE, proj.m);
glUniform3f(locCamPos, camPos.x, camPos.y, camPos.z);
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, (GLsizei)idx.size(), GL_UNSIGNED_INT, nullptr);
glBindVertexArray(0);
glfwSwapBuffers(win);
}
// ── Cleanup ───────────────────────────────────────────────────────────────
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &EBO);
glDeleteTextures(1, &texAlbedo);
glDeleteTextures(1, &texNormal);
glDeleteTextures(1, &texMetallic);
glDeleteTextures(1, &texRoughness);
glDeleteProgram(prog);
glfwTerminate();
return 0;
}