25. 2Dレンダリングとスプライト

此の章からパート5「2Dとゲームの土台」が始まります。
第24章の最後で2つ約束しました。
使い回せるクラスは「大きなmain.cc一つ」のプロジェクトを出てエンジンのライブラリになる事、そして最初のゲームは2Dなので、其の前にスプライトに一歩戻る事です。
此の章で起こるのは正に其れで、前半と後半に分かれます。

前半は構成の変更です。
第1〜24章の全てがengineという静的ライブラリに移ります。
自分のフォルダー、自分のCMakeLists.txt、そしてインクルードの決まりとファイルのパスの決まりが一つずつ出来ます。
第24章のmain.ccにまだ残っていた3Dのフレームのコード(影のパス、HDRの流れ)はエンジンの2つのクラスになり、第24章のプログラム自体は、前の場面をピクセル単位で同じに描かなければならない確認用のプログラムscene3dになります。

後半は、パート6のゲームが乗る2Dの道具です。
y軸が下向きの2Dカメラ、レターボックス、低解像度のピクセルキャンバス、何千個ものスプライトを数回の描画コールで描くスプライトバッチ(glNamedBufferSubData又は永続マップとフェンス)、スプライトシートとアトラス、コマ送りのアニメーション、ピクセルアートをくっきり保つフィルタリングの決まり、そして2Dの色の決まりです。

25.1 此の章で作る物

プログラムgameは、3つの場面を持つ小さな道具のデモになりました。
既定の場面1は、320 × 180で描いてちょうど4倍に拡大したピクセルアートの場面です。
行ったり来たりする主人公、アニメーションするコイン、2匹のスライム、回る丸のこ、木箱、レンガの足場、流れる雲があります。

デモの場面1:320 × 180のピクセルアートの横スクロールアクション風の場面を4倍に拡大した物。空、雲3つ、草と土の地面、左に木箱、金のコイン4枚、青い宝石、ハート、色を掛けた主人公3人(赤、半透明、黒い影)が乗ったレンガの足場、丸のこの付いた石の柱、緑のスライム2匹、花、歩く主人公。隅のHUDはスプライト90、描画コール4

動画では動いている所が見られます。
キャンバスのピクセルは、回る丸のこの上でも全て画面上の4 × 4の塊です:

場面2は回る1万個のスプライトをバッチに投げ込み、描画コールが何回掛かるかを表示します。
場面3はフィルタリングの選択肢を並べて比べます。
操作:

  • 1、2、3:ピクセルアートの場面、1万個のスプライト、フィルタリングの比較
  • ←と→(又はAとD):場面1で主人公を歩かせる。押さなければ勝手に歩く
  • T:テクスチャ毎(既定) ⇔ 並べ替え無し(場面2:描画コール 2 ⇔ 10 000)
  • U:頂点の送り方、glNamedBufferSubData ⇔ 永続マップ
  • =と−:場面2のスプライトを2倍又は半分に(10〜160 000)
  • P:アニメーションを止める、Esc:終了

第24章からの変更:

  • 全てのクラスとシェーダーが移動:ヘッダーはengine/include/engine/へ、ソースはengine/src/へ、シェーダーはengine/shaders/へ。#include "x.hh"は全て#include "engine/x.hh"に
  • engine/CMakeLists.txt(新規)が静的ライブラリを作り、一番上のCMakeLists.txtは其れを中心に書き直す
  • engine/include/engine/renderer3d.hhとengine/src/renderer3d.cc(新規):第24章のmain.ccから取り出したShadowMapとPostChain
  • src/main.ccはtests/scene3d/main.cc(3Dの確認用のscene3d)に、src/gltf_dump.ccはtools/gltf_dump.ccに
  • mathx.hhにVec2用の2Dの補助を追加
  • 新しい2Dのファイル:rect.hh、camera2d.hh/.cc、pixel_canvas.hh/.cc、sprite_batch.hh/.cc、sprite_sheet.hh/.cc、animation.hh/.cc、engine/shaders/sprite.vert/.frag
  • demo/main.cc(新規):此の章のデモ、実行ファイルgame
  • assets/sprites/(新規):主人公、物のアトラス、隙間の無いタイルの複製、3 × 5の小さなピクセルフォント。全てあたしのスクリプトで生成(完成したファイルは章のZIPとアセットのZIPのch25/に入っています)

25.2 何故エンジンのライブラリにするのか

此の先の4つのゲーム

シリーズの残りでは4つのゲームを、其々何章かに分けて作ります:

章 ゲーム 主な材料
27〜29 スペースインベーダー インスタンシングで描くプレイヤーとエイリアン、射撃、衝突判定、シーン、スコア
30〜32 2D格闘ゲーム キャラクター、2D物理、攻撃と当たり判定、シーングラフ、スクロールするステージ、AIの対戦相手
33〜35 トップダウンRPG タイルマップ、移動、扉とマップの切り替え、NPC、会話、アイテム
36〜39 TPS キャラクターとカメラ、3Dの衝突判定と物理、射撃、敵、HUD

ゲームは其々別のプログラムで、自分のmain、自分のアセット、自分のルールを持ちます。
でも4つとも同じWindow、Shader、Texture2D、Framebuffer、そして此の章からは同じスプライトバッチと2Dカメラが要ります。
ゲーム毎に其のファイルをコピーすると、一つのコピーで直したバグが残りの3つに残り、第39章の頃には少しずつ違うエンジンが4つ出来てしまいます。

エンジンのライブラリとは

エンジンのライブラリとは、単にゲームが共有するコードを一度だけコンパイルし、はっきりした境界を付けた物です。
境界の片側は公開ヘッダー、つまり約束です。
#include "engine/sprite_batch.hh"と書けばスプライトが描けます。
反対側はソースで、ゲームは其れをインクルードせず、知る必要もありません。
依存の向きは決まっています。
ゲームはエンジンに依存し、エンジンはゲームに決して依存しません。

技術的には、あたし達の物は静的ライブラリです。
CMakeはエンジンの.ccファイルを一度だけオブジェクトファイルにコンパイルし、一つのアーカイブ(Linux及びFreeBSDではlibengine.a、Visual Studioではengine.lib)に詰めます。
ゲームをリンクする時、リンカーはアーカイブの中でゲームが実際に使う部分をゲームの実行ファイルにコピーします。
もう一つの選択肢の共有ライブラリ(.so、.dll)は実行時に読み込まれ、リンクし直さずに更新出来ます。
但しWindowsでは公開するクラス全てにエクスポートの指定が要り、DLLを全ての.exeの隣に置かなければなりません。
全てのゲームを同じソースの木から作るチュートリアルでは、静的の方が簡単で、失う物は何もありません。

入れる物、入れない物

使い回せる物は全て入れます。
第1〜24章のクラスは其のまま、main.ccに書き下されていた3Dのフレームの部品(25.7節)、そして此の章の2Dの道具です。
入れないのは、一つのプログラムだけが要る物です。
ゲームのルール、レベル、デモの3つの場面です。
クラスは第1〜24章と同じくグローバルな名前空間のままです。
自分のCamera2Dを定義するゲームがあれば衝突しますが、あたし達のゲームにはありませんし、チュートリアルではengine::SpriteよりSpriteの方が読み易いからです。

25.3 新しい構成

フォルダー

移動後のプロジェクトは此うなります:

CMakeLists.txt              GLFW, GLAD, enable_warnings(), set_working_directory(), add_subdirectory(engine),
                            game, gltf_dump, scene3d, games/<name> (if present)
engine/
  CMakeLists.txt            the static library engine (+ stb_image)
  include/engine/*.hh       public headers
  src/*.cc                  implementation
  shaders/                  every shader of chapters 1-24 + sprite.vert/.frag
demo/main.cc                this chapter's demo → executable game
tests/scene3d/main.cc       chapter 24's main.cc adapted → executable scene3d
tools/gltf_dump.cc          the glTF dump tool of chapter 13 → executable gltf_dump
assets/                     shared: models/, textures/ (unchanged), sprites/ (new)
games/<name>/               from chapter 27: invaders, fighter, rpg, tps
external/                   glad, stb, linalg as before (not in the ZIP)

demo/には今の道具の章(此の章と次の章)のプログラム、tests/にはエンジンを確かめるプログラム、tools/にはGPUを全く使わないプログラムが入ります。
ゲームは其々games/の下に、自分のsrc/、assets/、CMakeLists.txtを持つフォルダーを貰います。
ゲームの章は自分のフォルダーの外を何も変えません。

インクルードの書き方は一つ

ヘッダーは思ったより一段深いengine/include/engine/にあり、全てのファイルがフォルダーの名前付きでインクルードします:

#include "engine/sprite_batch.hh"

CMakeが皆に渡すインクルードのディレクトリはengine/includeなので、engine/の部分は名前の一部です。
フォルダーが一つ増える代わりに、2つの物が手に入ります。
ゲームが自分のcamera.hhやanimation.hhを持っても、#include "camera.hh"がどちらを見付けるか迷う事がありません。
そして読む人には、ヘッダーがエンジンの物かゲームの物か一目で分かります。
此の決まりはエンジンの中でも同じで、sprite_batch.ccは"sprite_batch.hh"ではなく"engine/sprite_batch.hh"をインクルードします。

何故src/ではなくdemo/なのか

デモをsrc/main.ccに置いたままにする事も出来ました。
其うしなかった理由はgitです。
第24章のsrc/main.ccは本当に少し手を加えてtests/scene3d/main.ccに移るのですが、gitが移動を見付けるのは古いパスが消えた時だけです。
古いパスに新しいファイルがあると、git diffはsrc/main.ccを頭から書き直した物と、全く新しいtests/scene3d/main.ccとして表示します。
src/が無くなれば、本当の変更付きの名前の変更として表示されます。

25.4 第24章のプロジェクトを移す

ファイルの移動

一緒に作って来た人の為に、第24章のプロジェクトを此の構成にする方法です。
コマンドは、プロジェクトのルートにいるUnixのシェル用で、プロジェクトがgitに入っている前提です(git mvは各ファイルの履歴を保ちます)。
gitが無ければmvを、WindowsではPowerShellのMove-Itemを同じ様に使って下さい:

mkdir -p engine/include/engine engine/src engine/shaders tools tests/scene3d demo
git mv src/*.hh engine/include/engine/
git mv src/gltf_dump.cc tools/
git mv src/main.cc tests/scene3d/main.cc
git mv src/*.cc engine/src/            # incl. stb_image_impl.cc
git mv shaders/* engine/shaders/

順番に少しだけ意味があります。
最後のsrc/*.ccがstb_image_impl.ccも含め残りのソースを全てエンジンに持って行く前に、gltf_dump.ccとmain.ccがsrc/を出ていなければなりません。
終わるとsrc/とshaders/は空になり、消して構いません。

インクルードの行とシェーダーのパス

移動で壊れた所は、2つのsedのコマンドで直します:

# "x.hh" → "engine/x.hh" in every moved file (only lines starting with #include "…hh")
sed -i -E 's/^#include "([a-z_0-9]+\.hh)"/#include "engine\/\1"/' engine/include/engine/*.hh engine/src/*.cc tools/*.cc tests/scene3d/main.cc
sed -i 's#"shaders/#"engine/shaders/#g' engine/src/ibl.cc tests/scene3d/main.cc

1つ目は、#include "で始まり、.hhで終わる小文字のファイル名が続く行だけを書き換えます。
なので#include <glad/glad.h>、#include <linalg.hh>、#include <stb_image.h>(山括弧:あたし達のヘッダーではない)は其のままです。
2つ目は、パスでシェーダーを読む2箇所を直します。
ibl.ccのIbl::buildと、古いmain.ccのシェーダーの読み込みです。
"shaders/という文字列があるのは此の2つのファイルだけです。
第24章のコピーで此の手順を実行し、此の章のスナップショットと比べて確かめました。
手順の後、移動した全てのファイルは、此の章がわざと編集する物(mathx.hh、tests/scene3d/main.cc)と、まだshaders/post.vertと書いてあるframebuffer.hhのコメント1つを除いて同じになります。

其の後は手で書く部分で、此の章の残りで順に説明します:

  1. engine/CMakeLists.txtと新しい一番上のCMakeLists.txtを書く(25.5節)。
  2. mathx.hhに2Dの補助を足す(25.8節)。
  3. renderer3d.hh/.ccを足し、tests/scene3d/main.ccで使う(25.7節)。
  4. 2Dのファイル、スプライトのシェーダー、assets/sprites/、demo/main.ccを足す(25.9〜25.17節)。
  5. 古いビルドのフォルダーを消し(rm -rf build)、設定し直す。ターゲットが変わったので、古いキャッシュは混乱の元になるだけです。

差分の見た目

此の章の差分は此処迄のシリーズで一番大きく、git diff --statによると90ファイルが変わり、1877行の追加と341行の削除があります。
但し殆どは名前の変更です。
19個のシェーダー、9個のヘッダー、stb_image_impl.ccは変わらずに移動し(類似度100%)、残りの移動したファイルはインクルードの行だけが変わり(ibl.ccのシェーダーのパス、framebuffer.hhのコメント、mathx.hhの新しい2Dの補助は別)、src/main.cc → tests/scene3d/main.ccは類似度64%の名前の変更です。
なので移動したファイルは此処に貼りません。
最後のダウンロードに全部入っていて、差分ビューアーは名前の変更毎に本当の編集だけを表示します。

25.5 CMakeを一行ずつ

2つの補助関数

一番上のCMakeLists.txtの始まりは前と同じです(C++の標準、GLFW、GLADは変わりません)。
其の後に、全てのターゲットが(後でゲームのCMakeLists.txtも)呼ぶ2つの関数を定義します:

# 警告を有効にする(自分のコードだけ)。エンジンとゲームの全ターゲットで使う
# Enables warnings (our own code only). Used by the engine and every game target
function(enable_warnings target)
  if(MSVC)
    target_compile_options(${target} PRIVATE /W4 /utf-8)
  else()
    target_compile_options(${target} PRIVATE -Wall -Wextra)
  endif()
endfunction()

# シェーダーとアセットは作業ディレクトリ(= プロジェクトのルート)からの相対パスで読む:
#   engine/shaders/…(エンジン)、assets/…(共有)、games/<名前>/…(各ゲーム)。
# Visual Studioでは各実行ファイルの作業ディレクトリをルートにする。Unixではルートから ./build/game を実行。
# Shaders and assets are loaded relative to the working directory (= the project root):
#   engine/shaders/... (the engine), assets/... (shared), games/<name>/... (each game).
# Visual Studio: every executable's working directory is the root. Unix: run ./build/game from the root.
function(set_working_directory target)
  set_property(TARGET ${target} PROPERTY VS_DEBUGGER_WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}")
endfunction()

function(名前 引数…) … endfunction()がCMakeの関数を定義し、中では${target}が引数です。
enable_warningsは、第24章の決まったターゲットの一覧に対するforeachの代わりです。
其の一覧では、サブディレクトリで定義されたターゲットを知る事が出来ませんでした。
set_working_directoryは第1章と同じくVisual Studioのデバッガーの作業ディレクトリを設定しますが、値は${PROJECT_SOURCE_DIR}です。
此れは一番近いproject()コマンドのフォルダーで、games/invaders/CMakeLists.txtから呼ばれても、あたし達のルートです。
(${CMAKE_CURRENT_SOURCE_DIR}はサブディレクトリになるので間違いです。${CMAKE_SOURCE_DIR}は此処では正しいですが、誰かが此の木全体をadd_subdirectoryで大きなプロジェクトに入れると間違いになります。)
CMakeはファイルを上から下へ読み、エンジンのファイルもenable_warningsを呼ぶので、関数はadd_subdirectory(engine)より前に定義しなければなりません。

エンジンのライブラリ

# エンジン:第1〜24章のクラス+2Dの道具(静的ライブラリ) / the engine: the classes of chapters 1-24 + the 2D toolkit
# (a static library)
add_subdirectory(engine)

add_subdirectory(engine)はengine/CMakeLists.txtを其の場で、貼り付けた様に読みます。
但し今のディレクトリはengine/なので、中の相対パスはengine/から始まります。
此のファイルは短いので全部見せます:

# エンジン:どのゲームでも使うクラスをまとめた静的ライブラリ
# The engine: a static library with the classes every game uses
#
#   engine/include/engine/*.hh  公開ヘッダー(#include "engine/sprite_batch.hh") / public headers
#   engine/src/*.cc             実装 / the implementation
#   engine/shaders/*            エンジンのシェーダー(実行時にプロジェクトのルートから読む) / the engine's shaders
#                               (loaded at run time, relative to the project root)

# stb_image:実装は src/stb_image_impl.cc だけ。他人のコードなので警告フラグなしの別ライブラリにする
# stb_image: the implementation lives in src/stb_image_impl.cc only. It is someone else's code,
# so it is a separate library built without our warning flags
add_library(stb_image STATIC src/stb_image_impl.cc)
target_include_directories(stb_image PUBLIC ${PROJECT_SOURCE_DIR}/external/stb)

add_library(engine STATIC
  # 第1〜24章 / chapters 1-24
  src/window.cc
  src/gl_debug.cc
  src/buffer.cc
  src/mesh.cc
  src/file_util.cc
  src/shader.cc
  src/texture.cc
  src/shapes.cc
  src/camera.cc
  src/material.cc
  src/lights.cc
  src/json.cc
  src/gltf.cc
  src/model.cc
  src/framebuffer.cc
  src/cubemap.cc
  src/gpu_timer.cc
  src/tangents.cc
  src/ibl.cc
  src/pbr_material.cc
  src/renderer3d.cc
  # 第25章:2D / chapter 25: 2D
  src/camera2d.cc
  src/pixel_canvas.cc
  src/sprite_batch.cc
  src/sprite_sheet.cc
  src/animation.cc)

# PUBLIC:エンジンを使う側(ゲーム)にも include/、linalg.hh、GLAD、GLFWが見える
# PUBLIC: whoever links the engine (the games) also sees include/, linalg.hh, GLAD and GLFW
target_include_directories(engine PUBLIC include ${PROJECT_SOURCE_DIR}/external/linalg)
target_link_libraries(engine PRIVATE stb_image PUBLIC glad glfw)
enable_warnings(engine)

一行ずつ:

  • add_library(stb_image STATIC src/stb_image_impl.cc)は第6章のstb_imageライブラリを移した物です。src/は今はengine/src/の意味です。stb_imageはあたし達のコードではないので、矢張り警告フラグは付けません。
  • ${PROJECT_SOURCE_DIR}/external/stb:external/はルートに残るので、engine/の中からは絶対パスが要ります。ただのexternal/stbだと、存在しないengine/external/stbの意味になります。
  • add_library(engine STATIC …)は26個のソースを並べます。第1〜24章の20個、renderer3d.cc、2Dの5つのファイルです。STATICでアーカイブになります。此の言葉が無いと、CMakeはキャッシュ変数BUILD_SHARED_LIBSを見て静的か共有かを選びます。
  • target_include_directories(engine PUBLIC include …):includeはengine/includeで、"engine/x.hh"を使える様にするフォルダーです。external/linalgは<linalg.hh>の場所で、mathx.hhが其れをインクルードします。
  • target_link_libraries(engine PRIVATE stb_image PUBLIC glad glfw)は、エンジン自身が要る物と、使う側が受け継ぐ物を書きます(次の節)。

PUBLIC、PRIVATEとゲームに届く物

CMakeのターゲットは使用要件(usage requirements)を持ちます。
インクルードのディレクトリ、コンパイル時の定義、ライブラリの内、ターゲットを使う側にも要る物です。
前に付ける言葉が其の行き先を決めます:

  • PRIVATE:ターゲット自身をビルドする時だけ。
  • INTERFACE:ターゲットを使う側だけで、ターゲット自身には使わない。
  • PUBLIC:両方。

エンジンのヘッダーは<glad/glad.h>、(window.hhを通して)<GLFW/glfw3.h>、<linalg.hh>をインクルードするので、エンジンのヘッダーをインクルードする人は皆其のインクルードのディレクトリが要ります。
従ってPUBLICです。
stb_imageのライブラリはtexture.ccとcubemap.ccの中だけで使い、エンジンのヘッダーは其れに触れないのでPRIVATEです。
ゲームがうっかりstb_image.hをインクルードする事もありません。

第25章のCMakeのターゲット。実行ファイルgame、scene3d、games/<name>は静的ライブラリengineをPRIVATEでリンクする。engineはgladとglfwをPUBLIC、stb_imageをPRIVATEでリンクする。gltf_dumpは何もリンクせず、エンジンのソース3つを自分でコンパイルする。PUBLICは使う側にもインクルードのディレクトリとリンクが伝わる。PRIVATEはengineだけが其のヘッダーを使うが、engineは静的ライブラリなのでリンクは伝わり、stb_imageは全ての実行ファイルに入る

静的ライブラリには一つ微妙な点があります。
静的ライブラリは其れ自体がリンクされる事は無く、ただのアーカイブなので、其のPRIVATEのライブラリさえ、其れを使う全ての実行ファイルのリンクの行に入らなければなりません。
CMakeは此れを自動でやります(内部では使う側に対してstb_imageを「リンクだけ」と記録します)。
だからゲームはstb_imageの名前を一度も書かずに正しくリンク出来ます。

PRIVATE stb_image PUBLIC glad glfwの順番は、あたしのテスト用のマシンでは見た目だけの物ではありません。テストに使うstb_image.hの代役はlibpngが要り、其れはテスト用ハーネスのglfwターゲットから来ます。静的なアーカイブでは、リンカーは記号を左から右へ解決します。本物のヘッダーだけのstb_image.hでは順番は関係ありませんが、害もありません。

なのでゲームは全部を手に入れるのに一行だけで済みます:

target_link_libraries(game PRIVATE engine)

実行ファイル

一番上のファイルに戻ると、デモが此のライブラリを使う最初のプログラムです:

# この章のデモ / this chapter's demo
add_executable(game demo/main.cc)
target_link_libraries(game PRIVATE engine)
enable_warnings(game)
set_working_directory(game)
set_property(DIRECTORY PROPERTY VS_STARTUP_PROJECT game)

ゲームをリンクする物は無いので、ゲームはエンジンをPRIVATEでリンクします。
VS_STARTUP_PROJECTで、第1章と同じくVisual StudioのF5がgameを起動します。
此れが無いと、プログラムではないALL_BUILDを「実行」しようとします。

第13章のglTFの道具はGPUもウィンドウも要りません:

# glTF/GLBの中身を表示する道具。GPUもウィンドウも使わないのでエンジン全体はリンクしない(GLFWもGLADも要らない)
# A tool that prints what is inside glTF/GLB files. It uses no GPU and no window, so it does not link the whole
# engine (no GLFW, no GLAD)
add_executable(gltf_dump
  tools/gltf_dump.cc
  engine/src/gltf.cc
  engine/src/json.cc
  engine/src/file_util.cc)
target_include_directories(gltf_dump PRIVATE engine/include external/linalg)
enable_warnings(gltf_dump)

engineをリンクすると、PUBLICの依存を通してGLADとGLFWがリンクの行に引き込まれるので、道具は要る3つのソースを自分でコンパイルするだけにします。
其の3つのファイルは2回(エンジン用と道具用に)コンパイルされますが、1〜2秒掛かるだけで、道具はグラフィックスのライブラリと無縁でいられます。

3Dの確認用プログラムにはスイッチが付いています:

# 第24章の3D場面をエンジンで描く確認用プログラム(影・PBR・IBL・ブルーム)。TPS(第36〜39章)の土台
# A check that draws the chapter 24 3D scene through the engine (shadows, PBR, IBL, bloom). The basis of the TPS
# (chapters 36-39)
option(BUILD_SCENE3D "Build the 3D check program scene3d" ON)
if(BUILD_SCENE3D)
  add_executable(scene3d tests/scene3d/main.cc)
  target_link_libraries(scene3d PRIVATE engine)
  enable_warnings(scene3d)
  set_working_directory(scene3d)
endif()

option(名前 "説明" ON)はキャッシュ変数を作ります。
cmakeのコマンドラインで-DBUILD_SCENE3D=OFF(又はcmake-gui、Visual StudioのCMakeの設定)とすれば外せるので、例えば2Dのゲームを作っている間のビルド時間を節約出来ます。

最後にゲームです:

# ゲーム(第27章から):games/<名前>/CMakeLists.txt があれば加える。各ゲームは自分の実行ファイル
# The games (from chapter 27): added when games/<name>/CMakeLists.txt exists. Each game is its own executable
foreach(name invaders fighter rpg tps)
  if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/games/${name}/CMakeLists.txt")
    add_subdirectory(games/${name})
  endif()
endforeach()

foreach(name a b c)は一覧を回り、if(EXISTS …)は設定の時にファイルシステムを調べます。
なのでgames/がまだ無い此の章では何も起きません。
第27章からは、各ゲームのフォルダーにCMakeLists.txtが出来た途端に、誰も此のファイルを編集せずに拾われます。
ゲーム自身のファイルは5行です。
add_executable、自分のインクルードのディレクトリ、target_link_libraries(<name> PRIVATE engine)、enable_warnings、set_working_directoryです。

バイナリの出来る場所

各実行ファイルは、其のCMakeLists.txtに対応するビルドのフォルダーに出来ます:

ターゲット LinuxとFreeBSD Visual Studio
game build/game build\Debug\game.exe
scene3d build/scene3d build\Debug\scene3d.exe
gltf_dump build/gltf_dump build\Debug\gltf_dump.exe
ゲーム(第27章から) build/games/invaders/invaders build\games\invaders\Debug\invaders.exe

エンジンのアーカイブ自体はbuild/engine/に出来ますが、実行する物ではありません。

25.6 実行時のパス

第1〜24章はファイルを作業ディレクトリからの相対パスで読み、プログラムは何時もプロジェクトのルートから実行しました。
此の決まりは残り、今では複数のプログラムと一つの共有のエンジンを動かす唯一の決まりになります。
全ての実行ファイルは、プロジェクトのルートを作業ディレクトリにして実行します。
するとパスの意味は何時も同じです:

  • engine/shaders/…:エンジンのシェーダー。自分のシェーダーを読むエンジンのコード(Ibl、PostChain、SpriteBatch)は此の文字通りのパスを使う。
  • assets/…:共有のアセット(モデル、テクスチャ、スプライト、そして第26章からのフォント)。ゲームは読むだけ。
  • games/<name>/assets/…とgames/<name>/shaders/…:一つのゲーム自身のファイル。

LinuxとFreeBSDでは、全てのプログラムをルートから./build/game、./build/scene3d、./build/games/invaders/invadersの様に起動するという事です。
cd build && ./gameではいけません。
Visual Studioのソリューションでは、set_working_directoryが全てのターゲットに既に設定しています。
Visual Studioの「フォルダーを開く」モードでは、第1章のlaunch.vs.jsonに、gameだけでなく起動するプログラム毎に"currentDir": "${workspaceRoot}"が要ります。

代わりにシェーダーを各実行ファイルの隣にコピーしてはどうでしょう?
其れだとプログラム毎にコピーが一つ出来、変更の度にコピーし直さなければならず、第5章からのシェーダーを読み直すRキーは古いコピーを読み直してしまいます。
木は一つ、作業ディレクトリも一つ、全てのファイルのコピーも一つです。

25.7 3Dのフレームも移る

第20〜24章はmain.ccの中で3Dのフレームを少しずつ作りました。
第23章の光の行列とバイアスの変換、第20・21章のMSAA、解決、ブルーム、ポストのパスです。
ゲームは他のプログラムのmain.ccにある関数を呼べないので、此れらの部品はrenderer3d.hhのエンジンのコードになります:

  • lightSpaceMatrix(dir, centre, radius, mapSize, depthRange)は其のまま。加えてBoundingSphereと、第23章のカメラの視錐台に合わせるfrustumSphere(…)(カメラが真上や真下を向いても安全になりました)。
  • ShadowBiasとapplyShadowBias:第23章の影のテクセル単位のバイアスを、深度の単位に変換する。
  • ShadowMap:深度テクスチャのフレームバッファとShadowユニフォームブロック(結合点2)を持つ。begin()が光の箱を合わせ、ブロックを埋め、深度のパスを準備する。end()が深度テクスチャをユニット5に繋ぐ。
  • PostChain:2つの付け先を持つマルチサンプルのHDRの描き先、解決先、半分の大きさのブルームのフレームバッファ2つ、postとblurのプログラム、Postブロック(結合点3)を持つ。beginScene()、endScene()(解決+ブルーム)、present()(ポストで画面へ)。

中身は第20〜24章のコードを移しただけで、作った章が一行ずつ説明しています。
tests/scene3d/main.ccでは準備が此れだけになり:

  // 影の地図(第23章、結合点2のShadowブロックも持つ)と、HDR・MSAA・ブルームの後処理(第20・21章、結合点3の
  // Postブロックも持つ):第25章でエンジンの部品になった
  // The shadow map (chapter 23; it also owns the Shadow block, binding 2) and the HDR / MSAA / bloom post-processing
  // (chapters 20-21; it also owns the Post block, binding 3): engine pieces since chapter 25
  ShadowMap shadowMap(2048);
  std::optional<PostChain> postChain = PostChain::create(window.width(), window.height());
  if (!shadowMap.complete() || !postChain) return 1;
  window.onResize = [&](int width, int height) { postChain->resize(width, height); };

フレームは此うなります:

    //------------------------------------------------------------------
    // 0. 影の地図:太陽から見た深度(第23章)。光の箱は場面全体を囲む球
    // 0. the shadow map: depth as seen from the sun (chapter 23). The light box is a sphere around the whole scene
    //------------------------------------------------------------------
    const BoundingSphere fit = {{0.0f, 1.0f, 2.5f}, 9.5f};
    if (shadowMap.begin(lights.directional.direction, fit, ShadowBias{}, ShadowFilter::Pcf3x3, shadowsOn))
      drawShadowCasters();
    glEnable(GL_CULL_FACE);
    shadowMap.end(); // 深度テクスチャをユニット5へ / the depth texture goes on unit 5
    if (frame++ % 60 == 5)
      printf("light box radius %.2f m: %.1f mm per shadow texel\n", fit.radius, 1000.0f * shadowMap.metresPerTexel());

    //------------------------------------------------------------------
    // 1. 場面をHDR・MSAAで描き、解決してブルーム / 1. draw the scene in HDR with MSAA, resolve it and bloom
    //------------------------------------------------------------------
    postChain->beginScene();
    drawScene();
    postChain->endScene();

    //------------------------------------------------------------------
    // 2. 画面へ:場面+ブルーム、露出、トーンマッピング、sRGB / 2. to the screen: scene + bloom, exposure, tone
    //    mapping, sRGB
    //------------------------------------------------------------------
    postChain->present(window.width(), window.height(), effect);

何も壊れていない事はどうやって分かるのでしょう?
scene3dは同じキーで第24章の場面を描きます。
其のフレーム10を第24章のフレーム10と比べました(どちらもフレーム8でPを押して風車を止め、同じ瞬間にして)。
1280 × 720の全てのピクセルで一番大きな差は0です。
tests/フォルダーは其の為にあります。
第36〜39章のTPSは此の2つのクラスの上に作るので、scene3dが、其れらがまだ第24章と同じ物を描く証拠になります。

25.8 2Dの数学と長方形

linalg.hhのVec2には、足し算、引き算、前から数を掛ける拡大縮小(s𝐯)、内積、長さしかありません。
2Dのコードにはもう少し要るので、mathx.hh(ダウンロードしたlinalg.hhではなく、あたし達自身の拡張ヘッダー)に足します:

// 2D(第25章):linalg.hhのVec2には足し算・引き算・スカラー倍・内積・長さしかないので足す
// 2D (chapter 25): linalg.hh's Vec2 only has addition, subtraction, scaling, dot and length, so we add the rest
inline Vec2 operator*(Vec2 v, float s) { return {v.x * s, v.y * s}; }
inline Vec2 operator/(Vec2 v, float s) { return {v.x / s, v.y / s}; }
inline Vec2 operator-(Vec2 v) { return {-v.x, -v.y}; }
// 成分ごとの掛け算(大きさの拡大など) / component-wise product (scaling a size, for example)
inline Vec2 operator*(Vec2 a, Vec2 b) { return {a.x * b.x, a.y * b.y}; }
inline Vec2 &operator+=(Vec2 &a, Vec2 b) { return a = a + b; }
inline Vec2 &operator-=(Vec2 &a, Vec2 b) { return a = a - b; }
inline Vec2 &operator*=(Vec2 &a, float s) { return a = a * s; }
inline Vec2 lerp(Vec2 a, Vec2 b, float t) { return a + t * (b - a); }
inline Vec4 lerp(Vec4 a, Vec4 b, float t) { return a + t * (b - a); }
// 長さ0なら0のまま / stays zero for a zero vector
inline Vec2 normalize(Vec2 v) {
  float len = length(v);
  return len > 0.0f ? v / len : Vec2{};
}
// 回転(ラジアン)。2Dの画面座標(y下向き)では正の角度は時計回りに見える
// Rotation (radians). In 2D screen coordinates (y down) a positive angle looks clockwise
inline Vec2 rotate(Vec2 v, float angle) {
  float c = std::cos(angle), s = std::sin(angle);
  return {c * v.x - s * v.y, s * v.x + c * v.y};
}

operator*(Vec2, Vec2)は成分毎に掛けます。
下のs.origin * s.sizeの様に大きさを拡大縮小します。
normalizeは0のベクトルに対して0で割らずに0を返します。
止まっているキャラクターの移動方向は0のベクトルで、NaNの位置は見付けにくいバグです。
rotateは線型代数 第8章の回転行列を書き下した物です。
あの章ではy軸が上向きなので正の角度は反時計回りでした。
y軸が下向きの画面では、同じ式が時計回りに回します。
式は何も変わっておらず、y軸を描く向きが変わっただけです。

長方形には新しいヘッダーrect.hhがあります:

// 2Dの長方形(第25章):スプライトの位置と大きさ、UVの範囲、当たり判定の箱(第26章)
// A 2D rectangle (chapter 25): sprite positions and sizes, UV ranges, collision boxes (chapter 26)
#pragma once

#include "engine/mathx.hh"

// 軸に平行な長方形。2Dの座標はy下向き(左上が原点)なので、(x, y)が左上、x + w が右、y + h が下
// An axis-aligned rectangle. 2D coordinates point y down (origin at the top left), so (x, y) is the top-left corner,
// x + w the right edge and y + h the bottom edge
struct Rect {
  float x = 0.0f, y = 0.0f, w = 0.0f, h = 0.0f;

  float left() const { return x; }
  float right() const { return x + w; }
  float top() const { return y; }
  float bottom() const { return y + h; }
  Vec2 position() const { return {x, y}; }
  Vec2 size() const { return {w, h}; }
  Vec2 centre() const { return {x + 0.5f * w, y + 0.5f * h}; }

  // 中心と大きさから / from a center and a size
  static Rect fromCentre(Vec2 c, Vec2 size) { return {c.x - 0.5f * size.x, c.y - 0.5f * size.y, size.x, size.y}; }
  // dだけずらした長方形 / the rectangle moved by d
  Rect translated(Vec2 d) const { return {x + d.x, y + d.y, w, h}; }
};

yが下向きなので(x, y)は左上の角で、bottom()は大きい方のyのy + hです。
Rectはスプライトの位置、UVの範囲、そして第26章では当たり判定の箱に使います。

25.9 2Dのカメラ

y下向き、原点は左上

OpenGLのクリップ座標はyが上向きで、此れ迄の3Dの世界も全て其うでした。
2Dではエンジンはもう一つの約束を使い、其れはエンジン全体の決まりです:

  • 単位はゲームの仮想解像度(殆どのゲームで320 × 180)の仮想ピクセル。
  • y軸は下向きで、原点は左上の角。
  • 正の回転は画面上で時計回り。
  • 画像の一番上の行がv=0なので、スプライトのテクスチャは第6章の上下反転無しで読む。

画像ファイルの行の並び、タイルマップの書き方(0行目が一番上)、文字の流れ(行は下へ進む)、マウスの位置の報告(GLFWはウィンドウの左上の角から測る)が全て此の向きです。
yが下向きなら、画像編集ソフトのスプライトのピクセル(3, 5)はコードでもピクセル(3, 5)、2行目のタイルはy = 2 * 16に描き、マウスは反転が要りません。

行列

カメラは此うです:

// 2Dの座標系(エンジン全体の約束):
//   * 単位は仮想ピクセル。y軸は下向き、原点は左上(画像・タイルマップ・文字の並びと同じ)。
//   * 正の回転は画面上で時計回り。
//   * 画像の一番上の行がv = 0(テクスチャは上下反転せずに読む)。
// The 2D coordinate system (an engine-wide convention):
//   * Units are virtual pixels. The y axis points down, the origin is at the top left (like images, tile maps and
//     lines of text).
//   * A positive rotation is clockwise on screen.
//   * The top row of an image is v = 0 (textures are loaded without flipping).
struct Camera2D {
  // 拡大率1のときに見える広さ(仮想解像度) / what is visible at zoom 1 (the virtual resolution)
  Vec2 viewSize = {320.0f, 180.0f};
  // 画面の真ん中に来るワールドの点 / the world point shown in the middle of the screen
  Vec2 centre = {160.0f, 90.0f};
  float zoom = 1.0f;     // 2 = 2倍に大きく / 2 = twice as large
  float rotation = 0.0f; // ラジアン、画面上で時計回り / radians, clockwise on screen
  // 中心を(今の拡大率での)画面のピクセルにそろえる:スクロールが画面のピクセル単位になり、絵はビューのピクセルの
  // 格子に揃ったまま動く / Snap the center to whole screen pixels (at the current zoom): scrolling moves in whole view
  // pixels, so the art stays on the view's pixel grid
  bool pixelSnap = false;

  // ワールド → クリップ座標(SpriteBatch::beginに渡す) / world → clip space (pass it to SpriteBatch::begin)
  Mat4 matrix() const;
  // 仮想画面の点(0〜viewSize、左上が原点) → ワールド、とその逆 / a virtual-screen point (0..viewSize, origin top
  // left) → world, and back
  Vec2 toWorld(Vec2 viewPoint) const;
  Vec2 toView(Vec2 worldPoint) const;
  // 見えている範囲を囲むワールドの長方形(回転していれば少し広い) / the world rectangle around what is visible
  // (a little larger when rotated)
  Rect visibleRect() const;

  // ワールド座標 = 仮想画面のピクセル(HUD・文字・メニュー用) / world coordinates = virtual-screen pixels (for HUDs,
  // text and menus)
  static Camera2D screen(Vec2 size) { return {.viewSize = size, .centre = 0.5f * size}; }
};

既定値付きのただの構造体なので、Camera2D camera;だけで(0, 0)から(320, 180)迄の範囲が見えます。
Camera2D::screen(size)は、ワールドの単位がビューのピクセルで、原点が左上のカメラを作ります。
HUD、メニュー、場面2と3が使う物です。
行列:

Mat4 Camera2D::matrix() const {
  Vec2 c = centre;
  if (pixelSnap) {
    // 画面のピクセル(= 仮想ピクセル × zoom)単位に丸める / round to screen pixels (= virtual pixels × zoom)
    c = {std::round(c.x * zoom) / zoom, std::round(c.y * zoom) / zoom};
  }
  float hw = 0.5f * viewSize.x / zoom, hh = 0.5f * viewSize.y / zoom;
  // 上(top)が-hh、下(bottom)が+hh:yが下向きになる / top = -hh, bottom = +hh: y points down
  Mat4 projection = orthographicGl(-hw, hw, hh, -hh, -1.0f, 1.0f);
  // ビュー:中心を原点へ移し、カメラの回転の逆に回す / view: move the center to the origin and undo the camera's rotation
  return projection * rotateZ(-rotation) * translate({-c.x, -c.y, 0.0f});
}

線型代数 第9章で習った通り右から左へ読みます。
先ずワールドを動かしてカメラの中心を原点にし、次にカメラの回転を戻し、最後に投影します。
投影は線型代数 第12章のorthographicGlで、仕掛けは引数にあります。
bottom = +hh、top = −hhを渡すのです。
此の関数のyの行は

yndc=2top−bottomy−top+bottomtop−bottom

で、top=−h、bottom=h(hは見える高さの半分)とすると、2つ目の項は消え、1つ目は2−2h=−1hになります:

yndc=−yh

中心より下の点(正のy)は負のNDCのyになり、其れは画面の下です。
此のマイナス一つがyの反転の全てで、パイプラインの他の部分は其れを知りません。

既定のカメラでの計算例です。
h=90、幅の半分はw=160、中心は(160, 90)です。
ワールドの点(100, 45)は先ず(100−160,45−90)=(−60,−45)になり、次にxndc=−60/160=−0.375、yndc=−(−45)/90=0.5です。
320 × 180のビューポートでは、NDCの(−0.375, 0.5)はピクセルx=(−0.375+1)/2⋅320=100、下から数えてy=(0.5+1)/2⋅180=135、つまり上から180−135=45です。
点は丁度座標の示す場所にあります。

左:y下向きの仮想ピクセルのワールド。左上の(0, 0)から(320, 180)迄の320 × 180の長方形、カメラの中心(160, 90)と点(100, 45)。右:y上向きのクリップ座標。左上の(−1, 1)から(1, −1)迄で、同じ点が(−0.375, 0.5)にある。Camera2D::matrixは、top = −hh、bottom = +hhのorthographicGl × rotateZ(−回転) × translate(−中心)

zoomは見える大きさを割ります。
拡大率2ではwとhが半分になり、全てが2倍の大きさに見えます。
rotationはカメラを回し、ワールドは逆に回るのでrotateZ(-rotation)です。
pixelSnapは行列を作る前に中心を画面の整数のピクセルに丸めます。
カメラがピクセルの端数ずつスクロールすると、画面に直接描いたピクセルアートは自分のピクセルより細かい刻みで滑り、ビューのピクセルの格子から外れます(25.15節で詳しく)。

2Dのスプライトには奥行きが無いので、orthographicGlにはnear −1、far 1を渡し、全てz=0に描きます。重なったスプライトの順番は深度テストではなく描く順番で決まります(25.12節)。

点の変換

カメラはマウスやカリングの為に、点を両方向に変換も出来ます:

Vec2 Camera2D::toWorld(Vec2 viewPoint) const {
  Vec2 fromCentre = (viewPoint - 0.5f * viewSize) / zoom;
  return centre + ::rotate(fromCentre, rotation);
}

Vec2 Camera2D::toView(Vec2 worldPoint) const {
  Vec2 local = ::rotate(worldPoint - centre, -rotation) * zoom;
  return local + 0.5f * viewSize;
}

toWorldは仮想画面の点(0〜viewSize、左上が原点)を受け取り、其の下にあるワールドの点を返します。
toViewは其の逆です。
visibleRect()はビューの4つの角を囲むワールドの長方形を返し、カメラが回っていればビューより少し大きくなります。

25.10 レターボックス

仮想解像度は決まっていますが、ウィンドウの大きさは様々です。
レターボックスはビューを歪めずにウィンドウに出来るだけ大きく収め、残りを上下か左右の帯で埋めます:

// ウィンドウの中の描く場所(glViewportの値)。x, yはGLの約束どおり左下から
// Where to draw inside the window (the glViewport values). x and y count from the bottom left, as GL does
struct Viewport {
  int x = 0, y = 0, width = 0, height = 0;
  int top = 0;        // ウィンドウの上端からの距離(マウスの変換用) / distance from the window's top (for the mouse)
  float scale = 1.0f; // 仮想ピクセル1つが画面の何ピクセルか / screen pixels per virtual pixel

  void apply() const; // glViewport
  // ウィンドウの座標(GLFWのマウス、左上が原点) → 仮想画面の座標 / window coordinates (the GLFW mouse, origin top
  // left) → virtual-screen coordinates
  Vec2 toView(Vec2 windowPoint) const {
    return {(windowPoint.x - static_cast<float>(x)) / scale, (windowPoint.y - static_cast<float>(top)) / scale};
  }
};

// 仮想解像度viewSizeを縦横比を保ったまま一番大きくウィンドウに入れる。余りは上下か左右の帯(レターボックス)。
// integerScaleなら倍率を整数に切り捨てる(ピクセルアートのピクセルがみな同じ大きさになる)
// Fits the virtual resolution viewSize into the window as large as possible without changing its aspect ratio. What
// is left becomes bars at the top and bottom or the sides (letterboxing). integerScale rounds the scale down to a
// whole number (every pixel-art pixel gets the same size)
Viewport letterbox(int windowWidth, int windowHeight, Vec2 viewSize, bool integerScale);

Viewport letterbox(int windowWidth, int windowHeight, Vec2 viewSize, bool integerScale) {
  float scale = std::min(static_cast<float>(windowWidth) / viewSize.x, static_cast<float>(windowHeight) / viewSize.y);
  // 整数倍に切り捨て。ウィンドウが仮想解像度より小さければ1未満のまま / round down to a whole number; below 1 if the
  // window is smaller than the virtual resolution
  if (integerScale && scale >= 1.0f) scale = std::floor(scale);
  Viewport v;
  v.width = static_cast<int>(std::lround(viewSize.x * scale));
  v.height = static_cast<int>(std::lround(viewSize.y * scale));
  v.x = (windowWidth - v.width) / 2;
  v.top = (windowHeight - v.height) / 2;
  v.y = windowHeight - v.top - v.height; // GLは下から数える / GL counts from the bottom
  v.scale = scale;
  return v;
}

倍率は2つの比の小さい方なので、ビューは両方向に収まります。
ピクセルアートではintegerScaleが其れを整数に切り捨て、全ての仮想ピクセルが同じ数の画面のピクセルになります(何故其れが大事かは25.15節)。
倍率が1未満(ウィンドウがビューより小さい)だと丸める整数が無いので、端数のままです。
Viewportはyの値を両方持ちます。
glViewportが欲しい下から数えたyと、マウスに要る上から数えたtopです。

320 × 180のビューの例を、丁度此のコードで計算しました:

ウィンドウ 比 integerScale = true integerScale = false
1280 × 720 4、4 × 4:1280 × 720、帯無し 同じ
1920 × 1080 6、6 × 6:1920 × 1080、帯無し 同じ
1366 × 768 4.27、4.27 × 4:1280 × 720、x = 43、top = 24 × 4.27:1365 × 768、x = 0、top = 0
1440 × 900 4.5、5 × 4:1280 × 720、x = 80、top = 90 × 4.5:1440 × 810、x = 0、top = 45
800 × 600 2.5、3.33 × 2:640 × 360、x = 80、top = 120 × 2.5:800 × 450、x = 0、top = 75

1440 × 900のウィンドウを4分の1の大きさで2つ。左はintegerScale true:320 × 180のビューを4倍の1280 × 720にして真ん中に置き、左右に80ピクセル、上下に90ピクセルの黒い帯。右はintegerScale false:ビューを4.5倍の1440 × 810にして幅一杯にし、上下に45ピクセルの帯

1366 × 768の行には丸めの細かい点があります。
320⋅4.26‾=1365.3‾で、std::lroundが1365にするので、1列だけ黒が残ります。
滑らかな絵なら問題無く、ピクセルアートなら何れにせよ整数の方を使います。

Viewport::toViewはマウスの位置を仮想画面に変換します。
1366 × 768の例では、ウィンドウのピクセル(700, 400)のクリックは((700−43)/4,(400−24)/4)=(164.25,94)になり、其れをcamera.toWorldに通せばマウスの下のワールドの点です。

25.11 ピクセルキャンバス

整数倍のレターボックスは、ピクセルアートを描く一つの方法です。
ビューポートを設定し、仮想解像度のカメラを使い、ウィンドウに直接描きます。
すると全てのスプライトは画面の解像度、仮想ピクセル1つ当たり4つの画面のピクセルでラスタライズされます。
何も回らず、ピクセルの間に置かれない限り、其れで問題ありません。
でも回る丸のこは、絵自身のピクセルよりずっと細かい画面の大きさのピクセルで描かれてしまいます。
ピクセルアートの世界では、此の大きさの合わないピクセルを「ミクセル」(mixel)と呼びます。

もう一つの方法は、本当の320 × 180の画像に描き、画像を拡大する事です。
其れがPixelCanvasです:

// ピクセルアート用の低解像度のキャンバス(第25章):仮想解像度のFBOに描いて、整数倍に拡大して画面に出す
// A low-resolution canvas for pixel art (chapter 25): draw into an FBO at the virtual resolution, then scale it up by
// a whole number onto the screen
#pragma once

#include "engine/camera2d.hh"
#include "engine/framebuffer.hh"

// 回転や半端な位置のスプライトも、画面ではピクセルの格子に乗る(本物の低解像度)。
// 画面の解像度で直接描く(Camera2D+letterbox)と、回転した物が細かいピクセルで描かれる:好みで選ぶ
// Rotated or sub-pixel sprites still land on the pixel grid on screen (a true low resolution).
// Drawing straight at screen resolution (Camera2D + letterbox) renders rotated things with finer pixels: pick what
// you prefer
class PixelCanvas {
public:
  PixelCanvas(int width, int height);

  // キャンバスに描き始める:FBOを繋ぎ、ビューポートを全体にしてclearColorで塗る
  // Starts drawing into the canvas: binds the FBO, sets a full viewport and clears it to clearColor
  void begin(Vec4 clearColor) const;
  // 画面へ:既定のフレームバッファをbarColorで塗り、真ん中にGL_NEARESTで拡大コピー(glBlitNamedFramebuffer)。
  // 使った場所(マウスの変換に使える)を返す。glClearColorは変わったまま
  // To the screen: clears the default framebuffer to barColor and copies the canvas into the middle, scaled with
  // GL_NEAREST (glBlitNamedFramebuffer). Returns where it went (useful for the mouse). Leaves glClearColor changed
  Viewport present(int windowWidth, int windowHeight, bool integerScale = true, Vec4 barColor = {0, 0, 0, 1}) const;

  int width() const { return fbo.width(); }
  int height() const { return fbo.height(); }
  Vec2 size() const { return {static_cast<float>(fbo.width()), static_cast<float>(fbo.height())}; }
  const Framebuffer &framebuffer() const { return fbo; }

private:
  Framebuffer fbo;
};

#include "engine/pixel_canvas.hh"

// 色はRGBA8(2Dの色はsRGBの値のまま扱う、第25章)。スプライトは並べ替えで重ねるので深度は要らない
// The color is RGBA8 (2D colors stay sRGB-encoded values, chapter 25). Sprites are layered by sorting, so no depth
PixelCanvas::PixelCanvas(int width, int height)
    : fbo(width, height, {.colorFormat = GL_RGBA8, .depthStencilFormat = 0}) {
  fbo.color().setFilter(GL_NEAREST, GL_NEAREST);
}

void PixelCanvas::begin(Vec4 clearColor) const {
  fbo.bind();
  glClearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w);
  glClear(GL_COLOR_BUFFER_BIT);
}

Viewport PixelCanvas::present(int windowWidth, int windowHeight, bool integerScale, Vec4 barColor) const {
  Viewport v = letterbox(windowWidth, windowHeight, size(), integerScale);
  Framebuffer::bindDefault(windowWidth, windowHeight);
  glClearColor(barColor.x, barColor.y, barColor.z, barColor.w);
  glClear(GL_COLOR_BUFFER_BIT);
  // 0 = 既定のフレームバッファ。GL_NEARESTなのでピクセルがぼけずに大きくなる
  // 0 = the default framebuffer. GL_NEAREST keeps the pixels sharp while enlarging
  glBlitNamedFramebuffer(fbo.id(), 0, 0, 0, fbo.width(), fbo.height(), v.x, v.y, v.x + v.width, v.y + v.height,
                         GL_COLOR_BUFFER_BIT, GL_NEAREST);
  return v;
}

キャンバスは、GL_RGBA8の色テクスチャ(何故sRGBではないかは25.16節)を持ち、深度バッファの無い第17章のFramebufferです。
スプライトは描く順番で並べるので深度は要りません。
beginは其れを繋ぎ(ビューポートも320 × 180になります)、クリアします。
presentはウィンドウ全体を帯の色でクリアし、第20章でMSAAの解決に使ったglBlitNamedFramebufferでキャンバスをレターボックスの長方形にコピーします:

  • readFramebuffer、drawFramebuffer:コピー元(あたし達のFBO)とコピー先。0は既定のフレームバッファ、つまりウィンドウ。
  • srcX0, srcY0, srcX1, srcY1:コピー元の長方形。此処ではキャンバス全体。
  • dstX0, dstY0, dstX1, dstY1:コピー先の長方形。此処ではレターボックスのビューポートで、GLの全てと同じく下から数える。2つの長方形の大きさが違うと、ブリットは拡大縮小する。
  • mask:どのバッファをコピーするか。GL_COLOR_BUFFER_BIT。
  • filter:拡大縮小のGL_NEAREST又はGL_LINEAR。GL_NEARESTはキャンバスのピクセルを其々4 × 4の塊として繰り返し、GL_LINEARはぼかす。

よくある間違い:ブリットはマルチサンプルのフレームバッファには全く書けず、マルチサンプルの物から読む時は拡大縮小出来ません(どちらもGL_INVALID_OPERATION)。
GL_LINEARでブリット出来るのは色だけで(深度とステンシルはGL_NEAREST)、ブリットはビューポートとブレンドを無視しますが、シザーテストには従います。
又、presentはglClearColorを帯の色にしたままにします。
其の後にウィンドウをクリアするコードは、自分の色を設定して下さい。

どちらの方法が正しいかは好みの問題です。
キャンバスは本当の低解像度になります。
回転も拡大縮小も含めて全てが粗いピクセルの格子に乗り、昔のハードウェアの様です。
直接描くと、ミクセルと引き換えに滑らかな回転とピクセル以下の動きが得られます。
25.15節で2つを並べて見せます。
デモの場面1はキャンバスを使います。

25.12 スプライトバッチ

何故まとめるのか

スプライトはテクスチャを貼った長方形、三角形2つです。
一つずつ自分のglDrawElementsで描いても動きますし、多くの最初の2Dレンダラーは其処から始まります。
でも描画コールの度にドライバーのCPUの時間が掛かります。
状態を検証し、繋がっているオブジェクトを解決し、コマンドを記録するのです。
1フレームに数百回の描画コールなら問題ありませんが、1万発の弾、パーティクル、タイルは無理です。

スプライトバッチは、1フレームのスプライトを全て一つの動的な頂点バッファに集め、同じテクスチャのスプライトを全部1回の呼び出しで描きます。
GPUにとっては、1回の呼び出しに三角形が2つでも2万個でも構いません。
ドライバーのコストは呼び出し毎に掛かります。

スプライト

バッチへの入力は小さな構造体です:

// 色:sRGBの値(画像編集ソフトと同じ)、アルファはそのまま(乗算前)。0xRRGGBBAAから作れる
// Colors: sRGB values (as in image editors), straight (not premultiplied) alpha. Can be made from 0xRRGGBBAA
constexpr Vec4 hexColor(std::uint32_t rrggbbaa) {
  return {static_cast<float>((rrggbbaa >> 24) & 0xFF) / 255.0f, static_cast<float>((rrggbbaa >> 16) & 0xFF) / 255.0f,
          static_cast<float>((rrggbbaa >> 8) & 0xFF) / 255.0f, static_cast<float>(rrggbbaa & 0xFF) / 255.0f};
}
constexpr Vec4 kWhite = {1.0f, 1.0f, 1.0f, 1.0f};

// 一枚のスプライト(四角形)。位置・大きさはワールドの単位(ふつうは仮想ピクセル、y下向き)
// One sprite (a quad). Position and size are in world units (usually virtual pixels, y down)
struct Sprite {
  const Texture2D *texture = nullptr; // nullptr = 白(色だけの四角形) / white (a plain colored rectangle)
  Vec2 position;                      // originが来る場所 / where `origin` ends up
  Vec2 size = {16.0f, 16.0f};         // 描く大きさ / drawn size
  Rect uv = {0.0f, 0.0f, 1.0f, 1.0f}; // テクスチャの範囲(0〜1、左上がv = 0) / texture area (0..1, v = 0 at the top)
  Vec2 origin = {0.0f, 0.0f};         // 回転と位置の基準(大きさに対する割合:(0.5, 0.5) = 中心) / pivot for rotation
                                      // and position (fraction of the size: (0.5, 0.5) = the center)
  float rotation = 0.0f;              // ラジアン、画面上で時計回り / radians, clockwise on screen
  Vec4 color = kWhite;                // 掛ける色(sRGB、アルファ) / tint (sRGB, alpha)
  float layer = 0.0f;                 // SpriteSort::Layerの順番:大きいほど手前 / order for SpriteSort::Layer: larger
                                      // is in front
  bool flipX = false, flipY = false;  // 左右・上下反転(向きを変えたキャラクター) / mirror (a character turning round)
};

此の順番の指示付き初期化子で使う物です:{.texture = &tex, .position = {10, 20}, .size = {32, 32}}。
positionはoriginが来る場所で、originは大きさに対する割合です。
(0, 0)は左上の角(既定)、(0.5, 0.5)は中心、(0.5, 1)は下の中心、つまりキャラクターの足元です。
回転もoriginの周りなので、origin (0.5, 0.5)の丸のこは其の場で回ります。
colorはテクスチャに掛けられ、hexColor(0xff7070ff)なら画像編集ソフトの表示通りに書けます。
texture = nullptrは、組み込みの1 × 1の白いテクスチャで色だけの長方形を描きます。

頂点の形式

角は其々20バイトの頂点一つになります:

// 頂点:位置、UV、色(RGBA8、0〜1に正規化)。20バイト / a vertex: position, UV, color (RGBA8 normalized to 0..1);
// 20 bytes
struct SpriteVertex {
  Vec2 position;
  Vec2 uv;
  std::uint32_t color; // R = 下位バイト / R = lowest byte
};

// 頂点の形式:location 0 = 位置、1 = UV、2 = 色(4バイトを0〜1に正規化) / the vertex format: location 0 = position,
// 1 = UV, 2 = color (4 bytes normalized to 0..1)
static void setupVertexArray(GLuint vao, GLuint vertexBuffer, GLuint indexBuffer) {
  glVertexArrayVertexBuffer(vao, 0, vertexBuffer, 0, sizeof(SpriteVertex));
  glVertexArrayElementBuffer(vao, indexBuffer);
  glEnableVertexArrayAttrib(vao, 0);
  glVertexArrayAttribFormat(vao, 0, 2, GL_FLOAT, GL_FALSE, offsetof(SpriteVertex, position));
  glVertexArrayAttribBinding(vao, 0, 0);
  glEnableVertexArrayAttrib(vao, 1);
  glVertexArrayAttribFormat(vao, 1, 2, GL_FLOAT, GL_FALSE, offsetof(SpriteVertex, uv));
  glVertexArrayAttribBinding(vao, 1, 0);
  glEnableVertexArrayAttrib(vao, 2);
  glVertexArrayAttribFormat(vao, 2, 4, GL_UNSIGNED_BYTE, GL_TRUE, offsetof(SpriteVertex, color));
  glVertexArrayAttribBinding(vao, 2, 0);
}

// 0〜1の色 → RGBA8(Rが下位バイト:メモリ上でR, G, B, Aの順) / a 0..1 color → RGBA8 (R in the lowest byte: R, G, B,
// A in memory order)
static std::uint32_t packColor(Vec4 c) {
  auto byte = [](float v) { return static_cast<std::uint32_t>(std::lround(std::clamp(v, 0.0f, 1.0f) * 255.0f)); };
  return byte(c.x) | (byte(c.y) << 8) | (byte(c.z) << 16) | (byte(c.w) << 24);
}

色は4つのfloatではなく4バイトに詰めます。
頂点当たり12バイト、スプライト当たり48バイトの節約です。
新しいのはglVertexArrayAttribFormat(vao, attribIndex, size, type, normalized, relativeOffset)のnormalizedの引数です。
型がGL_UNSIGNED_BYTEでnormalized = GL_TRUEなら、頂点シェーダーは各バイトを255で割った値を受け取るので、255は1.0、128は0.502として届きます。
GL_FALSEだと255.0が届き、全てのスプライトが真っ白に飛びます。
此れがよくある間違いです。
packColorはRを一番下のバイトに置くので、メモリ上のバイトはR、G、B、Aの順になり、属性が読む順番と同じです。
(此れはリトルエンディアンのCPUが前提で、あたし達の全てのプラットフォームのx86-64とARM64は其うです。)

角はCPUで

draw()はスプライトを直ぐに4つの角の頂点にします:

void SpriteBatch::draw(const Sprite &s) {
  // 四隅をスプライトの中で作り(originを原点に)、回して、positionへ動かす(CPUで計算:頂点はもうワールド座標)
  // Build the corners inside the sprite (origin at 0), rotate them and move them to position (done on the CPU: the
  // vertices are already in world space)
  Vec2 o = s.origin * s.size;
  Vec2 corners[4] = {{-o.x, -o.y}, {s.size.x - o.x, -o.y}, {s.size.x - o.x, s.size.y - o.y}, {-o.x, s.size.y - o.y}};
  if (s.rotation != 0.0f) {
    float c = std::cos(s.rotation), sn = std::sin(s.rotation);
    for (Vec2 &p : corners) p = {c * p.x - sn * p.y, sn * p.x + c * p.y};
  }
  float u0 = s.uv.x, v0 = s.uv.y, u1 = s.uv.x + s.uv.w, v1 = s.uv.y + s.uv.h;
  if (s.flipX) std::swap(u0, u1);
  if (s.flipY) std::swap(v0, v1);
  const Vec2 uvs[4] = {{u0, v0}, {u1, v0}, {u1, v1}, {u0, v1}};
  Quad q;
  std::uint32_t color = packColor(s.color);
  for (int i = 0; i < 4; ++i) q.v[i] = {s.position + corners[i], uvs[i], color};
  q.texture = s.texture ? s.texture : &white;
  q.layer = s.layer;
  quads.push_back(q);
}

先ずoriginからの相対的な角、次に回転(25.8節の式を其の場に書いた物)、最後にpositionへの移動です。
頂点はもうワールド座標でバッファに入るので、シェーダーはカメラの行列だけが要り、位置、大きさ、回転が何であれ全てのスプライトを同じ呼び出しで描けます。
3Dの章の様にスプライト毎にモデル行列を使うと、ユニフォームの変更、従って別の描画コールがスプライト毎に要ります。
反転は角ではなくUVを入れ替えます。
左を向いた主人公は、u0とu1を入れ替えた同じ四角形です。

origin (0.5, 1)の16 × 16の主人公のスプライトの四角形。左はrotation 0:角0は左上でUV (u0, v0)、角1は右上で(u1, v0)、角2は右下で(u1, v1)、角3は左下で(u0, v1)。基準点は下の中心で、角0から角2への点線の対角線が四角形を三角形0-1-2と2-3-0に分ける。右は同じスプライトを基準点の周りに0.5ラジアン回した物で、y下向きの画面では時計回り

スプライトではカリングを切らなければなりません。角0、1、2はy下向きの画面では時計回りで、OpenGLの既定のglFrontFace(GL_CCW)では其れは裏面です。裏面のカリングを有効にすると全てのスプライトが消えます。(flipXは角ではなくUVを入れ替えるので巻き方向は変わりませんが、負の大きさなら変わります。)バッチは単純にカリングを切ります(下の「end()の後のGLの状態」を参照)。

インデックスバッファ一つとglDrawElementsBaseVertex

四角形は全て同じインデックスの並びを使うので、インデックスバッファはcreate()で一度だけ作ります:

  // インデックスは変わらない:四角形iは頂点4i〜4i+3の三角形2つ(0-1-2、2-3-0)
  // The indices never change: quad i is two triangles over vertices 4i..4i+3 (0-1-2, 2-3-0)
  const size_t capacity = static_cast<size_t>(settings.capacity);
  std::vector<std::uint32_t> indices(capacity * 6);
  for (std::uint32_t i = 0; i < static_cast<std::uint32_t>(capacity); ++i) {
    const std::uint32_t q[6] = {4 * i, 4 * i + 1, 4 * i + 2, 4 * i + 2, 4 * i + 3, 4 * i};
    std::copy(q, q + 6, indices.begin() + static_cast<std::ptrdiff_t>(6 * i));
  }
  batch.indexBuffer = Buffer(indices.data(), static_cast<GLsizeiptr>(indices.size() * sizeof(std::uint32_t)));

四角形8192個(既定の容量)で8192⋅6⋅4=196608バイト、192 KiBで、二度と触りません。
バッファの頂点0から始まらない四角形を描く為に、バッチはglDrawElementsBaseVertex(mode, count, type, indices, basevertex)を使います:

  • mode、count、type、indices:glDrawElementsと同じ。count = 6 · 四角形の数、GL_UNSIGNED_INT、indices = nullptrは「要素バッファの先頭から」の意味(要素バッファの中のバイトのオフセットをポインタにキャストした物)。
  • basevertex:使う前に全てのインデックスに足す数。basevertex = 4 · startなら、インデックス0は頂点4⋅startの意味になる。

なので同じインデックス0、1、2、2、3、0、4、5、…が頂点バッファのどの位置にも使えます。
下の永続マップは其れに頼っています。

並べ替えと描画コール

draw()は集めるだけで、end()が順番を決めて描きます:

void SpriteBatch::end() {
  if (!begun) return;
  begun = false;
  // 描く順番(quadsの番号)を決める。stable_sortなので同じキーの中では描いた順のまま
  // Decide the drawing order (indices into quads). stable_sort keeps submission order among equal keys
  std::vector<std::uint32_t> order(quads.size());
  std::iota(order.begin(), order.end(), 0u);
  auto textureId = [&](std::uint32_t i) { return quads[i].texture->id(); };
  if (sortMode == SpriteSort::Texture) {
    std::stable_sort(order.begin(), order.end(), [&](std::uint32_t a, std::uint32_t b) { return textureId(a) < textureId(b); });
  } else if (sortMode == SpriteSort::Layer) {
    std::stable_sort(order.begin(), order.end(), [&](std::uint32_t a, std::uint32_t b) {
      if (quads[a].layer != quads[b].layer) return quads[a].layer < quads[b].layer;
      return textureId(a) < textureId(b);
    });
  }

  shader->use();
  glBindVertexArray(vao);
  // 同じテクスチャが続く間(容量まで)を一回の描画コールにする / one draw call per run of the same texture (up to the
  // capacity)
  const size_t capacity = static_cast<size_t>(settings.capacity);
  size_t first = 0;
  while (first < order.size()) {
    const Texture2D *texture = quads[order[first]].texture;
    size_t count = 1;
    while (first + count < order.size() && count < capacity && quads[order[first + count]].texture == texture) ++count;
    flush(order, first, count, *texture);
    first += count;
  }
  glBindVertexArray(0);
  currentStats.sprites = static_cast<int>(quads.size());
  lastStats = currentStats;
}

orderのベクトルはquadsへの番号を持つので、並べ替えでは96バイトの四角形ではなく4バイトの数を動かします。
std::stable_sortは同じキーの中で描いた順番を保ち、其れが3つ目のモードで大事になります。
其の後ループは並べ替えた一覧を辿り、同じテクスチャの連続(最大capacity個)に切り分け、連続一つが描画コール1回です。
3つのモード:

// end()でどう並べてから描くか / how sprites are ordered before drawing in end()
enum class SpriteSort {
  None,    // 描いた順のまま。テクスチャが変わるたびに描画コールが一つ増える / submission order; every texture change
           // costs one more draw call
  Texture, // テクスチャごとにまとめる(描画コール最少)。重なりの順番は保証しない / grouped by texture (fewest draw
           // calls); overlap order is not kept
  Layer,   // layerの小さい順(奥から手前)。同じlayerの中ではテクスチャごと、同じテクスチャなら描いた順
           // by layer, small first (back to front); within one layer grouped by texture, then submission order
};

  • None:描いた順番。テクスチャが変わる度に描画コールが増えるので、テクスチャが交互ならスプライト毎に1回。
  • Texture:テクスチャ毎にまとめ、呼び出しが一番少ない。テクスチャの違うスプライトの重なりは描いた順でなくなるので、テクスチャ間の重なりがどうでも良い時(パーティクル、別のバッチで描いた背景の上の弾等)に使う。
  • Layer:layer(小さい方が奥)、layerの中ではテクスチャ、テクスチャの中では描いた順番。場面の為のモード。

スプライトの3つの行。SpriteSort::Noneで主人公とコインがH O H O H Oと交互なら、テクスチャが変わる度に1回で描画コール6回。SpriteSort::TextureはH H H O O Oにまとめて描画コール2回。場面1のSpriteSort::Layer:雲がlayer 0、タイルがlayer 1、アイテムがlayer 2、色付きの主人公がlayer 2、主人公がlayer 3で、O L0、O L1、H L2、O L2、H L3に並び、同じテクスチャの連続はlayerを跨いで1回になるので描画コール4回。layer 2の中ではテクスチャの番号が小さい方が先

デモの数字は此処から直接出て来ます。
場面2は主人公とコインのスプライトを5000個ずつ交互に描くので、並べ替え無しで描画コール10 000回、テクスチャ毎なら2回です。
場面1は2つのテクスチャから4つのlayerに90個のスプライトを描き、描画コールは4回です。
雲(layer 0)もタイル(layer 1)もobjects.pngから来ていて、連続はテクスチャが変わる所でしか切れないので、1回の呼び出しを共有します。
layer 2の中ではGLの名前(番号)が小さいテクスチャが先で、此処では先に読んだhero.pngです(ドライバーは普通名前を小さい順に配ります)。
なので色付きの主人公は、同じlayerのコインやスライムより先に描かれます。
重なっていないので関係ありませんが、決まりが見えます。
layerの中ではテクスチャが決めるので、重なりの順番が大事なスプライトには違うlayerを付けて下さい。

capacityも連続を切ります。
場面2を20 000個にすると(=を1回)、テクスチャ毎に8192を超える10 000個の四角形があるので、其々2回、合わせて4回になります。
160 000個ではテクスチャ毎に⌈80000/8192⌉=10回、合わせて20回です。

glNamedBufferSubDataで送る

各連続は、描画コールの前に頂点をGPUのバッファに入れなければなりません。
簡単な方法のSpriteUpload::SubDataは、create()で作るcapacity個の四角形のバッファを一つ使います:

  } else {
    // 書き換え可能なストレージ(GL_DYNAMIC_STORAGE_BIT):glNamedBufferSubDataで送る
    // Updatable storage (GL_DYNAMIC_STORAGE_BIT): filled with glNamedBufferSubData
    batch.vertexBuffer = Buffer(nullptr, static_cast<GLsizeiptr>(capacity) * quadBytes, GL_DYNAMIC_STORAGE_BIT);
    batch.staging.resize(capacity * 4);
  }

GL_DYNAMIC_STORAGE_BITは、後でglNamedBufferSubDataを使える様にするglNamedBufferStorageのフラグです(第19章でユニフォームバッファに使いました)。
連続毎にflushは四角形を並べ替えた順にCPU側のstagingの配列にコピーし、オフセット0にアップロードします:

  } else {
    for (size_t i = 0; i < count; ++i) std::memcpy(&staging[4 * i], quads[order[first + i]].v, sizeof(Quad::v));
    vertexBuffer.update(staging.data(), static_cast<GLsizeiptr>(count * 4 * sizeof(SpriteVertex)));
  }
  texture.bind(0);
  // baseVertex:インデックスに足す数。インデックスバッファは0から始まるまま使える
  // baseVertex: added to every index, so the index buffer can always start at 0
  glDrawElementsBaseVertex(GL_TRIANGLES, static_cast<GLsizei>(count * 6), GL_UNSIGNED_INT, nullptr, baseVertex);
  ++currentStats.drawCalls;

GPUがまだ前の連続を描いていなくても、全ての連続が同じバッファの同じバイトを使い回します。
glNamedBufferSubDataにはコピーの意味があるので、此れは正当です。
呼び出しが戻った時にはドライバーがデータを受け取っていて、前の描画が古い中身を見る事を保証します。
どうやるかはドライバー次第です。
新しいデータを隠れた一時的なバッファにコピーしてGPUの時間軸の上でコピーを予約するか、バッファの名前の裏に新しいメモリを割り当てるか、最悪の場合はGPUが其のバッファを使い終わる迄待ちます。
良い所は簡単な事、悪い所は余分なコピーの代金を払い、ドライバーの賢さに頼る事です。
何れにせよ量は小さいです。
四角形は80バイトなので、1万個のスプライトは1フレーム800 000バイト、60フレーム毎秒で毎秒48 MBです。

永続マップとフェンス

OpenGL 4.4で、ドライバーのコピーを省く方法が加わりました。
永続マップです。
バッファを一度だけマップし、プログラムが動いている間ずっとポインタを持ち、GPUが読むメモリに頂点を直接書きます。
代わりに同期があたし達の仕事になります。
GPUがまだ読んでいない頂点を上書きするのを、もう誰も止めてくれないからです。

バッファは、其々capacity個の四角形の3つの区画で作ります:

  const GLsizeiptr quadBytes = 4 * sizeof(SpriteVertex);
  if (settings.upload == SpriteUpload::Persistent) {
    // 永続マップ:3区画分のストレージを一度だけマップし、ずっと書き続ける。COHERENTなので書いた値は
    // フラッシュなしでGPUに見える(ただしGPUが読み終わったかはフェンスで確かめる)
    // Persistent mapping: storage for three regions, mapped once and written for the whole run. COHERENT makes
    // writes visible to the GPU without explicit flushes (whether the GPU has finished reading is checked with fences)
    const GLbitfield flags = GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT;
    const GLsizeiptr bytes = kRegions * static_cast<GLsizeiptr>(capacity) * quadBytes;
    batch.vertexBuffer = Buffer(nullptr, bytes, flags);
    batch.mapped = static_cast<SpriteVertex *>(glMapNamedBufferRange(batch.vertexBuffer.id(), 0, bytes, flags));
    if (!batch.mapped) {
      fprintf(stderr, "スプライトの頂点バッファをマップできない / cannot map the sprite vertex buffer\n");
      return std::nullopt;
    }

  • glNamedBufferStorage(buffer, size, data, flags)(Bufferクラスの中)にGL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT:ストレージは書き込み用にマップ出来、GPUが使う間もマップしたままで良く、書いた値は明示的なフラッシュ無しにGPUに見える。
  • glMapNamedBufferRange(buffer, offset, length, access)は範囲をマップしてポインタを返す。アクセスのビットはストレージのフラグの一部でなければならず、此処では同じ3つ。GL_MAP_PERSISTENT_BIT無しで作ったバッファを其のビットでマップするのはエラーで、永続ではないマップをしたままのバッファから描くのもエラー。
  • GL_MAP_COHERENT_BITが無ければ、書いた範囲毎にglFlushMappedNamedBufferRangeを呼ばなければならない(GL_MAP_FLUSH_EXPLICIT_BITでマップして)。

3つの区画は輪になります。
CPUが一つの区画に書いている間、GPUは其の前の区画をまだ読んでいるかもしれません。
フェンスが、GPUが区画を使い終えた地点に印を付けます:

void SpriteBatch::flush(const std::vector<std::uint32_t> &order, size_t first, size_t count, const Texture2D &texture) {
  GLint baseVertex = 0;
  if (settings.upload == SpriteUpload::Persistent) {
    // 今の区画に入らなければ次の区画へ:今の区画にフェンスを置き、次の区画の古いフェンス(GPUがそこを読み終えたか)を待つ
    // If it does not fit into the current region, move on: put a fence after the current region's draws and wait
    // for the next region's old fence (has the GPU finished reading it?)
    if (regionUsed + static_cast<int>(count) > settings.capacity) {
      fences[region] = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
      region = (region + 1) % kRegions;
      regionUsed = 0;
      if (fences[region]) {
        // GL_SYNC_FLUSH_COMMANDS_BIT:フェンスがまだGPUに送られていなければ送る(でないと永久に待つ)
        // GL_SYNC_FLUSH_COMMANDS_BIT: sends the fence to the GPU if it is not yet (otherwise we could wait forever)
        while (glClientWaitSync(fences[region], GL_SYNC_FLUSH_COMMANDS_BIT, 1'000'000) == GL_TIMEOUT_EXPIRED) {
        }
        glDeleteSync(std::exchange(fences[region], nullptr));
      }
    }
    int start = region * settings.capacity + regionUsed;
    SpriteVertex *out = mapped + static_cast<size_t>(start) * 4;
    for (size_t i = 0; i < count; ++i) std::memcpy(out + 4 * i, quads[order[first + i]].v, sizeof(Quad::v));
    baseVertex = 4 * start;
    regionUsed += static_cast<int>(count);

連続が今の区画に入らない時:

  1. glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0)が、此の区画を読む描画の後にフェンスをコマンドの流れに入れる。GPUが其れより前を全て実行するとシグナル状態になるGLsyncオブジェクトを返す。2つの引数は決まっていて、此の条件とフラグ0。
  2. バッチは次の区画に移る。3つ目の後は最初に戻る。
  3. 其の区画に前の周のフェンスがあれば、glClientWaitSync(sync, flags, timeout)でCPUが其れを待つ。GL_SYNC_FLUSH_COMMANDS_BITはフェンスが本当にGPUに送られる様にする(でないとドライバーの待ち行列に入ったままのコマンドを待つ事になりかねない)。タイムアウトはナノ秒で此処では1 ms、結果がGL_TIMEOUT_EXPIREDの間ループする。他の結果はGL_ALREADY_SIGNALED、GL_CONDITION_SATISFIED、GL_WAIT_FAILED。
  4. glDeleteSyncがフェンスを解放する。もう要らない。

其の後四角形をmemcpyでマップした所にコピーし、描画コールはbaseVertex = 4 · startで其れを見付けます。
フェンスのオブジェクトはrelease()でも消し、マップはバッファを消すと無くなります。

一度だけマップした一つのバッファに、capacity個の四角形の区画が3つ。区画0は一杯でフェンスF0で終わり、GPUがまだ読んでいるかもしれない。区画1は途中迄埋まっていて、CPUが此処にmemcpyで書き、baseVertex = 4 × startで描く。区画2は前の周の古いフェンスF2で終わり、使い直す前にCPUがglClientWaitSyncで其のフェンスを待つ。手順:今の区画が一杯なら其の描画の後にglFenceSync、次の区画へ(一周する)、GPUが其の区画の古いフェンスを過ぎる迄待って消す、四角形をマップした所にコピーして其処から描く

大きさは3⋅8192⋅80=1966080バイト、1.875 MiBです。
本当のトリプルバッファリングには、capacityが1フレームのスプライトの数以上で、区画が丸2フレーム後に初めて使い直される様にするべきです。
1万個のスプライト(とHUDの約100個)の場面2は其れを超えています。
更に連続は2つの区画に分かれる事が無いので、5000個の連続2つは一つの区画に一緒には入りません。
毎フレーム新しい区画が2つ始まり、輪は約1.5フレーム毎に一周します。
隙間無く詰めた場合の3⋅8192/10100≈2.4フレームではありません。
此れが手元のマシンでどれだけ掛かるか、そして何故其の測定が誤解を招くかは25.18節で見ます。

永続ではない中間の方法は、フレーム毎にglMapNamedBufferRangeをGL_MAP_INVALIDATE_RANGE_BIT(古い中身は捨てて良い)又はGL_MAP_UNSYNCHRONIZED_BIT(待たない、使用中の所には触らないと約束する)で呼ぶ事と、昔からのオーファニング(orphaning)です。書く前にglNamedBufferData(buffer, size, nullptr, usage)又はglInvalidateBufferDataを呼ぶと、GPUが古いメモリを読み続ける間にドライバーが新しいメモリをくれます。あたし達のバッファは不変のストレージ(glNamedBufferStorage)なので、無効化は出来ますが作り直しは出来ません。

シェーダーと乗算済みアルファ

シェーダーはシリーズで一番短い物です:

#version 460 core
// スプライト(第25章):頂点はCPUでワールド座標にしてある。ここでは2Dカメラの行列を掛けるだけ
// Sprites (chapter 25): the CPU already put the vertices in world space; here we only apply the 2D camera's matrix
layout(location = 0) in vec2 aPosition;
layout(location = 1) in vec2 aUv;
layout(location = 2) in vec4 aColor; // RGBA8 → 0〜1(sRGBの値、乗算前のアルファ) / 0..1 (sRGB values, straight alpha)

uniform mat4 uViewProjection;

out vec2 vUv;
out vec4 vColor;

void main() {
  vUv = aUv;
  // テクスチャは乗算済みアルファなので、掛ける色も乗算済みにする / the textures are premultiplied, so the tint is too
  vColor = vec4(aColor.rgb * aColor.a, aColor.a);
  gl_Position = uViewProjection * vec4(aPosition, 0.0, 1.0);
}

#version 460 core
// スプライト(第25章):テクスチャ × 色。どちらも乗算済みアルファ(ブレンドは GL_ONE, GL_ONE_MINUS_SRC_ALPHA)
// Sprites (chapter 25): texture × color, both premultiplied alpha (blending is GL_ONE, GL_ONE_MINUS_SRC_ALPHA)
in vec2 vUv;
in vec4 vColor;

layout(binding = 0) uniform sampler2D uTexture;

layout(location = 0) out vec4 out_color;

void main() {
  out_color = texture(uTexture, vUv) * vColor;
}

頂点シェーダーはカメラの行列を掛けるだけ、フラグメントシェーダーはテクスチャと色を掛けるだけです。
全ては乗算済みアルファです。
第16章が暗い縁を無くす為に紹介した表し方です。
スプライトのテクスチャは読む時に乗算済みにし、頂点シェーダーが色を(ra,ga,ba,a)と乗算済みにするので、アルファ0.45の色はスプライト全体を薄くします。
ブレンドの式は

𝐜=𝐜s+(1−αs)𝐜d

で、𝐜sはシェーダーの乗算済みの出力、𝐜dはフレームバッファに既にある物、つまりglBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA)です。

場面1の計算例です。
足場の上の半透明の主人公の色は(1, 1, 1, 0.45)です。
空0x8fd3ff、つまり(143,211,255)/255=(0.5608,0.8275,1)の前にある、値(0.2, 0.4, 0.6)でアルファ1のテクセルを考えます。
頂点シェーダーは色を(0.45,0.45,0.45,0.45)にし、フラグメントシェーダーは(0.2,0.4,0.6,1)⋅0.45=(0.09,0.18,0.27,0.45)を出し、ブレンドで

(0.09,0.18,0.27)+0.55⋅(0.5608,0.8275,1)=(0.3984,0.6351,0.82)

になります。
8ビットでは(102, 162, 209)、主人公45%、空55%です。
隣の黒い影はhexColor(0x000000b0)、アルファ176/255=0.69を使います。
RGBが0なので空を0.31⋅(143,211,255)=(44,65,79)に暗くするだけです。

ブレンドモード

// 混ぜ方。テクスチャも色も乗算済みアルファで扱う / blending. Textures and colors are handled as premultiplied alpha
enum class SpriteBlend {
  Alpha,    // ふつうの半透明(GL_ONE, GL_ONE_MINUS_SRC_ALPHA) / ordinary transparency
  Additive, // 足す(光・炎・爆発)(GL_ONE, GL_ONE) / adds up (light, fire, explosions)
};

AdditiveはglBlendFunc(GL_ONE, GL_ONE)です。
スプライトの色が其処にある色に足されるので、重なったスプライトは明るくなるだけで暗くはならず、光、炎、火花、爆発の見え方になります。
乗算済みアルファなら、足し算に特別なテクスチャは要りません。
透明なテクセルは(0, 0, 0, 0)で、何も足さないからです。
モードはbegin()毎なので、足し算のスプライトは普通の物の後に自分のbegin/endで描きます。

end()の後のGLの状態

begin()は此うです:

void SpriteBatch::begin(const Mat4 &viewProjection, SpriteSort sort, SpriteBlend blend) {
  if (begun) fprintf(stderr, "SpriteBatch::begin: end()が抜けている / end() is missing\n");
  begun = true;
  sortMode = sort;
  quads.clear();
  currentStats = {};
  shader->set("uViewProjection", viewProjection);
  // 2Dの状態:深度なし(重なりは描く順・layerで決める)、カリングなし(y下向きの射影で四角形は画面上で時計回り
  // = 裏向きになる。flipXはUVを入れ替えるだけ)、乗算済みアルファのブレンド / the 2D state: no depth (overlap is
  // decided by order / layer), no culling (the y-down projection makes the quads clockwise on screen, i.e. back faces;
  // flipX only swaps the UVs), premultiplied-alpha blending
  glDisable(GL_DEPTH_TEST);
  glDisable(GL_CULL_FACE);
  glEnable(GL_BLEND);
  if (blend == SpriteBlend::Additive) glBlendFunc(GL_ONE, GL_ONE);
  else glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
}

2Dの状態はbegin()で設定し、end()の後も其のまま残します。
ブレンドon、深度テストoff、カリングoff、そしてend()の後はVAO 0とユニット0の最後のテクスチャです。
バッチは前の状態を知らないので戻しませんし、毎フレームglGetでGLの状態を問い合わせるのは遅いです。
なので決まりは此うです(ShadowMap::beginとscene3dは既に守っています)。
スプライトの後に3Dを描く人が3Dの状態を設定し直す(glEnable(GL_DEPTH_TEST)、glEnable(GL_CULL_FACE)、不透明な物ではブレンドoff)。
TPSは3Dのフレームの後にスプライトバッチでHUDを描き、次のフレームは深度テストを有効にする所から始めます。

begin()は前のbegin()にend()が無かった時にも警告します。
其の間違いは、さもないと一つのバッチのスプライトが別のバッチに現れるという形で出ます。
drawRectとdrawRectOutlineはtexture = nullptrのdraw()の上に作ってあります。
色だけの長方形と、輪郭用の細い長方形4つで、第26章で当たり判定の箱を見せるのに使います。

25.13 スプライトシートとアトラス

テクスチャが変わる度に描画コールが掛かり得るので、2Dのゲームは沢山の画像を一つのテクスチャに入れます。
スプライトシートは、一人のキャラクターのコマを格子に並べた其の様なテクスチャです。
アトラスは関係の無い様々な大きさの画像を詰め込み、其々の場所を一覧にします。
どちらもテクスチャと長方形の一覧なので、エンジンには両方の為のクラスが一つ、SpriteSheetがあります。

スプライト用のテクスチャを読む

std::optional<Texture2D> loadSpriteTexture(const std::string &path, TextureFilter filter) {
  // flipY = false:y下向きの2Dでは画像の一番上の行がv = 0のままで良い / with y-down 2D the image's top row can stay v = 0
  std::optional<Texture2D> texture =
      Texture2D::load(path, {.flipY = false, .mipmaps = false, .srgb = false, .premultiplyAlpha = true});
  if (!texture) return std::nullopt;
  GLenum f = filter == TextureFilter::Nearest ? GL_NEAREST : GL_LINEAR;
  texture->setFilter(f, f);
  // 繰り返さない:端のコマが反対側の端を読まないように / no repeat: frames at the edge must not read the opposite edge
  texture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
  return texture;
}

一回の呼び出しに決め事が4つ:

  • flipY = false:yが下向きなら、画像の0行目はファイルと同じくv=0。第6章の反転はOpenGLのvが上向きだからあったので、あたし達の2Dの世界には要らない。
  • mipmaps = false:スプライトは決まった倍率で描き、ミップマップは小さい大きさで隣のコマを混ぜてしまう(25.15節で詳しく)。
  • srgb = false:25.16節の色の決まり。
  • premultiplyAlpha = true:バッチは乗算済みでブレンドする。

GL_CLAMP_TO_EDGEで、画像の端にあるコマがGL_LINEARで反対側の端を読まない様にします。
既定のGL_REPEATだと回り込みます。

格子のシート

主人公は格子です。
16 × 16のマスに、1ピクセルの外側の余白(margin)と1ピクセルの隙間(spacing)があります:

std::optional<SpriteSheet> SpriteSheet::loadGrid(const std::string &imagePath, int cellWidth, int cellHeight,
                                                 int margin, int spacing, TextureFilter filter) {
  std::optional<Texture2D> texture = loadSpriteTexture(imagePath, filter);
  if (!texture) return std::nullopt;
  SpriteSheet sheet;
  sheet.image = std::move(*texture);
  for (int y = margin; y + cellHeight <= sheet.image.height() - margin; y += cellHeight + spacing)
    for (int x = margin; x + cellWidth <= sheet.image.width() - margin; x += cellWidth + spacing)
      sheet.frames.push_back({static_cast<float>(x), static_cast<float>(y), static_cast<float>(cellWidth),
                              static_cast<float>(cellHeight)});
  if (sheet.frames.empty()) {
    fprintf(stderr, "%s: コマが一つもない / no frames fit (%d x %d cells)\n", imagePath.c_str(), cellWidth, cellHeight);
    return std::nullopt;
  }
  return sheet;
}

5倍に拡大したhero.png:137 × 18ピクセルに、1ピクセルの透明な外側の余白と隙間で16 × 16のマスが8つ。コマ0と1は待機(1は瞬き)、2〜5は歩き、6はジャンプ、7は空。コマiはx = 1 + 17 iから始まる

ループはcellWidth + spacingずつ進むので、主人公のコマiはx=1+17iから始まります。
画像の幅は1+8⋅17=137ピクセルです。
条件x + cellWidth <= width - marginでx=1,18,…,120の8マスが入り、8つ目は空です(生成スクリプトは7コマを8列に並べます)。
主人公が隣のコマの切れ端を見せないのは隙間のお陰です(25.15節)。
格子には名前が無いので、主人公のクリップはコードで足します:

  // 主人公のクリップ:コマの番号はhero.pngの並び(0〜1 待機、2〜5 歩き、6 ジャンプ)
  // The hero's clips: frame numbers follow hero.png (0-1 idle, 2-5 walk, 6 jump)
  hero->addClip({.name = "idle", .frames = {0, 0, 0, 0, 0, 0, 1}, .fps = 6.0f});
  hero->addClip({.name = "walk", .frames = {2, 3, 4, 5}, .fps = 10.0f});

アトラスのファイル

objects.pngには、タイル、コイン、宝石、ハート、丸のこ、スライム、花、雲が様々な大きさで入っています。
位置は隣のテキストファイルobjects.atlasにあり、生成スクリプトが書きます:

# objects: tiles (extruded 1 px borders), items, slime, cloud (generated by the author's own script)
image objects.png
sprite grass 1 1 16 16
sprite dirt 19 1 16 16
sprite brick 37 1 16 16
sprite stone 55 1 16 16
sprite crate 73 1 16 16
sprite coin_0 1 19 12 12
sprite coin_1 15 19 12 12
sprite coin_2 29 19 12 12
sprite coin_3 43 19 12 12
sprite gem 57 19 10 9
sprite heart 69 19 9 8
sprite saw 80 19 16 16
sprite slime_0 98 19 16 16
sprite slime_1 1 37 16 16
sprite flower 19 37 8 8
sprite cloud 29 37 32 12
clip coin_spin 8 loop coin_0 coin_1 coin_2 coin_3
clip slime_bounce 3 loop slime_0 slime_1

形式は1行に1項目です。
image <ファイル>(.atlasファイルからの相対パス)、左上が原点のピクセルでsprite <名前> <x> <y> <幅> <高さ>、clip <名前> <fps> <loop又はonce> <コマ…>、そしてコメントの#です。
SpriteSheet::loadAtlasは其れをstd::istringstreamで一語ずつ読みます:

  while (std::getline(lines, line)) {
    ++lineNumber;
    std::istringstream in(line);
    std::string keyword;
    if (!(in >> keyword) || keyword[0] == '#') continue;
    if (keyword == "image") {
      if (!(in >> imageFile)) return fail("image <ファイル> / image <file>");
    } else if (keyword == "sprite") {
      std::string name;
      Rect r;
      if (!(in >> name >> r.x >> r.y >> r.w >> r.h)) return fail("sprite <name> <x> <y> <w> <h>");
      sheet.frames.push_back(r);
      sheet.names.push_back(name);
    } else if (keyword == "clip") {
      PendingClip p;
      std::string mode;
      if (!(in >> p.clip.name >> p.clip.fps >> mode) || (mode != "loop" && mode != "once"))
        return fail("clip <name> <fps> <loop|once> <frames...>");
      p.clip.loop = mode == "loop";
      for (std::string f; in >> f;) p.frameNames.push_back(f);
      p.line = lineNumber;
      pending.push_back(std::move(p));
    } else {
      return fail("知らないキーワード / unknown keyword");
    }
  }

エラーはコンパイラーの様にファイル:行: メッセージで報告します。
人が手で編集するファイルでは此れが大事です。
クリップはコマを名前で指し、名前はファイル全体を読んだ後に解決するので、クリップを其れが使うスプライトより前に書いても構いません。
画像の外にはみ出すスプライトの長方形は、画面にゴミを出す代わりに読み込みの時点で拒否します。
そしてファイルが全く読めなければ、プロジェクトのルートから実行したかを尋ねます。
殆ど何時も其れが原因だからです。
此の様なテキストの形式は道具が出力する物でもあります。
TexturePacker、Aseprite、無料のパッカーは同じ情報をJSONやXMLで書き出し、30行程のパーサーで同じ様にSpriteSheetに出来ます。

UVと出来合いのスプライト

Rect SpriteSheet::pixels(int index) const {
  if (index < 0 || index >= count()) {
    if (!warnedIndex)
      fprintf(stderr, "SpriteSheet: 範囲外のコマ / frame index out of range: %d (count %d)\n", index, count());
    warnedIndex = true;
    return {};
  }
  return frames[static_cast<size_t>(index)];
}

全ての読み出しはpixels(i)を通り、此れが先に番号を調べます。
クリップが無い時にAnimator::frame()が返す−1の様な悪い番号では、vectorの終わりの先を読む代わりに空の長方形を返します。
スプライトの大きさは0になって何も描かれず、stderrの1行が其の事を知らせます(シートごとに1回だけで、毎秒60回ではありません)。

Rect SpriteSheet::uv(int index) const {
  Rect r = pixels(index);
  float w = static_cast<float>(image.width()), h = static_cast<float>(image.height());
  return {r.x / w, r.y / h, r.w / w, r.h / h};
}

Sprite SpriteSheet::sprite(int index, Vec2 position, Vec2 origin, float scale) const {
  return {.texture = &image, .position = position, .size = size(index) * scale, .uv = uv(index), .origin = origin};
}

uv(i)はピクセルの長方形を画像の大きさで割ります。
128 × 128のアトラスの(15, 19)にある12 × 12のcoin_1なら(15/128,19/128,12/128,12/128)=(0.1171875,0.1484375,0.09375,0.09375)です。
128は2の冪なので、どれも2進の浮動小数点数で正確です。
sprite(i, position, origin, scale)はテクスチャ、UV、大きさを埋めたSpriteを返すので、コマを描くのは一行で、要るフィールドは後から変えます:

      // 回る丸のこ(回転は中心の周り:origin = (0.5, 0.5)) / a spinning saw blade (rotates about its center:
      // origin = (0.5, 0.5))
      Sprite saw = objects->sprite(objects->find("saw"), {264.0f, 84.0f}, {0.5f, 0.5f});
      saw.rotation = 3.0f * time;
      saw.layer = 2.0f;
      batch.draw(saw);

シートが自分のテクスチャを持ち、スプライトは其れを指すので、シートは1フレームで其のスプライトを描く全てのバッチより長生きしなければなりません。
クリップはstd::dequeにあり、後ろに足しても要素を動かさないので、clip("walk")が返したポインタは後のaddClipの後も有効です。
std::vectorだと再割り当ての後にぶら下がる事があります。

25.14 コマ送りのアニメーション

コマ送りのアニメーションは、コマの一覧と速さです:

// 一つの動き(歩く・待つ・回る…):スプライトシートのコマ番号の列と速さ
// One motion (walk, idle, spin...): a list of sprite-sheet frame indices and a speed
struct AnimationClip {
  std::string name;
  std::vector<int> frames; // SpriteSheetの番号 / SpriteSheet indices
  float fps = 10.0f;       // 1秒に何コマ / frames per second
  bool loop = true;        // falseなら最後のコマで止まる / false: stops on the last frame

  float duration() const { return fps > 0.0f ? static_cast<float>(frames.size()) / fps : 0.0f; }
};

// クリップを再生する(キャラクター一人に一つ)。クリップは指すだけ(SpriteSheetが持つ)
// Plays a clip (one per character). It only points at the clip (the SpriteSheet owns it)
class Animator {
public:
  // 再生する。同じクリップならそのまま続ける(restart = trueで最初から)。nullptrで止める
  // Plays a clip. The same clip keeps running (restart = true starts it over). nullptr stops
  void play(const AnimationClip *clip, bool restart = false);
  // 時間を進める(固定ステップの更新から呼ぶ) / advances time (call it from the fixed-step update)
  void update(float dt);

  // 今のコマ:スプライトシートの番号(クリップがなければ-1) / the current frame: a sprite-sheet index (-1 without
  // a clip)
  int frame() const;
  // クリップの中で何番目のコマか / which frame of the clip
  int frameIndex() const;
  // 繰り返さないクリップが最後まで行ったか / has a non-looping clip reached its end?
  bool finished() const;
  const AnimationClip *clip() const { return current; }
  float time() const { return elapsed; }

  float speed = 1.0f; // 再生速度の倍率(負なら逆再生) / playback speed multiplier (negative plays backwards)

private:
  const AnimationClip *current = nullptr;
  float elapsed = 0.0f;
};

void Animator::play(const AnimationClip *clip, bool restart) {
  if (clip == current && !restart) return;
  current = clip;
  elapsed = 0.0f;
}

void Animator::update(float dt) {
  if (!current) return;
  elapsed += dt * speed;
  // 繰り返すクリップは時間を一周分に収める(長く動かしてもfloatの精度が落ちない)。負のspeedは逆再生:
  // 繰り返すクリップは最後へ回り込み、onceのクリップは最初のコマで止まる
  // Looping clips keep the time within one cycle (float precision does not degrade over long runs). A negative
  // speed plays backwards: looping clips wrap around to the end, once-clips stop on the first frame
  float length = current->duration();
  if (current->loop && length > 0.0f) {
    elapsed = std::fmod(elapsed, length);
    if (elapsed < 0.0f) elapsed += length;
  } else if (elapsed < 0.0f) {
    elapsed = 0.0f;
  }
}

int Animator::frameIndex() const {
  if (!current || current->frames.empty()) return -1;
  int count = static_cast<int>(current->frames.size());
  int i = static_cast<int>(std::floor(elapsed * current->fps));
  return current->loop ? i % count : std::min(i, count - 1);
}

int Animator::frame() const {
  int i = frameIndex();
  return i < 0 ? -1 : current->frames[static_cast<size_t>(i)];
}

bool Animator::finished() const {
  return current && !current->loop && elapsed * current->fps >= static_cast<float>(current->frames.size());
}

Animatorはキャラクター一人に一つです。
クリップは共有され、アニメーターは一つを指すだけです。
既に再生中のクリップでplayを呼んでも何もしないので、歩いている間は毎回の更新でplay(walk)を呼んでも、歩きが毎回最初に戻る事はありません。
restart = trueで強制的に最初からにします(繰り返せる攻撃等)。
update(dt)は時間を進め、繰り返すクリップではfmodで一周の中に収めるので、何時間遊んでもfloatが大きくなり過ぎて精度が落ちる事はありません。
frameIndexはただの⌊t⋅fps⌋で、繰り返しなら一周させ、onceのクリップなら最後で止めます。

計算例です。
主人公の歩きは10 fpsの4コマなので、一周は4/10=0.4秒です。
0.73秒後、fmod(0.73, 0.4)は0.33で、⌊0.33⋅10⌋=3、クリップのコマ3はシートのコマ5です。
待機のクリップ{0, 0, 0, 0, 0, 0, 1}は6 fpsで7/6≈1.17秒毎に繰り返し、最後の1/6≈0.17秒に瞬きのコマを見せます。
一覧の中でコマを繰り返すのが、コマに違う長さを与える一番簡単な方法です。
coin_spinは4/8=0.5秒で一回転し、slime_bounceは2/3≈0.67秒掛かります。

finished()は、攻撃の様なonceのクリップが最後のコマを再生し終えた事をゲームに教え、ゲームは待機に戻せます。
speedはクリップ全体の時間を拡大縮小します(速く歩く主人公)。
他のキャラクターと共有するクリップには触りません。
負の速さではクリップを逆に再生します。
繰り返すクリップは最初のコマから最後のコマへ回り込み(fmodは符号を残すので、updateは負の時間に一周分を足します)、onceのクリップは最初のコマで止まります。
其れが無いと時間が0より下になり、frameIndexは負の番号を返してしまいます。

25.15 ピクセルアートのフィルタリング

ピクセルアートは、全てのピクセルを手で置いた絵です。
隣のテクセルを混ぜるフィルタリングは正に其れを壊すので、ピクセルアートには幾つかの決まりが要ります。
デモの場面3は其の一つ一つをわざと破ります:

デモの場面3、フィルタリングの比較。上の行:主人公を12倍にしたGL_NEAREST(くっきり)とGL_LINEAR(ぼやける)、7.5倍にして回したGL_NEAREST(不揃いでギザギザのピクセル)とGL_LINEAR(ぼやける)。中の左:DIRECT x6、画面の解像度で回る主人公と丸のこで、斜めの縁が細かい。中:CANVAS x6、同じ物を48 × 48のキャンバスに描いて拡大した物で、回っても粗いピクセル。右:3.3倍にしたタイルを、隙間のあるアトラスからGL_LINEARで描いた物と、隙間の無いアトラスから描いて隣のタイルの細い継ぎ目が見える物

最近傍、整数倍、整数の位置

  • GL_NEAREST、ミップマップ無し。 GL_LINEAR(上の行の2つ目)はテクセルの間を補間し、12倍では全ての縁が12ピクセルの柔らかい坂になる。両方のフィルターはGLSL 第11章で説明した。ミップマップは段毎に2 × 2のテクセルを平均するので、ピクセルアートをぼかし、アトラスでは隣のコマを混ぜる。
  • 整数倍。 7.5倍のGL_NEAREST(3つ目)では、テクセル一つが画面の7.5ピクセルを覆うが、画面のピクセルは分けられないので、テクセルの幅が7と8ピクセルで交互になり、主人公の輪郭が不揃いに見える。此れはにじみではなく丸めで、治すには整数の倍率しかない。だからletterbox(…, true)。
  • 整数のピクセルの位置。 4倍でx = 10.5のスプライトは仮想ピクセルの中の2つ目の画面のピクセルから始まる。直接描くと、倍率が整数なので其のピクセルは矢張りどれも画面の4ピクセル幅だが、周りの全ての物のピクセルと揃わなくなり、動いている間は自分のピクセルより細かい刻みで滑る。位置は丸め(デモではstd::round(heroPos.x))、スクロールするカメラはpixelSnapを使う。

デモは違いを見せる為にhero.pngを2回、フィルター毎に一度ずつ読みます。
フィルターはテクスチャの状態なので、一つの画像に2つのフィルターなら2つのテクスチャ(又は一つのテクスチャと2つのサンプラーオブジェクト、第23章が影の地図の表示でやった様に)が要ります。

キャンバスか直接か

中の行は、25.11節の2つの方法を、同じ主人公と丸のこ、同じ倍率で並べた物です。
DIRECT ×6は6倍のカメラでウィンドウに直接描きます。
回すと縁は画面の細かいピクセルに沿い、滑らかですが絵とは違うピクセルの大きさです。
CANVAS ×6は48 × 48のPixelCanvasに描き、キャンバスのテクスチャを6倍にして描きます。
回しても粗い格子に乗ったままです。
動画で両方を見て下さい:

此処ではキャンバスをブリットではなくスプライトとして描くので、落とし穴がもう一つ見えます:

      // FBOの色テクスチャは下の行がv = 0(GLの約束):y下向きの2DではflipYで描く
      // An FBO's color texture has its bottom row at v = 0 (the GL convention): draw it with flipY in y-down 2D
      Sprite canvasSprite = {.texture = &smallCanvas.framebuffer().color(), .position = {341.0f, 380.0f},
                             .size = {288.0f, 288.0f}, .flipY = true};
      batch.draw(canvasSprite);

OpenGLはy上向きで描くので、フレームバッファの色テクスチャは一番下の行がv=0です。
あたし達のスプライトのUVはv=0が上なので、キャンバスのテクスチャをスプライトとして描くと、flipYでv0とv1を入れ替えない限り上下逆さまになります。
(presentのブリットには要りません。どちらの長方形もGLの下から上の座標で渡すからです。)

アトラスのにじみと隙間

右側のパネルはにじみを見せます。
タイルの縁に、隣のタイルの細い線が現れるのです。
此れはコマの縁の近くのサンプルが其の縁を越えて届くと何時でも起こります。
GL_LINEARでは、サンプラーはサンプルの点の周りの2 × 2のテクセルを混ぜ、テクセルの中心はi+0.5にあります。
テクセル16から始まるタイルの0.2テクセル内側、つまりu=16.2テクセルのサンプルは、中心15.5と16.5の間にあり、テクセル15を16.5−16.2=0.3、テクセル16を0.7取ります。
テクセル15が隣の草のタイルの物なら、草の色が30%土ににじみます。

テクセル12〜19の2つの行。上は隙間無し:テクセル12〜15が草、16〜19が土。u = 16.2のサンプルはテクセル15を0.3、テクセル16を0.7取るので、草の色が30%土ににじむ。下は各タイルに1ピクセルの縁の複製:テクセル12〜14が草で15は草の複製、16は土のタイルの最初のテクセルの複製、17〜19が土。u = 17.2のサンプルはテクセル16を0.3、17を0.7取り、16は17の複製なので結果は土だけ

デモのタイルは3.3倍、0.3と0.4ピクセルずらして描くので、縁のサンプルは丁度其の様な端数に落ちます。
タイルの最初の画面の列は中心が四角形の0.2画面ピクセル内側なので、サンプルは0.2/3.3=0.06テクセル内側、最初のテクセルの中心の0.44テクセル手前にあり、隣の重みは0.44です。
2つのアトラスを拡大すると此うです:

場面3の2つの切り抜きを2倍に拡大した物。上は1ピクセルの縁の複製の隙間ありのGL_LINEAR ×3.3:草、土、レンガ、石、木箱のタイルが綺麗に繋がる。下は隙間なしのGL_LINEAR ×3.3:隣のタイルの細い縦線が土、レンガ、石を走る

解決策は隙間(パディング)です。
アトラスの全てのコマの周りに少なくとも1ピクセルの隙間を空けます。
スプライトの隙間は透明です(乗算済みにするとテクセルは(0, 0, 0, 0)なので、にじんで来ても見えません)。
タイルでは透明な隙間だと透明がにじみ、継ぎ目から背景が見えてしまうので、タイルの縁のピクセルを外側の隙間に複製(extrude)します。
すると縁のサンプルは、タイルの縁を其の複製と混ぜる事になります。
objects.atlasは正に其うしていて、草はx 1〜16にあり縁の複製が0と17、土は19から始まり複製が18と35です。
objects_nopad.atlasは同じタイルを隙間無く詰めた物で、其れが下のパネルです。

整数倍、整数の位置のGL_NEARESTなら、サンプルがコマの外に落ちる事は無いので、隙間は安全網です。
カメラが端数の倍率でズームしたり、スプライトが回ったり、スクロールするカメラがスナップしていなかったりすると、直ぐに役に立ちます。
昔からの方法、全てのUVの長方形を半テクセル縮める事は、隙間無しでも効きますが、全てのコマの縁を半テクセルずつ削ります。
詰め直せないアトラスの為の最後の手段です。

25.16 2Dの色

第21章は3Dの決まりを決めました。
色の画像は全て線型の光にデコードし、ライティングとブレンドは全て線型の値で行い、最後にpost.fragで一度だけエンコードします。
2Dではエンジンはわざと違う選択をします:

  • スプライトのテクスチャ、フォントのテクスチャ、キャンバスは、ファイルのsRGBでエンコードされた値を持つGL_RGBA8(srgb = false)。サンプラーは保存された数をそのまま返す。
  • シェーダーは其の数に色を掛け、ブレンドは其のまま混ぜる。
  • GL_FRAMEBUFFER_SRGBはoffのままなので、結果は変わらずにウィンドウに書かれ、モニターはPNGをデコードするのと同じ様にデコードする。

2つの列。2D(此の章):描いた通りのsRGBの値のスプライトのPNG、其れからsrgb falseのGL_RGBA8で、デコードせずに其のまま読む、其れからsprite.frag+ブレンドで、テクスチャ × 色をsRGBの値のまま混ぜる、其れからGL_FRAMEBUFFER_SRGBがoffの既定のフレームバッファに其のまま書く、其れからモニターがデコードし、画像編集ソフトで見た通り。3D(第21章):sRGBの値の色のPNG、其れからサンプラーが線型にデコードするGL_SRGB8_ALPHA8、其れからRGBA16Fの線型の光でライティング、ブレンド、ブルーム、其れからpost.fragでトーンマッピングしてlinearToSrgb、其れからモニターがデコード。駄目な例:デコードしたsRGBテクスチャをエンコードせずに画面へ書くと暗過ぎる

此れは第21章が警告した間違いではないでしょうか?
ライティングなら間違いです。
光は線型に足し合わされ、エンコードした数は其うならないからです。
でも2Dのスプライトは照らされません。
絵であり、描いた人は全ての半透明のピクセル、フェード、色付けを、(Photoshopの既定の設定でも、普通のピクセルアートのエディターでも)同じく保存した値で混ぜる画像編集ソフトで判断しています。
sRGBの空間で混ぜれば描いた人が見た物が再現され、線型の空間で混ぜれば其れが変わります。
違いは本物です。
黒の上の50%の白は、保存した値のまま混ぜると0.5、レベル128で、画面は其れを白の光の0.214として見せます(第21章の曲線)。
線型の光で混ぜれば光の0.5で、レベル188として保存されます。
黒へのフェードの見え方が違い、どちらも正しくあり得ますが、2Dのゲームでは「描いた通り」が期待され、昔からの2Dのエンジンは此うしています。

其れにhexColor(0xRRGGBBAA)がカラーピッカーで見る数を其のまま取れ、フレームの最後のエンコードのパスも要りません。
もう一つの筋の通った選択は、sRGBのテクスチャ(srgb = true)、線型のブレンド、最後のエンコード(sRGBに対応したフレームバッファでのGL_FRAMEBUFFER_SRGB、又は最後のシェーダーのパス)です。
決してしてはいけないのは混ぜる事です。
サンプラーが線型にデコードするsRGBのテクスチャを、エンコード無しで普通のフレームバッファに書く事です。
すると全ての色が線型の値のまま画面に届き、モニターがもう一度デコードして、全てが暗過ぎる様になります。

後のTPSにも同じ決まりが当てはまります。
其の3Dの画像はpost.fragから既にエンコードされて出て来るので、上にスプライトバッチで描くHUDは、此処と同じくsRGBの値を重ねて混ぜます。

あたしのテスト用のマシンの既定のフレームバッファは、第21章で分かった通りsRGBに対応しているので、其処ではglEnable(GL_FRAMEBUFFER_SRGB)が効いてしまいます。だから2Dのコードは決して其れを有効にしません。offなら、描画もglBlitNamedFramebufferも何も変換しません。

25.17 デモ

準備

demo/main.ccは約400行で、殆どはスプライトを置くコードです。
準備では、Uで切り替えられる様に、頂点の送り方だけが違う2つのバッチを作り、シートを読みます:

  // 二つのスプライトバッチ:頂点の送り方だけが違う(Uで切り替え) / two sprite batches that differ only in how
  // vertices are uploaded (U switches)
  std::optional<SpriteBatch> subDataBatch = SpriteBatch::create({.upload = SpriteUpload::SubData});
  std::optional<SpriteBatch> persistentBatch = SpriteBatch::create({.upload = SpriteUpload::Persistent});
  // ピクセルアートはGL_NEAREST。比較用にGL_LINEARでも読む / pixel art uses GL_NEAREST; also loaded with GL_LINEAR for
  // the comparison
  std::optional<SpriteSheet> hero = SpriteSheet::loadGrid("assets/sprites/hero.png", 16, 16, 1, 1);
  std::optional<SpriteSheet> heroLinear =
      SpriteSheet::loadGrid("assets/sprites/hero.png", 16, 16, 1, 1, TextureFilter::Linear);
  std::optional<SpriteSheet> objects = SpriteSheet::loadAtlas("assets/sprites/objects.atlas");
  std::optional<SpriteSheet> objectsLinear = SpriteSheet::loadAtlas("assets/sprites/objects.atlas", TextureFilter::Linear);
  std::optional<SpriteSheet> noPadLinear = SpriteSheet::loadAtlas("assets/sprites/objects_nopad.atlas", TextureFilter::Linear);
  std::optional<SpriteSheet> font = SpriteSheet::loadGrid("assets/sprites/pixfont.png", 4, 6);
  if (!subDataBatch || !persistentBatch || !hero || !heroLinear || !objects || !objectsLinear || !noPadLinear || !font)
    return 1;

  // 主人公のクリップ:コマの番号はhero.pngの並び(0〜1 待機、2〜5 歩き、6 ジャンプ)
  // The hero's clips: frame numbers follow hero.png (0-1 idle, 2-5 walk, 6 jump)
  hero->addClip({.name = "idle", .frames = {0, 0, 0, 0, 0, 0, 1}, .fps = 6.0f});
  hero->addClip({.name = "walk", .frames = {2, 3, 4, 5}, .fps = 10.0f});
  const AnimationClip *idleClip = hero->clip("idle");
  const AnimationClip *walkClip = hero->clip("walk");
  const AnimationClip *coinClip = objects->clip("coin_spin");
  const AnimationClip *slimeClip = objects->clip("slime_bounce");
  if (!idleClip || !walkClip || !coinClip || !slimeClip) return 1;

全ての資源を確かめている事に注目して下さい。
全てのファクトリーがstd::optionalを返し、ファイルが無ければプログラムは理由を表示して1で終わります。
カメラ:

  // 場面1:320×180の仮想解像度(1280×720にちょうど4倍) / scene 1: a 320 × 180 virtual resolution (exactly 4× in 1280 × 720)
  PixelCanvas canvas(320, 180);
  Camera2D canvasCamera = Camera2D::screen(canvas.size());
  // 場面2・3:ウィンドウのピクセルそのまま / scenes 2 and 3: plain window pixels
  Camera2D screenCamera = Camera2D::screen({1280.0f, 720.0f});
  // 場面3のキャンバス比較用:48×48の小さなキャンバス / for scene 3's canvas comparison: a small 48 × 48 canvas
  PixelCanvas smallCanvas(48, 48);
  Camera2D smallCamera = Camera2D::screen(smallCanvas.size());

デモはまだ可変の時間の刻み(window.time()からのdt)を使います。
ゲームが使う固定ステップのゲームループは第26章で紹介します。
HUDの文字は20行程の補助関数drawPixelTextで描きます。
ASCII 32〜95の為の4 × 6のマスの格子のシートに入った3 × 5のフォントで、文字cはコマc − 32、ペンは1文字毎に4ピクセル進みます。
もう一つの補助関数pixelTextSizeは文字が覆う大きさ(一番長い行 × 4ピクセルから最後の隙間を引いた幅と、行数 × 6から1を引いた高さ)を返すので、HUDの背景の箱は余白を揃えて文字に合います。
第26章で其れをちゃんとしたFontクラスに置き換えます。

場面1:ピクセルアートの場面

場面1の各フレームは、キャンバスを繋いでlayerで並べ替えるバッチを始める所から始まります:

      canvas.begin(hexColor(0x8fd3ffff));
      batch.begin(canvasCamera.matrix(), SpriteSort::Layer);
      // 雲:ゆっくり流れる(奥、layer 0) / clouds drift slowly (at the back, layer 0)
      int cloud = objects->find("cloud");
      for (int i = 0; i < 3; ++i) {
        float x = std::fmod(40.0f + 130.0f * static_cast<float>(i) + 6.0f * time, 380.0f) - 40.0f;
        Sprite s = objects->sprite(cloud, {std::round(x), 18.0f + 14.0f * static_cast<float>(i % 2)});
        batch.draw(s);
      }

其の後に、layer 1に地面、足場、木箱、柱、layer 2に丸のこ、コイン、宝石、ハート、花、スライム、そして主人公達が来ます:

      // 色を掛けた主人公:赤、半透明、影(黒) / tinted heroes: red, half transparent, a black silhouette
      const Vec4 tints[] = {hexColor(0xff7070ff), {1.0f, 1.0f, 1.0f, 0.45f}, hexColor(0x000000b0)};
      for (int i = 0; i < 3; ++i) {
        Sprite s = hero->sprite(0, {192.0f + 20.0f * static_cast<float>(i), 96.0f}, {0.5f, 1.0f});
        s.color = tints[i];
        s.layer = 2.0f;
        batch.draw(s);
      }
      // 主人公:足元(下の中心)が基準。左へ歩くときは左右反転 / the hero: the pivot is the feet (bottom center).
      // Mirrored when walking left
      Sprite h = hero->sprite(heroAnim.frame(), {std::round(heroPos.x), heroPos.y}, {0.5f, 1.0f});
      h.flipX = heroDir < 0.0f;
      h.layer = 3.0f;
      batch.draw(h);
      batch.end();
      SpriteStats stats = batch.stats();
      // HUD(同じキャンバス、別のbegin/end) / the HUD (same canvas, a separate begin/end)
      batch.begin(canvasCamera.matrix());
      char hud[128];
      snprintf(hud, sizeof hud, "SCENE 1: PIXEL ART 320X180 X4\nSPRITES %d  DRAW CALLS %d", stats.sprites, stats.drawCalls);
      Vec2 hudSize = pixelTextSize(hud, 1.0f);
      batch.drawRect({2.0f, 2.0f, hudSize.x + 4.0f, hudSize.y + 4.0f}, hexColor(0x1b172699)); // 2ピクセルの余白 / 2 px margin
      drawPixelText(batch, *font, hud, {4.0f, 4.0f}, 1.0f, kWhite);
      batch.end();
      canvas.present(window.width(), window.height());

主人公のoriginは(0.5, 1)、足元なので、heroPosは草の上に立つ点です(y = 144は草の行の上端)。
flipXで向きを変えると、左の縁ではなく足元を軸に左右反転します。
xは整数のピクセルに丸め、yは最初から整数です。
HUDは場面の後に、同じキャンバスへの2回目のbegin/endで既定の並べ替えで描くので、何時も一番上です。
其れからcanvas.presentが320 × 180のキャンバスを4倍にして1280 × 720のウィンドウに入れ、此の大きさなら帯はありません。

場面2:1万個のスプライト

場面2はCamera2D::screen({1280, 720})でウィンドウに直接描きます:

      auto start = std::chrono::steady_clock::now();
      batch.begin(screenCamera.matrix(), sortByTexture ? SpriteSort::Texture : SpriteSort::None);
      for (const Mover &m : movers) {
        // 主人公は歩き、コインは回る。コマはそれぞれの時間のずれで / heroes walk, coins spin, each with its own offset
        int heroFrame = 2 + static_cast<int>((time + m.phase) * 10.0f) % 4;
        int coinFrame = coinClip->frames[static_cast<size_t>((time + m.phase) * 8.0f) % 4];
        Sprite s = m.kind == 0 ? hero->sprite(heroFrame, m.position, {0.5f, 0.5f}, 2.0f)
                               : objects->sprite(coinFrame, m.position, {0.5f, 0.5f}, 2.0f);
        s.rotation = m.angle;
        batch.draw(s);
      }
      batch.end();
      float batchMs = std::chrono::duration<float, std::milli>(std::chrono::steady_clock::now() - start).count();
      SpriteStats stats = batch.stats();

moversはわざと2つのテクスチャを交互にしていて(m.kind = i % 2)、SpriteSort::Noneにとって最悪の場合です。
画像は両方のモードです。
此のスプライトは重なりの順番を気にしないので、見た目は同じで、其処が要点です:

場面2のスクリーンショット2枚を並べた物。2倍にした1万個の回る主人公とコイン。左:SpriteSort::None、描画コール10 000回。右:SpriteSort::Texture、描画コール2回。HUDはスプライトの数、描画コール、並べ替えと送り方のモード、バッチとフレームのCPUの時間を表示

動画は1250個(−キーを3回)で動かしています。
1万個の小さな動くスプライトは小さな動画に圧縮出来ないからです:

場面3:フィルタリング

場面3は25.15節の画像です。
×12と×7.5で両方のフィルターの主人公の4つのパネル、直接とキャンバスのパネル、隙間ありと無しのタイルです。
全て既定の並べ替えSpriteSort::Noneの一つのバッチ(と48 × 48のキャンバスへの小さなバッチ)で描きます。
Noneは描いた順番を保つので、各パネルの背景の長方形は其の上のスプライトやラベルより先に描かれます。

25.18 性能

あたしのテスト用のマシン(2つのCPUコアで動くMesaのソフトウェアラスタライザーllvmpipe。其れが何を意味するかは第19章で説明しました)では、1万個のスプライトの場面2で、beginからend迄のバッチのCPUの時間は此うなります:

モード 描画コール バッチの時間
SpriteSort::Texture、SubData 2 約5〜16 ms、大抵10
SpriteSort::None、SubData 10 000 約60〜100 ms
SpriteSort::Texture、Persistent 2 約40〜45 ms

最初の2行が此の章の言いたい事です。
同じ1万個のスプライトでも、一つ一つが別の描画コールだと6〜10倍のCPUの時間が掛かります。
本物のGPUのドライバーではどちらの数字も小さくなりますが、比は同じ位かもっと悪くなります。
呼び出し毎のドライバーのオーバーヘッドは、正にGPUがCPUから取り除けない物だからです。

3行目は永続マップが4倍遅い様に見え、此のマシンでは実際其うですが、思う様な理由ではありません。
四角形をマップした所にコピーするのは5000個のスプライト当たり約0.07 msで、40 msの残りはglClientWaitSyncの中で費やされます。
llvmpipeはワーカースレッドでラスタライズし、テスト用ハーネスのバッファの交換はCPUに画面を待たせる事が無いので、CPUはラスタライザーのずっと先を走ります。
SubDataでは其の遅れは見えません。
ドライバーがコピーと描画を待ち行列に入れ、CPUは先へ進むからです。
永続マップでは、フェンスの待ちが、CPUがラスタライザーが追い付くのを実際に待つ最初の場所になるので、待ちが測っているのはアップロードではなくラスタライザーです。

なので此の測定はGPUを代表しておらず、此処から結論を出すべきではありません。
本物のGPUで期待される振る舞いは逆です。
GPU自身が詰まっていない限り、CPUが輪を一周して戻って来る前にGPUは区画を終えているので、フェンスは既にシグナル状態で、glClientWaitSyncは直ぐに戻ります。
CPUはGPUが読むメモリに直接書き、ドライバーのコピーも、glNamedBufferSubDataの中の暗黙の同期もありません。
どれだけ節約出来るかはドライバー次第で、数千個のスプライトならどちらの方法も大抵十分速いです。
永続マップが効くのは、1フレームのデータが大きくなる時(大量のパーティクル、文字、デバッグ用の線)や、使用中のバッファへのglNamedBufferSubDataをドライバーが扱う時に止まってしまう時です。
自分のハードウェアでGPUのタイマー(第19章のGpuTimer)で測るのが確かめる方法です。

場面1の1フレーム、90個のスプライトの320 × 180のキャンバスとHUDとブリットは、此処でも数ミリ秒です。

25.19 プラットフォーム毎の注意

  • FreeBSD(とmacOS)のsed -iはバックアップの拡張子の引数が要ります。sed -i -E '…'ではなくsed -i '' -E '…'と書いて下さい。LinuxのGNU sedは25.4節の形を受け付けます。Windowsでは、エディターの「複数ファイルの置換」(正規表現^#include "([a-z_0-9]+.hh)" → #include "engine/$1")でインクルードを直すか、Git for Windowsと一緒にsedを入れて下さい。
  • Visual Studio。 生成されたソリューションには今は幾つものプロジェクトがあります。VS_STARTUP_PROJECTがgameを選び、別のプロジェクトを右クリック → 「スタートアップ プロジェクトに設定」で其れを起動出来、作業ディレクトリは設定済みです。「フォルダーを開く」モードでは、launch.vs.jsonにターゲット毎にcurrentDirを足して下さい(25.6節)。ファイルを移した後はビルドのフォルダー又はCMakeのキャッシュを消して下さい。さもないとVisual Studioが古いターゲットを持ち続けます。
  • 永続マップはOpenGL 4.4又はARB_buffer_storageが要るので、GL 4.6のドライバーには全てあります。WindowsとLinuxのNVIDIA、AMD、Intel、LinuxとFreeBSDのMesaです。
  • 強制のアンチエイリアス。 ドライバーのコントロールパネルが全てのOpenGLのウィンドウにマルチサンプルを強制すると、既定のフレームバッファがマルチサンプルになり、PixelCanvas::presentの拡大縮小のブリットがGL_INVALID_OPERATIONで失敗します(第2章のデバッグ出力が教えてくれます)。コントロールパネルを「アプリケーションによる制御」にして下さい。
  • エンディアン。 packColorはリトルエンディアンのCPUを前提にしていて、あたし達の全てのプラットフォーム(x86-64とARM64)は其うです。

25.20 本物のエンジンではどうしているか

  • インスタンシング又は頂点プリング。 スプライト毎に20バイトの頂点を4つではなく、多くのエンジンはスプライト毎にインスタンスを一つ(位置、大きさ、origin、回転、UVの長方形、色:80バイトではなく48バイト)アップロードし、角は頂点シェーダーで作ります。インスタンスの属性と共有の単位四角形で(第19章)、又はgl_VertexIDでシェーダーストレージバッファを読んで(「頂点プリング」)。課題5は前者をやります。
  • テクスチャの切り替えを減らす。 頂点毎にレイヤーの番号を持つGL_TEXTURE_2D_ARRAYのアトラスや、バインドレステクスチャ(ARB_bindless_texture)で、1回の描画コールが沢山の画像を使えるので、並べ替えないスプライトでも1回の呼び出しにまとまります(課題7)。Vulkanのデスクリプターインデクシングも同じ考えです。
  • 並べ替えの代わりに深度。 不透明なスプライトは深度バッファとlayerをzとして使い、どの順番でも描けます。並べ替えが要るのは半透明の物だけです。ピクセルアートでは殆ど全てが不透明か完全な透明なので、アルファテストと深度が良く効きます。
  • 道具。 本物のプロジェクトは道具(TexturePacker、Asepriteのスプライトシートの書き出し、UnityのSprite Atlas)でアトラスを詰め、隙間を自動で足し(TexturePackerとAsepriteは縁の複製も出来ます)、アニメーションのデータも書き出します。此のシリーズのアトラスを作ったあたしのスクリプトは其の小さな版です。
  • Godot、Unity、LÖVEも似た考えで2Dの描画をまとめます。同じテクスチャ(とマテリアル)の続けての描画を1回の描画コールにまとめ、頂点を毎フレーム流し込みます。描く順番は使う人が決める物(ソーティングレイヤー、zインデックス)か、LÖVEでは単に描画の呼び出しの順番で決まります。細かい所はエンジンやバージョンによって違います。Unityの「Pixel Perfect Camera」はletterbox(…, true)とpixelSnapがする事をし、低解像度の描き先、つまりあたし達のPixelCanvasに描く事も出来ます。
  • VulkanとSlang。 其処では動的な頂点バッファは大抵、フェンス付きの「永続的にマップした」ホストから見えるメモリで、実行中のフレーム毎に区画が一つです。此の章の輪のバッファは又出会う形です。

25.21 まとめ

  • 此の章から、使い回すコードは静的ライブラリengine。ヘッダーはengine/include/engine/(何時も#include "engine/x.hh")、ソースはengine/src/、シェーダーはengine/shaders/。プログラムはgame(demo/)、scene3d(tests/)、gltf_dump(tools/)、そして第27章からはgames/<name>/のゲーム。
  • CMake:add_subdirectory(engine)、add_library(engine STATIC …)、PUBLICのインクルードのディレクトリとglad/glfw、PRIVATE stb_image(ライブラリが静的なので、矢張り全ての実行ファイルにリンクされる)、関数enable_warningsとset_working_directory。ゲームにはtarget_link_libraries(<name> PRIVATE engine)が要る。
  • 全てのプログラムをプロジェクトのルートから実行する。 パス:engine/shaders/…、assets/…、games/<name>/…。
  • ShadowMapとPostChain(renderer3d.hh)が第20〜24章のフレームのコードを持つ。scene3dは第24章をピクセル単位で同じに描く。
  • 2Dの約束:仮想ピクセル、y下向き、原点は左上、時計回りの回転、画像の0行目 = v=0。Camera2D::matrix()はtop = −h、bottom = +hのorthographicGlを使い、yndc=−y/hになる。
  • レターボックスはビューを一番大きな(整数の)倍率で収める。Viewportはyの両方の約束を持ち、マウスを変換する。PixelCanvasは仮想解像度で描き、GL_NEARESTでブリットする。
  • SpriteBatch:角はCPUで、正規化したバイトの色の20バイトの頂点、変わらないインデックスバッファ一つとglDrawElementsBaseVertex、同じテクスチャの連続一つに描画コール1回。並べ替えのモードNone、Texture、Layer:場面2で10 000回対2回、場面1で4回。
  • アップロード:glNamedBufferSubData(簡単、ドライバーが同期する)又は永続マップ(GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT、3つの区画、glFenceSyncとglClientWaitSync)。
  • 何処でも乗算済みアルファ。Alpha = (GL_ONE, GL_ONE_MINUS_SRC_ALPHA)、Additive = (GL_ONE, GL_ONE)。end()の後:ブレンドon、深度テストoff、カリングoff。
  • スプライトシート:loadGrid(margin、spacing)とloadAtlas(.atlasのテキストの形式)。AnimationClip+Animator:コマ、fps、loop、play、update、frame。
  • ピクセルアート:GL_NEAREST、ミップマップ無し、整数倍、整数のピクセルの位置、にじみ対策に1 px以上の隙間(スプライトは透明、タイルは縁の複製)。スプライトとして描くFBOのテクスチャにはflipYが要る。
  • 2Dの色:スプライトはsRGBの値のGL_RGBA8で描いた通りに混ぜ、GL_FRAMEBUFFER_SRGBはoff。第21章の線型の3Dのパイプラインとは違う。
  • llvmpipeでは、永続マップの道はアップロードのコストではなくCPUのラスタライザーでのフェンスの待ちを測ってしまう。GPUを代表しない。

25.22 課題

  1. ★ 場面1のメインのバッチをSpriteSort::Noneにし、歩く主人公を描く行(Sprite h = …からbatch.draw(h)迄)をbatch.beginの直後に移して下さい。主人公が木箱、石の柱、花、スライムの前を通る時、其れらが主人公の上に描かれ、HUDは描画コールが4回ではなく3回(hero.png、objects.png、色付きの主人公の為にもう一度hero.png)と表示するはずです。其の後layerを元に戻して下さい。
  2. ★ 場面2に3つ目のテクスチャを足して下さい。3つ毎に1つの動く物をpixfont.pngの文字にします(m.kind = i % 3)。テクスチャ毎(既定)ではHUDが描画コール3回を表示し、並べ替え無し(Tを押す)ではスプライト毎に1回の10 000回のままのはずです。
  3. ★ 場面1の丸のこを、メインのバッチの後に自分のbegin/endでSpriteBlend::Additiveにしてオレンジ色(hexColor(0xff9030ff))を掛けて描き、石の柱に重なる様に12ピクセル下へ動かして下さい。空の上では殆ど白くなり(空と丸のこが足されて1を超える)、石に重なる所では石が覆われずに明るくなって透けて見え、透明な角は何も変えないはずです。
  4. ★★ キーを押していない時は主人公を立ち止まらせて下さい(input == 0ならidleClipを再生し、押した時だけ動く)。すると待機のクリップの瞬きが漸く見え、7/6≈1.17秒毎に1/6秒の間瞬くはずです。其の後、スペースを押した時にジャンプのコマ6をonceのクリップとして足し、finished()で待機に戻して下さい。
  5. ★★ スプライト毎の4つの頂点をインスタンシングに置き換えて下さい。変わらない単位四角形と、スプライト毎のインスタンス一つ(位置、大きさ、origin、回転、UVの長方形、色:48バイト)で、角はsprite.vertでgl_VertexID又は四角形の属性とglVertexArrayBindingDivisorから作ります。画像は全く同じのまま、スプライト当たりのアップロードは80バイトから48バイト(60%)に減り、描画コールの数は変わらないはずです。
  6. ★★ 場面1のカメラをzoom = 2で主人公に付いて行かせ、場面1をウィンドウに直接(キャンバスの代わりに1280 × 720のレターボックスで)描いて下さい。pixelSnap = falseとtrueで一度ずつです。スナップしないとタイルはウィンドウのどのピクセルにも来られるので、絵のピクセルの8分の1の刻みで、絵自身のピクセルより細かくスクロールし、スナップするとビューの整数のピクセル(拡大率2ではウィンドウの4ピクセル、絵のピクセルの半分)で動くはずです。倍率が整数なので、どちらでも絵のピクセルは全て丁度ウィンドウの8 × 8ピクセルのままです。キャンバス版ではどちらでもキャンバスの整数のピクセルで動きます。(主人公は丸めたxで描き、カメラは丸めていない位置に付いて行くので、どの版でも主人公はワールドに対して少し揺れます。)
  7. ★★★ hero.pngとobjects.pngを一つのGL_TEXTURE_2D_ARRAY(137 × 128のレイヤー2つ、小さい画像は余白で埋め、UVは其の大きさで計算)に入れ、SpriteVertexにレイヤーの番号を足し、sampler2DArrayで読んで下さい。すると場面2はSpriteSort::Noneでも描画コール2回を表示し(8192の容量が矢張り1万個のスプライトを2回に分ける)、−を1回押すと(5000個)描画コール1回になるはずです。

DIFFをダウンロード

プロジェクトをダウンロード(ZIP)

ファイル: a/CMakeLists.txt | b/CMakeLists.txt

前新
@@ -19,58 +19,63 @@ endif()
19 add_library(glad STATIC external/glad/src/glad.c) 19 add_library(glad STATIC external/glad/src/glad.c)
20 target_include_directories(glad PUBLIC external/glad/include) 20 target_include_directories(glad PUBLIC external/glad/include)
21   21  
22 # stb_image:実装は src/stb_image_impl.cc だけ。他人のコードなので警告フラグなしの別ライブラリにする 22 # 警告を有効にする(自分のコードだけ)。エンジンとゲームの全ターゲットで使う
23 # stb_image: the implementation lives in src/stb_image_impl.cc only. It is someone else's code, 23 # Enables warnings (our own code only). Used by the engine and every game target
24 # so it is a separate library built without our warning flags 24 function(enable_warnings target)
25 add_library(stb_image STATIC src/stb_image_impl.cc)    
26 target_include_directories(stb_image PUBLIC external/stb)    
27      
28 add_executable(game    
29 src/main.cc    
30 src/window.cc    
31 src/gl_debug.cc    
32 src/buffer.cc    
33 src/mesh.cc    
34 src/file_util.cc    
35 src/shader.cc    
36 src/texture.cc    
37 src/shapes.cc    
38 src/camera.cc    
39 src/material.cc    
40 src/lights.cc    
41 src/json.cc    
42 src/gltf.cc    
43 src/model.cc    
44 src/framebuffer.cc    
45 src/cubemap.cc    
46 src/gpu_timer.cc    
47 src/tangents.cc    
48 src/ibl.cc    
49 src/pbr_material.cc)    
50 target_include_directories(game PRIVATE src external/stb external/linalg)    
51 target_link_libraries(game PRIVATE glad stb_image glfw)    
52      
53 # glTF/GLBの中身を表示する道具。GPUもウィンドウも使わないのでGLFWとGLADは要らない    
54 # A tool that prints what is inside glTF/GLB files. It uses no GPU and no window, so no GLFW and no GLAD    
55 add_executable(gltf_dump    
56 src/gltf_dump.cc    
57 src/gltf.cc    
58 src/json.cc    
59 src/file_util.cc)    
60 target_include_directories(gltf_dump PRIVATE src external/linalg)    
61      
62 # 警告を有効にする(自分のコードだけ) / enable warnings (our own code only)    
63 foreach(target game gltf_dump)    
64 if(MSVC) 25 if(MSVC)
65 target_compile_options(${target} PRIVATE /W4 /utf-8) 26 target_compile_options(${target} PRIVATE /W4 /utf-8)
66 else() 27 else()
67 target_compile_options(${target} PRIVATE -Wall -Wextra) 28 target_compile_options(${target} PRIVATE -Wall -Wextra)
68 endif() 29 endif()
69 endforeach() 30 endfunction()
    31  
    32 # シェーダーとアセットは作業ディレクトリ(= プロジェクトのルート)からの相対パスで読む:
    33 # engine/shaders/…(エンジン)、assets/…(共有)、games/<名前>/…(各ゲーム)。
    34 # Visual Studioでは各実行ファイルの作業ディレクトリをルートにする。Unixではルートから ./build/game を実行。
    35 # Shaders and assets are loaded relative to the working directory (= the project root):
    36 # engine/shaders/... (the engine), assets/... (shared), games/<name>/... (each game).
    37 # Visual Studio: every executable's working directory is the root. Unix: run ./build/game from the root.
    38 function(set_working_directory target)
    39 set_property(TARGET ${target} PROPERTY VS_DEBUGGER_WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}")
    40 endfunction()
    41  
    42 # エンジン:第1〜24章のクラス+2Dの道具(静的ライブラリ) / the engine: the classes of chapters 1-24 + the 2D toolkit
    43 # (a static library)
    44 add_subdirectory(engine)
70   45  
71 # シェーダーとアセットは作業ディレクトリからの相対パスで読む。 46 # この章のデモ / this chapter's demo
72 # Visual Studioではプロジェクトのルートを作業ディレクトリにする。Unixではルートから ./build/game を実行。 47 add_executable(game demo/main.cc)
73 # Shaders and assets are loaded relative to the working directory. 48 target_link_libraries(game PRIVATE engine)
74 # Visual Studio: use the project root as the working directory. Unix: run ./build/game from the root. 49 enable_warnings(game)
75 set_property(TARGET game PROPERTY VS_DEBUGGER_WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") 50 set_working_directory(game)
76 set_property(DIRECTORY PROPERTY VS_STARTUP_PROJECT game) 51 set_property(DIRECTORY PROPERTY VS_STARTUP_PROJECT game)
    52  
    53 # glTF/GLBの中身を表示する道具。GPUもウィンドウも使わないのでエンジン全体はリンクしない(GLFWもGLADも要らない)
    54 # A tool that prints what is inside glTF/GLB files. It uses no GPU and no window, so it does not link the whole
    55 # engine (no GLFW, no GLAD)
    56 add_executable(gltf_dump
    57 tools/gltf_dump.cc
    58 engine/src/gltf.cc
    59 engine/src/json.cc
    60 engine/src/file_util.cc)
    61 target_include_directories(gltf_dump PRIVATE engine/include external/linalg)
    62 enable_warnings(gltf_dump)
    63  
    64 # 第24章の3D場面をエンジンで描く確認用プログラム(影・PBR・IBL・ブルーム)。TPS(第36〜39章)の土台
    65 # A check that draws the chapter 24 3D scene through the engine (shadows, PBR, IBL, bloom). The basis of the TPS
    66 # (chapters 36-39)
    67 option(BUILD_SCENE3D "Build the 3D check program scene3d" ON)
    68 if(BUILD_SCENE3D)
    69 add_executable(scene3d tests/scene3d/main.cc)
    70 target_link_libraries(scene3d PRIVATE engine)
    71 enable_warnings(scene3d)
    72 set_working_directory(scene3d)
    73 endif()
    74  
    75 # ゲーム(第27章から):games/<名前>/CMakeLists.txt があれば加える。各ゲームは自分の実行ファイル
    76 # The games (from chapter 27): added when games/<name>/CMakeLists.txt exists. Each game is its own executable
    77 foreach(name invaders fighter rpg tps)
    78 if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/games/${name}/CMakeLists.txt")
    79 add_subdirectory(games/${name})
    80 endif()
    81 endforeach()

ファイル: a/README.md | b/README.md

前新
@@ -41,11 +41,29 @@ build\Debug\game.exe
41 または `build\opengl_tutorial.sln` を開いてF5(作業ディレクトリはプロジェクトのルートに設定済み)。 41 または `build\opengl_tutorial.sln` を開いてF5(作業ディレクトリはプロジェクトのルートに設定済み)。
42 Or open `build\opengl_tutorial.sln` and press F5 (the working directory is already set to the project root). 42 Or open `build\opengl_tutorial.sln` and press F5 (the working directory is already set to the project root).
43   43  
44 glTF/GLBファイルの中身を表示する道具(第13章から) / a tool that prints what is inside a glTF/GLB file (from chapter 13): 44 ## プロジェクトの構成 / Project layout(第25章から / from chapter 25)
    45  
    46 ```
    47 engine/ エンジン(静的ライブラリ engine) / the engine (static library `engine`)
    48 include/engine/*.hh 公開ヘッダー:#include "engine/sprite_batch.hh" / public headers
    49 src/*.cc 実装 / implementation
    50 shaders/ エンジンのシェーダー / the engine's shaders
    51 demo/main.cc この章のデモ(実行ファイル game) / this chapter's demo (executable `game`)
    52 assets/ 共有のアセット(スプライト、フォント、3Dモデル) / shared assets (sprites, fonts, 3D models)
    53 tools/gltf_dump.cc glTF/GLBの中身を表示する道具(gltf_dump) / prints what is inside a glTF/GLB file
    54 tests/scene3d/main.cc 3Dの確認:第24章の場面をエンジンで描く(scene3d、-DBUILD_SCENE3D=OFFで外せる)
    55 the 3D check: the chapter 24 scene through the engine (`scene3d`; -DBUILD_SCENE3D=OFF skips it)
    56 games/<名前>/ ゲーム(第27章から、それぞれ自分の実行ファイル) / the games (from chapter 27, one executable each)
    57 ```
45   58  
46 ```sh 59 ```sh
47 ./build/gltf_dump assets/models/diorama.glb # Windows: build\Debug\gltf_dump.exe assets\models\diorama.glb 60 ./build/game # この章のデモ / this chapter's demo
    61 ./build/scene3d # 3Dの確認 / the 3D check
    62 ./build/gltf_dump assets/models/diorama.glb # Windows: build\Debug\gltf_dump.exe assets\models\diorama.glb
48 ``` 63 ```
49   64  
50 シェーダーとアセットは作業ディレクトリからの相対パスで読み込むので、必ずプロジェクトのルートから実行すること。 65 シェーダーとアセットは作業ディレクトリからの相対パスで読み込むので、必ずプロジェクトのルートから実行すること
51 Shaders and assets are loaded relative to the working directory, so always run from the project root. 66 (engine/shaders/…、assets/…、games/<名前>/…)。Visual Studioではどの実行ファイルも作業ディレクトリがルートに設定済み。
    67 Shaders and assets are loaded relative to the working directory, so always run from the project root
    68 (engine/shaders/..., assets/..., games/<name>/...). In Visual Studio every executable already uses the root as its
    69 working directory.

ファイル: a/assets/LICENSE.txt | b/assets/LICENSE.txt

前新
@@ -18,3 +18,7 @@ textures/bricks.png レンガ / bricks (chapter 22)
18 textures/bricks_normal.png レンガの法線マップ+高さ / brick normal map + height (chapter 22) 18 textures/bricks_normal.png レンガの法線マップ+高さ / brick normal map + height (chapter 22)
19 models/barrel.glb 樽(PBRのテクスチャ付き) / a barrel with PBR textures (chapter 22) 19 models/barrel.glb 樽(PBRのテクスチャ付き) / a barrel with PBR textures (chapter 22)
20 textures/leaves.png 葉(アルファ付き) / leaves with alpha (chapter 23) 20 textures/leaves.png 葉(アルファ付き) / leaves with alpha (chapter 23)
    21 sprites/hero.png ピクセルアートの主人公(16×16、7コマ) / pixel-art hero (16×16, 7 frames) (chapter 25)
    22 sprites/objects.png/.atlas タイル・コイン・宝石・スライムなど / tiles, coins, gems, slime... (chapter 25)
    23 sprites/objects_nopad.* 隙間なしのタイル(にじみの例) / tiles without gaps (the bleeding example) (chapter 25)
    24 sprites/pixfont.png 3×5のピクセルフォント / a 3×5 pixel font (chapter 25)

ファイル: /dev/null | b/assets/sprites/hero.png

新しいファイル:100644 / バイナリファイル

ファイル: /dev/null | b/assets/sprites/objects.atlas

前新
@@ -0,0 +1,20 @@
    1 # objects: tiles (extruded 1 px borders), items, slime, cloud (generated by the author's own script)
    2 image objects.png
    3 sprite grass 1 1 16 16
    4 sprite dirt 19 1 16 16
    5 sprite brick 37 1 16 16
    6 sprite stone 55 1 16 16
    7 sprite crate 73 1 16 16
    8 sprite coin_0 1 19 12 12
    9 sprite coin_1 15 19 12 12
    10 sprite coin_2 29 19 12 12
    11 sprite coin_3 43 19 12 12
    12 sprite gem 57 19 10 9
    13 sprite heart 69 19 9 8
    14 sprite saw 80 19 16 16
    15 sprite slime_0 98 19 16 16
    16 sprite slime_1 1 37 16 16
    17 sprite flower 19 37 8 8
    18 sprite cloud 29 37 32 12
    19 clip coin_spin 8 loop coin_0 coin_1 coin_2 coin_3
    20 clip slime_bounce 3 loop slime_0 slime_1

ファイル: /dev/null | b/assets/sprites/objects.png

新しいファイル:100644 / バイナリファイル

ファイル: /dev/null | b/assets/sprites/objects_nopad.atlas

前新
@@ -0,0 +1,7 @@
    1 # the same tiles WITHOUT gaps (bleeding demo, chapter 25; generated by the author's own script)
    2 image objects_nopad.png
    3 sprite grass 0 0 16 16
    4 sprite dirt 16 0 16 16
    5 sprite brick 32 0 16 16
    6 sprite stone 48 0 16 16
    7 sprite crate 64 0 16 16

ファイル: /dev/null | b/assets/sprites/objects_nopad.png

新しいファイル:100644 / バイナリファイル

ファイル: /dev/null | b/assets/sprites/pixfont.png

新しいファイル:100644 / バイナリファイル

ファイル: /dev/null | b/demo/main.cc

前新
@@ -0,0 +1,427 @@
    1 // 第25章:2Dレンダリングとスプライト
    2 // Chapter 25: 2D rendering and sprites
    3 //
    4 // 操作 / Controls:
    5 // 1 / 2 / 3 場面:ピクセルアート(320×180のキャンバス) / 10 000スプライト / フィルタリングの比較
    6 // scene: pixel art (a 320 × 180 canvas) / 10 000 sprites / filtering comparison
    7 // ← → / A D 主人公を歩かせる(場面1。押さなければ自動で歩く) / walk the hero (scene 1; walks by itself otherwise)
    8 // T 並べ替え:なし ⇔ テクスチャごと(場面2:描画コール 約10 000 ⇔ 2) / sorting: none ⇔ by texture
    9 // (scene 2: about 10 000 ⇔ 2 draw calls)
    10 // U 頂点の送り方:glNamedBufferSubData ⇔ 永続マップ / vertex upload: glNamedBufferSubData ⇔ persistent
    11 // mapping
    12 // = / - スプライトの数を2倍・半分に(場面2) / twice / half as many sprites (scene 2)
    13 // P アニメーションを止める・動かす / pause / resume the animation
    14 // Esc 終了 / quit
    15 //
    16 // 2Dの約束(エンジン全体):仮想ピクセル、y下向き、左上が原点、正の回転は時計回り。色はsRGBの値のまま混ぜる
    17 // The 2D conventions (engine-wide): virtual pixels, y down, origin at the top left, positive rotation is clockwise.
    18 // Colors are blended as sRGB-encoded values
    19 #include "engine/animation.hh"
    20 #include "engine/camera2d.hh"
    21 #include "engine/pixel_canvas.hh"
    22 #include "engine/sprite_batch.hh"
    23 #include "engine/sprite_sheet.hh"
    24 #include "engine/window.hh"
    25  
    26 #include <algorithm>
    27 #include <chrono>
    28 #include <cmath>
    29 #include <cstdint>
    30 #include <cstdio>
    31 #include <optional>
    32 #include <string>
    33 #include <string_view>
    34 #include <vector>
    35  
    36 // 第25章のHUD:3×5のピクセルフォント(格子のシート、ASCII 32〜95)で文字を描く。第26章でFontクラスになる
    37 // The chapter 25 HUD: text drawn with the 3 × 5 pixel font (a grid sheet, ASCII 32-95). Chapter 26 turns this into
    38 // the Font class
    39 static void drawPixelText(SpriteBatch &batch, const SpriteSheet &font, std::string_view text, Vec2 position,
    40 float scale, Vec4 color, float layer = 100.0f) {
    41 Vec2 pen = position;
    42 for (char c : text) {
    43 if (c == '\n') {
    44 pen = {position.x, pen.y + 6.0f * scale};
    45 continue;
    46 }
    47 if (c >= 'a' && c <= 'z') c = static_cast<char>(c - 'a' + 'A'); // 大文字だけ / capitals only
    48 int index = c - 32;
    49 if (index > 0 && index < font.count()) {
    50 Sprite s = font.sprite(index, pen, {0.0f, 0.0f}, scale);
    51 s.color = color;
    52 s.layer = layer;
    53 batch.draw(s);
    54 }
    55 pen.x += 4.0f * scale; // 送り幅:3ピクセル+隙間1 / advance: 3 pixels + 1 gap
    56 }
    57 }
    58  
    59 // drawPixelTextが覆う大きさ(一番長い行 × 行数。最後の文字の後の隙間は数えない):HUDの箱を文字に合わせる
    60 // The size drawPixelText covers (the longest line × the lines, without the gap after the last character): fits the
    61 // HUD box to its text
    62 static Vec2 pixelTextSize(std::string_view text, float scale) {
    63 int column = 0, widest = 0, lines = 1;
    64 for (char c : text) {
    65 if (c == '\n') {
    66 ++lines;
    67 column = 0;
    68 continue;
    69 }
    70 widest = std::max(widest, ++column);
    71 }
    72 return Vec2{4.0f * static_cast<float>(widest) - 1.0f, 6.0f * static_cast<float>(lines) - 1.0f} * scale;
    73 }
    74  
    75 // 乱数(第26章でRngクラスになる) / random numbers (chapter 26 turns this into the Rng class)
    76 static float random01(std::uint32_t &state) {
    77 state = state * 1664525u + 1013904223u;
    78 return static_cast<float>(state >> 8) / 16777216.0f;
    79 }
    80  
    81 // 場面2の一枚:位置・速さ・回転・どのシートのどのコマか / one sprite of scene 2: position, velocity, spin, which
    82 // sheet and frame
    83 struct Mover {
    84 Vec2 position, velocity;
    85 float angle, spin;
    86 int kind; // 0 = 主人公(hero.png)、1 = コイン(objects.png) / 0 = hero (hero.png), 1 = coin (objects.png)
    87 float phase; // アニメーションのずれ / animation offset
    88 };
    89  
    90 static std::vector<Mover> makeMovers(int count, Vec2 area) {
    91 std::vector<Mover> movers;
    92 std::uint32_t seed = 25;
    93 for (int i = 0; i < count; ++i) {
    94 Mover m;
    95 m.position = {random01(seed) * area.x, random01(seed) * area.y};
    96 float a = 6.2831853f * random01(seed), speed = 40.0f + 120.0f * random01(seed);
    97 m.velocity = {speed * std::cos(a), speed * std::sin(a)};
    98 m.angle = 6.2831853f * random01(seed);
    99 m.spin = (random01(seed) - 0.5f) * 4.0f;
    100 // 交互に別のテクスチャ:並べ替えなしだと1枚ごとに描画コールが要る / alternate textures: without sorting every
    101 // sprite needs its own draw call
    102 m.kind = i % 2;
    103 m.phase = random01(seed);
    104 movers.push_back(m);
    105 }
    106 return movers;
    107 }
    108  
    109 int main() {
    110 Window window;
    111 if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 25")) return 1;
    112  
    113 // 二つのスプライトバッチ:頂点の送り方だけが違う(Uで切り替え) / two sprite batches that differ only in how
    114 // vertices are uploaded (U switches)
    115 std::optional<SpriteBatch> subDataBatch = SpriteBatch::create({.upload = SpriteUpload::SubData});
    116 std::optional<SpriteBatch> persistentBatch = SpriteBatch::create({.upload = SpriteUpload::Persistent});
    117 // ピクセルアートはGL_NEAREST。比較用にGL_LINEARでも読む / pixel art uses GL_NEAREST; also loaded with GL_LINEAR for
    118 // the comparison
    119 std::optional<SpriteSheet> hero = SpriteSheet::loadGrid("assets/sprites/hero.png", 16, 16, 1, 1);
    120 std::optional<SpriteSheet> heroLinear =
    121 SpriteSheet::loadGrid("assets/sprites/hero.png", 16, 16, 1, 1, TextureFilter::Linear);
    122 std::optional<SpriteSheet> objects = SpriteSheet::loadAtlas("assets/sprites/objects.atlas");
    123 std::optional<SpriteSheet> objectsLinear = SpriteSheet::loadAtlas("assets/sprites/objects.atlas", TextureFilter::Linear);
    124 std::optional<SpriteSheet> noPadLinear = SpriteSheet::loadAtlas("assets/sprites/objects_nopad.atlas", TextureFilter::Linear);
    125 std::optional<SpriteSheet> font = SpriteSheet::loadGrid("assets/sprites/pixfont.png", 4, 6);
    126 if (!subDataBatch || !persistentBatch || !hero || !heroLinear || !objects || !objectsLinear || !noPadLinear || !font)
    127 return 1;
    128  
    129 // 主人公のクリップ:コマの番号はhero.pngの並び(0〜1 待機、2〜5 歩き、6 ジャンプ)
    130 // The hero's clips: frame numbers follow hero.png (0-1 idle, 2-5 walk, 6 jump)
    131 hero->addClip({.name = "idle", .frames = {0, 0, 0, 0, 0, 0, 1}, .fps = 6.0f});
    132 hero->addClip({.name = "walk", .frames = {2, 3, 4, 5}, .fps = 10.0f});
    133 const AnimationClip *idleClip = hero->clip("idle");
    134 const AnimationClip *walkClip = hero->clip("walk");
    135 const AnimationClip *coinClip = objects->clip("coin_spin");
    136 const AnimationClip *slimeClip = objects->clip("slime_bounce");
    137 if (!idleClip || !walkClip || !coinClip || !slimeClip) return 1;
    138  
    139 // 場面1:320×180の仮想解像度(1280×720にちょうど4倍) / scene 1: a 320 × 180 virtual resolution (exactly 4× in 1280 × 720)
    140 PixelCanvas canvas(320, 180);
    141 Camera2D canvasCamera = Camera2D::screen(canvas.size());
    142 // 場面2・3:ウィンドウのピクセルそのまま / scenes 2 and 3: plain window pixels
    143 Camera2D screenCamera = Camera2D::screen({1280.0f, 720.0f});
    144 // 場面3のキャンバス比較用:48×48の小さなキャンバス / for scene 3's canvas comparison: a small 48 × 48 canvas
    145 PixelCanvas smallCanvas(48, 48);
    146 Camera2D smallCamera = Camera2D::screen(smallCanvas.size());
    147  
    148 int scene = 0, spriteCount = 10000;
    149 bool sortByTexture = true, persistent = false, paused = false;
    150 std::vector<Mover> movers = makeMovers(spriteCount, {1280.0f, 720.0f});
    151 window.onKey = [&](int key, int action, int /*mods*/) {
    152 if (action != GLFW_PRESS) return;
    153 if (key == GLFW_KEY_ESCAPE) window.close();
    154 if (key >= GLFW_KEY_1 && key <= GLFW_KEY_3) scene = key - GLFW_KEY_1;
    155 if (key == GLFW_KEY_T) sortByTexture = !sortByTexture;
    156 if (key == GLFW_KEY_U) persistent = !persistent;
    157 if (key == GLFW_KEY_P) paused = !paused;
    158 if (key == GLFW_KEY_EQUAL || key == GLFW_KEY_MINUS) {
    159 spriteCount = key == GLFW_KEY_EQUAL ? std::min(spriteCount * 2, 160000) : std::max(spriteCount / 2, 10);
    160 movers = makeMovers(spriteCount, {1280.0f, 720.0f});
    161 printf("sprites: %d\n", spriteCount);
    162 }
    163 };
    164  
    165 // 主人公(場面1) / the hero (scene 1)
    166 Animator heroAnim;
    167 heroAnim.play(walkClip);
    168 Vec2 heroPos = {60.0f, 144.0f}; // 足元 / feet
    169 float heroDir = 1.0f;
    170 Animator coinAnim, slimeAnim;
    171 coinAnim.play(coinClip);
    172 slimeAnim.play(slimeClip);
    173  
    174 float time = 0.0f;
    175 double lastTime = window.time();
    176 auto lastFrame = std::chrono::steady_clock::now();
    177 float frameMs = 0.0f;
    178 int frame = 0;
    179 while (!window.shouldClose()) {
    180 double now = window.time();
    181 float dt = static_cast<float>(now - lastTime);
    182 lastTime = now;
    183 window.pollEvents();
    184 // 本当の時間(CPU):1フレームにかかったミリ秒(なめらかに) / real time (CPU): milliseconds per frame (smoothed)
    185 auto wall = std::chrono::steady_clock::now();
    186 float ms = std::chrono::duration<float, std::milli>(wall - lastFrame).count();
    187 lastFrame = wall;
    188 frameMs = frame == 0 ? ms : 0.9f * frameMs + 0.1f * ms;
    189 if (paused) dt = 0.0f;
    190 time += dt;
    191  
    192 SpriteBatch &batch = persistent ? *persistentBatch : *subDataBatch;
    193 coinAnim.update(dt);
    194 slimeAnim.update(dt);
    195  
    196 if (scene == 0) {
    197 //------------------------------------------------------------------
    198 // 場面1:ピクセルアート。320×180のキャンバスに描いて、整数倍で画面へ
    199 // Scene 1: pixel art. Drawn into the 320 × 180 canvas, then scaled by a whole number onto the screen
    200 //------------------------------------------------------------------
    201 float input = 0.0f;
    202 if (window.keyDown(GLFW_KEY_LEFT) || window.keyDown(GLFW_KEY_A)) input -= 1.0f;
    203 if (window.keyDown(GLFW_KEY_RIGHT) || window.keyDown(GLFW_KEY_D)) input += 1.0f;
    204 if (input != 0.0f) heroDir = input;
    205 else if (heroPos.x > 290.0f) heroDir = -1.0f; // 自動で往復 / walks back and forth by itself
    206 else if (heroPos.x < 30.0f) heroDir = 1.0f;
    207 heroPos.x = std::clamp(heroPos.x + heroDir * 40.0f * dt, 8.0f, 312.0f);
    208 heroAnim.play(dt > 0.0f ? walkClip : idleClip);
    209 heroAnim.update(dt);
    210  
    211 canvas.begin(hexColor(0x8fd3ffff));
    212 batch.begin(canvasCamera.matrix(), SpriteSort::Layer);
    213 // 雲:ゆっくり流れる(奥、layer 0) / clouds drift slowly (at the back, layer 0)
    214 int cloud = objects->find("cloud");
    215 for (int i = 0; i < 3; ++i) {
    216 float x = std::fmod(40.0f + 130.0f * static_cast<float>(i) + 6.0f * time, 380.0f) - 40.0f;
    217 Sprite s = objects->sprite(cloud, {std::round(x), 18.0f + 14.0f * static_cast<float>(i % 2)});
    218 batch.draw(s);
    219 }
    220 // 地面:草の列と土の列。layer 1 / the ground: a row of grass and a row of dirt. Layer 1
    221 int grass = objects->find("grass"), dirt = objects->find("dirt"), brick = objects->find("brick");
    222 int crate = objects->find("crate"), stone = objects->find("stone");
    223 for (int x = 0; x < 20; ++x) {
    224 Sprite g = objects->sprite(grass, {16.0f * static_cast<float>(x), 144.0f});
    225 g.layer = 1.0f;
    226 batch.draw(g);
    227 for (float y : {160.0f, 176.0f}) {
    228 Sprite d = objects->sprite(dirt, {16.0f * static_cast<float>(x), y});
    229 d.layer = 1.0f;
    230 batch.draw(d);
    231 }
    232 }
    233 // レンガの足場と木箱 / a brick ledge and crates
    234 for (int x = 0; x < 4; ++x) {
    235 Sprite b = objects->sprite(brick, {176.0f + 16.0f * static_cast<float>(x), 96.0f});
    236 b.layer = 1.0f;
    237 batch.draw(b);
    238 }
    239 for (Vec2 p : {Vec2{24.0f, 128.0f}, Vec2{40.0f, 128.0f}, Vec2{32.0f, 112.0f}}) {
    240 Sprite c = objects->sprite(crate, p);
    241 c.layer = 1.0f;
    242 batch.draw(c);
    243 }
    244 for (int y = 0; y < 3; ++y) {
    245 Sprite s = objects->sprite(stone, {256.0f, 96.0f + 16.0f * static_cast<float>(y)});
    246 s.layer = 1.0f;
    247 batch.draw(s);
    248 }
    249 // 回る丸のこ(回転は中心の周り:origin = (0.5, 0.5)) / a spinning saw blade (rotates about its center:
    250 // origin = (0.5, 0.5))
    251 Sprite saw = objects->sprite(objects->find("saw"), {264.0f, 84.0f}, {0.5f, 0.5f});
    252 saw.rotation = 3.0f * time;
    253 saw.layer = 2.0f;
    254 batch.draw(saw);
    255 // コイン(アニメーション)と宝石・ハート・花 / coins (animated), a gem, a heart and flowers
    256 for (int i = 0; i < 4; ++i) {
    257 Sprite c = objects->sprite(coinAnim.frame(), {76.0f + 16.0f * static_cast<float>(i), 112.0f});
    258 c.layer = 2.0f;
    259 batch.draw(c);
    260 }
    261 Sprite gem = objects->sprite(objects->find("gem"), {150.0f, 118.0f + std::round(2.0f * std::sin(3.0f * time))});
    262 gem.layer = 2.0f;
    263 batch.draw(gem);
    264 Sprite heart = objects->sprite(objects->find("heart"), {170.0f, 120.0f});
    265 heart.layer = 2.0f;
    266 batch.draw(heart);
    267 for (float x : {96.0f, 152.0f, 228.0f, 300.0f}) {
    268 Sprite f = objects->sprite(objects->find("flower"), {x, 136.0f});
    269 f.layer = 2.0f;
    270 batch.draw(f);
    271 }
    272 // スライム2匹(同じクリップ、片方は左右反転) / two slimes (the same clip, one mirrored)
    273 for (int i = 0; i < 2; ++i) {
    274 Sprite s = objects->sprite(slimeAnim.frame(), {200.0f + 90.0f * static_cast<float>(i), 128.0f});
    275 s.flipX = i == 1;
    276 s.layer = 2.0f;
    277 batch.draw(s);
    278 }
    279 // 色を掛けた主人公:赤、半透明、影(黒) / tinted heroes: red, half transparent, a black silhouette
    280 const Vec4 tints[] = {hexColor(0xff7070ff), {1.0f, 1.0f, 1.0f, 0.45f}, hexColor(0x000000b0)};
    281 for (int i = 0; i < 3; ++i) {
    282 Sprite s = hero->sprite(0, {192.0f + 20.0f * static_cast<float>(i), 96.0f}, {0.5f, 1.0f});
    283 s.color = tints[i];
    284 s.layer = 2.0f;
    285 batch.draw(s);
    286 }
    287 // 主人公:足元(下の中心)が基準。左へ歩くときは左右反転 / the hero: the pivot is the feet (bottom center).
    288 // Mirrored when walking left
    289 Sprite h = hero->sprite(heroAnim.frame(), {std::round(heroPos.x), heroPos.y}, {0.5f, 1.0f});
    290 h.flipX = heroDir < 0.0f;
    291 h.layer = 3.0f;
    292 batch.draw(h);
    293 batch.end();
    294 SpriteStats stats = batch.stats();
    295 // HUD(同じキャンバス、別のbegin/end) / the HUD (same canvas, a separate begin/end)
    296 batch.begin(canvasCamera.matrix());
    297 char hud[128];
    298 snprintf(hud, sizeof hud, "SCENE 1: PIXEL ART 320X180 X4\nSPRITES %d DRAW CALLS %d", stats.sprites, stats.drawCalls);
    299 Vec2 hudSize = pixelTextSize(hud, 1.0f);
    300 batch.drawRect({2.0f, 2.0f, hudSize.x + 4.0f, hudSize.y + 4.0f}, hexColor(0x1b172699)); // 2ピクセルの余白 / 2 px margin
    301 drawPixelText(batch, *font, hud, {4.0f, 4.0f}, 1.0f, kWhite);
    302 batch.end();
    303 canvas.present(window.width(), window.height());
    304 } else if (scene == 1) {
    305 //------------------------------------------------------------------
    306 // 場面2:たくさんのスプライトを一つのバッチで / Scene 2: many sprites in one batch
    307 //------------------------------------------------------------------
    308 for (Mover &m : movers) {
    309 m.position += m.velocity * dt;
    310 if (m.position.x < 0.0f || m.position.x > 1280.0f) m.velocity.x = -m.velocity.x;
    311 if (m.position.y < 0.0f || m.position.y > 720.0f) m.velocity.y = -m.velocity.y;
    312 m.angle += m.spin * dt;
    313 }
    314 Framebuffer::bindDefault(window.width(), window.height());
    315 glClearColor(0.07f, 0.08f, 0.13f, 1.0f);
    316 glClear(GL_COLOR_BUFFER_BIT);
    317 auto start = std::chrono::steady_clock::now();
    318 batch.begin(screenCamera.matrix(), sortByTexture ? SpriteSort::Texture : SpriteSort::None);
    319 for (const Mover &m : movers) {
    320 // 主人公は歩き、コインは回る。コマはそれぞれの時間のずれで / heroes walk, coins spin, each with its own offset
    321 int heroFrame = 2 + static_cast<int>((time + m.phase) * 10.0f) % 4;
    322 int coinFrame = coinClip->frames[static_cast<size_t>((time + m.phase) * 8.0f) % 4];
    323 Sprite s = m.kind == 0 ? hero->sprite(heroFrame, m.position, {0.5f, 0.5f}, 2.0f)
    324 : objects->sprite(coinFrame, m.position, {0.5f, 0.5f}, 2.0f);
    325 s.rotation = m.angle;
    326 batch.draw(s);
    327 }
    328 batch.end();
    329 float batchMs = std::chrono::duration<float, std::milli>(std::chrono::steady_clock::now() - start).count();
    330 SpriteStats stats = batch.stats();
    331 batch.begin(screenCamera.matrix());
    332 char hud[256];
    333 snprintf(hud, sizeof hud,
    334 "SCENE 2: %d SPRITES IN ONE BATCH\nDRAW CALLS %d SORT %s (T) UPLOAD %s (U)\n"
    335 "BATCH %.1f MS FRAME %.1f MS (CPU)",
    336 stats.sprites, stats.drawCalls, sortByTexture ? "BY TEXTURE" : "NONE",
    337 persistent ? "PERSISTENT MAP" : "SUBDATA", static_cast<double>(batchMs), static_cast<double>(frameMs));
    338 Vec2 hudSize = pixelTextSize(hud, 4.0f);
    339 batch.drawRect({8.0f, 8.0f, hudSize.x + 16.0f, hudSize.y + 16.0f}, hexColor(0x000000c0)); // 余白8 / 8 px margin
    340 drawPixelText(batch, *font, hud, {16.0f, 16.0f}, 4.0f, hexColor(0xffe08aff));
    341 batch.end();
    342 if (frame % 60 == 2)
    343 printf("scene 2: %d sprites, %d draw calls (%s, %s), batch %.1f ms\n", stats.sprites, stats.drawCalls,
    344 sortByTexture ? "by texture" : "unsorted", persistent ? "persistent" : "subdata",
    345 static_cast<double>(batchMs));
    346 } else {
    347 //------------------------------------------------------------------
    348 // 場面3:フィルタリング:GL_NEAREST ⇔ GL_LINEAR、整数倍 ⇔ 半端な倍率と回転、直接 ⇔ キャンバス、隙間 ⇔ にじみ
    349 // Scene 3: filtering: GL_NEAREST ⇔ GL_LINEAR, whole ⇔ fractional scale and rotation, direct ⇔ canvas,
    350 // gaps ⇔ bleeding
    351 //------------------------------------------------------------------
    352 heroAnim.play(walkClip);
    353 heroAnim.update(dt);
    354 float angle = 0.35f * std::sin(0.8f * time);
    355 // 小さなキャンバスに回る主人公と丸のこ(48×48の本物のピクセル) / a turning hero and saw in the small canvas
    356 // (real 48 × 48 pixels)
    357 smallCanvas.begin(hexColor(0x2a3350ff));
    358 batch.begin(smallCamera.matrix());
    359 Sprite small = hero->sprite(heroAnim.frame(), {24.0f, 22.0f}, {0.5f, 0.5f}, 2.0f);
    360 small.rotation = angle;
    361 batch.draw(small);
    362 Sprite smallSaw = objects->sprite(objects->find("saw"), {38.0f, 38.0f}, {0.5f, 0.5f});
    363 smallSaw.rotation = 2.0f * time;
    364 batch.draw(smallSaw);
    365 batch.end();
    366  
    367 Framebuffer::bindDefault(window.width(), window.height());
    368 glClearColor(0.10f, 0.11f, 0.16f, 1.0f);
    369 glClear(GL_COLOR_BUFFER_BIT);
    370 batch.begin(screenCamera.matrix());
    371 const Vec4 label = hexColor(0xffe08aff), panel = hexColor(0x2a3350ff);
    372 // 上の段:×12(整数)と×7.5で回転、それぞれGL_NEARESTとGL_LINEAR / top row: ×12 (whole) and ×7.5 rotated, each
    373 // with GL_NEAREST and GL_LINEAR
    374 const char *names[] = {"NEAREST X12", "LINEAR X12", "NEAREST X7.5 TURNED", "LINEAR X7.5 TURNED"};
    375 for (int i = 0; i < 4; ++i) {
    376 float x0 = 20.0f + 315.0f * static_cast<float>(i);
    377 batch.drawRect({x0, 40.0f, 300.0f, 280.0f}, panel);
    378 drawPixelText(batch, *font, names[i], {x0 + 8.0f, 48.0f}, 3.0f, label);
    379 const SpriteSheet &sheet = i % 2 == 0 ? *hero : *heroLinear;
    380 Sprite s = sheet.sprite(0, {x0 + 150.0f, 190.0f}, {0.5f, 0.5f}, i < 2 ? 12.0f : 7.5f);
    381 if (i >= 2) s.rotation = angle;
    382 batch.draw(s);
    383 }
    384 // 中の段:直接(画面の細かいピクセルで回る) ⇔ キャンバス(48×48を6倍) / middle row: direct (turns with the
    385 // screen's fine pixels) ⇔ canvas (48 × 48 enlarged 6×)
    386 batch.drawRect({20.0f, 340.0f, 300.0f, 330.0f}, panel);
    387 drawPixelText(batch, *font, "DIRECT X6", {28.0f, 348.0f}, 3.0f, label);
    388 Sprite direct = hero->sprite(heroAnim.frame(), {20.0f + 6.0f * 24.0f + 6.0f, 380.0f + 6.0f * 22.0f}, {0.5f, 0.5f}, 12.0f);
    389 direct.rotation = angle;
    390 batch.draw(direct);
    391 Sprite directSaw = objects->sprite(objects->find("saw"), {26.0f + 6.0f * 38.0f, 380.0f + 6.0f * 38.0f}, {0.5f, 0.5f}, 6.0f);
    392 directSaw.rotation = 2.0f * time;
    393 batch.draw(directSaw);
    394 batch.drawRect({335.0f, 340.0f, 300.0f, 330.0f}, panel);
    395 drawPixelText(batch, *font, "CANVAS X6", {343.0f, 348.0f}, 3.0f, label);
    396 // FBOの色テクスチャは下の行がv = 0(GLの約束):y下向きの2DではflipYで描く
    397 // An FBO's color texture has its bottom row at v = 0 (the GL convention): draw it with flipY in y-down 2D
    398 Sprite canvasSprite = {.texture = &smallCanvas.framebuffer().color(), .position = {341.0f, 380.0f},
    399 .size = {288.0f, 288.0f}, .flipY = true};
    400 batch.draw(canvasSprite);
    401 // 右下:タイルをGL_LINEARで×3.3に。隙間(縁の複製)あり ⇔ なし / bottom right: tiles at ×3.3 with GL_LINEAR, with
    402 // gaps (extruded edges) ⇔ without
    403 for (int k = 0; k < 2; ++k) {
    404 float y0 = 340.0f + 170.0f * static_cast<float>(k);
    405 batch.drawRect({650.0f, y0, 610.0f, 160.0f}, panel);
    406 drawPixelText(batch, *font, k == 0 ? "LINEAR X3.3, 1 PX EXTRUDED GAPS" : "LINEAR X3.3, NO GAPS: BLEEDING",
    407 {658.0f, y0 + 8.0f}, 3.0f, label);
    408 const SpriteSheet &sheet = k == 0 ? *objectsLinear : *noPadLinear;
    409 const char *tiles[] = {"grass", "dirt", "brick", "stone", "crate"};
    410 for (int t = 0; t < 10; ++t) {
    411 int index = sheet.find(tiles[t / 2]);
    412 batch.draw(sheet.sprite(index, {660.0f + 52.8f * static_cast<float>(t) + 0.3f, y0 + 45.0f + 0.4f}, {0.0f, 0.0f}, 3.3f));
    413 batch.draw(sheet.sprite(index, {660.0f + 52.8f * static_cast<float>(t) + 0.3f, y0 + 45.0f + 52.8f + 0.4f}, {0.0f, 0.0f}, 3.3f));
    414 }
    415 }
    416 batch.end();
    417 }
    418  
    419 if (frame++ % 120 == 1) {
    420 char title[128];
    421 snprintf(title, sizeof title, "OpenGL Tutorial - Chapter 25 - scene %d - %d draw calls", scene + 1, batch.stats().drawCalls);
    422 window.setTitle(title);
    423 }
    424 window.swapBuffers();
    425 }
    426 return 0;
    427 }

ファイル: /dev/null | b/engine/CMakeLists.txt

前新
@@ -0,0 +1,49 @@
    1 # エンジン:どのゲームでも使うクラスをまとめた静的ライブラリ
    2 # The engine: a static library with the classes every game uses
    3 #
    4 # engine/include/engine/*.hh 公開ヘッダー(#include "engine/sprite_batch.hh") / public headers
    5 # engine/src/*.cc 実装 / the implementation
    6 # engine/shaders/* エンジンのシェーダー(実行時にプロジェクトのルートから読む) / the engine's shaders
    7 # (loaded at run time, relative to the project root)
    8  
    9 # stb_image:実装は src/stb_image_impl.cc だけ。他人のコードなので警告フラグなしの別ライブラリにする
    10 # stb_image: the implementation lives in src/stb_image_impl.cc only. It is someone else's code,
    11 # so it is a separate library built without our warning flags
    12 add_library(stb_image STATIC src/stb_image_impl.cc)
    13 target_include_directories(stb_image PUBLIC ${PROJECT_SOURCE_DIR}/external/stb)
    14  
    15 add_library(engine STATIC
    16 # 第1〜24章 / chapters 1-24
    17 src/window.cc
    18 src/gl_debug.cc
    19 src/buffer.cc
    20 src/mesh.cc
    21 src/file_util.cc
    22 src/shader.cc
    23 src/texture.cc
    24 src/shapes.cc
    25 src/camera.cc
    26 src/material.cc
    27 src/lights.cc
    28 src/json.cc
    29 src/gltf.cc
    30 src/model.cc
    31 src/framebuffer.cc
    32 src/cubemap.cc
    33 src/gpu_timer.cc
    34 src/tangents.cc
    35 src/ibl.cc
    36 src/pbr_material.cc
    37 src/renderer3d.cc
    38 # 第25章:2D / chapter 25: 2D
    39 src/camera2d.cc
    40 src/pixel_canvas.cc
    41 src/sprite_batch.cc
    42 src/sprite_sheet.cc
    43 src/animation.cc)
    44  
    45 # PUBLIC:エンジンを使う側(ゲーム)にも include/、linalg.hh、GLAD、GLFWが見える
    46 # PUBLIC: whoever links the engine (the games) also sees include/, linalg.hh, GLAD and GLFW
    47 target_include_directories(engine PUBLIC include ${PROJECT_SOURCE_DIR}/external/linalg)
    48 target_link_libraries(engine PRIVATE stb_image PUBLIC glad glfw)
    49 enable_warnings(engine)

ファイル: /dev/null | b/engine/include/engine/animation.hh

前新
@@ -0,0 +1,43 @@
    1 // コマ送りのアニメーション(第25章) / frame-by-frame animation (chapter 25)
    2 #pragma once
    3  
    4 #include <string>
    5 #include <vector>
    6  
    7 // 一つの動き(歩く・待つ・回る…):スプライトシートのコマ番号の列と速さ
    8 // One motion (walk, idle, spin...): a list of sprite-sheet frame indices and a speed
    9 struct AnimationClip {
    10 std::string name;
    11 std::vector<int> frames; // SpriteSheetの番号 / SpriteSheet indices
    12 float fps = 10.0f; // 1秒に何コマ / frames per second
    13 bool loop = true; // falseなら最後のコマで止まる / false: stops on the last frame
    14  
    15 float duration() const { return fps > 0.0f ? static_cast<float>(frames.size()) / fps : 0.0f; }
    16 };
    17  
    18 // クリップを再生する(キャラクター一人に一つ)。クリップは指すだけ(SpriteSheetが持つ)
    19 // Plays a clip (one per character). It only points at the clip (the SpriteSheet owns it)
    20 class Animator {
    21 public:
    22 // 再生する。同じクリップならそのまま続ける(restart = trueで最初から)。nullptrで止める
    23 // Plays a clip. The same clip keeps running (restart = true starts it over). nullptr stops
    24 void play(const AnimationClip *clip, bool restart = false);
    25 // 時間を進める(固定ステップの更新から呼ぶ) / advances time (call it from the fixed-step update)
    26 void update(float dt);
    27  
    28 // 今のコマ:スプライトシートの番号(クリップがなければ-1) / the current frame: a sprite-sheet index (-1 without
    29 // a clip)
    30 int frame() const;
    31 // クリップの中で何番目のコマか / which frame of the clip
    32 int frameIndex() const;
    33 // 繰り返さないクリップが最後まで行ったか / has a non-looping clip reached its end?
    34 bool finished() const;
    35 const AnimationClip *clip() const { return current; }
    36 float time() const { return elapsed; }
    37  
    38 float speed = 1.0f; // 再生速度の倍率(負なら逆再生) / playback speed multiplier (negative plays backwards)
    39  
    40 private:
    41 const AnimationClip *current = nullptr;
    42 float elapsed = 0.0f;
    43 };

ファイル: a/src/buffer.hh | b/engine/include/engine/buffer.hh

類似度:100% / 名前の変更元:src/buffer.hh / 名前の変更先:engine/include/engine/buffer.hh

ファイル: a/src/camera.hh | b/engine/include/engine/camera.hh

類似度:100% / 名前の変更元:src/camera.hh / 名前の変更先:engine/include/engine/camera.hh

ファイル: /dev/null | b/engine/include/engine/camera2d.hh

前新
@@ -0,0 +1,65 @@
    1 // 2Dのカメラ(第25章):仮想解像度の正射影と、ウィンドウへの拡大(レターボックス)
    2 // The 2D camera (chapter 25): an orthographic projection for a virtual resolution, and scaling it to the window
    3 // (letterboxing)
    4 #pragma once
    5  
    6 #include "engine/mathx.hh"
    7 #include "engine/rect.hh"
    8  
    9 // 2Dの座標系(エンジン全体の約束):
    10 // * 単位は仮想ピクセル。y軸は下向き、原点は左上(画像・タイルマップ・文字の並びと同じ)。
    11 // * 正の回転は画面上で時計回り。
    12 // * 画像の一番上の行がv = 0(テクスチャは上下反転せずに読む)。
    13 // The 2D coordinate system (an engine-wide convention):
    14 // * Units are virtual pixels. The y axis points down, the origin is at the top left (like images, tile maps and
    15 // lines of text).
    16 // * A positive rotation is clockwise on screen.
    17 // * The top row of an image is v = 0 (textures are loaded without flipping).
    18 struct Camera2D {
    19 // 拡大率1のときに見える広さ(仮想解像度) / what is visible at zoom 1 (the virtual resolution)
    20 Vec2 viewSize = {320.0f, 180.0f};
    21 // 画面の真ん中に来るワールドの点 / the world point shown in the middle of the screen
    22 Vec2 centre = {160.0f, 90.0f};
    23 float zoom = 1.0f; // 2 = 2倍に大きく / 2 = twice as large
    24 float rotation = 0.0f; // ラジアン、画面上で時計回り / radians, clockwise on screen
    25 // 中心を(今の拡大率での)画面のピクセルにそろえる:スクロールが画面のピクセル単位になり、絵はビューのピクセルの
    26 // 格子に揃ったまま動く / Snap the center to whole screen pixels (at the current zoom): scrolling moves in whole view
    27 // pixels, so the art stays on the view's pixel grid
    28 bool pixelSnap = false;
    29  
    30 // ワールド → クリップ座標(SpriteBatch::beginに渡す) / world → clip space (pass it to SpriteBatch::begin)
    31 Mat4 matrix() const;
    32 // 仮想画面の点(0〜viewSize、左上が原点) → ワールド、とその逆 / a virtual-screen point (0..viewSize, origin top
    33 // left) → world, and back
    34 Vec2 toWorld(Vec2 viewPoint) const;
    35 Vec2 toView(Vec2 worldPoint) const;
    36 // 見えている範囲を囲むワールドの長方形(回転していれば少し広い) / the world rectangle around what is visible
    37 // (a little larger when rotated)
    38 Rect visibleRect() const;
    39  
    40 // ワールド座標 = 仮想画面のピクセル(HUD・文字・メニュー用) / world coordinates = virtual-screen pixels (for HUDs,
    41 // text and menus)
    42 static Camera2D screen(Vec2 size) { return {.viewSize = size, .centre = 0.5f * size}; }
    43 };
    44  
    45 // ウィンドウの中の描く場所(glViewportの値)。x, yはGLの約束どおり左下から
    46 // Where to draw inside the window (the glViewport values). x and y count from the bottom left, as GL does
    47 struct Viewport {
    48 int x = 0, y = 0, width = 0, height = 0;
    49 int top = 0; // ウィンドウの上端からの距離(マウスの変換用) / distance from the window's top (for the mouse)
    50 float scale = 1.0f; // 仮想ピクセル1つが画面の何ピクセルか / screen pixels per virtual pixel
    51  
    52 void apply() const; // glViewport
    53 // ウィンドウの座標(GLFWのマウス、左上が原点) → 仮想画面の座標 / window coordinates (the GLFW mouse, origin top
    54 // left) → virtual-screen coordinates
    55 Vec2 toView(Vec2 windowPoint) const {
    56 return {(windowPoint.x - static_cast<float>(x)) / scale, (windowPoint.y - static_cast<float>(top)) / scale};
    57 }
    58 };
    59  
    60 // 仮想解像度viewSizeを縦横比を保ったまま一番大きくウィンドウに入れる。余りは上下か左右の帯(レターボックス)。
    61 // integerScaleなら倍率を整数に切り捨てる(ピクセルアートのピクセルがみな同じ大きさになる)
    62 // Fits the virtual resolution viewSize into the window as large as possible without changing its aspect ratio. What
    63 // is left becomes bars at the top and bottom or the sides (letterboxing). integerScale rounds the scale down to a
    64 // whole number (every pixel-art pixel gets the same size)
    65 Viewport letterbox(int windowWidth, int windowHeight, Vec2 viewSize, bool integerScale);

ファイル: a/src/cubemap.hh | b/engine/include/engine/cubemap.hh

前新
@@ -30,7 +30,7 @@ public:
30 // Loads six image files (order +X, -X, +Y, -Y, +Z, -Z). No vertical flip: cube-map faces start at the top row. 30 // Loads six image files (order +X, -X, +Y, -Y, +Z, -Z). No vertical flip: cube-map faces start at the top row.
31 // All must be squares of the same size. Builds mipmaps (for blurry reflections). On failure prints the error 31 // All must be squares of the same size. Builds mipmaps (for blurry reflections). On failure prints the error
32 // and returns std::nullopt. 32 // and returns std::nullopt.
33 // srgb = true:色の画像なのでGL_SRGB8_ALPHA8にする(第21章。空はtrue) / srgb = true: a colour image, stored as 33 // srgb = true:色の画像なのでGL_SRGB8_ALPHA8にする(第21章。空はtrue) / srgb = true: a color image, stored as
34 // GL_SRGB8_ALPHA8 (chapter 21; true for skies) 34 // GL_SRGB8_ALPHA8 (chapter 21; true for skies)
35 static std::optional<Cubemap> load(const std::array<std::string, 6> &paths, bool srgb = false); 35 static std::optional<Cubemap> load(const std::array<std::string, 6> &paths, bool srgb = false);
36 // dir/px.png, dir/nx.png … を読む / loads dir/px.png, dir/nx.png, ... 36 // dir/px.png, dir/nx.png … を読む / loads dir/px.png, dir/nx.png, ...

ファイル: a/src/file_util.hh | b/engine/include/engine/file_util.hh

類似度:100% / 名前の変更元:src/file_util.hh / 名前の変更先:engine/include/engine/file_util.hh

ファイル: a/src/framebuffer.hh | b/engine/include/engine/framebuffer.hh

前新
@@ -1,7 +1,7 @@
1 // フレームバッファ:画面の代わりにテクスチャへ描く / framebuffers: draw into a texture instead of the screen 1 // フレームバッファ:画面の代わりにテクスチャへ描く / framebuffers: draw into a texture instead of the screen
2 #pragma once 2 #pragma once
3   3  
4 #include "texture.hh" 4 #include "engine/texture.hh"
5   5  
6 #include <glad/glad.h> 6 #include <glad/glad.h>
7   7  
@@ -11,35 +11,45 @@ constexpr int kMaxColorAttachments = 4; // GLは最低8を保証する / GL guar
11   11  
12 // フレームバッファに何を付けるか / what to attach to a framebuffer 12 // フレームバッファに何を付けるか / what to attach to a framebuffer
13 struct FramebufferSpec { 13 struct FramebufferSpec {
14 // 色のテクスチャの形式(0 = 色なし)。HDRではGL_RGBA16F(第21章) 14 // 色のテクスチャの形式(0 = 色なし:描く色・読む色はGL_NONE)。HDRではGL_RGBA16F(第21章)。
15 // The colour texture's format (0 = no colour). GL_RGBA16F for HDR (chapter 21) 15 // テクスチャはミップマップなし、CLAMP_TO_EDGE、GL_LINEAR
    16 // The color texture's format (0 = no color: draw and read buffer GL_NONE). GL_RGBA16F for HDR (chapter 21).
    17 // The textures have no mipmaps, CLAMP_TO_EDGE, GL_LINEAR
16 GLenum colorFormat = GL_RGBA8; 18 GLenum colorFormat = GL_RGBA8;
17 // 色の付け先の数(MRT、第21章):GL_COLOR_ATTACHMENT0〜。全部colorFormat。シェーダーは 19 // 色の付け先の数(MRT、第21章):GL_COLOR_ATTACHMENT0〜。全部colorFormat。シェーダーは
18 // layout(location = i) out … でi番目に書く(最大kMaxColorAttachments) 20 // layout(location = i) out … でi番目に書く(最大kMaxColorAttachments)
19 // The number of colour attachments (MRT, chapter 21): GL_COLOR_ATTACHMENT0... All use colorFormat. A shader writes 21 // The number of color attachments (MRT, chapter 21): GL_COLOR_ATTACHMENT0... All use colorFormat. A shader writes
20 // the i-th one with layout(location = i) out ... (at most kMaxColorAttachments) 22 // the i-th one with layout(location = i) out ... (at most kMaxColorAttachments)
21 int colorCount = 1; 23 int colorCount = 1;
22 // 深度・ステンシルのレンダーバッファの形式(0 = なし)。サンプラーで読まないのでテクスチャでなくて良い 24 // 深度・ステンシルの形式(0 = なし)。普通はレンダーバッファ(サンプラーで読まないものはテクスチャでなくて良い)、
23 // The depth-stencil renderbuffer's format (0 = none). It is never sampled, so it need not be a texture 25 // depthTexture = trueならテクスチャ。GL_DEPTH24_STENCIL8・GL_DEPTH32F_STENCIL8は深度とステンシルの両方に、
    26 // 深度だけの形式(GL_DEPTH_COMPONENT24など)は深度にだけ付く
    27 // The depth-stencil format (0 = none). Normally a renderbuffer (what is never sampled need not be a texture); a
    28 // texture with depthTexture = true. GL_DEPTH24_STENCIL8 / GL_DEPTH32F_STENCIL8 attach as depth and stencil,
    29 // depth-only formats (GL_DEPTH_COMPONENT24 etc.) as depth only
24 GLenum depthStencilFormat = GL_DEPTH24_STENCIL8; 30 GLenum depthStencilFormat = GL_DEPTH24_STENCIL8;
25 // マルチサンプル(MSAA、第20章):1ピクセルあたりのサンプル数。0 = 普通のフレームバッファ(色はテクスチャ)。 31 // マルチサンプル(MSAA、第20章):1ピクセルあたりのサンプル数。0 = 普通のフレームバッファ(色はテクスチャ)。
26 // 1以上なら色も深度もマルチサンプルのレンダーバッファになり、サンプラーでは読めない:blitToで普通の 32 // 1以上なら色も深度もマルチサンプルのレンダーバッファになり、サンプラーでは読めない:blitToで普通の
27 // フレームバッファに解決(resolve)してから使う。ドライバーは要求以上の数を選ぶことがある(samples()で確かめる)。 33 // フレームバッファに解決(resolve)してから使う。ドライバーは要求以上の数を選ぶことがある(samples()で確かめる)。
28 // Multisampling (MSAA, chapter 20): samples per pixel. 0 = an ordinary framebuffer (the colour is a texture). 34 // Multisampling (MSAA, chapter 20): samples per pixel. 0 = an ordinary framebuffer (the color is a texture).
29 // 1 or more makes both colour and depth multisampled renderbuffers, which cannot be sampled: resolve them into 35 // 1 or more makes both color and depth multisampled renderbuffers, which cannot be sampled: resolve them into
30 // an ordinary framebuffer with blitTo first. The driver may pick more samples than requested (check samples()). 36 // an ordinary framebuffer with blitTo first. The driver may pick more samples than requested (check samples()).
31 int samples = 0; 37 int samples = 0;
32 // 深度をレンダーバッファではなくテクスチャにする(影の地図、第23章)。depthStencilFormatは 38 // 深度をレンダーバッファではなくテクスチャにする(影の地図、第23章)。depthStencilFormatは
33 // GL_DEPTH_COMPONENT24 / 32Fなど。比較モードon、GL_LINEAR、外側はGL_CLAMP_TO_BORDERで1。depth()で読む 39 // GL_DEPTH_COMPONENT24 / 32Fなど。比較モードon、GL_LINEAR、外側はGL_CLAMP_TO_BORDERで1。depth()で読む。
    40 // マルチサンプルとは一緒に使えない
34 // Make the depth a texture instead of a renderbuffer (shadow maps, chapter 23). depthStencilFormat is 41 // Make the depth a texture instead of a renderbuffer (shadow maps, chapter 23). depthStencilFormat is
35 // GL_DEPTH_COMPONENT24 / 32F etc. Comparison mode on, GL_LINEAR, GL_CLAMP_TO_BORDER with 1 outside. Read it with depth() 42 // GL_DEPTH_COMPONENT24 / 32F etc. Comparison mode on, GL_LINEAR, GL_CLAMP_TO_BORDER with 1 outside. Read it with
    43 // depth(). Not supported together with multisampling
36 bool depthTexture = false; 44 bool depthTexture = false;
37 }; 45 };
38   46  
39 // フレームバッファオブジェクト(FBO):色のテクスチャ+深度・ステンシルのレンダーバッファ(RAII、コピー不可・移動可)。DSAで作る。 47 // フレームバッファオブジェクト(FBO):色のテクスチャ(MRTなら複数)+深度・ステンシル(レンダーバッファ、
40 // マルチサンプル(spec.samples > 0)なら色もレンダーバッファ。 48 // depthTextureならテクスチャ)。RAII、コピー不可・移動可。DSAで作る。マルチサンプル(spec.samples > 0)なら色も
41 // A framebuffer object (FBO): a colour texture + a depth-stencil renderbuffer (RAII, non-copyable, movable), built with DSA. 49 // レンダーバッファ。
42 // When multisampled (spec.samples > 0) the colour is a renderbuffer too. 50 // A framebuffer object (FBO): color textures (several with MRT) + a depth-stencil attachment (a renderbuffer, or a
    51 // texture with depthTexture). RAII, non-copyable, movable, built with DSA. When multisampled (spec.samples > 0) the
    52 // color is a renderbuffer too.
43 class Framebuffer { 53 class Framebuffer {
44 public: 54 public:
45 Framebuffer() = default; 55 Framebuffer() = default;
@@ -63,7 +73,7 @@ public:
63   73  
64 // 描いた結果。シェーダーでサンプリングできる(マルチサンプルなら空:id() == 0) 74 // 描いた結果。シェーダーでサンプリングできる(マルチサンプルなら空:id() == 0)
65 // The result; can be sampled in a shader (empty for a multisampled framebuffer: id() == 0) 75 // The result; can be sampled in a shader (empty for a multisampled framebuffer: id() == 0)
66 // index = 何番目の色の付け先か(MRT) / index = which colour attachment (MRT) 76 // index = 何番目の色の付け先か(MRT) / index = which color attachment (MRT)
67 const Texture2D &color(int index = 0) const { return colorTextures[static_cast<size_t>(index)]; } 77 const Texture2D &color(int index = 0) const { return colorTextures[static_cast<size_t>(index)]; }
68 Texture2D &color(int index = 0) { return colorTextures[static_cast<size_t>(index)]; } 78 Texture2D &color(int index = 0) { return colorTextures[static_cast<size_t>(index)]; }
69 int colorCount() const { return spec.colorFormat != 0 ? spec.colorCount : 0; } 79 int colorCount() const { return spec.colorFormat != 0 ? spec.colorCount : 0; }
@@ -79,8 +89,8 @@ public:
79 // the same size is allowed from a multisampled source). mask = GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT... (depth 89 // the same size is allowed from a multisampled source). mask = GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT... (depth
80 // only with GL_NEAREST) 90 // only with GL_NEAREST)
81 // 色の付け先が複数あれば、一つずつ同じ番号の付け先へコピーする(ブリットは読む色を一つしか選べない) 91 // 色の付け先が複数あれば、一つずつ同じ番号の付け先へコピーする(ブリットは読む色を一つしか選べない)
82 // With several colour attachments each one is copied into the attachment with the same number (a blit can read 92 // With several color attachments each one is copied into the attachment with the same number (a blit can read
83 // only one colour buffer at a time) 93 // only one color buffer at a time)
84 void blitTo(const Framebuffer &target, GLbitfield mask = GL_COLOR_BUFFER_BIT, GLenum filter = GL_NEAREST) const; 94 void blitTo(const Framebuffer &target, GLbitfield mask = GL_COLOR_BUFFER_BIT, GLenum filter = GL_NEAREST) const;
85   95  
86 GLuint id() const { return fbo; } 96 GLuint id() const { return fbo; }
@@ -97,7 +107,7 @@ private:
97   107  
98 GLuint fbo = 0; 108 GLuint fbo = 0;
99 GLuint depthStencil = 0; // レンダーバッファ / renderbuffer 109 GLuint depthStencil = 0; // レンダーバッファ / renderbuffer
100 // マルチサンプルの色のレンダーバッファ(第20章) / multisampled colour renderbuffers (chapter 20) 110 // マルチサンプルの色のレンダーバッファ(第20章) / multisampled color renderbuffers (chapter 20)
101 std::array<GLuint, kMaxColorAttachments> colorSamples = {}; 111 std::array<GLuint, kMaxColorAttachments> colorSamples = {};
102 std::array<Texture2D, kMaxColorAttachments> colorTextures; 112 std::array<Texture2D, kMaxColorAttachments> colorTextures;
103 Texture2D depthTex; // 第23章 / chapter 23 113 Texture2D depthTex; // 第23章 / chapter 23
@@ -106,10 +116,10 @@ private:
106 FramebufferSpec spec; 116 FramebufferSpec spec;
107 }; 117 };
108   118  
109 // 画面全体を覆う三角形(ポストプロセス用)。頂点はシェーダーがgl_VertexIDから作る(shaders/post.vert)。 119 // 画面全体を覆う三角形(ポストプロセス用)。頂点はシェーダーがgl_VertexIDから作る(engine/shaders/post.vert)。
110 // 頂点属性のない空のVAOを持つだけ:コアプロファイルでは描くときにVAOが必ず要る(RAII、コピー不可・移動可)。 120 // 頂点属性のない空のVAOを持つだけ:コアプロファイルでは描くときにVAOが必ず要る(RAII、コピー不可・移動可)。
111 // A triangle covering the whole screen (for post-processing). The shader makes the vertices from gl_VertexID 121 // A triangle covering the whole screen (for post-processing). The shader makes the vertices from gl_VertexID
112 // (shaders/post.vert). It only owns an empty VAO without attributes: the core profile always needs a VAO bound 122 // (engine/shaders/post.vert). It only owns an empty VAO without attributes: the core profile always needs a VAO bound
113 // to draw (RAII, non-copyable, movable). 123 // to draw (RAII, non-copyable, movable).
114 class FullscreenTriangle { 124 class FullscreenTriangle {
115 public: 125 public:

ファイル: a/src/gl_debug.hh | b/engine/include/engine/gl_debug.hh

類似度:100% / 名前の変更元:src/gl_debug.hh / 名前の変更先:engine/include/engine/gl_debug.hh

ファイル: a/src/gltf.hh | b/engine/include/engine/gltf.hh

前新
@@ -9,7 +9,7 @@
9 // skins, animations, morph targets (skipped), Draco / meshopt compression 9 // skins, animations, morph targets (skipped), Draco / meshopt compression
10 #pragma once 10 #pragma once
11   11  
12 #include "mathx.hh" 12 #include "engine/mathx.hh"
13   13  
14 #include <cstddef> 14 #include <cstddef>
15 #include <cstdint> 15 #include <cstdint>

ファイル: a/src/gpu_timer.hh | b/engine/include/engine/gpu_timer.hh

類似度:100% / 名前の変更元:src/gpu_timer.hh / 名前の変更先:engine/include/engine/gpu_timer.hh

ファイル: a/src/ibl.hh | b/engine/include/engine/ibl.hh

前新
@@ -3,9 +3,9 @@
3 // at start-up 3 // at start-up
4 #pragma once 4 #pragma once
5   5  
6 #include "cubemap.hh" 6 #include "engine/cubemap.hh"
7 #include "framebuffer.hh" 7 #include "engine/framebuffer.hh"
8 #include "shader.hh" 8 #include "engine/shader.hh"
9   9  
10 #include <optional> 10 #include <optional>
11   11  
@@ -42,5 +42,5 @@ public:
42 private: 42 private:
43 Cubemap irradianceMap; 43 Cubemap irradianceMap;
44 Cubemap prefilteredMap; 44 Cubemap prefilteredMap;
45 Framebuffer brdfFbo; // 色のテクスチャがLUT(GL_RG16F) / its colour texture is the LUT (GL_RG16F) 45 Framebuffer brdfFbo; // 色のテクスチャがLUT(GL_RG16F) / its color texture is the LUT (GL_RG16F)
46 }; 46 };

ファイル: a/src/json.hh | b/engine/include/engine/json.hh

類似度:100% / 名前の変更元:src/json.hh / 名前の変更先:engine/include/engine/json.hh

ファイル: a/src/lights.hh | b/engine/include/engine/lights.hh

前新
@@ -1,9 +1,9 @@
1 // 光源:平行光源・点光源・スポットライト / light casters: directional, point and spot lights 1 // 光源:平行光源・点光源・スポットライト / light casters: directional, point and spot lights
2 #pragma once 2 #pragma once
3   3  
4 #include "mathx.hh" 4 #include "engine/mathx.hh"
5 #include "shader.hh" 5 #include "engine/shader.hh"
6 #include "uniforms.hh" 6 #include "engine/uniforms.hh"
7   7  
8 #include <vector> 8 #include <vector>
9   9  
@@ -22,7 +22,7 @@ constexpr int kMaxSpotLights = 4;
22 // Directional light (sun, moon): no position, comes from the same direction everywhere 22 // Directional light (sun, moon): no position, comes from the same direction everywhere
23 struct DirectionalLight { 23 struct DirectionalLight {
24 Vec3 direction = {0.0f, -1.0f, 0.0f}; // 光が進む向き(光源へ向かう向きの逆) / the direction the light travels 24 Vec3 direction = {0.0f, -1.0f, 0.0f}; // 光が進む向き(光源へ向かう向きの逆) / the direction the light travels
25 Vec3 color = {0.0f, 0.0f, 0.0f}; // 色と明るさ。0 = オフ / colour and brightness; 0 = off 25 Vec3 color = {0.0f, 0.0f, 0.0f}; // 色と明るさ。0 = オフ / color and brightness; 0 = off
26 }; 26 };
27   27  
28 // 点光源(電球):一点から全方向へ、距離で弱くなる / point light (a bulb): all directions from one point, weaker with distance 28 // 点光源(電球):一点から全方向へ、距離で弱くなる / point light (a bulb): all directions from one point, weaker with distance

ファイル: a/src/material.hh | b/engine/include/engine/material.hh

前新
@@ -1,9 +1,9 @@
1 // マテリアル:物体の表面の性質 / material: the properties of an object's surface 1 // マテリアル:物体の表面の性質 / material: the properties of an object's surface
2 #pragma once 2 #pragma once
3   3  
4 #include "mathx.hh" 4 #include "engine/mathx.hh"
5 #include "shader.hh" 5 #include "engine/shader.hh"
6 #include "texture.hh" 6 #include "engine/texture.hh"
7   7  
8 // アルファ(不透明度)の使い方。glTFのalphaModeと同じ。シェーダーでは0/1/2 8 // アルファ(不透明度)の使い方。glTFのalphaModeと同じ。シェーダーでは0/1/2
9 // How alpha (opacity) is used. Same as glTF's alphaMode; 0/1/2 in the shader 9 // How alpha (opacity) is used. Same as glTF's alphaMode; 0/1/2 in the shader
@@ -14,11 +14,11 @@ enum class AlphaMode {
14 }; 14 };
15   15  
16 // Blinn-Phongのマテリアル。色とマップ(テクスチャ)は掛け合わされる。マップがなければ白(=色だけ)。 16 // Blinn-Phongのマテリアル。色とマップ(テクスチャ)は掛け合わされる。マップがなければ白(=色だけ)。
17 // A Blinn-Phong material. Each colour is multiplied with its map (texture); no map means white (= the colour alone). 17 // A Blinn-Phong material. Each color is multiplied with its map (texture); no map means white (= the color alone).
18 struct Material { 18 struct Material {
19 Vec3 diffuse = {1.0f, 1.0f, 1.0f}; // 拡散反射の色(物体の色) / diffuse colour (the object's colour) 19 Vec3 diffuse = {1.0f, 1.0f, 1.0f}; // 拡散反射の色(物体の色) / diffuse color (the object's color)
20 Vec3 specular = {0.5f, 0.5f, 0.5f}; // 鏡面反射の色と強さ / specular colour and strength 20 Vec3 specular = {0.5f, 0.5f, 0.5f}; // 鏡面反射の色と強さ / specular color and strength
21 Vec3 emission = {0.0f, 0.0f, 0.0f}; // 発光の色:光が当たらなくても見える / emission colour: visible even without light 21 Vec3 emission = {0.0f, 0.0f, 0.0f}; // 発光の色:光が当たらなくても見える / emission color: visible even without light
22 float shininess = 32.0f; // 光沢度 / shininess 22 float shininess = 32.0f; // 光沢度 / shininess
23   23  
24 float alpha = 1.0f; // 不透明度。diffuseMapのアルファと掛ける / opacity, multiplied with diffuseMap's alpha 24 float alpha = 1.0f; // 不透明度。diffuseMapのアルファと掛ける / opacity, multiplied with diffuseMap's alpha
@@ -29,7 +29,7 @@ struct Material {
29   29  
30 // 環境(ユニット3のキューブマップ)の映り込み(第18章)。金属だけ。第24章のIBLまでの簡単な代わり 30 // 環境(ユニット3のキューブマップ)の映り込み(第18章)。金属だけ。第24章のIBLまでの簡単な代わり
31 // Reflection of the environment (the cube map on unit 3, chapter 18). Metals only; a simple stand-in until IBL (ch24) 31 // Reflection of the environment (the cube map on unit 3, chapter 18). Metals only; a simple stand-in until IBL (ch24)
32 Vec3 reflectivity = {0.0f, 0.0f, 0.0f}; // 映り込みの色と強さ(0 = なし) / colour and strength of the reflection (0 = none) 32 Vec3 reflectivity = {0.0f, 0.0f, 0.0f}; // 映り込みの色と強さ(0 = なし) / color and strength of the reflection (0 = none)
33 float reflectionBlur = 0.0f; // 0 = 鏡、1 = 一番ぼやけたミップマップ / 0 = mirror, 1 = the blurriest mip level 33 float reflectionBlur = 0.0f; // 0 = 鏡、1 = 一番ぼやけたミップマップ / 0 = mirror, 1 = the blurriest mip level
34   34  
35 const Texture2D *diffuseMap = nullptr; // テクスチャユニット0 / texture unit 0 35 const Texture2D *diffuseMap = nullptr; // テクスチャユニット0 / texture unit 0

ファイル: a/src/mathx.hh | b/engine/include/engine/mathx.hh

前新
@@ -27,7 +27,31 @@ inline Mat3 toMat3(const Mat4 &m) {
27 inline Mat3 normalMatrix(const Mat4 &model) { return toMat3(transpose(inverse(model))); } 27 inline Mat3 normalMatrix(const Mat4 &model) { return toMat3(transpose(inverse(model))); }
28   28  
29 // sRGBの色(カラーピッカーや画像編集ソフトの値、0〜1)→ リニア(第21章)。シェーダーの計算はリニアで行う 29 // sRGBの色(カラーピッカーや画像編集ソフトの値、0〜1)→ リニア(第21章)。シェーダーの計算はリニアで行う
30 // An sRGB colour (the values of colour pickers and image editors, 0..1) → linear (chapter 21). Shaders compute in 30 // An sRGB color (the values of color pickers and image editors, 0..1) → linear (chapter 21). Shaders compute in
31 // linear space 31 // linear space
32 inline float srgbToLinear(float c) { return c <= 0.04045f ? c / 12.92f : std::pow((c + 0.055f) / 1.055f, 2.4f); } 32 inline float srgbToLinear(float c) { return c <= 0.04045f ? c / 12.92f : std::pow((c + 0.055f) / 1.055f, 2.4f); }
33 inline Vec3 srgbToLinear(Vec3 c) { return {srgbToLinear(c.x), srgbToLinear(c.y), srgbToLinear(c.z)}; } 33 inline Vec3 srgbToLinear(Vec3 c) { return {srgbToLinear(c.x), srgbToLinear(c.y), srgbToLinear(c.z)}; }
    34  
    35 // 2D(第25章):linalg.hhのVec2には足し算・引き算・スカラー倍・内積・長さしかないので足す
    36 // 2D (chapter 25): linalg.hh's Vec2 only has addition, subtraction, scaling, dot and length, so we add the rest
    37 inline Vec2 operator*(Vec2 v, float s) { return {v.x * s, v.y * s}; }
    38 inline Vec2 operator/(Vec2 v, float s) { return {v.x / s, v.y / s}; }
    39 inline Vec2 operator-(Vec2 v) { return {-v.x, -v.y}; }
    40 // 成分ごとの掛け算(大きさの拡大など) / component-wise product (scaling a size, for example)
    41 inline Vec2 operator*(Vec2 a, Vec2 b) { return {a.x * b.x, a.y * b.y}; }
    42 inline Vec2 &operator+=(Vec2 &a, Vec2 b) { return a = a + b; }
    43 inline Vec2 &operator-=(Vec2 &a, Vec2 b) { return a = a - b; }
    44 inline Vec2 &operator*=(Vec2 &a, float s) { return a = a * s; }
    45 inline Vec2 lerp(Vec2 a, Vec2 b, float t) { return a + t * (b - a); }
    46 inline Vec4 lerp(Vec4 a, Vec4 b, float t) { return a + t * (b - a); }
    47 // 長さ0なら0のまま / stays zero for a zero vector
    48 inline Vec2 normalize(Vec2 v) {
    49 float len = length(v);
    50 return len > 0.0f ? v / len : Vec2{};
    51 }
    52 // 回転(ラジアン)。2Dの画面座標(y下向き)では正の角度は時計回りに見える
    53 // Rotation (radians). In 2D screen coordinates (y down) a positive angle looks clockwise
    54 inline Vec2 rotate(Vec2 v, float angle) {
    55 float c = std::cos(angle), s = std::sin(angle);
    56 return {c * v.x - s * v.y, s * v.x + c * v.y};
    57 }

ファイル: a/src/mesh.hh | b/engine/include/engine/mesh.hh

前新
@@ -2,7 +2,7 @@
2 // Mesh: a vertex array object + vertex buffer + index buffer 2 // Mesh: a vertex array object + vertex buffer + index buffer
3 #pragma once 3 #pragma once
4   4  
5 #include "buffer.hh" 5 #include "engine/buffer.hh"
6   6  
7 #include <linalg.hh> 7 #include <linalg.hh>
8   8  
@@ -57,7 +57,7 @@ constexpr VertexAttrib kModelVertexLayout[] = {
57 }; 57 };
58   58  
59 // インスタンスごとのデータ(第19章):モデル行列(列4本をlocation 4〜7)と色(location 8) 59 // インスタンスごとのデータ(第19章):モデル行列(列4本をlocation 4〜7)と色(location 8)
60 // Per-instance data (chapter 19): the model matrix (its four columns at locations 4..7) and a colour (location 8) 60 // Per-instance data (chapter 19): the model matrix (its four columns at locations 4..7) and a color (location 8)
61 struct InstanceData { 61 struct InstanceData {
62 Mat4 model; 62 Mat4 model;
63 Vec3 color; 63 Vec3 color;

ファイル: a/src/model.hh | b/engine/include/engine/model.hh

前新
@@ -1,12 +1,12 @@
1 // glTF/GLBのモデルをGPUに載せて描く / uploads a glTF/GLB model to the GPU and draws it 1 // glTF/GLBのモデルをGPUに載せて描く / uploads a glTF/GLB model to the GPU and draws it
2 #pragma once 2 #pragma once
3   3  
4 #include "gltf.hh" 4 #include "engine/gltf.hh"
5 #include "material.hh" 5 #include "engine/material.hh"
6 #include "mesh.hh" 6 #include "engine/mesh.hh"
7 #include "pbr_material.hh" 7 #include "engine/pbr_material.hh"
8 #include "shader.hh" 8 #include "engine/shader.hh"
9 #include "texture.hh" 9 #include "engine/texture.hh"
10   10  
11 #include <optional> 11 #include <optional>
12 #include <span> 12 #include <span>
@@ -70,7 +70,7 @@ public:
70 // passのプリミティブだけを描く。Transparentでは、viewPosから各プリミティブの箱の中心までの距離で遠い順に並べる。 70 // passのプリミティブだけを描く。Transparentでは、viewPosから各プリミティブの箱の中心までの距離で遠い順に並べる。
71 // 両面(doubleSided)のマテリアルは、その間だけフェイスカリングを切って描く。 71 // 両面(doubleSided)のマテリアルは、その間だけフェイスカリングを切って描く。
72 // Draws only the primitives of `pass`. Transparent sorts them back to front by the distance from viewPos to the 72 // Draws only the primitives of `pass`. Transparent sorts them back to front by the distance from viewPos to the
73 // centre of each primitive's box. Double-sided materials are drawn with face culling turned off for that draw. 73 // center of each primitive's box. Double-sided materials are drawn with face culling turned off for that draw.
74 // shading = Pbrならマテリアルは金属・粗さ・遮蔽などのテクスチャごとPbrMaterialで設定する(第24章) 74 // shading = Pbrならマテリアルは金属・粗さ・遮蔽などのテクスチャごとPbrMaterialで設定する(第24章)
75 // With shading = Pbr the materials are set as PbrMaterial, with their metallic-roughness, occlusion... maps (ch. 24) 75 // With shading = Pbr the materials are set as PbrMaterial, with their metallic-roughness, occlusion... maps (ch. 24)
76 void draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, ModelPass pass, 76 void draw(const Shader &shader, const Mat4 &transform, const Texture2D &white, ModelPass pass,
@@ -78,14 +78,14 @@ public:
78 // 形だけを描く:マテリアルもテクスチャも設定せず、ノードごとにuModelだけ(シェーダーが使っていればuNormalMatrixも)。 78 // 形だけを描く:マテリアルもテクスチャも設定せず、ノードごとにuModelだけ(シェーダーが使っていればuNormalMatrixも)。
79 // 深度の表示、輪郭、のちの影(第23章)のように、色を使わないパス用。 79 // 深度の表示、輪郭、のちの影(第23章)のように、色を使わないパス用。
80 // Draws the shape only: no materials or textures, just uModel per node (and uNormalMatrix if the shader uses it). 80 // Draws the shape only: no materials or textures, just uModel per node (and uNormalMatrix if the shader uses it).
81 // For passes that need no colour: the depth view, outlines, and later shadows (chapter 23). 81 // For passes that need no color: the depth view, outlines, and later shadows (chapter 23).
82 void drawGeometry(const Shader &shader, const Mat4 &transform) const; 82 void drawGeometry(const Shader &shader, const Mat4 &transform) const;
83   83  
84 // 影の地図の深度だけを描く(第23章)。OpaqueとMaskのプリミティブ(Blendは影を落とさない)。Maskのマテリアルは 84 // 影の地図の深度だけを描く(第23章)。OpaqueとMaskのプリミティブ(Blendは影を落とさない)。Maskのマテリアルは
85 // ベースカラーのテクスチャ(なければwhite)をユニット0に繋ぎ、uAlphaMask = 1、uAlphaCutoff、uBaseAlphaを設定する 85 // ベースカラーのテクスチャ(なければwhite)をユニット0に繋ぎ、uAlphaMask = 1、uAlphaCutoff、uBaseAlphaを設定する
86 // (シェーダーがdiscardで葉の形に切り抜く)。ほかはuAlphaMask = 0。両面のマテリアルはカリングを切る。 86 // (シェーダーがdiscardで葉の形に切り抜く)。ほかはuAlphaMask = 0。両面のマテリアルはカリングを切る。
87 // Draws depth only, for shadow maps (chapter 23). Opaque and Mask primitives (Blend casts no shadow). For Mask 87 // Draws depth only, for shadow maps (chapter 23). Opaque and Mask primitives (Blend casts no shadow). For Mask
88 // materials the base colour texture (or white) goes on unit 0 and uAlphaMask = 1, uAlphaCutoff and uBaseAlpha are 88 // materials the base color texture (or white) goes on unit 0 and uAlphaMask = 1, uAlphaCutoff and uBaseAlpha are
89 // set (the shader discards to cut out leaves); otherwise uAlphaMask = 0. Double-sided materials turn culling off. 89 // set (the shader discards to cut out leaves); otherwise uAlphaMask = 0. Double-sided materials turn culling off.
90 void drawDepth(const Shader &shader, const Mat4 &transform, const Texture2D &white) const; 90 void drawDepth(const Shader &shader, const Mat4 &transform, const Texture2D &white) const;
91   91  

ファイル: a/src/pbr_material.hh | b/engine/include/engine/pbr_material.hh

前新
@@ -2,11 +2,11 @@
2 // glTF's metallic-roughness model 2 // glTF's metallic-roughness model
3 #pragma once 3 #pragma once
4   4  
5 #include "gltf.hh" 5 #include "engine/gltf.hh"
6 #include "material.hh" 6 #include "engine/material.hh"
7 #include "mathx.hh" 7 #include "engine/mathx.hh"
8 #include "shader.hh" 8 #include "engine/shader.hh"
9 #include "texture.hh" 9 #include "engine/texture.hh"
10   10  
11 // テクスチャはすべて「係数 × テクスチャ」。ないテクスチャには白を繋ぐ(白 × 係数 = 係数)。 11 // テクスチャはすべて「係数 × テクスチャ」。ないテクスチャには白を繋ぐ(白 × 係数 = 係数)。
12 // Every texture is "factor × texture". A missing texture is replaced by white (white × factor = factor). 12 // Every texture is "factor × texture". A missing texture is replaced by white (white × factor = factor).

ファイル: /dev/null | b/engine/include/engine/pixel_canvas.hh

前新
@@ -0,0 +1,34 @@
    1 // ピクセルアート用の低解像度のキャンバス(第25章):仮想解像度のFBOに描いて、整数倍に拡大して画面に出す
    2 // A low-resolution canvas for pixel art (chapter 25): draw into an FBO at the virtual resolution, then scale it up by
    3 // a whole number onto the screen
    4 #pragma once
    5  
    6 #include "engine/camera2d.hh"
    7 #include "engine/framebuffer.hh"
    8  
    9 // 回転や半端な位置のスプライトも、画面ではピクセルの格子に乗る(本物の低解像度)。
    10 // 画面の解像度で直接描く(Camera2D+letterbox)と、回転した物が細かいピクセルで描かれる:好みで選ぶ
    11 // Rotated or sub-pixel sprites still land on the pixel grid on screen (a true low resolution).
    12 // Drawing straight at screen resolution (Camera2D + letterbox) renders rotated things with finer pixels: pick what
    13 // you prefer
    14 class PixelCanvas {
    15 public:
    16 PixelCanvas(int width, int height);
    17  
    18 // キャンバスに描き始める:FBOを繋ぎ、ビューポートを全体にしてclearColorで塗る
    19 // Starts drawing into the canvas: binds the FBO, sets a full viewport and clears it to clearColor
    20 void begin(Vec4 clearColor) const;
    21 // 画面へ:既定のフレームバッファをbarColorで塗り、真ん中にGL_NEARESTで拡大コピー(glBlitNamedFramebuffer)。
    22 // 使った場所(マウスの変換に使える)を返す。glClearColorは変わったまま
    23 // To the screen: clears the default framebuffer to barColor and copies the canvas into the middle, scaled with
    24 // GL_NEAREST (glBlitNamedFramebuffer). Returns where it went (useful for the mouse). Leaves glClearColor changed
    25 Viewport present(int windowWidth, int windowHeight, bool integerScale = true, Vec4 barColor = {0, 0, 0, 1}) const;
    26  
    27 int width() const { return fbo.width(); }
    28 int height() const { return fbo.height(); }
    29 Vec2 size() const { return {static_cast<float>(fbo.width()), static_cast<float>(fbo.height())}; }
    30 const Framebuffer &framebuffer() const { return fbo; }
    31  
    32 private:
    33 Framebuffer fbo;
    34 };

ファイル: /dev/null | b/engine/include/engine/rect.hh

前新
@@ -0,0 +1,25 @@
    1 // 2Dの長方形(第25章):スプライトの位置と大きさ、UVの範囲、当たり判定の箱(第26章)
    2 // A 2D rectangle (chapter 25): sprite positions and sizes, UV ranges, collision boxes (chapter 26)
    3 #pragma once
    4  
    5 #include "engine/mathx.hh"
    6  
    7 // 軸に平行な長方形。2Dの座標はy下向き(左上が原点)なので、(x, y)が左上、x + w が右、y + h が下
    8 // An axis-aligned rectangle. 2D coordinates point y down (origin at the top left), so (x, y) is the top-left corner,
    9 // x + w the right edge and y + h the bottom edge
    10 struct Rect {
    11 float x = 0.0f, y = 0.0f, w = 0.0f, h = 0.0f;
    12  
    13 float left() const { return x; }
    14 float right() const { return x + w; }
    15 float top() const { return y; }
    16 float bottom() const { return y + h; }
    17 Vec2 position() const { return {x, y}; }
    18 Vec2 size() const { return {w, h}; }
    19 Vec2 centre() const { return {x + 0.5f * w, y + 0.5f * h}; }
    20  
    21 // 中心と大きさから / from a center and a size
    22 static Rect fromCentre(Vec2 c, Vec2 size) { return {c.x - 0.5f * size.x, c.y - 0.5f * size.y, size.x, size.y}; }
    23 // dだけずらした長方形 / the rectangle moved by d
    24 Rect translated(Vec2 d) const { return {x + d.x, y + d.y, w, h}; }
    25 };

ファイル: /dev/null | b/engine/include/engine/renderer3d.hh

前新
@@ -0,0 +1,133 @@
    1 // 3Dのフレームの部品(第20〜24章のmain.ccから移したもの):影の地図とHDRの後処理の流れ
    2 // Pieces of a 3D frame (moved from the main.cc of chapters 20-24): the shadow map and the HDR post-processing chain
    3 #pragma once
    4  
    5 #include "engine/framebuffer.hh"
    6 #include "engine/mathx.hh"
    7 #include "engine/shader.hh"
    8 #include "engine/uniforms.hh"
    9  
    10 #include <optional>
    11  
    12 // 平行光源の光から見た行列:centreを中心とする半径radiusの球を正射影の箱に収める(第23章)。箱は影の地図の
    13 // 1テクセル単位で動かす(カメラが動いても影の縁がちらつかない)。depthRangeに箱の奥行き(m)を返す
    14 // The directional light's matrix: an orthographic box enclosing the sphere (`centre`, `radius`) (chapter 23). The box
    15 // moves in whole shadow-map texels (shadow edges do not shimmer when the camera moves). Returns the box depth (m) in
    16 // depthRange
    17 Mat4 lightSpaceMatrix(Vec3 lightDir, Vec3 centre, float radius, int mapSize, float &depthRange);
    18  
    19 // 球(光の箱を合わせる範囲) / a sphere (what the light box is fitted to)
    20 struct BoundingSphere {
    21 Vec3 centre;
    22 float radius = 1.0f;
    23 };
    24  
    25 // カメラの視錐台のnearDist〜farDistの部分を囲む球(第23章のJ)。中心は8つの角の平均、半径は一番遠い角まで:
    26 // カメラが回っても大きさが変わらないので、影の地図のテクセルの大きさも変わらない
    27 // The sphere around the camera frustum between nearDist and farDist (chapter 23, key J). Center = the mean of the 8
    28 // corners, radius = to the farthest corner: its size does not change as the camera turns, so neither does the size
    29 // of a shadow-map texel
    30 BoundingSphere frustumSphere(Vec3 eye, Vec3 forward, float fovY, float aspect, float nearDist, float farDist);
    31  
    32 // 影のバイアス(第23章)。inTexelsなら値は影の地図の1テクセルのワールドでの大きさの倍数(地図の大きさを変えても
    33 // 効き目が同じ)、そうでなければメートル。既定値は第23・24章の既定(0.5 / 1 / 3テクセル)
    34 // The shadow biases (chapter 23). With inTexels the values are multiples of one shadow-map texel's world size (they
    35 // work the same at any map size), otherwise meters. The defaults are those of chapters 23-24 (0.5 / 1 / 3 texels)
    36 struct ShadowBias {
    37 float constant = 0.5f; // 一定のバイアス / constant bias
    38 float slope = 1.0f; // tanθ当たり / per unit of tan θ
    39 float normalOffset = 3.0f; // 法線方向のずらし / push along the normal
    40 bool inTexels = true;
    41 };
    42  
    43 // バイアスを0〜1の深度(正射影なので深度は距離に比例)とメートルに直してblockに書く
    44 // Converts the biases to 0..1 depth (orthographic: depth is proportional to distance) and meters, and writes them into
    45 // block
    46 void applyShadowBias(ShadowBlock &block, const ShadowBias &bias, float radius, int mapSize, float depthRange);
    47  
    48 // 平行光源の影の地図(第23章):深度テクスチャのFBO+Shadowブロック(結合点2)。使い方:
    49 // shadow.begin(sunDir, sphere); … 影を落とす物をshadow.vert/.frag+Model::drawDepthで描く … shadow.end();
    50 // end()が深度テクスチャをユニット5に繋ぐ。enabled = falseでもbegin/endを呼ぶ(UBOが「影なし」になる)
    51 // A directional shadow map (chapter 23): a depth-texture FBO + the Shadow block (binding 2). Usage:
    52 // shadow.begin(sunDir, sphere); ... draw the casters with shadow.vert/.frag + Model::drawDepth ... shadow.end();
    53 // end() binds the depth texture to unit 5. Call begin/end even when disabled (the UBO then says "no shadows")
    54 class ShadowMap {
    55 public:
    56 static constexpr GLuint kUnit = 5; // テクスチャユニット / texture unit
    57  
    58 explicit ShadowMap(int size = 2048);
    59  
    60 // 光の箱を合わせてShadowブロックを更新する。enabledなら影の地図に描く準備(bind・深度クリア・深度テスト・
    61 // 裏面カリング)をしてtrueを返す。falseなら何も描かないこと
    62 // Fits the light box and updates the Shadow block. When enabled, prepares drawing into the map (bind, depth clear,
    63 // depth test, back-face culling) and returns true. When it returns false, draw nothing
    64 bool begin(Vec3 lightDir, const BoundingSphere &fit, const ShadowBias &bias = {},
    65 ShadowFilter filter = ShadowFilter::Pcf3x3, bool enabled = true);
    66 // 深度テクスチャをユニット5に繋ぐ(描き終わってから) / binds the depth texture to unit 5 (after drawing)
    67 void end() const;
    68  
    69 // 地図の大きさを変える(FBOを作り直す) / changes the map size (re-creates the FBO)
    70 void resize(int size);
    71 int size() const { return fbo.width(); }
    72 bool complete() const { return fbo.complete(); }
    73 const Texture2D &depth() const { return fbo.depth(); }
    74 const ShadowBlock &block() const { return current; }
    75 // 1テクセルがワールドで何メートルか(最後のbeginの値) / how many meters one texel covers (from the last begin)
    76 float metresPerTexel() const { return texelMetres; }
    77  
    78 private:
    79 Framebuffer fbo;
    80 UniformBuffer<ShadowBlock> ubo{kShadowBinding};
    81 ShadowBlock current;
    82 float texelMetres = 0.0f;
    83 };
    84  
    85 // HDRの後処理の流れ(第20・21章):MSAAのRGBA16F × 2(色+明るい部分、MRT)に描き → 解決 → 半分の大きさで
    86 // ブルームのぼかし(横・縦のピンポン) → post.fragで露出・トーンマッピング・sRGB・効果を掛けて画面へ。
    87 // Postブロック(結合点3)も持つ:場面のシェーダーがuBloomThresholdを読むので、beginSceneの前にsettingsを決める
    88 // The HDR post-processing chain (chapters 20-21): draw into a multisampled RGBA16F × 2 target (color + bright part,
    89 // MRT) → resolve → bloom blur at half size (horizontal/vertical ping-pong) → post.frag applies exposure, tone mapping,
    90 // sRGB and the effect on the way to the screen. It also owns the Post block (binding 3): the scene shaders read
    91 // uBloomThreshold, so set `settings` before beginScene
    92 struct PostChainSettings {
    93 int samples = 4; // 0 = MSAAなし / no MSAA(llvmpipeで速い / faster on llvmpipe)
    94 GLenum format = GL_RGBA16F; // GL_R11F_G11F_B10Fも可 / GL_R11F_G11F_B10F also works
    95 int bloomPasses = 4; // 横+縦の組の数(0 = ぼかさない) / number of horizontal + vertical pairs (0 = no blur)
    96 };
    97  
    98 class PostChain {
    99 public:
    100 static std::optional<PostChain> create(int width, int height, const PostChainSettings &settings = {});
    101  
    102 // ウィンドウの大きさが変わったとき / when the window size changes
    103 void resize(int width, int height);
    104 // Postブロックをアップロードし、場面のFBOに切り替える(ビューポートも)。クリアは呼ぶ側で
    105 // Uploads the Post block and binds the scene FBO (and its viewport). Clearing is up to the caller
    106 void beginScene();
    107 // 解決(MSAA → 普通のFBO)とブルーム。深度テストは切られる / resolve (MSAA → ordinary FBO) and bloom. Turns the
    108 // depth test off
    109 void endScene();
    110 // 画面(既定のフレームバッファ)へ:場面+ブルーム → post.frag。effectは第17章の1〜6のキー(0 = なし)
    111 // To the screen (the default framebuffer): scene + bloom → post.frag. effect = the chapter 17 keys 1-6 (0 = none)
    112 void present(int windowWidth, int windowHeight, int effect = 0);
    113 // シェーダーを読み直す / reloads the shaders
    114 bool reload();
    115  
    116 PostBlock settings; // 露出・ブルーム・トーンマッピング… / exposure, bloom, tone mapping...
    117  
    118 const Framebuffer &scene() const { return sceneFbo; } // 解決後(色0 = 場面、色1 = 明るい部分) / after the resolve
    119 // ぼかした明るい部分:最後の縦のパスの結果。bloomPasses = 0ならぼかす前の明るい部分(全体の大きさ)
    120 // The blurred bright part: the result of the last vertical pass. With bloomPasses = 0 the unblurred bright part
    121 // (full size)
    122 const Texture2D &bloom() const { return config.bloomPasses > 0 ? bloomFbo[1].color() : sceneFbo.color(1); }
    123  
    124 private:
    125 PostChain() = default;
    126  
    127 PostChainSettings config;
    128 std::optional<Shader> post, blur;
    129 Framebuffer msaaFbo, sceneFbo;
    130 Framebuffer bloomFbo[2];
    131 FullscreenTriangle fullscreen;
    132 std::optional<UniformBuffer<PostBlock>> ubo;
    133 };

ファイル: a/src/shader.hh | b/engine/include/engine/shader.hh

前新
@@ -1,7 +1,7 @@
1 // シェーダープログラム / a shader program 1 // シェーダープログラム / a shader program
2 #pragma once 2 #pragma once
3   3  
4 #include "mathx.hh" 4 #include "engine/mathx.hh"
5   5  
6 #include <glad/glad.h> 6 #include <glad/glad.h>
7   7  

ファイル: a/src/shapes.hh | b/engine/include/engine/shapes.hh

前新
@@ -3,16 +3,16 @@
3 // in the OpenGL convention (v grows upwards) 3 // in the OpenGL convention (v grows upwards)
4 #pragma once 4 #pragma once
5   5  
6 #include "mesh.hh" 6 #include "engine/mesh.hh"
7   7  
8 // 原点を中心とした大きさsizeの箱。UVはメートル単位でtileSizeごとに繰り返す(伸びない:壁、柱、段に。第22章) 8 // 原点を中心とした大きさsizeの箱。UVはメートル単位でtileSizeごとに繰り返す(伸びない:壁、柱、段に。第22章)
9 // A box of the given size centred on the origin. UVs are in metres, repeating every tileSize (no stretching: for walls, 9 // A box of the given size centered on the origin. UVs are in meters, repeating every tileSize (no stretching: for walls,
10 // pillars, steps; chapter 22) 10 // pillars, steps; chapter 22)
11 Mesh makeBox(Vec3 size, float tileSize = 1.0f); 11 Mesh makeBox(Vec3 size, float tileSize = 1.0f);
12   12  
13 // 原点を中心とした1×1×1の立方体。面ごとに頂点4つ(UVと法線が面ごとに違うので共有できない)=24頂点、36インデックス。 13 // 原点を中心とした1×1×1の立方体。面ごとに頂点4つ(UVと法線が面ごとに違うので共有できない)=24頂点、36インデックス。
14 // 外から見て反時計回り(第16章のカリング用)。 14 // 外から見て反時計回り(第16章のカリング用)。
15 // A 1×1×1 cube centred on the origin. 4 vertices per face (UVs and normals differ per face, so corners 15 // A 1×1×1 cube centered on the origin. 4 vertices per face (UVs and normals differ per face, so corners
16 // cannot be shared) = 24 vertices, 36 indices. Counter-clockwise seen from outside (for culling in chapter 16). 16 // cannot be shared) = 24 vertices, 36 indices. Counter-clockwise seen from outside (for culling in chapter 16).
17 Mesh makeCube(); 17 Mesh makeCube();
18   18  
@@ -22,8 +22,8 @@ Mesh makePlane(float size, float uvRepeat);
22   22  
23 // 原点を中心とした直径1の球(UV球)。segments = 経度方向の分割数、rings = 緯度方向の分割数。 23 // 原点を中心とした直径1の球(UV球)。segments = 経度方向の分割数、rings = 緯度方向の分割数。
24 // 法線は中心から外向き。立方体と同じく外から見て反時計回り。 24 // 法線は中心から外向き。立方体と同じく外から見て反時計回り。
25 // A sphere of diameter 1 centred on the origin (a UV sphere). segments = divisions around, rings = from pole to pole. 25 // A sphere of diameter 1 centered on the origin (a UV sphere). segments = divisions around, rings = from pole to pole.
26 // The normals point outwards from the centre. Counter-clockwise seen from outside, like the cube. 26 // The normals point outwards from the center. Counter-clockwise seen from outside, like the cube.
27 Mesh makeSphere(int segments = 32, int rings = 16); 27 Mesh makeSphere(int segments = 32, int rings = 16);
28   28  
29 // 縦の1×1の板をcount枚、Y軸の周りに等間隔で回して重ねたもの(草の株)。原点は下の辺の真ん中、UVのv = 0が下。 29 // 縦の1×1の板をcount枚、Y軸の周りに等間隔で回して重ねたもの(草の株)。原点は下の辺の真ん中、UVのv = 0が下。

ファイル: /dev/null | b/engine/include/engine/sprite_batch.hh

前新
@@ -0,0 +1,140 @@
    1 // スプライトバッチ(第25章):たくさんの四角形を一つの動的な頂点バッファにまとめ、テクスチャごとに一度に描く
    2 // The sprite batch (chapter 25): collects many quads into one dynamic vertex buffer and draws them with one draw call
    3 // per texture
    4 #pragma once
    5  
    6 #include "engine/buffer.hh"
    7 #include "engine/mathx.hh"
    8 #include "engine/rect.hh"
    9 #include "engine/shader.hh"
    10 #include "engine/texture.hh"
    11  
    12 #include <cstdint>
    13 #include <optional>
    14 #include <vector>
    15  
    16 // 色:sRGBの値(画像編集ソフトと同じ)、アルファはそのまま(乗算前)。0xRRGGBBAAから作れる
    17 // Colors: sRGB values (as in image editors), straight (not premultiplied) alpha. Can be made from 0xRRGGBBAA
    18 constexpr Vec4 hexColor(std::uint32_t rrggbbaa) {
    19 return {static_cast<float>((rrggbbaa >> 24) & 0xFF) / 255.0f, static_cast<float>((rrggbbaa >> 16) & 0xFF) / 255.0f,
    20 static_cast<float>((rrggbbaa >> 8) & 0xFF) / 255.0f, static_cast<float>(rrggbbaa & 0xFF) / 255.0f};
    21 }
    22 constexpr Vec4 kWhite = {1.0f, 1.0f, 1.0f, 1.0f};
    23  
    24 // 一枚のスプライト(四角形)。位置・大きさはワールドの単位(ふつうは仮想ピクセル、y下向き)
    25 // One sprite (a quad). Position and size are in world units (usually virtual pixels, y down)
    26 struct Sprite {
    27 const Texture2D *texture = nullptr; // nullptr = 白(色だけの四角形) / white (a plain colored rectangle)
    28 Vec2 position; // originが来る場所 / where `origin` ends up
    29 Vec2 size = {16.0f, 16.0f}; // 描く大きさ / drawn size
    30 Rect uv = {0.0f, 0.0f, 1.0f, 1.0f}; // テクスチャの範囲(0〜1、左上がv = 0) / texture area (0..1, v = 0 at the top)
    31 Vec2 origin = {0.0f, 0.0f}; // 回転と位置の基準(大きさに対する割合:(0.5, 0.5) = 中心) / pivot for rotation
    32 // and position (fraction of the size: (0.5, 0.5) = the center)
    33 float rotation = 0.0f; // ラジアン、画面上で時計回り / radians, clockwise on screen
    34 Vec4 color = kWhite; // 掛ける色(sRGB、アルファ) / tint (sRGB, alpha)
    35 float layer = 0.0f; // SpriteSort::Layerの順番:大きいほど手前 / order for SpriteSort::Layer: larger
    36 // is in front
    37 bool flipX = false, flipY = false; // 左右・上下反転(向きを変えたキャラクター) / mirror (a character turning round)
    38 };
    39  
    40 // end()でどう並べてから描くか / how sprites are ordered before drawing in end()
    41 enum class SpriteSort {
    42 None, // 描いた順のまま。テクスチャが変わるたびに描画コールが一つ増える / submission order; every texture change
    43 // costs one more draw call
    44 Texture, // テクスチャごとにまとめる(描画コール最少)。重なりの順番は保証しない / grouped by texture (fewest draw
    45 // calls); overlap order is not kept
    46 Layer, // layerの小さい順(奥から手前)。同じlayerの中ではテクスチャごと、同じテクスチャなら描いた順
    47 // by layer, small first (back to front); within one layer grouped by texture, then submission order
    48 };
    49  
    50 // 混ぜ方。テクスチャも色も乗算済みアルファで扱う / blending. Textures and colors are handled as premultiplied alpha
    51 enum class SpriteBlend {
    52 Alpha, // ふつうの半透明(GL_ONE, GL_ONE_MINUS_SRC_ALPHA) / ordinary transparency
    53 Additive, // 足す(光・炎・爆発)(GL_ONE, GL_ONE) / adds up (light, fire, explosions)
    54 };
    55  
    56 // 頂点データの送り方 / how vertex data reaches the GPU
    57 enum class SpriteUpload {
    58 SubData, // glNamedBufferSubData:毎回コピー。簡単で、ドライバーが同期を面倒見る / a copy per draw call; simple, the
    59 // driver handles synchronization
    60 Persistent, // 永続マップ(GL_MAP_PERSISTENT_BIT):バッファに直接書く。3つの区画を回し、フェンスで待つ
    61 // persistent mapping: write straight into the buffer; three regions in turn, guarded by fences
    62 };
    63  
    64 struct SpriteBatchSettings {
    65 int capacity = 8192; // 一回の描画コールのスプライトの最大数 / the most sprites in one draw call
    66 SpriteUpload upload = SpriteUpload::SubData;
    67 };
    68  
    69 // 直前のend()の結果 / what the last end() did
    70 struct SpriteStats {
    71 int sprites = 0;
    72 int drawCalls = 0;
    73 };
    74  
    75 // 頂点:位置、UV、色(RGBA8、0〜1に正規化)。20バイト / a vertex: position, UV, color (RGBA8 normalized to 0..1);
    76 // 20 bytes
    77 struct SpriteVertex {
    78 Vec2 position;
    79 Vec2 uv;
    80 std::uint32_t color; // R = 下位バイト / R = lowest byte
    81 };
    82  
    83 // スプライトバッチ(RAII、コピー不可・移動可)。使い方:
    84 // batch.begin(camera.matrix()); batch.draw(sprite); … batch.end();
    85 // end()が並べ替えて描く。end()の後は:ブレンドon、深度テストoff、カリングoff(3Dに戻るときは設定し直す)
    86 // The sprite batch (RAII, non-copyable, movable). Usage:
    87 // batch.begin(camera.matrix()); batch.draw(sprite); ... batch.end();
    88 // end() sorts and draws. After end(): blending on, depth test off, culling off (set them again when going back to 3D)
    89 class SpriteBatch {
    90 public:
    91 // シェーダー engine/shaders/sprite.vert/.frag を読む。失敗したらstd::nullopt
    92 // Loads the shader engine/shaders/sprite.vert/.frag. std::nullopt on failure
    93 static std::optional<SpriteBatch> create(const SpriteBatchSettings &settings = {});
    94 ~SpriteBatch();
    95 SpriteBatch(const SpriteBatch &) = delete;
    96 SpriteBatch &operator=(const SpriteBatch &) = delete;
    97 SpriteBatch(SpriteBatch &&other) noexcept;
    98 SpriteBatch &operator=(SpriteBatch &&other) noexcept;
    99  
    100 // viewProjection = Camera2D::matrix()(ワールド → クリップ座標) / Camera2D::matrix() (world → clip space)
    101 void begin(const Mat4 &viewProjection, SpriteSort sort = SpriteSort::None, SpriteBlend blend = SpriteBlend::Alpha);
    102 void draw(const Sprite &sprite);
    103 // 色だけの長方形と、その枠(当たり判定の箱の表示など) / a plain colored rectangle and its outline (e.g. to show
    104 // collision boxes)
    105 void drawRect(const Rect &rect, Vec4 color, float layer = 0.0f);
    106 void drawRectOutline(const Rect &rect, Vec4 color, float thickness = 1.0f, float layer = 0.0f);
    107 void end();
    108  
    109 const SpriteStats &stats() const { return lastStats; }
    110 SpriteUpload upload() const { return settings.upload; }
    111  
    112 private:
    113 SpriteBatch() = default;
    114 // 頂点4つ分の四角形と、並べ替えに要る物 / one quad's 4 vertices plus what sorting needs
    115 struct Quad {
    116 SpriteVertex v[4];
    117 const Texture2D *texture;
    118 float layer;
    119 };
    120 void flush(const std::vector<std::uint32_t> &order, size_t first, size_t count, const Texture2D &texture);
    121 void release();
    122  
    123 SpriteBatchSettings settings;
    124 std::optional<Shader> shader;
    125 Buffer vertexBuffer, indexBuffer;
    126 GLuint vao = 0;
    127 Texture2D white; // 色だけの四角形用の1×1 / 1 × 1, for plain rectangles
    128  
    129 // 永続マップ / persistent mapping
    130 static constexpr int kRegions = 3;
    131 SpriteVertex *mapped = nullptr;
    132 GLsync fences[kRegions] = {};
    133 int region = 0, regionUsed = 0; // 今の区画と、そこで使ったスプライトの数 / the current region and sprites used there
    134  
    135 std::vector<Quad> quads;
    136 std::vector<SpriteVertex> staging; // SubData用の書き込み先 / where SubData writes first
    137 SpriteSort sortMode = SpriteSort::None;
    138 SpriteStats lastStats, currentStats;
    139 bool begun = false;
    140 };

ファイル: /dev/null | b/engine/include/engine/sprite_sheet.hh

前新
@@ -0,0 +1,74 @@
    1 // スプライトシート(アトラス):一枚のテクスチャにたくさんのコマ(第25章)
    2 // Sprite sheets (atlases): many frames in one texture (chapter 25)
    3 #pragma once
    4  
    5 #include "engine/animation.hh"
    6 #include "engine/rect.hh"
    7 #include "engine/sprite_batch.hh"
    8 #include "engine/texture.hh"
    9  
    10 #include <deque>
    11 #include <optional>
    12 #include <string>
    13 #include <string_view>
    14 #include <vector>
    15  
    16 enum class TextureFilter {
    17 Nearest, // ピクセルアート:くっきり(GL_NEAREST) / pixel art: crisp (GL_NEAREST)
    18 Linear, // 滑らか(GL_LINEAR):拡大するとぼける / smooth (GL_LINEAR): blurry when enlarged
    19 };
    20  
    21 // 2D用の画像を読む:上下反転なし(一番上の行がv = 0)、ミップマップなし、乗算済みアルファ、端はCLAMP_TO_EDGE。
    22 // 色の値はsRGBのまま(GL_RGBA8):2Dの色は画像編集ソフトで見たとおりに混ぜる(第25章)
    23 // Loads an image for 2D: no flip (the top row is v = 0), no mipmaps, premultiplied alpha, CLAMP_TO_EDGE.
    24 // The colors stay sRGB-encoded (GL_RGBA8): 2D colors blend exactly as seen in an image editor (chapter 25)
    25 std::optional<Texture2D> loadSpriteTexture(const std::string &path, TextureFilter filter = TextureFilter::Nearest);
    26  
    27 // スプライトシート(RAII、コピー不可・移動可):テクスチャを持ち、コマ(ピクセルの長方形)と名前とクリップを覚える
    28 // A sprite sheet (RAII, non-copyable, movable): owns the texture and knows the frames (pixel rectangles), their names
    29 // and the animation clips
    30 class SpriteSheet {
    31 public:
    32 // 格子のシート:cellWidth × cellHeightのコマが左上から右へ、行ごとに並ぶ。margin = 外側の余白、spacing = コマの間の
    33 // 隙間(にじみ防止、第25章)。コマの名前は番号 / a grid sheet: cellWidth × cellHeight frames from the top left to the
    34 // right, row by row. margin = the outer border, spacing = the gap between frames (against bleeding, chapter 25).
    35 // Frames are known by number
    36 static std::optional<SpriteSheet> loadGrid(const std::string &imagePath, int cellWidth, int cellHeight, int margin = 0,
    37 int spacing = 0, TextureFilter filter = TextureFilter::Nearest);
    38 // アトラスの説明ファイル(.atlas、テキスト)から。1行に1つ / from an atlas description file (.atlas, text), one
    39 // entry per line:
    40 // image <ファイル> 画像(.atlasのフォルダからの相対パス) / the image (relative to the .atlas)
    41 // sprite <名前> <x> <y> <幅> <高さ> コマ(ピクセル、左上が原点) / a frame (pixels, origin top left)
    42 // clip <名前> <fps> <loop|once> <コマ…> アニメーション(コマは名前で) / an animation (frames by name)
    43 // # … コメント / comment
    44 static std::optional<SpriteSheet> loadAtlas(const std::string &atlasPath, TextureFilter filter = TextureFilter::Nearest);
    45  
    46 const Texture2D &texture() const { return image; }
    47 int count() const { return static_cast<int>(frames.size()); }
    48 // コマの長方形。範囲外の番号(Animator::frame()の-1など)は空の長方形(大きさ0:何も描かれない)になり、
    49 // 最初の一回だけstderrに知らせる / a frame's rectangle. An index out of range (such as Animator::frame()'s -1)
    50 // gives an empty rectangle (size 0: nothing is drawn), reported once on stderr
    51 Rect pixels(int index) const; // ピクセル / pixels
    52 Rect uv(int index) const; // 0〜1
    53 Vec2 size(int index) const { return pixels(index).size(); }
    54 // 名前でコマを探す(なければ-1) / finds a frame by name (-1 if missing)
    55 int find(std::string_view name) const;
    56 // クリップ(なければnullptr) / a clip (nullptr if missing)
    57 const AnimationClip *clip(std::string_view name) const;
    58 void addClip(AnimationClip clip) { clips.push_back(std::move(clip)); }
    59  
    60 // そのコマのSprite:テクスチャ・UV・大きさ(ピクセル × scale)を埋める。位置などは後から変える
    61 // A Sprite for that frame: fills in the texture, UVs and size (pixels × scale); change position etc. afterwards
    62 Sprite sprite(int index, Vec2 position, Vec2 origin = {0.0f, 0.0f}, float scale = 1.0f) const;
    63  
    64 private:
    65 SpriteSheet() = default;
    66  
    67 Texture2D image;
    68 std::vector<Rect> frames;
    69 std::vector<std::string> names; // framesと同じ順(格子なら空) / same order as frames (empty for grids)
    70 // dequeは後ろに足しても要素が動かない:clip()が返したポインタはaddClipの後も使える
    71 // A deque never moves its elements when appending: pointers returned by clip() stay valid after addClip
    72 std::deque<AnimationClip> clips;
    73 mutable bool warnedIndex = false; // 範囲外の番号を一度知らせた / an out-of-range index was reported
    74 };

ファイル: a/src/tangents.hh | b/engine/include/engine/tangents.hh

前新
@@ -2,7 +2,7 @@
2 // Computing tangents (chapter 22): for every vertex, which surface directions a normal map's "right" and "up" are 2 // Computing tangents (chapter 22): for every vertex, which surface directions a normal map's "right" and "up" are
3 #pragma once 3 #pragma once
4   4  
5 #include "mesh.hh" 5 #include "engine/mesh.hh"
6   6  
7 #include <cstdint> 7 #include <cstdint>
8 #include <vector> 8 #include <vector>

ファイル: a/src/texture.hh | b/engine/include/engine/texture.hh

前新
@@ -13,13 +13,13 @@ struct TextureOptions {
13 bool mipmaps = true; // ミップマップを作る / build mipmaps 13 bool mipmaps = true; // ミップマップを作る / build mipmaps
14 // 色の画像(ベースカラー、発光)はtrue:GL_SRGB8_ALPHA8になり、読むときにGPUがリニアに直す(第21章)。 14 // 色の画像(ベースカラー、発光)はtrue:GL_SRGB8_ALPHA8になり、読むときにGPUがリニアに直す(第21章)。
15 // データ(法線、金属・粗さ、遮蔽、高さ)はfalseのまま:値そのものに意味がある 15 // データ(法線、金属・粗さ、遮蔽、高さ)はfalseのまま:値そのものに意味がある
16 // true for colour images (base colour, emission): the texture becomes GL_SRGB8_ALPHA8 and the GPU converts to 16 // true for color images (base color, emission): the texture becomes GL_SRGB8_ALPHA8 and the GPU converts to
17 // linear when sampling (chapter 21). Keep false for data (normals, metallic-roughness, occlusion, height): the 17 // linear when sampling (chapter 21). Keep false for data (normals, metallic-roughness, occlusion, height): the
18 // values themselves mean something 18 // values themselves mean something
19 bool srgb = false; 19 bool srgb = false;
20 // RGBにアルファを掛けてからアップロードする(乗算済みアルファ、第16章)。ミップマップもその値から作られる。 20 // RGBにアルファを掛けてからアップロードする(乗算済みアルファ、第16章)。ミップマップもその値から作られる。
21 // Multiply RGB by alpha before uploading (premultiplied alpha, chapter 16). Mipmaps are then built from those values. 21 // Multiply RGB by alpha before uploading (premultiplied alpha, chapter 16). Mipmaps are then built from those values.
22 // srgbなら、リニアに直してから掛けてsRGBに戻す(第21章) / with srgb the colour is converted to linear, multiplied and 22 // srgbなら、リニアに直してから掛けてsRGBに戻す(第21章) / with srgb the color is converted to linear, multiplied and
23 // converted back to sRGB (chapter 21) 23 // converted back to sRGB (chapter 21)
24 bool premultiplyAlpha = false; 24 bool premultiplyAlpha = false;
25 }; 25 };
@@ -63,7 +63,7 @@ public:
63 void setFilter(GLenum minFilter, GLenum magFilter); 63 void setFilter(GLenum minFilter, GLenum magFilter);
64 void setWrap(GLenum wrapS, GLenum wrapT); 64 void setWrap(GLenum wrapS, GLenum wrapT);
65 // GL_CLAMP_TO_BORDERで外側を読んだときの色(影の地図では1 = 一番奥 = 影なし、第23章) 65 // GL_CLAMP_TO_BORDERで外側を読んだときの色(影の地図では1 = 一番奥 = 影なし、第23章)
66 // The colour read outside with GL_CLAMP_TO_BORDER (1 = farthest = not in shadow for shadow maps, chapter 23) 66 // The color read outside with GL_CLAMP_TO_BORDER (1 = farthest = not in shadow for shadow maps, chapter 23)
67 void setBorderColor(float r, float g, float b, float a); 67 void setBorderColor(float r, float g, float b, float a);
68 // 深度テクスチャの比較モード(第23章):onなら sampler2DShadow で texture(s, vec3(uv, 深さ)) が 68 // 深度テクスチャの比較モード(第23章):onなら sampler2DShadow で texture(s, vec3(uv, 深さ)) が
69 // 「深さ <= 保存された深度」の結果(0か1、GL_LINEARなら周りの4テクセルの結果の補間)を返す 69 // 「深さ <= 保存された深度」の結果(0か1、GL_LINEARなら周りの4テクセルの結果の補間)を返す

ファイル: a/src/uniforms.hh | b/engine/include/engine/uniforms.hh

前新
@@ -2,7 +2,7 @@
2 // Uniform buffers (UBOs): blocks of uniforms shared by many shaders (chapter 19) 2 // Uniform buffers (UBOs): blocks of uniforms shared by many shaders (chapter 19)
3 #pragma once 3 #pragma once
4   4  
5 #include "buffer.hh" 5 #include "engine/buffer.hh"
6   6  
7 #include <linalg.hh> 7 #include <linalg.hh>
8   8  

ファイル: a/src/window.hh | b/engine/include/engine/window.hh

類似度:100% / 名前の変更元:src/window.hh / 名前の変更先:engine/include/engine/window.hh

ファイル: a/shaders/blur.frag | b/engine/shaders/blur.frag

前新
@@ -12,8 +12,8 @@ layout(location = 0) out vec4 out_color;
12 void main() { 12 void main() {
13 // 9タップのガウス(パスカルの三角形の12段目から両端の1と12を除いた物:中央924、左右に792, 495, 220, 66、/4070)を、 13 // 9タップのガウス(パスカルの三角形の12段目から両端の1と12を除いた物:中央924、左右に792, 495, 220, 66、/4070)を、
14 // 線型補間で5回の読み込みにまとめたもの:隣り合う2テクセルの間を読めば、GPUが重み付きで平均してくれる 14 // 線型補間で5回の読み込みにまとめたもの:隣り合う2テクセルの間を読めば、GPUが重み付きで平均してくれる
15 // A 9-tap Gaussian (row 12 of Pascal's triangle without the outer 1 and 12: centre 924, then 792, 495, 220, 66 on 15 // A 9-tap Gaussian (row 12 of Pascal's triangle without the outer 1 and 12: center 924, then 792, 495, 220, 66 on
16 // each side, /4070) folded into 5 reads with linear filtering: reading between two neighbouring texels makes the 16 // each side, /4070) folded into 5 reads with linear filtering: reading between two neighboring texels makes the
17 // GPU average them with the right weights 17 // GPU average them with the right weights
18 const float offsets[3] = float[](0.0, 1.3846153846, 3.2307692308); 18 const float offsets[3] = float[](0.0, 1.3846153846, 3.2307692308);
19 const float weights[3] = float[](0.2270270270, 0.3162162162, 0.0702702703); 19 const float weights[3] = float[](0.2270270270, 0.3162162162, 0.0702702703);

ファイル: a/shaders/depth.frag | b/engine/shaders/depth.frag

前新
@@ -1,5 +1,5 @@
1 #version 460 core 1 #version 460 core
2 // 深度バッファの値を灰色で見せる(頂点シェーダーはunlit.vert) / shows depth-buffer values as grey (vertex shader: unlit.vert) 2 // 深度バッファの値を灰色で見せる(頂点シェーダーはunlit.vert) / shows depth-buffer values as gray (vertex shader: unlit.vert)
3   3  
4 uniform int uDepthMode; // 1 = そのままの値(非線型) / the raw value (non-linear), 2 = 線型にした距離 / linearised distance 4 uniform int uDepthMode; // 1 = そのままの値(非線型) / the raw value (non-linear), 2 = 線型にした距離 / linearised distance
5 uniform float uNearPlane; // カメラのnearPlane / the camera's nearPlane 5 uniform float uNearPlane; // カメラのnearPlane / the camera's nearPlane

ファイル: a/shaders/envmap.frag | b/engine/shaders/envmap.frag

前新
@@ -16,7 +16,7 @@ layout(std140, binding = 0) uniform Camera {
16 }; 16 };
17 uniform int uEnvMode; // 0 = 反射 / reflection, 1 = 屈折 / refraction, 2 = フレネル(ガラス) / Fresnel (glass) 17 uniform int uEnvMode; // 0 = 反射 / reflection, 1 = 屈折 / refraction, 2 = フレネル(ガラス) / Fresnel (glass)
18 uniform float uIor; // 屈折率(ガラス1.52、水1.33) / index of refraction (glass 1.52, water 1.33) 18 uniform float uIor; // 屈折率(ガラス1.52、水1.33) / index of refraction (glass 1.52, water 1.33)
19 uniform vec3 uTint; // 反射・屈折の色 / colour of the reflection / refraction 19 uniform vec3 uTint; // 反射・屈折の色 / color of the reflection / refraction
20 uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / brightness of the sky (1 by day, dark at night) 20 uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / brightness of the sky (1 by day, dark at night)
21   21  
22 layout(location = 0) out vec4 out_color; 22 layout(location = 0) out vec4 out_color;

ファイル: a/shaders/ibl_brdf.frag | b/engine/shaders/ibl_brdf.frag

類似度:100% / 名前の変更元:shaders/ibl_brdf.frag / 名前の変更先:engine/shaders/ibl_brdf.frag

ファイル: a/shaders/ibl_irradiance.frag | b/engine/shaders/ibl_irradiance.frag

前新
@@ -3,7 +3,7 @@
3 // 結果は「白い拡散面がNを向いていたら反射する明るさ」(= 放射照度E / π)。pbr.fragはベースカラーを掛けるだけ 3 // 結果は「白い拡散面がNを向いていたら反射する明るさ」(= 放射照度E / π)。pbr.fragはベースカラーを掛けるだけ
4 // IBL (chapter 24): the irradiance cube map. For each direction N, average the sky light arriving from the whole 4 // IBL (chapter 24): the irradiance cube map. For each direction N, average the sky light arriving from the whole
5 // hemisphere weighted by cos θ. The result is "how bright a white diffuse surface facing N looks" (= irradiance E / π); 5 // hemisphere weighted by cos θ. The result is "how bright a white diffuse surface facing N looks" (= irradiance E / π);
6 // pbr.frag only multiplies it by the base colour 6 // pbr.frag only multiplies it by the base color
7 layout(binding = 0) uniform samplerCube uEnvironment; 7 layout(binding = 0) uniform samplerCube uEnvironment;
8 uniform int uFace; 8 uniform int uFace;
9 uniform float uSize; // この面の大きさ(ピクセル) / this face's size (pixels) 9 uniform float uSize; // この面の大きさ(ピクセル) / this face's size (pixels)

ファイル: a/shaders/ibl_prefilter.frag | b/engine/shaders/ibl_prefilter.frag

類似度:100% / 名前の変更元:shaders/ibl_prefilter.frag / 名前の変更先:engine/shaders/ibl_prefilter.frag

ファイル: a/shaders/pbr.frag | b/engine/shaders/pbr.frag

前新
@@ -72,7 +72,7 @@ layout(std140, binding = 1) uniform Lights {
72 DirectionalLight uDirLight; 72 DirectionalLight uDirLight;
73 PointLight uPointLights[MAX_POINT_LIGHTS]; 73 PointLight uPointLights[MAX_POINT_LIGHTS];
74 SpotLight uSpotLights[MAX_SPOT_LIGHTS]; 74 SpotLight uSpotLights[MAX_SPOT_LIGHTS];
75 vec3 uAmbient; // 環境光の色と明るさ / ambient light colour and brightness 75 vec3 uAmbient; // 環境光の色と明るさ / ambient light color and brightness
76 int uPointLightCount; // 使っている数 / how many are in use 76 int uPointLightCount; // 使っている数 / how many are in use
77 int uSpotLightCount; 77 int uSpotLightCount;
78 }; 78 };
@@ -100,7 +100,7 @@ layout(std140, binding = 2) uniform Shadow {
100 }; 100 };
101   101  
102 // 0 = 全部、1 = ベースカラー、2 = 金属度、3 = 粗さ、4 = 遮蔽、5 = 法線、6 = 直接光だけ、7 = IBLだけ、8 = 影 102 // 0 = 全部、1 = ベースカラー、2 = 金属度、3 = 粗さ、4 = 遮蔽、5 = 法線、6 = 直接光だけ、7 = IBLだけ、8 = 影
103 // 0 = everything, 1 = base colour, 2 = metallic, 3 = roughness, 4 = occlusion, 5 = normals, 6 = direct light only, 103 // 0 = everything, 1 = base color, 2 = metallic, 3 = roughness, 4 = occlusion, 5 = normals, 6 = direct light only,
104 // 7 = IBL only, 8 = shadow 104 // 7 = IBL only, 8 = shadow
105 uniform int uViewMode; 105 uniform int uViewMode;
106 // 0 = 直接光+IBL、1 = 直接光だけ、2 = IBLだけ / 0 = direct + IBL, 1 = direct only, 2 = IBL only 106 // 0 = 直接光+IBL、1 = 直接光だけ、2 = IBLだけ / 0 = direct + IBL, 1 = direct only, 2 = IBL only
@@ -173,14 +173,14 @@ vec3 fresnelSchlickRoughness(float cosTheta, vec3 f0, float roughness) {
173   173  
174 struct Surface { 174 struct Surface {
175 vec3 n, v; 175 vec3 n, v;
176 vec3 base; // ベースカラー(リニア) / base colour (linear) 176 vec3 base; // ベースカラー(リニア) / base color (linear)
177 float metallic, roughness; 177 float metallic, roughness;
178 vec3 f0; // 正面の反射率:非金属0.04、金属はベースカラー / reflectance at normal incidence: 0.04 for dielectrics, 178 vec3 f0; // 正面の反射率:非金属0.04、金属はベースカラー / reflectance at normal incidence: 0.04 for dielectrics,
179 // the base colour for metals 179 // the base color for metals
180 }; 180 };
181   181  
182 // 一つの光の直接光。radiance = 面に届く光(光の色 × 減衰 × 影) 182 // 一つの光の直接光。radiance = 面に届く光(光の色 × 減衰 × 影)
183 // Direct light from one light. radiance = the light reaching the surface (light colour × attenuation × shadow) 183 // Direct light from one light. radiance = the light reaching the surface (light color × attenuation × shadow)
184 vec3 directLight(Surface s, vec3 l, vec3 radiance) { 184 vec3 directLight(Surface s, vec3 l, vec3 radiance) {
185 float nDotL = max(dot(s.n, l), 0.0); 185 float nDotL = max(dot(s.n, l), 0.0);
186 if (nDotL <= 0.0) return vec3(0.0); 186 if (nDotL <= 0.0) return vec3(0.0);
@@ -196,7 +196,7 @@ vec3 directLight(Surface s, vec3 l, vec3 radiance) {
196 vec3 kd = (1.0 - f) * (1.0 - s.metallic); 196 vec3 kd = (1.0 - f) * (1.0 - s.metallic);
197 // このシリーズの光の色は「正面から照らした白い拡散面の明るさ」(Blinn-Phongと同じ意味)。物理的なランバートは 197 // このシリーズの光の色は「正面から照らした白い拡散面の明るさ」(Blinn-Phongと同じ意味)。物理的なランバートは
198 // base/πなので、光の強さをπ倍して同じ明るさにする 198 // base/πなので、光の強さをπ倍して同じ明るさにする
199 // Our light colours mean "how bright a white diffuse surface lit head-on looks" (as with Blinn-Phong). Physical 199 // Our light colors mean "how bright a white diffuse surface lit head-on looks" (as with Blinn-Phong). Physical
200 // Lambert is base/π, so the light is scaled by π to get the same brightness 200 // Lambert is base/π, so the light is scaled by π to get the same brightness
201 return (kd * s.base / PI + specular) * radiance * PI * nDotL; 201 return (kd * s.base / PI + specular) * radiance * PI * nDotL;
202 } 202 }
@@ -276,7 +276,7 @@ void main() {
276 uv = parallaxOcclusion(vUv, vec3(dot(toEye, tangent), dot(toEye, bitangent), dot(toEye, geometricNormal)), uvDx, uvDy); 276 uv = parallaxOcclusion(vUv, vec3(dot(toEye, tangent), dot(toEye, bitangent), dot(toEye, geometricNormal)), uvDx, uvDy);
277 } 277 }
278   278  
279 // ベースカラーとアルファ(第16・20章と同じ扱い) / base colour and alpha (handled as in chapters 16 and 20) 279 // ベースカラーとアルファ(第16・20章と同じ扱い) / base color and alpha (handled as in chapters 16 and 20)
280 vec4 baseSample = textureGrad(uBaseColorMap, uv, uvDx, uvDy); 280 vec4 baseSample = textureGrad(uBaseColorMap, uv, uvDx, uvDy);
281 float alpha = uMaterial.baseColor.a * baseSample.a; 281 float alpha = uMaterial.baseColor.a * baseSample.a;
282 float alphaWidth = fwidth(alpha); 282 float alphaWidth = fwidth(alpha);
@@ -328,7 +328,7 @@ void main() {
328   328  
329 //------------------------------------------------------------------ 329 //------------------------------------------------------------------
330 // IBL:空からの光。拡散 = 放射照度 × ベースカラー、鏡面 = ぼかした映り込み × (F0 · A + B)(スプリットサム) 330 // IBL:空からの光。拡散 = 放射照度 × ベースカラー、鏡面 = ぼかした映り込み × (F0 · A + B)(スプリットサム)
331 // IBL: light from the sky. Diffuse = irradiance × base colour, specular = blurred reflection × (F0 · A + B) (split sum) 331 // IBL: light from the sky. Diffuse = irradiance × base color, specular = blurred reflection × (F0 · A + B) (split sum)
332 //------------------------------------------------------------------ 332 //------------------------------------------------------------------
333 float nDotV = max(dot(s.n, s.v), 1e-4); 333 float nDotV = max(dot(s.n, s.v), 1e-4);
334 vec3 f = fresnelSchlickRoughness(nDotV, s.f0, s.roughness); 334 vec3 f = fresnelSchlickRoughness(nDotV, s.f0, s.roughness);

ファイル: a/shaders/phong.frag | b/engine/shaders/phong.frag

前新
@@ -2,14 +2,14 @@
2 in vec3 vWorldPos; 2 in vec3 vWorldPos;
3 in vec3 vNormal; 3 in vec3 vNormal;
4 in vec2 vUv; 4 in vec2 vUv;
5 in vec3 vTint; // インスタンスの色(第19章) / the instance colour (chapter 19) 5 in vec3 vTint; // インスタンスの色(第19章) / the instance color (chapter 19)
6 in vec4 vTangent; // ワールド座標の接線、w = 従法線の向き(第22章) / world-space tangent, w = bitangent sign (chapter 22) 6 in vec4 vTangent; // ワールド座標の接線、w = 従法線の向き(第22章) / world-space tangent, w = bitangent sign (chapter 22)
7   7  
8 // 表面の性質。色はそれぞれのマップと掛け合わされる / surface properties; each colour is multiplied with its map 8 // 表面の性質。色はそれぞれのマップと掛け合わされる / surface properties; each color is multiplied with its map
9 struct Material { 9 struct Material {
10 vec3 diffuse; // 拡散反射の色 / diffuse colour 10 vec3 diffuse; // 拡散反射の色 / diffuse color
11 vec3 specular; // 鏡面反射の色と強さ / specular colour and strength 11 vec3 specular; // 鏡面反射の色と強さ / specular color and strength
12 vec3 emission; // 発光の色 / emission colour 12 vec3 emission; // 発光の色 / emission color
13 float shininess; // 光沢度 / shininess 13 float shininess; // 光沢度 / shininess
14 float alpha; // 不透明度(diffuseマップのアルファと掛ける) / opacity (multiplied with the diffuse map's alpha) 14 float alpha; // 不透明度(diffuseマップのアルファと掛ける) / opacity (multiplied with the diffuse map's alpha)
15 int alphaMode; // 0 = 不透明 / opaque, 1 = マスク / mask (discard), 2 = ブレンド / blend 15 int alphaMode; // 0 = 不透明 / opaque, 1 = マスク / mask (discard), 2 = ブレンド / blend
@@ -73,7 +73,7 @@ layout(std140, binding = 1) uniform Lights {
73 DirectionalLight uDirLight; 73 DirectionalLight uDirLight;
74 PointLight uPointLights[MAX_POINT_LIGHTS]; 74 PointLight uPointLights[MAX_POINT_LIGHTS];
75 SpotLight uSpotLights[MAX_SPOT_LIGHTS]; 75 SpotLight uSpotLights[MAX_SPOT_LIGHTS];
76 vec3 uAmbient; // 環境光の色と明るさ / ambient light colour and brightness 76 vec3 uAmbient; // 環境光の色と明るさ / ambient light color and brightness
77 int uPointLightCount; // 使っている数 / how many are in use 77 int uPointLightCount; // 使っている数 / how many are in use
78 int uSpotLightCount; 78 int uSpotLightCount;
79 }; 79 };
@@ -145,8 +145,8 @@ struct Surface {
145 vec3 position; // ワールド座標 / world space 145 vec3 position; // ワールド座標 / world space
146 vec3 normal; // 単位ベクトル / unit vector 146 vec3 normal; // 単位ベクトル / unit vector
147 vec3 view; // 目へ向かう単位ベクトル / unit vector towards the eye 147 vec3 view; // 目へ向かう単位ベクトル / unit vector towards the eye
148 vec3 diffuse; // マップを掛けた拡散反射の色 / diffuse colour with the map applied 148 vec3 diffuse; // マップを掛けた拡散反射の色 / diffuse color with the map applied
149 vec3 specular; // マップを掛けた鏡面反射の色 / specular colour with the map applied 149 vec3 specular; // マップを掛けた鏡面反射の色 / specular color with the map applied
150 float shininess; 150 float shininess;
151 }; 151 };
152   152  
@@ -244,7 +244,7 @@ void main() {
244 vec4 base = textureGrad(uDiffuseMap, uv, uvDx, uvDy); 244 vec4 base = textureGrad(uDiffuseMap, uv, uvDx, uvDy);
245 float alpha = uMaterial.alpha * base.a; 245 float alpha = uMaterial.alpha * base.a;
246 // アルファが1ピクセルでどれだけ変わるか(分岐の前に:fwidthは隣のピクセルと一緒に計算する) 246 // アルファが1ピクセルでどれだけ変わるか(分岐の前に:fwidthは隣のピクセルと一緒に計算する)
247 // How much alpha changes across one pixel (before any branch: fwidth is computed together with the neighbours) 247 // How much alpha changes across one pixel (before any branch: fwidth is computed together with the neighbors)
248 float alphaWidth = fwidth(alpha); 248 float alphaWidth = fwidth(alpha);
249 if (uMaterial.alphaMode == ALPHA_MASK && uAlphaToCoverage) { 249 if (uMaterial.alphaMode == ALPHA_MASK && uAlphaToCoverage) {
250 // しきい値の前後1ピクセルで0→1になるように鋭くする(そのままだとテクスチャのぼけた縁で半透明が広がる) 250 // しきい値の前後1ピクセルで0→1になるように鋭くする(そのままだとテクスチャのぼけた縁で半透明が広がる)
@@ -253,7 +253,7 @@ void main() {
253 alpha = (alpha - uMaterial.alphaCutoff) / max(alphaWidth, 1e-4) + 0.5; 253 alpha = (alpha - uMaterial.alphaCutoff) / max(alphaWidth, 1e-4) + 0.5;
254 if (alpha <= 0.0) discard; 254 if (alpha <= 0.0) discard;
255 } else if (uMaterial.alphaMode == ALPHA_MASK && alpha < uMaterial.alphaCutoff) { 255 } else if (uMaterial.alphaMode == ALPHA_MASK && alpha < uMaterial.alphaCutoff) {
256 // マスク:しきい値未満は捨てる(色も深度も書かない) / mask: discard below the threshold (writes neither colour nor depth) 256 // マスク:しきい値未満は捨てる(色も深度も書かない) / mask: discard below the threshold (writes neither color nor depth)
257 discard; 257 discard;
258 } 258 }
259 // ブレンド:完全に透明なら深度も書かないように捨てる / blend: discard fully transparent pixels so they do not write depth 259 // ブレンド:完全に透明なら深度も書かないように捨てる / blend: discard fully transparent pixels so they do not write depth

ファイル: a/shaders/phong.vert | b/engine/shaders/phong.vert

前新
@@ -24,7 +24,7 @@ out vec3 vNormal;
24 out vec2 vUv; 24 out vec2 vUv;
25 out vec4 vTangent; // ワールド座標の接線と向き / world-space tangent and sign 25 out vec4 vTangent; // ワールド座標の接線と向き / world-space tangent and sign
26 // インスタンスごとの色(第19章)。インスタンシングでないときはこのユニフォーム(既定値は白) 26 // インスタンスごとの色(第19章)。インスタンシングでないときはこのユニフォーム(既定値は白)
27 // The per-instance colour (chapter 19). Without instancing it comes from this uniform (white by default) 27 // The per-instance color (chapter 19). Without instancing it comes from this uniform (white by default)
28 uniform vec3 uTint = vec3(1.0); 28 uniform vec3 uTint = vec3(1.0);
29 out vec3 vTint; 29 out vec3 vTint;
30   30  

ファイル: a/shaders/phong_instanced.vert | b/engine/shaders/phong_instanced.vert

前新
@@ -1,6 +1,6 @@
1 #version 460 core 1 #version 460 core
2 // インスタンシング用のphong.vert:インスタンスごとの行列と色を頂点属性で受け取る(フラグメントシェーダーはphong.frag) 2 // インスタンシング用のphong.vert:インスタンスごとの行列と色を頂点属性で受け取る(フラグメントシェーダーはphong.frag)
3 // phong.vert for instancing: the per-instance matrix and colour arrive as vertex attributes (fragment shader: phong.frag) 3 // phong.vert for instancing: the per-instance matrix and color arrive as vertex attributes (fragment shader: phong.frag)
4 layout(location = 0) in vec3 aPosition; 4 layout(location = 0) in vec3 aPosition;
5 layout(location = 1) in vec3 aNormal; 5 layout(location = 1) in vec3 aNormal;
6 layout(location = 2) in vec2 aUv; 6 layout(location = 2) in vec2 aUv;

ファイル: a/shaders/post.frag | b/engine/shaders/post.frag

前新
@@ -45,7 +45,7 @@ vec3 linearToSrgb(vec3 c) {
45 } 45 }
46   46  
47 // UVの位置の表示用の色(0〜1)。ガンマのモード0と3ではsRGBにした後、1と2ではまだリニア 47 // UVの位置の表示用の色(0〜1)。ガンマのモード0と3ではsRGBにした後、1と2ではまだリニア
48 // The display colour at a UV position (0..1): sRGB-encoded in gamma modes 0 and 3, still linear in 1 and 2 48 // The display color at a UV position (0..1): sRGB-encoded in gamma modes 0 and 3, still linear in 1 and 2
49 vec3 display(vec2 uv) { 49 vec3 display(vec2 uv) {
50 vec3 hdr = texture(uScene, uv).rgb; 50 vec3 hdr = texture(uScene, uv).rgb;
51 if (uPostView == 0) hdr += uBloomStrength * texture(uBloom, uv).rgb; 51 if (uPostView == 0) hdr += uBloomStrength * texture(uBloom, uv).rgb;

ファイル: a/shaders/post.vert | b/engine/shaders/post.vert

類似度:100% / 名前の変更元:shaders/post.vert / 名前の変更先:engine/shaders/post.vert

ファイル: a/shaders/shadow.frag | b/engine/shaders/shadow.frag

前新
@@ -1,9 +1,9 @@
1 #version 460 core 1 #version 460 core
2 // 影の地図のフラグメントシェーダー:色は書かない(深度はGPUが書く)。葉や草は切り抜く 2 // 影の地図のフラグメントシェーダー:色は書かない(深度はGPUが書く)。葉や草は切り抜く
3 // Shadow-map fragment shader: no colour is written (the GPU writes the depth). Leaves and grass are cut out 3 // Shadow-map fragment shader: no color is written (the GPU writes the depth). Leaves and grass are cut out
4 in vec2 vUv; 4 in vec2 vUv;
5   5  
6 layout(binding = 0) uniform sampler2D uBaseMap; // Maskのときのベースカラー(アルファ) / base colour for Mask (alpha) 6 layout(binding = 0) uniform sampler2D uBaseMap; // Maskのときのベースカラー(アルファ) / base color for Mask (alpha)
7 uniform bool uAlphaMask; // 切り抜くか / cut out? 7 uniform bool uAlphaMask; // 切り抜くか / cut out?
8 uniform float uAlphaCutoff; 8 uniform float uAlphaCutoff;
9 uniform float uBaseAlpha; // マテリアルのアルファ係数 / the material's alpha factor 9 uniform float uBaseAlpha; // マテリアルのアルファ係数 / the material's alpha factor

ファイル: a/shaders/shadow.vert | b/engine/shaders/shadow.vert

類似度:100% / 名前の変更元:shaders/shadow.vert / 名前の変更先:engine/shaders/shadow.vert

ファイル: a/shaders/shadow_debug.frag | b/engine/shaders/shadow_debug.frag

前新
@@ -1,6 +1,6 @@
1 #version 460 core 1 #version 460 core
2 // 影の地図を見せる(第23章):深度テクスチャを灰色で。比較なしのサンプラーオブジェクトで読む 2 // 影の地図を見せる(第23章):深度テクスチャを灰色で。比較なしのサンプラーオブジェクトで読む
3 // Shows the shadow map (chapter 23): the depth texture as grey. Read through a sampler object without comparison 3 // Shows the shadow map (chapter 23): the depth texture as gray. Read through a sampler object without comparison
4 in vec2 vUv; 4 in vec2 vUv;
5   5  
6 layout(binding = 0) uniform sampler2D uDepth; 6 layout(binding = 0) uniform sampler2D uDepth;

ファイル: a/shaders/skybox.frag | b/engine/shaders/skybox.frag

前新
@@ -7,7 +7,7 @@ layout(binding = 3) uniform samplerCube uSkybox;
7   7  
8 uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / brightness of the sky (1 by day, dark at night) 8 uniform vec3 uEnvironmentTint; // 空の明るさ(昼1、夜は暗く) / brightness of the sky (1 by day, dark at night)
9 uniform float uSunRadiance = 60.0; // 太陽の円盤の明るさ(平行光源の色の倍数、第21章) / the sun disc's brightness 9 uniform float uSunRadiance = 60.0; // 太陽の円盤の明るさ(平行光源の色の倍数、第21章) / the sun disc's brightness
10 // (a multiple of the directional light's colour, chapter 21) 10 // (a multiple of the directional light's color, chapter 21)
11   11  
12 struct DirectionalLight { 12 struct DirectionalLight {
13 vec3 direction; 13 vec3 direction;
@@ -27,7 +27,7 @@ struct SpotLight {
27 vec3 attenuation; 27 vec3 attenuation;
28 }; 28 };
29 // 光(結合点1):太陽の向きと色を使う。phong.fragと同じ宣言 / the lights (binding 1): for the sun's direction and 29 // 光(結合点1):太陽の向きと色を使う。phong.fragと同じ宣言 / the lights (binding 1): for the sun's direction and
30 // colour. The same declaration as phong.frag 30 // color. The same declaration as phong.frag
31 layout(std140, binding = 1) uniform Lights { 31 layout(std140, binding = 1) uniform Lights {
32 DirectionalLight uDirLight; 32 DirectionalLight uDirLight;
33 PointLight uPointLights[8]; 33 PointLight uPointLights[8];

ファイル: a/shaders/skybox.vert | b/engine/shaders/skybox.vert

類似度:100% / 名前の変更元:shaders/skybox.vert / 名前の変更先:engine/shaders/skybox.vert

ファイル: /dev/null | b/engine/shaders/sprite.frag

前新
@@ -0,0 +1,13 @@
    1 #version 460 core
    2 // スプライト(第25章):テクスチャ × 色。どちらも乗算済みアルファ(ブレンドは GL_ONE, GL_ONE_MINUS_SRC_ALPHA)
    3 // Sprites (chapter 25): texture × color, both premultiplied alpha (blending is GL_ONE, GL_ONE_MINUS_SRC_ALPHA)
    4 in vec2 vUv;
    5 in vec4 vColor;
    6  
    7 layout(binding = 0) uniform sampler2D uTexture;
    8  
    9 layout(location = 0) out vec4 out_color;
    10  
    11 void main() {
    12 out_color = texture(uTexture, vUv) * vColor;
    13 }

ファイル: /dev/null | b/engine/shaders/sprite.vert

前新
@@ -0,0 +1,18 @@
    1 #version 460 core
    2 // スプライト(第25章):頂点はCPUでワールド座標にしてある。ここでは2Dカメラの行列を掛けるだけ
    3 // Sprites (chapter 25): the CPU already put the vertices in world space; here we only apply the 2D camera's matrix
    4 layout(location = 0) in vec2 aPosition;
    5 layout(location = 1) in vec2 aUv;
    6 layout(location = 2) in vec4 aColor; // RGBA8 → 0〜1(sRGBの値、乗算前のアルファ) / 0..1 (sRGB values, straight alpha)
    7  
    8 uniform mat4 uViewProjection;
    9  
    10 out vec2 vUv;
    11 out vec4 vColor;
    12  
    13 void main() {
    14 vUv = aUv;
    15 // テクスチャは乗算済みアルファなので、掛ける色も乗算済みにする / the textures are premultiplied, so the tint is too
    16 vColor = vec4(aColor.rgb * aColor.a, aColor.a);
    17 gl_Position = uViewProjection * vec4(aPosition, 0.0, 1.0);
    18 }

ファイル: a/shaders/unlit.frag | b/engine/shaders/unlit.frag

前新
@@ -1,6 +1,6 @@
1 #version 460 core 1 #version 460 core
2 // ライティングなしの一色(光源の目印用)。HDRなので1より明るい色も使える(第21章) 2 // ライティングなしの一色(光源の目印用)。HDRなので1より明るい色も使える(第21章)
3 // One colour without lighting (for light markers). HDR, so colours brighter than 1 work (chapter 21) 3 // One color without lighting (for light markers). HDR, so colors brighter than 1 work (chapter 21)
4 uniform vec3 uColor; 4 uniform vec3 uColor;
5   5  
6 layout(location = 0) out vec4 out_color; 6 layout(location = 0) out vec4 out_color;

ファイル: a/shaders/unlit.vert | b/engine/shaders/unlit.vert

類似度:100% / 名前の変更元:shaders/unlit.vert / 名前の変更先:engine/shaders/unlit.vert

ファイル: /dev/null | b/engine/src/animation.cc

前新
@@ -0,0 +1,42 @@
    1 #include "engine/animation.hh"
    2  
    3 #include <algorithm>
    4 #include <cmath>
    5  
    6 void Animator::play(const AnimationClip *clip, bool restart) {
    7 if (clip == current && !restart) return;
    8 current = clip;
    9 elapsed = 0.0f;
    10 }
    11  
    12 void Animator::update(float dt) {
    13 if (!current) return;
    14 elapsed += dt * speed;
    15 // 繰り返すクリップは時間を一周分に収める(長く動かしてもfloatの精度が落ちない)。負のspeedは逆再生:
    16 // 繰り返すクリップは最後へ回り込み、onceのクリップは最初のコマで止まる
    17 // Looping clips keep the time within one cycle (float precision does not degrade over long runs). A negative
    18 // speed plays backwards: looping clips wrap around to the end, once-clips stop on the first frame
    19 float length = current->duration();
    20 if (current->loop && length > 0.0f) {
    21 elapsed = std::fmod(elapsed, length);
    22 if (elapsed < 0.0f) elapsed += length;
    23 } else if (elapsed < 0.0f) {
    24 elapsed = 0.0f;
    25 }
    26 }
    27  
    28 int Animator::frameIndex() const {
    29 if (!current || current->frames.empty()) return -1;
    30 int count = static_cast<int>(current->frames.size());
    31 int i = static_cast<int>(std::floor(elapsed * current->fps));
    32 return current->loop ? i % count : std::min(i, count - 1);
    33 }
    34  
    35 int Animator::frame() const {
    36 int i = frameIndex();
    37 return i < 0 ? -1 : current->frames[static_cast<size_t>(i)];
    38 }
    39  
    40 bool Animator::finished() const {
    41 return current && !current->loop && elapsed * current->fps >= static_cast<float>(current->frames.size());
    42 }

ファイル: a/src/buffer.cc | b/engine/src/buffer.cc

前新
@@ -1,4 +1,4 @@
1 #include "buffer.hh" 1 #include "engine/buffer.hh"
2   2  
3 #include <utility> 3 #include <utility>
4   4  

ファイル: a/src/camera.cc | b/engine/src/camera.cc

前新
@@ -1,4 +1,4 @@
1 #include "camera.hh" 1 #include "engine/camera.hh"
2   2  
3 #include <algorithm> 3 #include <algorithm>
4 #include <cmath> 4 #include <cmath>

ファイル: /dev/null | b/engine/src/camera2d.cc

前新
@@ -0,0 +1,57 @@
    1 #include "engine/camera2d.hh"
    2  
    3 #include <glad/glad.h>
    4  
    5 #include <algorithm>
    6 #include <cmath>
    7  
    8 Mat4 Camera2D::matrix() const {
    9 Vec2 c = centre;
    10 if (pixelSnap) {
    11 // 画面のピクセル(= 仮想ピクセル × zoom)単位に丸める / round to screen pixels (= virtual pixels × zoom)
    12 c = {std::round(c.x * zoom) / zoom, std::round(c.y * zoom) / zoom};
    13 }
    14 float hw = 0.5f * viewSize.x / zoom, hh = 0.5f * viewSize.y / zoom;
    15 // 上(top)が-hh、下(bottom)が+hh:yが下向きになる / top = -hh, bottom = +hh: y points down
    16 Mat4 projection = orthographicGl(-hw, hw, hh, -hh, -1.0f, 1.0f);
    17 // ビュー:中心を原点へ移し、カメラの回転の逆に回す / view: move the center to the origin and undo the camera's rotation
    18 return projection * rotateZ(-rotation) * translate({-c.x, -c.y, 0.0f});
    19 }
    20  
    21 Vec2 Camera2D::toWorld(Vec2 viewPoint) const {
    22 Vec2 fromCentre = (viewPoint - 0.5f * viewSize) / zoom;
    23 return centre + ::rotate(fromCentre, rotation);
    24 }
    25  
    26 Vec2 Camera2D::toView(Vec2 worldPoint) const {
    27 Vec2 local = ::rotate(worldPoint - centre, -rotation) * zoom;
    28 return local + 0.5f * viewSize;
    29 }
    30  
    31 Rect Camera2D::visibleRect() const {
    32 Vec2 corners[4] = {toWorld({0.0f, 0.0f}), toWorld({viewSize.x, 0.0f}), toWorld({viewSize.x, viewSize.y}),
    33 toWorld({0.0f, viewSize.y})};
    34 Vec2 lo = corners[0], hi = corners[0];
    35 for (Vec2 p : corners) {
    36 lo = {std::min(lo.x, p.x), std::min(lo.y, p.y)};
    37 hi = {std::max(hi.x, p.x), std::max(hi.y, p.y)};
    38 }
    39 return {lo.x, lo.y, hi.x - lo.x, hi.y - lo.y};
    40 }
    41  
    42 void Viewport::apply() const { glViewport(x, y, width, height); }
    43  
    44 Viewport letterbox(int windowWidth, int windowHeight, Vec2 viewSize, bool integerScale) {
    45 float scale = std::min(static_cast<float>(windowWidth) / viewSize.x, static_cast<float>(windowHeight) / viewSize.y);
    46 // 整数倍に切り捨て。ウィンドウが仮想解像度より小さければ1未満のまま / round down to a whole number; below 1 if the
    47 // window is smaller than the virtual resolution
    48 if (integerScale && scale >= 1.0f) scale = std::floor(scale);
    49 Viewport v;
    50 v.width = static_cast<int>(std::lround(viewSize.x * scale));
    51 v.height = static_cast<int>(std::lround(viewSize.y * scale));
    52 v.x = (windowWidth - v.width) / 2;
    53 v.top = (windowHeight - v.height) / 2;
    54 v.y = windowHeight - v.top - v.height; // GLは下から数える / GL counts from the bottom
    55 v.scale = scale;
    56 return v;
    57 }

ファイル: a/src/cubemap.cc | b/engine/src/cubemap.cc

前新
@@ -1,4 +1,4 @@
1 #include "cubemap.hh" 1 #include "engine/cubemap.hh"
2   2  
3 #include <stb_image.h> 3 #include <stb_image.h>
4   4  

ファイル: a/src/file_util.cc | b/engine/src/file_util.cc

前新
@@ -1,4 +1,4 @@
1 #include "file_util.hh" 1 #include "engine/file_util.hh"
2   2  
3 #include <fstream> 3 #include <fstream>
4 #include <iterator> 4 #include <iterator>

ファイル: a/src/framebuffer.cc | b/engine/src/framebuffer.cc

前新
@@ -1,4 +1,4 @@
1 #include "framebuffer.hh" 1 #include "engine/framebuffer.hh"
2   2  
3 #include <algorithm> 3 #include <algorithm>
4 #include <cstdio> 4 #include <cstdio>
@@ -14,7 +14,7 @@ void Framebuffer::createAttachments() {
14 actualSamples = 0; 14 actualSamples = 0;
15 int count = colorCount(); 15 int count = colorCount();
16 if (count > kMaxColorAttachments) { 16 if (count > kMaxColorAttachments) {
17 fprintf(stderr, "色の付け先が多すぎる / too many colour attachments: %d (max %d)\n", count, kMaxColorAttachments); 17 fprintf(stderr, "色の付け先が多すぎる / too many color attachments: %d (max %d)\n", count, kMaxColorAttachments);
18 count = spec.colorCount = kMaxColorAttachments; 18 count = spec.colorCount = kMaxColorAttachments;
19 } 19 }
20 GLenum drawBuffers[kMaxColorAttachments]; 20 GLenum drawBuffers[kMaxColorAttachments];
@@ -23,7 +23,7 @@ void Framebuffer::createAttachments() {
23 drawBuffers[i] = attachment; 23 drawBuffers[i] = attachment;
24 if (spec.samples > 0) { 24 if (spec.samples > 0) {
25 // マルチサンプルの色:ピクセルごとにsamples個の色を持つレンダーバッファ。テクスチャのように読めない 25 // マルチサンプルの色:ピクセルごとにsamples個の色を持つレンダーバッファ。テクスチャのように読めない
26 // Multisampled colour: a renderbuffer with `samples` colours per pixel. It cannot be read like a texture 26 // Multisampled color: a renderbuffer with `samples` colors per pixel. It cannot be read like a texture
27 GLuint &rb = colorSamples[static_cast<size_t>(i)]; 27 GLuint &rb = colorSamples[static_cast<size_t>(i)];
28 glCreateRenderbuffers(1, &rb); 28 glCreateRenderbuffers(1, &rb);
29 glNamedRenderbufferStorageMultisample(rb, spec.samples, spec.colorFormat, w, h); 29 glNamedRenderbufferStorageMultisample(rb, spec.samples, spec.colorFormat, w, h);
@@ -33,7 +33,7 @@ void Framebuffer::createAttachments() {
33 glGetNamedRenderbufferParameteriv(rb, GL_RENDERBUFFER_SAMPLES, &actualSamples); 33 glGetNamedRenderbufferParameteriv(rb, GL_RENDERBUFFER_SAMPLES, &actualSamples);
34 } else { 34 } else {
35 // 色:ミップマップなしのテクスチャ。端の外を読まないようにCLAMP_TO_EDGE(ぼかしのカーネルが端で反対側を拾わない) 35 // 色:ミップマップなしのテクスチャ。端の外を読まないようにCLAMP_TO_EDGE(ぼかしのカーネルが端で反対側を拾わない)
36 // Colour: a texture without mipmaps. CLAMP_TO_EDGE so blur kernels at the border do not pick up the opposite side 36 // Color: a texture without mipmaps. CLAMP_TO_EDGE so blur kernels at the border do not pick up the opposite side
37 Texture2D &t = colorTextures[static_cast<size_t>(i)]; 37 Texture2D &t = colorTextures[static_cast<size_t>(i)];
38 t = Texture2D(w, h, spec.colorFormat, 1); 38 t = Texture2D(w, h, spec.colorFormat, 1);
39 t.setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); 39 t.setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
@@ -46,7 +46,7 @@ void Framebuffer::createAttachments() {
46 // Fragment output location i goes to attachment i (by default only ATTACHMENT0 is written) 46 // Fragment output location i goes to attachment i (by default only ATTACHMENT0 is written)
47 glNamedFramebufferDrawBuffers(fbo, count, drawBuffers); 47 glNamedFramebufferDrawBuffers(fbo, count, drawBuffers);
48 } else { 48 } else {
49 // 色を描かない(例:影の深度だけ、第23章) / no colour drawn (e.g. shadow depth only, chapter 23) 49 // 色を描かない(例:影の深度だけ、第23章) / no color drawn (e.g. shadow depth only, chapter 23)
50 glNamedFramebufferDrawBuffer(fbo, GL_NONE); 50 glNamedFramebufferDrawBuffer(fbo, GL_NONE);
51 glNamedFramebufferReadBuffer(fbo, GL_NONE); 51 glNamedFramebufferReadBuffer(fbo, GL_NONE);
52 } 52 }
@@ -64,8 +64,8 @@ void Framebuffer::createAttachments() {
64 } else if (spec.depthStencilFormat != 0) { 64 } else if (spec.depthStencilFormat != 0) {
65 glCreateRenderbuffers(1, &depthStencil); 65 glCreateRenderbuffers(1, &depthStencil);
66 // 色と深度のサンプル数は同じでなければならない(違うとフレームバッファが不完全)。要求ではなく、色が実際に 66 // 色と深度のサンプル数は同じでなければならない(違うとフレームバッファが不完全)。要求ではなく、色が実際に
67 // 貰った数を使う(色が無ければ要求の数) / colour and depth must have the same number of samples (otherwise the 67 // 貰った数を使う(色が無ければ要求の数) / color and depth must have the same number of samples (otherwise the
68 // framebuffer is incomplete): use the count the colour actually got, not the request (the request if no colour) 68 // framebuffer is incomplete): use the count the color actually got, not the request (the request if no color)
69 int depthSamples = actualSamples > 0 ? actualSamples : spec.samples; 69 int depthSamples = actualSamples > 0 ? actualSamples : spec.samples;
70 if (depthSamples > 0) glNamedRenderbufferStorageMultisample(depthStencil, depthSamples, spec.depthStencilFormat, w, h); 70 if (depthSamples > 0) glNamedRenderbufferStorageMultisample(depthStencil, depthSamples, spec.depthStencilFormat, w, h);
71 else glNamedRenderbufferStorage(depthStencil, spec.depthStencilFormat, w, h); 71 else glNamedRenderbufferStorage(depthStencil, spec.depthStencilFormat, w, h);
@@ -91,7 +91,7 @@ void Framebuffer::destroyAttachments() {
91 } 91 }
92   92  
93 bool Framebuffer::resize(int width, int height) { 93 bool Framebuffer::resize(int width, int height) {
94 if (width <= 0 || height <= 0) return false; // 最小化中 / minimised 94 if (width <= 0 || height <= 0) return false; // 最小化中 / minimized
95 if (width == w && height == h) return complete(); 95 if (width == w && height == h) return complete();
96 w = width; 96 w = width;
97 h = height; 97 h = height;
@@ -108,7 +108,7 @@ bool Framebuffer::complete() const {
108   108  
109 void Framebuffer::blitTo(const Framebuffer &target, GLbitfield mask, GLenum filter) const { 109 void Framebuffer::blitTo(const Framebuffer &target, GLbitfield mask, GLenum filter) const {
110 // 読む側の四角形 → 書く側の四角形。読む色はglNamedFramebufferReadBuffer(既定はGL_COLOR_ATTACHMENT0) 110 // 読む側の四角形 → 書く側の四角形。読む色はglNamedFramebufferReadBuffer(既定はGL_COLOR_ATTACHMENT0)
111 // source rectangle → destination rectangle. The colour read comes from glNamedFramebufferReadBuffer 111 // source rectangle → destination rectangle. The color read comes from glNamedFramebufferReadBuffer
112 // (GL_COLOR_ATTACHMENT0 by default) 112 // (GL_COLOR_ATTACHMENT0 by default)
113 int colors = (mask & GL_COLOR_BUFFER_BIT) ? std::min(colorCount(), target.colorCount()) : 0; 113 int colors = (mask & GL_COLOR_BUFFER_BIT) ? std::min(colorCount(), target.colorCount()) : 0;
114 if (colors <= 1) { 114 if (colors <= 1) {
@@ -116,7 +116,7 @@ void Framebuffer::blitTo(const Framebuffer &target, GLbitfield mask, GLenum filt
116 return; 116 return;
117 } 117 }
118 // 複数の色:読む色(ReadBuffer)と書く色(DrawBuffer)を一つずつ選んでコピーし、最後に元に戻す 118 // 複数の色:読む色(ReadBuffer)と書く色(DrawBuffer)を一つずつ選んでコピーし、最後に元に戻す
119 // Several colours: pick one read buffer and one draw buffer at a time, copy, and restore them afterwards 119 // Several colors: pick one read buffer and one draw buffer at a time, copy, and restore them afterwards
120 for (int i = 0; i < colors; ++i) { 120 for (int i = 0; i < colors; ++i) {
121 GLenum attachment = GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(i); 121 GLenum attachment = GL_COLOR_ATTACHMENT0 + static_cast<GLenum>(i);
122 glNamedFramebufferReadBuffer(fbo, attachment); 122 glNamedFramebufferReadBuffer(fbo, attachment);

ファイル: a/src/gl_debug.cc | b/engine/src/gl_debug.cc

前新
@@ -1,4 +1,4 @@
1 #include "gl_debug.hh" 1 #include "engine/gl_debug.hh"
2   2  
3 #include <glad/glad.h> 3 #include <glad/glad.h>
4   4  

ファイル: a/src/gltf.cc | b/engine/src/gltf.cc

前新
@@ -1,7 +1,7 @@
1 #include "gltf.hh" 1 #include "engine/gltf.hh"
2   2  
3 #include "file_util.hh" 3 #include "engine/file_util.hh"
4 #include "json.hh" 4 #include "engine/json.hh"
5   5  
6 #include <cstdio> 6 #include <cstdio>
7 #include <cstring> 7 #include <cstring>

ファイル: a/src/gpu_timer.cc | b/engine/src/gpu_timer.cc

前新
@@ -1,4 +1,4 @@
1 #include "gpu_timer.hh" 1 #include "engine/gpu_timer.hh"
2   2  
3 GpuTimer::GpuTimer() { glCreateQueries(GL_TIME_ELAPSED, kQueries, queries); } 3 GpuTimer::GpuTimer() { glCreateQueries(GL_TIME_ELAPSED, kQueries, queries); }
4   4  

ファイル: a/src/ibl.cc | b/engine/src/ibl.cc

前新
@@ -1,4 +1,4 @@
1 #include "ibl.hh" 1 #include "engine/ibl.hh"
2   2  
3 #include <algorithm> 3 #include <algorithm>
4 #include <chrono> 4 #include <chrono>
@@ -8,7 +8,7 @@
8   8  
9 namespace { 9 namespace {
10   10  
11 // 面ごとに描くための、色の付け先だけのFBO(RAII) / an FBO with only a colour attachment, for drawing face by face (RAII) 11 // 面ごとに描くための、色の付け先だけのFBO(RAII) / an FBO with only a color attachment, for drawing face by face (RAII)
12 struct FaceTarget { 12 struct FaceTarget {
13 GLuint fbo = 0, vao = 0; 13 GLuint fbo = 0, vao = 0;
14 FaceTarget() { 14 FaceTarget() {
@@ -43,9 +43,9 @@ double elapsedMs(std::chrono::steady_clock::time_point start) {
43 } // namespace 43 } // namespace
44   44  
45 std::optional<Ibl> Ibl::build(const Cubemap &environment, const IblSettings &settings) { 45 std::optional<Ibl> Ibl::build(const Cubemap &environment, const IblSettings &settings) {
46 std::optional<Shader> irradianceShader = Shader::load("shaders/post.vert", "shaders/ibl_irradiance.frag"); 46 std::optional<Shader> irradianceShader = Shader::load("engine/shaders/post.vert", "engine/shaders/ibl_irradiance.frag");
47 std::optional<Shader> prefilterShader = Shader::load("shaders/post.vert", "shaders/ibl_prefilter.frag"); 47 std::optional<Shader> prefilterShader = Shader::load("engine/shaders/post.vert", "engine/shaders/ibl_prefilter.frag");
48 std::optional<Shader> brdfShader = Shader::load("shaders/post.vert", "shaders/ibl_brdf.frag"); 48 std::optional<Shader> brdfShader = Shader::load("engine/shaders/post.vert", "engine/shaders/ibl_brdf.frag");
49 if (!irradianceShader || !prefilterShader || !brdfShader) return std::nullopt; 49 if (!irradianceShader || !prefilterShader || !brdfShader) return std::nullopt;
50   50  
51 Ibl ibl; 51 Ibl ibl;

ファイル: a/src/json.cc | b/engine/src/json.cc

前新
@@ -1,4 +1,4 @@
1 #include "json.hh" 1 #include "engine/json.hh"
2   2  
3 #include <cmath> 3 #include <cmath>
4 #include <cstdlib> 4 #include <cstdlib>

ファイル: a/src/lights.cc | b/engine/src/lights.cc

前新
@@ -1,4 +1,4 @@
1 #include "lights.hh" 1 #include "engine/lights.hh"
2   2  
3 #include <cmath> 3 #include <cmath>
4 #include <cstdio> 4 #include <cstdio>

ファイル: a/src/material.cc | b/engine/src/material.cc

前新
@@ -1,4 +1,4 @@
1 #include "material.hh" 1 #include "engine/material.hh"
2   2  
3 void Material::apply(const Shader &shader, const Texture2D &white) const { 3 void Material::apply(const Shader &shader, const Texture2D &white) const {
4 // 構造体のユニフォームは「変数名.メンバー名」で一つずつ設定する 4 // 構造体のユニフォームは「変数名.メンバー名」で一つずつ設定する

ファイル: a/src/mesh.cc | b/engine/src/mesh.cc

前新
@@ -1,4 +1,4 @@
1 #include "mesh.hh" 1 #include "engine/mesh.hh"
2   2  
3 #include <utility> 3 #include <utility>
4   4  

ファイル: a/src/model.cc | b/engine/src/model.cc

前新
@@ -1,6 +1,6 @@
1 #include "model.hh" 1 #include "engine/model.hh"
2   2  
3 #include "tangents.hh" 3 #include "engine/tangents.hh"
4   4  
5 #include <algorithm> 5 #include <algorithm>
6 #include <cmath> 6 #include <cmath>
@@ -26,7 +26,7 @@ static Material phongFromPbr(const GltfMaterial &m, float metallicScale, float r
26 // 金属は拡散反射をしない / metals have no diffuse reflection 26 // 金属は拡散反射をしない / metals have no diffuse reflection
27 p.diffuse = (1.0f - metallic) * base; 27 p.diffuse = (1.0f - metallic) * base;
28 // 正面から見た反射率F0:非金属は約4%、金属は自分の色 / reflectance at normal incidence F0: ~4% for non-metals, 28 // 正面から見た反射率F0:非金属は約4%、金属は自分の色 / reflectance at normal incidence F0: ~4% for non-metals,
29 // the base colour for metals 29 // the base color for metals
30 Vec3 f0 = lerp({0.04f, 0.04f, 0.04f}, base, metallic); 30 Vec3 f0 = lerp({0.04f, 0.04f, 0.04f}, base, metallic);
31 // 粗さ → 光沢度:Blinn-Phongとベックマン分布の対応 n = 2/α² − 2(α = 粗さ²) 31 // 粗さ → 光沢度:Blinn-Phongとベックマン分布の対応 n = 2/α² − 2(α = 粗さ²)
32 // roughness → shininess: the Blinn-Phong / Beckmann correspondence n = 2/α² − 2 (α = roughness²) 32 // roughness → shininess: the Blinn-Phong / Beckmann correspondence n = 2/α² − 2 (α = roughness²)
@@ -176,7 +176,7 @@ std::optional<Model> Model::load(const std::string &path) {
176 // Textures: decode the embedded PNG/JPEG and upload it. glTF UVs start at the image's top-left: no flipping 176 // Textures: decode the embedded PNG/JPEG and upload it. glTF UVs start at the image's top-left: no flipping
177 std::vector<Vec4> averages(g.textures.size(), Vec4{1.0f, 1.0f, 1.0f, 1.0f}); 177 std::vector<Vec4> averages(g.textures.size(), Vec4{1.0f, 1.0f, 1.0f, 1.0f});
178 // どのテクスチャが色か(第21章):ベースカラーと発光はsRGB、ほかはデータなのでリニア(glTFの仕様どおり) 178 // どのテクスチャが色か(第21章):ベースカラーと発光はsRGB、ほかはデータなのでリニア(glTFの仕様どおり)
179 // Which textures hold colours (chapter 21): base colour and emissive are sRGB, the rest is data and linear (as the 179 // Which textures hold colors (chapter 21): base color and emissive are sRGB, the rest is data and linear (as the
180 // glTF spec says) 180 // glTF spec says)
181 std::vector<int> colorUse(g.textures.size(), 0), dataUse(g.textures.size(), 0); 181 std::vector<int> colorUse(g.textures.size(), 0), dataUse(g.textures.size(), 0);
182 auto mark = [](std::vector<int> &use, const GltfTextureRef &ref) { 182 auto mark = [](std::vector<int> &use, const GltfTextureRef &ref) {
@@ -208,10 +208,10 @@ std::optional<Model> Model::load(const std::string &path) {
208 static_cast<float>(sum[2] / pixels), static_cast<float>(sum[3] / pixels)}; 208 static_cast<float>(sum[2] / pixels), static_cast<float>(sum[3] / pixels)};
209   209  
210 // 同じテクスチャを色とデータの両方に使うファイルもありうる:その場合はリニアにして警告する 210 // 同じテクスチャを色とデータの両方に使うファイルもありうる:その場合はリニアにして警告する
211 // A file may use the same texture both as a colour and as data: then it stays linear, with a warning 211 // A file may use the same texture both as a color and as data: then it stays linear, with a warning
212 bool srgb = colorUse[i] > 0 && dataUse[i] == 0; 212 bool srgb = colorUse[i] > 0 && dataUse[i] == 0;
213 if (colorUse[i] > 0 && dataUse[i] > 0) 213 if (colorUse[i] > 0 && dataUse[i] > 0)
214 fprintf(stderr, "%s: textures[%zu] は色にもデータにも使われている:リニアで読む / is used both as colour and as data: " 214 fprintf(stderr, "%s: textures[%zu] は色にもデータにも使われている:リニアで読む / is used both as color and as data: "
215 "loaded as linear\n", path.c_str(), i); 215 "loaded as linear\n", path.c_str(), i);
216 Texture2D texture = Texture2D::fromPixels(image->rgba.data(), image->width, image->height, 216 Texture2D texture = Texture2D::fromPixels(image->rgba.data(), image->width, image->height,
217 {.flipY = false, .mipmaps = true, .srgb = srgb}); 217 {.flipY = false, .mipmaps = true, .srgb = srgb});
@@ -234,7 +234,7 @@ std::optional<Model> Model::load(const std::string &path) {
234 } 234 }
235 // マテリアルのないプリミティブ用。glTFの既定(金属度1、粗さ1)だと拡散色の無い淡い塊になるので、白いプラスチックにする 235 // マテリアルのないプリミティブ用。glTFの既定(金属度1、粗さ1)だと拡散色の無い淡い塊になるので、白いプラスチックにする
236 // For primitives without a material. glTF's default (metallic 1, roughness 1) would be a pale blob with no diffuse 236 // For primitives without a material. glTF's default (metallic 1, roughness 1) would be a pale blob with no diffuse
237 // colour here, so use white plastic 237 // color here, so use white plastic
238 model.defaultMaterial.pbr.name = "(default)"; 238 model.defaultMaterial.pbr.name = "(default)";
239 model.defaultMaterial.pbr.metallicFactor = 0.0f; 239 model.defaultMaterial.pbr.metallicFactor = 0.0f;
240 model.defaultMaterial.pbr.roughnessFactor = 0.5f; 240 model.defaultMaterial.pbr.roughnessFactor = 0.5f;
@@ -390,7 +390,7 @@ void Model::drawItems(const std::vector<DrawItem> &items, const Shader &shader,
390 m.apply(shader, *white); 390 m.apply(shader, *white);
391 } else if (white) { 391 } else if (white) {
392 Material m = md.phong; 392 Material m = md.phong;
393 m.diffuseMap = texture(md.pbr.baseColorTexture.index); // 色 = 係数 × テクスチャ / colour = factor × texture 393 m.diffuseMap = texture(md.pbr.baseColorTexture.index); // 色 = 係数 × テクスチャ / color = factor × texture
394 m.emissionMap = texture(md.pbr.emissiveTexture.index); 394 m.emissionMap = texture(md.pbr.emissiveTexture.index);
395 m.normalMap = texture(md.pbr.normalTexture.index); // 第22章 / chapter 22 395 m.normalMap = texture(md.pbr.normalTexture.index); // 第22章 / chapter 22
396 m.normalScale = md.pbr.normalTexture.scale; 396 m.normalScale = md.pbr.normalTexture.scale;

ファイル: a/src/pbr_material.cc | b/engine/src/pbr_material.cc

前新
@@ -1,4 +1,4 @@
1 #include "pbr_material.hh" 1 #include "engine/pbr_material.hh"
2   2  
3 void PbrMaterial::apply(const Shader &shader, const Texture2D &white) const { 3 void PbrMaterial::apply(const Shader &shader, const Texture2D &white) const {
4 shader.set("uMaterial.baseColor", baseColor); 4 shader.set("uMaterial.baseColor", baseColor);

ファイル: /dev/null | b/engine/src/pixel_canvas.cc

前新
@@ -0,0 +1,26 @@
    1 #include "engine/pixel_canvas.hh"
    2  
    3 // 色はRGBA8(2Dの色はsRGBの値のまま扱う、第25章)。スプライトは並べ替えで重ねるので深度は要らない
    4 // The color is RGBA8 (2D colors stay sRGB-encoded values, chapter 25). Sprites are layered by sorting, so no depth
    5 PixelCanvas::PixelCanvas(int width, int height)
    6 : fbo(width, height, {.colorFormat = GL_RGBA8, .depthStencilFormat = 0}) {
    7 fbo.color().setFilter(GL_NEAREST, GL_NEAREST);
    8 }
    9  
    10 void PixelCanvas::begin(Vec4 clearColor) const {
    11 fbo.bind();
    12 glClearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w);
    13 glClear(GL_COLOR_BUFFER_BIT);
    14 }
    15  
    16 Viewport PixelCanvas::present(int windowWidth, int windowHeight, bool integerScale, Vec4 barColor) const {
    17 Viewport v = letterbox(windowWidth, windowHeight, size(), integerScale);
    18 Framebuffer::bindDefault(windowWidth, windowHeight);
    19 glClearColor(barColor.x, barColor.y, barColor.z, barColor.w);
    20 glClear(GL_COLOR_BUFFER_BIT);
    21 // 0 = 既定のフレームバッファ。GL_NEARESTなのでピクセルがぼけずに大きくなる
    22 // 0 = the default framebuffer. GL_NEAREST keeps the pixels sharp while enlarging
    23 glBlitNamedFramebuffer(fbo.id(), 0, 0, 0, fbo.width(), fbo.height(), v.x, v.y, v.x + v.width, v.y + v.height,
    24 GL_COLOR_BUFFER_BIT, GL_NEAREST);
    25 return v;
    26 }

ファイル: /dev/null | b/engine/src/renderer3d.cc

前新
@@ -0,0 +1,151 @@
    1 #include "engine/renderer3d.hh"
    2  
    3 #include <algorithm>
    4 #include <cmath>
    5  
    6 Mat4 lightSpaceMatrix(Vec3 lightDir, Vec3 centre, float radius, int mapSize, float &depthRange) {
    7 Vec3 d = normalize(lightDir);
    8 Vec3 up = std::fabs(d.y) > 0.99f ? Vec3{0.0f, 0.0f, 1.0f} : Vec3{0.0f, 1.0f, 0.0f};
    9 Mat4 view = lookAt({0.0f, 0.0f, 0.0f}, d, up); // 回転だけ:光の向きを-Zに / rotation only: the light along -Z
    10 Vec4 c = view * Vec4{centre.x, centre.y, centre.z, 1.0f};
    11 float texel = 2.0f * radius / static_cast<float>(mapSize);
    12 float cx = std::floor(c.x / texel) * texel, cy = std::floor(c.y / texel) * texel;
    13 // 奥行き:球の手前に20 m余分に(箱の外の、光と球の間にある物も影を落とすように)
    14 // Depth: 20 m extra in front of the sphere (so casters between the light and the sphere still cast)
    15 float nearPlane = -c.z - radius - 20.0f, farPlane = -c.z + radius;
    16 depthRange = farPlane - nearPlane;
    17 return orthographicGl(cx - radius, cx + radius, cy - radius, cy + radius, nearPlane, farPlane) * view;
    18 }
    19  
    20 BoundingSphere frustumSphere(Vec3 eye, Vec3 forward, float fovY, float aspect, float nearDist, float farDist) {
    21 Vec3 f = normalize(forward);
    22 Vec3 r = normalize(cross(f, std::fabs(f.y) > 0.99f ? Vec3{0.0f, 0.0f, -1.0f} : Vec3{0.0f, 1.0f, 0.0f}));
    23 Vec3 u = cross(r, f);
    24 float th = std::tan(0.5f * fovY);
    25 Vec3 corners[8];
    26 int k = 0;
    27 for (float dist : {nearDist, farDist})
    28 for (float sy : {-1.0f, 1.0f})
    29 for (float sx : {-1.0f, 1.0f}) corners[k++] = eye + dist * f + (sx * dist * th * aspect) * r + (sy * dist * th) * u;
    30 BoundingSphere s{{0.0f, 0.0f, 0.0f}, 0.0f};
    31 for (Vec3 c : corners) s.centre = s.centre + 0.125f * c;
    32 for (Vec3 c : corners) s.radius = std::max(s.radius, length(c - s.centre));
    33 return s;
    34 }
    35  
    36 void applyShadowBias(ShadowBlock &block, const ShadowBias &bias, float radius, int mapSize, float depthRange) {
    37 float unit = bias.inTexels ? 2.0f * radius / static_cast<float>(mapSize) : 1.0f; // m
    38 block.bias = bias.constant * unit / depthRange;
    39 block.slopeBias = bias.slope * unit / depthRange;
    40 block.normalOffset = bias.normalOffset * unit;
    41 }
    42  
    43 //------------------------------------------------------------------
    44 // ShadowMap
    45 //------------------------------------------------------------------
    46  
    47 // 色なし、深度だけのテクスチャ(32ビット浮動小数点)。比較モード・GL_LINEAR・外側は1
    48 // No color, only a depth texture (32-bit float). Comparison mode, GL_LINEAR, 1 outside
    49 static const FramebufferSpec kShadowSpec = {.colorFormat = 0, .depthStencilFormat = GL_DEPTH_COMPONENT32F,
    50 .depthTexture = true};
    51  
    52 ShadowMap::ShadowMap(int size) : fbo(size, size, kShadowSpec) {}
    53  
    54 void ShadowMap::resize(int size) { fbo.resize(size, size); }
    55  
    56 bool ShadowMap::begin(Vec3 lightDir, const BoundingSphere &fit, const ShadowBias &bias, ShadowFilter filter,
    57 bool enabled) {
    58 float depthRange = 1.0f;
    59 current.lightSpace = lightSpaceMatrix(lightDir, fit.centre, fit.radius, fbo.width(), depthRange);
    60 applyShadowBias(current, bias, fit.radius, fbo.width(), depthRange);
    61 current.filter = static_cast<int>(filter);
    62 current.texel = {1.0f / static_cast<float>(fbo.width()), 1.0f / static_cast<float>(fbo.height())};
    63 current.enabled = enabled ? 1 : 0;
    64 ubo.update(current);
    65 texelMetres = 2.0f * fit.radius / static_cast<float>(fbo.width());
    66 // 硬い影はGL_NEAREST、それ以外はGL_LINEAR(比較の結果を2×2で補間) / hard shadows use GL_NEAREST, the others
    67 // GL_LINEAR (the comparison results are blended 2 × 2)
    68 GLenum mode = filter == ShadowFilter::Hard ? GL_NEAREST : GL_LINEAR;
    69 fbo.depth().setFilter(mode, mode);
    70 if (!enabled) return false;
    71 fbo.bind();
    72 glEnable(GL_DEPTH_TEST);
    73 glDepthMask(GL_TRUE);
    74 glClear(GL_DEPTH_BUFFER_BIT);
    75 glEnable(GL_CULL_FACE);
    76 glCullFace(GL_BACK);
    77 return true;
    78 }
    79  
    80 void ShadowMap::end() const { fbo.depth().bind(kUnit); }
    81  
    82 //------------------------------------------------------------------
    83 // PostChain
    84 //------------------------------------------------------------------
    85  
    86 std::optional<PostChain> PostChain::create(int width, int height, const PostChainSettings &settings) {
    87 PostChain chain;
    88 chain.config = settings;
    89 chain.post = Shader::load("engine/shaders/post.vert", "engine/shaders/post.frag");
    90 chain.blur = Shader::load("engine/shaders/post.vert", "engine/shaders/blur.frag");
    91 if (!chain.post || !chain.blur) return std::nullopt;
    92 if (!chain.post->checkUniformBlock("Post", sizeof(PostBlock))) return std::nullopt;
    93 // 付け先0 = 場面の色、付け先1 = ブルームにする明るい部分(MRT) / attachment 0 = the scene color, attachment 1 = the
    94 // bright part for bloom (MRT)
    95 const FramebufferSpec hdrSpec = {.colorFormat = settings.format, .colorCount = 2};
    96 FramebufferSpec msaaSpec = hdrSpec;
    97 msaaSpec.samples = settings.samples;
    98 if (settings.samples > 0) chain.msaaFbo = Framebuffer(width, height, msaaSpec);
    99 chain.sceneFbo = Framebuffer(width, height, hdrSpec);
    100 // ブルームのぼかしは半分の大きさで(4分の1のピクセル数:速く、広くぼける)。深度は要らない
    101 // The bloom blur runs at half size (a quarter of the pixels: faster, and it spreads further). No depth needed
    102 const FramebufferSpec bloomSpec = {.colorFormat = settings.format, .depthStencilFormat = 0};
    103 for (Framebuffer &f : chain.bloomFbo) f = Framebuffer(width / 2, height / 2, bloomSpec);
    104 if ((settings.samples > 0 && !chain.msaaFbo.complete()) || !chain.sceneFbo.complete() ||
    105 !chain.bloomFbo[0].complete() || !chain.bloomFbo[1].complete())
    106 return std::nullopt;
    107 chain.ubo.emplace(kPostBinding);
    108 return chain;
    109 }
    110  
    111 void PostChain::resize(int width, int height) {
    112 if (config.samples > 0) msaaFbo.resize(width, height);
    113 sceneFbo.resize(width, height);
    114 for (Framebuffer &f : bloomFbo) f.resize(width / 2, height / 2);
    115 }
    116  
    117 void PostChain::beginScene() {
    118 ubo->update(settings);
    119 (config.samples > 0 ? msaaFbo : sceneFbo).bind();
    120 }
    121  
    122 void PostChain::endScene() {
    123 if (config.samples > 0) msaaFbo.blitTo(sceneFbo); // 色の付け先は2つとも / both color attachments
    124 // ブルーム:明るい部分(付け先1)を半分の大きさで、横・縦・横・縦…とぼかす(ピンポン)
    125 // Bloom: blur the bright part (attachment 1) at half size, horizontally, vertically, ... (ping-pong)
    126 glDisable(GL_DEPTH_TEST);
    127 blur->use();
    128 for (int pass = 0; pass < 2 * config.bloomPasses; ++pass) {
    129 bloomFbo[pass % 2].bind();
    130 // 最初は全体の大きさの明るい部分から(線型補間で2×2の平均も取れる)、あとは前のパスの結果から
    131 // The first pass reads the full-size bright part (linear filtering also averages 2 × 2), later passes read the
    132 // previous result
    133 (pass == 0 ? sceneFbo.color(1) : bloomFbo[(pass + 1) % 2].color()).bind(0);
    134 blur->set("uDirection", pass % 2 == 0 ? Vec2{1.0f, 0.0f} : Vec2{0.0f, 1.0f});
    135 fullscreen.draw();
    136 }
    137 }
    138  
    139 void PostChain::present(int windowWidth, int windowHeight, int effect) {
    140 Framebuffer::bindDefault(windowWidth, windowHeight);
    141 glDisable(GL_DEPTH_TEST);
    142 post->use();
    143 post->set("uEffect", effect);
    144 post->set("uFlipX", 0);
    145 sceneFbo.color(0).bind(0);
    146 bloom().bind(1);
    147 sceneFbo.color(1).bind(2);
    148 fullscreen.draw();
    149 }
    150  
    151 bool PostChain::reload() { return post->reload() && blur->reload(); }

ファイル: a/src/shader.cc | b/engine/src/shader.cc

前新
@@ -1,6 +1,6 @@
1 #include "shader.hh" 1 #include "engine/shader.hh"
2   2  
3 #include "file_util.hh" 3 #include "engine/file_util.hh"
4   4  
5 #include <cstdio> 5 #include <cstdio>
6 #include <string_view> 6 #include <string_view>

ファイル: a/src/shapes.cc | b/engine/src/shapes.cc

前新
@@ -1,6 +1,6 @@
1 #include "shapes.hh" 1 #include "engine/shapes.hh"
2   2  
3 #include "tangents.hh" 3 #include "engine/tangents.hh"
4   4  
5 #include <cmath> 5 #include <cmath>
6 #include <vector> 6 #include <vector>
@@ -11,9 +11,9 @@ static void addFace(std::vector<ModelVertex> &vertices, std::vector<std::uint32_
11 Vec3 up, Vec3 half = {0.5f, 0.5f, 0.5f}, float tile = 0.0f) { 11 Vec3 up, Vec3 half = {0.5f, 0.5f, 0.5f}, float tile = 0.0f) {
12 std::uint32_t first = static_cast<std::uint32_t>(vertices.size()); 12 std::uint32_t first = static_cast<std::uint32_t>(vertices.size());
13 auto extent = [&](Vec3 axis) { return std::fabs(axis.x) * half.x + std::fabs(axis.y) * half.y + std::fabs(axis.z) * half.z; }; 13 auto extent = [&](Vec3 axis) { return std::fabs(axis.x) * half.x + std::fabs(axis.y) * half.y + std::fabs(axis.z) * half.z; };
14 Vec3 c = extent(normal) * normal; // 面の中心 / centre of the face 14 Vec3 c = extent(normal) * normal; // 面の中心 / center of the face
15 Vec3 r = extent(right) * right, u = extent(up) * up; 15 Vec3 r = extent(right) * right, u = extent(up) * up;
16 // tile > 0:UVはメートル÷tile(面の大きさに合わせて繰り返す)、0:面ごとに0〜1 / tile > 0: UV = metres ÷ tile 16 // tile > 0:UVはメートル÷tile(面の大きさに合わせて繰り返す)、0:面ごとに0〜1 / tile > 0: UV = meters ÷ tile
17 // (repeats with the face size); 0: 0..1 per face 17 // (repeats with the face size); 0: 0..1 per face
18 float su = tile > 0.0f ? 2.0f * extent(right) / tile : 1.0f, sv = tile > 0.0f ? 2.0f * extent(up) / tile : 1.0f; 18 float su = tile > 0.0f ? 2.0f * extent(right) / tile : 1.0f, sv = tile > 0.0f ? 2.0f * extent(up) / tile : 1.0f;
19 vertices.push_back({c - r - u, normal, {0.0f, 0.0f}, {}}); // 左下 / bottom left 19 vertices.push_back({c - r - u, normal, {0.0f, 0.0f}, {}}); // 左下 / bottom left
@@ -80,7 +80,7 @@ Mesh makeSphere(int segments, int rings) {
80 } 80 }
81 } 81 }
82 // 隣り合う二つの輪の間を四角形(三角形2つ)で埋める。極の潰れた三角形は省く。 82 // 隣り合う二つの輪の間を四角形(三角形2つ)で埋める。極の潰れた三角形は省く。
83 // Fill between neighbouring rings with quads (two triangles). Skip the degenerate triangles at the poles. 83 // Fill between neighboring rings with quads (two triangles). Skip the degenerate triangles at the poles.
84 std::uint32_t row = static_cast<std::uint32_t>(segments + 1); 84 std::uint32_t row = static_cast<std::uint32_t>(segments + 1);
85 for (std::uint32_t r = 0; r < static_cast<std::uint32_t>(rings); ++r) { 85 for (std::uint32_t r = 0; r < static_cast<std::uint32_t>(rings); ++r) {
86 for (std::uint32_t s = 0; s < static_cast<std::uint32_t>(segments); ++s) { 86 for (std::uint32_t s = 0; s < static_cast<std::uint32_t>(segments); ++s) {

ファイル: /dev/null | b/engine/src/sprite_batch.cc

前新
@@ -0,0 +1,231 @@
    1 #include "engine/sprite_batch.hh"
    2  
    3 #include <algorithm>
    4 #include <cmath>
    5 #include <cstdio>
    6 #include <cstring>
    7 #include <numeric>
    8 #include <utility>
    9  
    10 // 頂点の形式:location 0 = 位置、1 = UV、2 = 色(4バイトを0〜1に正規化) / the vertex format: location 0 = position,
    11 // 1 = UV, 2 = color (4 bytes normalized to 0..1)
    12 static void setupVertexArray(GLuint vao, GLuint vertexBuffer, GLuint indexBuffer) {
    13 glVertexArrayVertexBuffer(vao, 0, vertexBuffer, 0, sizeof(SpriteVertex));
    14 glVertexArrayElementBuffer(vao, indexBuffer);
    15 glEnableVertexArrayAttrib(vao, 0);
    16 glVertexArrayAttribFormat(vao, 0, 2, GL_FLOAT, GL_FALSE, offsetof(SpriteVertex, position));
    17 glVertexArrayAttribBinding(vao, 0, 0);
    18 glEnableVertexArrayAttrib(vao, 1);
    19 glVertexArrayAttribFormat(vao, 1, 2, GL_FLOAT, GL_FALSE, offsetof(SpriteVertex, uv));
    20 glVertexArrayAttribBinding(vao, 1, 0);
    21 glEnableVertexArrayAttrib(vao, 2);
    22 glVertexArrayAttribFormat(vao, 2, 4, GL_UNSIGNED_BYTE, GL_TRUE, offsetof(SpriteVertex, color));
    23 glVertexArrayAttribBinding(vao, 2, 0);
    24 }
    25  
    26 // 0〜1の色 → RGBA8(Rが下位バイト:メモリ上でR, G, B, Aの順) / a 0..1 color → RGBA8 (R in the lowest byte: R, G, B,
    27 // A in memory order)
    28 static std::uint32_t packColor(Vec4 c) {
    29 auto byte = [](float v) { return static_cast<std::uint32_t>(std::lround(std::clamp(v, 0.0f, 1.0f) * 255.0f)); };
    30 return byte(c.x) | (byte(c.y) << 8) | (byte(c.z) << 16) | (byte(c.w) << 24);
    31 }
    32  
    33 std::optional<SpriteBatch> SpriteBatch::create(const SpriteBatchSettings &settings) {
    34 SpriteBatch batch;
    35 batch.settings = settings;
    36 batch.shader = Shader::load("engine/shaders/sprite.vert", "engine/shaders/sprite.frag");
    37 if (!batch.shader) return std::nullopt;
    38  
    39 // インデックスは変わらない:四角形iは頂点4i〜4i+3の三角形2つ(0-1-2、2-3-0)
    40 // The indices never change: quad i is two triangles over vertices 4i..4i+3 (0-1-2, 2-3-0)
    41 const size_t capacity = static_cast<size_t>(settings.capacity);
    42 std::vector<std::uint32_t> indices(capacity * 6);
    43 for (std::uint32_t i = 0; i < static_cast<std::uint32_t>(capacity); ++i) {
    44 const std::uint32_t q[6] = {4 * i, 4 * i + 1, 4 * i + 2, 4 * i + 2, 4 * i + 3, 4 * i};
    45 std::copy(q, q + 6, indices.begin() + static_cast<std::ptrdiff_t>(6 * i));
    46 }
    47 batch.indexBuffer = Buffer(indices.data(), static_cast<GLsizeiptr>(indices.size() * sizeof(std::uint32_t)));
    48  
    49 const GLsizeiptr quadBytes = 4 * sizeof(SpriteVertex);
    50 if (settings.upload == SpriteUpload::Persistent) {
    51 // 永続マップ:3区画分のストレージを一度だけマップし、ずっと書き続ける。COHERENTなので書いた値は
    52 // フラッシュなしでGPUに見える(ただしGPUが読み終わったかはフェンスで確かめる)
    53 // Persistent mapping: storage for three regions, mapped once and written for the whole run. COHERENT makes
    54 // writes visible to the GPU without explicit flushes (whether the GPU has finished reading is checked with fences)
    55 const GLbitfield flags = GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT;
    56 const GLsizeiptr bytes = kRegions * static_cast<GLsizeiptr>(capacity) * quadBytes;
    57 batch.vertexBuffer = Buffer(nullptr, bytes, flags);
    58 batch.mapped = static_cast<SpriteVertex *>(glMapNamedBufferRange(batch.vertexBuffer.id(), 0, bytes, flags));
    59 if (!batch.mapped) {
    60 fprintf(stderr, "スプライトの頂点バッファをマップできない / cannot map the sprite vertex buffer\n");
    61 return std::nullopt;
    62 }
    63 } else {
    64 // 書き換え可能なストレージ(GL_DYNAMIC_STORAGE_BIT):glNamedBufferSubDataで送る
    65 // Updatable storage (GL_DYNAMIC_STORAGE_BIT): filled with glNamedBufferSubData
    66 batch.vertexBuffer = Buffer(nullptr, static_cast<GLsizeiptr>(capacity) * quadBytes, GL_DYNAMIC_STORAGE_BIT);
    67 batch.staging.resize(capacity * 4);
    68 }
    69 glCreateVertexArrays(1, &batch.vao);
    70 setupVertexArray(batch.vao, batch.vertexBuffer.id(), batch.indexBuffer.id());
    71  
    72 const unsigned char whitePixel[4] = {255, 255, 255, 255};
    73 batch.white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false});
    74 return batch;
    75 }
    76  
    77 void SpriteBatch::release() {
    78 for (GLsync &f : fences)
    79 if (f) glDeleteSync(std::exchange(f, nullptr));
    80 if (vao) glDeleteVertexArrays(1, &vao);
    81 vao = 0;
    82 // マップしたままのバッファは削除すれば外れる / a mapped buffer is unmapped when it is deleted
    83 mapped = nullptr;
    84 }
    85  
    86 SpriteBatch::~SpriteBatch() { release(); }
    87  
    88 SpriteBatch::SpriteBatch(SpriteBatch &&other) noexcept { *this = std::move(other); }
    89  
    90 SpriteBatch &SpriteBatch::operator=(SpriteBatch &&other) noexcept {
    91 if (this != &other) {
    92 release();
    93 settings = other.settings;
    94 shader = std::move(other.shader);
    95 vertexBuffer = std::move(other.vertexBuffer);
    96 indexBuffer = std::move(other.indexBuffer);
    97 vao = std::exchange(other.vao, 0);
    98 white = std::move(other.white);
    99 mapped = std::exchange(other.mapped, nullptr);
    100 for (int i = 0; i < kRegions; ++i) fences[i] = std::exchange(other.fences[i], nullptr);
    101 region = other.region;
    102 regionUsed = other.regionUsed;
    103 quads = std::move(other.quads);
    104 staging = std::move(other.staging);
    105 sortMode = other.sortMode;
    106 lastStats = other.lastStats;
    107 currentStats = other.currentStats;
    108 begun = other.begun;
    109 }
    110 return *this;
    111 }
    112  
    113 void SpriteBatch::begin(const Mat4 &viewProjection, SpriteSort sort, SpriteBlend blend) {
    114 if (begun) fprintf(stderr, "SpriteBatch::begin: end()が抜けている / end() is missing\n");
    115 begun = true;
    116 sortMode = sort;
    117 quads.clear();
    118 currentStats = {};
    119 shader->set("uViewProjection", viewProjection);
    120 // 2Dの状態:深度なし(重なりは描く順・layerで決める)、カリングなし(y下向きの射影で四角形は画面上で時計回り
    121 // = 裏向きになる。flipXはUVを入れ替えるだけ)、乗算済みアルファのブレンド / the 2D state: no depth (overlap is
    122 // decided by order / layer), no culling (the y-down projection makes the quads clockwise on screen, i.e. back faces;
    123 // flipX only swaps the UVs), premultiplied-alpha blending
    124 glDisable(GL_DEPTH_TEST);
    125 glDisable(GL_CULL_FACE);
    126 glEnable(GL_BLEND);
    127 if (blend == SpriteBlend::Additive) glBlendFunc(GL_ONE, GL_ONE);
    128 else glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
    129 }
    130  
    131 void SpriteBatch::draw(const Sprite &s) {
    132 // 四隅をスプライトの中で作り(originを原点に)、回して、positionへ動かす(CPUで計算:頂点はもうワールド座標)
    133 // Build the corners inside the sprite (origin at 0), rotate them and move them to position (done on the CPU: the
    134 // vertices are already in world space)
    135 Vec2 o = s.origin * s.size;
    136 Vec2 corners[4] = {{-o.x, -o.y}, {s.size.x - o.x, -o.y}, {s.size.x - o.x, s.size.y - o.y}, {-o.x, s.size.y - o.y}};
    137 if (s.rotation != 0.0f) {
    138 float c = std::cos(s.rotation), sn = std::sin(s.rotation);
    139 for (Vec2 &p : corners) p = {c * p.x - sn * p.y, sn * p.x + c * p.y};
    140 }
    141 float u0 = s.uv.x, v0 = s.uv.y, u1 = s.uv.x + s.uv.w, v1 = s.uv.y + s.uv.h;
    142 if (s.flipX) std::swap(u0, u1);
    143 if (s.flipY) std::swap(v0, v1);
    144 const Vec2 uvs[4] = {{u0, v0}, {u1, v0}, {u1, v1}, {u0, v1}};
    145 Quad q;
    146 std::uint32_t color = packColor(s.color);
    147 for (int i = 0; i < 4; ++i) q.v[i] = {s.position + corners[i], uvs[i], color};
    148 q.texture = s.texture ? s.texture : &white;
    149 q.layer = s.layer;
    150 quads.push_back(q);
    151 }
    152  
    153 void SpriteBatch::drawRect(const Rect &rect, Vec4 color, float layer) {
    154 draw({.position = rect.position(), .size = rect.size(), .color = color, .layer = layer});
    155 }
    156  
    157 void SpriteBatch::drawRectOutline(const Rect &r, Vec4 color, float t, float layer) {
    158 drawRect({r.x, r.y, r.w, t}, color, layer);
    159 drawRect({r.x, r.bottom() - t, r.w, t}, color, layer);
    160 drawRect({r.x, r.y + t, t, r.h - 2 * t}, color, layer);
    161 drawRect({r.right() - t, r.y + t, t, r.h - 2 * t}, color, layer);
    162 }
    163  
    164 void SpriteBatch::end() {
    165 if (!begun) return;
    166 begun = false;
    167 // 描く順番(quadsの番号)を決める。stable_sortなので同じキーの中では描いた順のまま
    168 // Decide the drawing order (indices into quads). stable_sort keeps submission order among equal keys
    169 std::vector<std::uint32_t> order(quads.size());
    170 std::iota(order.begin(), order.end(), 0u);
    171 auto textureId = [&](std::uint32_t i) { return quads[i].texture->id(); };
    172 if (sortMode == SpriteSort::Texture) {
    173 std::stable_sort(order.begin(), order.end(), [&](std::uint32_t a, std::uint32_t b) { return textureId(a) < textureId(b); });
    174 } else if (sortMode == SpriteSort::Layer) {
    175 std::stable_sort(order.begin(), order.end(), [&](std::uint32_t a, std::uint32_t b) {
    176 if (quads[a].layer != quads[b].layer) return quads[a].layer < quads[b].layer;
    177 return textureId(a) < textureId(b);
    178 });
    179 }
    180  
    181 shader->use();
    182 glBindVertexArray(vao);
    183 // 同じテクスチャが続く間(容量まで)を一回の描画コールにする / one draw call per run of the same texture (up to the
    184 // capacity)
    185 const size_t capacity = static_cast<size_t>(settings.capacity);
    186 size_t first = 0;
    187 while (first < order.size()) {
    188 const Texture2D *texture = quads[order[first]].texture;
    189 size_t count = 1;
    190 while (first + count < order.size() && count < capacity && quads[order[first + count]].texture == texture) ++count;
    191 flush(order, first, count, *texture);
    192 first += count;
    193 }
    194 glBindVertexArray(0);
    195 currentStats.sprites = static_cast<int>(quads.size());
    196 lastStats = currentStats;
    197 }
    198  
    199 void SpriteBatch::flush(const std::vector<std::uint32_t> &order, size_t first, size_t count, const Texture2D &texture) {
    200 GLint baseVertex = 0;
    201 if (settings.upload == SpriteUpload::Persistent) {
    202 // 今の区画に入らなければ次の区画へ:今の区画にフェンスを置き、次の区画の古いフェンス(GPUがそこを読み終えたか)を待つ
    203 // If it does not fit into the current region, move on: put a fence after the current region's draws and wait
    204 // for the next region's old fence (has the GPU finished reading it?)
    205 if (regionUsed + static_cast<int>(count) > settings.capacity) {
    206 fences[region] = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
    207 region = (region + 1) % kRegions;
    208 regionUsed = 0;
    209 if (fences[region]) {
    210 // GL_SYNC_FLUSH_COMMANDS_BIT:フェンスがまだGPUに送られていなければ送る(でないと永久に待つ)
    211 // GL_SYNC_FLUSH_COMMANDS_BIT: sends the fence to the GPU if it is not yet (otherwise we could wait forever)
    212 while (glClientWaitSync(fences[region], GL_SYNC_FLUSH_COMMANDS_BIT, 1'000'000) == GL_TIMEOUT_EXPIRED) {
    213 }
    214 glDeleteSync(std::exchange(fences[region], nullptr));
    215 }
    216 }
    217 int start = region * settings.capacity + regionUsed;
    218 SpriteVertex *out = mapped + static_cast<size_t>(start) * 4;
    219 for (size_t i = 0; i < count; ++i) std::memcpy(out + 4 * i, quads[order[first + i]].v, sizeof(Quad::v));
    220 baseVertex = 4 * start;
    221 regionUsed += static_cast<int>(count);
    222 } else {
    223 for (size_t i = 0; i < count; ++i) std::memcpy(&staging[4 * i], quads[order[first + i]].v, sizeof(Quad::v));
    224 vertexBuffer.update(staging.data(), static_cast<GLsizeiptr>(count * 4 * sizeof(SpriteVertex)));
    225 }
    226 texture.bind(0);
    227 // baseVertex:インデックスに足す数。インデックスバッファは0から始まるまま使える
    228 // baseVertex: added to every index, so the index buffer can always start at 0
    229 glDrawElementsBaseVertex(GL_TRIANGLES, static_cast<GLsizei>(count * 6), GL_UNSIGNED_INT, nullptr, baseVertex);
    230 ++currentStats.drawCalls;
    231 }

ファイル: /dev/null | b/engine/src/sprite_sheet.cc

前新
@@ -0,0 +1,144 @@
    1 #include "engine/sprite_sheet.hh"
    2  
    3 #include "engine/file_util.hh"
    4  
    5 #include <algorithm>
    6 #include <cstdio>
    7 #include <sstream>
    8  
    9 std::optional<Texture2D> loadSpriteTexture(const std::string &path, TextureFilter filter) {
    10 // flipY = false:y下向きの2Dでは画像の一番上の行がv = 0のままで良い / with y-down 2D the image's top row can stay v = 0
    11 std::optional<Texture2D> texture =
    12 Texture2D::load(path, {.flipY = false, .mipmaps = false, .srgb = false, .premultiplyAlpha = true});
    13 if (!texture) return std::nullopt;
    14 GLenum f = filter == TextureFilter::Nearest ? GL_NEAREST : GL_LINEAR;
    15 texture->setFilter(f, f);
    16 // 繰り返さない:端のコマが反対側の端を読まないように / no repeat: frames at the edge must not read the opposite edge
    17 texture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
    18 return texture;
    19 }
    20  
    21 std::optional<SpriteSheet> SpriteSheet::loadGrid(const std::string &imagePath, int cellWidth, int cellHeight,
    22 int margin, int spacing, TextureFilter filter) {
    23 std::optional<Texture2D> texture = loadSpriteTexture(imagePath, filter);
    24 if (!texture) return std::nullopt;
    25 SpriteSheet sheet;
    26 sheet.image = std::move(*texture);
    27 for (int y = margin; y + cellHeight <= sheet.image.height() - margin; y += cellHeight + spacing)
    28 for (int x = margin; x + cellWidth <= sheet.image.width() - margin; x += cellWidth + spacing)
    29 sheet.frames.push_back({static_cast<float>(x), static_cast<float>(y), static_cast<float>(cellWidth),
    30 static_cast<float>(cellHeight)});
    31 if (sheet.frames.empty()) {
    32 fprintf(stderr, "%s: コマが一つもない / no frames fit (%d x %d cells)\n", imagePath.c_str(), cellWidth, cellHeight);
    33 return std::nullopt;
    34 }
    35 return sheet;
    36 }
    37  
    38 std::optional<SpriteSheet> SpriteSheet::loadAtlas(const std::string &atlasPath, TextureFilter filter) {
    39 std::optional<std::string> text = readTextFile(atlasPath);
    40 if (!text) {
    41 fprintf(stderr, "%s: 読めない / cannot read (プロジェクトのルートから実行した? / running from the project root?)\n",
    42 atlasPath.c_str());
    43 return std::nullopt;
    44 }
    45 SpriteSheet sheet;
    46 std::string imageFile;
    47 struct PendingClip {
    48 AnimationClip clip;
    49 std::vector<std::string> frameNames;
    50 int line;
    51 };
    52 std::vector<PendingClip> pending;
    53 std::istringstream lines(*text);
    54 std::string line;
    55 int lineNumber = 0;
    56 auto fail = [&](const char *what) {
    57 fprintf(stderr, "%s:%d: %s\n", atlasPath.c_str(), lineNumber, what);
    58 return std::nullopt;
    59 };
    60 while (std::getline(lines, line)) {
    61 ++lineNumber;
    62 std::istringstream in(line);
    63 std::string keyword;
    64 if (!(in >> keyword) || keyword[0] == '#') continue;
    65 if (keyword == "image") {
    66 if (!(in >> imageFile)) return fail("image <ファイル> / image <file>");
    67 } else if (keyword == "sprite") {
    68 std::string name;
    69 Rect r;
    70 if (!(in >> name >> r.x >> r.y >> r.w >> r.h)) return fail("sprite <name> <x> <y> <w> <h>");
    71 sheet.frames.push_back(r);
    72 sheet.names.push_back(name);
    73 } else if (keyword == "clip") {
    74 PendingClip p;
    75 std::string mode;
    76 if (!(in >> p.clip.name >> p.clip.fps >> mode) || (mode != "loop" && mode != "once"))
    77 return fail("clip <name> <fps> <loop|once> <frames...>");
    78 p.clip.loop = mode == "loop";
    79 for (std::string f; in >> f;) p.frameNames.push_back(f);
    80 p.line = lineNumber;
    81 pending.push_back(std::move(p));
    82 } else {
    83 return fail("知らないキーワード / unknown keyword");
    84 }
    85 }
    86 if (imageFile.empty()) return fail("imageの行がない / no image line");
    87 // クリップのコマの名前を番号にする(spriteより前に書いても良い) / turn clip frame names into indices (clips may come
    88 // before the sprites they use)
    89 for (PendingClip &p : pending) {
    90 for (const std::string &f : p.frameNames) {
    91 int index = sheet.find(f);
    92 if (index < 0) {
    93 lineNumber = p.line;
    94 return fail(("そのコマはない / no such sprite: " + f).c_str());
    95 }
    96 p.clip.frames.push_back(index);
    97 }
    98 sheet.clips.push_back(std::move(p.clip));
    99 }
    100 // 画像は.atlasと同じフォルダ / the image lives next to the .atlas file
    101 size_t slash = atlasPath.find_last_of("/\\");
    102 std::string folder = slash == std::string::npos ? "" : atlasPath.substr(0, slash + 1);
    103 std::optional<Texture2D> texture = loadSpriteTexture(folder + imageFile, filter);
    104 if (!texture) return std::nullopt;
    105 sheet.image = std::move(*texture);
    106 for (const Rect &r : sheet.frames)
    107 if (r.x < 0 || r.y < 0 || r.right() > static_cast<float>(sheet.image.width()) ||
    108 r.bottom() > static_cast<float>(sheet.image.height())) {
    109 fprintf(stderr, "%s: コマが画像の外にはみ出す / a sprite lies outside the image\n", atlasPath.c_str());
    110 return std::nullopt;
    111 }
    112 return sheet;
    113 }
    114  
    115 Rect SpriteSheet::pixels(int index) const {
    116 if (index < 0 || index >= count()) {
    117 if (!warnedIndex)
    118 fprintf(stderr, "SpriteSheet: 範囲外のコマ / frame index out of range: %d (count %d)\n", index, count());
    119 warnedIndex = true;
    120 return {};
    121 }
    122 return frames[static_cast<size_t>(index)];
    123 }
    124  
    125 Rect SpriteSheet::uv(int index) const {
    126 Rect r = pixels(index);
    127 float w = static_cast<float>(image.width()), h = static_cast<float>(image.height());
    128 return {r.x / w, r.y / h, r.w / w, r.h / h};
    129 }
    130  
    131 int SpriteSheet::find(std::string_view name) const {
    132 auto it = std::find(names.begin(), names.end(), name);
    133 return it == names.end() ? -1 : static_cast<int>(it - names.begin());
    134 }
    135  
    136 const AnimationClip *SpriteSheet::clip(std::string_view name) const {
    137 for (const AnimationClip &c : clips)
    138 if (c.name == name) return &c;
    139 return nullptr;
    140 }
    141  
    142 Sprite SpriteSheet::sprite(int index, Vec2 position, Vec2 origin, float scale) const {
    143 return {.texture = &image, .position = position, .size = size(index) * scale, .uv = uv(index), .origin = origin};
    144 }

ファイル: a/src/stb_image_impl.cc | b/engine/src/stb_image_impl.cc

類似度:100% / 名前の変更元:src/stb_image_impl.cc / 名前の変更先:engine/src/stb_image_impl.cc

ファイル: a/src/tangents.cc | b/engine/src/tangents.cc

前新
@@ -1,4 +1,4 @@
1 #include "tangents.hh" 1 #include "engine/tangents.hh"
2   2  
3 #include <cmath> 3 #include <cmath>
4   4  

ファイル: a/src/texture.cc | b/engine/src/texture.cc

前新
@@ -1,4 +1,4 @@
1 #include "texture.hh" 1 #include "engine/texture.hh"
2   2  
3 #include <stb_image.h> 3 #include <stb_image.h>
4   4  
@@ -57,7 +57,7 @@ Texture2D Texture2D::fromPixels(const unsigned char *rgba, int width, int height
57 Texture2D texture(width, height, options.srgb ? GL_SRGB8_ALPHA8 : GL_RGBA8, levels); 57 Texture2D texture(width, height, options.srgb ? GL_SRGB8_ALPHA8 : GL_RGBA8, levels);
58 if (options.premultiplyAlpha) { 58 if (options.premultiplyAlpha) {
59 // 乗算済みアルファ:色 × アルファ。透明なピクセルの色は(何色でも)0になる 59 // 乗算済みアルファ:色 × アルファ。透明なピクセルの色は(何色でも)0になる
60 // premultiplied alpha: colour × alpha. Transparent pixels become 0 whatever colour they had 60 // premultiplied alpha: color × alpha. Transparent pixels become 0 whatever color they had
61 std::vector<unsigned char> pm(rgba, rgba + static_cast<size_t>(width) * static_cast<size_t>(height) * 4); 61 std::vector<unsigned char> pm(rgba, rgba + static_cast<size_t>(width) * static_cast<size_t>(height) * 4);
62 // sRGBの値にそのまま掛けると、暗い縁が暗くなりすぎる:リニアで掛ける / multiplying the sRGB-encoded values directly 62 // sRGBの値にそのまま掛けると、暗い縁が暗くなりすぎる:リニアで掛ける / multiplying the sRGB-encoded values directly
63 // makes dark edges too dark: multiply in linear space 63 // makes dark edges too dark: multiply in linear space

ファイル: a/src/window.cc | b/engine/src/window.cc

前新
@@ -5,9 +5,9 @@
5 #define NOMINMAX 5 #define NOMINMAX
6 #include <windows.h> 6 #include <windows.h>
7 #endif 7 #endif
8 #include "window.hh" 8 #include "engine/window.hh"
9   9  
10 #include "gl_debug.hh" 10 #include "engine/gl_debug.hh"
11   11  
12 #include <cstdio> 12 #include <cstdio>
13   13  
@@ -54,7 +54,7 @@ bool Window::create(int width, int height, const char *title, int samples) {
54   54  
55 glfwMakeContextCurrent(glfwWindow); 55 glfwMakeContextCurrent(glfwWindow);
56 if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { 56 if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
57 fprintf(stderr, "GLADの初期化に失敗 / failed to initialise GLAD\n"); 57 fprintf(stderr, "GLADの初期化に失敗 / failed to initialize GLAD\n");
58 return false; 58 return false;
59 } 59 }
60 printf("OpenGL %s / %s\n", (const char *)glGetString(GL_VERSION), (const char *)glGetString(GL_RENDERER)); 60 printf("OpenGL %s / %s\n", (const char *)glGetString(GL_VERSION), (const char *)glGetString(GL_RENDERER));
@@ -99,7 +99,7 @@ void Window::setVsync(bool on) {
99 double Window::time() const { return glfwGetTime(); } 99 double Window::time() const { return glfwGetTime(); }
100   100  
101 float Window::aspect() const { 101 float Window::aspect() const {
102 // 最小化するとサイズが0になる / the size becomes 0 when minimised 102 // 最小化するとサイズが0になる / the size becomes 0 when minimized
103 return fbHeight > 0 ? static_cast<float>(fbWidth) / static_cast<float>(fbHeight) : 1.0f; 103 return fbHeight > 0 ? static_cast<float>(fbWidth) / static_cast<float>(fbHeight) : 1.0f;
104 } 104 }
105   105  

ファイル: a/src/main.cc | b/tests/scene3d/main.cc

前新
@@ -1,5 +1,7 @@
1 // 第24章:物理ベースレンダリング 1 // 3Dの確認:第24章の場面(PBR・IBL・影・HDR・ブルーム・MSAA)をエンジンの部品で描く(第25章から)。
2 // Chapter 24: physically based rendering 2 // TPS(第36〜39章)を作る前に、3Dのクラスが動くことをここで確かめる
    3 // The 3D check: the chapter 24 scene (PBR, IBL, shadows, HDR, bloom, MSAA) drawn with the engine's pieces (from
    4 // chapter 25). Before building the TPS (chapters 36-39), this shows that the 3D classes work
3 // 5 //
4 // 操作 / Controls: 6 // 操作 / Controls:
5 // WASD 前後左右に移動 / move forward, back, left, right 7 // WASD 前後左右に移動 / move forward, back, left, right
@@ -12,7 +14,7 @@
12 // K 見る場所:場面 → 球の格子(金属度 × 粗さ) → 見本の球 / look at: the scene → the sphere grid 14 // K 見る場所:場面 → 球の格子(金属度 × 粗さ) → 見本の球 / look at: the scene → the sphere grid
13 // (metallic × roughness) → the sample spheres 15 // (metallic × roughness) → the sample spheres
14 // V 表示(PBR):全部 → ベースカラー → 金属度 → 粗さ → 遮蔽 → 法線 → 直接光 → IBL → 影 16 // V 表示(PBR):全部 → ベースカラー → 金属度 → 粗さ → 遮蔽 → 法線 → 直接光 → IBL → 影
15 // view (PBR): all → base colour → metallic → roughness → occlusion → normals → direct → IBL → shadow 17 // view (PBR): all → base color → metallic → roughness → occlusion → normals → direct → IBL → shadow
16 // H 影のオン・オフ / shadows on / off 18 // H 影のオン・オフ / shadows on / off
17 // = / - 露出を上げる・下げる / exposure up / down 19 // = / - 露出を上げる・下げる / exposure up / down
18 // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出 20 // 1〜6 効果:なし / 反転 / グレースケール / シャープ / ぼかし / エッジ検出
@@ -24,21 +26,22 @@
24 // Tab カーソルのキャプチャ切り替え / toggle cursor capture 26 // Tab カーソルのキャプチャ切り替え / toggle cursor capture
25 // R シェーダーを読み直す / reload the shaders 27 // R シェーダーを読み直す / reload the shaders
26 // Esc 終了 / quit 28 // Esc 終了 / quit
27 #include "camera.hh" 29 #include "engine/camera.hh"
28 #include "cubemap.hh" 30 #include "engine/cubemap.hh"
29 #include "framebuffer.hh" 31 #include "engine/framebuffer.hh"
30 #include "ibl.hh" 32 #include "engine/ibl.hh"
31 #include "lights.hh" 33 #include "engine/lights.hh"
32 #include "material.hh" 34 #include "engine/material.hh"
33 #include "mathx.hh" 35 #include "engine/mathx.hh"
34 #include "mesh.hh" 36 #include "engine/mesh.hh"
35 #include "model.hh" 37 #include "engine/model.hh"
36 #include "pbr_material.hh" 38 #include "engine/pbr_material.hh"
37 #include "shader.hh" 39 #include "engine/renderer3d.hh"
38 #include "shapes.hh" 40 #include "engine/shader.hh"
39 #include "texture.hh" 41 #include "engine/shapes.hh"
40 #include "uniforms.hh" 42 #include "engine/texture.hh"
41 #include "window.hh" 43 #include "engine/uniforms.hh"
    44 #include "engine/window.hh"
42   45  
43 #include <algorithm> 46 #include <algorithm>
44 #include <cmath> 47 #include <cmath>
@@ -48,7 +51,7 @@
48 #include <utility> 51 #include <utility>
49 #include <vector> 52 #include <vector>
50   53  
51 // 物を置く場所:位置(底の中心)とY軸周りの回転 / where things go: position (bottom centre) and yaw 54 // 物を置く場所:位置(底の中心)とY軸周りの回転 / where things go: position (bottom center) and yaw
52 struct Placement { 55 struct Placement {
53 Vec3 position; 56 Vec3 position;
54 float angle; 57 float angle;
@@ -59,53 +62,13 @@ static const Placement kCrates[] = {
59 {{-6.0f, 0.0f, -1.0f}, 0.8f}, {{-5.2f, 0.0f, 3.5f}, -0.6f}, 62 {{-6.0f, 0.0f, -1.0f}, 0.8f}, {{-5.2f, 0.0f, 3.5f}, -0.6f},
60 }; 63 };
61   64  
62 constexpr int kMsaaSamples = 4; // 第20章 / chapter 20 65 static const char *const kPbrViewNames[] = {"all", "base color", "metallic", "roughness", "occlusion",
63 constexpr int kBloomPasses = 4; // 横+縦の組の数 / number of horizontal + vertical pairs    
64      
65 static const char *const kPbrViewNames[] = {"all", "base colour", "metallic", "roughness", "occlusion",    
66 "normals", "direct only", "IBL only", "shadow"}; 66 "normals", "direct only", "IBL only", "shadow"};
67 static const char *const kPhongViewNames[] = {"all", "ambient", "diffuse", "specular", "emission", 67 static const char *const kPhongViewNames[] = {"all", "ambient", "diffuse", "specular", "emission",
68 "normals", "vertex normals", "tangents", "bitangents", "shadow"}; 68 "normals", "vertex normals", "tangents", "bitangents", "shadow"};
69 static const char *const kLightingNames[] = {"direct + IBL", "direct only", "IBL only"}; 69 static const char *const kLightingNames[] = {"direct + IBL", "direct only", "IBL only"};
70   70  
71 // 影のバイアスの方法 / the shadow bias methods 71 constexpr int kFirstVectorView = 5; // ここからはベクトルを色で見せる / from here on, vectors are shown as colors
72 struct BiasMode {    
73 const char *name;    
74 float constant; // m(inTexelsならテクセルの大きさの倍数) / m (multiples of the texel size if inTexels)    
75 float slope; // tanθ当たり / per unit of tan θ    
76 float normalOffset; // 法線方向のずらし / push along the normal    
77 bool polygonOffset; // 影の地図を描くときにglPolygonOffset / glPolygonOffset while drawing the shadow map    
78 bool inTexels; // 値を影の地図の1テクセルのワールドでの大きさで測る:地図の大きさを変えても効き目が同じ    
79 // values measured in the world size of one shadow-map texel: works the same at any map size    
80 };    
81 static const BiasMode kBiasModes[] = {    
82 {"none (shadow acne)", 0.0f, 0.0f, 0.0f, false, false},    
83 {"constant 1 cm", 0.01f, 0.0f, 0.0f, false, false},    
84 {"slope-scaled + normal offset (in texels)", 0.5f, 1.0f, 3.0f, false, true},    
85 {"glPolygonOffset(2, 4) only", 0.0f, 0.0f, 0.0f, true, false},    
86 {"too large: 40 cm (peter-panning)", 0.4f, 0.0f, 0.0f, false, false},    
87 };    
88 constexpr size_t kDefaultBias = 2;    
89 constexpr int kShadowSizes[] = {512, 1024, 2048, 4096};    
90      
91 // 平行光源の光から見た行列:centreを中心とする半径radiusの球を正射影の箱に収める。箱は影の地図の1テクセル単位で    
92 // 動かす(カメラが動いても影の縁がちらつかない)。depthRangeに箱の奥行き(m)を返す    
93 // The directional light's matrix: an orthographic box enclosing the sphere (centre, radius). The box moves in whole    
94 // shadow-map texels (shadow edges do not shimmer when the camera moves). Returns the box depth (m) in depthRange    
95 static Mat4 lightSpaceMatrix(Vec3 lightDir, Vec3 centre, float radius, int mapSize, float &depthRange) {    
96 Vec3 d = normalize(lightDir);    
97 Vec3 up = std::fabs(d.y) > 0.99f ? Vec3{0.0f, 0.0f, 1.0f} : Vec3{0.0f, 1.0f, 0.0f};    
98 Mat4 view = lookAt({0.0f, 0.0f, 0.0f}, d, up); // 回転だけ:光の向きを-Zに / rotation only: the light along -Z    
99 Vec4 c = view * Vec4{centre.x, centre.y, centre.z, 1.0f};    
100 float texel = 2.0f * radius / static_cast<float>(mapSize);    
101 float cx = std::floor(c.x / texel) * texel, cy = std::floor(c.y / texel) * texel;    
102 // 奥行き:球の手前に20 m余分に(箱の外の、光と球の間にある物も影を落とすように)    
103 // Depth: 20 m extra in front of the sphere (so casters between the light and the sphere still cast)    
104 float nearPlane = -c.z - radius - 20.0f, farPlane = -c.z + radius;    
105 depthRange = farPlane - nearPlane;    
106 return orthographicGl(cx - radius, cx + radius, cy - radius, cy + radius, nearPlane, farPlane) * view;    
107 }    
108 constexpr int kFirstVectorView = 5; // ここからはベクトルを色で見せる / from here on, vectors are shown as colours    
109 static const char *const kEffectNames[] = {"none", "invert", "grayscale", "sharpen", "blur", "edge detection"}; 72 static const char *const kEffectNames[] = {"none", "invert", "grayscale", "sharpen", "blur", "edge detection"};
110   73  
111 static float random01(std::uint32_t &state) { 74 static float random01(std::uint32_t &state) {
@@ -155,7 +118,7 @@ static std::vector<Mat4> makeWires() {
155 wires.push_back(beam(p, p + Vec3{0.0f, 4.2f, 0.0f}, 0.12f)); // 電柱 / pole 118 wires.push_back(beam(p, p + Vec3{0.0f, 4.2f, 0.0f}, 0.12f)); // 電柱 / pole
156 wires.push_back(beam(p + Vec3{-0.7f, 4.0f, 0.0f}, p + Vec3{0.7f, 4.0f, 0.0f}, 0.08f)); // 腕木 / cross-arm 119 wires.push_back(beam(p + Vec3{-0.7f, 4.0f, 0.0f}, p + Vec3{0.7f, 4.0f, 0.0f}, 0.08f)); // 腕木 / cross-arm
157 } 120 }
158 // 電柱の間に3本ずつ、少したるませて(8本の直線でつなぐ) / three wires between neighbouring poles, sagging a little 121 // 電柱の間に3本ずつ、少したるませて(8本の直線でつなぐ) / three wires between neighboring poles, sagging a little
159 // (each made of 8 straight pieces) 122 // (each made of 8 straight pieces)
160 for (size_t i = 0; i + 1 < std::size(poles); ++i) { 123 for (size_t i = 0; i + 1 < std::size(poles); ++i) {
161 for (float side : {-0.6f, 0.0f, 0.6f}) { 124 for (float side : {-0.6f, 0.0f, 0.6f}) {
@@ -171,7 +134,7 @@ static std::vector<Mat4> makeWires() {
171 return wires; 134 return wires;
172 } 135 }
173   136  
174 // 電線に吊るした提灯:発光する球。位置と色 / paper lanterns hanging from the wires: emissive spheres, position + colour 137 // 電線に吊るした提灯:発光する球。位置と色 / paper lanterns hanging from the wires: emissive spheres, position + color
175 struct Lantern { 138 struct Lantern {
176 Vec3 position; 139 Vec3 position;
177 Vec3 color; 140 Vec3 color;
@@ -193,7 +156,7 @@ static std::vector<Lantern> makeLanterns() {
193   156  
194 int main() { 157 int main() {
195 Window window; 158 Window window;
196 if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 24")) return 1; 159 if (!window.create(1280, 720, "OpenGL Tutorial - 3D check")) return 1;
197   160  
198 // 画面(既定のフレームバッファ)がsRGBか:GL_FRAMEBUFFER_SRGBが効くのはsRGBのときだけ 161 // 画面(既定のフレームバッファ)がsRGBか:GL_FRAMEBUFFER_SRGBが効くのはsRGBのときだけ
199 // Is the screen (the default framebuffer) sRGB? GL_FRAMEBUFFER_SRGB only has an effect if it is 162 // Is the screen (the default framebuffer) sRGB? GL_FRAMEBUFFER_SRGB only has an effect if it is
@@ -201,31 +164,28 @@ int main() {
201 glGetNamedFramebufferAttachmentParameteriv(0, GL_BACK_LEFT, GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, &encoding); 164 glGetNamedFramebufferAttachmentParameteriv(0, GL_BACK_LEFT, GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, &encoding);
202 printf("default framebuffer encoding: %s\n", encoding == GL_SRGB ? "sRGB" : "linear"); 165 printf("default framebuffer encoding: %s\n", encoding == GL_SRGB ? "sRGB" : "linear");
203   166  
204 std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); 167 std::optional<Shader> phong = Shader::load("engine/shaders/phong.vert", "engine/shaders/phong.frag");
205 // PBR:頂点シェーダーはphongと同じ / PBR: the same vertex shader as phong 168 // PBR:頂点シェーダーはphongと同じ / PBR: the same vertex shader as phong
206 std::optional<Shader> pbr = Shader::load("shaders/phong.vert", "shaders/pbr.frag"); 169 std::optional<Shader> pbr = Shader::load("engine/shaders/phong.vert", "engine/shaders/pbr.frag");
207 std::optional<Shader> skybox = Shader::load("shaders/skybox.vert", "shaders/skybox.frag"); 170 std::optional<Shader> skybox = Shader::load("engine/shaders/skybox.vert", "engine/shaders/skybox.frag");
208 std::optional<Shader> post = Shader::load("shaders/post.vert", "shaders/post.frag"); 171 std::optional<Shader> unlit = Shader::load("engine/shaders/unlit.vert", "engine/shaders/unlit.frag");
209 std::optional<Shader> blur = Shader::load("shaders/post.vert", "shaders/blur.frag"); 172 // 色の画像はsRGB(第21章):GPUが読むときにリニアに直す / color images are sRGB (chapter 21): the GPU converts them
210 std::optional<Shader> unlit = Shader::load("shaders/unlit.vert", "shaders/unlit.frag");    
211 // 色の画像はsRGB(第21章):GPUが読むときにリニアに直す / colour images are sRGB (chapter 21): the GPU converts them    
212 // to linear when sampling 173 // to linear when sampling
213 std::optional<Cubemap> sky = Cubemap::loadDirectory("assets/textures/sky", ".png", true); 174 std::optional<Cubemap> sky = Cubemap::loadDirectory("assets/textures/sky", ".png", true);
214 std::optional<Texture2D> floorTexture = Texture2D::load("assets/textures/floor.png", {.srgb = true}); 175 std::optional<Texture2D> floorTexture = Texture2D::load("assets/textures/floor.png", {.srgb = true});
215 std::optional<Texture2D> grassTexture = Texture2D::load("assets/textures/grass_blades.png", {.srgb = true}); 176 std::optional<Texture2D> grassTexture = Texture2D::load("assets/textures/grass_blades.png", {.srgb = true});
216 // レンガ:色はsRGB、法線マップはデータなのでリニア(Aは高さ) / bricks: the colour is sRGB, the normal map is data and 177 // レンガ:色はsRGB、法線マップはデータなのでリニア(Aは高さ) / bricks: the color is sRGB, the normal map is data and
217 // stays linear (A = height) 178 // stays linear (A = height)
218 std::optional<Texture2D> brickTexture = Texture2D::load("assets/textures/bricks.png", {.srgb = true}); 179 std::optional<Texture2D> brickTexture = Texture2D::load("assets/textures/bricks.png", {.srgb = true});
219 std::optional<Texture2D> brickNormal = Texture2D::load("assets/textures/bricks_normal.png"); 180 std::optional<Texture2D> brickNormal = Texture2D::load("assets/textures/bricks_normal.png");
220 std::optional<Texture2D> leavesTexture = Texture2D::load("assets/textures/leaves.png", {.srgb = true}); 181 std::optional<Texture2D> leavesTexture = Texture2D::load("assets/textures/leaves.png", {.srgb = true});
221 // 影の地図を描くシェーダーと、それを見せるシェーダー / the shader that draws the shadow map and the one that shows it 182 // 影の地図を描くシェーダー / the shader that draws the shadow map
222 std::optional<Shader> shadowShader = Shader::load("shaders/shadow.vert", "shaders/shadow.frag"); 183 std::optional<Shader> shadowShader = Shader::load("engine/shaders/shadow.vert", "engine/shaders/shadow.frag");
223 std::optional<Shader> shadowDebug = Shader::load("shaders/post.vert", "shaders/shadow_debug.frag"); 184 if (!phong || !pbr || !skybox || !unlit || !sky || !floorTexture || !grassTexture || !brickTexture ||
224 if (!phong || !pbr || !skybox || !post || !blur || !unlit || !sky || !floorTexture || !grassTexture || !brickTexture || 185 !brickNormal || !leavesTexture || !shadowShader)
225 !brickNormal || !leavesTexture || !shadowShader || !shadowDebug)    
226 return 1; 186 return 1;
227 grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); 187 grassTexture->setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
228 for (const Shader *s : {&*phong, &*pbr, &*skybox, &*post, &*unlit, &*shadowShader}) 188 for (const Shader *s : {&*phong, &*pbr, &*skybox, &*unlit, &*shadowShader})
229 if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock)) || 189 if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock)) ||
230 !s->checkUniformBlock("Post", sizeof(PostBlock)) || !s->checkUniformBlock("Shadow", sizeof(ShadowBlock))) 190 !s->checkUniformBlock("Post", sizeof(PostBlock)) || !s->checkUniformBlock("Shadow", sizeof(ShadowBlock)))
231 return 1; 191 return 1;
@@ -233,7 +193,7 @@ int main() {
233 std::optional<Model> scene = Model::load("assets/models/diorama.glb"); 193 std::optional<Model> scene = Model::load("assets/models/diorama.glb");
234 std::optional<Model> crate = Model::load("assets/models/crate.glb"); 194 std::optional<Model> crate = Model::load("assets/models/crate.glb");
235 // 樽:色・金属と粗さ・法線・遮蔽のテクスチャ付き。蓋にはTANGENTがない(Modelが計算する) 195 // 樽:色・金属と粗さ・法線・遮蔽のテクスチャ付き。蓋にはTANGENTがない(Modelが計算する)
236 // The barrel: colour, metallic-roughness, normal and occlusion textures. The lid has no TANGENT (Model computes it) 196 // The barrel: color, metallic-roughness, normal and occlusion textures. The lid has no TANGENT (Model computes it)
237 std::optional<Model> barrel = Model::load("assets/models/barrel.glb"); 197 std::optional<Model> barrel = Model::load("assets/models/barrel.glb");
238 if (!scene || !crate || !barrel) return 1; 198 if (!scene || !crate || !barrel) return 1;
239   199  
@@ -254,45 +214,15 @@ int main() {
254   214  
255 UniformBuffer<CameraBlock> cameraUbo(kCameraBinding); 215 UniformBuffer<CameraBlock> cameraUbo(kCameraBinding);
256 UniformBuffer<LightsBlock> lightsUbo(kLightsBinding); 216 UniformBuffer<LightsBlock> lightsUbo(kLightsBinding);
257 UniformBuffer<PostBlock> postUbo(kPostBinding); 217  
258 UniformBuffer<ShadowBlock> shadowUbo(kShadowBinding); 218 // 影の地図(第23章、結合点2のShadowブロックも持つ)と、HDR・MSAA・ブルームの後処理(第20・21章、結合点3の
259   219 // Postブロックも持つ):第25章でエンジンの部品になった
260 // 影の地図:色なし、深度だけのテクスチャ(32ビット浮動小数点)。比較モード・GL_LINEAR・外側は1 220 // The shadow map (chapter 23; it also owns the Shadow block, binding 2) and the HDR / MSAA / bloom post-processing
261 // The shadow map: no colour, only a depth texture (32-bit float). Comparison mode, GL_LINEAR, 1 outside 221 // (chapters 20-21; it also owns the Post block, binding 3): engine pieces since chapter 25
262 size_t shadowSizeIndex = 2; 222 ShadowMap shadowMap(2048);
263 const FramebufferSpec shadowSpec = {.colorFormat = 0, .depthStencilFormat = GL_DEPTH_COMPONENT32F, .depthTexture = true}; 223 std::optional<PostChain> postChain = PostChain::create(window.width(), window.height());
264 Framebuffer shadowFbo(kShadowSizes[shadowSizeIndex], kShadowSizes[shadowSizeIndex], shadowSpec); 224 if (!shadowMap.complete() || !postChain) return 1;
265 if (!shadowFbo.complete()) return 1; 225 window.onResize = [&](int width, int height) { postChain->resize(width, height); };
266 // 影の地図を「見る」ためのサンプラーオブジェクト:比較なし。ユニットに繋ぐとテクスチャ自身の設定より優先される    
267 // A sampler object for *looking at* the shadow map: no comparison. Bound to a unit, it overrides the texture's own    
268 // sampling state    
269 GLuint rawDepthSampler = 0;    
270 glCreateSamplers(1, &rawDepthSampler);    
271 glSamplerParameteri(rawDepthSampler, GL_TEXTURE_COMPARE_MODE, GL_NONE);    
272 glSamplerParameteri(rawDepthSampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);    
273 glSamplerParameteri(rawDepthSampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);    
274      
275 // HDRのフレームバッファ(第21章):色はGL_RGBA16F(1より明るい値も負の値も持てる半精度の浮動小数点)。    
276 // 付け先0 = 場面の色、付け先1 = ブルームにする明るい部分(MRT)。MSAA(第20章)で描いて sceneFbo に解決する    
277 // HDR framebuffers (chapter 21): the colour is GL_RGBA16F (half floats that can hold values above 1, and negative    
278 // ones). Attachment 0 = the scene colour, attachment 1 = the bright part for bloom (MRT). Drawn with MSAA    
279 // (chapter 20) and resolved into sceneFbo    
280 const FramebufferSpec hdrSpec = {.colorFormat = GL_RGBA16F, .colorCount = 2};    
281 FramebufferSpec msaaSpec = hdrSpec;    
282 msaaSpec.samples = kMsaaSamples;    
283 Framebuffer msaaFbo(window.width(), window.height(), msaaSpec);    
284 Framebuffer sceneFbo(window.width(), window.height(), hdrSpec);    
285 // ブルームのぼかしは半分の大きさで(4分の1のピクセル数:速く、広くぼける)。深度は要らない    
286 // The bloom blur runs at half size (a quarter of the pixels: faster, and it spreads further). No depth needed    
287 const FramebufferSpec bloomSpec = {.colorFormat = GL_RGBA16F, .depthStencilFormat = 0};    
288 Framebuffer bloomFbo[2] = {Framebuffer(window.width() / 2, window.height() / 2, bloomSpec),    
289 Framebuffer(window.width() / 2, window.height() / 2, bloomSpec)};    
290 if (!msaaFbo.complete() || !sceneFbo.complete() || !bloomFbo[0].complete()) return 1;    
291 window.onResize = [&](int width, int height) {    
292 msaaFbo.resize(width, height);    
293 sceneFbo.resize(width, height);    
294 for (Framebuffer &f : bloomFbo) f.resize(width / 2, height / 2);    
295 };    
296   226  
297 Camera fps; 227 Camera fps;
298 fps.position = {0.6f, 3.6f, 12.5f}; 228 fps.position = {0.6f, 3.6f, 12.5f};
@@ -305,13 +235,8 @@ int main() {
305   235  
306 bool useOrbit = false, shadowsOn = true, usePbr = true; 236 bool useOrbit = false, shadowsOn = true, usePbr = true;
307 int lighting = 0, place = 0; 237 int lighting = 0, place = 0;
308 // 第23章の影の設定(この章では固定。キーは第23章) / the chapter 23 shadow settings (fixed here; the keys are in ch23)    
309 const bool fitFrustum = false, showShadowMap = false;    
310 const size_t biasMode = kDefaultBias;    
311 const int cullMode = 0, shadowFilter = static_cast<int>(ShadowFilter::Pcf3x3);    
312 int viewMode = 0, effect = 0; 238 int viewMode = 0, effect = 0;
313 float exposureEv = 0.0f; // 露出(段、EV):倍率は2^EV / exposure in stops (EV): the multiplier is 2^EV 239 float exposureEv = 0.0f; // 露出(段、EV):倍率は2^EV / exposure in stops (EV): the multiplier is 2^EV
314 PostBlock postSettings;    
315 bool night = false, flashlightOn = false, windmillMoving = true; 240 bool night = false, flashlightOn = false, windmillMoving = true;
316 float windmillTime = 0.0f; 241 float windmillTime = 0.0f;
317 window.setCursorCaptured(true); 242 window.setCursorCaptured(true);
@@ -322,8 +247,8 @@ int main() {
322 // IBLのシェーダー(ibl_*.frag)は作るときだけ使う:読み直す = IBLを作り直す(失敗したら前のIBLのまま) 247 // IBLのシェーダー(ibl_*.frag)は作るときだけ使う:読み直す = IBLを作り直す(失敗したら前のIBLのまま)
323 // The IBL shaders (ibl_*.frag) are only used while building: reloading them = rebuilding the IBL (the old one stays 248 // The IBL shaders (ibl_*.frag) are only used while building: reloading them = rebuilding the IBL (the old one stays
324 // if that fails) 249 // if that fails)
325 if (key == GLFW_KEY_R && phong->reload() && pbr->reload() && skybox->reload() && post->reload() && blur->reload() && 250 if (key == GLFW_KEY_R && phong->reload() && pbr->reload() && skybox->reload() && postChain->reload() &&
326 unlit->reload() && shadowShader->reload() && shadowDebug->reload()) { 251 unlit->reload() && shadowShader->reload()) {
327 if (std::optional<Ibl> rebuilt = Ibl::build(*sky)) { 252 if (std::optional<Ibl> rebuilt = Ibl::build(*sky)) {
328 ibl = std::move(rebuilt); 253 ibl = std::move(rebuilt);
329 printf("シェーダーを読み直した / shaders reloaded\n"); 254 printf("シェーダーを読み直した / shaders reloaded\n");
@@ -378,7 +303,7 @@ int main() {
378 // 手で作るマテリアルはすべてPbrMaterial(第24章)。Blinn-Phongで描くときはtoBlinnPhongで変換する。 303 // 手で作るマテリアルはすべてPbrMaterial(第24章)。Blinn-Phongで描くときはtoBlinnPhongで変換する。
379 // 手で選んだ色はsRGBの値なのでsrgbToLinearでリニアに 304 // 手で選んだ色はsRGBの値なのでsrgbToLinearでリニアに
380 // Every hand-made material is a PbrMaterial (chapter 24); for Blinn-Phong they are converted with toBlinnPhong. 305 // Every hand-made material is a PbrMaterial (chapter 24); for Blinn-Phong they are converted with toBlinnPhong.
381 // Hand-picked colours are sRGB values, so srgbToLinear makes them linear 306 // Hand-picked colors are sRGB values, so srgbToLinear makes them linear
382 auto rgb = [](float r, float g, float b, float a = 1.0f) { 307 auto rgb = [](float r, float g, float b, float a = 1.0f) {
383 Vec3 c = srgbToLinear(Vec3{r, g, b}); 308 Vec3 c = srgbToLinear(Vec3{r, g, b});
384 return Vec4{c.x, c.y, c.z, a}; 309 return Vec4{c.x, c.y, c.z, a};
@@ -425,7 +350,7 @@ int main() {
425 constexpr float kLanternGlow = 6.0f; 350 constexpr float kLanternGlow = 6.0f;
426   351  
427 // 見本の球:磨いた金、クロム、粗い銅、赤いプラスチック(glTFの値で、金属のベースカラー = F0) 352 // 見本の球:磨いた金、クロム、粗い銅、赤いプラスチック(glTFの値で、金属のベースカラー = F0)
428 // Sample spheres: polished gold, chrome, rough copper, red plastic (glTF values; a metal's base colour = its F0) 353 // Sample spheres: polished gold, chrome, rough copper, red plastic (glTF values; a metal's base color = its F0)
429 struct Showcase { 354 struct Showcase {
430 Vec3 position; 355 Vec3 position;
431 PbrMaterial material; 356 PbrMaterial material;
@@ -443,7 +368,6 @@ int main() {
443 const Vec3 kGridCentre = {0.0f, 5.5f, 24.0f}; 368 const Vec3 kGridCentre = {0.0f, 5.5f, 24.0f};
444 const Vec4 kGridColor = rgb(0.9f, 0.35f, 0.15f); 369 const Vec4 kGridColor = rgb(0.9f, 0.35f, 0.15f);
445   370  
446 FullscreenTriangle fullscreen;    
447 glEnable(GL_CULL_FACE); 371 glEnable(GL_CULL_FACE);
448   372  
449 // 場面全体を今のフレームバッファに描く。litはpbr(PBR)かphong(比較用のBlinn-Phong) 373 // 場面全体を今のフレームバッファに描く。litはpbr(PBR)かphong(比較用のBlinn-Phong)
@@ -588,7 +512,7 @@ int main() {
588 scene->nodes[static_cast<size_t>(rotor)].rotation = 512 scene->nodes[static_cast<size_t>(rotor)].rotation =
589 Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * windmillTime) * rotorStart; 513 Quat::fromAxisAngle({0.0f, 0.0f, 1.0f}, -0.8f * windmillTime) * rotorStart;
590   514  
591 float aspect = static_cast<float>(sceneFbo.width()) / static_cast<float>(sceneFbo.height()); 515 float aspect = static_cast<float>(postChain->scene().width()) / static_cast<float>(postChain->scene().height());
592   516  
593 CameraBlock camera; 517 CameraBlock camera;
594 camera.view = useOrbit ? orbit.view() : fps.view(); 518 camera.view = useOrbit ? orbit.view() : fps.view();
@@ -620,138 +544,44 @@ int main() {
620 lights.spots.push_back({.position = camera.viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}}); 544 lights.spots.push_back({.position = camera.viewPos, .direction = viewDir, .color = {1.0f, 0.95f, 0.85f}});
621 lightsUbo.update(lights.toBlock()); 545 lightsUbo.update(lights.toBlock());
622 environmentTint = night ? Vec3{0.02f, 0.025f, 0.05f} : Vec3{1.0f, 1.0f, 1.0f}; 546 environmentTint = night ? Vec3{0.02f, 0.025f, 0.05f} : Vec3{1.0f, 1.0f, 1.0f};
623 postSettings.exposure = std::exp2(exposureEv); 547 postChain->settings.exposure = std::exp2(exposureEv);
624 postSettings.bloomStrength = 0.08f; 548 postChain->settings.bloomStrength = 0.08f;
625 // ベクトルの表示(法線・接線)は値をそのまま見せる:トーンマッピングなし、露出1(phong.fragが逆変換して出す) 549 // ベクトルの表示(法線・接線)は値をそのまま見せる:トーンマッピングなし、露出1(phong.fragが逆変換して出す)
626 // The vector views (normals, tangents) show the raw values: no tone mapping, exposure 1 (phong.frag outputs them 550 // The vector views (normals, tangents) show the raw values: no tone mapping, exposure 1 (phong.frag outputs them
627 // pre-decoded) 551 // pre-decoded)
628 if (usePbr ? (viewMode >= 2 && viewMode <= 5) || viewMode == 8 : viewMode >= kFirstVectorView) { 552 if (usePbr ? (viewMode >= 2 && viewMode <= 5) || viewMode == 8 : viewMode >= kFirstVectorView) {
629 postSettings.exposure = 1.0f; 553 postChain->settings.exposure = 1.0f;
630 postSettings.toneMapper = static_cast<int>(ToneMapper::Clamp); 554 postChain->settings.toneMapper = static_cast<int>(ToneMapper::Clamp);
631 } else { 555 } else {
632 postSettings.toneMapper = static_cast<int>(ToneMapper::Aces); 556 postChain->settings.toneMapper = static_cast<int>(ToneMapper::Aces);
633 } 557 }
634 postUbo.update(postSettings);    
635   558  
636 //------------------------------------------------------------------ 559 //------------------------------------------------------------------
637 // 0. 影の地図:太陽から見た深度(第23章) / 0. the shadow map: depth as seen from the sun (chapter 23) 560 // 0. 影の地図:太陽から見た深度(第23章)。光の箱は場面全体を囲む球
    561 // 0. the shadow map: depth as seen from the sun (chapter 23). The light box is a sphere around the whole scene
638 //------------------------------------------------------------------ 562 //------------------------------------------------------------------
639 // 光の箱:場面全体を囲む球か、カメラの視錐台の手前8 mを囲む球 / the light box: a sphere around the whole scene, 563 const BoundingSphere fit = {{0.0f, 1.0f, 2.5f}, 9.5f};
640 // or a sphere around the first 8 m of the camera frustum 564 if (shadowMap.begin(lights.directional.direction, fit, ShadowBias{}, ShadowFilter::Pcf3x3, shadowsOn))
641 Vec3 fitCentre = {0.0f, 1.0f, 2.5f};    
642 float fitRadius = 9.5f;    
643 if (fitFrustum) {    
644 float nearPlane = 0.1f, farPlane = 8.0f, fov = useOrbit ? orbit.fov : fps.fov;    
645 Vec3 f = viewDir, r = normalize(cross(f, Vec3{0.0f, 1.0f, 0.0f})), u = cross(r, f);    
646 float th = std::tan(0.5f * fov);    
647 Vec3 corners[8];    
648 int k = 0;    
649 for (float dist : {nearPlane, farPlane})    
650 for (float sy : {-1.0f, 1.0f})    
651 for (float sx : {-1.0f, 1.0f})    
652 corners[k++] = camera.viewPos + dist * f + (sx * dist * th * aspect) * r + (sy * dist * th) * u;    
653 // 中心は8つの角の平均、半径は一番遠い角まで(カメラが回っても大きさは変わらない)    
654 // Centre = the mean of the 8 corners, radius = to the farthest corner (its size does not change as the camera turns)    
655 fitCentre = {0.0f, 0.0f, 0.0f};    
656 for (Vec3 c : corners) fitCentre = fitCentre + 0.125f * c;    
657 fitRadius = 0.0f;    
658 for (Vec3 c : corners) fitRadius = std::max(fitRadius, length(c - fitCentre));    
659 }    
660 if (frame++ % 60 == 5) printf("light box radius %.2f m: %.1f mm per shadow texel\n", fitRadius, 2000.0f * fitRadius / static_cast<float>(shadowFbo.width()));    
661 const BiasMode &bias = kBiasModes[biasMode];    
662 float depthRange = 1.0f;    
663 ShadowBlock shadowBlock;    
664 shadowBlock.lightSpace = lightSpaceMatrix(lights.directional.direction, fitCentre, fitRadius, shadowFbo.width(), depthRange);    
665 // バイアスはメートルで決めて、0〜1の深度に直す(正射影なので深度は距離に比例) / biases are chosen in metres and    
666 // converted to 0..1 depth (orthographic: depth is proportional to distance)    
667 float unit = bias.inTexels ? 2.0f * fitRadius / static_cast<float>(shadowFbo.width()) : 1.0f; // m    
668 shadowBlock.bias = bias.constant * unit / depthRange;    
669 shadowBlock.slopeBias = bias.slope * unit / depthRange;    
670 shadowBlock.normalOffset = bias.normalOffset * unit;    
671 shadowBlock.filter = shadowFilter;    
672 shadowBlock.texel = {1.0f / static_cast<float>(shadowFbo.width()), 1.0f / static_cast<float>(shadowFbo.height())};    
673 shadowBlock.enabled = shadowsOn ? 1 : 0;    
674 shadowUbo.update(shadowBlock);    
675 // 硬い影はGL_NEAREST、それ以外はGL_LINEAR(比較の結果を2×2で補間) / hard shadows use GL_NEAREST, the others    
676 // GL_LINEAR (the comparison results are blended 2 × 2)    
677 GLenum shadowFilterMode = shadowFilter == static_cast<int>(ShadowFilter::Hard) ? GL_NEAREST : GL_LINEAR;    
678 shadowFbo.depth().setFilter(shadowFilterMode, shadowFilterMode);    
679      
680 if (shadowsOn) {    
681 shadowFbo.bind();    
682 glEnable(GL_DEPTH_TEST);    
683 glClear(GL_DEPTH_BUFFER_BIT);    
684 if (cullMode == 1) glCullFace(GL_FRONT); // 表面を捨て、裏面の深度を保存する / keep the back faces' depth    
685 if (cullMode == 2) glDisable(GL_CULL_FACE);    
686 if (bias.polygonOffset) {    
687 // ハードウェアの傾きバイアス:深度 += factor × 傾き + units × 最小の深度の差 / hardware slope bias:    
688 // depth += factor × slope + units × the smallest depth step    
689 glEnable(GL_POLYGON_OFFSET_FILL);    
690 glPolygonOffset(2.0f, 4.0f);    
691 }    
692 drawShadowCasters(); 565 drawShadowCasters();
693 glDisable(GL_POLYGON_OFFSET_FILL); 566 glEnable(GL_CULL_FACE);
694 glCullFace(GL_BACK); 567 shadowMap.end(); // 深度テクスチャをユニット5へ / the depth texture goes on unit 5
695 glEnable(GL_CULL_FACE); 568 if (frame++ % 60 == 5)
696 } 569 printf("light box radius %.2f m: %.1f mm per shadow texel\n", fit.radius, 1000.0f * shadowMap.metresPerTexel());
697 // 影の地図はユニット5(描き終わってから繋ぐ) / the shadow map goes on unit 5 (after it has been drawn)    
698 shadowFbo.depth().bind(5);    
699   570  
700 //------------------------------------------------------------------ 571 //------------------------------------------------------------------
701 // 1. 場面をHDR・MSAAで描き、解決する(色の付け先は2つとも) / 1. draw the scene in HDR with MSAA and resolve it 572 // 1. 場面をHDR・MSAAで描き、解決してブルーム / 1. draw the scene in HDR with MSAA, resolve it and bloom
702 // (both colour attachments)    
703 //------------------------------------------------------------------ 573 //------------------------------------------------------------------
704 msaaFbo.bind(); 574 postChain->beginScene();
705 drawScene(); 575 drawScene();
706 msaaFbo.blitTo(sceneFbo); 576 postChain->endScene();
707   577  
708 //------------------------------------------------------------------ 578 //------------------------------------------------------------------
709 // 2. ブルーム:明るい部分(付け先1)を半分の大きさで、横・縦・横・縦…とぼかす(ピンポン) 579 // 2. 画面へ:場面+ブルーム、露出、トーンマッピング、sRGB / 2. to the screen: scene + bloom, exposure, tone
710 // 2. Bloom: blur the bright part (attachment 1) at half size, horizontally, vertically, ... (ping-pong)    
711 //------------------------------------------------------------------    
712 glDisable(GL_DEPTH_TEST);    
713 blur->use();    
714 for (int pass = 0; pass < 2 * kBloomPasses; ++pass) {    
715 bloomFbo[pass % 2].bind();    
716 // 最初は全体の大きさの明るい部分から(線型補間で2×2の平均も取れる)、あとは前のパスの結果から    
717 // The first pass reads the full-size bright part (linear filtering also averages 2 × 2), later passes read the    
718 // previous result    
719 (pass == 0 ? sceneFbo.color(1) : bloomFbo[(pass + 1) % 2].color()).bind(0);    
720 blur->set("uDirection", pass % 2 == 0 ? Vec2{1.0f, 0.0f} : Vec2{0.0f, 1.0f});    
721 fullscreen.draw();    
722 }    
723      
724 //------------------------------------------------------------------    
725 // 3. 画面へ:場面+ブルーム、露出、トーンマッピング、sRGB / 3. to the screen: scene + bloom, exposure, tone    
726 // mapping, sRGB 580 // mapping, sRGB
727 //------------------------------------------------------------------ 581 //------------------------------------------------------------------
728 Framebuffer::bindDefault(window.width(), window.height()); 582 postChain->present(window.width(), window.height(), effect);
729 post->use();    
730 post->set("uEffect", effect);    
731 post->set("uFlipX", 0);    
732 sceneFbo.color(0).bind(0);    
733 bloomFbo[1].color().bind(1); // 最後の縦のパスの結果 / the result of the last vertical pass    
734 sceneFbo.color(1).bind(2);    
735 fullscreen.draw();    
736      
737 // 影の地図を左下に(比較なしのサンプラーで深度を読む) / the shadow map at the bottom left (depth read through the    
738 // sampler without comparison)    
739 if (showShadowMap) {    
740 glViewport(16, 16, 320, 320);    
741 shadowDebug->use();    
742 shadowFbo.depth().bind(0);    
743 glBindSampler(0, rawDepthSampler);    
744 fullscreen.draw();    
745 glBindSampler(0, 0); // ユニット0はテクスチャ自身の設定に戻る / unit 0 goes back to the texture's own state    
746 // 影の地図をユニット0から外す:次のシャドウパスではshadow.fragのuBaseMapがユニット0で、描き込み中の深度を    
747 // 読むとフィードバックループになる / take the shadow map off unit 0: in the next shadow pass shadow.frag's    
748 // uBaseMap is on unit 0, and reading the depth being written would be a feedback loop    
749 white.bind(0);    
750 glViewport(0, 0, window.width(), window.height());    
751 }    
752   583  
753 window.swapBuffers(); 584 window.swapBuffers();
754 } 585 }
755 glDeleteSamplers(1, &rawDepthSampler);    
756 return 0; 586 return 0;
757 } 587 }

ファイル: a/src/gltf_dump.cc | b/tools/gltf_dump.cc

前新
@@ -12,7 +12,7 @@
12 #define NOMINMAX 12 #define NOMINMAX
13 #include <windows.h> 13 #include <windows.h>
14 #endif 14 #endif
15 #include "gltf.hh" 15 #include "engine/gltf.hh"
16   16  
17 #include <cmath> 17 #include <cmath>
18 #include <cstdio> 18 #include <cstdio>
@@ -214,7 +214,7 @@ static bool dump(const std::string &path, bool all) {
214 for (size_t i = 0; i < g.materials.size(); ++i) { 214 for (size_t i = 0; i < g.materials.size(); ++i) {
215 const GltfMaterial &m = g.materials[i]; 215 const GltfMaterial &m = g.materials[i];
216 const Vec4 &b = m.baseColorFactor; 216 const Vec4 &b = m.baseColorFactor;
217 printf(" [%zu] \"%s\": base colour (%g, %g, %g, %g), metallic %g, roughness %g", i, m.name.c_str(), b.x, b.y, b.z, 217 printf(" [%zu] \"%s\": base color (%g, %g, %g, %g), metallic %g, roughness %g", i, m.name.c_str(), b.x, b.y, b.z,
218 b.w, m.metallicFactor, m.roughnessFactor); 218 b.w, m.metallicFactor, m.roughnessFactor);
219 if (m.emissiveFactor.x > 0.0f || m.emissiveFactor.y > 0.0f || m.emissiveFactor.z > 0.0f) 219 if (m.emissiveFactor.x > 0.0f || m.emissiveFactor.y > 0.0f || m.emissiveFactor.z > 0.0f)
220 printf(", emissive (%g, %g, %g) x %g", m.emissiveFactor.x, m.emissiveFactor.y, m.emissiveFactor.z, 220 printf(", emissive (%g, %g, %g) x %g", m.emissiveFactor.x, m.emissiveFactor.y, m.emissiveFactor.z,


コメント(0)

まだコメントはありません。