0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

WebGL 3D キューブを 4×4 行列から手書きで実装した(gl-matrix 不使用)

0
Posted at

作ったもの

3D Cubehttps://sen.ltd/portfolio/cube-3d/

スクリーンショット

  • Pure WebGL 1.0(ライブラリ不使用)
  • 4×4 行列を手書き実装(12 関数)
  • マウスドラッグで回転、スクロールでズーム
  • ワイヤフレームオーバーレイ
  • 行列のライブ表示(projection / view / model)
  • シェーダソースをパネルで公開
  • 3 色モード(solid / gradient / mono)

vanilla JS、ゼロ依存、ビルド不要node --test で 34 ケース。

列優先(column-major)

WebGL は列優先ストレージ。m[0..3] は最初の。行優先で読むと間違う:

return new Float32Array([
  1, 0, 0, 0,  // 第 1 列
  0, 1, 0, 0,  // 第 2 列
  0, 0, 1, 0,
  0, 0, 0, 1,
]);

OpenGL 由来の伝統で、数学的には行優先の方が読みやすいが、みんな受け入れている。

任意軸回りの回転(ロドリゲスの公式)

t*x*x + c,    t*x*y + s*z, t*x*z - s*y, 0,
t*x*y - s*z, t*y*y + c,    t*y*z + s*x, 0,
t*x*z + s*y, t*y*z - s*x, t*z*z + c,    0,

c = cos θ, s = sin θ, t = 1 - c。X→Y→Z と順に回す代わりに閉形式で一発。数値的にも安定。

透視投影

const f = 1 / Math.tan(fov / 2);
// f/aspect, f, (far+near)/(near-far), etc.

フラスタム(錐台)を NDC 単位立方体にマッピング。第 4 行の -1 が透視除算を有効化し、z 項が深度レンジを [-1, 1] に写す。

なぜ gl-matrix を使わないか

入門チュートリアルの多くが gl-matrix を import する。それだと「WebGL が何をしているか」はブラックボックス。行列を自分で書くと、回転が三角関数の組み合わせだと腑に落ちる。魔法が算術に変わる瞬間がある。

シリーズ

100+ 公開ポートフォリオ シリーズの #74 です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?