4. 頂点属性とインデックスバッファ
第3章では、オレンジ色の三角形を1つ描きました。
其の頂点には位置しか無く、色はフラグメントシェーダーの中の定数でした。
本物のメッシュは、頂点毎にもっと多くの情報を持っています。
色、テクスチャ座標、法線、接線、ボーンのウェイト等です。
此の章では、頂点に2つ目の属性として自分の色を持たせ、ラスタライザーに三角形の中で色を混ぜて貰います。
次に、同じ頂点を何度も書くのを止めます。
インデックスバッファを使うと、四角形は6頂点ではなく4頂点、六角形は18頂点ではなく7頂点で済みます。
最後に、OpenGLが描けるプリミティブの種類を全て見て、全ての図形の中の三角形が見えるワイヤーフレーム表示も追加します。
其の途中で、第3章で手書きしていたglCreate…とglDelete…の組は、BufferとMeshと言う2つの小さなRAIIクラスになります。
此れ以降の全ての章が此の2つを使います。
4.1 此の章で作る物
6つの図形を描きます。
其々が自分の頂点配列オブジェクト(VAO)を持っています。
- 左上:角が赤・緑・青の三角形。其の間は全て補間された色です。
- 中央上:インデックスバッファで2つの頂点を共有する、2つの三角形で出来た四角形。
- 右上:コードで生成した六角形。中心の頂点は白で、6つの三角形全てが共有しています。
- 左下:点として描いた15個の頂点。
- 中央下:閉じた線で描いた星。
- 右下:トライアングルストリップで描いた波打つリボン。
Pキーで塗り潰しとワイヤーフレームを切り替え、Escキーで終了します。
プロジェクトは第3章の最後の状態から始めます。
4つのファイル(buffer.hh、buffer.cc、mesh.hh、mesh.cc)を追加し、main.ccの殆どを書き直します。
CMakeLists.txtには新しいソースファイルを2つ足すだけです:
add_executable(game
src/main.cc
src/window.cc
src/gl_debug.cc
src/buffer.cc
src/mesh.cc)
ビルドと実行は今迄と全く同じです。
LinuxとFreeBSDではcmake --build buildと./build/game、Visual StudioではF5です。
CMakeLists.txtが変わった事はCMakeが自分で気付き、自動で設定し直します(Visual Studioのビルド出力に出て来るZERO_CHECKプロジェクトが其れです)。
4.2 Bufferクラス
第3章では、glCreateBuffersとglNamedBufferStorageで頂点バッファを作り、mainの最後で手で削除しました。
三角形1つなら其れで構いません。
でも6つの図形が其々2つのバッファを持つと、削除し忘れの原因になりますし、途中のreturnは後片付けを丸ごと飛ばしてしまいます。
其処で最初の新しいファイルは、バッファオブジェクトをクラスで包み、デストラクターで削除する様にします:
// GPUのバッファ / a GPU buffer
#pragma once
#include <glad/glad.h>
// バッファオブジェクト(RAII、コピー不可・移動可)。
// A buffer object (RAII, non-copyable, movable).
class Buffer {
public:
Buffer() = default;
// 不変ストレージ(glNamedBufferStorage)を作ってdataをコピーする。flags=0なら後から書き換えられない。
// Creates immutable storage (glNamedBufferStorage) and copies data in. flags = 0: cannot be updated later.
Buffer(const void *data, GLsizeiptr byteCount, GLbitfield flags = 0);
~Buffer();
Buffer(const Buffer &) = delete;
Buffer &operator=(const Buffer &) = delete;
Buffer(Buffer &&other) noexcept;
Buffer &operator=(Buffer &&other) noexcept;
GLuint id() const { return handle; }
GLsizeiptr size() const { return bytes; }
private:
GLuint handle = 0;
GLsizeiptr bytes = 0;
};
#include "buffer.hh"
#include <utility>
Buffer::Buffer(const void *data, GLsizeiptr byteCount, GLbitfield flags) : bytes(byteCount) {
glCreateBuffers(1, &handle);
glNamedBufferStorage(handle, byteCount, data, flags);
}
Buffer::~Buffer() {
if (handle) glDeleteBuffers(1, &handle);
}
// 移動したら元のオブジェクトは空(0)になる / a moved-from object becomes empty (0)
Buffer::Buffer(Buffer &&other) noexcept
: handle(std::exchange(other.handle, 0)), bytes(std::exchange(other.bytes, 0)) {}
Buffer &Buffer::operator=(Buffer &&other) noexcept {
if (this != &other) {
if (handle) glDeleteBuffers(1, &handle);
handle = std::exchange(other.handle, 0);
bytes = std::exchange(other.bytes, 0);
}
return *this;
}
此の後のMesh、Shader、Texture2Dも全く同じ形をしているので、設計の判断を幾つか説明しておきます:
- コンストラクターがストレージを作り、一度に中身を入れます。
glNamedBufferStorage(buffer, size, data, flags)はsizeバイトを確保し、dataからsizeバイトをコピーします。此のストレージは不変(immutable)で、サイズは二度と変えられません。flags = 0なら中身も変えられないので、ドライバーはデータを一番速いGPUメモリに置く事が出来ます。後の章でバッファをglNamedBufferSubDataで更新したい時は、GL_DYNAMIC_STORAGE_BITを渡します(第19章のユニフォームバッファ、第25章のスプライトバッチ)。 - コピー禁止。
Bufferがコピー出来ると、2つのオブジェクトが同じGLの名前を持ち、両方のデストラクターが其れを削除します。2回目のglDeleteBuffersは何も消さないか、もっと悪い場合は、偶々同じ名前を貰った新しいバッファを消してしまいます。 - 移動は可能。 関数からバッファを返したり、
std::vectorに入れたりはしたいです。ムーブコンストラクターはstd::exchangeでハンドルを受け取り、元には0を残します。デストラクターは0を無視します。ムーブ代入は、先ず自分が持っているバッファを削除します。 - 例外は使いません。 此のコンストラクターは実際には失敗しません。メモリ不足等の問題は戻り値ではなく、第2章のデバッグコールバックで報告されます。
注意: RAIIのGLオブジェクトは、全てコンテキストが残っている間に破棄しなければなりません。其の為、Windowは常にmainの最初の変数です。C++はローカル変数を宣言と逆の順に破棄するので、ウィンドウ(とコンテキスト)が最後になります。
4.3 インターリーブされた頂点データ
新しい頂点は位置と色を持ちます。
C++では、linalg.hhのVec3を2つ並べた構造体です。
此の章で初めてlinalg.hhをインクルードします:
// 位置と色を交互に並べた(インターリーブ)頂点 / a vertex with position and colour interleaved
struct ColorVertex {
Vec3 position;
Vec3 color;
};
Vec3はパディング無しのfloat3つ(12バイト)なので、ColorVertexは24バイトで、色は位置の12バイト後から始まります。
std::vector<ColorVertex>は頂点を順番に並べて保存するので、其々の位置の直後に其の頂点の色が来ます。
此れをインターリーブ(交互配置)と呼びます:
GPUが頂点番号の属性を見付けるには、3つの数が必要です:
- ストライド:或る頂点から次の頂点迄のバイト数(24)。
- 頂点の中での属性の相対オフセット(位置は0、色は12)。
- バッファの中で頂点が始まるオフセット(此処では0)。
此れらから、属性のアドレスを次の様に計算します:
例えば、頂点2の色はバイト目、頂点3の位置はバイト目にあります。
第3章では、ストライドとオフセットはglVertexArrayVertexBufferに渡しました(此れらはバインディングの情報です)。
相対オフセットはglVertexArrayAttribFormatに渡しました(此れは属性の情報です)。
此の分け方のお陰で、今回の様に複数の属性が1つのバッファを共有出来ます。
もう1つのやり方は分離(非インターリーブ)レイアウトです。
先ず全ての位置、次に全ての色を、1つのバッファの2つのオフセット、又は2つのバッファに置きます。
どちらでも動きます。
頂点の読み込み装置が1つの頂点の全てを同じメモリの辺りから読めるので、普通はインターリーブが基本です。
一部の属性しか使わないパスでは分離の方が有利です。
例えば位置だけを読むシャドウパスです(分離レイアウトは課題6で作ります)。
4.4 頂点の形式を記述する
第3章では、1つの属性の為にglEnableVertexArrayAttrib、glVertexArrayAttribFormat、glVertexArrayAttribBindingを手で呼びました。
属性が2つになり、此れから頂点の型も沢山増えるので、形式をデータとして書き、1つのループで呼び出しをさせたいです。
1つの属性の説明は、mesh.hhの小さな構造体です:
// 頂点属性一つの説明(DSAのglVertexArrayAttribFormatに渡す内容)。
// 頂点の形式はこれの配列で表す(例:constexpr VertexAttrib kLayout[] = {...})
// Describes one vertex attribute (what glVertexArrayAttribFormat needs).
// A vertex format is an array of these (e.g. constexpr VertexAttrib kLayout[] = {...})
struct VertexAttrib {
GLuint location; // シェーダーの layout(location = N) / the shader's layout(location = N)
GLint components; // 成分の数(vec3なら3) / number of components (3 for a vec3)
GLuint offset; // 頂点の先頭からのバイト数(offsetof) / bytes from the vertex start (offsetof)
GLenum type = GL_FLOAT; // 成分の型 / component type
GLboolean normalized = GL_FALSE; // 整数を0〜1にするか / map integers to 0..1?
};
フィールドは、glVertexArrayAttribFormat(vao, attribIndex, size, type, normalized, relativeOffset)の引数其の物です:
location:属性の番号。頂点シェーダーのlayout(location = N)と一致させます。components:1〜4。vec3なら3です。シェーダーがバッファより多くの成分を宣言している場合、足りない成分は(0, 0, 0, 1)から補われます。従って、floatを3つしか渡さないvec4のwは1になります。offset:頂点の先頭からの相対オフセット(バイト)。offsetofでコンパイラーに計算させます。type:メモリ上での各成分の型。例えばGL_FLOAT、GL_HALF_FLOAT、GL_UNSIGNED_BYTE、GL_SHORTです。normalized:整数型の時だけ意味があります。GL_TRUEなら、0〜255のunsigned charはシェーダーでは0.0〜1.0のfloatになります(符号付きの型なら−1.0〜1.0)。GL_FALSEなら、同じ値のfloatに変換されるだけなので、255は255.0になります。
ColorVertexの形式は、main.ccで構造体の直ぐ隣に置いた、此れの2要素の配列です:
// この形式をVAOに教える / tells the VAO about this format
constexpr VertexAttrib kColorVertexLayout[] = {
{0, 3, offsetof(ColorVertex, position)}, // layout(location = 0) in vec3 aPosition
{1, 3, offsetof(ColorVertex, color)}, // layout(location = 1) in vec3 aColor
};
デフォルト値のあるメンバー(type、normalized)は省略しています。
後の頂点の型も同じ書き方で自分の配列を持ちます(第6章でテクスチャ座標付きの物、第8章で完全な3D頂点を追加します)。
注意: 何故std::initializer_listではなくconstexprの配列なのでしょうか?initializer_listの裏の配列は隠れた一時オブジェクトで、其の寿命はリストを置く場所で変わります(グローバルなら問題無く、クラスのメンバーや戻り値ならダングリングになります)。此れはC++の有名な罠です。constexprの配列は静的な記憶域を持ち、Meshが受け取るstd::span<const VertexAttrib>に自動で変換されます。
属性の形式で良くある間違いです。
どれもコンパイルも実行も出来て、GLのエラーも出ません:
glEnableVertexArrayAttribを忘れる。 無効な属性はバッファを全く読みません。代わりにシェーダーは定数(デフォルトでは(0, 0, 0, 1))を受け取るので、色が全部黒になります。下のループなら忘れる事は出来ません。- オフセットやストライドの間違い。 シェーダーが位置の半分と色の半分を読み、図形がバラバラな三角形に爆発します。
offsetofとsizeof(Vertex)を使えば、手で数えた数字は要りません。 - シェーダーに存在しないlocation。 データは読まれますが、黙って無視されます。
- 整数の属性。
glVertexArrayAttribFormatは常にfloatを渡します。シェーダーでivec4やuvec4を使うなら(例えばボーンの番号)、normalized引数の無いglVertexArrayAttribIFormatが必要です。
4.5 Meshクラス
Meshは、1回の描画に必要な物を全て持ちます。
VAO、頂点バッファ、任意のインデックスバッファ、頂点又はインデックスの数、そしてプリミティブの種類です。
// 一つの描画単位(RAII、コピー不可・移動可)。インデックスが空ならglDrawArraysで描く。
// One drawable unit (RAII, non-copyable, movable). With no indices it draws with glDrawArrays.
class Mesh {
public:
Mesh() = default;
// 任意の頂点構造体の配列から作る / build from an array of any vertex struct
template <typename Vertex>
Mesh(const std::vector<Vertex> &vertices, const std::vector<std::uint32_t> &indices,
std::span<const VertexAttrib> layout, GLenum mode = GL_TRIANGLES)
: Mesh(vertices.data(), static_cast<GLsizeiptr>(vertices.size() * sizeof(Vertex)),
static_cast<GLsizei>(sizeof(Vertex)), static_cast<GLsizei>(vertices.size()), indices, layout, mode) {}
~Mesh();
Mesh(const Mesh &) = delete;
Mesh &operator=(const Mesh &) = delete;
Mesh(Mesh &&other) noexcept;
Mesh &operator=(Mesh &&other) noexcept;
void draw() const;
GLuint vao() const { return vertexArray; }
private:
Mesh(const void *vertexData, GLsizeiptr vertexBytes, GLsizei stride, GLsizei numVertices,
const std::vector<std::uint32_t> &indices, std::span<const VertexAttrib> layout, GLenum mode);
GLuint vertexArray = 0;
Buffer vertexBuffer;
Buffer indexBuffer;
GLsizei vertexCount = 0;
GLsizei indexCount = 0;
GLenum primitive = GL_TRIANGLES; // GL_TRIANGLES, GL_LINES, GL_POINTS…
};
公開コンストラクターはテンプレートなので、どんな頂点構造体でも使えます。
やっている事は、vectorをポインター、バイト数、ストライド、頂点数に変えて、privateのコンストラクターに渡すだけです。
本当の処理は其のprivateのコンストラクターにあり、mesh.ccに書きます。
こうすると、GLのコードは頂点の型毎ではなく1回だけコンパイルされます。
#include "mesh.hh"
#include <utility>
Mesh::Mesh(const void *vertexData, GLsizeiptr vertexBytes, GLsizei stride, GLsizei numVertices,
const std::vector<std::uint32_t> &indices, std::span<const VertexAttrib> layout, GLenum mode)
: vertexBuffer(vertexData, vertexBytes), vertexCount(numVertices),
indexCount(static_cast<GLsizei>(indices.size())), primitive(mode) {
glCreateVertexArrays(1, &vertexArray);
// 頂点バッファをバインディング0に繋ぐ / attach the vertex buffer to binding 0
glVertexArrayVertexBuffer(vertexArray, 0, vertexBuffer.id(), 0, stride);
// 各属性の形式と、どのバインディングから読むか / each attribute's format and which binding it reads
for (const VertexAttrib &a : layout) {
glEnableVertexArrayAttrib(vertexArray, a.location);
glVertexArrayAttribFormat(vertexArray, a.location, a.components, a.type, a.normalized, a.offset);
glVertexArrayAttribBinding(vertexArray, a.location, 0);
}
// インデックスバッファはVAOに一つだけ / a VAO has exactly one index buffer
if (!indices.empty()) {
indexBuffer = Buffer(indices.data(), static_cast<GLsizeiptr>(indices.size() * sizeof(std::uint32_t)));
glVertexArrayElementBuffer(vertexArray, indexBuffer.id());
}
}
順番に見ていきます:
- メンバー初期化リストで頂点バッファを作り(4.2の
Bufferのコンストラクター)、数とプリミティブの種類を保存します。 glCreateVertexArraysで空のVAOを作ります。glVertexArrayVertexBuffer(vao, bindingIndex, buffer, offset, stride)で、頂点バッファをバインディング0に繋ぎます。開始は0バイト目、stride = sizeof(Vertex)です。- レイアウトの各属性について、有効にし、形式を記述し、バインディング0に繋ぎます。
- インデックスがあれば、其の為の2つ目の
Bufferを作り、VAOのエレメントバッファとして繋ぎます。詳しくは4.7で説明します。
ムーブ操作とデストラクターはBufferと同じ形です。
vertexBufferとindexBufferはBufferのメンバーなので自分で削除されます。
デストラクターが削除するのはVAOだけです。
Mesh::~Mesh() {
if (vertexArray) glDeleteVertexArrays(1, &vertexArray);
}
Mesh::Mesh(Mesh &&other) noexcept
: vertexArray(std::exchange(other.vertexArray, 0)), vertexBuffer(std::move(other.vertexBuffer)),
indexBuffer(std::move(other.indexBuffer)), vertexCount(other.vertexCount), indexCount(other.indexCount),
primitive(other.primitive) {}
Mesh &Mesh::operator=(Mesh &&other) noexcept {
if (this != &other) {
if (vertexArray) glDeleteVertexArrays(1, &vertexArray);
vertexArray = std::exchange(other.vertexArray, 0);
vertexBuffer = std::move(other.vertexBuffer);
indexBuffer = std::move(other.indexBuffer);
vertexCount = other.vertexCount;
indexCount = other.indexCount;
primitive = other.primitive;
}
return *this;
}
描画ではVAOをバインドし、2つの描画コマンドのどちらかを呼びます:
void Mesh::draw() const {
glBindVertexArray(vertexArray);
if (indexCount > 0) {
// インデックスで頂点を選ぶ / pick vertices through the indices
glDrawElements(primitive, indexCount, GL_UNSIGNED_INT, nullptr);
} else {
glDrawArrays(primitive, 0, vertexCount);
}
}
glDrawArraysは第3章のコマンドです。
glDrawElementsは新しいので、シェーダーの後で節を1つ使って説明します。
4.6 シェーダー:2つ目の属性と補間
シェーダーはまだmain.ccの中の文字列です(次の章でファイルに移します)。
頂点シェーダーは2つ目の入力を受け取り、其れを次へ渡します:
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);
}
)";
頂点シェーダーは頂点毎に1回実行されてvColorを書き、フラグメントシェーダーはピクセル毎に1回実行されてvColorを読みます。
此の2つの宣言は、プログラムをリンクする時に名前で対応付けられ(layout(location = N)を書けば其の番号で)、型も一致しなければなりません。
片方の名前を打ち間違えるとリンクエラーになり、第3章のlinkProgramが其れを表示します。
でも頂点は3つで、ピクセルは何百個もあります。
三角形の真ん中のピクセルは、どの色になるのでしょうか?
ラスタライザーはピクセルの中心毎に、0以上で合計が1になる3つの重み(重心座標)を計算し、其れで3つの頂点の値を混ぜます:
重みの求め方はGLSLシリーズの第3章で説明しました。
RGBの三角形で、を赤、を緑、を青として、2つのピクセルを確かめてみましょう:
- 下の辺の真ん中は頂点0と頂点1の丁度中間なので、、です。色はで、暗いオリーブ色です。スクリーンショットでも見えます。
- 三角形の中心(重心)はなので、色はの暗い灰色です。
補間は頂点シェーダーの全ての出力のデフォルトですが、outとinの前に修飾子を付けると変えられます:
| 修飾子 | フラグメントシェーダーが受け取る値 |
|---|---|
smooth(デフォルト) |
パースペクティブ補正付きで補間(3Dで意味を持ちます、第8章) |
noperspective |
画面空間で線型に補間 |
flat |
補間無し:1つの頂点(三角形の最後の頂点、「プロボーキング頂点」)の値 |
整数の出力(int、ivec2等)は混ぜようが無いので、flatにしなければなりません。
4.7 インデックスバッファ
四角形は2つの三角形です。
glDrawArraysなら6つの頂点が必要で、三角形が対角線を共有するので、其の内の2つは全く同じ物のコピーになります。
インデックスバッファを使うと、4つの角を1回だけ保存し、三角形は其れらへの番号(インデックス)で並べます:
main.ccでは次の通りです:
// 2. 四角形:頂点4つ+インデックス6つ(三角形2つが2頂点を共有)
// A quad: 4 vertices + 6 indices (the two triangles share 2 vertices)
std::vector<ColorVertex> quadVertices = {
{{-0.14f, 0.20f, 0.0f}, {1.0f, 0.8f, 0.2f}}, // 0 左下 / bottom left
{{ 0.14f, 0.20f, 0.0f}, {1.0f, 0.3f, 0.3f}}, // 1 右下 / bottom right
{{ 0.14f, 0.70f, 0.0f}, {0.6f, 0.2f, 0.8f}}, // 2 右上 / top right
{{-0.14f, 0.70f, 0.0f}, {0.2f, 0.6f, 1.0f}}, // 3 左上 / top left
};
std::vector<std::uint32_t> quadIndices = {
0, 1, 2, // 一つ目の三角形 / first triangle
2, 3, 0, // 二つ目の三角形 / second triangle
};
Mesh quad(quadVertices, quadIndices, kColorVertexLayout);
両方の三角形は反時計回り(0 → 1 → 2と2 → 3 → 0)で、此れがOpenGLのデフォルトの表面の向きです。
今はまだ関係ありませんが、第16章で裏面を捨てる(カリング)様になると、順番が正しくなければなりません。
バイト数を数えてみましょう。
インデックス無しでは、四角形の頂点はバイト必要です。
インデックス有りでは、頂点がバイト、インデックスがバイトで、合計バイトです。
大した差には見えませんが、メッシュが大きくなる程差は広がります。
閉じた三角形メッシュでは、1つの頂点を平均で約6つの三角形が共有しています。
仕事も減ります。
GPUは最近実行した頂点シェーダーの結果をインデックスをキーにした小さなキャッシュに残すので、複数の三角形が使う頂点は1回しか計算されない事が良くあります。
インデックスバッファを繋ぐ:glVertexArrayElementBuffer
glVertexArrayElementBuffer(vao, buffer)は、bufferをvaoのエレメント(インデックス)バッファにします。
引数は此の2つだけで、1つのVAOが持てるエレメントバッファは1つだけです。
VAOが其れを覚えているので、Mesh::drawはバッファを何もバインドしません。
VAOをバインドするだけで十分です。
注意: 第3章の「バインドしてから編集する」古い方式では、VAOをバインドした状態でglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo)を呼んでインデックスバッファを繋ぎます。此のバインドポイントはVAOの状態だからです。其の悪名高い結果として、VAOがバインドされたままインデックスバッファのバインドを外すと、VAOから外れてしまい、次の描画が失敗します。DSAには此の罠がありません。
インデックスで描く:glDrawElements
glDrawElements(mode, count, type, indices)は、バインドされたVAOのエレメントバッファを通して頂点を選びながら、count個の頂点を描きます:
mode:プリミティブの種類で、glDrawArraysと同じです(GL_TRIANGLES等、4.9を参照)。count:読むインデックスの数で、三角形の数ではありません。四角形なら6です。type:バッファの中のインデックスの型で、GL_UNSIGNED_BYTE、GL_UNSIGNED_SHORT、GL_UNSIGNED_INTのどれかです。此のシリーズのインデックスは常にstd::uint32_tなので、MeshはGL_UNSIGNED_INTを渡します。indices:名前とポインター型に騙されないで下さい。此れはエレメントバッファの中のバイトオフセットを、ポインターとして渡す物です。先頭から読むのでnullptr(オフセット0)です。四角形の2つ目の三角形から始めたいなら、(void *)(3 * sizeof(std::uint32_t))を渡します。
良くある間違い:
countに三角形の数を渡す:メッシュの3分の1しか描かれません。- データと合わない
type。32ビットのインデックスにGL_UNSIGNED_SHORTを指定すると、各インデックスを2つの半分として読み、メッシュがぐちゃぐちゃになります。 - エレメントバッファを繋いでいない。コアプロファイルでは最後の引数にCPUのポインターを渡す事はもう出来ないので、エレメントバッファの無い
glDrawElementsはGL_INVALID_OPERATIONになり、デバッグロガーが表示します。 - 最後の頂点より大きいインデックス。結果は未定義です。0を返すドライバーもゴミを返すドライバーもあるので、どちらも当てにしないで下さい。
4.8 計算で作る図形:六角形
四角形なら座標を手で書いても構いませんが、丸い物は計算した方が楽です。
makePolygonは、中心の頂点と円周上のsides個の頂点から正多角形を作ります:
// 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;
// 色相(0〜1)から鮮やかな色 / a saturated colour from a hue in 0..1
static Vec3 hueColor(float h) {
auto channel = [h](float offset) {
return 0.5f + 0.5f * std::cos(2.0f * PI * (h + offset));
};
return {channel(0.0f), channel(2.0f / 3.0f), channel(1.0f / 3.0f)};
}
// 中心+周りの頂点で正多角形。インデックスで中心を共有する。
// A regular polygon from a centre plus a ring of vertices. The indices share the centre vertex.
static Mesh makePolygon(Vec2 center, float radius, int sides) {
std::vector<ColorVertex> vertices = {{{center.x, center.y, 0.0f}, {1.0f, 1.0f, 1.0f}}};
std::vector<std::uint32_t> indices;
for (int i = 0; i < sides; ++i) {
float a = 2.0f * PI * static_cast<float>(i) / static_cast<float>(sides);
vertices.push_back({{center.x + radius * kAspectFix * std::cos(a), center.y + radius * std::sin(a), 0.0f},
hueColor(static_cast<float>(i) / static_cast<float>(sides))});
std::uint32_t current = static_cast<std::uint32_t>(i + 1);
std::uint32_t next = static_cast<std::uint32_t>((i + 1) % sides + 1);
indices.insert(indices.end(), {0, current, next}); // 三角形一つ / one triangle
}
return Mesh(vertices, indices, kColorVertexLayout);
}
頂点0は白い中心です。
頂点は円周上の角度の位置、つまり次の座標にあります:
(半径の円の上の角度の点を、横に倍縮めた物です)。
係数(kAspectFix)は一時的な誤魔化しです。
NDCは縦も横も−1から1迄ですが、ウィンドウは横1280ピクセル、縦720ピクセルなので、NDCの1は縦より横の方が長く、正直に円を描くと楕円になってしまいます。
此れが何処から来るのかは線型代数シリーズの第12章で説明しました。
第7章で行列、第8章で投影変換を使って直すと、kAspectFixは無くなります。
円周上の各頂点の色はhueColorが決めます。
3分の1回転ずつずらした3つのコサイン波から虹色を作る関数です:
(一番右の頂点)ならで、明るい赤です。
三角形はインデックス、、を使います。
剰余のお陰で、最後の三角形は頂点1に戻ります。
なら三角形は(0, 1, 2)、(0, 2, 3)、(0, 3, 4)、(0, 4, 5)、(0, 5, 6)、(0, 6, 1)です。
従って六角形には頂点とインデックスが必要で、バイトです。
インデックス無しならバイトになります。
白い中心を6つの三角形全てが共有しているので、スクリーンショットの様に、補間された色は真ん中の白から角の色相へと滑らかに変わります。
4.9 プリミティブの種類
此処迄の描画は全てGL_TRIANGLES、つまり3頂点で三角形1つでした。
glDrawArraysとglDrawElementsのmode引数を変えると、同じ頂点の列を別の形に解釈出来ます。
実際に出会う7つのモードを、其々6つの頂点に使った図です:
| モード | 個の頂点がどうなるか |
|---|---|
GL_POINTS |
個の点 |
GL_LINES |
本の別々の線:0–1、2–3、… |
GL_LINE_STRIP |
繋がった本の線:0–1、1–2、2–3、… |
GL_LINE_LOOP |
本の線:ラインストリップに、最後の頂点から0へ戻る線を足した物 |
GL_TRIANGLES |
個の別々の三角形:(0, 1, 2)、(3, 4, 5)、… |
GL_TRIANGLE_STRIP |
個の三角形:新しい頂点が直前の2つと三角形を作る |
GL_TRIANGLE_FAN |
全て頂点0を共有する個の三角形:(0, 1, 2)、(0, 2, 3)、… |
古いGL_QUADSとGL_POLYGONはコアプロファイルにはありません。
四角形は常に2つの三角形です。
デモではGL_TRIANGLESの他に3つのモードを使っています。
GL_POINTS:点の格子
makePointsは5 × 3の格子状の頂点を作り、インデックスは使いません:
// 5×3の点 / a 5×3 grid of points
static Mesh makePoints(Vec2 center) {
std::vector<ColorVertex> vertices;
for (int y = 0; y < 3; ++y)
for (int x = 0; x < 5; ++x)
vertices.push_back({{center.x + (static_cast<float>(x) - 2.0f) * 0.07f, center.y + (static_cast<float>(y) - 1.0f) * 0.12f, 0.0f},
hueColor(static_cast<float>(x + 5 * y) / 15.0f)});
return Mesh(vertices, {}, kColorVertexLayout, GL_POINTS);
}
各点は、頂点を中心にしたglPointSizeピクセルの正方形です。
mainで一度だけglPointSize(10.0f)として10ピクセルにしています。
シェーダーでgl_PointSizeに書いて頂点毎に大きさを決める事も出来ますが、其れにはglEnable(GL_PROGRAM_POINT_SIZE)が必要です。
有効にしなければglPointSizeの値が使われます。
点は常に画面を向いた正方形なので、デバッグに便利です(メッシュの頂点、ライトの位置、パーティクル等を描く時)。
GL_LINE_LOOP:星
makeStarは外側の半径と其の0.4倍の半径を交互に使って2つの円の上に10個の頂点を置き、閉じた線として描きます:
// 星形の線(GL_LINE_LOOPは最後の頂点と最初を繋ぐ) / a star outline (GL_LINE_LOOP joins the last vertex to the first)
static Mesh makeStar(Vec2 center, float radius) {
std::vector<ColorVertex> vertices;
for (int i = 0; i < 10; ++i) {
float a = PI * 0.5f + PI * static_cast<float>(i) / 5.0f;
float r = (i % 2 == 0) ? radius : radius * 0.4f;
vertices.push_back({{center.x + r * kAspectFix * std::cos(a), center.y + r * std::sin(a), 0.0f},
hueColor(static_cast<float>(i) / 10.0f)});
}
return Mesh(vertices, {}, kColorVertexLayout, GL_LINE_LOOP);
}
最初の頂点は(真上)にあり、1歩毎に進むので、10歩で丁度1周です。
GL_LINE_LOOPは9から0への線を自分で足してくれます。
GL_LINE_STRIPだと星に隙間が出来ます。
線の幅は1ピクセルです。
glLineWidthはありますが、コアプロファイルで確実に動くのは幅1.0だけなので、エンジンは太い線を三角形で出来た細長い四角形として描きます。
GL_TRIANGLE_STRIP:リボン
makeRibbonはサイン波の下と上に頂点を1組ずつ作り、ストリップとして描きます:
// 波打つリボン(GL_TRIANGLE_STRIPは頂点を一つ足すごとに三角形が一つ増える)
// A wavy ribbon (GL_TRIANGLE_STRIP: every extra vertex adds one triangle)
static Mesh makeRibbon(Vec2 center) {
std::vector<ColorVertex> vertices;
for (int i = 0; i < 10; ++i) {
float t = static_cast<float>(i) / 9.0f;
float x = center.x + (t - 0.5f) * 0.45f;
float wave = 0.08f * std::sin(t * 2.0f * PI);
Vec3 color = hueColor(t * 0.5f);
vertices.push_back({{x, center.y + wave - 0.08f, 0.0f}, color});
vertices.push_back({{x, center.y + wave + 0.08f, 0.0f}, 0.6f * color});
}
return Mesh(vertices, {}, kColorVertexLayout, GL_TRIANGLE_STRIP);
}
10組で20頂点になり、ストリップは其れを個の三角形にします。
別々の三角形で描くなら、同じリボンに頂点が必要です。
ストリップの三角形は頂点、、を使いますが、が奇数の時、OpenGLは最初の2つを入れ替えて(k + 1, k, k + 2)にします。
其の為、ストリップの全ての三角形が同じ向きになります。
各組の上の頂点は暗く(0.6f * color)してあるので、リボンに陰影が付きます。
昔のハードウェアでは、ストリップはとても重要でした。
今は頂点キャッシュのお陰でインデックス付きのGL_TRIANGLESも大抵同じ位速く、生成するのもずっと簡単なので、殆どのエンジンは全てを此れで描きます。
表の残りのGL_TRIANGLE_FANは、課題3で六角形を作り直す時に使います。
4.10 mainで全部を組み立てる
ウィンドウから描画ループ迄のmainです。
シェーダーの補助関数compileShaderとlinkProgramは第3章から変わっていない(コメントを短くしただけ)ので、繰り返しません。
int main() {
Window window;
if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 4")) 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_P) {
wireframe = !wireframe;
// 三角形を線で描く(デバッグに便利) / draw triangles as lines (handy for debugging)
glPolygonMode(GL_FRONT_AND_BACK, wireframe ? GL_LINE : GL_FILL);
}
};
// 1. 色付きの三角形:色は三角形の中で補間される / a coloured triangle: colours are interpolated inside it
std::vector<ColorVertex> triangleVertices = {
{{-0.85f, 0.20f, 0.0f}, {1.0f, 0.0f, 0.0f}}, // 赤 / red
{{-0.35f, 0.20f, 0.0f}, {0.0f, 1.0f, 0.0f}}, // 緑 / green
{{-0.60f, 0.75f, 0.0f}, {0.0f, 0.0f, 1.0f}}, // 青 / blue
};
Mesh triangle(triangleVertices, {}, kColorVertexLayout);
最初のメッシュはRGBの三角形です。
インデックスが無い({}は空のインデックスのvector)ので、draw()はglDrawArraysを使います。
次に4.7の四角形と、計算で作る4つの図形です:
// 3〜6. 計算で作る図形(VAOはそれぞれ別) / generated shapes (each has its own VAO)
Mesh hexagon = makePolygon({0.6f, 0.45f}, 0.27f, 6);
Mesh points = makePoints({-0.6f, -0.45f});
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
全てのメッシュが同じシェーダープログラムと同じ頂点形式を使います。
描画ループではプログラムを1回だけ有効にし、其の後で全てのメッシュを描きます。
其々のdraw()が自分のVAOをバインドします:
while (!window.shouldClose()) {
window.pollEvents();
glClearColor(0.10f, 0.15f, 0.25f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(program);
triangle.draw();
quad.draw();
hexagon.draw();
points.draw();
star.draw();
ribbon.draw();
window.swapBuffers();
}
glDeleteProgram(program);
return 0; // メッシュはここで自動的に削除される / the meshes are deleted automatically here
}
最後のglDeleteVertexArraysやglDeleteBuffersはもうありません。
mainから戻る時にメッシュが(宣言と逆の順に)破棄され、其々が自分のVAOとバッファを削除し、其の後でやっとウィンドウが破棄されます。
プログラムはまだ生のGLuintですが、第5章で此れもクラスにします。
描画の間にVAOを切り替えるのは軽い処理で、全てのレンダラーが此の様に動いています。
頂点形式とバッファの組み合わせ毎に1つのVAOを持ち、描画の直前にバインドします。
4.11 ワイヤーフレーム表示
Pキーは、GLのグローバルな状態を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_P) {
wireframe = !wireframe;
// 三角形を線で描く(デバッグに便利) / draw triangles as lines (handy for debugging)
glPolygonMode(GL_FRONT_AND_BACK, wireframe ? GL_LINE : GL_FILL);
}
};
glPolygonMode(face, mode)は、ポリゴンをどうラスタライズするかを決めます:
face:コアプロファイルではGL_FRONT_AND_BACKでなければなりません。古いGL_FRONTとGL_BACKは、今はGL_INVALID_ENUMエラーです。mode:GL_FILL(デフォルト)は三角形を塗り潰し、GL_LINEは辺だけ、GL_POINTは角だけを描きます。
此れで各図形の構造が見えます。
四角形の2つの三角形が共有する対角線、六角形の中心の周りの6つの三角形、そしてストリップのジグザグです。
点と星は全く変わりません。
glPolygonModeはポリゴンにしか効かず、点と線には関係無いからです。
辺の色も補間されたままで、今度は線に沿って補間されている事にも注目して下さい。
ポリゴンモードはグローバルな状態なので、誰かが戻す迄、其の後の全ての描画に効き続けます。
此れはOpenGLのステートマシン(第2章)の典型で、「何故か急にUIが線で描かれる」と言うバグの良くある原因です。
ワイヤーフレーム表示は、グラフィックスで最も役に立つデバッグ道具の1つです。
メッシュが思った通りの三角形で出来ているか、一目で分かります。
4.12 実際のエンジンでのやり方
- 頂点形式はデータ。 エンジンはあたし達の
VertexAttribの配列の様な表で頂点のレイアウトを記述し(メッシュのファイルから生成する事も多いです)、レイアウト毎に1つのVAO(Vulkanならパイプラインの頂点入力の状態)を作ります。 - 属性の圧縮。 色は
normalized = GL_TRUEのGL_UNSIGNED_BYTE4つ(12バイトではなく4バイト)、法線は10ビットずつ詰めた整数(GL_INT_2_10_10_10_REV)、テクスチャ座標はGL_HALF_FLOATにします。頂点が小さい程メモリの帯域を使わず、其れが本当のボトルネックである事が多いです。 - 16ビットのインデックス。 頂点が65,536個以下のメッシュなら、インデックスのメモリが半分になります。glTFファイル(第13章)は8・16・32ビットのインデックスを使い、此のシリーズのローダーは其れを32ビットに変換します。
- インデックスバッファの最適化。 ツールで三角形を並べ替えて、続く三角形がまだ頂点キャッシュにある頂点を使い回せる様にし、更に頂点を並べ替えてメモリを順番に読める様にします。
- プリミティブリスタート。
glEnable(GL_PRIMITIVE_RESTART_FIXED_INDEX)を使うと、インデックスの最大値(32ビットなら0xFFFFFFFF)で今のストリップやループを終わらせて新しく始められるので、沢山のストリップを1回の描画コマンドに詰められます。 - 特別なパスの為の分離ストリーム。 深度だけのパスやシャドウパスは位置しか要らないので、位置を他の属性とは別のバッファに置くエンジンもあります。
4.13 まとめ
- 頂点は複数の属性を持てます。インターリーブでは頂点毎に属性を並べ、属性のアドレスはオフセット + i × ストライド + 相対オフセットです。
VertexAttribとconstexprのレイアウト配列で頂点形式をデータとして書き、Meshが其れをglEnableVertexArrayAttrib、glVertexArrayAttribFormat、glVertexArrayAttribBindingの呼び出しに変えます。- 頂点シェーダーの出力は、フラグメントシェーダーが読む前に重心座標の重みで補間されます。
flatとnoperspectiveで変えられます。 - インデックスバッファは各頂点を1回だけ保存し、三角形をインデックスで並べます。
glVertexArrayElementBufferでVAOに繋ぎ、glDrawElementsで描きます。countはインデックスの数で、最後の引数はバイトオフセットです。 - プリミティブの種類は頂点の列の解釈を変えます:点、線、ラインストリップとループ、三角形、トライアングルストリップとファン。
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)は全ての図形の三角形を見せてくれるグローバルな状態です。BufferとMeshはRAIIクラスです。コピー禁止、移動可能で、ウィンドウより先に破棄されます。
4.14 課題
- ★ 四角形の4つの角に新しい色を付けて下さい(例えば反時計回りに赤・黄・緑・青)。各角は1回だけ保存されてインデックスで共有されているので、変えるのは4行だけです。対角線の見えない、滑らかな4色のグラデーションになるはずです。
- ★
makePolygonのsidesを3、5、32に変えて下さい。三角形、五角形、そして縁に虹色が一周するほぼ完全な円になるはずです。毎回Pを押して三角形を数えて下さい。 - ★★ 六角形を
GL_TRIANGLE_FANでインデックス無しに作り直して下さい。中心の頂点、円周上の6頂点、もう一度最初の円周上の頂点(合計8頂点)です。ワイヤーフレームも含めて、インデックス付きの六角形と全く同じ絵になるはずです。 - ★★ 横に32分割、縦に16段の球(継ぎ目の頂点を重複させると頂点、三角形は個)が、24バイトの頂点と32ビットのインデックスで、インデックス有りと無しで何バイト必要か紙の上で計算して下さい。次に16ビットのインデックスでも計算して下さい。インデックス有りはおよそ3分の1、16ビットならおよそ4分の1の大きさになるはずです。
- ★★ 色を
Vec3ではなく4つのstd::uint8_tで保存して下さい({1, 4, offsetof(…), GL_UNSIGNED_BYTE, GL_TRUE}と0〜255の値)。絵は変わらず、頂点のsizeofは24バイトから16バイトに減るはずです。normalizedをGL_FALSEにするとどうなるでしょうか? - ★★★ RGBの三角形を非インターリーブで作って下さい。位置を1つの
Bufferに、色をもう1つのBufferに入れ、バインディング0と1に繋ぎます(Meshを拡張するか、DSAの関数を直接呼びます)。結果は同じ見た目になるはずです。其の上で、どちらのレイアウトがどんな時に良いのか、自分の言葉で説明して下さい。 - ★★★
glDrawElementsに0ではないオフセットを渡して、四角形の2つ目の三角形だけを描いて下さい。次にglPolygonMode(GL_FRONT_AND_BACK, GL_POINT)と点の大きさ10を試して下さい。半分の四角形が見え、其の次は全ての三角形の角だけが見えるはずです。
ファイル: a/CMakeLists.txt | b/CMakeLists.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -22,7 +22,9 @@ target_include_directories(glad PUBLIC external/glad/include) | |||
| 22 | add_executable(game | 22 | add_executable(game |
| 23 | src/main.cc | 23 | src/main.cc |
| 24 | src/window.cc | 24 | src/window.cc |
| 25 | src/gl_debug.cc) | 25 | src/gl_debug.cc |
| 26 | src/buffer.cc | ||
| 27 | src/mesh.cc) | ||
| 26 | target_include_directories(game PRIVATE src external/stb external/linalg) | 28 | target_include_directories(game PRIVATE src external/stb external/linalg) |
| 27 | target_link_libraries(game PRIVATE glad glfw) | 29 | target_link_libraries(game PRIVATE glad glfw) |
| 28 | 30 | ||
ファイル: /dev/null | b/src/buffer.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,25 @@ | |||
| 1 | #include "buffer.hh" | ||
| 2 | |||
| 3 | #include <utility> | ||
| 4 | |||
| 5 | Buffer::Buffer(const void *data, GLsizeiptr byteCount, GLbitfield flags) : bytes(byteCount) { | ||
| 6 | glCreateBuffers(1, &handle); | ||
| 7 | glNamedBufferStorage(handle, byteCount, data, flags); | ||
| 8 | } | ||
| 9 | |||
| 10 | Buffer::~Buffer() { | ||
| 11 | if (handle) glDeleteBuffers(1, &handle); | ||
| 12 | } | ||
| 13 | |||
| 14 | // 移動したら元のオブジェクトは空(0)になる / a moved-from object becomes empty (0) | ||
| 15 | Buffer::Buffer(Buffer &&other) noexcept | ||
| 16 | : handle(std::exchange(other.handle, 0)), bytes(std::exchange(other.bytes, 0)) {} | ||
| 17 | |||
| 18 | Buffer &Buffer::operator=(Buffer &&other) noexcept { | ||
| 19 | if (this != &other) { | ||
| 20 | if (handle) glDeleteBuffers(1, &handle); | ||
| 21 | handle = std::exchange(other.handle, 0); | ||
| 22 | bytes = std::exchange(other.bytes, 0); | ||
| 23 | } | ||
| 24 | return *this; | ||
| 25 | } | ||
ファイル: /dev/null | b/src/buffer.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,27 @@ | |||
| 1 | // GPUのバッファ / a GPU buffer | ||
| 2 | #pragma once | ||
| 3 | |||
| 4 | #include <glad/glad.h> | ||
| 5 | |||
| 6 | // バッファオブジェクト(RAII、コピー不可・移動可)。 | ||
| 7 | // A buffer object (RAII, non-copyable, movable). | ||
| 8 | class Buffer { | ||
| 9 | public: | ||
| 10 | Buffer() = default; | ||
| 11 | // 不変ストレージ(glNamedBufferStorage)を作ってdataをコピーする。flags=0なら後から書き換えられない。 | ||
| 12 | // Creates immutable storage (glNamedBufferStorage) and copies data in. flags = 0: cannot be updated later. | ||
| 13 | Buffer(const void *data, GLsizeiptr byteCount, GLbitfield flags = 0); | ||
| 14 | ~Buffer(); | ||
| 15 | |||
| 16 | Buffer(const Buffer &) = delete; | ||
| 17 | Buffer &operator=(const Buffer &) = delete; | ||
| 18 | Buffer(Buffer &&other) noexcept; | ||
| 19 | Buffer &operator=(Buffer &&other) noexcept; | ||
| 20 | |||
| 21 | GLuint id() const { return handle; } | ||
| 22 | GLsizeiptr size() const { return bytes; } | ||
| 23 | |||
| 24 | private: | ||
| 25 | GLuint handle = 0; | ||
| 26 | GLsizeiptr bytes = 0; | ||
| 27 | }; | ||
ファイル: a/src/main.cc | b/src/main.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,29 +1,50 @@ | |||
| 1 | // 第3章:こんにちは三角形 | 1 | // 第4章:頂点属性とインデックスバッファ |
| 2 | // Chapter 3: Hello Triangle | 2 | // Chapter 4: vertex attributes and index buffers |
| 3 | // | ||
| 4 | // 操作 / Controls: P ワイヤーフレーム切り替え / toggle wireframe, Esc 終了 / quit | ||
| 5 | #include "mesh.hh" | ||
| 3 | #include "window.hh" | 6 | #include "window.hh" |
| 4 | 7 | ||
| 8 | #include <linalg.hh> | ||
| 9 | |||
| 10 | #include <cmath> | ||
| 11 | #include <cstddef> | ||
| 5 | #include <cstdio> | 12 | #include <cstdio> |
| 6 | #include <string_view> | 13 | #include <vector> |
| 14 | |||
| 15 | // 位置と色を交互に並べた(インターリーブ)頂点 / a vertex with position and colour interleaved | ||
| 16 | struct ColorVertex { | ||
| 17 | Vec3 position; | ||
| 18 | Vec3 color; | ||
| 19 | }; | ||
| 20 | |||
| 21 | // この形式をVAOに教える / tells the VAO about this format | ||
| 22 | constexpr VertexAttrib kColorVertexLayout[] = { | ||
| 23 | {0, 3, offsetof(ColorVertex, position)}, // layout(location = 0) in vec3 aPosition | ||
| 24 | {1, 3, offsetof(ColorVertex, color)}, // layout(location = 1) in vec3 aColor | ||
| 25 | }; | ||
| 7 | 26 | ||
| 8 | // 頂点シェーダー:頂点ごとに一回実行される / vertex shader: runs once per vertex | ||
| 9 | static const char *kVertexShader = R"(#version 460 core | 27 | static const char *kVertexShader = R"(#version 460 core |
| 10 | layout(location = 0) in vec3 aPosition; | 28 | layout(location = 0) in vec3 aPosition; |
| 29 | layout(location = 1) in vec3 aColor; | ||
| 30 | |||
| 31 | out vec3 vColor; // フラグメントシェーダーへ(補間される) / to the fragment shader (interpolated) | ||
| 11 | 32 | ||
| 12 | void main() { | 33 | void main() { |
| 13 | gl_Position = vec4(aPosition, 1.0); // 座標はそのままNDC / the position is already in NDC | 34 | vColor = aColor; |
| 35 | gl_Position = vec4(aPosition, 1.0); | ||
| 14 | } | 36 | } |
| 15 | )"; | 37 | )"; |
| 16 | 38 | ||
| 17 | // フラグメントシェーダー:ピクセルごとに一回実行される / fragment shader: runs once per pixel | ||
| 18 | static const char *kFragmentShader = R"(#version 460 core | 39 | static const char *kFragmentShader = R"(#version 460 core |
| 40 | in vec3 vColor; | ||
| 19 | layout(location = 0) out vec4 out_color; | 41 | layout(location = 0) out vec4 out_color; |
| 20 | 42 | ||
| 21 | void main() { | 43 | void main() { |
| 22 | out_color = vec4(1.0, 0.55, 0.15, 1.0); // オレンジ / orange | 44 | out_color = vec4(vColor, 1.0); |
| 23 | } | 45 | } |
| 24 | )"; | 46 | )"; |
| 25 | 47 | ||
| 26 | // シェーダーを一つコンパイル。失敗したら0。 / compile one shader stage. Returns 0 on failure. | ||
| 27 | static GLuint compileShader(GLenum type, const char *source) { | 48 | static GLuint compileShader(GLenum type, const char *source) { |
| 28 | GLuint shader = glCreateShader(type); | 49 | GLuint shader = glCreateShader(type); |
| 29 | glShaderSource(shader, 1, &source, nullptr); | 50 | glShaderSource(shader, 1, &source, nullptr); |
| @@ -42,14 +63,11 @@ static GLuint compileShader(GLenum type, const char *source) { | |||
| 42 | return shader; | 63 | return shader; |
| 43 | } | 64 | } |
| 44 | 65 | ||
| 45 | // 二つのシェーダーをプログラムにリンク。失敗したら0。 / link two shaders into a program. Returns 0 on failure. | ||
| 46 | static GLuint linkProgram(GLuint vertexShader, GLuint fragmentShader) { | 66 | static GLuint linkProgram(GLuint vertexShader, GLuint fragmentShader) { |
| 47 | GLuint program = glCreateProgram(); | 67 | GLuint program = glCreateProgram(); |
| 48 | glAttachShader(program, vertexShader); | 68 | glAttachShader(program, vertexShader); |
| 49 | glAttachShader(program, fragmentShader); | 69 | glAttachShader(program, fragmentShader); |
| 50 | glLinkProgram(program); | 70 | glLinkProgram(program); |
| 51 | |||
| 52 | // リンク後はシェーダーオブジェクトは要らない / the shader objects are not needed after linking | ||
| 53 | glDetachShader(program, vertexShader); | 71 | glDetachShader(program, vertexShader); |
| 54 | glDetachShader(program, fragmentShader); | 72 | glDetachShader(program, fragmentShader); |
| 55 | glDeleteShader(vertexShader); | 73 | glDeleteShader(vertexShader); |
| @@ -67,75 +85,113 @@ static GLuint linkProgram(GLuint vertexShader, GLuint fragmentShader) { | |||
| 67 | return program; | 85 | return program; |
| 68 | } | 86 | } |
| 69 | 87 | ||
| 70 | struct TriangleObjects { | 88 | // NDCは横に引き伸ばされる(1280×720)ので、計算で作る図形はxを縮める。第8章で投影行列が解決する。 |
| 71 | GLuint vao = 0; // 頂点配列オブジェクト / vertex array object | 89 | // NDC is stretched horizontally (1280×720), so generated shapes shrink x. Chapter 8's projection fixes this. |
| 72 | GLuint vbo = 0; // 頂点バッファ / vertex buffer | 90 | constexpr float kAspectFix = 720.0f / 1280.0f; |
| 73 | }; | ||
| 74 | 91 | ||
| 75 | // DSA方式(OpenGL 4.5):オブジェクトの名前を直接渡して編集する | 92 | // 色相(0〜1)から鮮やかな色 / a saturated colour from a hue in 0..1 |
| 76 | // DSA style (OpenGL 4.5): edit objects by passing their name directly | 93 | static Vec3 hueColor(float h) { |
| 77 | static TriangleObjects createTriangleDsa(const float *vertices, GLsizeiptr bytes) { | 94 | auto channel = [h](float offset) { |
| 78 | TriangleObjects t; | 95 | return 0.5f + 0.5f * std::cos(2.0f * PI * (h + offset)); |
| 79 | glCreateBuffers(1, &t.vbo); | 96 | }; |
| 80 | glNamedBufferStorage(t.vbo, bytes, vertices, 0); // 0 = 後から書き換えない / 0 = never updated later | 97 | return {channel(0.0f), channel(2.0f / 3.0f), channel(1.0f / 3.0f)}; |
| 81 | |||
| 82 | glCreateVertexArrays(1, &t.vao); | ||
| 83 | // バインディング0にバッファを繋ぐ:オフセット0、一頂点あたり3つのfloat | ||
| 84 | // attach the buffer to binding 0: offset 0, 3 floats per vertex | ||
| 85 | glVertexArrayVertexBuffer(t.vao, 0, t.vbo, 0, 3 * sizeof(float)); | ||
| 86 | // 属性0 = vec3のfloat、頂点の先頭から0バイト、バインディング0から読む | ||
| 87 | // attribute 0 = vec3 of floats, 0 bytes into the vertex, read from binding 0 | ||
| 88 | glEnableVertexArrayAttrib(t.vao, 0); | ||
| 89 | glVertexArrayAttribFormat(t.vao, 0, 3, GL_FLOAT, GL_FALSE, 0); | ||
| 90 | glVertexArrayAttribBinding(t.vao, 0, 0); | ||
| 91 | return t; | ||
| 92 | } | 98 | } |
| 93 | 99 | ||
| 94 | // 古い方式:バインドしてから「今バインドされているもの」を編集する(多くの古いチュートリアル) | 100 | // 中心+周りの頂点で正多角形。インデックスで中心を共有する。 |
| 95 | // Classic style: bind, then edit "whatever is bound" (most older tutorials) | 101 | // A regular polygon from a centre plus a ring of vertices. The indices share the centre vertex. |
| 96 | static TriangleObjects createTriangleClassic(const float *vertices, GLsizeiptr bytes) { | 102 | static Mesh makePolygon(Vec2 center, float radius, int sides) { |
| 97 | TriangleObjects t; | 103 | std::vector<ColorVertex> vertices = {{{center.x, center.y, 0.0f}, {1.0f, 1.0f, 1.0f}}}; |
| 98 | glGenVertexArrays(1, &t.vao); | 104 | std::vector<std::uint32_t> indices; |
| 99 | glBindVertexArray(t.vao); | 105 | for (int i = 0; i < sides; ++i) { |
| 100 | 106 | float a = 2.0f * PI * static_cast<float>(i) / static_cast<float>(sides); | |
| 101 | glGenBuffers(1, &t.vbo); | 107 | vertices.push_back({{center.x + radius * kAspectFix * std::cos(a), center.y + radius * std::sin(a), 0.0f}, |
| 102 | glBindBuffer(GL_ARRAY_BUFFER, t.vbo); | 108 | hueColor(static_cast<float>(i) / static_cast<float>(sides))}); |
| 103 | glBufferData(GL_ARRAY_BUFFER, bytes, vertices, GL_STATIC_DRAW); | 109 | std::uint32_t current = static_cast<std::uint32_t>(i + 1); |
| 110 | std::uint32_t next = static_cast<std::uint32_t>((i + 1) % sides + 1); | ||
| 111 | indices.insert(indices.end(), {0, current, next}); // 三角形一つ / one triangle | ||
| 112 | } | ||
| 113 | return Mesh(vertices, indices, kColorVertexLayout); | ||
| 114 | } | ||
| 104 | 115 | ||
| 105 | // 今GL_ARRAY_BUFFERにバインドされているバッファが属性0に記録される | 116 | // 5×3の点 / a 5×3 grid of points |
| 106 | // the buffer currently bound to GL_ARRAY_BUFFER is recorded for attribute 0 | 117 | static Mesh makePoints(Vec2 center) { |
| 107 | glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), nullptr); | 118 | std::vector<ColorVertex> vertices; |
| 108 | glEnableVertexAttribArray(0); | 119 | for (int y = 0; y < 3; ++y) |
| 120 | for (int x = 0; x < 5; ++x) | ||
| 121 | vertices.push_back({{center.x + (static_cast<float>(x) - 2.0f) * 0.07f, center.y + (static_cast<float>(y) - 1.0f) * 0.12f, 0.0f}, | ||
| 122 | hueColor(static_cast<float>(x + 5 * y) / 15.0f)}); | ||
| 123 | return Mesh(vertices, {}, kColorVertexLayout, GL_POINTS); | ||
| 124 | } | ||
| 109 | 125 | ||
| 110 | glBindVertexArray(0); // 後で誤って変更しないように外す / unbind so it is not changed by accident | 126 | // 星形の線(GL_LINE_LOOPは最後の頂点と最初を繋ぐ) / a star outline (GL_LINE_LOOP joins the last vertex to the first) |
| 111 | return t; | 127 | static Mesh makeStar(Vec2 center, float radius) { |
| 128 | std::vector<ColorVertex> vertices; | ||
| 129 | for (int i = 0; i < 10; ++i) { | ||
| 130 | float a = PI * 0.5f + PI * static_cast<float>(i) / 5.0f; | ||
| 131 | float r = (i % 2 == 0) ? radius : radius * 0.4f; | ||
| 132 | vertices.push_back({{center.x + r * kAspectFix * std::cos(a), center.y + r * std::sin(a), 0.0f}, | ||
| 133 | hueColor(static_cast<float>(i) / 10.0f)}); | ||
| 134 | } | ||
| 135 | return Mesh(vertices, {}, kColorVertexLayout, GL_LINE_LOOP); | ||
| 112 | } | 136 | } |
| 113 | 137 | ||
| 114 | int main(int argc, char **argv) { | 138 | // 波打つリボン(GL_TRIANGLE_STRIPは頂点を一つ足すごとに三角形が一つ増える) |
| 115 | // 「./build/game --classic」で古い「バインドして編集」方式でVAOを作る(結果は同じ) | 139 | // A wavy ribbon (GL_TRIANGLE_STRIP: every extra vertex adds one triangle) |
| 116 | // "./build/game --classic" builds the VAO with the classic bind-to-edit style (same result) | 140 | static Mesh makeRibbon(Vec2 center) { |
| 117 | bool classic = argc > 1 && std::string_view(argv[1]) == "--classic"; | 141 | std::vector<ColorVertex> vertices; |
| 142 | for (int i = 0; i < 10; ++i) { | ||
| 143 | float t = static_cast<float>(i) / 9.0f; | ||
| 144 | float x = center.x + (t - 0.5f) * 0.45f; | ||
| 145 | float wave = 0.08f * std::sin(t * 2.0f * PI); | ||
| 146 | Vec3 color = hueColor(t * 0.5f); | ||
| 147 | vertices.push_back({{x, center.y + wave - 0.08f, 0.0f}, color}); | ||
| 148 | vertices.push_back({{x, center.y + wave + 0.08f, 0.0f}, 0.6f * color}); | ||
| 149 | } | ||
| 150 | return Mesh(vertices, {}, kColorVertexLayout, GL_TRIANGLE_STRIP); | ||
| 151 | } | ||
| 118 | 152 | ||
| 153 | int main() { | ||
| 119 | Window window; | 154 | Window window; |
| 120 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 3")) return 1; | 155 | if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 4")) return 1; |
| 156 | |||
| 157 | bool wireframe = false; | ||
| 121 | window.onKey = [&](int key, int action, int /*mods*/) { | 158 | window.onKey = [&](int key, int action, int /*mods*/) { |
| 122 | if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) window.close(); | 159 | if (action != GLFW_PRESS) return; |
| 160 | if (key == GLFW_KEY_ESCAPE) window.close(); | ||
| 161 | if (key == GLFW_KEY_P) { | ||
| 162 | wireframe = !wireframe; | ||
| 163 | // 三角形を線で描く(デバッグに便利) / draw triangles as lines (handy for debugging) | ||
| 164 | glPolygonMode(GL_FRONT_AND_BACK, wireframe ? GL_LINE : GL_FILL); | ||
| 165 | } | ||
| 123 | }; | 166 | }; |
| 124 | 167 | ||
| 125 | // 三角形の頂点(NDC:x, yは-1〜1) / triangle vertices (NDC: x and y in -1..1) | 168 | // 1. 色付きの三角形:色は三角形の中で補間される / a coloured triangle: colours are interpolated inside it |
| 126 | const float vertices[] = { | 169 | std::vector<ColorVertex> triangleVertices = { |
| 127 | -0.5f, -0.5f, 0.0f, // 左下 / bottom left | 170 | {{-0.85f, 0.20f, 0.0f}, {1.0f, 0.0f, 0.0f}}, // 赤 / red |
| 128 | 0.5f, -0.5f, 0.0f, // 右下 / bottom right | 171 | {{-0.35f, 0.20f, 0.0f}, {0.0f, 1.0f, 0.0f}}, // 緑 / green |
| 129 | 0.0f, 0.5f, 0.0f, // 上 / top | 172 | {{-0.60f, 0.75f, 0.0f}, {0.0f, 0.0f, 1.0f}}, // 青 / blue |
| 173 | }; | ||
| 174 | Mesh triangle(triangleVertices, {}, kColorVertexLayout); | ||
| 175 | |||
| 176 | // 2. 四角形:頂点4つ+インデックス6つ(三角形2つが2頂点を共有) | ||
| 177 | // A quad: 4 vertices + 6 indices (the two triangles share 2 vertices) | ||
| 178 | std::vector<ColorVertex> quadVertices = { | ||
| 179 | {{-0.14f, 0.20f, 0.0f}, {1.0f, 0.8f, 0.2f}}, // 0 左下 / bottom left | ||
| 180 | {{ 0.14f, 0.20f, 0.0f}, {1.0f, 0.3f, 0.3f}}, // 1 右下 / bottom right | ||
| 181 | {{ 0.14f, 0.70f, 0.0f}, {0.6f, 0.2f, 0.8f}}, // 2 右上 / top right | ||
| 182 | {{-0.14f, 0.70f, 0.0f}, {0.2f, 0.6f, 1.0f}}, // 3 左上 / top left | ||
| 183 | }; | ||
| 184 | std::vector<std::uint32_t> quadIndices = { | ||
| 185 | 0, 1, 2, // 一つ目の三角形 / first triangle | ||
| 186 | 2, 3, 0, // 二つ目の三角形 / second triangle | ||
| 130 | }; | 187 | }; |
| 188 | Mesh quad(quadVertices, quadIndices, kColorVertexLayout); | ||
| 131 | 189 | ||
| 132 | TriangleObjects triangle; | 190 | // 3〜6. 計算で作る図形(VAOはそれぞれ別) / generated shapes (each has its own VAO) |
| 133 | if (classic) { | 191 | Mesh hexagon = makePolygon({0.6f, 0.45f}, 0.27f, 6); |
| 134 | printf("classic bind-to-edit style\n"); | 192 | Mesh points = makePoints({-0.6f, -0.45f}); |
| 135 | triangle = createTriangleClassic(vertices, sizeof vertices); | 193 | Mesh star = makeStar({0.0f, -0.45f}, 0.3f); |
| 136 | } else { | 194 | Mesh ribbon = makeRibbon({0.6f, -0.45f}); |
| 137 | triangle = createTriangleDsa(vertices, sizeof vertices); | ||
| 138 | } | ||
| 139 | 195 | ||
| 140 | GLuint vs = compileShader(GL_VERTEX_SHADER, kVertexShader); | 196 | GLuint vs = compileShader(GL_VERTEX_SHADER, kVertexShader); |
| 141 | GLuint fs = compileShader(GL_FRAGMENT_SHADER, kFragmentShader); | 197 | GLuint fs = compileShader(GL_FRAGMENT_SHADER, kFragmentShader); |
| @@ -143,22 +199,25 @@ int main(int argc, char **argv) { | |||
| 143 | GLuint program = linkProgram(vs, fs); | 199 | GLuint program = linkProgram(vs, fs); |
| 144 | if (!program) return 1; | 200 | if (!program) return 1; |
| 145 | 201 | ||
| 202 | glPointSize(10.0f); // GL_POINTSの大きさ(ピクセル) / size of GL_POINTS in pixels | ||
| 203 | |||
| 146 | while (!window.shouldClose()) { | 204 | while (!window.shouldClose()) { |
| 147 | window.pollEvents(); | 205 | window.pollEvents(); |
| 148 | 206 | ||
| 149 | glClearColor(0.10f, 0.15f, 0.25f, 1.0f); | 207 | glClearColor(0.10f, 0.15f, 0.25f, 1.0f); |
| 150 | glClear(GL_COLOR_BUFFER_BIT); | 208 | glClear(GL_COLOR_BUFFER_BIT); |
| 151 | 209 | ||
| 152 | glUseProgram(program); // このシェーダーで描く / draw with this shader | 210 | glUseProgram(program); |
| 153 | glBindVertexArray(triangle.vao); // この頂点データで描く / draw with this vertex data | 211 | triangle.draw(); |
| 154 | glDrawArrays(GL_TRIANGLES, 0, 3); // 頂点0から3つ = 三角形1つ / 3 vertices from vertex 0 = one triangle | 212 | quad.draw(); |
| 213 | hexagon.draw(); | ||
| 214 | points.draw(); | ||
| 215 | star.draw(); | ||
| 216 | ribbon.draw(); | ||
| 155 | 217 | ||
| 156 | window.swapBuffers(); | 218 | window.swapBuffers(); |
| 157 | } | 219 | } |
| 158 | 220 | ||
| 159 | // ウィンドウ(コンテキスト)より先に削除する / delete before the window (context) goes away | ||
| 160 | glDeleteProgram(program); | 221 | glDeleteProgram(program); |
| 161 | glDeleteVertexArrays(1, &triangle.vao); | 222 | return 0; // メッシュはここで自動的に削除される / the meshes are deleted automatically here |
| 162 | glDeleteBuffers(1, &triangle.vbo); | ||
| 163 | return 0; | ||
| 164 | } | 223 | } |
ファイル: /dev/null | b/src/mesh.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,58 @@ | |||
| 1 | #include "mesh.hh" | ||
| 2 | |||
| 3 | #include <utility> | ||
| 4 | |||
| 5 | Mesh::Mesh(const void *vertexData, GLsizeiptr vertexBytes, GLsizei stride, GLsizei numVertices, | ||
| 6 | const std::vector<std::uint32_t> &indices, std::span<const VertexAttrib> layout, GLenum mode) | ||
| 7 | : vertexBuffer(vertexData, vertexBytes), vertexCount(numVertices), | ||
| 8 | indexCount(static_cast<GLsizei>(indices.size())), primitive(mode) { | ||
| 9 | glCreateVertexArrays(1, &vertexArray); | ||
| 10 | |||
| 11 | // 頂点バッファをバインディング0に繋ぐ / attach the vertex buffer to binding 0 | ||
| 12 | glVertexArrayVertexBuffer(vertexArray, 0, vertexBuffer.id(), 0, stride); | ||
| 13 | |||
| 14 | // 各属性の形式と、どのバインディングから読むか / each attribute's format and which binding it reads | ||
| 15 | for (const VertexAttrib &a : layout) { | ||
| 16 | glEnableVertexArrayAttrib(vertexArray, a.location); | ||
| 17 | glVertexArrayAttribFormat(vertexArray, a.location, a.components, a.type, a.normalized, a.offset); | ||
| 18 | glVertexArrayAttribBinding(vertexArray, a.location, 0); | ||
| 19 | } | ||
| 20 | |||
| 21 | // インデックスバッファはVAOに一つだけ / a VAO has exactly one index buffer | ||
| 22 | if (!indices.empty()) { | ||
| 23 | indexBuffer = Buffer(indices.data(), static_cast<GLsizeiptr>(indices.size() * sizeof(std::uint32_t))); | ||
| 24 | glVertexArrayElementBuffer(vertexArray, indexBuffer.id()); | ||
| 25 | } | ||
| 26 | } | ||
| 27 | |||
| 28 | Mesh::~Mesh() { | ||
| 29 | if (vertexArray) glDeleteVertexArrays(1, &vertexArray); | ||
| 30 | } | ||
| 31 | |||
| 32 | Mesh::Mesh(Mesh &&other) noexcept | ||
| 33 | : vertexArray(std::exchange(other.vertexArray, 0)), vertexBuffer(std::move(other.vertexBuffer)), | ||
| 34 | indexBuffer(std::move(other.indexBuffer)), vertexCount(other.vertexCount), indexCount(other.indexCount), | ||
| 35 | primitive(other.primitive) {} | ||
| 36 | |||
| 37 | Mesh &Mesh::operator=(Mesh &&other) noexcept { | ||
| 38 | if (this != &other) { | ||
| 39 | if (vertexArray) glDeleteVertexArrays(1, &vertexArray); | ||
| 40 | vertexArray = std::exchange(other.vertexArray, 0); | ||
| 41 | vertexBuffer = std::move(other.vertexBuffer); | ||
| 42 | indexBuffer = std::move(other.indexBuffer); | ||
| 43 | vertexCount = other.vertexCount; | ||
| 44 | indexCount = other.indexCount; | ||
| 45 | primitive = other.primitive; | ||
| 46 | } | ||
| 47 | return *this; | ||
| 48 | } | ||
| 49 | |||
| 50 | void Mesh::draw() const { | ||
| 51 | glBindVertexArray(vertexArray); | ||
| 52 | if (indexCount > 0) { | ||
| 53 | // インデックスで頂点を選ぶ / pick vertices through the indices | ||
| 54 | glDrawElements(primitive, indexCount, GL_UNSIGNED_INT, nullptr); | ||
| 55 | } else { | ||
| 56 | glDrawArrays(primitive, 0, vertexCount); | ||
| 57 | } | ||
| 58 | } | ||
ファイル: /dev/null | b/src/mesh.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,56 @@ | |||
| 1 | // メッシュ:頂点配列オブジェクト+頂点バッファ+インデックスバッファ | ||
| 2 | // Mesh: a vertex array object + vertex buffer + index buffer | ||
| 3 | #pragma once | ||
| 4 | |||
| 5 | #include "buffer.hh" | ||
| 6 | |||
| 7 | #include <cstdint> | ||
| 8 | #include <span> | ||
| 9 | #include <vector> | ||
| 10 | |||
| 11 | // 頂点属性一つの説明(DSAのglVertexArrayAttribFormatに渡す内容)。 | ||
| 12 | // 頂点の形式はこれの配列で表す(例:constexpr VertexAttrib kLayout[] = {...}) | ||
| 13 | // Describes one vertex attribute (what glVertexArrayAttribFormat needs). | ||
| 14 | // A vertex format is an array of these (e.g. constexpr VertexAttrib kLayout[] = {...}) | ||
| 15 | struct VertexAttrib { | ||
| 16 | GLuint location; // シェーダーの layout(location = N) / the shader's layout(location = N) | ||
| 17 | GLint components; // 成分の数(vec3なら3) / number of components (3 for a vec3) | ||
| 18 | GLuint offset; // 頂点の先頭からのバイト数(offsetof) / bytes from the vertex start (offsetof) | ||
| 19 | GLenum type = GL_FLOAT; // 成分の型 / component type | ||
| 20 | GLboolean normalized = GL_FALSE; // 整数を0〜1にするか / map integers to 0..1? | ||
| 21 | }; | ||
| 22 | |||
| 23 | // 一つの描画単位(RAII、コピー不可・移動可)。インデックスが空ならglDrawArraysで描く。 | ||
| 24 | // One drawable unit (RAII, non-copyable, movable). With no indices it draws with glDrawArrays. | ||
| 25 | class Mesh { | ||
| 26 | public: | ||
| 27 | Mesh() = default; | ||
| 28 | |||
| 29 | // 任意の頂点構造体の配列から作る / build from an array of any vertex struct | ||
| 30 | template <typename Vertex> | ||
| 31 | Mesh(const std::vector<Vertex> &vertices, const std::vector<std::uint32_t> &indices, | ||
| 32 | std::span<const VertexAttrib> layout, GLenum mode = GL_TRIANGLES) | ||
| 33 | : Mesh(vertices.data(), static_cast<GLsizeiptr>(vertices.size() * sizeof(Vertex)), | ||
| 34 | static_cast<GLsizei>(sizeof(Vertex)), static_cast<GLsizei>(vertices.size()), indices, layout, mode) {} | ||
| 35 | |||
| 36 | ~Mesh(); | ||
| 37 | Mesh(const Mesh &) = delete; | ||
| 38 | Mesh &operator=(const Mesh &) = delete; | ||
| 39 | Mesh(Mesh &&other) noexcept; | ||
| 40 | Mesh &operator=(Mesh &&other) noexcept; | ||
| 41 | |||
| 42 | void draw() const; | ||
| 43 | |||
| 44 | GLuint vao() const { return vertexArray; } | ||
| 45 | |||
| 46 | private: | ||
| 47 | Mesh(const void *vertexData, GLsizeiptr vertexBytes, GLsizei stride, GLsizei numVertices, | ||
| 48 | const std::vector<std::uint32_t> &indices, std::span<const VertexAttrib> layout, GLenum mode); | ||
| 49 | |||
| 50 | GLuint vertexArray = 0; | ||
| 51 | Buffer vertexBuffer; | ||
| 52 | Buffer indexBuffer; | ||
| 53 | GLsizei vertexCount = 0; | ||
| 54 | GLsizei indexCount = 0; | ||
| 55 | GLenum primitive = GL_TRIANGLES; // GL_TRIANGLES, GL_LINES, GL_POINTS… | ||
| 56 | }; | ||
コメント(0)
まだコメントはありません。
ログインするとコメント出来ます。