diff --git a/CMakeLists.txt b/CMakeLists.txt index ae113a6..3947347 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -24,7 +24,9 @@ add_executable(game src/window.cc src/gl_debug.cc src/buffer.cc - src/mesh.cc) + src/mesh.cc + src/file_util.cc + src/shader.cc) target_include_directories(game PRIVATE src external/stb external/linalg) target_link_libraries(game PRIVATE glad glfw) diff --git a/shaders/shapes.frag b/shaders/shapes.frag new file mode 100644 index 0000000..571e5fd --- /dev/null +++ b/shaders/shapes.frag @@ -0,0 +1,13 @@ +#version 460 core +in vec3 vColor; + +uniform float uTime; // 秒 / seconds +uniform vec3 uTint; // 図形ごとの色 / per-shape colour + +layout(location = 0) out vec4 out_color; + +void main() { + // 画面を左から右へ流れる明るさの波 / a wave of brightness moving across the screen + float wave = 0.75 + 0.25 * sin(uTime * 3.0 - gl_FragCoord.x * 0.02); + out_color = vec4(vColor * uTint * wave, 1.0); +} diff --git a/shaders/shapes.vert b/shaders/shapes.vert new file mode 100644 index 0000000..1d98468 --- /dev/null +++ b/shaders/shapes.vert @@ -0,0 +1,12 @@ +#version 460 core +layout(location = 0) in vec3 aPosition; +layout(location = 1) in vec3 aColor; + +uniform vec2 uOffset; // NDCでの移動量 / offset in NDC + +out vec3 vColor; + +void main() { + vColor = aColor; + gl_Position = vec4(aPosition.xy + uOffset, aPosition.z, 1.0); +} diff --git a/src/file_util.cc b/src/file_util.cc new file mode 100644 index 0000000..8bf1201 --- /dev/null +++ b/src/file_util.cc @@ -0,0 +1,13 @@ +#include "file_util.hh" + +#include +#include + +std::optional readTextFile(const std::string &path) { + // バイナリモード:Windowsで改行が変換されないように / binary mode: no newline conversion on Windows + std::ifstream file(path, std::ios::binary); + if (!file) return std::nullopt; + std::ostringstream text; + text << file.rdbuf(); + return text.str(); +} diff --git a/src/file_util.hh b/src/file_util.hh new file mode 100644 index 0000000..c7bd487 --- /dev/null +++ b/src/file_util.hh @@ -0,0 +1,9 @@ +// ファイルの読み込み / reading files +#pragma once + +#include +#include + +// ファイル全体を文字列として読む。開けなければstd::nullopt。 +// Reads a whole file into a string. std::nullopt if it cannot be opened. +std::optional readTextFile(const std::string &path); diff --git a/src/main.cc b/src/main.cc index 4d7fc86..57a8330 100644 --- a/src/main.cc +++ b/src/main.cc @@ -1,8 +1,12 @@ -// 第4章:頂点属性とインデックスバッファ -// Chapter 4: vertex attributes and index buffers +// 第5章:シェーダークラスとユニフォーム +// Chapter 5: a shader class and uniforms // -// 操作 / Controls: P ワイヤーフレーム切り替え / toggle wireframe, Esc 終了 / quit +// 操作 / Controls: +// R シェーダーを読み直す / reload the shaders +// P ワイヤーフレーム切り替え / toggle wireframe +// Esc 終了 / quit #include "mesh.hh" +#include "shader.hh" #include "window.hh" #include @@ -10,6 +14,7 @@ #include #include #include +#include #include // 位置と色を交互に並べた(インターリーブ)頂点 / a vertex with position and colour interleaved @@ -24,67 +29,6 @@ constexpr VertexAttrib kColorVertexLayout[] = { {1, 3, offsetof(ColorVertex, color)}, // layout(location = 1) in vec3 aColor }; -static const char *kVertexShader = R"(#version 460 core -layout(location = 0) in vec3 aPosition; -layout(location = 1) in vec3 aColor; - -out vec3 vColor; // フラグメントシェーダーへ(補間される) / to the fragment shader (interpolated) - -void main() { - vColor = aColor; - gl_Position = vec4(aPosition, 1.0); -} -)"; - -static const char *kFragmentShader = R"(#version 460 core -in vec3 vColor; -layout(location = 0) out vec4 out_color; - -void main() { - out_color = vec4(vColor, 1.0); -} -)"; - -static GLuint compileShader(GLenum type, const char *source) { - GLuint shader = glCreateShader(type); - glShaderSource(shader, 1, &source, nullptr); - glCompileShader(shader); - - GLint ok = 0; - glGetShaderiv(shader, GL_COMPILE_STATUS, &ok); - if (!ok) { - char log[2048]; - glGetShaderInfoLog(shader, sizeof log, nullptr, log); - fprintf(stderr, "%sシェーダーのエラー / %s shader error:\n%s\n", type == GL_VERTEX_SHADER ? "頂点" : "フラグメント", - type == GL_VERTEX_SHADER ? "vertex" : "fragment", log); - glDeleteShader(shader); - return 0; - } - return shader; -} - -static GLuint linkProgram(GLuint vertexShader, GLuint fragmentShader) { - GLuint program = glCreateProgram(); - glAttachShader(program, vertexShader); - glAttachShader(program, fragmentShader); - glLinkProgram(program); - glDetachShader(program, vertexShader); - glDetachShader(program, fragmentShader); - glDeleteShader(vertexShader); - glDeleteShader(fragmentShader); - - GLint ok = 0; - glGetProgramiv(program, GL_LINK_STATUS, &ok); - if (!ok) { - char log[2048]; - glGetProgramInfoLog(program, sizeof log, nullptr, log); - fprintf(stderr, "リンクエラー / link error:\n%s\n", log); - glDeleteProgram(program); - return 0; - } - return program; -} - // NDCは横に引き伸ばされる(1280×720)ので、計算で作る図形はxを縮める。第8章で投影行列が解決する。 // NDC is stretched horizontally (1280×720), so generated shapes shrink x. Chapter 8's projection fixes this. constexpr float kAspectFix = 720.0f / 1280.0f; @@ -152,12 +96,21 @@ static Mesh makeRibbon(Vec2 center) { int main() { Window window; - if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 4")) return 1; + if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 5")) return 1; + + // シェーダーはファイルから読む(作業ディレクトリ=プロジェクトのルート) + // shaders are read from files (working directory = project root) + std::optional shader = Shader::load("shaders/shapes.vert", "shaders/shapes.frag"); + if (!shader) return 1; bool wireframe = false; window.onKey = [&](int key, int action, int /*mods*/) { if (action != GLFW_PRESS) return; if (key == GLFW_KEY_ESCAPE) window.close(); + if (key == GLFW_KEY_R) { + // 失敗しても古いシェーダーで描き続ける / on failure we keep drawing with the old shader + if (shader->reload()) printf("シェーダーを読み直した / shaders reloaded\n"); + } if (key == GLFW_KEY_P) { wireframe = !wireframe; // 三角形を線で描く(デバッグに便利) / draw triangles as lines (handy for debugging) @@ -193,12 +146,6 @@ int main() { Mesh star = makeStar({0.0f, -0.45f}, 0.3f); Mesh ribbon = makeRibbon({0.6f, -0.45f}); - GLuint vs = compileShader(GL_VERTEX_SHADER, kVertexShader); - GLuint fs = compileShader(GL_FRAGMENT_SHADER, kFragmentShader); - if (!vs || !fs) return 1; - GLuint program = linkProgram(vs, fs); - if (!program) return 1; - glPointSize(10.0f); // GL_POINTSの大きさ(ピクセル) / size of GL_POINTS in pixels while (!window.shouldClose()) { @@ -207,17 +154,33 @@ int main() { glClearColor(0.10f, 0.15f, 0.25f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); - glUseProgram(program); + float t = static_cast(window.time()); + const Vec3 white = {1.0f, 1.0f, 1.0f}; + + shader->use(); + // フレームに一回:全ての描画で同じ値 / once per frame: the same value for every draw + shader->set("uTime", t); + + // 描画ごと:ユニフォームは次に変えるまでプログラムに残る + // per draw: a uniform keeps its value in the program until we change it + shader->set("uOffset", Vec2{0.0f, 0.0f}); + shader->set("uTint", white); triangle.draw(); - quad.draw(); - hexagon.draw(); points.draw(); star.draw(); ribbon.draw(); + // 四角形:色が白とオレンジの間で変わる / the quad: colour moves between white and orange + float pulse = 0.5f + 0.5f * std::sin(t * 2.0f); + shader->set("uTint", lerp(white, Vec3{1.0f, 0.5f, 0.1f}, pulse)); + quad.draw(); + + // 六角形:上下に揺れる / the hexagon bobs up and down + shader->set("uTint", white); + shader->set("uOffset", Vec2{0.0f, 0.1f * std::sin(t * 3.0f)}); + hexagon.draw(); + window.swapBuffers(); } - - glDeleteProgram(program); - return 0; // メッシュはここで自動的に削除される / the meshes are deleted automatically here + return 0; // シェーダーとメッシュはここで自動的に削除される / the shader and meshes are deleted automatically here } diff --git a/src/shader.cc b/src/shader.cc new file mode 100644 index 0000000..ec12940 --- /dev/null +++ b/src/shader.cc @@ -0,0 +1,181 @@ +#include "shader.hh" + +#include "file_util.hh" + +#include +#include +#include + +// コンパイラのログの一行から行番号を探し、位置の部分を取り除いたメッセージをmessageに入れる。行番号がなければ0。 +// Mesa: "0:12(5): error: ..." +// NVIDIA: "0(12) : error C1008: ..." +// AMD/Intel: "ERROR: 0:12: ..." +// Finds the line number in one line of the compiler log and stores the message without the location +// in message. Returns 0 if there is no line number. +static int parseLogLine(std::string_view line, std::string &message) { + for (size_t i = 0; i + 2 < line.size(); ++i) { + bool startOk = (i == 0 || line[i - 1] == ' '); + if (!startOk || line[i] != '0' || (line[i + 1] != ':' && line[i + 1] != '(')) continue; + int number = 0; + size_t j = i + 2; + while (j < line.size() && line[j] >= '0' && line[j] <= '9') number = number * 10 + (line[j++] - '0'); + if (j == i + 2) continue; + size_t rest = line.find(": ", j); // 位置の後の「: 」 / the ": " after the location + rest = rest == std::string_view::npos ? j : rest + 2; + message = std::string(line.substr(0, i)) + std::string(line.substr(rest)); + return number; + } + message = std::string(line); + return 0; +} + +// ソースのn行目(1始まり) / line n of the source (1-based) +static std::string_view sourceLine(std::string_view source, int n) { + size_t start = 0; + for (int i = 1; i < n; ++i) { + start = source.find('\n', start); + if (start == std::string_view::npos) return {}; + ++start; + } + size_t end = source.find('\n', start); + return source.substr(start, end == std::string_view::npos ? std::string_view::npos : end - start); +} + +// エラーを「ファイル:行: メッセージ」の形で表示し、その行のソースも見せる +// Prints errors as "file:line: message" and shows that source line +static void printShaderLog(const std::string &path, std::string_view source, std::string_view log) { + while (!log.empty()) { + size_t end = log.find('\n'); + std::string_view line = log.substr(0, end); + log = end == std::string_view::npos ? std::string_view{} : log.substr(end + 1); + if (line.empty()) continue; + + std::string message; + int n = parseLogLine(line, message); + if (n > 0) { + std::string_view code = sourceLine(source, n); + fprintf(stderr, "%s:%d: %s\n %4d | %.*s\n", path.c_str(), n, message.c_str(), n, static_cast(code.size()), + code.data()); + } else { + fprintf(stderr, "%s: %s\n", path.c_str(), message.c_str()); + } + } +} + +// 一つのステージ(頂点・フラグメント…)をファイルからコンパイル。失敗したら0。 +// Compiles one stage (vertex, fragment, ...) from a file. Returns 0 on failure. +static GLuint compileStage(GLenum type, const std::string &path) { + std::optional source = readTextFile(path); + if (!source) { + fprintf(stderr, "%s: 開けない / cannot open (プロジェクトのルートから実行した? / running from the project root?)\n", + path.c_str()); + return 0; + } + GLuint shader = glCreateShader(type); + const char *text = source->c_str(); + glShaderSource(shader, 1, &text, nullptr); + glCompileShader(shader); + + GLint ok = 0; + glGetShaderiv(shader, GL_COMPILE_STATUS, &ok); + if (!ok) { + GLint length = 0; + glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length); + std::string log(static_cast(length > 1 ? length : 1), '\0'); + glGetShaderInfoLog(shader, length, nullptr, log.data()); + printShaderLog(path, *source, log.c_str()); + glDeleteShader(shader); + return 0; + } + return shader; +} + +// 頂点とフラグメントをリンク。失敗したら0。 / links a vertex and a fragment shader. Returns 0 on failure. +static GLuint buildProgram(const std::string &vertexPath, const std::string &fragmentPath) { + GLuint vs = compileStage(GL_VERTEX_SHADER, vertexPath); + GLuint fs = compileStage(GL_FRAGMENT_SHADER, fragmentPath); + if (!vs || !fs) { + glDeleteShader(vs); // 0は無視される / 0 is silently ignored + glDeleteShader(fs); + return 0; + } + GLuint program = glCreateProgram(); + glAttachShader(program, vs); + glAttachShader(program, fs); + glLinkProgram(program); + glDetachShader(program, vs); + glDetachShader(program, fs); + glDeleteShader(vs); + glDeleteShader(fs); + + GLint ok = 0; + glGetProgramiv(program, GL_LINK_STATUS, &ok); + if (!ok) { + char log[4096]; + glGetProgramInfoLog(program, sizeof log, nullptr, log); + fprintf(stderr, "%s + %s: リンクエラー / link error:\n%s\n", vertexPath.c_str(), fragmentPath.c_str(), log); + glDeleteProgram(program); + return 0; + } + return program; +} + +std::optional Shader::load(const std::string &vertexPath, const std::string &fragmentPath) { + GLuint program = buildProgram(vertexPath, fragmentPath); + if (!program) return std::nullopt; + Shader shader; + shader.program = program; + shader.vertexPath = vertexPath; + shader.fragmentPath = fragmentPath; + return shader; +} + +bool Shader::reload() { + GLuint fresh = buildProgram(vertexPath, fragmentPath); + if (!fresh) return false; // 古いプログラムを残す / keep the old program + glDeleteProgram(program); + program = fresh; + warned.clear(); + return true; +} + +Shader::~Shader() { + if (program) glDeleteProgram(program); +} + +Shader::Shader(Shader &&other) noexcept + : program(std::exchange(other.program, 0)), vertexPath(std::move(other.vertexPath)), + fragmentPath(std::move(other.fragmentPath)), warned(std::move(other.warned)) {} + +Shader &Shader::operator=(Shader &&other) noexcept { + if (this != &other) { + if (program) glDeleteProgram(program); + program = std::exchange(other.program, 0); + vertexPath = std::move(other.vertexPath); + fragmentPath = std::move(other.fragmentPath); + warned = std::move(other.warned); + } + return *this; +} + +GLint Shader::location(const char *name) const { + GLint loc = glGetUniformLocation(program, name); + // -1:名前の間違い、または使われていないので最適化で消された + // -1: a typo, or the uniform is unused and the compiler removed it + if (loc < 0 && warned.insert(name).second) + fprintf(stderr, "%s + %s: ユニフォーム「%s」がない / no active uniform \"%s\"\n", vertexPath.c_str(), + fragmentPath.c_str(), name, name); + return loc; +} + +// location が -1 なら glProgramUniform* は何もしない / with location -1, glProgramUniform* does nothing +void Shader::set(const char *name, int value) const { glProgramUniform1i(program, location(name), value); } +void Shader::set(const char *name, float value) const { glProgramUniform1f(program, location(name), value); } +void Shader::set(const char *name, Vec2 v) const { glProgramUniform2f(program, location(name), v.x, v.y); } +void Shader::set(const char *name, Vec3 v) const { glProgramUniform3f(program, location(name), v.x, v.y, v.z); } +void Shader::set(const char *name, Vec4 v) const { glProgramUniform4f(program, location(name), v.x, v.y, v.z, v.w); } + +void Shader::set(const char *name, const Mat4 &m) const { + // linalg.hhは列優先なので転置しない(GL_FALSE) / linalg.hh is column-major, so no transpose (GL_FALSE) + glProgramUniformMatrix4fv(program, location(name), 1, GL_FALSE, &m.c[0].x); +} diff --git a/src/shader.hh b/src/shader.hh new file mode 100644 index 0000000..c0e2aa5 --- /dev/null +++ b/src/shader.hh @@ -0,0 +1,48 @@ +// シェーダープログラム / a shader program +#pragma once + +#include +#include + +#include +#include +#include + +// ファイルから読み込んだシェーダープログラム(RAII、コピー不可・移動可)。 +// A shader program loaded from files (RAII, non-copyable, movable). +class Shader { +public: + Shader() = default; + ~Shader(); + Shader(const Shader &) = delete; + Shader &operator=(const Shader &) = delete; + Shader(Shader &&other) noexcept; + Shader &operator=(Shader &&other) noexcept; + + // 頂点・フラグメントシェーダーのファイルから作る。失敗したらエラーを表示してstd::nullopt。 + // Builds a program from vertex and fragment shader files. On failure prints the errors and returns std::nullopt. + static std::optional load(const std::string &vertexPath, const std::string &fragmentPath); + + // ファイルを読み直す。失敗したら古いプログラムをそのまま使い続け、falseを返す。 + // Re-reads the files. On failure keeps using the old program and returns false. + bool reload(); + + void use() const { glUseProgram(program); } + GLuint id() const { return program; } + + // ユニフォームを設定(DSA:glProgramUniform*なので use() は不要) + // Set uniforms (DSA: glProgramUniform*, so use() is not needed) + void set(const char *name, int value) const; + void set(const char *name, float value) const; + void set(const char *name, Vec2 value) const; + void set(const char *name, Vec3 value) const; + void set(const char *name, Vec4 value) const; + void set(const char *name, const Mat4 &value) const; + +private: + GLint location(const char *name) const; + + GLuint program = 0; + std::string vertexPath, fragmentPath; + mutable std::unordered_set warned; // 見つからない名前は一度だけ警告 / warn once per missing name +};