diff --git a/docs/HD-RENDERER.md b/docs/HD-RENDERER.md index 3036092..4227296 100644 --- a/docs/HD-RENDERER.md +++ b/docs/HD-RENDERER.md @@ -19,9 +19,13 @@ Horizon действует правило clean-room. Исключение — P | Что | Где | |---|---| -| Весь HD-конвейер: цели, проходы, WGSL-шейдеры (строками), тайлы света, AO, тени, bloom, tonemap, TAA | `horizon/crates/horizon-client/src/gfx/hd.rs` | -| Объёмные облака (рэймарч слоя, тени облаков на землю) и объёмный туман (лучи света через тени каскадов), их цели и проходы; CPU-шум (2D, 3D Worley) | `horizon/crates/horizon-client/src/gfx/hd_volumes.rs`, `hd_noise.rs` | -| Атмосфера: сборка текстуры неба (WGSL), чтение неба/дымки/тона света в шейдерах, цвет солнца (`sun_transmittance`) | `horizon/crates/horizon-client/src/gfx/hd_sky.rs` (+ `THIRD_PARTY_PHOTON.md`) | +| Оркестровка HD: `Hd`, общие цели, буфер кадра, `resize`/`write`, сборка шейдеров (`assemble`: прелюдия + тело), контракты цвета/глубины/альф/времени (комментарий в начале файла) | `horizon/crates/horizon-client/src/gfx/hd/mod.rs` | +| Униформ кадра `HdFrame` (Rust) и сцена `HdScene`/`HdLight`/`HdSettings`, свет солнца/луны/облаков (`light_of`, `cloud_light`); общая WGSL-прелюдия (`HdFrame`, `FullOut`, `vs_full`) | `gfx/hd/frame.rs`, `gfx/hd/prelude.wgsl` | +| Тени (каскады, `Shadows`, `cascades()`); G-буфер (`GBuffer`, форматы) | `gfx/hd/shadows.rs`; `gfx/hd/gbuffer.rs` | +| AO (GTAO + блюр); освещение `fs_light` (+ тайлы источников: `tiles.rs`); вода (проход геометрии и композит) | `gfx/hd/ao.rs` + `ao.wgsl`, `ao_blur.wgsl`; `gfx/hd/lighting.rs` + `light.wgsl`, `gfx/hd/tiles.rs`; `gfx/hd/water.rs` + `water.wgsl` | +| TAA/TAAU и джиттер; bloom; tonemap (+ `Hd::finish`) | `gfx/hd/taa.rs` + `taa.wgsl`; `gfx/hd/bloom.rs` + `bloom.wgsl`; `gfx/hd/tonemap.rs` + `tonemap.wgsl` | +| Объёмные облака (рэймарч слоя, тени облаков на землю) и объёмный туман, их цели и проходы; CPU-шум (2D, 3D Worley) | `gfx/hd/volumes.rs` + `cloud_common.wgsl`, `cloud.wgsl`, `cloud_shadow.wgsl`, `fog.wgsl`; `gfx/hd/noise.rs` | +| Атмосфера: сборка текстуры неба (WGSL), чтение неба/дымки/тона света в шейдерах, цвет солнца (`sun_transmittance`) | `gfx/hd/sky.rs` + `sky.wgsl`, `sky_funcs.wgsl` (+ `THIRD_PARTY_PHOTON.md`) | | Встраивание в кадр: G-буфер-проход, каскады теней, вызовы `hd.light` / `hd.finish`, джиттер, тайминги | `horizon/crates/horizon-client/src/gfx.rs` (`Renderer::render`, ищи `hd_on`, `AirDef fork:`) | | G-буфер террейна: `fs_gbuffer`, `fs_shadow` | `horizon/crates/horizon-client/src/terrain.wgsl` | | G-буфер сущностей и моделей мода: `fs_entity_gbuffer`, `fs_entity_shadow` | `horizon/crates/horizon-client/src/entity.wgsl` | @@ -120,6 +124,28 @@ Bind groups кэшируются и пересоздаются только пр Композит воды (`WATER`, group 0): 0 `HdFrame`, 1 `lit`, 2 глубина G-буфера, 3 цвет воды, 4 нормаль воды, 5 глубина воды, 6–7 тени, 8 лайтмап, 9 сэмплер, 10 текстура неба. Проход неба (`SKY_PASS`, group 0): только `HdFrame`. +## Контракты (цвет, глубина, альфа, время) + +Полная таблица «проход: что читает → что пишет» — в начале `gfx/hd/mod.rs`, подробности — в начале файла каждого прохода. + +- **Цвет.** От освещения до tonemap всё в «показанном» пространстве ванили (гамма, основные цвета Rec. 709), значения могут быть > 1 + (`Rgba16Float`); tonemap не трогает ≤ 0.8. Исключения: текстура неба — линейная яркость Rec. 709 (марш в Rec. 2020; показывают + читатели через `sky_show`); albedo G-буфера — `Rgba8Unorm` в том же показанном пространстве. +- **Глубина.** Камера: reversed-Z, `Depth32Float`, 1 — близко, 0 — далеко/ничего (очистка в 0; глубина воды 0 — воды нет). Тени: + обычная Z ортопроекции света (0 — у света, 1 — далеко), сравнение `<=`. +- **Альфа.** albedo.a — эмиссия (свет добавляет `rgb·a·1.5`); `lit.a`: 1 — обычный пиксель, 0.5 — вода (в rgb дно без воздуха), + 0.6 — прозрачное перед водой; `air.a` — пропускание воздуха; облака и туман: `a` — пропускание (`c·a + rgb`); вода: цвет.a — + свет блоков, нормаль.a — свет неба; история TAA: a — дистанция; AO: x — окклюзия, y — дистанция. +- **Координаты.** Позиции относительно камеры; для узоров (волны, шум облаков, ветер) мировая координата передаётся по модулю периода + (256, 65536). Мировая проекция с джиттером; `prev_view_proj` — с джиттером для `fs_taa` и без для `fs_taau` (выбирает `Hd::write`). +- **Время.** Три разных часа: счётчик кадров (`params.w`, mod 64, вращение шума), время воды (`water.y`, секунды стенных часов mod 600), + игровое время (`clouds.w`, секунды `HdScene.seconds` mod 300000, ветер облаков). Реплей, замораживающий игровое время, не + останавливает воду. +- **Истории.** Две цели TAA и две цели облаков принадлежат своим проходам, создаются в `resize`, сбрасываются при resize, телепорте + (> 64 блоков), выключенном TAA; один `Hd` обслуживает одну камеру, истории разных камер не смешиваются. +- **Размеры.** world — масштабированная цель мира (G-буфер, AO ½, свет, вода, облака/туман ½), out — окно (TAA, bloom, tonemap). +- **Bind groups** кэшируются по видам, которые читают; пересоздаются при resize и смене входного вида; нет роста в установившемся кадре. + ## Как проверять ```bash @@ -129,8 +155,10 @@ cargo test -p horizon-client --lib hd # naga-разбор всех HD-ш cd ../airdef-mod && cargo horizon-mod build && cargo test # мод и его шейдер ``` -WGSL-ошибки в `hd.rs` всплывают только в рантайме — поэтому каждый новый шейдер добавляй в naga-тест -`lighting_shader_parses`. +WGSL-ошибки всплывают только в рантайме — поэтому каждый новый шейдер добавляй в список `shaders()` в тестах +`gfx/hd/mod.rs`: `lighting_shader_parses` (naga-разбор каждого итогового шейдера), `every_wgsl_file_is_tested` (каждый `.wgsl` +входит в проверенный шейдер), `bindings_match_the_layouts` (привязки WGSL = `*_BINDINGS` в Rust: номера, виды, размерности), +`frame_layout_matches_the_prelude` (поля и размер `HdFrame` в Rust и в прелюдии). Игра офскрин (только одна копия за раз; данные в `run-home/`, мир `Polygon`): @@ -190,11 +218,12 @@ HORIZON_HD_TAA=0 --out run-home-bench/out/taa-off` — A/B; `--baseline run-home | #35: ванильные облака (HD-облака выключены) красятся закатным цветом в собственном проходе (`hd::vanilla_cloud_tint` → цвет в `clouds::Input`), эвристика по глубине G-буфера убрана из `fs_light` | готово | в рабочем дереве форка | | #37: воздух (ванильный туман, aerial, объёмный туман, лучи, ореолы) на воде считается до **поверхности** и кладётся один раз поверх готовой воды: `fs_light` пишет во вторую цель `air` (рассеяние + пропускание), `fs_water` применяет её после поглощения | готово | в рабочем дереве форка | | #36: ванильная вода не рисует цвет в HD (`fs_translucent` при `Globals.hd_flags.x`, глубину оставляет); прозрачное перед водой (`d` ближе `wd`) не отключает HD-воду: вода считается на освещённом дне и добавляется к сцене с весом 0.7; преломление не берёт тексели с таким прозрачным (`textureGather` по альфе) | готово (проверены стекло; частицы и scale 0.67 не проверялись) | в рабочем дереве форка | +| #45: `gfx/hd.rs` разделён на модуль `gfx/hd/` (по файлу на проход: `shadows`, `gbuffer`, `ao`, `sky`, `volumes`, `lighting`+`tiles`, `water`, `taa`, `bloom`, `tonemap`, `frame`), WGSL вынесен в `.wgsl` (`include_str!`, общая прелюдия), у каждого прохода своя структура ресурсов/пайплайнов; контракты цвета, глубины, альф и времени записаны в `hd/mod.rs` и в начале файлов проходов; тесты привязок и размера `HdFrame`. Вид не менялся (сверка `tools/hd_bench.py`) | готово | в рабочем дереве форка | | #39: веер восхода `vanilla_sunrise_weight` отсекается до цикла по 16 треугольникам выше горизонта (знак x стороны солнца и наклон ≤ α/3; проверено перебором 200 тыс. лучей без пропусков); `hd lighting` на рассвете 5.3 → 3.3 мс (M-серия, 2560×1440) | готово | в рабочем дереве форка | ## План (по порядку) и ТЗ -Каждый пункт — самостоятельная задача. Перед началом прочитай `hd.rs` целиком. +Каждый пункт — самостоятельная задача. Перед началом прочитай `gfx/hd/mod.rs` (контракты) и файл нужного прохода. 1. **TAAU — временной апскейлер** (поверх TAA) — СДЕЛАНО (патч 18, см. статус; масштаб — `HORIZON_HD_SCALE`, переопределяет «масштаб разрешения» настроек Horizon только для HD; поля в `HdSettings` нет). Осталось: LOD-bias текстур террейна, MetalFX. Исходное ТЗ: Мир и G-буфер рендерятся в `render_scale` (например 0.67), TAA-проход восстанавливает полное разрешение: история в полном разрешении, текущий кадр семплируется с учётом @@ -266,7 +295,7 @@ HORIZON_HD_TAA=0 --out run-home-bench/out/taa-off` — A/B; `--baseline run-home - **Облака (24).** Слой 192.33…264.33 блока (`CLOUD_BASE/CLOUD_THICKNESS`), ветер 3 блока/с (`CLOUD_WIND`), шум — текстуры, сгенерированные на CPU при создании HD (`hd_noise.rs`: 2D 256² покрытие/форма, 3D 64³ Worley). Плотность — по `clouds_cumulus_density` Photon (порог покрытия × форма, «яйцо» по высоте, эрозия Worley, резкий верх), рассеяние — `clouds_cumulus_scattering` (октавы, пудра, фазы). Цвет света — `cloud_light` (Rust): пропускание атмосферы на высоте солнца; солнце светит облакам до −0.2 по высоте, дальше луна. Воздушная перспектива `exp(−d/3600)` к цвету дымки. История сбрасывается при resize, телепорте и без TAA. Опция ванильных облаков «выкл» → `frame.clouds` пуст → нет ни облаков, ни теней. Тень: `cloud_shadow` в `fs_light` (карта оптической толщины; гаснет при солнце ниже ~0.1–0.25 по высоте). - **Туман (25).** `fs_fog`: 18 шагов, плотность `fog_sigma` (высотная дымка от y=62, масштаб 42; утренний туман — пока солнце на «утренней» стороне и низко; пятна из 3D-шума; дождь; затухание ниже y≈28–58, чтобы не светить в пещерах), свет — Photon-смесь двух HG, «вечернее свечение» ×1…3. Старые 14 шагов лучей остаются при `HORIZON_HD_VOLFOG=0`; ореолы вокруг источников мода — всегда. - **Тайминги.** Метки Metal (`HORIZON_SHADER_PACK_TIMING=1`, Hills, 2560×1440): `hd clouds` ≈ 6 мс (завышено: метка ловит ожидание соседних проходов), `hd cloud shadows` 0.2–3 (шум), `hd fog` ≈ 1.3. По среднему кадру GPU «оба выкл → оба вкл»: +0.2…3.7 мс (замеры шумные: рядом шла чужая игра на том же GPU). Как удешевить: у облаков — длина шага (14) и потолок шагов (26) в `fs_cloud`, 3 шага света, 4 октавы, облака в четверть разрешения; у тумана — `FOG_STEPS`. -- **Разработка шейдеров.** `HORIZON_HD_SHADER_DIR=<папка>`: каждый HD-шейдер читается из `<папка>/<метка>.wgsl` (записывается из встроенного, если файла нет) — правки видны после перезапуска игры без пересборки; готовое переносится в константы вручную. +- **Разработка шейдеров.** `HORIZON_HD_SHADER_DIR=<папка>`: каждый HD-шейдер читается из `<папка>/<метка>.wgsl` (записывается из встроенного, если файла нет; это тело без прелюдии, она добавляется всегда) — правки видны после перезапуска игры без пересборки; готовое переносится в `gfx/hd/*.wgsl` вручную. - **Слабые места.** Облака не отражаются в воде (SSR берёт небо без облаков); не закрывают далёкую землю выше слоя (только небо); карта теней облаков ±1200 блоков и почти не работает при солнце ниже ~10°; туман не знает рельефа (только высоту над y=62); нет перистых облаков; на быстром повороте камеры история облаков отбрасывается (кратковременный шум). ## Заметки по исправлениям #35–#41 (преемнику) diff --git a/horizon-patches/0001-Mod-API-AirDef-fork-world-models-client-particles-so.patch b/horizon-patches/0001-Mod-API-AirDef-fork-world-models-client-particles-so.patch index 7c0bf8d..cb33b93 100644 --- a/horizon-patches/0001-Mod-API-AirDef-fork-world-models-client-particles-so.patch +++ b/horizon-patches/0001-Mod-API-AirDef-fork-world-models-client-particles-so.patch @@ -1,7 +1,7 @@ From 3de7a6875140a107e28563cc44489b55f5794517 Mon Sep 17 00:00:00 2001 From: chexit Date: Wed, 28 Oct 2026 12:37:45 +0300 -Subject: [PATCH 01/25] Mod API (AirDef fork): world models, client particles, +Subject: [PATCH 01/27] Mod API (AirDef fork): world models, client particles, sounds, ground heights render.set-models draws block models with an interpolated pose per id; diff --git a/horizon-patches/0002-cargo-horizon-mod-report-particles-and-sounds.patch b/horizon-patches/0002-cargo-horizon-mod-report-particles-and-sounds.patch index 96483c0..946dba9 100644 --- a/horizon-patches/0002-cargo-horizon-mod-report-particles-and-sounds.patch +++ b/horizon-patches/0002-cargo-horizon-mod-report-particles-and-sounds.patch @@ -1,7 +1,7 @@ From a6d64e6415bf618539af464e521091e72b72d72f Mon Sep 17 00:00:00 2001 From: chexit Date: Wed, 28 Oct 2026 12:39:45 +0300 -Subject: [PATCH 02/25] cargo-horizon-mod: report particles and sounds +Subject: [PATCH 02/27] cargo-horizon-mod: report particles and sounds Co-Authored-By: Claude Opus 5.5 --- diff --git a/horizon-patches/0003-Mod-API-AirDef-fork-full-screen-post-pass-for-mods.patch b/horizon-patches/0003-Mod-API-AirDef-fork-full-screen-post-pass-for-mods.patch index aa0f577..0ceff45 100644 --- a/horizon-patches/0003-Mod-API-AirDef-fork-full-screen-post-pass-for-mods.patch +++ b/horizon-patches/0003-Mod-API-AirDef-fork-full-screen-post-pass-for-mods.patch @@ -1,7 +1,7 @@ From ee79b3562feebe51959a01f1585a9e85bd53ccb5 Mon Sep 17 00:00:00 2001 From: chexit Date: Wed, 28 Oct 2026 13:33:10 +0300 -Subject: [PATCH 03/25] Mod API (AirDef fork): full-screen post pass for mods +Subject: [PATCH 03/27] Mod API (AirDef fork): full-screen post pass for mods render.set-post compiles a mod's WGSL after a prelude (camera matrices, time, 256 vec4 of params, the world's colour and depth) and runs it after diff --git a/horizon-patches/0004-Mod-models-draw-far-models-as-scaled-impostors-past-.patch b/horizon-patches/0004-Mod-models-draw-far-models-as-scaled-impostors-past-.patch index 3f8b7e0..5d83e47 100644 --- a/horizon-patches/0004-Mod-models-draw-far-models-as-scaled-impostors-past-.patch +++ b/horizon-patches/0004-Mod-models-draw-far-models-as-scaled-impostors-past-.patch @@ -1,7 +1,7 @@ From 2b137dbbedd540daeebc7f5e387847aeb56a1355 Mon Sep 17 00:00:00 2001 From: chexit Date: Wed, 28 Oct 2026 22:09:30 +0300 -Subject: [PATCH 04/25] Mod models: draw far models as scaled impostors past +Subject: [PATCH 04/27] Mod models: draw far models as scaled impostors past the far plane, cull at 4096 --- diff --git a/horizon-patches/0005-Mod-cameras-render.set-views-draws-the-world-from-ot.patch b/horizon-patches/0005-Mod-cameras-render.set-views-draws-the-world-from-ot.patch index ed566c5..1f03148 100644 --- a/horizon-patches/0005-Mod-cameras-render.set-views-draws-the-world-from-ot.patch +++ b/horizon-patches/0005-Mod-cameras-render.set-views-draws-the-world-from-ot.patch @@ -1,7 +1,7 @@ From c8ebca6e0af68630e65211844b34d25c5b985c03 Mon Sep 17 00:00:00 2001 From: chexit Date: Wed, 28 Oct 2026 22:31:00 +0300 -Subject: [PATCH 05/25] Mod cameras: render.set-views draws the world from +Subject: [PATCH 05/27] Mod cameras: render.set-views draws the world from other points into pictures that HUD view shapes show (API level 9) Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0006-Mods-more-fuel-per-tick-and-per-event-AirDef-plans-r.patch b/horizon-patches/0006-Mods-more-fuel-per-tick-and-per-event-AirDef-plans-r.patch index 6994a4e..8cd636f 100644 --- a/horizon-patches/0006-Mods-more-fuel-per-tick-and-per-event-AirDef-plans-r.patch +++ b/horizon-patches/0006-Mods-more-fuel-per-tick-and-per-event-AirDef-plans-r.patch @@ -1,7 +1,7 @@ From 8d2261fc4f8072c32e454139cfea7a8c0cd9d664 Mon Sep 17 00:00:00 2001 From: chexit Date: Wed, 28 Oct 2026 23:08:21 +0300 -Subject: [PATCH 06/25] Mods: more fuel per tick and per event (AirDef plans +Subject: [PATCH 06/27] Mods: more fuel per tick and per event (AirDef plans raids) Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0007-Mod-cameras-up-to-1920x1080-full-screen-replays.patch b/horizon-patches/0007-Mod-cameras-up-to-1920x1080-full-screen-replays.patch index 26234ff..5c60249 100644 --- a/horizon-patches/0007-Mod-cameras-up-to-1920x1080-full-screen-replays.patch +++ b/horizon-patches/0007-Mod-cameras-up-to-1920x1080-full-screen-replays.patch @@ -1,7 +1,7 @@ From 6c548de34def8e4a624d734243418090798bd16a Mon Sep 17 00:00:00 2001 From: chexit Date: Wed, 28 Oct 2026 23:25:29 +0300 -Subject: [PATCH 07/25] Mod cameras up to 1920x1080 (full-screen replays) +Subject: [PATCH 07/27] Mod cameras up to 1920x1080 (full-screen replays) Co-Authored-By: Claude Opus 5.5 --- diff --git a/horizon-patches/0008-Mod-cameras-distant-terrain-tiles-fog-measured-from-.patch b/horizon-patches/0008-Mod-cameras-distant-terrain-tiles-fog-measured-from-.patch index f253d67..4256dd0 100644 --- a/horizon-patches/0008-Mod-cameras-distant-terrain-tiles-fog-measured-from-.patch +++ b/horizon-patches/0008-Mod-cameras-distant-terrain-tiles-fog-measured-from-.patch @@ -1,7 +1,7 @@ From 9b9e93269d67401cc620567a884d5ce97f68d76e Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 11:15:11 +0300 -Subject: [PATCH 08/25] Mod cameras: distant terrain tiles, fog measured from +Subject: [PATCH 08/27] Mod cameras: distant terrain tiles, fog measured from the camera, no impostors while one is shown Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0009-Mods-game.world-id-so-mods-keep-state-per-world-API-.patch b/horizon-patches/0009-Mods-game.world-id-so-mods-keep-state-per-world-API-.patch index 3461de0..14aafb4 100644 --- a/horizon-patches/0009-Mods-game.world-id-so-mods-keep-state-per-world-API-.patch +++ b/horizon-patches/0009-Mods-game.world-id-so-mods-keep-state-per-world-API-.patch @@ -1,7 +1,7 @@ From 065d9fa02966238a5bd9ff460392a1a809db0b11 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 11:25:45 +0300 -Subject: [PATCH 09/25] Mods: game.world-id, so mods keep state per world (API +Subject: [PATCH 09/27] Mods: game.world-id, so mods keep state per world (API level 9) Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0010-cargo-horizon-mod-trial-runs-behind-feature-full-so-.patch b/horizon-patches/0010-cargo-horizon-mod-trial-runs-behind-feature-full-so-.patch index c2c204c..37daee2 100644 --- a/horizon-patches/0010-cargo-horizon-mod-trial-runs-behind-feature-full-so-.patch +++ b/horizon-patches/0010-cargo-horizon-mod-trial-runs-behind-feature-full-so-.patch @@ -1,7 +1,7 @@ From 1bf28135fd9a31f837323dc3a8d81ed73343d816 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 12:01:08 +0300 -Subject: [PATCH 10/25] cargo-horizon-mod: trial runs behind feature full, so a +Subject: [PATCH 10/27] cargo-horizon-mod: trial runs behind feature full, so a packing-only tool skips wasmtime Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0011-HD-lighting-G-buffer-pass-per-pixel-mod-point-lights.patch b/horizon-patches/0011-HD-lighting-G-buffer-pass-per-pixel-mod-point-lights.patch index 4af1037..5b1a429 100644 --- a/horizon-patches/0011-HD-lighting-G-buffer-pass-per-pixel-mod-point-lights.patch +++ b/horizon-patches/0011-HD-lighting-G-buffer-pass-per-pixel-mod-point-lights.patch @@ -1,7 +1,7 @@ From 0a56f5616df4699588cbcc529d4720661baa810f Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 13:18:43 +0300 -Subject: [PATCH 11/25] HD lighting: G-buffer pass, per-pixel mod point lights +Subject: [PATCH 11/27] HD lighting: G-buffer pass, per-pixel mod point lights in HDR, bloom and tone curve; render.set-lights and render.set-lighting (API level 10) diff --git a/horizon-patches/0012-HD-lighting-stage-2-sun-and-moon-shadow-cascades-the.patch b/horizon-patches/0012-HD-lighting-stage-2-sun-and-moon-shadow-cascades-the.patch index f961a16..4ef7699 100644 --- a/horizon-patches/0012-HD-lighting-stage-2-sun-and-moon-shadow-cascades-the.patch +++ b/horizon-patches/0012-HD-lighting-stage-2-sun-and-moon-shadow-cascades-the.patch @@ -1,7 +1,7 @@ From 9ebf0031fe9ba6b7f02afb26e4fd3a1ba4ddb0d0 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 13:59:43 +0300 -Subject: [PATCH 12/25] HD lighting stage 2: sun and moon shadow cascades, the +Subject: [PATCH 12/27] HD lighting stage 2: sun and moon shadow cascades, the world relit (sun by face angle and shadow, sky and block light through the lightmap), light shafts and halos, fog over it again, a light colour grade diff --git a/horizon-patches/0013-HD-bind-groups-cached-until-a-resize-or-a-new-source.patch b/horizon-patches/0013-HD-bind-groups-cached-until-a-resize-or-a-new-source.patch index 51fd635..1cea5bc 100644 --- a/horizon-patches/0013-HD-bind-groups-cached-until-a-resize-or-a-new-source.patch +++ b/horizon-patches/0013-HD-bind-groups-cached-until-a-resize-or-a-new-source.patch @@ -1,7 +1,7 @@ From 7a5a38f68923aec62f10bfa0df50b436474ed612 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 16:19:53 +0300 -Subject: [PATCH 13/25] HD: bind groups cached until a resize or a new source, +Subject: [PATCH 13/27] HD: bind groups cached until a resize or a new source, shadow passes draw only the entities that cast shadows Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0014-HD-lights-culled-per-16x16-tile-surface-and-halo-lis.patch b/horizon-patches/0014-HD-lights-culled-per-16x16-tile-surface-and-halo-lis.patch index b2c6412..795996a 100644 --- a/horizon-patches/0014-HD-lights-culled-per-16x16-tile-surface-and-halo-lis.patch +++ b/horizon-patches/0014-HD-lights-culled-per-16x16-tile-surface-and-halo-lis.patch @@ -1,7 +1,7 @@ From 8020811e57d4b5a9ea1cd72d30ce859dc5095d35 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 16:25:44 +0300 -Subject: [PATCH 14/25] HD: lights culled per 16x16 tile (surface and halo +Subject: [PATCH 14/27] HD: lights culled per 16x16 tile (surface and halo lists built on the CPU), a naga test for the lighting shaders Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0015-HD-GPU-time-per-pass-in-the-F3-timing-list-half-reso.patch b/horizon-patches/0015-HD-GPU-time-per-pass-in-the-F3-timing-list-half-reso.patch index 55d8e7e..a7c94f3 100644 --- a/horizon-patches/0015-HD-GPU-time-per-pass-in-the-F3-timing-list-half-reso.patch +++ b/horizon-patches/0015-HD-GPU-time-per-pass-in-the-F3-timing-list-half-reso.patch @@ -1,7 +1,7 @@ From 72d3fddfea329e578162656151350f0aa2efd323 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 16:43:36 +0300 -Subject: [PATCH 15/25] HD: GPU time per pass in the F3 timing list, +Subject: [PATCH 15/27] HD: GPU time per pass in the F3 timing list, half-resolution GTAO with a depth-aware blur Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0016-HD-shadows-draw-only-sun-facing-quads-and-skip-burie.patch b/horizon-patches/0016-HD-shadows-draw-only-sun-facing-quads-and-skip-burie.patch index 755022f..f4fd807 100644 --- a/horizon-patches/0016-HD-shadows-draw-only-sun-facing-quads-and-skip-burie.patch +++ b/horizon-patches/0016-HD-shadows-draw-only-sun-facing-quads-and-skip-burie.patch @@ -1,7 +1,7 @@ From 1fd83a821bf270879d8ece5aa583f200ed920d89 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 17:02:02 +0300 -Subject: [PATCH 16/25] HD: shadows draw only sun-facing quads and skip buried +Subject: [PATCH 16/27] HD: shadows draw only sun-facing quads and skip buried sections, the far cascade every second frame; TAA (Halton jitter, reprojection by depth, YCoCg variance clipping) before bloom diff --git a/horizon-patches/0017-Mods-model-handles-render.model-id-model-generation-.patch b/horizon-patches/0017-Mods-model-handles-render.model-id-model-generation-.patch index 990cea8..d5ff475 100644 --- a/horizon-patches/0017-Mods-model-handles-render.model-id-model-generation-.patch +++ b/horizon-patches/0017-Mods-model-handles-render.model-id-model-generation-.patch @@ -1,7 +1,7 @@ From 1502d359d599228fe0f44ce6b99a3fded2ac5ea0 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 17:02:02 +0300 -Subject: [PATCH 17/25] Mods: model handles (render.model-id, model-generation, +Subject: [PATCH 17/27] Mods: model handles (render.model-id, model-generation, set-models-by-id; API level 11) so mods send no model names each tick; clear-post and set-lighting documented diff --git a/horizon-patches/0018-HD-temporal-upscaling-HORIZON_HD_SCALE-world-G-buffe.patch b/horizon-patches/0018-HD-temporal-upscaling-HORIZON_HD_SCALE-world-G-buffe.patch index 2a832fc..3526ebc 100644 --- a/horizon-patches/0018-HD-temporal-upscaling-HORIZON_HD_SCALE-world-G-buffe.patch +++ b/horizon-patches/0018-HD-temporal-upscaling-HORIZON_HD_SCALE-world-G-buffe.patch @@ -1,7 +1,7 @@ From 0f9d99b8ad3e4b72e621d84c2396cf1d3d2b7a33 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 17:19:57 +0300 -Subject: [PATCH 18/25] HD: temporal upscaling (HORIZON_HD_SCALE: world, +Subject: [PATCH 18/27] HD: temporal upscaling (HORIZON_HD_SCALE: world, G-buffer and lighting at a lower size, rebuilt to the window in the TAA pass); fix flickering shadows near the player (the near cascade lost its sections on frames the far one was held, the held far matrix ignored the diff --git a/horizon-patches/0019-HD-water-its-own-pass-colour-normal-depth-the-floor-.patch b/horizon-patches/0019-HD-water-its-own-pass-colour-normal-depth-the-floor-.patch index f6138a3..42d6c67 100644 --- a/horizon-patches/0019-HD-water-its-own-pass-colour-normal-depth-the-floor-.patch +++ b/horizon-patches/0019-HD-water-its-own-pass-colour-normal-depth-the-floor-.patch @@ -1,7 +1,7 @@ From 38250c4392e27d5700842ca6ee47291dd1831b72 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 17:47:52 +0300 -Subject: [PATCH 19/25] HD water: its own pass (colour, normal, depth), the +Subject: [PATCH 19/27] HD water: its own pass (colour, normal, depth), the floor under it lit, a composite with world-space waves, refraction with depth absorption in the biome colour, screen-space reflections, Fresnel and a shadowed sun glint (HORIZON_HD_WATER=0 to switch off) diff --git a/horizon-patches/0020-HD-water-no-vanilla-texture-on-the-surface-the-biome.patch b/horizon-patches/0020-HD-water-no-vanilla-texture-on-the-surface-the-biome.patch index 3044c26..81018ce 100644 --- a/horizon-patches/0020-HD-water-no-vanilla-texture-on-the-surface-the-biome.patch +++ b/horizon-patches/0020-HD-water-no-vanilla-texture-on-the-surface-the-biome.patch @@ -1,7 +1,7 @@ From dbc6f8a6e9c2eeabe1de15f1794013c90be7faa5 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 17:56:04 +0300 -Subject: [PATCH 20/25] HD water: no vanilla texture on the surface (the biome +Subject: [PATCH 20/27] HD water: no vanilla texture on the surface (the biome colour only), a darker, deeper colour Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0021-HD-sky-and-light-a-physical-atmosphere-Rayleigh-Mie-.patch b/horizon-patches/0021-HD-sky-and-light-a-physical-atmosphere-Rayleigh-Mie-.patch index 655097c..ce02767 100644 --- a/horizon-patches/0021-HD-sky-and-light-a-physical-atmosphere-Rayleigh-Mie-.patch +++ b/horizon-patches/0021-HD-sky-and-light-a-physical-atmosphere-Rayleigh-Mie-.patch @@ -1,7 +1,7 @@ From 13e74537dd6e63482e3613e0e416de1158944dfe Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 18:38:19 +0300 -Subject: [PATCH 21/25] HD sky and light: a physical atmosphere (Rayleigh, Mie, +Subject: [PATCH 21/27] HD sky and light: a physical atmosphere (Rayleigh, Mie, ozone; constants and transmittance after Photon, MIT) for the sky, haze, fog and water reflections; warmer sunlight from the atmosphere's transmittance, a gentle sky-coloured ambient, soft PCSS-lite shadows near the player, a haze diff --git a/horizon-patches/0022-HD-water-a-darker-blue-a-little-clearer-ripples-a-li.patch b/horizon-patches/0022-HD-water-a-darker-blue-a-little-clearer-ripples-a-li.patch index 2941e5f..055702e 100644 --- a/horizon-patches/0022-HD-water-a-darker-blue-a-little-clearer-ripples-a-li.patch +++ b/horizon-patches/0022-HD-water-a-darker-blue-a-little-clearer-ripples-a-li.patch @@ -1,7 +1,7 @@ From 6277e051a89c2537570982f6ef275887193c05cf Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 19:02:16 +0300 -Subject: [PATCH 22/25] HD water: a darker blue, a little clearer, ripples a +Subject: [PATCH 22/27] HD water: a darker blue, a little clearer, ripples a little higher Co-Authored-By: Claude Opus 5.5 diff --git a/horizon-patches/0023-HD-Photon-style-sunsets-Rec.-2020-atmosphere-sun-tin.patch b/horizon-patches/0023-HD-Photon-style-sunsets-Rec.-2020-atmosphere-sun-tin.patch index 70d5c32..09938d1 100644 --- a/horizon-patches/0023-HD-Photon-style-sunsets-Rec.-2020-atmosphere-sun-tin.patch +++ b/horizon-patches/0023-HD-Photon-style-sunsets-Rec.-2020-atmosphere-sun-tin.patch @@ -1,7 +1,7 @@ From 982265d21bb9d74ec0040db03feb5a55762286ad Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 21:41:48 +0300 -Subject: [PATCH 23/25] HD: Photon-style sunsets (Rec. 2020 atmosphere, sun +Subject: [PATCH 23/27] HD: Photon-style sunsets (Rec. 2020 atmosphere, sun tint, blue hour; MIT), volumetric clouds with ground shadows instead of vanilla's in HD, volumetric fog with sun shafts and morning mist (HORIZON_HD_CLOUDS=0, HORIZON_HD_VOLFOG=0) diff --git a/horizon-patches/0024-Mods-world-queries-for-simulations-render.query-rays.patch b/horizon-patches/0024-Mods-world-queries-for-simulations-render.query-rays.patch index 3a8c068..2068d67 100644 --- a/horizon-patches/0024-Mods-world-queries-for-simulations-render.query-rays.patch +++ b/horizon-patches/0024-Mods-world-queries-for-simulations-render.query-rays.patch @@ -1,7 +1,7 @@ From 24971b3c67d8c87673eb2e0d204cedf8a2f46d1c Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 21:43:22 +0300 -Subject: [PATCH 24/25] Mods: world queries for simulations (render.query-rays, +Subject: [PATCH 24/27] Mods: world queries for simulations (render.query-rays, query-sections, world-changes; API level 12): block-exact rays and section occupancy by collision, sight or sound, answered next tick within budgets, and a log of changed sections diff --git a/horizon-patches/0025-HD-fixes-rain-level-from-the-world-not-from-rain-geo.patch b/horizon-patches/0025-HD-fixes-rain-level-from-the-world-not-from-rain-geo.patch index f79755d..833241e 100644 --- a/horizon-patches/0025-HD-fixes-rain-level-from-the-world-not-from-rain-geo.patch +++ b/horizon-patches/0025-HD-fixes-rain-level-from-the-world-not-from-rain-geo.patch @@ -1,7 +1,7 @@ From fdec4960983bdff82f3793460f9a5234f0cd3f49 Mon Sep 17 00:00:00 2001 From: chexit Date: Thu, 29 Oct 2026 22:56:15 +0300 -Subject: [PATCH 25/25] HD fixes: rain level from the world not from rain +Subject: [PATCH 25/27] HD fixes: rain level from the world not from rain geometry (#41), TAA history on the jittered grid (#38), vanilla cloud tint without a depth heuristic (#35), air fog once over water (#37), translucent things in front of HD water (#36), cheaper sunrise fan (#39), halos in thick diff --git a/horizon-patches/0026-HD-split-into-modules-gfx-hd-one-Rust-file-and-one-W.patch b/horizon-patches/0026-HD-split-into-modules-gfx-hd-one-Rust-file-and-one-W.patch new file mode 100644 index 0000000..4cc6b71 --- /dev/null +++ b/horizon-patches/0026-HD-split-into-modules-gfx-hd-one-Rust-file-and-one-W.patch @@ -0,0 +1,9341 @@ +From 21391afb26f49505d6cdaf454a6355cd4e747503 Mon Sep 17 00:00:00 2001 +From: chexit +Date: Thu, 29 Oct 2026 23:19:53 +0300 +Subject: [PATCH 26/27] HD split into modules (gfx/hd/: one Rust file and one + WGSL file per pass, a shared prelude), contracts for colour, depth, alpha, + time and coordinates written down, tests that the frame layout and bindings + match between Rust and WGSL (#45) + +Co-Authored-By: Claude Opus 5.5 +--- + crates/horizon-client/src/gfx.rs | 3 - + crates/horizon-client/src/gfx/hd.rs | 3414 ----------------- + crates/horizon-client/src/gfx/hd/ao.rs | 159 + + crates/horizon-client/src/gfx/hd/ao.wgsl | 93 + + crates/horizon-client/src/gfx/hd/ao_blur.wgsl | 28 + + crates/horizon-client/src/gfx/hd/bloom.rs | 148 + + crates/horizon-client/src/gfx/hd/bloom.wgsl | 52 + + crates/horizon-client/src/gfx/hd/cloud.wgsl | 146 + + .../src/gfx/hd/cloud_common.wgsl | 71 + + .../src/gfx/hd/cloud_shadow.wgsl | 18 + + crates/horizon-client/src/gfx/hd/fog.wgsl | 124 + + crates/horizon-client/src/gfx/hd/frame.rs | 205 + + crates/horizon-client/src/gfx/hd/gbuffer.rs | 81 + + crates/horizon-client/src/gfx/hd/light.wgsl | 397 ++ + crates/horizon-client/src/gfx/hd/lighting.rs | 265 ++ + crates/horizon-client/src/gfx/hd/mod.rs | 896 +++++ + .../src/gfx/{hd_noise.rs => hd/noise.rs} | 0 + crates/horizon-client/src/gfx/hd/prelude.wgsl | 39 + + crates/horizon-client/src/gfx/hd/shadows.rs | 121 + + crates/horizon-client/src/gfx/hd/sky.rs | 160 + + crates/horizon-client/src/gfx/hd/sky.wgsl | 172 + + .../horizon-client/src/gfx/hd/sky_funcs.wgsl | 139 + + crates/horizon-client/src/gfx/hd/taa.rs | 299 ++ + crates/horizon-client/src/gfx/hd/taa.wgsl | 215 ++ + crates/horizon-client/src/gfx/hd/tiles.rs | 186 + + crates/horizon-client/src/gfx/hd/tonemap.rs | 151 + + crates/horizon-client/src/gfx/hd/tonemap.wgsl | 41 + + .../src/gfx/{hd_volumes.rs => hd/volumes.rs} | 476 +-- + crates/horizon-client/src/gfx/hd/water.rs | 209 + + crates/horizon-client/src/gfx/hd/water.wgsl | 302 ++ + crates/horizon-client/src/gfx/hd_sky.rs | 390 -- + 31 files changed, 4806 insertions(+), 4194 deletions(-) + delete mode 100644 crates/horizon-client/src/gfx/hd.rs + create mode 100644 crates/horizon-client/src/gfx/hd/ao.rs + create mode 100644 crates/horizon-client/src/gfx/hd/ao.wgsl + create mode 100644 crates/horizon-client/src/gfx/hd/ao_blur.wgsl + create mode 100644 crates/horizon-client/src/gfx/hd/bloom.rs + create mode 100644 crates/horizon-client/src/gfx/hd/bloom.wgsl + create mode 100644 crates/horizon-client/src/gfx/hd/cloud.wgsl + create mode 100644 crates/horizon-client/src/gfx/hd/cloud_common.wgsl + create mode 100644 crates/horizon-client/src/gfx/hd/cloud_shadow.wgsl + create mode 100644 crates/horizon-client/src/gfx/hd/fog.wgsl + create mode 100644 crates/horizon-client/src/gfx/hd/frame.rs + create mode 100644 crates/horizon-client/src/gfx/hd/gbuffer.rs + create mode 100644 crates/horizon-client/src/gfx/hd/light.wgsl + create mode 100644 crates/horizon-client/src/gfx/hd/lighting.rs + create mode 100644 crates/horizon-client/src/gfx/hd/mod.rs + rename crates/horizon-client/src/gfx/{hd_noise.rs => hd/noise.rs} (100%) + create mode 100644 crates/horizon-client/src/gfx/hd/prelude.wgsl + create mode 100644 crates/horizon-client/src/gfx/hd/shadows.rs + create mode 100644 crates/horizon-client/src/gfx/hd/sky.rs + create mode 100644 crates/horizon-client/src/gfx/hd/sky.wgsl + create mode 100644 crates/horizon-client/src/gfx/hd/sky_funcs.wgsl + create mode 100644 crates/horizon-client/src/gfx/hd/taa.rs + create mode 100644 crates/horizon-client/src/gfx/hd/taa.wgsl + create mode 100644 crates/horizon-client/src/gfx/hd/tiles.rs + create mode 100644 crates/horizon-client/src/gfx/hd/tonemap.rs + create mode 100644 crates/horizon-client/src/gfx/hd/tonemap.wgsl + rename crates/horizon-client/src/gfx/{hd_volumes.rs => hd/volumes.rs} (52%) + create mode 100644 crates/horizon-client/src/gfx/hd/water.rs + create mode 100644 crates/horizon-client/src/gfx/hd/water.wgsl + delete mode 100644 crates/horizon-client/src/gfx/hd_sky.rs + +diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs +index a8031c1f6..bdc5b867a 100644 +--- a/crates/horizon-client/src/gfx.rs ++++ b/crates/horizon-client/src/gfx.rs +@@ -72,9 +72,6 @@ mod cull; + mod end_sky; + mod flat; + mod hd; +-mod hd_noise; +-mod hd_sky; +-mod hd_volumes; + mod hdr; + pub mod lightning; + mod lod; +diff --git a/crates/horizon-client/src/gfx/hd.rs b/crates/horizon-client/src/gfx/hd.rs +deleted file mode 100644 +index e84a618a9..000000000 +--- a/crates/horizon-client/src/gfx/hd.rs ++++ /dev/null +@@ -1,3414 +0,0 @@ +-//! AirDef fork: HD lighting. Before the world pass the solid terrain and the +-//! entities (with the mods' models) are drawn once more into a G-buffer: the +-//! surface colour without light and its normal. After the world pass the +-//! mods' point lights (rocket flames, flares, blasts) light every pixel of it +-//! into a high-dynamic-range target; the mod's post pass runs on that; then +-//! bright parts bloom and a tone curve brings it to the screen — vanilla's +-//! range (up to about 0.8) left as it is, only what is brighter rolled off. +-use super::hd_sky; +-pub use super::hd_volumes::clouds_enabled; +-use super::hd_volumes::{self, HdVolumes}; +-use super::pack_timing::PassTiming; +-use glam::Mat4; +-use std::sync::atomic::{AtomicU64, Ordering}; +- +-/// The G-buffer's formats. +-pub const ALBEDO: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm; +-pub const NORMAL: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float; +-/// Sky and block light per pixel. +-pub const LIGHT_LEVELS: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm; +-/// The lit world and the post pass's output. +-pub const HDR: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float; +-/// The water pass's targets: the surface colour with the block light, and the normal with the sky light. +-pub const WATER_TINT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float; +-pub const WATER_NORMAL: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm; +-/// The most lights drawn a frame. +-pub const MAX_LIGHTS: usize = 512; +-/// The side (pixels) of a tile of the screen with its own short list of lights. +-const TILE: u32 = 16; +-/// The indices all the tile lists may hold together; a tile past it loops over every light. +-const TILE_INDICES: usize = 1 << 19; +-/// A list length that means "every light": the list overflowed. +-const EVERY_LIGHT: u32 = u32::MAX; +-/// Bloom's mip levels. +-const BLOOM_LEVELS: usize = 6; +-/// The ambient occlusion's targets (half resolution): occlusion and the distance it was taken at. +-pub const AO_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rg16Float; +-/// The occlusion's default strength (`Hd::ao_strength`; 0 turns it off). +-pub const AO_STRENGTH: f32 = 1.0; +-/// The timed passes of bloom, by level (each is timed on its own; the report sums them). +-const BLOOM_NAMES: [&str; 2 * BLOOM_LEVELS] = [ +- "hd bloom#0", +- "hd bloom#1", +- "hd bloom#2", +- "hd bloom#3", +- "hd bloom#4", +- "hd bloom#5", +- "hd bloom#6", +- "hd bloom#7", +- "hd bloom#8", +- "hd bloom#9", +- "hd bloom#10", +- "hd bloom#11", +-]; +- +-/// A light for this frame, relative to the camera. +-#[repr(C)] +-#[derive(Clone, Copy, Debug, Default, bytemuck::Pod, bytemuck::Zeroable)] +-pub struct HdLight { +- /// xyz: camera-relative position; w: radius. +- pub pos: [f32; 4], +- /// rgb: colour; w: intensity. +- pub color: [f32; 4], +-} +- +-/// The frame's HD settings. +-#[derive(Clone, Copy, Debug)] +-pub struct HdSettings { +- pub exposure: f32, +- pub bloom: f32, +-} +- +-#[repr(C)] +-#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] +-struct HdFrame { +- /// Clip space to camera-relative position. +- inverse_view_proj: [[f32; 4]; 4], +- /// width, height, 1/width, 1/height. +- resolution: [f32; 4], +- /// lights, exposure, bloom, a frame counter. +- params: [f32; 4], +- /// The shadow cascades: camera-relative position to the light's clip space. +- cascades: [[[f32; 4]; 4]; 2], +- /// xyz: towards the sun (or the moon at night); w: how much it lights (0 set or hidden). +- sun: [f32; 4], +- sun_color: [f32; 4], +- fog_color: [f32; 4], +- /// Environmental start, end; render-distance start, end. +- fog: [f32; 4], +- /// x: sky light kept in the shade; y: blocks' light; z: the air's density (rays, halos); +- /// w: the ambient occlusion's strength (0 off). +- ambient: [f32; 4], +- /// x: shadows on; y, z: the cascades' half sizes; w: the light tiles per row. +- shadow: [f32; 4], +- /// The previous frame's camera-relative view-projection without jitter (for TAA). +- prev_view_proj: [[f32; 4]; 4], +- /// xyz: how far the camera moved since that frame; w: 1 when the history is usable. +- taa: [f32; 4], +- /// x: the history's weight; y: the sharpening (0 without TAA); zw: the jitter in world pixels. +- taa_params: [f32; 4], +- /// The (jittered) world-to-clip matrix the world was drawn with (rays in the water pass). +- view_proj: [[f32; 4]; 4], +- /// x: the water effect runs this frame; y: seconds for the waves (wraps at 600); zw: the +- /// camera's x and z modulo 256, the waves' period. +- water: [f32; 4], +- /// rgb: the sky's colour; w: 1 when there is a sky. +- sky_color: [f32; 4], +- /// xyz: towards the sun itself (not the moon); w: 1 when the atmosphere draws the sky. +- sky_sun: [f32; 4], +- /// x: vanilla's sky fog end; z: how overcast the sky is (rain: 0 clear, 1 vanilla's colours). +- sky_extra: [f32; 4], +- /// Vanilla's sunrise colour fan (rgb, alpha), taken out of the sky before the atmosphere is put in. +- sunrise: [f32; 4], +- /// x: the cloud slab's base height relative to the camera; y: its thickness; z: 1 when the +- /// volumetric clouds are drawn; w: seconds (the wind). +- clouds: [f32; 4], +- /// xy: the camera's x and z in the world modulo 65536; z: extra coverage (rain); w: 1 when the +- /// clouds' history is usable. +- cloud_cam: [f32; 4], +- /// xyz: the direction the clouds are lit from (the sun, or the moon at night). +- cloud_dir: [f32; 4], +- /// rgb: the colour of that light at the clouds; w: its strength. +- cloud_sun: [f32; 4], +- /// x: 1 when the volumetric fog is drawn; y: the camera's height in the world; z: the morning mist. +- vfog: [f32; 4], +-} +- +-/// What the world around looks like this frame (from the renderer's globals). +-#[derive(Clone, Copy, Debug)] +-pub struct HdScene { +- /// The shadow cascades' matrices (`cascades`; the far one may be a frame or two old). +- pub cascades: [Mat4; 2], +- /// The (jittered) projection the world was drawn with. +- pub view_proj: Mat4, +- /// Last frame's view-projection without jitter, and the camera's move since (TAA). +- pub prev_view_proj: Mat4, +- /// The same frame's matrix as it was drawn, jitter included. History kept on the jittered +- /// pixel grid (`fs_taa`, scale 1) is looked up with this; `fs_taau` resolves the history on the +- /// unjittered output grid and uses `prev_view_proj`. +- pub prev_view_proj_jittered: Mat4, +- pub camera_delta: glam::Vec3, +- /// This frame is anti-aliased over time (the projection is jittered). +- pub taa: bool, +- /// The jitter in world-target pixels, screen orientation (x right, y down): the world's sample +- /// of a pixel lies this far from its centre (the upscaler weighs samples by it). +- pub jitter_px: [f32; 2], +- /// Towards the sun, and the sky's darkening (0 day, 1 night). +- pub sun: glam::Vec3, +- pub dark: f32, +- pub rain: f32, +- pub fog_color: [f32; 4], +- pub fog: [f32; 4], +- /// The sky has a sun at all (the Overworld). +- pub sky: bool, +- pub sky_color: [f32; 3], +- /// The camera's x and z modulo 256 (the waves' period), so the waves hold still in the world. +- pub camera_mod: [f32; 2], +- /// The water effect may run (not underwater, not disabled). +- pub water: bool, +- /// Vanilla's sunrise fan colour and its sky fog end (to subtract vanilla's sky from the world). +- pub sunrise: [f32; 4], +- pub sky_fog_end: f32, +- /// The volumetric clouds are drawn (vanilla's option is on, in the Overworld). +- pub clouds: bool, +- /// The camera's world position, x and z modulo 65536 (precision), and y; seconds of game time. +- pub camera_world: [f32; 3], +- pub seconds: f32, +-} +- +-/// The cascades' half sizes (blocks) and shadow map size. +-pub const CASCADES: [f32; 2] = [40.0, 176.0]; +-pub const SHADOW_SIZE: u32 = 2048; +- +-const COMMON: &str = r#" +-struct HdFrame { +- inverse_view_proj: mat4x4, +- resolution: vec4, +- params: vec4, +- cascades: array, 2>, +- sun: vec4, +- sun_color: vec4, +- fog_color: vec4, +- fog: vec4, +- ambient: vec4, +- shadow: vec4, +- prev_view_proj: mat4x4, +- taa: vec4, +- taa_params: vec4, +- view_proj: mat4x4, +- water: vec4, +- sky_color: vec4, +- sky_sun: vec4, +- sky_extra: vec4, +- sunrise: vec4, +- clouds: vec4, +- cloud_cam: vec4, +- cloud_dir: vec4, +- cloud_sun: vec4, +- vfog: vec4, +-} +-struct FullOut { +- @builtin(position) position: vec4, +- @location(0) uv: vec2, +-} +-@vertex +-fn vs_full(@builtin(vertex_index) i: u32) -> FullOut { +- let uv = vec2(f32((i << 1u) & 2u), f32(i & 2u)); +- var out: FullOut; +- out.position = vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0); +- out.uv = uv; +- return out; +-} +-"#; +- +-const LIGHT: &str = r#" +-struct Light { +- pos: vec4, +- color: vec4, +-} +-@group(0) @binding(0) var frame: HdFrame; +-@group(0) @binding(1) var scene_color: texture_2d; +-@group(0) @binding(2) var scene_depth: texture_depth_2d; +-@group(0) @binding(3) var albedo_tex: texture_2d; +-@group(0) @binding(4) var normal_tex: texture_2d; +-@group(0) @binding(5) var gbuffer_depth: texture_depth_2d; +-@group(0) @binding(6) var lights: array; +-@group(0) @binding(7) var light_tex: texture_2d; +-@group(0) @binding(8) var shadow_map: texture_depth_2d_array; +-@group(0) @binding(9) var shadow_sampler: sampler_comparison; +-@group(0) @binding(10) var lightmap: texture_2d; +-@group(0) @binding(11) var linear: sampler; +-// Per tile of 16x16 pixels: where its surface list and its halo list start in this array and +-// how long they are (4 words), then the lists of light indices. A length of 0xffffffff means +-// every light. +-@group(0) @binding(12) var tiles: array; +-// Ambient occlusion at half resolution: x the occlusion (1 open), y the distance it was taken at. +-@group(0) @binding(13) var ao_tex: texture_2d; +-// The water pass's depth: the nearest water surface (0 where there is none). +-@group(0) @binding(14) var water_depth: texture_depth_2d; +-//SKY15 +-// The volumetric fog (half resolution: light in rgb, transmittance in a), the distance it was marched +-// to, the volumetric clouds (half resolution: light, transmittance) and the clouds' shadow map. +-@group(0) @binding(16) var fog_tex: texture_2d; +-@group(0) @binding(17) var fog_dist_tex: texture_2d; +-@group(0) @binding(18) var cloud_tex: texture_2d; +-@group(0) @binding(19) var cloud_shadow_tex: texture_2d; +-const CLOUD_SHADOW_R: f32 = 1200.0; +-// The pixel being lit, for the shadow filter's noise. +-var frag_px: vec2; +- +-// The occlusion at a full-resolution pixel `dist` away: the four nearest half-resolution texels +-// weighted by closeness and by how near their distance is, so it doesn't bleed across edges. +-fn ao_at(px: vec2, dist: f32) -> f32 { +- let size = vec2(textureDimensions(ao_tex)); +- let f = vec2(px) * 0.5; +- let base = vec2(floor(f)); +- let t = f - floor(f); +- var sum = 0.0; +- var total = 0.0; +- for (var j = 0; j < 2; j++) { +- for (var i = 0; i < 2; i++) { +- let q = clamp(base + vec2(i, j), vec2(0), size - 1); +- let s = textureLoad(ao_tex, q, 0).xy; +- let bw = select(1.0 - t.x, t.x, i == 1) * select(1.0 - t.y, t.y, j == 1); +- let dz = (s.y - dist) / (0.03 * dist + 0.1); +- let w = select(0.0, bw / (1.0 + dz * dz * dz * dz), s.y > 0.0); +- sum += s.x * w; +- total += w; +- } +- } +- if total < 0.0001 { +- return textureLoad(ao_tex, clamp(px / 2, vec2(0), size - 1), 0).x; +- } +- return sum / total; +-} +- +-// Interleaved gradient noise: a different offset each pixel and frame, for the ray march. +-fn ign(px: vec2) -> f32 { +- let p = px + vec2(5.588238 * frame.params.w); +- return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); +-} +- +-// Where a camera-relative point falls in cascade c: uv and depth. +-fn cascade_at(p: vec3, c: i32) -> vec3 { +- let s = frame.cascades[c] * vec4(p, 1.0); +- return vec3(s.x * 0.5 + 0.5, 0.5 - s.y * 0.5, s.z); +-} +- +-// The sun's (or moon's) light reaching p: 1 lit, 0 in shadow; soft-edged. +-fn shadow(p: vec3, n: vec3) -> f32 { +- return shadow_taps(p, n, 1); +-} +- +-// A point of a disc of radius 1 (Vogel's spiral), turned by `angle`. +-fn vogel(i: i32, count: i32, angle: f32) -> vec2 { +- let r = sqrt((f32(i) + 0.5) / f32(count)); +- let a = f32(i) * 2.39996323 + angle; +- return vec2(cos(a), sin(a)) * r; +-} +- +-// The near cascade's soft shadow: a blocker search sets the penumbra's width (wider the farther +-// the shadow's caster is above the receiver), then a ring of taps turned by a per-pixel noise +-// filters it; the temporal pass averages the noise. `s`: the point in the cascade (uv, depth), +-// `texel`: the cascade's texel in blocks. +-fn soft_shadow(s: vec3, texel: f32) -> f32 { +- let angle = ign(frag_px) * 6.2831853; +- var blocker = 0.0; +- var found = 0.0; +- for (var i = 0; i < 8; i++) { +- let o = vogel(i, 8, angle) * (6.0 / 2048.0); +- let q = clamp(vec2((s.xy + o) * 2048.0), vec2(0), vec2(2047)); +- let z = textureLoad(shadow_map, q, 0, 0); +- if z < s.z - 0.0006 { +- blocker += z; +- found += 1.0; +- } +- } +- if found < 0.5 { return 1.0; } +- // The caster's height above the receiver, in blocks (the cascade's depth spans 799 blocks). +- let height = (s.z - blocker / found) * 799.0; +- let radius = clamp(height * 0.18 / texel, 1.6, 8.0); +- var lit = 0.0; +- for (var i = 0; i < 12; i++) { +- let o = vogel(i, 12, angle + 1.7) * (radius / 2048.0); +- lit += textureSampleCompareLevel(shadow_map, shadow_sampler, s.xy + o, 0, s.z - 0.0005 - 0.00005 * radius); +- } +- return lit / 12.0; +-} +- +-// `shadow` with a (2 * r + 1) square of taps: the floor under water takes one (the water dims and +-// blurs it anyway). +-fn shadow_taps(p: vec3, n: vec3, r: i32) -> f32 { +- let dist = length(p); +- let c = select(1, 0, dist < frame.shadow.y * 0.92); +- let texel = select(frame.shadow.z, frame.shadow.y, c == 0) * 2.0 / 2048.0; +- let q = p + n * texel * 1.5; +- let s = cascade_at(q, c); +- if any(s.xy < vec2(0.0)) || any(s.xy > vec2(1.0)) || s.z > 1.0 { return 1.0; } +- var lit = 0.0; +- let fade = clamp((frame.shadow.z - dist) / 16.0, 0.0, 1.0); +- if r == 1 && c == 0 { +- return mix(1.0, soft_shadow(s, texel), fade); +- } +- let step = 1.0 / 2048.0; +- for (var y = -r; y <= r; y++) { +- for (var x = -r; x <= r; x++) { +- lit += textureSampleCompareLevel(shadow_map, shadow_sampler, s.xy + vec2(f32(x), f32(y)) * step, c, s.z - 0.0005); +- } +- } +- return mix(1.0, lit / f32((2 * r + 1) * (2 * r + 1)), fade); +-} +- +-// One shadow sample, for the rays through the air. +-fn lit_at(p: vec3) -> f32 { +- let s = cascade_at(p, 1); +- if any(s.xy < vec2(0.0)) || any(s.xy > vec2(1.0)) || s.z > 1.0 { return 1.0; } +- return textureSampleCompareLevel(shadow_map, shadow_sampler, s.xy, 1, s.z - 0.001); +-} +- +-fn linear_fog(d: f32, start: f32, end: f32) -> f32 { +- if d <= start { return 0.0; } +- if d >= end { return 1.0; } +- return (d - start) / (end - start); +-} +- +-// The share of the sunlight the clouds let through at a camera-relative point: the shadow map +-// holds, for the sun's way down through the slab from a point of its base, the optical depth +-// (Photon's cloud shadow map, as a lookup rather than a pass). +-fn cloud_shadow(p: vec3) -> f32 { +- if frame.clouds.z < 0.5 { return 1.0; } +- let l = frame.cloud_dir.xyz; +- if l.y < 0.1 { return 1.0; } +- let t = (frame.clouds.x - p.y) / l.y; +- if t <= 0.0 { return 1.0; } +- let q = p.xz + l.xz * t; +- let uv = q / (2.0 * CLOUD_SHADOW_R) + vec2(0.5); +- if any(uv < vec2(0.0)) || any(uv > vec2(1.0)) { return 1.0; } +- let od = textureSampleLevel(cloud_shadow_tex, linear, uv, 0.0).r; +- // Fade out as the sun gets low (the shadow then falls far from the cloud). +- let fade = smoothstep(0.1, 0.25, l.y); +- return mix(1.0, mix(1.0, exp(-od * 0.9), 0.9), fade); +-} +- +-// The volumetric fog at a full-resolution pixel `dist` away: the four nearest half-resolution +-// texels weighted by closeness and by how near their march's length is (so it does not bleed over edges). +-fn fog_at(px: vec2, dist: f32) -> vec4 { +- let size = vec2(textureDimensions(fog_tex)); +- let f = vec2(px) * 0.5 - vec2(0.25); +- let base = vec2(floor(f)); +- let t = f - floor(f); +- var sum = vec4(0.0); +- var total = 0.0; +- for (var j = 0; j < 2; j++) { +- for (var i = 0; i < 2; i++) { +- let q = clamp(base + vec2(i, j), vec2(0), size - 1); +- let s = textureLoad(fog_tex, q, 0); +- let sd = textureLoad(fog_dist_tex, q, 0).x; +- let bw = select(1.0 - t.x, t.x, i == 1) * select(1.0 - t.y, t.y, j == 1); +- let dz = (sd - dist) / (0.06 * dist + 0.4); +- let w = bw / (1.0 + dz * dz * dz * dz); +- sum += s * w; +- total += w; +- } +- } +- if total < 0.0001 { +- return textureLoad(fog_tex, clamp(px / 2, vec2(0), size - 1), 0); +- } +- return sum / total; +-} +- +-struct LightOut { +- // The lit colour; alpha 0.5 marks water (the floor under it, lit without any air), 0.6 an +- // object in front of the water (the scene as drawn). +- @location(0) lit: vec4, +- // Water: the air between the camera and the surface (scattered light, transmittance); +- // in front of the water: the floor lit (rgb); else nothing. +- @location(1) air: vec4, +-} +- +-// An opaque surface lit: the ambient, the sun and the mods' lights over its albedo. +-fn shade_surface(px: vec2, p: vec3, water: bool) -> vec3 { +- let sun = frame.sun.xyz; +- let sun_on = frame.sun.w; +- let atmosphere = frame.sky_sun.w > 0.5; +- let count = u32(frame.params.x); +- let tile = ((u32(px.y) >> 4u) * u32(frame.shadow.w) + (u32(px.x) >> 4u)) * 4u; +- let surface_start = tiles[tile]; +- let surface_all = tiles[tile + 1u] == 0xffffffffu; +- let surface_count = select(tiles[tile + 1u], count, surface_all); +- let n = normalize(textureLoad(normal_tex, px, 0).xyz); +- let albedo = textureLoad(albedo_tex, px, 0); +- let lm = textureLoad(light_tex, px, 0).xy; +- // Vanilla's light (sky and blocks through the lightmap), shaded where the sun can't reach. +- let base = textureSampleLevel(lightmap, linear, clamp(vec2(lm.y, lm.x) * (15.0 / 16.0) + 0.5 / 16.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0)), 0.0).rgb; +- let block = textureSampleLevel(lightmap, linear, vec2(lm.y * (15.0 / 16.0) + 0.5 / 16.0, 0.5 / 16.0), 0.0).rgb; +- let sky_reach = smoothstep(0.35, 0.95, lm.x); +- var s = 1.0; +- let ndl = dot(n, sun); +- if sun_on > 0.0 && ndl > 0.0 && sky_reach > 0.0 { s = shadow_taps(p, n, select(1, 0, water)) * cloud_shadow(p); } else { s = 0.0; } +- // Shadowed sky light (ambient) keeps vanilla's look, blocks' light stays as is; the sun adds +- // direct light by the face's angle. +- let direct = frame.sun_color.rgb * sun_on * max(ndl, 0.0) * s * sky_reach; +- // Contact shadows from the ambient occlusion: on the ambient and blocks' light fully, on +- // the mods' lights by half, not on the sun or on emission. +- var occlusion = 1.0; +- // (The water dims and blurs the floor under it: no occlusion there.) +- if frame.ambient.w > 0.0 && !water { occlusion = ao_at(px, length(p)); } +- let ao_ambient = mix(1.0, occlusion, frame.ambient.w); +- let ao_lights = mix(1.0, occlusion, frame.ambient.w * 0.5); +- // The sky's light is bluish from above and carries the horizon's colour from the sides; +- // faces turned up take more of it than the ones turned down. +- var sky_tint = vec3(1.0); +- if atmosphere { +- let reach = smoothstep(0.25, 0.9, lm.x); +- let up = clamp(n.y * 0.5 + 0.5, 0.0, 1.0); +- let shape = mix(0.66, 1.1, smoothstep(0.1, 1.0, up)); +- let hue = mix(vec3(1.0), sky_light_tint(n), 0.4 * (1.0 - 0.5 * frame.sun_color.a)); +- sky_tint = mix(vec3(1.0), hue * shape, reach); +- } +- var light = max(base * sky_tint * frame.ambient.x, block * frame.ambient.y) * ao_ambient + direct; +- // The mods' lights. +- for (var k = 0u; k < surface_count; k++) { +- let l = lights[select(tiles[surface_start + k], k, surface_all)]; +- let to = l.pos.xyz - p; +- let dist = length(to); +- if dist >= l.pos.w { continue; } +- let window = pow(clamp(1.0 - pow(dist / l.pos.w, 4.0), 0.0, 1.0), 2.0); +- let falloff = l.color.w / (dist * dist + 1.0) * window; +- let k = max(dot(n, to / max(dist, 0.001)) * 0.85 + 0.15, 0.0); +- light += l.color.rgb * falloff * k * ao_lights; +- } +- return albedo.rgb * light + albedo.rgb * albedo.a * 1.5; +-} +- +-@fragment +-fn fs_light(in: FullOut) -> LightOut { +- let px = vec2(in.position.xy); +- let scene = textureLoad(scene_color, px, 0).rgb; +- let d = textureLoad(scene_depth, px, 0); +- let g = textureLoad(gbuffer_depth, px, 0); +- // Water over the opaque world (or over nothing): the water composite lays the surface over +- // the floor, which is lit here with no air. Something translucent in front of the water +- // (`front`: nearer than its surface) keeps the scene as drawn; the floor goes beside it. +- var wd = 0.0; +- var water_here = false; +- if frame.water.x > 0.5 { +- wd = textureLoad(water_depth, px, 0); +- water_here = wd > 0.0 && (g <= 0.0 || wd >= g); +- } +- let front = water_here && g > 0.0 && d - wd > d * 0.002; +- let water = water_here && !front; +- let has_floor = water && g > 0.0; +- let dd = select(d, g, has_floor); +- let ndc = vec4(in.uv.x * 2.0 - 1.0, 1.0 - in.uv.y * 2.0, max(dd, 0.000001), 1.0); +- let h = frame.inverse_view_proj * ndc; +- let p = h.xyz / h.w; +- let view = normalize(p); +- // Where the air ends: the water's surface over water, else the pixel itself. +- var ps = p; +- if water { +- let hf = frame.inverse_view_proj * vec4(in.uv.x * 2.0 - 1.0, 1.0 - in.uv.y * 2.0, max(wd, 0.000001), 1.0); +- ps = hf.xyz / hf.w; +- } +- let view_s = normalize(ps); +- let sun = frame.sun.xyz; +- let sun_on = frame.sun.w; +- let count = u32(frame.params.x); +- let tile = ((u32(px.y) >> 4u) * u32(frame.shadow.w) + (u32(px.x) >> 4u)) * 4u; +- let halo_start = tiles[tile + 2u]; +- let halo_all = tiles[tile + 3u] == 0xffffffffu; +- let halo_count = select(tiles[tile + 3u], count, halo_all); +- frag_px = in.position.xy; +- let atmosphere = frame.sky_sun.w > 0.5; +- var c = scene; +- // The sky: the atmosphere's, with what the world drew over vanilla's plain sky (sun, moon, +- // stars, clouds) kept on top. +- if d <= 0.0 && atmosphere { +- var kept = max(scene - vanilla_sky(view), vec3(0.0)); +- var sky = atmosphere_sky(view); +- // The sun: vanilla's square sprite is taken out and a round disc with a soft haze round +- // it (warm, strongest low) is drawn in its place. +- let toward = dot(view, frame.sky_sun.xyz); +- kept *= 1.0 - smoothstep(0.965, 0.975, toward); +- let clear = 1.0 - frame.sky_extra.z; +- let shine = smoothstep(-0.04, 0.02, frame.sky_sun.y) * clear; +- let glow = max(toward, 0.0); +- let angle = acos(clamp(toward, -1.0, 1.0)); +- sky += frame.sun_color.rgb * shine * (pow(glow, 24.0) * 0.07 + pow(glow, 400.0) * 0.4 + 6.0 * (1.0 - smoothstep(0.016, 0.022, angle))); +- c = sky + kept; +- // The volumetric clouds over the sky and the sun. +- if frame.clouds.z > 0.5 { +- let cl = textureSampleLevel(cloud_tex, linear, in.uv, 0.0); +- c = c * cl.a + cl.rgb; +- } +- } +- // (Vanilla's clouds, when the volumetric ones are off, take the low sun's colour in their own +- // pass: `vanilla_cloud_tint`, applied to their colour on the CPU.) +- let surface = has_floor || (!water_here && d > 0.0 && abs(d - g) <= max(d, g) * 0.002); +- if surface { +- c = shade_surface(px, p, water); +- // Vanilla's fog over it again (the water composite does it at the surface). +- if !water { +- let sph = length(p); +- let cyl = max(length(p.xz), abs(p.y)); +- let f = max(linear_fog(sph, frame.fog.x, frame.fog.y), linear_fog(cyl, frame.fog.z, frame.fog.w)); +- let haze = haze_colour(view); +- c = mix(c, haze, f * frame.fog_color.a); +- // Aerial perspective: far things take the horizon's colour a little before the fog does. +- if atmosphere && frame.fog.x > 1.0e6 { +- c = mix(c, haze, (1.0 - exp(-sph / 700.0)) * 0.5); +- } +- } +- } +- // What lies behind a translucent thing in front of the water: the floor, lit. +- var floor_lit = vec3(0.0); +- if front { +- let hg = frame.inverse_view_proj * vec4(in.uv.x * 2.0 - 1.0, 1.0 - in.uv.y * 2.0, max(g, 0.000001), 1.0); +- floor_lit = shade_surface(px, hg.xyz / hg.w, true); +- } +- // The air between the camera and the pixel (the water's surface over water): the volumetric +- // fog (what it hides, what it scatters), the sun's rays between the shadows, and the halos +- // round the mods' lights. Over water they go to the composite, which lays them over the +- // finished water; elsewhere over the pixel here. +- var air_t = 1.0; +- var air_s = vec3(0.0); +- let far = select(min(length(ps), frame.shadow.z), frame.shadow.z, d <= 0.0); +- let density = frame.ambient.z; +- let volumetric = frame.vfog.x > 0.5 && atmosphere; +- if volumetric { +- var fog_len = 192.0; +- if d > 0.0 { fog_len = min(length(ps), 192.0); } +- let fg = fog_at(px, fog_len); +- air_t = fg.a; +- air_s = fg.rgb; +- } +- if !volumetric && sun_on > 0.0 && density > 0.0 { +- let steps = 14; +- let jitter = ign(in.position.xy); +- var acc = 0.0; +- for (var i = 0; i < steps; i++) { +- let t = (f32(i) + jitter) / f32(steps) * far; +- acc += lit_at(view_s * t); +- } +- // Henyey-Greenstein, forward scattering: brightest looking towards the sun. +- let cos_t = dot(view_s, sun); +- let gk = 0.6; +- let phase = (1.0 - gk * gk) / pow(1.0 + gk * gk - 2.0 * gk * cos_t, 1.5) * 0.08; +- air_s += frame.sun_color.rgb * sun_on * (acc / f32(steps)) * phase * (1.0 - exp(-far * density)); +- } +- for (var k = 0u; k < halo_count; k++) { +- let l = lights[select(tiles[halo_start + k], k, halo_all)]; +- // Nearest point of the view ray to the light, and the glow along the ray in front of it. +- let t0 = dot(l.pos.xyz, view_s); +- let hh = length(l.pos.xyz - view_s * t0) + 0.5; +- if hh > l.pos.w * 0.5 { continue; } +- let a0 = atan((0.0 - t0) / hh); +- let a1 = atan((far - t0) / hh); +- // Thicker air glows more round a light, but only so far: the mist at dusk and many fires +- // at once would otherwise wash the picture out. +- air_s += l.color.rgb * l.color.w * (a1 - a0) / hh * 0.004 * (0.3 + min(density * 300.0, 0.9)); +- } +- var out: LightOut; +- if water { +- out.lit = vec4(c, 0.5); +- out.air = vec4(air_s, air_t); +- } else { +- out.lit = vec4(c * air_t + air_s, select(1.0, 0.6, front)); +- out.air = vec4(floor_lit, 0.0); +- } +- return out; +-} +-"#; +- +-const WATER: &str = r#" +-const PI: f32 = 3.14159265; +-const REFLECT_STEPS: i32 = 24; +-const REFLECT_RANGE: f32 = 96.0; +-@group(0) @binding(0) var frame: HdFrame; +-@group(0) @binding(1) var lit_tex: texture_2d; +-@group(0) @binding(2) var gbuffer_depth: texture_depth_2d; +-@group(0) @binding(3) var water_tint: texture_2d; +-@group(0) @binding(4) var water_normal: texture_2d; +-@group(0) @binding(5) var water_depth: texture_depth_2d; +-@group(0) @binding(6) var shadow_map: texture_depth_2d_array; +-@group(0) @binding(7) var shadow_sampler: sampler_comparison; +-@group(0) @binding(8) var lightmap: texture_2d; +-@group(0) @binding(9) var linear: sampler; +-//SKY10 +-// What the lighting left beside the lit world: over water the air in front of the surface (scattered +-// light, transmittance), in front of the water the lit floor. +-@group(0) @binding(11) var air_tex: texture_2d; +- +-fn ign(px: vec2) -> f32 { +- let p = px + vec2(5.588238 * frame.params.w); +- return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); +-} +- +-// The camera-relative position of the screen point `uv` at depth z. +-fn position_at(uv: vec2, z: f32) -> vec3 { +- let h = frame.inverse_view_proj * vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, z, 1.0); +- return h.xyz / h.w; +-} +- +-// The screen point (uv, clip w) of a camera-relative position. +-fn project(p: vec3) -> vec3 { +- let c = frame.view_proj * vec4(p, 1.0); +- return vec3(c.x / c.w * 0.5 + 0.5, 0.5 - c.y / c.w * 0.5, c.w); +-} +- +-fn on_screen(uv: vec2) -> bool { +- return all(uv > vec2(0.0)) && all(uv < vec2(1.0)); +-} +- +-fn texel(uv: vec2) -> vec2 { +- return clamp(vec2(uv * frame.resolution.xy), vec2(0), vec2(frame.resolution.xy) - 1); +-} +- +-// Sine waves in world space: wave vectors that are whole multiples of 2 pi / 256 and speeds that +-// are whole cycles per 600 s, so the sum repeats every 256 blocks and 10 minutes and holds still +-// in the world as the camera moves. x, y: the vector in units of 2 pi / 256; z: the slope the +-// wave adds; w: its phase. +-const WAVES = array, 26>( +- vec4(3.0, 1.0, 0.040, 0.3), +- vec4(-2.0, 5.0, 0.045, 2.1), +- vec4(7.0, 2.0, 0.040, 4.4), +- vec4(-5.0, -9.0, 0.040, 1.2), +- vec4(11.0, -4.0, 0.035, 5.6), +- vec4(13.0, 10.0, 0.035, 3.3), +- vec4(-17.0, 7.0, 0.030, 0.9), +- vec4(9.0, 23.0, 0.030, 2.7), +- vec4(-27.0, 19.0, 0.025, 4.9), +- vec4(31.0, 30.0, 0.025, 1.8), +- // Fine ripples (wavelengths of 0.7 to 3 blocks) for the many small sun sparkles: slopes small, +- // faded out by distance and pixel size like the rest. +- vec4(83.0, 41.0, 0.042, 0.4), +- vec4(-97.0, 59.0, 0.042, 3.1), +- vec4(71.0, -113.0, 0.042, 5.0), +- vec4(131.0, 89.0, 0.040, 1.5), +- vec4(-157.0, -103.0, 0.040, 4.2), +- vec4(191.0, -67.0, 0.038, 2.4), +- vec4(-223.0, 149.0, 0.038, 0.8), +- vec4(101.0, 241.0, 0.036, 3.7), +- vec4(-263.0, -181.0, 0.034, 5.5), +- vec4(311.0, 127.0, 0.034, 2.0), +- // Finer still (0.35 to 0.6 blocks): the small sparkles. +- vec4(397.0, -263.0, 0.050, 1.1), +- vec4(-467.0, 331.0, 0.050, 4.6), +- vec4(521.0, 449.0, 0.045, 3.0), +- vec4(-613.0, -199.0, 0.045, 5.9), +- vec4(293.0, 577.0, 0.045, 0.2), +- vec4(-701.0, 263.0, 0.040, 2.8), +-); +- +-// The gradient of the water's height at world x, z: the waves that a pixel `footprint` blocks +-// wide can still resolve (finer ones fade out, or they would shimmer). +-fn wave_gradient(xz: vec2, footprint: f32) -> vec2 { +- var grad = vec2(0.0); +- for (var i = 0; i < 26; i++) { +- let w = WAVES[i]; +- let k = w.xy * (2.0 * PI / 256.0); +- let len = length(k); +- let fade = clamp((2.0 * PI / len) / max(footprint, 0.0001) * 0.2 - 0.6, 0.0, 1.0); +- let cycles = round(sqrt(9.8 * len) * 0.5 * 600.0 / (2.0 * PI)); +- let omega = cycles * 2.0 * PI / 600.0; +- let phase = dot(k, xz) - omega * frame.water.y + w.w; +- grad += (k / len) * (w.z * fade * cos(phase)); +- } +- // A little higher than the table's slopes. +- return grad * 1.25; +-} +- +-fn cascade_at(p: vec3, c: i32) -> vec3 { +- let s = frame.cascades[c] * vec4(p, 1.0); +- return vec3(s.x * 0.5 + 0.5, 0.5 - s.y * 0.5, s.z); +-} +- +-// The sun's (or moon's) light reaching p: 1 lit, 0 in shadow (as the lighting pass has it). +-fn shadow(p: vec3, n: vec3) -> f32 { +- let dist = length(p); +- let c = select(1, 0, dist < frame.shadow.y * 0.92); +- let texel_size = select(frame.shadow.z, frame.shadow.y, c == 0) * 2.0 / 2048.0; +- let q = p + n * texel_size * 1.5; +- let s = cascade_at(q, c); +- if any(s.xy < vec2(0.0)) || any(s.xy > vec2(1.0)) || s.z > 1.0 { return 1.0; } +- var lit = 0.0; +- let step = 1.0 / 2048.0; +- for (var y = -1; y <= 1; y++) { +- for (var x = -1; x <= 1; x++) { +- lit += textureSampleCompareLevel(shadow_map, shadow_sampler, s.xy + vec2(f32(x), f32(y)) * step, c, s.z - 0.0005); +- } +- } +- let fade = clamp((frame.shadow.z - dist) / 16.0, 0.0, 1.0); +- return mix(1.0, lit / 9.0, fade); +-} +- +-fn linear_fog(d: f32, start: f32, end: f32) -> f32 { +- if d <= start { return 0.0; } +- if d >= end { return 1.0; } +- return (d - start) / (end - start); +-} +- +-// What the sky shows along r when the ray leaves the screen: the horizon's colour rising to +-// the zenith's, darker where the water lies under cover (`vis` is the sky light there). +-fn sky_along(r: vec3, vis: f32) -> vec3 { +- var c = frame.fog_color.rgb; +- if frame.sky_sun.w > 0.5 { +- c = atmosphere_sky(r); +- } else if frame.sky_color.w > 0.5 { +- c = mix(frame.fog_color.rgb, frame.sky_color.rgb, smoothstep(0.0, 0.5, r.y)); +- } +- return c * mix(0.12, 1.0, vis); +-} +- +-// Marches the ray from p along r over the depth buffer (28 steps, growing, jittered so TAA +-// averages the placement; then a binary search for the crossing). xyz: the colour found, +-// w: how much to trust it (0 for a miss, less near the screen's edge). +-fn reflection(p: vec3, r: vec3, jitter: f32) -> vec4 { +- var near = 0.0; +- for (var i = 0; i < REFLECT_STEPS; i++) { +- let u = (f32(i) + jitter) / f32(REFLECT_STEPS); +- let s = 0.12 + REFLECT_RANGE * u * u; +- let q = p + r * s; +- let sp = project(q); +- if sp.z <= 0.0 || !on_screen(sp.xy) { break; } +- let z = textureLoad(gbuffer_depth, texel(sp.xy), 0); +- if z > 0.0 { +- let c = frame.view_proj * vec4(q, 1.0); +- // Reversed Z: a larger depth is nearer; the ray is behind the surface when the +- // surface is nearer than it. +- if z > c.z / c.w { +- let behind = length(q) - length(position_at(sp.xy, z)); +- if behind < 0.4 + 0.08 * s { +- var lo = near; +- var hi = s; +- for (var k = 0; k < 5; k++) { +- let m = 0.5 * (lo + hi); +- let mq = p + r * m; +- let mp = project(mq); +- let mc = frame.view_proj * vec4(mq, 1.0); +- let mz = textureLoad(gbuffer_depth, texel(mp.xy), 0); +- if mz > mc.z / mc.w { hi = m; } else { lo = m; } +- } +- let hp = project(p + r * hi); +- let edge = min(min(hp.x, 1.0 - hp.x), min(hp.y, 1.0 - hp.y)); +- let colour = textureSampleLevel(lit_tex, linear, hp.xy, 0.0).rgb; +- return vec4(colour, smoothstep(0.0, 0.08, edge)); +- } +- } +- } +- near = s; +- } +- return vec4(0.0); +-} +- +-// The sun's glint on the waves (GGX, a rough lobe so it glitters instead of aliasing). +-fn glint(n: vec3, v: vec3, l: vec3) -> f32 { +- let h = normalize(l + v); +- let a = 0.07; +- let nh = max(dot(n, h), 0.0); +- let d = a * a / (PI * pow(nh * nh * (a * a - 1.0) + 1.0, 2.0)); +- let f = 0.02 + 0.98 * pow(1.0 - max(dot(v, h), 0.0), 5.0); +- return min(d * f * 0.25 * max(dot(n, l), 0.0) / max(dot(n, v), 0.1), 12.0); +-} +- +-// The water over the lit world: the world behind it (refracted by the waves, dimmed and tinted +-// by the water's depth), the sky and the world above it (a screen-space reflection) by Fresnel, +-// and the sun's glint. Pixels without water pass through. +-@fragment +-fn fs_water(in: FullOut) -> @location(0) vec4 { +- let px = vec2(in.position.xy); +- let base = textureLoad(lit_tex, px, 0); +- if base.a > 0.75 { return vec4(base.rgb, 1.0); } +- // Alpha 0.6: something translucent stands in front of the water here (base is the scene). +- let front = base.a > 0.55; +- let aux = textureLoad(air_tex, px, 0); +- let wd = textureLoad(water_depth, px, 0); +- let g = textureLoad(gbuffer_depth, px, 0); +- let tint = textureLoad(water_tint, px, 0); +- let nt = textureLoad(water_normal, px, 0); +- let p = position_at(in.uv, wd); +- let dist = length(p); +- let v = -p / dist; +- let geometric = normalize(nt.xyz * 2.0 - 1.0); +- // The waves tilt the flat parts of the surface only. +- let footprint = dist * frame.resolution.w * 1.4; +- let grad = wave_gradient(p.xz + frame.water.zw, footprint); +- let flat_part = smoothstep(0.6, 0.95, geometric.y); +- var n = normalize(geometric + vec3(-grad.x, 0.0, -grad.y) * flat_part); +- n = normalize(n + v * max(0.03 - dot(n, v), 0.0)); +- let ndv = max(dot(n, v), 0.02); +- +- // Light on the water: vanilla's lightmap at the surface, and the sun where it reaches. +- let levels = vec2(nt.a, tint.a); +- let sky_reach = smoothstep(0.35, 0.95, levels.x); +- var ambient = textureSampleLevel(lightmap, linear, clamp(vec2(levels.y, levels.x) * (15.0 / 16.0) + 0.5 / 16.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0)), 0.0).rgb; +- if frame.sky_sun.w > 0.5 { +- ambient *= mix(vec3(1.0), sky_light_tint(vec3(0.0, 1.0, 0.0)), 0.7 * sky_reach); +- } +- let block = textureSampleLevel(lightmap, linear, vec2(levels.y * (15.0 / 16.0) + 0.5 / 16.0, 0.5 / 16.0), 0.0).rgb; +- let sun = frame.sun.xyz; +- let sun_on = frame.sun.w; +- var sunlit = 0.0; +- if sun_on > 0.0 && sun.y > 0.0 && sky_reach > 0.0 { sunlit = shadow(p, vec3(0.0, 1.0, 0.0)) * sky_reach; } +- let volume_light = max(ambient * frame.ambient.x, block * frame.ambient.y) + frame.sun_color.rgb * sun_on * sunlit * 0.8; +- +- // Refraction: where the ray through the waves meets the world, against where the flat surface +- // would send it (so still water looks as vanilla's and only the waves distort). Not where +- // something translucent is in front of the water, nor onto texels that hold such a thing. +- let has_floor = g > 0.0; +- var uv_floor = in.uv; +- var floor_z = g; +- if has_floor && !front { +- let floor0 = position_at(in.uv, g); +- let depth0 = max(length(floor0) - dist, 0.0); +- let bent = refract(-v, n, 0.75) - refract(-v, geometric, 0.75); +- let moved = project(floor0 + bent * min(depth0, 24.0)); +- if moved.z > 0.0 && on_screen(moved.xy) { +- let z = textureLoad(gbuffer_depth, texel(moved.xy), 0); +- // The four texels the filter blends: none may be a pixel with a translucent thing +- // in front of the water. +- let marks = textureGather(3, lit_tex, linear, moved.xy); +- let tainted = any((marks > vec4(0.55)) & (marks < vec4(0.75))); +- // Only what lies behind the water: not the bank or an entity in front of it. +- if z > 0.0 && z <= wd && !tainted { +- uv_floor = moved.xy; +- floor_z = z; +- } +- } +- } +- var thickness = 48.0; +- if has_floor { +- thickness = clamp(length(position_at(uv_floor, floor_z)) - dist, 0.0, 48.0); +- } +- var behind = textureSampleLevel(lit_tex, linear, uv_floor, 0.0).rgb; +- if front { behind = aux.rgb; } +- // A deep, dark water: the biome's colour darkened and a little greyed, so it reads as +- // depth rather than as bright paint. +- let biome = clamp(tint.rgb, vec3(0.03), vec3(1.0)); +- let colour = mix(vec3(dot(biome, vec3(0.333))), biome, 0.85) * vec3(0.78, 0.86, 0.95); +- // The colours the water takes up fastest are the ones it has the least of. +- let absorb = exp(-(vec3(1.0) - colour) * 0.6 * (thickness + 0.3)); +- let refracted = behind * absorb + colour * volume_light * mix(0.65, 0.3, frame.sun_color.a) * (vec3(1.0) - absorb); +- +- // Reflection: the screen where the ray stays on it, the sky where it leaves it or misses. +- var r = reflect(-v, n); +- r.y = abs(r.y); +- // Looking down onto it the reflection is a few percent of the picture: the sky alone does. +- let fresnel = 0.02 + 0.98 * pow(1.0 - ndv, 5.0); +- var hit = vec4(0.0); +- if fresnel > 0.04 { hit = reflection(p, r, ign(in.position.xy)); } +- let sky_vis = mix(0.15, 1.0, sky_reach); +- let reflected = mix(sky_along(r, sky_vis), hit.rgb, hit.w); +- +- var c = refracted * (1.0 - fresnel) + reflected * fresnel; +- if sun_on > 0.0 && sunlit > 0.0 { +- c += frame.sun_color.rgb * sun_on * sunlit * glint(n, v, sun); +- } +- // Vanilla's fog over it, at the surface. +- let sph = dist; +- let cyl = max(length(p.xz), abs(p.y)); +- let f = max(linear_fog(sph, frame.fog.x, frame.fog.y), linear_fog(cyl, frame.fog.z, frame.fog.w)); +- let haze = haze_colour(-v); +- c = mix(c, haze, f * frame.fog_color.a); +- if frame.sky_sun.w > 0.5 && frame.fog.x > 1.0e6 { +- c = mix(c, haze, (1.0 - exp(-dist / 700.0)) * 0.5); +- } +- if front { +- // The scene as drawn, with the water's change to the floor laid under the translucent thing. +- c = base.rgb + (c - aux.rgb) * 0.7; +- } else { +- // The air between the camera and the surface: volumetric fog, rays, halos. +- c = c * aux.a + aux.rgb; +- } +- return vec4(max(c, vec3(0.0)), 1.0); +-} +-"#; +- +-const AO: &str = r#" +-const AO_RADIUS: f32 = 1.8; +-const AO_SLICES: i32 = 3; +-const AO_STEPS: i32 = 5; +-const PI: f32 = 3.14159265; +-@group(0) @binding(0) var frame: HdFrame; +-@group(0) @binding(1) var depth_tex: texture_depth_2d; +-@group(0) @binding(2) var normal_tex: texture_2d; +- +-// Interleaved gradient noise, shifted per frame (params.w) and per use. +-fn noise(px: vec2, shift: vec2) -> f32 { +- let p = px + shift + vec2(5.588238 * frame.params.w); +- return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); +-} +- +-// The camera-relative position of a (continuous) full-resolution pixel at depth z. +-fn position_at(px: vec2, z: f32) -> vec3 { +- let uv = px * frame.resolution.zw; +- let h = frame.inverse_view_proj * vec4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, z, 1.0); +- return h.xyz / h.w; +-} +- +-// Ground-truth ambient occlusion (horizon based): per slice through the view ray, the highest +-// horizon on either side, integrated against the normal's cosine lobe. Half resolution: one +-// pixel of each 2x2. +-@fragment +-fn fs_ao(in: FullOut) -> @location(0) vec2 { +- let size = vec2(textureDimensions(depth_tex)); +- let ic = min(vec2(in.position.xy) * 2, size - 1); +- let z = textureLoad(depth_tex, ic, 0); +- if z <= 0.0 { return vec2(1.0, 0.0); } +- let nrm = textureLoad(normal_tex, ic, 0).xyz; +- let c = vec2(ic) + 0.5; +- let p = position_at(c, z); +- let dist = length(p); +- if dot(nrm, nrm) < 0.01 { return vec2(1.0, dist); } +- let n = normalize(nrm); +- let v = -p / dist; +- // Blocks per pixel here (the plane of equal depth is square to the view), so how far in +- // pixels the radius reaches. +- let per_px = max(length(position_at(c + vec2(4.0, 0.0), z) - p) / 4.0, 0.00001); +- let reach = min(AO_RADIUS / per_px, 56.0); +- if reach < 2.0 { return vec2(1.0, dist); } +- let radius = reach * per_px; +- let rot = noise(in.position.xy, vec2(0.0)); +- let jitter = noise(in.position.xy, vec2(37.0, 17.0)); +- var visibility = 0.0; +- for (var s = 0; s < AO_SLICES; s++) { +- let phi = (f32(s) + rot) / f32(AO_SLICES) * PI; +- let d2 = vec2(cos(phi), sin(phi)); +- // The slice's direction in space, square to the view ray, and its plane's axis. +- let q = position_at(c + d2 * 4.0, z) - p; +- let dir = normalize(q - v * dot(q, v)); +- let axis = cross(dir, v); +- let projected = n - axis * dot(n, axis); +- let plen = length(projected); +- if plen < 0.0001 { visibility += 1.0; continue; } +- let cos_n = clamp(dot(projected, v) / plen, -1.0, 1.0); +- let nang = select(-1.0, 1.0, dot(projected, dir) >= 0.0) * acos(cos_n); +- var c_neg = -1.0; +- var c_pos = -1.0; +- for (var i = 0; i < AO_STEPS; i++) { +- let t = (f32(i) + jitter) / f32(AO_STEPS); +- let r = 1.5 + (reach - 1.5) * t * t; +- for (var side = 0; side < 2; side++) { +- let sg = select(-1.0, 1.0, side == 1); +- let ip = vec2(floor(c + d2 * (r * sg))); +- if any(ip < vec2(0)) || any(ip >= size) { continue; } +- let sz = textureLoad(depth_tex, ip, 0); +- if sz <= 0.0 { continue; } +- let to = position_at(vec2(ip) + 0.5, sz) - p; +- let len = length(to); +- // Points on (or under) the surface's own plane don't occlude it. +- if dot(to, n) < 0.1 * len { continue; } +- // Far points count less, to nothing at the radius. +- let fall = clamp((len - radius * 0.6) / (radius * 0.4), 0.0, 1.0); +- let ch = mix(dot(to / len, v), -1.0, fall); +- if side == 1 { c_pos = max(c_pos, ch); } else { c_neg = max(c_neg, ch); } +- } +- } +- var h_neg = -acos(clamp(c_neg, -1.0, 1.0)); +- var h_pos = acos(clamp(c_pos, -1.0, 1.0)); +- h_neg = nang + max(h_neg - nang, -0.5 * PI); +- h_pos = nang + min(h_pos - nang, 0.5 * PI); +- let sn = sin(nang); +- let arc_neg = cos_n + 2.0 * h_neg * sn - cos(2.0 * h_neg - nang); +- let arc_pos = cos_n + 2.0 * h_pos * sn - cos(2.0 * h_pos - nang); +- visibility += plen * 0.25 * (arc_neg + arc_pos); +- } +- let ao = clamp(visibility / f32(AO_SLICES), 0.0, 1.0); +- // Far away it is too coarse to show: fade out. +- return vec2(mix(1.0, ao, 1.0 - smoothstep(40.0, 96.0, dist)), dist); +-} +-"#; +- +-const AO_BLUR: &str = r#" +-@group(0) @binding(0) var frame: HdFrame; +-@group(0) @binding(1) var raw_ao: texture_2d; +- +-// A 5x5 blur that only takes texels at about the same distance (so not across an edge). +-@fragment +-fn fs_ao_blur(in: FullOut) -> @location(0) vec2 { +- let size = vec2(textureDimensions(raw_ao)); +- let ip = vec2(in.position.xy); +- let centre = textureLoad(raw_ao, ip, 0).xy; +- if centre.y <= 0.0 { return centre; } +- let tolerance = 0.03 * centre.y + 0.1; +- var sum = 0.0; +- var total = 0.0; +- for (var y = -2; y <= 2; y++) { +- for (var x = -2; x <= 2; x++) { +- let q = ip + vec2(x, y); +- if any(q < vec2(0)) || any(q >= size) { continue; } +- let s = textureLoad(raw_ao, q, 0).xy; +- if s.y <= 0.0 { continue; } +- let dz = (s.y - centre.y) / tolerance; +- let w = 1.0 / (1.0 + dz * dz * dz * dz); +- sum += s.x * w; +- total += w; +- } +- } +- return vec2(sum / max(total, 0.0001), centre.y); +-} +-"#; +- +-const BLOOM: &str = r#" +-@group(0) @binding(0) var frame: HdFrame; +-@group(0) @binding(1) var source: texture_2d; +-@group(0) @binding(2) var linear: sampler; +- +-// The first step down keeps only what is brighter than white (a soft knee). +-@fragment +-fn fs_prefilter(in: FullOut) -> @location(0) vec4 { +- let c = textureSampleLevel(source, linear, in.uv, 0.0).rgb; +- let peak = max(c.r, max(c.g, c.b)); +- let knee = 0.35; +- let soft = clamp(peak - 0.85 + knee, 0.0, 2.0 * knee); +- let weight = max(soft * soft / (4.0 * knee + 0.0001), peak - 0.85) / max(peak, 0.0001); +- return vec4(c * weight, 1.0); +-} +-// 13 taps (Call of Duty: Advanced Warfare's bloom), half size each step. +-@fragment +-fn fs_down(in: FullOut) -> @location(0) vec4 { +- let t = 1.0 / vec2(textureDimensions(source)); +- let s = in.uv; +- let a = textureSampleLevel(source, linear, s + t * vec2(-2.0, -2.0), 0.0).rgb; +- let b = textureSampleLevel(source, linear, s + t * vec2(0.0, -2.0), 0.0).rgb; +- let c = textureSampleLevel(source, linear, s + t * vec2(2.0, -2.0), 0.0).rgb; +- let d = textureSampleLevel(source, linear, s + t * vec2(-2.0, 0.0), 0.0).rgb; +- let e = textureSampleLevel(source, linear, s, 0.0).rgb; +- let f = textureSampleLevel(source, linear, s + t * vec2(2.0, 0.0), 0.0).rgb; +- let g = textureSampleLevel(source, linear, s + t * vec2(-2.0, 2.0), 0.0).rgb; +- let h = textureSampleLevel(source, linear, s + t * vec2(0.0, 2.0), 0.0).rgb; +- let i = textureSampleLevel(source, linear, s + t * vec2(2.0, 2.0), 0.0).rgb; +- let j = textureSampleLevel(source, linear, s + t * vec2(-1.0, -1.0), 0.0).rgb; +- let k = textureSampleLevel(source, linear, s + t * vec2(1.0, -1.0), 0.0).rgb; +- let l = textureSampleLevel(source, linear, s + t * vec2(-1.0, 1.0), 0.0).rgb; +- let m = textureSampleLevel(source, linear, s + t * vec2(1.0, 1.0), 0.0).rgb; +- var o = e * 0.125 + (a + c + g + i) * 0.03125 + (b + d + f + h) * 0.0625 + (j + k + l + m) * 0.125; +- return vec4(o, 1.0); +-} +-// A 3×3 tent, added onto the bigger level. +-@fragment +-fn fs_up(in: FullOut) -> @location(0) vec4 { +- let t = 1.0 / vec2(textureDimensions(source)); +- let s = in.uv; +- var o = textureSampleLevel(source, linear, s, 0.0).rgb * 4.0; +- o += (textureSampleLevel(source, linear, s + t * vec2(-1.0, 0.0), 0.0).rgb +- + textureSampleLevel(source, linear, s + t * vec2(1.0, 0.0), 0.0).rgb +- + textureSampleLevel(source, linear, s + t * vec2(0.0, -1.0), 0.0).rgb +- + textureSampleLevel(source, linear, s + t * vec2(0.0, 1.0), 0.0).rgb) * 2.0; +- o += textureSampleLevel(source, linear, s + t * vec2(-1.0, -1.0), 0.0).rgb +- + textureSampleLevel(source, linear, s + t * vec2(1.0, -1.0), 0.0).rgb +- + textureSampleLevel(source, linear, s + t * vec2(-1.0, 1.0), 0.0).rgb +- + textureSampleLevel(source, linear, s + t * vec2(1.0, 1.0), 0.0).rgb; +- return vec4(o / 16.0, 1.0); +-} +-"#; +- +-const TONEMAP: &str = r#" +-@group(0) @binding(0) var frame: HdFrame; +-@group(0) @binding(1) var hdr: texture_2d; +-@group(0) @binding(2) var bloom: texture_2d; +-@group(0) @binding(3) var linear: sampler; +- +-@fragment +-fn fs_tonemap(in: FullOut) -> @location(0) vec4 { +- var c = textureSampleLevel(hdr, linear, in.uv, 0.0).rgb; +- // A slight sharpen after TAA (its history resampling softens): the centre against its four +- // neighbours, kept within their range so it can't ring. +- let k = frame.taa_params.y; +- if k > 0.0 { +- let t = 1.0 / vec2(textureDimensions(hdr)); +- let n0 = textureSampleLevel(hdr, linear, in.uv + vec2(t.x, 0.0), 0.0).rgb; +- let n1 = textureSampleLevel(hdr, linear, in.uv - vec2(t.x, 0.0), 0.0).rgb; +- let n2 = textureSampleLevel(hdr, linear, in.uv + vec2(0.0, t.y), 0.0).rgb; +- let n3 = textureSampleLevel(hdr, linear, in.uv - vec2(0.0, t.y), 0.0).rgb; +- let lo = min(min(n0, n1), min(min(n2, n3), c)); +- let hi = max(max(n0, n1), max(max(n2, n3), c)); +- c = clamp(c * (1.0 + 4.0 * k) - (n0 + n1 + n2 + n3) * k, lo, hi); +- } +- c = c * frame.params.y; +- c += textureSampleLevel(bloom, linear, in.uv, 0.0).rgb * frame.params.z; +- // Up to 0.8 as it is (vanilla's look); above it, rolled off towards white by the +- // brightest channel, so hues hold instead of clipping. +- let peak = max(c.r, max(c.g, c.b)); +- let t = 0.8; +- if peak > t { +- let x = (peak - t) / (1.0 - t); +- let rolled = t + (1.0 - t) * (x / (1.0 + x)); +- c = c * (rolled / peak); +- // Very bright light bleaches towards white, as film does. +- c = mix(c, vec3(rolled), clamp((peak - 2.0) / 8.0, 0.0, 0.6)); +- } +- // A light grade: a touch more colour, and a gentle S round the middle grey. +- let luma = dot(c, vec3(0.2126, 0.7152, 0.0722)); +- c = max(mix(vec3(luma), c, 1.12), vec3(0.0)); +- c = mix(c, c * c * (3.0 - 2.0 * c), 0.18); +- return vec4(c, 1.0); +-} +-"#; +- +-const TAA: &str = r#" +-struct TaaOut { +- @location(0) color: vec4, +- @location(1) history: vec4, +-} +-@group(0) @binding(0) var frame: HdFrame; +-@group(0) @binding(1) var source: texture_2d; +-@group(0) @binding(2) var depth_tex: texture_depth_2d; +-@group(0) @binding(3) var history: texture_2d; +-@group(0) @binding(4) var linear: sampler; +- +-fn to_ycocg(c: vec3) -> vec3 { +- return vec3(c.r * 0.25 + c.g * 0.5 + c.b * 0.25, c.r * 0.5 - c.b * 0.5, c.g * 0.5 - c.r * 0.25 - c.b * 0.25); +-} +-fn from_ycocg(c: vec3) -> vec3 { +- let t = c.x - c.z; +- return vec3(t + c.y, c.x + c.z, t - c.y); +-} +-// Compress the range so a very bright pixel does not dominate the blend or the clamp. +-fn squash(c: vec3) -> vec3 { +- return c / (1.0 + max(c.r, max(c.g, c.b))); +-} +-fn unsquash(c: vec3) -> vec3 { +- return c / max(1.0 - max(c.r, max(c.g, c.b)), 0.001); +-} +- +-// The history at a uv, filtered with a Catmull-Rom spline (five bilinear taps) so that +-// resampling it every frame doesn't blur. +-fn history_color(uv: vec2) -> vec3 { +- let size = vec2(textureDimensions(history)); +- let pos = uv * size; +- let c1 = floor(pos - 0.5) + 0.5; +- let f = pos - c1; +- let w0 = f * (-0.5 + f * (1.0 - 0.5 * f)); +- let w1 = 1.0 + f * f * (-2.5 + 1.5 * f); +- let w2 = f * (0.5 + f * (2.0 - 1.5 * f)); +- let w3 = f * f * (-0.5 + 0.5 * f); +- let w12 = w1 + w2; +- let t0 = (c1 - 1.0) / size; +- let t3 = (c1 + 2.0) / size; +- let t12 = (c1 + w2 / w12) / size; +- var sum = textureSampleLevel(history, linear, vec2(t12.x, t0.y), 0.0).rgb * (w12.x * w0.y); +- var total = w12.x * w0.y; +- sum += textureSampleLevel(history, linear, vec2(t0.x, t12.y), 0.0).rgb * (w0.x * w12.y); +- total += w0.x * w12.y; +- sum += textureSampleLevel(history, linear, t12, 0.0).rgb * (w12.x * w12.y); +- total += w12.x * w12.y; +- sum += textureSampleLevel(history, linear, vec2(t3.x, t12.y), 0.0).rgb * (w3.x * w12.y); +- total += w3.x * w12.y; +- sum += textureSampleLevel(history, linear, vec2(t12.x, t3.y), 0.0).rgb * (w12.x * w3.y); +- total += w12.x * w3.y; +- return max(sum / total, vec3(0.0)); +-} +- +-// Pulls `p` towards the box's centre until it is inside. +-fn clip_to_box(lo: vec3, hi: vec3, p: vec3) -> vec3 { +- let centre = (lo + hi) * 0.5; +- let ext = max((hi - lo) * 0.5, vec3(0.00001)); +- let off = (p - centre) / ext; +- let m = max(abs(off.x), max(abs(off.y), abs(off.z))); +- return select(p, centre + (p - centre) / m, m > 1.0); +-} +- +-// Temporal anti-aliasing: the history, reprojected by depth and the camera's move, clamped to +-// the colours round this pixel (so what moved or was uncovered can't ghost), blended in. +-@fragment +-fn fs_taa(in: FullOut) -> TaaOut { +- let size = vec2(textureDimensions(source)); +- let px = vec2(in.position.xy); +- let d = textureLoad(depth_tex, px, 0); +- var sum = vec3(0.0); +- var sum2 = vec3(0.0); +- var lo = vec3(1.0e9); +- var hi = vec3(-1.0e9); +- var centre = vec3(0.0); +- for (var y = -1; y <= 1; y++) { +- for (var x = -1; x <= 1; x++) { +- let q = clamp(px + vec2(x, y), vec2(0), size - 1); +- let s = to_ycocg(squash(textureLoad(source, q, 0).rgb)); +- sum += s; +- sum2 += s * s; +- lo = min(lo, s); +- hi = max(hi, s); +- if x == 0 && y == 0 { centre = s; } +- } +- } +- let sky = d <= 0.0; +- let ndc = vec4(in.uv.x * 2.0 - 1.0, 1.0 - in.uv.y * 2.0, max(d, 0.000001), 1.0); +- let h = frame.inverse_view_proj * ndc; +- let p = h.xyz / h.w; +- let dist = select(length(p), 0.0, sky); +- var resolved = centre; +- if frame.taa.w > 0.5 { +- let prev = frame.prev_view_proj * vec4(select(p + frame.taa.xyz, p, sky), 1.0); +- if prev.w > 0.0 { +- let pn = prev.xy / prev.w; +- let uv = vec2(pn.x * 0.5 + 0.5, 0.5 - pn.y * 0.5); +- if all(uv > vec2(0.0)) && all(uv < vec2(1.0)) { +- let hp = clamp(vec2(uv * vec2(size)), vec2(0), size - 1); +- let seen = textureLoad(history, hp, 0).a; +- let expected = select(length(p + frame.taa.xyz), 0.0, sky); +- // The same surface as last frame (not uncovered), by its distance. +- if abs(seen - expected) <= expected * 0.03 + 0.25 { +- let mean = sum / 9.0; +- let sigma = sqrt(max(sum2 / 9.0 - mean * mean, vec3(0.0))); +- let box_lo = min(max(mean - sigma * 1.5, lo), centre); +- let box_hi = max(min(mean + sigma * 1.5, hi), centre); +- let past = clip_to_box(box_lo, box_hi, to_ycocg(squash(history_color(uv)))); +- // Fast motion trusts the history less. +- let moved = length((uv - in.uv) * vec2(size)); +- let keep = mix(frame.taa_params.x, frame.taa_params.x * 0.75, clamp(moved / 4.0, 0.0, 1.0)); +- resolved = mix(centre, past, keep); +- } +- } +- } +- } +- let color = unsquash(from_ycocg(resolved)); +- var out: TaaOut; +- out.color = vec4(color, 1.0); +- out.history = vec4(color, dist); +- return out; +-} +- +-// The jittered samples' reconstruction filter (a polynomial fit of Lanczos-2, radius 2 in +-// world-target pixels): 1 at 0, 0 at 1 and 2, a little negative between. +-fn lanczos2(x: f32) -> f32 { +- let x2 = min(x * x, 4.0); +- let a = 0.4 * x2 - 1.0; +- let b = 0.25 * x2 - 1.0; +- return (1.5625 * a * a - 0.5625) * b * b; +-} +- +-// Temporal upscaling: the world (and its depth) is smaller than the output. Each output pixel +-// gathers the 3x3 world samples round it, each weighed by its distance from the pixel's centre +-// (the samples lie off the pixel centres by the frame's jitter), clamps the reprojected full-size +-// history to their colour box and blends: more history where the nearest sample is far away. +-@fragment +-fn fs_taau(in: FullOut) -> TaaOut { +- let low = vec2(textureDimensions(source)); +- let lowi = vec2(low); +- let high = vec2(textureDimensions(history)); +- let jit = frame.taa_params.zw; +- // The output pixel's place among the world's samples: sample i lies at index i - jit, and +- // the nearest to this pixel is `base`. +- let t = in.uv * low - 0.5 + jit; +- let base = vec2(floor(t + 0.5)); +- var sum = vec3(0.0); +- var sum2 = vec3(0.0); +- var lo = vec3(1.0e9); +- var hi = vec3(-1.0e9); +- var weighted = vec3(0.0); +- var total = 0.0; +- for (var y = -1; y <= 1; y++) { +- for (var x = -1; x <= 1; x++) { +- let q = clamp(base + vec2(x, y), vec2(0), lowi - 1); +- let s = to_ycocg(squash(textureLoad(source, q, 0).rgb)); +- sum += s; +- sum2 += s * s; +- lo = min(lo, s); +- hi = max(hi, s); +- let off = vec2(base + vec2(x, y)) - t; +- let w = lanczos2(off.x) * lanczos2(off.y); +- weighted += s * w; +- total += w; +- } +- } +- let current = weighted / max(total, 0.001); +- // Depth: the nearest of the 2x2 samples round the pixel (steady between frames at an edge). +- let corner = vec2(floor(in.uv * low - 0.5 + jit)); +- var d = 0.0; +- for (var y = 0; y <= 1; y++) { +- for (var x = 0; x <= 1; x++) { +- d = max(d, textureLoad(depth_tex, clamp(corner + vec2(x, y), vec2(0), lowi - 1), 0)); +- } +- } +- let sky = d <= 0.0; +- // The world was drawn shifted by the jitter in clip space; this pixel's unshifted point. +- let jc = vec2(jit.x * 2.0 / low.x, -jit.y * 2.0 / low.y); +- let ndc = vec4(in.uv.x * 2.0 - 1.0 + jc.x, 1.0 - in.uv.y * 2.0 + jc.y, max(d, 0.000001), 1.0); +- let h = frame.inverse_view_proj * ndc; +- let p = h.xyz / h.w; +- let dist = select(length(p), 0.0, sky); +- var resolved = current; +- if frame.taa.w > 0.5 { +- let prev = frame.prev_view_proj * vec4(select(p + frame.taa.xyz, p, sky), 1.0); +- if prev.w > 0.0 { +- let pn = prev.xy / prev.w; +- let uv = vec2(pn.x * 0.5 + 0.5, 0.5 - pn.y * 0.5); +- if all(uv > vec2(0.0)) && all(uv < vec2(1.0)) { +- let hp = clamp(vec2(uv * high), vec2(0), vec2(high) - 1); +- let seen = textureLoad(history, hp, 0).a; +- let expected = select(length(p + frame.taa.xyz), 0.0, sky); +- if abs(seen - expected) <= expected * 0.03 + 0.25 { +- let mean = sum / 9.0; +- let sigma = sqrt(max(sum2 / 9.0 - mean * mean, vec3(0.0))); +- let box_lo = min(max(mean - sigma * 1.25, lo), current); +- let box_hi = max(min(mean + sigma * 1.25, hi), current); +- let past = clip_to_box(box_lo, box_hi, to_ycocg(squash(history_color(uv)))); +- // How far the nearest sample is from the pixel's centre (0 on it, 1 at the +- // corner of the world's pixel): the farther, the less the frame says. +- let near = clamp(length(t - floor(t + 0.5)) / 0.7071, 0.0, 1.0); +- let fresh = (1.0 - frame.taa_params.x) * mix(1.8, 0.5, near); +- let moved = length((uv - in.uv) * high); +- let keep = (1.0 - fresh) * mix(1.0, 0.8, clamp(moved / 4.0, 0.0, 1.0)); +- resolved = mix(current, past, clamp(keep, 0.0, 0.98)); +- } +- } +- } +- } +- let color = unsquash(from_ycocg(resolved)); +- var out: TaaOut; +- out.color = vec4(color, 1.0); +- out.history = vec4(color, dist); +- return out; +-} +-"#; +- +-pub(super) struct Target { +- pub(super) view: wgpu::TextureView, +-} +- +-pub(super) fn target( +- device: &wgpu::Device, +- label: &str, +- size: [u32; 2], +- format: wgpu::TextureFormat, +-) -> Target { +- let view = device +- .create_texture(&wgpu::TextureDescriptor { +- label: Some(label), +- size: wgpu::Extent3d { +- width: size[0].max(1), +- height: size[1].max(1), +- depth_or_array_layers: 1, +- }, +- mip_level_count: 1, +- sample_count: 1, +- dimension: wgpu::TextureDimension::D2, +- format, +- usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, +- view_formats: &[], +- }) +- .create_view(&Default::default()); +- Target { view } +-} +- +-/// The outside views and sampler the lighting group reads. +-type LightKey = ( +- wgpu::TextureView, +- wgpu::TextureView, +- wgpu::TextureView, +- wgpu::Sampler, +-); +- +-/// What bloom and the tone curve read: the lit world, or the post pass's output. +-#[derive(Clone, Copy, PartialEq, Eq)] +-pub enum HdSource { +- Lit, +- Fx, +- /// The anti-aliased result of `taa`. +- Taa, +-} +- +-/// TAA is on unless `HORIZON_HD_TAA=0`. +-pub fn taa_enabled() -> bool { +- static ON: std::sync::OnceLock = std::sync::OnceLock::new(); +- *ON.get_or_init(|| std::env::var("HORIZON_HD_TAA").map_or(true, |v| v != "0")) +-} +- +-/// The water effect is on unless `HORIZON_HD_WATER=0`. +-pub fn water_enabled() -> bool { +- static ON: std::sync::OnceLock = std::sync::OnceLock::new(); +- *ON.get_or_init(|| std::env::var("HORIZON_HD_WATER").map_or(true, |v| v != "0")) +-} +- +-/// The Halton sequence's `index`-th number in `base`, in (0, 1). +-fn halton(mut index: u32, base: u32) -> f32 { +- let (mut f, mut r) = (1.0, 0.0); +- while index > 0 { +- f /= base as f32; +- r += f * (index % base) as f32; +- index /= base; +- } +- r +-} +- +-/// The history's weight when upscaling (the frames each pixel gathers are sparse, so more of them +-/// are kept than without; `fs_taau` lowers it where the frame's sample is near). +-const UPSCALE_HISTORY: f32 = 0.92; +- +-/// The world's size relative to the output (`HORIZON_HD_SCALE`, per axis, 0.25..=1) while HD is on, if +-/// set: it replaces the resolution scale of Horizon's settings for HD. 1 renders at full size. +-pub fn scale_override() -> Option { +- static SCALE: std::sync::OnceLock> = std::sync::OnceLock::new(); +- *SCALE.get_or_init(|| { +- let v: f32 = std::env::var("HORIZON_HD_SCALE").ok()?.parse().ok()?; +- v.is_finite().then(|| v.clamp(0.25, 1.0)) +- }) +-} +- +-/// How many jitter positions the sequence cycles through for an output `ratio` times the world's +-/// size per axis: 16 without upscaling, else 8 per output pixel's share of a world pixel +-/// (ratio squared), so every output pixel gets samples all over the world pixel it lies in. +-pub fn jitter_count(ratio: f32) -> u32 { +- if ratio <= 1.001 { +- 16 +- } else { +- ((8.0 * ratio * ratio).ceil() as u32).clamp(16, 64) +- } +-} +- +-/// Frame `frame`'s sub-pixel offset of the projection in clip space (a fraction of the +-/// screen's size in x and y), from the Halton(2, 3) sequence over `count` frames. +-pub fn jitter(frame: u32, size: [u32; 2], count: u32) -> [f32; 2] { +- let i = frame % count.max(1) + 1; +- [ +- (halton(i, 2) - 0.5) * 2.0 / size[0].max(1) as f32, +- (halton(i, 3) - 0.5) * 2.0 / size[1].max(1) as f32, +- ] +-} +- +-pub struct Hd { +- /// The world's size (the G-buffer, lighting, AO, post pass), and the output's (TAA, bloom, +- /// tone curve): bigger when the world is upscaled. +- size: [u32; 2], +- out: [u32; 2], +- pub albedo: wgpu::TextureView, +- pub normal: wgpu::TextureView, +- pub levels: wgpu::TextureView, +- /// The shadow cascades: the array to sample, one view per layer to draw. +- shadow_array: wgpu::TextureView, +- shadow_layers: Vec, +- shadow_sampler: wgpu::Sampler, +- /// The globals the shadow passes draw with (the light's view), and the camera's to put back. +- pub shadow_globals: [wgpu::Buffer; 2], +- pub main_globals: wgpu::Buffer, +- frames: u32, +- pub depth: wgpu::TextureView, +- /// The lit world, and the post pass's output. +- pub lit: wgpu::TextureView, +- pub fx: wgpu::TextureView, +- /// Water: its surface colour and normal, its depth (the nearest water surface; 0 elsewhere), +- /// the lit world with the water over it, and what draws and composites them. +- water_tint: wgpu::TextureView, +- water_normal: wgpu::TextureView, +- water_depth: wgpu::TextureView, +- lit_water: wgpu::TextureView, +- /// The lighting's second target: the air over water, the floor beside translucent things. +- air: wgpu::TextureView, +- water_layout: wgpu::BindGroupLayout, +- water_pipeline: wgpu::RenderPipeline, +- water_group: Option<((wgpu::TextureView, wgpu::Sampler), wgpu::BindGroup)>, +- /// The water effect runs this frame (the scene allows it and there is translucent terrain on +- /// screen), and `lit_view` is the composite. +- water_active: bool, +- /// The frame's translucent terrain exists (set by the renderer before `write`). +- pub water_geometry: bool, +- water_composited: bool, +- /// The volumetric clouds and the fog run this frame. +- clouds_active: bool, +- fog_active: bool, +- /// The sky-view texture (see `hd_sky`), the pass that marches it and its bind group. +- sky_lut: wgpu::TextureView, +- sky_pipeline: wgpu::RenderPipeline, +- sky_group: wgpu::BindGroup, +- /// The sun's height the sky-view texture was marched for (it depends on nothing else), and +- /// whether this frame's sun has moved enough to march it again. +- sky_drawn_for: f32, +- sky_stale: bool, +- started: std::time::Instant, +- /// TAA: the resolved frame, and the two histories (one read, one written, alternating). +- taa: wgpu::TextureView, +- history: [wgpu::TextureView; 2], +- history_ready: bool, +- history_flip: usize, +- taa_active: bool, +- taa_layout: wgpu::BindGroupLayout, +- taa_pipeline: wgpu::RenderPipeline, +- taau_pipeline: wgpu::RenderPipeline, +- taa_groups: Option<((wgpu::TextureView, wgpu::TextureView), [wgpu::BindGroup; 2])>, +- bloom: Vec, +- /// Bind groups, rebuilt only when their views change: `resize` drops all of them, the +- /// lighting and the source-reading ones are keyed by the views they read. +- light_group: [Option<(LightKey, wgpu::BindGroup)>; 2], +- /// The volumetric clouds and fog (see `hd_volumes`). +- volumes: HdVolumes, +- prefilter_group: Option<(wgpu::TextureView, wgpu::BindGroup)>, +- tone_group: Option<(wgpu::TextureView, wgpu::BindGroup)>, +- /// Reading bloom level k - 1 (for the down pass into level k, index k - 1) and level k (for +- /// the up pass onto level k - 1, index k - 1). +- down_groups: Vec, +- up_groups: Vec, +- frame: wgpu::Buffer, +- lights: wgpu::Buffer, +- /// The tiles' light lists (see `tile_lists`), sized for the screen, and the tiles per row. +- tiles: wgpu::Buffer, +- tiles_x: u32, +- tile_scratch: Vec>, +- tile_words: Vec, +- sampler: wgpu::Sampler, +- light_layout: wgpu::BindGroupLayout, +- light_pipeline: wgpu::RenderPipeline, +- bloom_layout: wgpu::BindGroupLayout, +- prefilter: wgpu::RenderPipeline, +- down: wgpu::RenderPipeline, +- up: wgpu::RenderPipeline, +- tone_layout: wgpu::BindGroupLayout, +- tone: wgpu::RenderPipeline, +- /// The ambient occlusion: its strength in the lighting, the half-resolution targets (raw, then +- /// blurred), their passes and bind groups (made at `resize`). +- pub ao_strength: f32, +- ao_raw: wgpu::TextureView, +- ao_blurred: wgpu::TextureView, +- ao_layout: wgpu::BindGroupLayout, +- ao_blur_layout: wgpu::BindGroupLayout, +- ao_pipeline: wgpu::RenderPipeline, +- ao_blur_pipeline: wgpu::RenderPipeline, +- ao_group: Option, +- ao_blur_group: Option, +- /// GPU time of the HD passes while diagnostics ask for it (`set_timing`). +- timing: Option, +- /// Bind groups made so far, and in the last frame (a steady state makes none). +- groups_made: AtomicU64, +- groups_seen: u64, +- pub groups_last_frame: u64, +-} +- +-/// The tiles' header (4 words each) and index lists for a screen of `size`. +-fn tiles_buffer(device: &wgpu::Device, size: [u32; 2]) -> wgpu::Buffer { +- let tiles = (size[0].div_ceil(TILE).max(1) * size[1].div_ceil(TILE).max(1)) as usize; +- device.create_buffer(&wgpu::BufferDescriptor { +- label: Some("HD light tiles"), +- size: ((tiles * 4 + TILE_INDICES) * std::mem::size_of::()) as u64, +- usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, +- mapped_at_creation: false, +- }) +-} +- +-/// Where a camera-relative sphere can show on the screen. +-enum Cover { +- /// Nowhere: it is wholly behind the camera. +- Nothing, +- /// Anywhere: it crosses the camera's plane, or holds the camera. +- Everywhere, +- /// Inside this pixel rectangle (min x, min y, max x, max y). +- Rect([f32; 4]), +-} +- +-/// The screen cover of the sphere at `c` of radius `r`: the projection of the 8 corners of the +-/// box round it. A box is convex and so is its projection while every corner is in front of the +-/// camera, so the rectangle holds the whole sphere. With some corners behind, the projection +-/// is not bounded and the cover is the whole screen; with all of them behind, no pixel ray +-/// (they all point forward) can meet the sphere. +-fn cover(view_proj: &Mat4, c: glam::Vec3, r: f32, size: [u32; 2]) -> Cover { +- if !c.is_finite() || !r.is_finite() { +- return Cover::Everywhere; +- } +- // A little more than the shader's radius, against rounding. +- let r = r * 1.01 + 0.01; +- let (mut lo, mut hi) = (glam::Vec2::splat(f32::MAX), glam::Vec2::splat(f32::MIN)); +- let mut front = 0; +- for corner in 0..8 { +- let o = glam::Vec3::new( +- if corner & 1 == 0 { -r } else { r }, +- if corner & 2 == 0 { -r } else { r }, +- if corner & 4 == 0 { -r } else { r }, +- ); +- let h = *view_proj * (c + o).extend(1.0); +- if h.w > 0.0 { +- front += 1; +- let ndc = glam::Vec2::new(h.x, h.y) / h.w; +- let px = glam::Vec2::new( +- (ndc.x * 0.5 + 0.5) * size[0] as f32, +- (0.5 - ndc.y * 0.5) * size[1] as f32, +- ); +- lo = lo.min(px); +- hi = hi.max(px); +- } +- } +- match front { +- 0 => Cover::Nothing, +- 8 => Cover::Rect([lo.x - 2.0, lo.y - 2.0, hi.x + 2.0, hi.y + 2.0]), +- _ => Cover::Everywhere, +- } +-} +- +-/// Fills `words` with each 16x16 tile's two lists of the lights that can reach it: header +-/// (surface start, surface length, halo start, halo length) per tile, then the indices; a +-/// length of `EVERY_LIGHT` stands for all of `lights` (a list past the buffer's room). The +-/// surface list holds the lights whose sphere can touch what the tile sees. The halo list +-/// holds the lights whose halo can reach a ray of the tile: the shader adds a halo for the +-/// view *line* passing within half the radius of the light, so a ray pointing away from a light +-/// behind it is lit too, and the mirrored sphere is covered as well. Lights stay in order, so +-/// the sums are the ones of the full loop. +-fn tile_lists( +- view_proj: &Mat4, +- lights: &[HdLight], +- size: [u32; 2], +- scratch: &mut Vec>, +- words: &mut Vec, +-) { +- let tx = size[0].div_ceil(TILE).max(1) as usize; +- let ty = size[1].div_ceil(TILE).max(1) as usize; +- let tiles = tx * ty; +- scratch.resize_with(tiles * 2, Vec::new); +- scratch.truncate(tiles * 2); +- scratch.iter_mut().for_each(Vec::clear); +- let mut add = |list: usize, area: Cover, light: u16| match area { +- Cover::Nothing => {} +- Cover::Everywhere => { +- for t in 0..tiles { +- scratch[t * 2 + list].push(light); +- } +- } +- Cover::Rect([x0, y0, x1, y1]) => { +- let tile = TILE as f32; +- if x1 < 0.0 || y1 < 0.0 || x0 >= size[0] as f32 || y0 >= size[1] as f32 { +- return; +- } +- let from = |v: f32, n: usize| ((v / tile).floor().max(0.0) as usize).min(n - 1); +- for y in from(y0, ty)..=from(y1, ty) { +- for x in from(x0, tx)..=from(x1, tx) { +- scratch[(y * tx + x) * 2 + list].push(light); +- } +- } +- } +- }; +- for (i, l) in lights.iter().enumerate() { +- let c = glam::Vec3::new(l.pos[0], l.pos[1], l.pos[2]); +- add(0, cover(view_proj, c, l.pos[3], size), i as u16); +- // The shader's halo reach: the line within `radius / 2 - 0.5` of the light. +- let reach = l.pos[3] * 0.5 - 0.5; +- if reach > 0.0 || !reach.is_finite() { +- add(1, cover(view_proj, c, reach, size), i as u16); +- add(1, cover(view_proj, -c, reach, size), i as u16); +- } +- } +- words.clear(); +- words.resize(tiles * 4, 0); +- let mut room = TILE_INDICES; +- for t in 0..tiles { +- for list in 0..2 { +- let ids = &mut scratch[t * 2 + list]; +- // Both the sphere and its mirror can name a light: once is enough. +- ids.dedup(); +- let at = t * 4 + list * 2; +- if ids.len() > room { +- words[at + 1] = EVERY_LIGHT; +- } else { +- room -= ids.len(); +- words[at] = words.len() as u32; +- words[at + 1] = ids.len() as u32; +- words.extend(ids.iter().map(|&i| u32::from(i))); +- } +- } +- } +-} +- +-/// The timestamps of the pass `name` while HD passes are timed. +-fn stamp<'a>( +- timing: &'a mut Option, +- name: &str, +-) -> Option> { +- timing.as_mut()?.writes(name) +-} +- +-/// `HORIZON_HD_AO=0` turns the ambient occlusion off, another number sets its strength. +-fn ao_strength_default() -> f32 { +- std::env::var("HORIZON_HD_AO") +- .ok() +- .and_then(|v| v.parse().ok()) +- .unwrap_or(AO_STRENGTH) +-} +- +-/// The shader's source: the common part, then the body with the sky-reading functions where it +-/// has a marker (`//SKY15`: the sky-view texture is binding 15, `//SKY10`: binding 10). +-pub(super) fn assemble(body: &str) -> String { +- let mut body = body.to_owned(); +- // Highest number first: `//SKY1` must not eat the start of `//SKY15`. +- for binding in (0..32).rev() { +- body = body.replace( +- &format!("//SKY{binding}"), +- &hd_sky::SKY_FUNCS.replace("SKYBIND", &binding.to_string()), +- ); +- } +- format!("{COMMON}{body}") +-} +- +-pub(super) fn module(device: &wgpu::Device, label: &str, body: &str) -> wgpu::ShaderModule { +- // Development: with `HORIZON_HD_SHADER_DIR` set, a shader's body is read from +- // `/