diff --git a/CMakeLists.txt b/CMakeLists.txt index 08aaf9f..bc1b480 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -37,7 +37,10 @@ add_executable(game src/shapes.cc src/camera.cc src/material.cc - src/lights.cc) + src/lights.cc + src/json.cc + src/gltf.cc + src/model.cc) target_include_directories(game PRIVATE src external/stb external/linalg) target_link_libraries(game PRIVATE glad stb_image glfw) diff --git a/src/main.cc b/src/main.cc index 9a4535f..7118129 100644 --- a/src/main.cc +++ b/src/main.cc @@ -1,5 +1,5 @@ -// 第13章:glTFとGLB:ファイルの読み込み(このプログラムは第12章と同じ。新しいのは gltf_dump) -// Chapter 13: glTF and GLB: reading the file (this program is the same as in chapter 12; the new part is gltf_dump) +// 第14章:モデルの読み込み +// Chapter 14: loading models // // 操作 / Controls: // WASD 前後左右に移動 / move forward, back, left, right @@ -9,19 +9,21 @@ // ホイール / wheel ズーム / zoom // C FPS ⇔ オービットカメラ / FPS ⇔ orbit camera // V 表示:全部 → 環境光 → 拡散 → 鏡面 → 発光 → 法線 / view: all → ambient → diffuse → specular → emission → normals -// P 点光源を止める・動かす / pause / resume the point lights -// 1 平行光源(月)のオン・オフ / directional light (the moon) on / off -// 2 点光源のオン・オフ / point lights on / off -// 3 スポットライトのオン・オフ / spotlights on / off +// N 昼 ⇔ 夜 / day ⇔ night // F 懐中電灯のオン・オフ / flashlight on / off +// P 風車を止める・回す / pause / resume the windmill +// H ノードの階層のオン・オフ(オフ=親の変換を無視) / node hierarchy on / off (off = ignore the parents) // Tab カーソルのキャプチャ切り替え / toggle cursor capture // R シェーダーを読み直す / reload the shaders // Esc 終了 / quit +// +// 使い方 / usage: game [model.glb] (指定すれば、そのモデルを場面の真ん中に置く / puts that model in the middle of the scene) #include "camera.hh" #include "lights.hh" #include "material.hh" #include "mathx.hh" #include "mesh.hh" +#include "model.hh" #include "shader.hh" #include "shapes.hh" #include "texture.hh" @@ -29,115 +31,74 @@ #include #include -#include #include -// 床に置いた箱:位置(底の中心)、大きさ、Y軸周りの回転 / crates on the floor: position (bottom centre), size, yaw +// 木箱のモデルを置く場所:位置(底の中心)とY軸周りの回転 / where the crate models go: position (bottom centre) and yaw struct CrateInfo { Vec3 position; - float size; float angle; }; static const CrateInfo kCrates[] = { - {{0.0f, 0.0f, 0.0f}, 1.0f, 0.0f}, {{1.1f, 0.0f, 0.2f}, 1.0f, 0.3f}, - {{0.5f, 1.0f, 0.1f}, 1.0f, -0.2f}, {{-3.0f, 0.0f, -2.0f}, 2.0f, 0.6f}, - {{-3.0f, 2.0f, -2.0f}, 1.0f, 0.1f}, {{4.0f, 0.0f, -4.0f}, 1.5f, -0.5f}, - {{-6.0f, 0.0f, 3.0f}, 1.0f, 0.9f}, {{6.5f, 0.0f, 2.5f}, 1.0f, 0.2f}, - {{2.0f, 0.0f, -9.0f}, 3.0f, 0.4f}, {{-8.0f, 0.0f, -8.0f}, 2.0f, -0.3f}, - {{9.0f, 0.0f, -12.0f}, 2.5f, 0.7f}, {{-2.5f, 0.0f, 5.5f}, 0.6f, 0.5f}, -}; - -// 色だけのマテリアル(古典的なOpenGLのマテリアル表から。表のambientは使わない:環境光 = uAmbient × diffuse) -// Colour-only materials (from the classic OpenGL material table; its ambient column is not used: -// our ambient light is uAmbient × diffuse) -struct NamedMaterial { - const char *name; - Material material; -}; - -static const NamedMaterial kMaterialSamples[] = { - {"gold", {.diffuse = {0.75164f, 0.60648f, 0.22648f}, - .specular = {0.628281f, 0.555802f, 0.366065f}, - .shininess = 51.2f}}, - {"silver", {.diffuse = {0.50754f, 0.50754f, 0.50754f}, - .specular = {0.508273f, 0.508273f, 0.508273f}, - .shininess = 51.2f}}, - {"copper", {.diffuse = {0.7038f, 0.27048f, 0.0828f}, - .specular = {0.256777f, 0.137622f, 0.086014f}, - .shininess = 12.8f}}, - {"jade", {.diffuse = {0.54f, 0.89f, 0.63f}, - .specular = {0.316228f, 0.316228f, 0.316228f}, - .shininess = 12.8f}}, - {"ruby", {.diffuse = {0.61424f, 0.04136f, 0.04136f}, - .specular = {0.727811f, 0.626959f, 0.626959f}, - .shininess = 76.8f}}, - {"cyan plastic", {.diffuse = {0.0f, 0.50980392f, 0.50980392f}, - .specular = {0.50196078f, 0.50196078f, 0.50196078f}, - .shininess = 32.0f}}, -}; - -// 点光源(提灯)の中心と色 / centres and colours of the point lights (lanterns) -struct LanternInfo { - Vec3 centre; - Vec3 color; + {{5.5f, 0.0f, 1.5f}, 0.4f}, {{6.3f, 0.0f, 2.6f}, -0.3f}, {{5.9f, 1.0f, 2.0f}, 0.1f}, + {{-6.0f, 0.0f, -1.0f}, 0.8f}, {{-5.2f, 0.0f, 3.5f}, -0.6f}, }; -static const LanternInfo kLanterns[] = { - {{2.6f, 1.2f, 0.2f}, {2.4f, 1.0f, 0.35f}}, // 橙 / orange - {{-1.8f, 1.0f, 0.8f}, {0.4f, 2.0f, 0.7f}}, // 緑 / green - {{4.5f, 1.6f, -4.5f}, {0.6f, 0.9f, 2.6f}}, // 青 / blue - {{-5.5f, 1.4f, -3.5f}, {2.2f, 0.5f, 1.8f}}, // 紫 / purple -}; - -// 箱の山を上から照らすスポットライト / the spotlight shining down on the pile of crates -constexpr Vec3 kStageSpotPos = {2.0f, 6.0f, 1.5f}; -constexpr Vec3 kStageSpotTarget = {0.3f, 0.5f, -0.2f}; - static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specular", "emission", "normals"}; -int main() { +static void printModel(const char *path, const Model &m) { + printf("%s: %zu nodes, %zu meshes, %zu primitives, %zu materials, %zu textures, bounds (%.2f, %.2f, %.2f) - (%.2f, " + "%.2f, %.2f)\n", + path, m.nodes.size(), m.meshCount(), m.primitiveCount(), m.materialCount(), m.textureCount(), m.boundsMin.x, + m.boundsMin.y, m.boundsMin.z, m.boundsMax.x, m.boundsMax.y, m.boundsMax.z); +} + +int main(int argc, char **argv) { Window window; - if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 13")) return 1; + if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 14")) return 1; std::optional phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); - std::optional unlit = Shader::load("shaders/unlit.vert", "shaders/unlit.frag"); - std::optional crate = Texture2D::load("assets/textures/crate.png"); - std::optional crateSpecular = Texture2D::load("assets/textures/crate_specular.png"); - std::optional crateEmission = Texture2D::load("assets/textures/crate_emission.png"); std::optional floorTexture = Texture2D::load("assets/textures/floor.png"); - if (!phong || !unlit || !crate || !crateSpecular || !crateEmission || !floorTexture) return 1; + if (!phong || !floorTexture) return 1; + + // モデル:真ん中の場面(引数で別のファイルにできる)と木箱 / models: the scene in the middle (or a file given + // on the command line) and the crate + const char *scenePath = argc > 1 ? argv[1] : "assets/models/diorama.glb"; + std::optional scene = Model::load(scenePath); + std::optional crate = Model::load("assets/models/crate.glb"); + if (!scene || !crate) return 1; + printModel(scenePath, *scene); + printModel("assets/models/crate.glb", *crate); glEnable(GL_DEPTH_TEST); - // 1×1の白いテクスチャ:マップのないマテリアルの代わり(白を掛けても色は変わらない) - // A 1×1 white texture: stands in for missing maps (multiplying by white changes nothing) const unsigned char whitePixel[4] = {255, 255, 255, 255}; Texture2D white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false}); + // 動かすノードと、光を置くノードを名前で探す(ないファイルでは-1) / find the node to animate and the node + // that carries the light by name (-1 in files that do not have them) + int rotor = scene->findNode("Rotor"); + int lanternNode = scene->findNode("LanternLight"); + Quat rotorStart = rotor >= 0 ? scene->nodes[static_cast(rotor)].rotation : Quat{}; + Camera fps; - fps.position = {0.5f, 2.4f, 8.5f}; - fps.pitch = radians(-14.0f); + fps.position = {0.0f, 2.6f, 9.0f}; + fps.pitch = radians(-12.0f); OrbitCamera orbit; - orbit.target = {0.0f, 0.8f, 0.0f}; - orbit.distance = 9.0f; + orbit.target = {0.0f, 1.2f, 0.0f}; + orbit.distance = 10.0f; orbit.yaw = radians(30.0f); bool useOrbit = false; int viewMode = 0; - bool lightMoving = true; - bool directionalOn = true, pointsOn = true, spotsOn = true, flashlightOn = true; - float lightTime = 0.0f; // 点光源の動きの時間(止められる) / time for the point lights' motion (can be paused) + bool night = false, flashlightOn = false, windmillMoving = true, hierarchy = true; + float windmillTime = 0.0f; window.setCursorCaptured(true); 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) { - bool ok = phong->reload(); - ok = unlit->reload() && ok; // 両方とも読み直す / reload both, even if the first one failed - if (ok) printf("シェーダーを読み直した / shaders reloaded\n"); - } + if (key == GLFW_KEY_R && phong->reload()) printf("シェーダーを読み直した / shaders reloaded\n"); if (key == GLFW_KEY_TAB) window.setCursorCaptured(!window.cursorCaptured()); if (key == GLFW_KEY_C) { useOrbit = !useOrbit; @@ -148,40 +109,21 @@ int main() { viewMode = (viewMode + 1) % 6; printf("view: %s\n", kViewModeNames[viewMode]); } - if (key == GLFW_KEY_P) lightMoving = !lightMoving; - if (key == GLFW_KEY_1) directionalOn = !directionalOn; - if (key == GLFW_KEY_2) pointsOn = !pointsOn; - if (key == GLFW_KEY_3) spotsOn = !spotsOn; + if (key == GLFW_KEY_N) night = !night; if (key == GLFW_KEY_F) flashlightOn = !flashlightOn; - if (key >= GLFW_KEY_1 && key <= GLFW_KEY_3) - printf("directional %s, points %s, spots %s\n", directionalOn ? "on" : "off", pointsOn ? "on" : "off", - spotsOn ? "on" : "off"); + if (key == GLFW_KEY_P) windmillMoving = !windmillMoving; + if (key == GLFW_KEY_H) { + hierarchy = !hierarchy; + printf("hierarchy: %s\n", hierarchy ? "on (world = parent x local)" : "off (world = local)"); + } }; - printf("material spheres (left to right):"); - for (const NamedMaterial &m : kMaterialSamples) printf(" %s", m.name); - printf("\n"); - - Mesh cube = makeCube(); - Mesh sphere = makeSphere(); Mesh floorMesh = makePlane(40.0f, 10.0f); - - // 床:石は少しだけ光る / the floor: stone is only slightly shiny Material floorMaterial; floorMaterial.diffuseMap = &*floorTexture; floorMaterial.specular = {0.15f, 0.15f, 0.15f}; floorMaterial.shininess = 16.0f; - // 箱:三枚のマップ。鏡面反射マップで金属の枠だけが光り、発光マップで隙間が光る - // The crate: three maps. The specular map makes only the metal frame shiny, the emission map lights the gaps - Material crateMaterial; - crateMaterial.diffuseMap = &*crate; - crateMaterial.specular = {1.0f, 1.0f, 1.0f}; - crateMaterial.shininess = 48.0f; - crateMaterial.specularMap = &*crateSpecular; - crateMaterial.emissionMap = &*crateEmission; - crateMaterial.emission = {1.0f, 1.0f, 1.0f}; - double lastTime = window.time(); while (!window.shouldClose()) { double now = window.time(); @@ -207,52 +149,38 @@ int main() { fps.move(dir, dt); } + // 風車の羽根:Rotorノードの回転だけを変える。子ノード(ハブと羽根4枚)は一緒に回る + // The windmill: change only the Rotor node's rotation. Its children (the hub and four blades) turn with it + if (windmillMoving) windmillTime += dt; + if (rotor >= 0) + scene->nodes[static_cast(rotor)].rotation = + Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * windmillTime) * rotorStart; + Mat4 view = useOrbit ? orbit.view() : fps.view(); Mat4 proj = useOrbit ? orbit.projection(window.aspect()) : fps.projection(window.aspect()); Vec3 viewPos = useOrbit ? orbit.position() : fps.position; Vec3 viewDir = useOrbit ? normalize(orbit.target - orbit.position()) : fps.front(); - // 夜の場面:弱い環境光と青白い月 / a night scene: weak ambient light and a pale blue moon - if (lightMoving) lightTime += dt; + // 昼は太陽、夜は月と街灯 / the sun by day, the moon and the street lamp by night LightSet lights; - lights.ambient = {0.03f, 0.035f, 0.05f}; - if (directionalOn) lights.directional = {.direction = {-0.4f, -1.0f, -0.6f}, .color = {0.22f, 0.27f, 0.4f}}; - - // 色の違う点光源四つ。それぞれ自分の中心の周りをゆっくり回る - // Four coloured point lights, each slowly circling its own centre - if (pointsOn) { - for (int i = 0; i < 4; ++i) { - float a = lightTime * (0.5f + 0.15f * static_cast(i)) + static_cast(i) * 1.7f; - lights.points.push_back({.position = kLanterns[i].centre + Vec3{1.2f * std::cos(a), 0.3f * std::sin(2.0f * a), - 1.2f * std::sin(a)}, - .color = kLanterns[i].color, - .attenuation = kMediumRange}); + if (!night) { + lights.ambient = {0.28f, 0.30f, 0.34f}; + lights.directional = {.direction = {-0.5f, -1.0f, -0.35f}, .color = {0.95f, 0.9f, 0.8f}}; + } else { + lights.ambient = {0.03f, 0.035f, 0.05f}; + lights.directional = {.direction = {-0.4f, -1.0f, -0.6f}, .color = {0.15f, 0.18f, 0.28f}}; + // 光の位置=空のノード「LanternLight」のワールド座標 / the light sits at the world position of the empty node + if (lanternNode >= 0) { + Vec4 p = scene->nodeTransform(lanternNode) * Vec4{0.0f, 0.0f, 0.0f, 1.0f}; + lights.points.push_back({.position = {p.x, p.y, p.z}, .color = {2.6f, 1.6f, 0.7f}, .attenuation = kMediumRange}); } } + if (flashlightOn) lights.spots.push_back({.position = viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); - // スポットライト:カメラの懐中電灯と、箱の山を上から照らすライト - // Spotlights: the camera's flashlight and a light shining down on the pile of crates - if (spotsOn) { - if (flashlightOn) - lights.spots.push_back({.position = viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); - lights.spots.push_back({.position = kStageSpotPos, - .direction = kStageSpotTarget - kStageSpotPos, - .color = {2.0f, 1.9f, 1.6f}, - .innerAngle = radians(16.0f), - .outerAngle = radians(24.0f)}); - } - - glClearColor(0.02f, 0.03f, 0.06f, 1.0f); + if (night) glClearColor(0.02f, 0.03f, 0.06f, 1.0f); + else glClearColor(0.45f, 0.62f, 0.85f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - // 一つの物を描く:モデル行列、法線行列、マテリアル / draws one object: model matrix, normal matrix, material - auto drawLit = [&](const Mesh &mesh, const Mat4 &model, const Material &material) { - phong->set("uModel", model); - phong->set("uNormalMatrix", normalMatrix(model)); - material.apply(*phong, white); - mesh.draw(); - }; - phong->use(); phong->set("uView", view); phong->set("uProj", proj); @@ -260,34 +188,14 @@ int main() { phong->set("uViewMode", viewMode); lights.apply(*phong); - drawLit(floorMesh, Mat4::identity(), floorMaterial); - - for (const CrateInfo &c : kCrates) { - Vec3 centre = c.position + Vec3{0.0f, 0.5f * c.size, 0.0f}; - drawLit(cube, translate(centre) * rotateY(c.angle) * scale({c.size, c.size, c.size}), crateMaterial); - } + phong->set("uModel", Mat4::identity()); + phong->set("uNormalMatrix", normalMatrix(Mat4::identity())); + floorMaterial.apply(*phong, white); + floorMesh.draw(); - // マテリアル見本の球を一列に / a row of sample spheres, one per material - for (size_t i = 0; i < std::size(kMaterialSamples); ++i) { - float x = (static_cast(i) - 2.5f) * 1.25f; - drawLit(sphere, translate({x, 0.5f, 2.6f}), kMaterialSamples[i].material); - } - - // 光源の目印:点光源は小さな球、スポットライトは小さな箱(懐中電灯は自分の目の位置なので描かない) - // Light markers: small spheres for point lights, small cubes for spotlights (not the flashlight: it is at our eye) - unlit->use(); - unlit->set("uView", view); - unlit->set("uProj", proj); - for (const PointLight &p : lights.points) { - unlit->set("uModel", translate(p.position) * scale({0.15f, 0.15f, 0.15f})); - unlit->set("uColor", p.color); - sphere.draw(); - } - if (spotsOn) { - unlit->set("uModel", translate(kStageSpotPos) * scale({0.2f, 0.2f, 0.2f})); - unlit->set("uColor", Vec3{1.0f, 1.0f, 0.9f}); - cube.draw(); - } + // モデルは自分でノードごとにuModelとマテリアルを設定する / the model sets uModel and the material per node itself + scene->draw(*phong, Mat4::identity(), white, hierarchy); + for (const CrateInfo &c : kCrates) crate->draw(*phong, translate(c.position) * rotateY(c.angle), white, hierarchy); window.swapBuffers(); } diff --git a/src/mesh.hh b/src/mesh.hh index ab2daf9..7c75c73 100644 --- a/src/mesh.hh +++ b/src/mesh.hh @@ -37,6 +37,24 @@ constexpr VertexAttrib kVertex3DLayout[] = { {2, 2, offsetof(Vertex3D, uv)}, // layout(location = 2) in vec2 aUv }; +// モデル(glTF)の頂点:Vertex3Dに接線を足したもの。接線は第22章の法線マッピングで使う。 +// wは従法線の向き(±1):従法線 = cross(normal, tangent.xyz) * tangent.w。接線がなければ (0, 0, 0, 0)。 +// A model (glTF) vertex: Vertex3D plus a tangent, used for normal mapping in chapter 22. +// w is the bitangent's sign (±1): bitangent = cross(normal, tangent.xyz) * tangent.w. (0, 0, 0, 0) if there is none. +struct ModelVertex { + Vec3 position; + Vec3 normal; + Vec2 uv; + Vec4 tangent; +}; + +constexpr VertexAttrib kModelVertexLayout[] = { + {0, 3, offsetof(ModelVertex, position)}, // layout(location = 0) in vec3 aPosition + {1, 3, offsetof(ModelVertex, normal)}, // layout(location = 1) in vec3 aNormal + {2, 2, offsetof(ModelVertex, uv)}, // layout(location = 2) in vec2 aUv + {3, 4, offsetof(ModelVertex, tangent)}, // layout(location = 3) in vec4 aTangent(第22章 / chapter 22) +}; + // 一つの描画単位(RAII、コピー不可・移動可)。インデックスが空ならglDrawArraysで描く。 // One drawable unit (RAII, non-copyable, movable). With no indices it draws with glDrawArrays. class Mesh { diff --git a/src/model.cc b/src/model.cc new file mode 100644 index 0000000..7e5fcbc --- /dev/null +++ b/src/model.cc @@ -0,0 +1,280 @@ +#include "model.hh" + +#include +#include + +//------------------------------------------ +// PBRマテリアル → Blinn-Phong(第24章で本物のPBRにするまでの近似) +// PBR material → Blinn-Phong (an approximation until chapter 24 does real PBR) +//------------------------------------------ + +static float clamp01(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; } + +// metallicScale・roughnessScale:金属・粗さテクスチャの平均(テクスチャがなければ1)。 +// Blinn-Phongはピクセルごとの金属度を扱えないので、テクスチャの平均で係数を代表させる。 +// metallicScale, roughnessScale: the averages of the metallic-roughness texture (1 without a texture). +// Our Blinn-Phong cannot vary metallic per pixel, so the texture's average stands in for it. +static Material phongFromPbr(const GltfMaterial &m, float metallicScale, float roughnessScale) { + float metallic = clamp01(m.metallicFactor * metallicScale); + float roughness = clamp01(m.roughnessFactor * roughnessScale); + Vec3 base = {m.baseColorFactor.x, m.baseColorFactor.y, m.baseColorFactor.z}; + + Material p; + // 金属は拡散反射をしない / metals have no diffuse reflection + p.diffuse = (1.0f - metallic) * base; + // 正面から見た反射率F0:非金属は約4%、金属は自分の色 / reflectance at normal incidence F0: ~4% for non-metals, + // the base colour for metals + Vec3 f0 = lerp({0.04f, 0.04f, 0.04f}, base, metallic); + // 粗さ → 光沢度:Blinn-Phongとベックマン分布の対応 n = 2/α² − 2(α = 粗さ²) + // roughness → shininess: the Blinn-Phong / Beckmann correspondence n = 2/α² − 2 (α = roughness²) + float alpha = roughness * roughness; + float n = alpha > 0.0f ? 2.0f / (alpha * alpha) - 2.0f : 1024.0f; + n = n < 1.0f ? 1.0f : n > 1024.0f ? 1024.0f : n; + // 正規化 (n + 8) / 8:鋭いハイライトほど明るく(反射する光の総量がほぼ一定になる) + // normalization (n + 8) / 8: sharper highlights get brighter (the total reflected light stays about the same) + p.specular = ((n + 8.0f) / 8.0f) * f0; + p.shininess = n; + p.emission = m.emissiveStrength * m.emissiveFactor; + return p; +} + +//------------------------------------------ +// 読み込み / loading +//------------------------------------------ + +// glTFのプリミティブ一つを頂点の配列にしてGPUに載せる。描けなければstd::nullopt。 +// Turns one glTF primitive into a vertex array and uploads it. std::nullopt if it cannot be drawn. +static std::optional loadPrimitive(const Gltf &g, const GltfPrimitive &p, const std::string &where) { + // 属性を読む。型が合わないものは無視する / read the attributes; ignore those with an unexpected type + auto read = [&](const char *name, int components) -> std::optional> { + int accessor = p.attribute(name); + if (accessor < 0) return std::nullopt; + if (g.accessors[static_cast(accessor)].components != components) { + fprintf(stderr, "%s: %s: %s の型が違うので無視 / unexpected type, ignored\n", g.path.c_str(), where.c_str(), name); + return std::nullopt; + } + return g.readFloats(accessor); + }; + + std::optional> positions = read("POSITION", 3); + if (!positions) { + fprintf(stderr, "%s: %s: POSITIONがないので描かない / no POSITION, skipped\n", g.path.c_str(), where.c_str()); + return std::nullopt; + } + std::optional> normals = read("NORMAL", 3); + std::optional> uvs = read("TEXCOORD_0", 2); + std::optional> tangents = read("TANGENT", 4); + + // 交互に並んだ頂点の配列を作る(ファイルの並び方に関係なく同じ形になる) + // Build an interleaved vertex array (the same layout whatever the file's layout was) + size_t count = positions->size() / 3; + std::vector vertices(count); + for (size_t i = 0; i < count; ++i) { + ModelVertex &v = vertices[i]; + const float *f = positions->data() + i * 3; + v.position = {f[0], f[1], f[2]}; + v.normal = {0.0f, 1.0f, 0.0f}; + if (normals) v.normal = {(*normals)[i * 3], (*normals)[i * 3 + 1], (*normals)[i * 3 + 2]}; + if (uvs) v.uv = {(*uvs)[i * 2], (*uvs)[i * 2 + 1]}; + if (tangents) v.tangent = {(*tangents)[i * 4], (*tangents)[i * 4 + 1], (*tangents)[i * 4 + 2], (*tangents)[i * 4 + 3]}; + } + + // インデックス:u8・u16・u32はすべてu32になる / indices: u8, u16 and u32 all become u32 + std::vector indices; + if (p.indices >= 0) { + std::optional> read32 = g.readIndices(p.indices); + if (!read32) return std::nullopt; + indices = std::move(*read32); + // 範囲外のインデックスはGPUで範囲外の読み込みになる:必ず調べる + // an out-of-range index would make the GPU read out of bounds: always check + for (std::uint32_t i : indices) { + if (i >= count) { + fprintf(stderr, "%s: %s: インデックスが頂点数を超える / index exceeds the vertex count\n", g.path.c_str(), + where.c_str()); + return std::nullopt; + } + } + } + + // 法線がなければ、glTFの仕様どおり平らな法線を作る。三角形ごとに頂点を分ける(インデックスなしにする) + // Without normals, make flat normals as the glTF spec requires. Each triangle gets its own vertices (no indices) + if (!normals && p.mode == kGltfTriangles) { + size_t corners = indices.empty() ? count : indices.size(); + std::vector flat; + flat.reserve(corners / 3 * 3); + for (size_t t = 0; t + 2 < corners; t += 3) { + ModelVertex a = vertices[indices.empty() ? t : indices[t]]; + ModelVertex b = vertices[indices.empty() ? t + 1 : indices[t + 1]]; + ModelVertex c = vertices[indices.empty() ? t + 2 : indices[t + 2]]; + Vec3 n = normalize(cross(b.position - a.position, c.position - a.position)); // 反時計回りなら外向き / CCW = outwards + a.normal = b.normal = c.normal = n; + flat.insert(flat.end(), {a, b, c}); + } + vertices = std::move(flat); + indices.clear(); + } + + Model::Primitive out; + out.material = p.material; + out.boundsMin = out.boundsMax = vertices.empty() ? Vec3{} : vertices[0].position; + for (const ModelVertex &v : vertices) { + const Vec3 &q = v.position; + out.boundsMin = {q.x < out.boundsMin.x ? q.x : out.boundsMin.x, q.y < out.boundsMin.y ? q.y : out.boundsMin.y, + q.z < out.boundsMin.z ? q.z : out.boundsMin.z}; + out.boundsMax = {q.x > out.boundsMax.x ? q.x : out.boundsMax.x, q.y > out.boundsMax.y ? q.y : out.boundsMax.y, + q.z > out.boundsMax.z ? q.z : out.boundsMax.z}; + } + // glTFのmode(0〜6)はGL_POINTS〜GL_TRIANGLE_FANと同じ値 / glTF modes 0..6 equal GL_POINTS..GL_TRIANGLE_FAN + out.mesh = Mesh(vertices, indices, kModelVertexLayout, static_cast(p.mode)); + return out; +} + +// 箱の8つの角を変換して、boundsを広げる / transforms the 8 corners of a box and grows the bounds +static void growBounds(Vec3 &lo, Vec3 &hi, bool &first, const Mat4 &m, Vec3 bmin, Vec3 bmax) { + for (int i = 0; i < 8; ++i) { + Vec4 c = m * Vec4{i & 1 ? bmax.x : bmin.x, i & 2 ? bmax.y : bmin.y, i & 4 ? bmax.z : bmin.z, 1.0f}; + if (first) { + lo = hi = {c.x, c.y, c.z}; + first = false; + } + lo = {c.x < lo.x ? c.x : lo.x, c.y < lo.y ? c.y : lo.y, c.z < lo.z ? c.z : lo.z}; + hi = {c.x > hi.x ? c.x : hi.x, c.y > hi.y ? c.y : hi.y, c.z > hi.z ? c.z : hi.z}; + } +} + +std::optional Model::load(const std::string &path) { + std::optional loaded = Gltf::load(path); + if (!loaded) return std::nullopt; + const Gltf &g = *loaded; + Model model; + + // テクスチャ:埋め込まれたPNG/JPEGをデコードしてアップロード。glTFのUVは画像の左上が原点なので反転しない + // Textures: decode the embedded PNG/JPEG and upload it. glTF UVs start at the image's top-left: no flipping + std::vector averages(g.textures.size(), Vec4{1.0f, 1.0f, 1.0f, 1.0f}); + model.textures.resize(g.textures.size()); // 読めなかったものは空(id 0)=白 / ones that fail stay empty (id 0) = white + for (size_t i = 0; i < g.textures.size(); ++i) { + const GltfTexture &t = g.textures[i]; + if (t.source < 0) continue; + std::optional> bytes = g.imageData(t.source); + if (!bytes) continue; + std::optional image = decodeImage(bytes->data(), bytes->size(), false); + if (!image) { + fprintf(stderr, "%s: images[%d] をデコードできない / cannot decode images[%d]\n", path.c_str(), t.source, t.source); + continue; + } + // 各チャンネルの平均(金属・粗さテクスチャの近似に使う) / average of each channel (for the metallic-roughness approximation) + double sum[4] = {0, 0, 0, 0}; + for (size_t p = 0; p < image->rgba.size(); ++p) sum[p % 4] += image->rgba[p]; + double pixels = static_cast(image->width) * image->height * 255.0; + averages[i] = {static_cast(sum[0] / pixels), static_cast(sum[1] / pixels), + static_cast(sum[2] / pixels), static_cast(sum[3] / pixels)}; + + // 色のテクスチャは本当はsRGB(第21章で直す) / colour textures are really sRGB (fixed in chapter 21) + Texture2D texture = Texture2D::fromPixels(image->rgba.data(), image->width, image->height, + {.flipY = false, .mipmaps = true}); + if (t.sampler >= 0) { + // 値はGLのenumそのもの(読み込み時に検査済み)。0 = 指定なし / the values are GL enums (validated); 0 = not given + const GltfSampler &s = g.samplers[static_cast(t.sampler)]; + texture.setWrap(static_cast(s.wrapS), static_cast(s.wrapT)); + texture.setFilter(s.minFilter ? static_cast(s.minFilter) : GL_LINEAR_MIPMAP_LINEAR, + s.magFilter ? static_cast(s.magFilter) : GL_LINEAR); + } + model.textures[i] = std::move(texture); + } + + // マテリアル / materials + for (const GltfMaterial &m : g.materials) { + Vec4 mr = {1.0f, 1.0f, 1.0f, 1.0f}; + int t = m.metallicRoughnessTexture.index; + if (t >= 0 && model.textures[static_cast(t)].id() != 0) mr = averages[static_cast(t)]; + model.materials.push_back({m, phongFromPbr(m, mr.z, mr.y)}); // B = 金属度 / metallic、G = 粗さ / roughness + } + // マテリアルのないプリミティブ用。glTFの既定(金属度1、粗さ1)だと拡散色の無い淡い塊になるので、白いプラスチックにする + // For primitives without a material. glTF's default (metallic 1, roughness 1) would be a pale blob with no diffuse + // colour here, so use white plastic + model.defaultMaterial.pbr.name = "(default)"; + model.defaultMaterial.pbr.metallicFactor = 0.0f; + model.defaultMaterial.pbr.roughnessFactor = 0.5f; + model.defaultMaterial.phong = phongFromPbr(model.defaultMaterial.pbr, 1.0f, 1.0f); + + // メッシュ / meshes + for (size_t i = 0; i < g.meshes.size(); ++i) { + MeshData mesh; + mesh.name = g.meshes[i].name; + for (size_t k = 0; k < g.meshes[i].primitives.size(); ++k) { + std::string where = "meshes[" + std::to_string(i) + "].primitives[" + std::to_string(k) + "]"; + std::optional prim = loadPrimitive(g, g.meshes[i].primitives[k], where); + if (prim) mesh.primitives.push_back(std::move(*prim)); // 描けないものは飛ばす / skip what cannot be drawn + } + model.meshes.push_back(std::move(mesh)); + } + + model.nodes = g.nodes; + model.roots = g.rootNodes(); + + // 全体の箱:メッシュのある全部のノードについて、プリミティブの箱を変換する + // The whole box: transform each primitive's box for every node that has a mesh + bool first = true; + for (size_t i = 0; i < model.nodes.size(); ++i) { + if (model.nodes[i].mesh < 0) continue; + Mat4 m = model.nodeTransform(static_cast(i)); + for (const Primitive &p : model.meshes[static_cast(model.nodes[i].mesh)].primitives) + growBounds(model.boundsMin, model.boundsMax, first, m, p.boundsMin, p.boundsMax); + } + return model; +} + +//------------------------------------------ +// 描画 / drawing +//------------------------------------------ + +size_t Model::primitiveCount() const { + size_t n = 0; + for (const MeshData &m : meshes) n += m.primitives.size(); + return n; +} + +const Texture2D *Model::texture(int index) const { + if (index < 0 || static_cast(index) >= textures.size()) return nullptr; + const Texture2D &t = textures[static_cast(index)]; + return t.id() != 0 ? &t : nullptr; +} + +int Model::findNode(std::string_view name) const { + for (size_t i = 0; i < nodes.size(); ++i) + if (nodes[i].name == name) return static_cast(i); + return -1; +} + +Mat4 Model::nodeTransform(int node) const { + if (node < 0 || static_cast(node) >= nodes.size()) return Mat4::identity(); + // 親をたどって左から掛ける:ルート × … × 親 × 自分 / walk up the parents multiplying from the left + Mat4 m = nodes[static_cast(node)].localTransform(); + for (int p = nodes[static_cast(node)].parent; p >= 0; p = nodes[static_cast(p)].parent) + m = nodes[static_cast(p)].localTransform() * m; + return m; +} + +void Model::draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, bool hierarchy) const { + for (int root : roots) drawNode(root, transform, transform, shader, white, hierarchy); +} + +void Model::drawNode(int node, const Mat4 &parentWorld, const Mat4 &transform, const Shader &shader, + const Texture2D &white, bool hierarchy) const { + const GltfNode &n = nodes[static_cast(node)]; + // ワールド行列 = 親のワールド行列 × 自分のローカル行列 / world = the parent's world matrix × our local matrix + Mat4 world = (hierarchy ? parentWorld : transform) * n.localTransform(); + if (n.mesh >= 0) { + shader.set("uModel", world); + shader.set("uNormalMatrix", normalMatrix(world)); + for (const Primitive &p : meshes[static_cast(n.mesh)].primitives) { + const MaterialData &md = p.material >= 0 ? materials[static_cast(p.material)] : defaultMaterial; + Material m = md.phong; + m.diffuseMap = texture(md.pbr.baseColorTexture.index); // 色 = 係数 × テクスチャ / colour = factor × texture + m.emissionMap = texture(md.pbr.emissiveTexture.index); + m.apply(shader, white); + p.mesh.draw(); + } + } + for (int child : n.children) drawNode(child, world, transform, shader, white, hierarchy); +} diff --git a/src/model.hh b/src/model.hh new file mode 100644 index 0000000..108c2aa --- /dev/null +++ b/src/model.hh @@ -0,0 +1,80 @@ +// glTF/GLBのモデルをGPUに載せて描く / uploads a glTF/GLB model to the GPU and draws it +#pragma once + +#include "gltf.hh" +#include "material.hh" +#include "mesh.hh" +#include "shader.hh" +#include "texture.hh" + +#include +#include +#include +#include + +// 読み込んだモデル:メッシュ(VAO)、テクスチャ、マテリアル、ノードの階層(RAII、コピー不可・移動可)。 +// 描くときは、ノードごとに 親のワールド行列 × 自分のローカル行列 をたどる。 +// A loaded model: meshes (VAOs), textures, materials and the node hierarchy (RAII, non-copyable, movable). +// Drawing walks the nodes, each with world = parent's world × its own local matrix. +class Model { +public: + // プリミティブ一つ=描画呼び出し一回 / one primitive = one draw call + struct Primitive { + Mesh mesh; + int material = -1; // materialsの番号、-1 = 既定 / index into materials, -1 = the default + Vec3 boundsMin, boundsMax; // モデル座標の箱 / box in model space + }; + struct MeshData { + std::string name; + std::vector primitives; + }; + // glTFのPBRマテリアルと、それを近似したBlinn-Phongのマテリアル(マップは描くときに繋ぐ) + // The glTF PBR material and the Blinn-Phong material approximating it (maps are attached at draw time) + struct MaterialData { + GltfMaterial pbr; + Material phong; + }; + + Model() = default; + Model(const Model &) = delete; + Model &operator=(const Model &) = delete; + Model(Model &&) noexcept = default; + Model &operator=(Model &&) noexcept = default; + + // .glb/.gltfを読み、GPUに載せる。失敗したらエラーを表示してstd::nullopt。 + // Loads a .glb/.gltf and uploads it to the GPU. On failure prints the error and returns std::nullopt. + static std::optional load(const std::string &path); + + // transform(モデル全体の置き場所)で描く。マップのないマテリアルにはwhiteを繋ぐ。 + // hierarchy = falseなら親の変換を無視する(なぜ親×子が必要かを見せるため)。 + // Draws with transform (where the whole model goes). Binds `white` for missing maps. + // hierarchy = false ignores the parents' transforms (to show why parent × child is needed). + void draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, bool hierarchy = true) const; + + // 名前でノードを探す。なければ-1 / finds a node by name; -1 if none + int findNode(std::string_view name) const; + // ノードのモデル座標での行列(ルートからの積)。描く場所はtransform × これ + // A node's matrix in model space (the product from the root). It is drawn at transform × this + Mat4 nodeTransform(int node) const; + + // ノードは公開:translation・rotation・scaleを書き換えると動かせる(行列のノードは動かせない) + // The nodes are public: change translation / rotation / scale to animate them (matrix nodes cannot be animated) + std::vector nodes; + std::vector roots; // 描き始めるノード / the nodes drawing starts from + Vec3 boundsMin, boundsMax; // モデル全体の箱(読み込んだときの姿勢) / box around the whole model (as loaded) + + size_t meshCount() const { return meshes.size(); } + size_t primitiveCount() const; + size_t materialCount() const { return materials.size(); } + size_t textureCount() const { return textures.size(); } + +private: + void drawNode(int node, const Mat4 &parentWorld, const Mat4 &transform, const Shader &shader, + const Texture2D &white, bool hierarchy) const; + const Texture2D *texture(int index) const; // なければnullptr / nullptr if missing + + std::vector meshes; + std::vector textures; // glTFのtexturesと同じ番号 / same indices as the glTF textures + std::vector materials; + MaterialData defaultMaterial; +}; diff --git a/src/texture.cc b/src/texture.cc index cc9cc98..502aa9d 100644 --- a/src/texture.cc +++ b/src/texture.cc @@ -82,3 +82,20 @@ void Texture2D::setWrap(GLenum wrapS, GLenum wrapT) { glTextureParameteri(handle, GL_TEXTURE_WRAP_S, static_cast(wrapS)); // 横 / horizontal (u) glTextureParameteri(handle, GL_TEXTURE_WRAP_T, static_cast(wrapT)); // 縦 / vertical (v) } + +std::optional decodeImage(const unsigned char *bytes, size_t size, bool flipY) { + stbi_set_flip_vertically_on_load(flipY ? 1 : 0); + int width = 0, height = 0, channels = 0; + // ファイルからではなくメモリから(GLBに埋め込まれた画像など) / from memory instead of a file (e.g. images embedded in a GLB) + unsigned char *pixels = stbi_load_from_memory(bytes, static_cast(size), &width, &height, &channels, 4); + if (!pixels) { + fprintf(stderr, "画像をデコードできない / cannot decode image: %s\n", stbi_failure_reason()); + return std::nullopt; + } + Image image; + image.width = width; + image.height = height; + image.rgba.assign(pixels, pixels + static_cast(width) * static_cast(height) * 4); + stbi_image_free(pixels); + return image; +} diff --git a/src/texture.hh b/src/texture.hh index 83dd1f4..badf6b9 100644 --- a/src/texture.hh +++ b/src/texture.hh @@ -3,8 +3,10 @@ #include +#include #include #include +#include struct TextureOptions { bool flipY = true; // 画像は上から、OpenGLのUVは下から / images start at the top, OpenGL UVs at the bottom @@ -12,6 +14,16 @@ struct TextureOptions { bool srgb = false; // 色の画像はsRGB(正しい扱いは第21章) / colour images are sRGB (handled properly in chapter 21) }; +// デコードした画像:RGBA8、上の行から順に / a decoded image: RGBA8, rows from the top +struct Image { + int width = 0, height = 0; + std::vector rgba; +}; + +// メモリ上の画像ファイル(PNG、JPEG…)をデコードする。flipY = trueなら上下を反転する。失敗したらstd::nullopt。 +// Decodes an image file held in memory (PNG, JPEG, ...). flipY = true flips it upside down. std::nullopt on failure. +std::optional decodeImage(const unsigned char *bytes, size_t size, bool flipY); + // 2Dテクスチャ(RAII、コピー不可・移動可)。DSAで作る。 // A 2D texture (RAII, non-copyable, movable), created with DSA. class Texture2D {