
ゲーム
イベント
マガジン
技術ブログ
この記事はセーフィー Advent Calendar 5日目の記事です。 こんにちは!セーフィーで AI-App ナンバープレート認識の Tech PdM(テクニカル・プロダクトマネージャー)を担当している土井です。 最近は PdM 寄りの業務が多く、日々のさまざまなタスクを Claude Code に任せています。 この記事では、Claude Code を何本も並べて仕事を任せるための仕組みを紹介します。 きっかけは会議が多くて、実作業の時間が取れなかったことです。 雑にタスクを振っても、まず整理してくれる AI が欲しいと思いました。 もう 1 つは「あのセッションどれだっけ?」と探
G-gen の西です。当記事では、Google Kubernetes Engine(GKE)において、Horizontal Pod Autoscaler(HPA)がアイドル状態のワークロードのレプリカ数を 0 までスケールインし、リソース使用率を最適化する機能 scale to zero (ゼロスケーリング)の実機検証結果を紹介します。 概要 scale to zero とは 前提条件 制約事項 検証の概要 検証環境 検証の流れ 設定手順 環境変数の設定 GKE クラスタの作成 Pub/Sub リソースの作成 検証用マニフェストの作成 マニフェストの適用と初期状態の確認 動作確認 検証結果の概要 メッセージがない状態でのスケールインの確認 メッセージの送信とスケールアウトの確認 メッセージの確認応答とスケールインの確認 概要 scale to zero とは scale to zero (ゼロスケーリング)は、Kubernetes の標準機能である Horizontal Pod Autoscaler (以下、HPA)において、アイドル状態のワークロードのレプリカ数を 0 までスケールインする機能です。Google Kubernetes Engine(以下、GKE)でこの機能を利用することで、需要がない時間帯のレプリカ数を 0 に保ち、リソース使用率を最適化できます。 GKE 1.36 以前のバージョンでは、HPA の minReplicas: 0 をサポートしていないという課題があり、キューのメッセージを処理するワーカーのように、処理対象がない時間帯が長いワークロードでも、Pod を 1つ以上常時稼働させる必要がありました。Autopilot では、Pod がプロビジョニングされている間、Pod のリソース requests に応じて課金されるため、処理がない時間帯にも料金が発生し続けてしまいます。 scale to zero は、この課題を解消し、処理対象がない時間帯のレプリカ数を 0 にできます。GKE では、外部指標を AutoscalingMetric カスタムリソースで定義し、HPA から参照します。AutoscalingMetric は、Cloud Monitoring やクラスタ内の Pod の指標を HPA に渡すためのマネージドな仕組のため、Kubernetes Event-Driven Autoscaling(KEDA)などのサードパーティの指標アダプタは必要ありません。当記事の検証環境では、以下の構成図のように、Pub/Sub サブスクリプションの未確認メッセージ数を、HPA が外部指標として参照します。 scale to zero 検証環境 scale to zero の有無による違いは、以下のとおりです。 比較項目 GKE 1.36 以前 GKE 1.37 以降 最小のレプリカ数 1 0 レプリカ数を 0 にするための指標 (指定できない) External または Object タイプの指標が 1つ以上必要 参考 : HPA を使用して GKE ワークロードをゼロにスケーリングする 参考 : カスタム指標または外部指標を使用して Pod を自動スケーリングする 参考 : Horizontal Pod Autoscaling - Scaling to and from zero 参考 : Google Kubernetes Engine の料金 参考 : GKE の弾力性がさらに向上: ゼロへのスケーリング、費用削減、ワークロードの応答性維持 なお、2026年11月現在、HPA の scale to zero は Kubernetes ではベータ版の機能で、GKE 1.37 以降はデフォルトで有効です。また、AutoscalingMetric で Cloud Monitoring の指標を取得する機能も、Preview 提供です。Preview の機能を使用する上での注意点については、以下の記事も参照してください。 blog.g-gen.co.jp Pub/Sub を始めとしたメッセージングサービスの詳細については、以下の記事も参照してください。 blog.g-gen.co.jp 前提条件 scale to zero を使用するには、以下の要件があります。詳細は以下の公式ドキュメントを参照してください。 項目 条件 GKE のバージョン コントロールプレーンとノードの両方が 1.37 以降であること HPA の API バージョン autoscaling/v2 指標 External または Object タイプの指標を 1つ以上設定が必要 Namespace AutoscalingMetric、HPA、スケール対象の Deployment が同じ Namespace であること Cloud Monitoring の指標 クラスタと同じプロジェクトに存在が必要 参考 : HPA を使用して GKE ワークロードをゼロにスケーリングする 参考 : カスタム指標または外部指標を使用して Pod を自動スケーリングする - Cloud Monitoring からカスタム指標または外部指標を取得する 制約事項 scale to zero には、以下の制約事項があります。 Cloud Monitoring のカスタム指標と外部指標は、1クラスタあたり合計で最大 100個 指標を 1つでも取得できない間は、スケールインしない 手動でレプリカ数を 0 にすると、1 以上に戻すまで、HPA の自動スケーリングが一時停止する ノードプールを 1.36 以前のバージョンにダウングレードする場合は、事前に minReplicas を 1 以上にする必要がある その他の制約事項については、以下の公式ドキュメントを参照してください。 参考 : 水平 Pod 自動スケーリングのトラブルシューティング - HPA を使用した GKE ワークロードのゼロへのスケールダウンとゼロからのスケールアップのトラブルシューティング 検証の概要 検証環境 検証環境は以下のとおりです。 項目 設定値 クラスタタイプ GKE Autopilot(Rapid チャンネル) GKE バージョン 1.37.0-gke.3503000 リージョン 東京(asia-northeast1) アプリケーション nginx:latest (スケール対象の Deployment ) 検証では、メッセージを処理するアプリケーションの代わりに、Nginx の Deployment をスケール対象にします。メッセージの取得と確認応答(ack)は、 gcloud pubsub subscriptions pull --auto-ack コマンドで行います。 検証の流れ 以下の流れで検証を実施し、レプリカ数と HPA の指標の推移を観察します。 フェーズ メッセージの状況 確認内容 0 メッセージなし レプリカ数が 0 までスケールインすること 1 50件を送信 レプリカ数が 0 からスケールアウトすること 2 50件を取得して確認応答 レプリカ数が再び 0 までスケールインすること 設定手順 環境変数の設定 以降のコマンドで使用する環境変数を設定します。 # プロジェクト ID とリージョンを設定する $ export PROJECT_ID = < プロジェクトID > $ export LOCATION =asia-northeast1 GKE クラスタの作成 2026年11月現在、GKE 1.37 は Rapid チャンネルで使用できます。 --release-channel=rapid を指定して、Autopilot クラスタを作成します。当記事の検証では、 1.37.0-gke.3503000 を指定しました。 # Autopilot クラスタを作成する $ gcloud container clusters create-auto scale-to-zero \ --project = ${PROJECT_ID} \ --location = ${LOCATION} \ --release-channel = rapid \ --cluster-version =< 1 . 37 系のバージョン > # kubectl の認証情報を取得する $ gcloud container clusters get-credentials scale-to-zero \ --project = ${PROJECT_ID} \ --location = ${LOCATION} 参考 : Autopilot クラスタの作成 参考 : GKE release notes(September 04, 2026) Pub/Sub リソースの作成 指標の取得元となる、トピックとサブスクリプションを作成します。 # トピックを作成する $ gcloud pubsub topics create my-worker-topic --project = ${PROJECT_ID} # トピックに接続するサブスクリプションを作成する $ gcloud pubsub subscriptions create my-worker-subscription \ --topic = my-worker-topic \ --project = ${PROJECT_ID} 検証用マニフェストの作成 検証用のマニフェストは、以下のとおり 1つのファイルにまとめて定義します。リソースは、 default Namespace に作成します。 scale to zero を有効化するには、HPA の minReplicas に 0 を指定し、指標は AutoscalingMetric で定義します。 # scale-to-zero.yaml --- # 1. スケール対象の Deployment apiVersion : apps/v1 kind : Deployment metadata : name : async-worker namespace : default spec : replicas : 3 # 初期のレプリカ数。再適用すると、この値に戻る selector : matchLabels : app : async-worker template : metadata : labels : app : async-worker spec : containers : - name : async-worker image : nginx:latest ports : - containerPort : 80 resources : limits : memory : 100Mi requests : cpu : 50m memory : 100Mi --- # 2. Pub/Sub サブスクリプションの未確認メッセージ数を、外部指標として定義する(AutoscalingMetric) apiVersion : autoscaling.gke.io/v1beta1 kind : AutoscalingMetric metadata : name : pubsub-queue-depth namespace : default spec : metrics : - promql : name : pubsub-undelivered query : > { "pubsub.googleapis.com/subscription/num_undelivered_messages" , subscription_id="my-worker-subscription" } --- # 3. HPA(minReplicas 0、maxReplicas 20) apiVersion : autoscaling/v2 kind : HorizontalPodAutoscaler metadata : name : async-worker-hpa namespace : default spec : scaleTargetRef : apiVersion : apps/v1 kind : Deployment name : async-worker minReplicas : 0 # レプリカ数 0 までのスケールインを許可する maxReplicas : 20 metrics : - type : External external : metric : # autoscaling.gke.io|<AutoscalingMetric のリソース名>|<指標名> の形式で指定する name : autoscaling.gke.io|pubsub-queue-depth|pubsub-undelivered target : type : AverageValue averageValue : "10" # Pod 1つあたりの未確認メッセージ数の目標値 なお、マニフェストで指定している averageValue: "10" は、Pod 1つあたりの未確認メッセージ数の目標値です。この設定では、HPA は、未確認メッセージ数を目標値の 10 で割り、小数点以下を切り上げた値をレプリカ数として算出します。実際のスケーリングには、最大レプリカ数や安定化ウィンドウなどの設定も適用されます。 マニフェストの適用と初期状態の確認 マニフェストをクラスタに適用し、AutoscalingMetric の状態を確認します。22:22:34 に適用しました。 # マニフェストを適用する $ kubectl apply -f scale-to-zero.yaml # AutoscalingMetric の状態を確認する $ kubectl describe autoscalingmetric pubsub-queue-depth ----- 出力例 ----- // 省略 Status: Metric Statuses: Hpa Name: autoscaling.gke.io|pubsub-queue-depth|pubsub-undelivered Name: pubsub-undelivered Events: < none > Status にエラーがないことと、HPA から参照する指標名( Hpa Name )を確認できます。 GKE の自動スケーリング指標アダプタは、クラスタのリソースを節約するため、デフォルトでレプリカ数 0 で実行されます。AutoscalingMetric を適用すると、 kube-system Namespace の autoscaling-metrics-adapter の Deployment のレプリカ数が、0 から 1 にスケールアウトしました。 # アダプタの Deployment を確認する $ kubectl get deployment autoscaling-metrics-adapter -n kube-system ----- 出力例 ----- NAME READY UP-TO-DATE AVAILABLE AGE autoscaling-metrics-adapter 1 / 1 1 1 104m 参考 : カスタム指標または外部指標を使用して Pod を自動スケーリングする - Cloud Monitoring からカスタム指標または外部指標を取得する 動作確認 検証結果の概要 検証全体を通じた、レプリカ数の推移は以下のとおりです。 タイミング レプリカ数 出来事 フェーズ0 マニフェスト適用後(22:22) 3 Deployment の初期のレプリカ数 フェーズ0 スケールイン後(22:27) 0 メッセージがない状態で、3 から 0 にスケールイン フェーズ1 スケールアウト後(22:42) 5 50件の送信の完了から約 3分後に、0 から 5 にスケールアウト フェーズ2 スケールイン後(22:55) 0 確認応答の開始から約 9分後に、5 から 0 にスケールイン 表から読み取れるように、サブスクリプションにメッセージがない間はレプリカ数が 0 までスケールインし、メッセージを送信すると 0 から 5 にスケールアウトし、確認応答の後は再び 0 までスケールインする様子が確認できます。 フェーズ1では、送信の完了から Pod の作成まで約 3分10秒、フェーズ2では、HPA の TARGETS が 0/10 (avg) と表示されてから Pod の終了が始まるまで約 4分50秒かかりました。なお、Pub/Sub の未確認メッセージ数の指標は、60秒ごとにサンプリングされ、サンプリング後、最長 120秒間は表示されません。また、HPA のスケールインには、デフォルトで 300秒の安定化ウィンドウがあり、この期間に算出した推奨値のうち最大の値を使用します。 参考 : Google Cloud 指標: P から Z - pubsub 参考 : 水平Pod自動スケーリング - 安定化ウィンドウ 参考 : 水平Pod自動スケーリング - デフォルトの動作 以降では、各フェーズにおける詳細な動作とリソースの推移を確認します。 メッセージがない状態でのスケールインの確認 サブスクリプションにメッセージがない状態で、HPA、Pod、ノードの状態を監視しました。 時刻 経過 出来事 22:22 - マニフェストを適用(22:22:34) 22:22〜22:26 約0〜3.5分 指標を取得できず、Events に FailedGetExternalMetric ( No recommendation )が記録される 22:27 約5分15秒 3つの Pod の終了が開始され、スケールインが始まる 22:26〜22:27 に、別々のターミナルで HPA、Pod、ノードを kubectl get -w で監視しました。 # HPA を監視する(各行の先頭に、行を受け取った時刻を付ける) $ kubectl get hpa async-worker-hpa -w | while read -r l; do echo " $( date +%T ) $l "; done ----- 出力例 ----- 22:26:45 NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE 22:26:45 async-worker-hpa Deployment/async-worker 0 / 10 ( avg ) 0 20 3 4m11s 22:27:49 async-worker-hpa Deployment/async-worker 0 / 10 ( avg ) 0 20 3 5m15s 22:28:04 async-worker-hpa Deployment/async-worker 0 / 10 ( avg ) 0 20 0 5m30s # Pod を監視する(各行の先頭に、行を受け取った時刻を付ける) $ kubectl get pods -l app =async-worker -w | while read -r l; do echo " $( date +%T ) $l "; done ----- 出力例 ----- 22:27:04 NAME READY STATUS RESTARTS AGE 22:27:04 async-worker-6b9b5cddc-2n8px 1 / 1 Running 0 4m30s 22:27:04 async-worker-6b9b5cddc-f689l 1 / 1 Running 0 4m30s 22:27:04 async-worker-6b9b5cddc-pfvfc 1 / 1 Running 0 4m30s // 省略 22:27:49 async-worker-6b9b5cddc-2n8px 1 / 1 Terminating 0 5m15s 22:27:49 async-worker-6b9b5cddc-pfvfc 1 / 1 Terminating 0 5m15s 22:27:49 async-worker-6b9b5cddc-f689l 1 / 1 Terminating 0 5m15s HPA の Conditions と Events は、 kubectl describe hpa で確認します。 # HPA の Conditions と Events を確認する $ kubectl describe hpa async-worker-hpa | sed -n ' /^Conditions:/,$p ' ----- 出力例 ----- Conditions: Type Status Reason Message ---- ------ ------ ------- AbleToScale True ReadyForNewScale recommended size matches current size ScalingActive True ValidMetricFound the HPA was able to successfully calculate a replica count from external metric autoscaling.gke.io|pubsub-queue-depth|pubsub-undelivered ScalingLimited False DesiredWithinRange the desired count is within the acceptable range ScaledToZero True ScaledToZero the HPA controller scaled the workload to zero Events: Type Reason Age From Message ---- ------ ---- ---- ------- Warning FailedGetExternalMetric 2m58s ( x15 over 6m13s ) horizontal-pod-autoscaler No recommendation Normal SuccessfulRescale 73s horizontal-pod-autoscaler New size: 0 ; reason: external metric autoscaling.gke.io|pubsub-queue-depth|pubsub-undelivered below target ScaledToZero 条件と ScalingActive 条件は、どちらも True でした。 ScalingActive が True のため、レプリカ数が 0 の間も、HPA は需要の増加を監視します。なお、監視を開始した 22:26:45 の時点で、 TARGETS は 0/10 (avg) でした。この約 1分後に Pod の終了が始まり、レプリカ数が 0 になりました。 メッセージの送信とスケールアウトの確認 メッセージを 50件送信しました。 # 送信の開始時刻を記録して、50件のメッセージを送信し、完了時刻を記録する $ date && for i in $( seq 1 50 ) ; do gcloud pubsub topics publish my-worker-topic --message =" msg- ${i} " --project = ${PROJECT_ID} done && date ----- 出力例 ----- 2026 年 10 月 24 日 土曜日 22:38:27 JST // 省略 2026 年 10 月 24 日 土曜日 22:39:07 JST 時刻 経過 出来事 22:39 - 50件の送信が完了 22:42 約3分10秒 4つの Pod が作成される。約 3秒後に 5つ目の Pod が作成され、レプリカ数が 5 になる 22:43 約4分30秒 5つ目の Pod が Running になる HPA の指標の値、Pod 数、スケーリングのイベントは、 kubectl describe hpa の出力から絞り込んで確認します。 # HPA の指標の値、Pod 数、スケーリングのイベントを確認する(抜粋) $ kubectl describe hpa async-worker-hpa | grep -E ' ^(Metrics|Deployment pods):|average value|New size: [45]; ' ----- 出力例 ----- Metrics: ( current / target ) " autoscaling.gke.io|pubsub-queue-depth|pubsub-undelivered " ( target average value ) : 10 / 10 Deployment pods: 5 current / 5 desired Normal SuccessfulRescale 102s horizontal-pod-autoscaler New size: 4 ; reason: external metric autoscaling.gke.io|pubsub-queue-depth|pubsub-undelivered above target Normal SuccessfulRescale 98s horizontal-pod-autoscaler New size: 5 ; reason: external metric autoscaling.gke.io|pubsub-queue-depth|pubsub-undelivered above target Metrics の 10 / 10 は、Pod 1つあたりの未確認メッセージ数の平均値(50件÷5)です。 averageValue: "10" のため、HPA は、未確認メッセージ数の 50件を目標値の 10 で割った 5 を、レプリカ数として算出しました。 5つ目の Pod は、新しいノードに配置されました。ノードは、Pod の作成から約 58秒後に追加されました。Google Cloud の公式ブログでは、新しい GKE ノードが起動するまでの待ち時間は、60〜90秒とされています。Pod は、作成から約 77秒後に Running になりました。また、新しいノードが追加された後の 22:43:25 に、既存の Pod 2つが終了し、新しいノード上の Pod に置き換わりました。 # Pod を監視する(抜粋) $ kubectl get pods -l app =async-worker -w | while read -r l; do echo " $( date +%T ) $l "; done ----- 出力例 ----- // 省略 22:42:17 async-worker-6b9b5cddc-dndll 0 / 1 Pending 0 1s // 省略 22:42:17 async-worker-6b9b5cddc-mkqck 0 / 1 Pending 0 0s 22:42:17 async-worker-6b9b5cddc-wc89n 0 / 1 Pending 0 0s 22:42:17 async-worker-6b9b5cddc-prv46 0 / 1 Pending 0 0s // 省略 22:42:20 async-worker-6b9b5cddc-2rnmc 0 / 1 Pending 0 0s // 省略 22:43:25 async-worker-6b9b5cddc-prv46 1 / 1 Terminating 0 68s // 省略 22:43:25 async-worker-6b9b5cddc-wc89n 1 / 1 Terminating 0 68s 22:43:25 async-worker-6b9b5cddc-gd88x 0 / 1 Pending 0 0s // 省略 22:43:26 async-worker-6b9b5cddc-v92l7 0 / 1 Pending 0 0s // 省略 22:43:37 async-worker-6b9b5cddc-2rnmc 1 / 1 Running 0 77s # ノードを監視する(各行の先頭に、行を受け取った時刻を付ける) $ kubectl get nodes -w | while read -r l; do echo " $( date +%T ) $l "; done ----- 出力例 ----- 22:27:22 NAME STATUS ROLES AGE VERSION 22:27:22 gk3-scale-to-zero-pool-1-6cb3ca9e-gp9h Ready < none > 2m20s v1. 37 .0-gke. 3503000 // 省略 22:43:18 gk3-scale-to-zero-pool-1-c539f5f5-dtrt NotReady < none > 1s v1. 37 .0-gke. 3503000 // 省略 22:43:22 gk3-scale-to-zero-pool-1-c539f5f5-dtrt Ready < none > 5s v1. 37 .0-gke. 3503000 メッセージの確認応答とスケールインの確認 アプリケーションの処理の代わりに、 gcloud pubsub subscriptions pull コマンドでメッセージを取得し、確認応答します。 # 開始時刻を記録して、メッセージを取得して確認応答し、完了時刻を記録する $ date && for i in $( seq 1 10 ) ; do gcloud pubsub subscriptions pull my-worker-subscription \ --auto-ack \ --limit = 100 \ --project = ${PROJECT_ID} done && date ----- 出力例 ----- 2026 年 10 月 24 日 土曜日 22:46:58 JST // 省略( 15 件を取得) // 省略( 35 件を取得) Listed 0 items. // 省略 2026 年 10 月 24 日 土曜日 22:49:43 JST 2回の pull で、15件と 35件、合計 50件を取得しました。経過時間は、確認応答を開始した 22:46:58 から計算しています。 時刻 経過 出来事 22:46 - 確認応答を開始(22:46:58)。最初の 2回の pull で 50件を取得 22:51 約4分 HPA の TARGETS が 0/10 (avg) になる 22:55 約9分 5つの Pod の終了が開始され、スケールインが始まる # HPA を監視する(抜粋) $ kubectl get hpa async-worker-hpa -w | while read -r l; do echo " $( date +%T ) $l "; done ----- 出力例 ----- // 省略 22:51:01 async-worker-hpa Deployment/async-worker 0 / 10 ( avg ) 0 20 5 28m 22:55:53 async-worker-hpa Deployment/async-worker 0 / 10 ( avg ) 0 20 5 33m 22:56:08 async-worker-hpa Deployment/async-worker 0 / 10 ( avg ) 0 20 0 33m # Pod を監視する(抜粋) $ kubectl get pods -l app =async-worker -w | while read -r l; do echo " $( date +%T ) $l "; done ----- 出力例 ----- // 省略 22:55:53 async-worker-6b9b5cddc-v92l7 1 / 1 Terminating 0 12m 22:55:53 async-worker-6b9b5cddc-mkqck 1 / 1 Terminating 0 13m 22:55:53 async-worker-6b9b5cddc-2rnmc 1 / 1 Terminating 0 13m 22:55:53 async-worker-6b9b5cddc-dndll 1 / 1 Terminating 0 13m 22:55:53 async-worker-6b9b5cddc-gd88x 1 / 1 Terminating 0 12m TARGETS が 0/10 (avg) と表示されてから約 4分50秒後に、Pod の終了が始まり、レプリカ数が 0 になりました。 西 拓磨 (記事一覧) クラウドソリューション部 クラウドエンジニアリング2課 東京都在住 2026年9月に G-gen にジョイン。前職ではSIerとしてオンプレミス、AWSなどのインフラ設計構築業務に従事。 インフラの経験をベースに現在はGoogle Cloudの学習中。 好きなことはランニング、ゲーム、自宅サーバーで色々検証をすること。
intdashグループの大久保です。 aptpod Advent Calendar 2026 の12月3日の記事を担当します。 WebAssemblyを用いてブラウザ上で色々な処理ができる時代になりました。とくに最近は、これまで難しかったブラウザからのGPU利用を可能にするWebGPUが主要なブラウザに実装されるようになりました。そこで今回は、ブラウザからGPUの性能を発揮できるか見るために、WebGPUによる物理シミュレーションゲームを作成してみます。言語としてRustを、ゲームエンジンとして bevy を選択します。これらはWebAssemblyを公式にサポートしており相性が良いです。 物理シミュレーション ソースコード 実行結果 まとめと感想 物理シミュレーション GPUにやらせてみる物理シミュレーションとして、熱拡散方程式を二次元格子状の差分法で解いてみます。おそらく物理シミュレーションとしてはもっとも単純で簡単な類のものです。 二次元の熱拡散方程式は以下の形になります。 有限差分法で二次元のセル (i, j) の温度を更新する計算は、以下の形で表されます。 大雑把な説明としては、自分自身の温度と周囲のセルとの温度差に比例して熱が流入、もしくは流出する式になります。 120x120のセルで構成された系とし、境界条件を低温 (T=0)として、マウスでドラッグしたところを高温 (T=1) に設定します。 ソースコード ゲームエンジンとしてbevyを使うので、 Cargo.toml に依存関係を記述します。 [dependencies] bevy = { version = "0.19" , features = [ "bevy_dev_tools" ] } [target.'cfg(target_arch = "wasm32")'.dependencies] bevy = { version = "0.19" , features = [ "webgpu" ] } main.rs に書くのは、WebGPUを使うためのセットアップとマウスイベントの処理です。また、FPSを表示するようにしています。 use bevy :: { asset :: RenderAssetUsages, core_pipeline :: schedule :: camera_driver, dev_tools :: fps_overlay :: {FpsOverlayConfig, FpsOverlayPlugin}, prelude :: * , render :: { extract_resource :: {ExtractResource, ExtractResourcePlugin}, render_asset :: RenderAssets, render_resource :: { binding_types :: {texture_storage_2d, uniform_buffer}, * , }, renderer :: {RenderContext, RenderDevice, RenderGraph, RenderQueue}, texture :: GpuImage, Render, RenderApp, RenderStartup, RenderSystems, }, shader :: ShaderCacheError, }; use std :: borrow :: Cow; const SHADER_ASSET_PATH: &str = "shaders/heat_diffusion.wgsl" ; /// 表示倍率。1 セルを DISPLAY_FACTOR x DISPLAY_FACTOR ピクセルで描画する。 const DISPLAY_FACTOR: u32 = 4 ; /// 格子のセル数。縦横とも WORKGROUP_SIZE の倍数にすること。 const SIZE: UVec2 = UVec2 :: new ( 120 , 120 ); const WORKGROUP_SIZE: u32 = 8 ; /// マウスで与える温度と、外周に固定する低温の値。 const HOT: f32 = 1.0 ; const COLD: f32 = 0.0 ; /// r = alpha * dt / dx^2。2次元の陽解法が安定するには 0.25 以下にすること。 const DIFFUSION_RATE: f32 = 0.2 ; /// マウスの熱源ブラシの半径 (セル単位)。 const BRUSH_RADIUS: f32 = 6.0 ; fn main () { App :: new () . insert_resource ( ClearColor ( Color :: BLACK)) . add_plugins (( DefaultPlugins . set (WindowPlugin { primary_window: Some (Window { title: "Heat diffusion (compute shader)" . into (), resolution: (SIZE * DISPLAY_FACTOR). into (), .. default () }), .. default () }) // 各セルがくっきりした正方形になるよう最近傍補間にする。 . set ( ImagePlugin :: default_nearest ()), HeatDiffusionComputePlugin, FpsOverlayPlugin { config: FpsOverlayConfig { text_config: TextFont :: from_font_size ( 16.0 ), .. default () }, }, )) . add_systems (Startup, setup) . add_systems (Update, (update_brush, switch_textures)) . run (); } fn setup ( mut commands: Commands, mut images: ResMut < Assets < Image >> ) { let mut image = Image :: new_target_texture (SIZE.x, SIZE.y, TextureFormat :: Rgba32Float, None ); image.asset_usage = RenderAssetUsages :: RENDER_WORLD; image.texture_descriptor.usage = TextureUsages :: COPY_DST | TextureUsages :: STORAGE_BINDING | TextureUsages :: TEXTURE_BINDING; let image0 = images. add (image. clone ()); let image1 = images. add (image); commands. spawn (( Sprite { image: image0. clone (), custom_size: Some (SIZE. as_vec2 ()), .. default () }, Transform :: from_scale ( Vec3 :: splat (DISPLAY_FACTOR as f32 )), )); commands. spawn (Camera2d); commands. insert_resource (HeatImages { texture_a: image0, texture_b: image1, }); commands. insert_resource (HeatUniforms { hot: HOT, cold: COLD, diffusion_rate: DIFFUSION_RATE, mouse: Vec2 :: ZERO, mouse_down: 0.0 , brush_radius: BRUSH_RADIUS, }); } // カーソル位置 (セル座標) とボタンの状態を毎フレーム uniform に書き込む。 // スプライトはウィンドウ全体をちょうど覆うので、ウィンドウのピクセル座標を // 表示倍率で割るだけでセル座標になる。 fn update_brush ( window: Single < & Window > , mouse_button: Res < ButtonInput < MouseButton >> , mut uniforms: ResMut < HeatUniforms > , ) { uniforms.mouse_down = if mouse_button. pressed ( MouseButton :: Left) { 1.0 } else { 0.0 }; if let Some (cursor) = window. cursor_position () { uniforms.mouse = cursor / DISPLAY_FACTOR as f32 ; } } // 最後に書き込まれたテクスチャを表示する。毎フレーム交互に切り替わる。 fn switch_textures (images: Res < HeatImages > , mut sprite: Single < &mut Sprite > ) { if sprite.image == images.texture_a { sprite.image = images.texture_b. clone (); } else { sprite.image = images.texture_a. clone (); } } struct HeatDiffusionComputePlugin ; impl Plugin for HeatDiffusionComputePlugin { fn build ( & self , app: &mut App) { // compute shader が使うリソースをレンダーワールドへ抽出する。 app. add_plugins (( ExtractResourcePlugin :: < HeatImages > :: default (), ExtractResourcePlugin :: < HeatUniforms > :: default (), )); let render_app = app. sub_app_mut (RenderApp); render_app . init_resource :: < HeatState > () . add_systems (RenderStartup, init_heat_pipeline) . add_systems ( Render, prepare_bind_group. in_set ( RenderSystems :: PrepareBindGroups), ) . add_systems (Render, update. in_set ( RenderSystems :: Prepare)) . add_systems (RenderGraph, heat_diffusion. before (camera_driver)); } } #[derive(Resource, Clone , ExtractResource)] struct HeatImages { texture_a: Handle < Image > , texture_b: Handle < Image > , } #[derive(Resource, Clone , ExtractResource, ShaderType)] struct HeatUniforms { hot: f32 , cold: f32 , diffusion_rate: f32 , mouse: Vec2, mouse_down: f32 , brush_radius: f32 , } #[derive(Resource)] struct HeatImageBindGroups ([BindGroup; 2 ]); fn prepare_bind_group ( mut commands: Commands, pipeline: Res < HeatPipeline > , gpu_images: Res < RenderAssets < GpuImage >> , heat_images: Res < HeatImages > , heat_uniforms: Res < HeatUniforms > , render_device: Res < RenderDevice > , pipeline_cache: Res < PipelineCache > , queue: Res < RenderQueue > , ) { let view_a = gpu_images. get ( & heat_images.texture_a). unwrap (); let view_b = gpu_images. get ( & heat_images.texture_b). unwrap (); let mut uniform_buffer = UniformBuffer :: from (heat_uniforms. into_inner ()); uniform_buffer. write_buffer ( & render_device, & queue); // bind_group 0 は A を読み B に書く。bind_group 1 は B を読み A に書く。 let bind_group_0 = render_device. create_bind_group ( None , & pipeline_cache. get_bind_group_layout ( & pipeline.texture_bind_group_layout), & BindGroupEntries :: sequential (( & view_a.texture_view, & view_b.texture_view, & uniform_buffer, )), ); let bind_group_1 = render_device. create_bind_group ( None , & pipeline_cache. get_bind_group_layout ( & pipeline.texture_bind_group_layout), & BindGroupEntries :: sequential (( & view_b.texture_view, & view_a.texture_view, & uniform_buffer, )), ); commands. insert_resource ( HeatImageBindGroups ([bind_group_0, bind_group_1])); } #[derive(Resource)] struct HeatPipeline { texture_bind_group_layout: BindGroupLayoutDescriptor, init_pipeline: CachedComputePipelineId, update_pipeline: CachedComputePipelineId, } fn init_heat_pipeline ( mut commands: Commands, asset_server: Res < AssetServer > , pipeline_cache: Res < PipelineCache > , ) { let texture_bind_group_layout = BindGroupLayoutDescriptor :: new ( "HeatImages" , & BindGroupLayoutEntries :: sequential ( ShaderStages :: COMPUTE, ( texture_storage_2d ( TextureFormat :: Rgba32Float, StorageTextureAccess :: ReadOnly), texture_storage_2d ( TextureFormat :: Rgba32Float, StorageTextureAccess :: WriteOnly), uniform_buffer :: < HeatUniforms > ( false ), ), ), ); let shader = asset_server. load (SHADER_ASSET_PATH); let init_pipeline = pipeline_cache. queue_compute_pipeline (ComputePipelineDescriptor { layout: vec! [texture_bind_group_layout. clone ()], shader: shader. clone (), entry_point: Some ( Cow :: from ( "init" )), .. default () }); let update_pipeline = pipeline_cache. queue_compute_pipeline (ComputePipelineDescriptor { layout: vec! [texture_bind_group_layout. clone ()], shader, entry_point: Some ( Cow :: from ( "update" )), .. default () }); commands. insert_resource (HeatPipeline { texture_bind_group_layout, init_pipeline, update_pipeline, }); } #[derive(Resource, Default )] enum HeatState { #[default] Loading, Init, Update ( usize ), } fn update ( pipeline: Res < HeatPipeline > , pipeline_cache: Res < PipelineCache > , mut state: ResMut < HeatState > , ) { match * state { HeatState :: Loading => { match pipeline_cache. get_compute_pipeline_state (pipeline.init_pipeline) { CachedPipelineState :: Ok (_) => { * state = HeatState :: Init; } // シェーダーがまだ読み込まれていなければ待つ。 CachedPipelineState :: Err ( ShaderCacheError :: ShaderNotLoaded (_)) => {} CachedPipelineState :: Err (err) => { panic! ( "Initializing assets/{SHADER_ASSET_PATH}: \n {err}" ) } _ => {} } } HeatState :: Init => { if let CachedPipelineState :: Ok (_) = pipeline_cache. get_compute_pipeline_state (pipeline.update_pipeline) { * state = HeatState :: Update ( 1 ); } } HeatState :: Update ( 0 ) => { * state = HeatState :: Update ( 1 ); } HeatState :: Update ( 1 ) => { * state = HeatState :: Update ( 0 ); } HeatState :: Update (_) => unreachable! (), } } fn heat_diffusion ( mut render_context: RenderContext, bind_groups: Res < HeatImageBindGroups > , pipeline_cache: Res < PipelineCache > , pipeline: Res < HeatPipeline > , state: Res < HeatState > , ) { let mut pass = render_context . command_encoder () . begin_compute_pass ( & ComputePassDescriptor :: default ()); match * state { HeatState :: Loading => {} HeatState :: Init => { let init_pipeline = pipeline_cache . get_compute_pipeline (pipeline.init_pipeline) . unwrap (); pass. set_bind_group ( 0 , & bind_groups. 0 [ 0 ], & []); pass. set_pipeline (init_pipeline); pass. dispatch_workgroups (SIZE.x / WORKGROUP_SIZE, SIZE.y / WORKGROUP_SIZE, 1 ); } HeatState :: Update (index) => { let update_pipeline = pipeline_cache . get_compute_pipeline (pipeline.update_pipeline) . unwrap (); pass. set_bind_group ( 0 , & bind_groups. 0 [index], & []); pass. set_pipeline (update_pipeline); pass. dispatch_workgroups (SIZE.x / WORKGROUP_SIZE, SIZE.y / WORKGROUP_SIZE, 1 ); } } } assets/shaders/heat_diffusion.wgsl に、WGSLでGPU上で行いたい処理を記述します。有限差分法による計算や、計算結果をサーモグラフィー風の温度分布図にする処理を行っています。 @group(0) @binding(0) var input: texture_storage_2d<rgba32float, read>; @group(0) @binding(1) var output: texture_storage_2d<rgba32float, write>; @group(0) @binding(2) var<uniform> config: HeatUniforms; struct HeatUniforms { // マウスのブラシで与える温度と、外周に固定する低温の値 (Dirichlet 境界)。 hot: f32, cold: f32, // r = alpha * dt / dx^2。無次元の拡散数 (<= 0.25)。 diffusion_rate: f32, // マウス位置 (セル座標)、ボタンが押されているか (0/1)、ブラシの半径 (セル単位)。 mouse: vec2<f32>, mouse_down: f32, brush_radius: f32, } // 温度を色に変換する。赤チャンネルは (正規化した) 温度と常に等しくし、シミュレーション // の値そのものとして使う。緑・青で青 (低温) -> 緑 -> 赤 (高温) のヒートマップにする。 fn heat_color(temperature: f32) -> vec4<f32> { let span = max(config.hot - config.cold, 1e-6); let t = clamp((temperature - config.cold) / span, 0.0, 1.0); let r = t; let g = 1.0 - abs(t - 0.5) * 2.0; let b = 1.0 - t; return vec4<f32>(r, g, b, 1.0); } fn temp_at(loc: vec2<i32>) -> f32 { return textureLoad(input, loc).r; } // 初期条件: 全体を低温にする。熱は後からマウスで与える。 @compute @workgroup_size(8, 8, 1) fn init(@builtin(global_invocation_id) invocation_id: vec3<u32>) { let dims = vec2<i32>(textureDimensions(output)); let loc = vec2<i32>(i32(invocation_id.x), i32(invocation_id.y)); if (loc.x >= dims.x || loc.y >= dims.y) { return; } textureStore(output, loc, heat_color(config.cold)); } @compute @workgroup_size(8, 8, 1) fn update(@builtin(global_invocation_id) invocation_id: vec3<u32>) { let dims = vec2<i32>(textureDimensions(input)); let loc = vec2<i32>(i32(invocation_id.x), i32(invocation_id.y)); if (loc.x >= dims.x || loc.y >= dims.y) { return; } // Dirichlet 境界条件: 領域の外周はすべて低温に固定する。 if (loc.x == 0 || loc.x == dims.x - 1 || loc.y == 0 || loc.y == dims.y - 1) { textureStore(output, loc, heat_color(config.cold)); return; } let center = temp_at(loc); let left = temp_at(loc + vec2<i32>(-1, 0)); let right = temp_at(loc + vec2<i32>(1, 0)); let up = temp_at(loc + vec2<i32>(0, -1)); let down = temp_at(loc + vec2<i32>(0, 1)); let laplacian = left + right + up + down - 4.0 * center; var new_t = center + config.diffusion_rate * laplacian; // マウスのブラシ: ボタンを押している間、カーソルから brush_radius 以内のセルを // 熱源として高温に固定する。 if (config.mouse_down > 0.5) { let d = vec2<f32>(f32(loc.x), f32(loc.y)) - config.mouse; if (dot(d, d) <= config.brush_radius * config.brush_radius) { new_t = config.hot; } } textureStore(output, loc, heat_color(new_t)); } 実行結果 以上をwasm向けにビルドし、サーバーを立ててブラウザからアクセスします。環境によっては実行するブラウザの設定を変え、WebGPUを有効にしなければ起動しません。 WebGPU熱拡散シミュレーション 初期状態は青一色(低温)ですが、カーソルでドラッグした部分が赤(高温)になります。時間が経つと、熱が拡散していき、温度が平均化されていく様子を観察できます。 この実行はUbuntu上のFirefoxで試しており、FPSも安定していました。Chromiumでも試しましたが、FPSが20程度で、環境によってはWebGPUの性能は安定しないようです。ネイティブ向けのバイナリにビルドすることもでき、そちらはもちろん問題なく動いていました。 まとめと感想 今回のコードは、シミュレーション対象と使いたい数式、モデル、可視化の方法をClaudeに伝えて実装してもらいました。GPUの処理能力を活用するためにWGSLのようなシェーディング言語を学ぶのはこれまでハードルが高かったのですが、生成AIの発達でかなり簡単に実装できるようになりました。 bevyはWebGPUの呼び出しやマウスイベントの処理を簡単にでき、マルチプラットフォームなため、ゲームだけでなくこのような可視化を行うアプリケーションのフレームワークとしても有用に感じられました。 WebGPUはまだブラウザ側で設定を有効にしないと動かなかったり、FPSが出ないものがあったりと未熟さを感じました。数値シミュレーションをやらせるなら、倍精度浮動小数点数が使えないのも残念です。ただブラウザ上でさくっとGPUによるシミュレーションと可視化が動くというのは、Webアプリケーションやゲームでの用途が広がりそうで興味深いです。






















