diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dc07a65..384838b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -55,6 +55,48 @@ jobs: env: RUSTDOCFLAGS: -D warnings + denoise: + # The `denoise` feature links Intel Open Image Denoise (ADR 0011): build and test it + # against the pinned official package. The jobs above build without it. + name: Denoise feature (${{ matrix.name }}) + strategy: + fail-fast: false + matrix: + include: + - name: macOS arm64 + os: macos-latest + oidn: arm64.macos + - name: Windows x64 + os: windows-latest + oidn: x64.windows + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v5 + - uses: dtolnay/rust-toolchain@stable + with: + components: clippy + - uses: Swatinem/rust-cache@v2 + with: + key: denoise + - uses: actions/cache@v4 + with: + path: .oidn + key: oidn-${{ matrix.oidn }}-${{ hashFiles('scripts/fetch-oidn.sh') }} + - name: Fetch OIDN + shell: bash + run: | + dir=$(cd "$(scripts/fetch-oidn.sh ${{ matrix.oidn }})" && pwd) + if command -v cygpath > /dev/null; then + # Windows: tests find the DLLs through PATH. + cygpath -w "$dir/bin" >> "$GITHUB_PATH" + dir=$(cygpath -w "$dir") + fi + echo "OIDN_DIR=$dir" >> "$GITHUB_ENV" + - name: Clippy + run: cargo clippy --workspace --all-targets --features aktis-pt/denoise,aktis-app/denoise -- -D warnings + - name: Test + run: cargo test --workspace --features aktis-pt/denoise,aktis-app/denoise + docs-check: name: Docs updated with code if: github.event_name == 'pull_request' && !contains(github.event.pull_request.labels.*.name, 'no-docs') diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 93556c2..d59c6bf 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -3,6 +3,9 @@ name: Release on: push: tags: ["v*.*.*"] + # Dry run: builds and packages every platform and uploads the archives as workflow + # artifacts, without the tag check or a GitHub Release. Works on forks too. + workflow_dispatch: permissions: contents: write @@ -13,8 +16,8 @@ env: jobs: prepare: name: Prepare - # Only the main repository publishes releases; forks skip this workflow. - if: github.repository == 'TriBinary/aktis' + # Only the main repository publishes releases; forks skip tag pushes (dry runs are fine). + if: github.repository == 'TriBinary/aktis' || github.event_name == 'workflow_dispatch' runs-on: ubuntu-latest outputs: version: ${{ steps.meta.outputs.version }} @@ -25,8 +28,14 @@ jobs: - id: meta name: Check tag matches Cargo version run: | - tag="${GITHUB_REF_NAME#v}" cargo_version=$(cargo metadata --no-deps --format-version 1 | jq -r '.packages[] | select(.name == "aktis-app") | .version') + if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then + echo "Dry run of $cargo_version" + echo "version=$cargo_version-dryrun" >> "$GITHUB_OUTPUT" + echo "prerelease=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + tag="${GITHUB_REF_NAME#v}" echo "tag=$tag cargo=$cargo_version" if [ "$tag" != "$cargo_version" ]; then echo "::error::Tag v$tag does not match workspace version $cargo_version in Cargo.toml" @@ -62,14 +71,17 @@ jobs: - name: macos-arm64 os: macos-latest target: aarch64-apple-darwin + oidn: arm64.macos archive: tar.gz - name: macos-x64 os: macos-latest target: x86_64-apple-darwin + oidn: x86_64.macos archive: tar.gz - name: windows-x64 os: windows-latest target: x86_64-pc-windows-msvc + oidn: x64.windows archive: zip runs-on: ${{ matrix.os }} steps: @@ -80,8 +92,17 @@ jobs: - uses: Swatinem/rust-cache@v2 with: key: ${{ matrix.target }} + - name: Fetch OIDN + shell: bash + run: | + dir=$(cd "$(scripts/fetch-oidn.sh ${{ matrix.oidn }})" && pwd) + echo "OIDN_POSIX_DIR=$dir" >> "$GITHUB_ENV" + command -v cygpath > /dev/null && dir=$(cygpath -w "$dir") + echo "OIDN_DIR=$dir" >> "$GITHUB_ENV" + # No rpath to the download folder in shipped binaries (crates/aktis-app/build.rs). + echo "AKTIS_OIDN_RELEASE=1" >> "$GITHUB_ENV" - name: Build - run: cargo build --release --locked -p aktis-app --target ${{ matrix.target }} + run: cargo build --release --locked -p aktis-app --features denoise --target ${{ matrix.target }} - name: Package shell: bash run: | @@ -90,6 +111,7 @@ jobs: bin="target/${{ matrix.target }}/release/aktis" [ "${{ runner.os }}" = "Windows" ] && bin="$bin.exe" cp "$bin" README.md CHANGELOG.md LICENSE-MIT LICENSE-APACHE "dist/$name/" + scripts/bundle-oidn.sh "$OIDN_POSIX_DIR" "dist/$name" cd dist if [ "${{ matrix.archive }}" = "zip" ]; then 7z a "$name.zip" "$name" > /dev/null @@ -105,6 +127,7 @@ jobs: publish: name: Publish GitHub Release + if: github.event_name == 'push' needs: [prepare, build] runs-on: ubuntu-latest steps: diff --git a/.gitignore b/.gitignore index 473ed9d..f6dab17 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,6 @@ /test-worlds/ /renders/ *.mca + +# OIDN downloads (scripts/fetch-oidn.sh) +/.oidn/ diff --git a/CHANGELOG.md b/CHANGELOG.md index ee6191f..8cc3d3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,12 +6,472 @@ uses [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Fixed + +- Path Tracer: the trace shader failed to compile on Windows (DX12/FXC: "array + reference cannot be used as an l-value"), so path-traced renders and jobs failed there. +- Docs: `cargo doc` failed on a link to a private item in `aktis-sp`. +- Tests: GPU tests skip software adapters (WARP on Windows CI), where the job-runner + tests ran for minutes and then crashed the test process. A new compile-only test, + `shaders_compile_on_any_adapter`, still builds the path tracer and preview pipelines + there, so FXC shader errors are still caught. +- Tests: tests in `preview_gpu.rs`, `pack_geometry.rs` and `shadow_gpu.rs` no longer + share a temp pack folder (one test's cleanup could delete another's files: "Invalid + argument" on macOS CI, a short mesh on Windows CI). + +## [0.1.0] - 2026-12-01 + +First release, a **beta**: every planned milestone (M1–M8) is done. Tested by hand on macOS +(Apple Silicon); Windows is built and tested in CI but not yet smoke-tested by hand. + +### Highlights + +- **Worlds:** opens Java Edition 26.3 saves from the vanilla launcher or Prism Launcher, + with the instance's resource packs stacked on top of your own client jar (no Mojang + assets are shipped). +- **Preview:** a rasterized fly-through of the selected area, with water, lava, paintings, + item frames and display entities. +- **Path Tracer:** progressive GPU path tracing with a Preetham sky and sun, LabPBR + normal and specular maps, glowing blocks as lights, refracting water, height fog with + light shafts, and Open Image Denoise. +- **Shader Pack:** OptiFine/Iris packs run outside the game, compiled for Metal and + DX12/Vulkan, shadows and custom textures included. BSL and Complementary Reimagined + render. +- **Animation:** a keyframe timeline for the camera, sun, sky and fog, real-time + playback with the camera path drawn, project files (`*.aktis.toml`), a render queue, + PNG sequences and MP4/MOV video through your own ffmpeg. +- **Big worlds:** a memory budget that lowers the detail radius to fit, one geometry + copy per engine in use, far terrain out to 512 chunks in every engine (through + Distant Horizons programs in shader packs), and a detail area that follows the camera. + +### Known limitations + +- Windows: not smoke-tested by hand. Binaries aren't signed or notarized (on macOS, + right-click → Open the first time). +- Fixed plains biome tint; no block entities (chests, signs, …) or mobs. +- Shader packs: pack defaults only (no options UI); no compute passes, raw custom textures, + clouds/weather/particle/entity programs; far terrain casts no shadow (`dh_shadow` isn't + run). +- Far terrain is a heightfield: no overhangs, caves, entities or biome tints far away. +- No headless rendering, 16-bit PNG/EXR, motion blur or animated block textures. + ### Added +- Re-centring: when the camera flies more than half the detail radius from the centre, a new + detail area (and its far terrain) loads around it in the background and replaces the old + one, keeping the view (about half a second at detail 8 / far 128 on the test save). Not + during playback or render jobs, or when the Project panel's Centre is custom. The Loaded + box shows the current centre. +- Far terrain in shader packs: packs with Distant Horizons programs (BSL, Complementary) + draw the far terrain with `dh_terrain`/`dh_water`, compiled with `DISTANT_HORIZONS` and + given the `dh*` uniforms, `dhMaterialId` and DH depth textures, so their fog, water and + composites treat it as they do with the Distant Horizons mod. Packs without those programs + show no far terrain, and the Render panel says so. Far terrain casts no shadow in shader + packs yet. +- Far terrain in the path tracer: the far columns are traced as a heightfield after the + detail area, so they show in the path view (with the sun's shadows, sky light and + bounces, and water that reflects and absorbs) and the albedo view (matching the preview). + Radius 128 on the test save adds 6.8 MiB on the GPU; the path view takes about twice as + long per sample when far terrain fills the view. +- Far terrain in the preview: beyond the detail radius, out to the new **Far radius** + (Project panel, default 64 chunks, up to 512; `--far-radius`; `far_radius` in project + files, missing = none), the terrain is drawn as coloured block columns that get coarser + with distance, with water over the sea floor. It meets the detail area without a gap and + counts towards the memory estimate (radius 128 on the test save: 0.15 s to read, 43 MiB + on the GPU). +- Far-terrain colours (not drawn yet): `aktis_render::lod::LodPalette` gives every block + state one colour, the mean of its top texture (tinted), with water, waterlogged plants + and snowy blocks handled. +- Far-terrain data (not drawn yet): `aktis_world::lod` reads one column (top block and, + under water, the ground) per 1–16 blocks square from the chunks' saved heightmaps, in + rings that get coarser with distance. The whole 26.3 test save reads in 0.13 s into + 4.8 MiB; columns match the full block data exactly. +- Memory budget (Project panel, Auto = half of your RAM, or a number of GB; also + `memory_budget_gb` in project files and `--memory-budget`): before loading, Aktis counts + the chunks the save really has around the centre and estimates the load's peak memory for + the engine in use. If it's over the budget, a smaller radius loads and the app says so + ("Radius lowered from 64 to 21 to fit the 4.0 GB memory budget."); the panel shows the + estimate and warns before Load. Queued jobs follow it too. Running out of GPU memory + while uploading a world now disables that engine with a message instead of crashing. +- Opt-in benchmark `m8_big_world`: time and memory of each load stage (chunks, assets, + mesh, quad grid, preview, path-tracer and shader-pack uploads) and of freeing them, with + the macOS process footprint split into malloc and GPU; byte counts + `BlockGrid::heap_bytes`, `WorldMesh::heap_bytes`, `PackMesh::heap_bytes` and + `ShaderPackRenderer::world_gpu_bytes`. Results in `docs/subsystems/far-terrain.md` → + "Measurements". +- Big worlds (M8) design: `docs/subsystems/far-terrain.md` (detail area plus a far-terrain + heightfield in LOD rings for every engine, a memory budget, one geometry copy per engine + in use, re-centring), ADRs 0019 and 0020, the planned `far_radius` and + `memory_budget_gb` project-file fields in `scene.md`, baseline load times and memory on + the 26.3 test save, and the M8 task list in the roadmap. No code yet. +- Animation performance notes: frame times per engine at 1080p, encode times and the + shader-pack warm-up check (`docs/subsystems/animation.md` → "Performance"), from a new + opt-in benchmark. +- Video: animation jobs can write MP4 (H.264 or H.265) or MOV (ProRes 422 HQ) through your + own ffmpeg, found on PATH or in the usual install folders (or chosen in the Output + section). Frames render first, then ffmpeg encodes them with BT.709 colour; the frames + are deleted unless Keep frames is on. A failed encode shows ffmpeg's message and offers + Encode again. +- Render queue: "Add animation…" and "Add still…" in the Render queue tab queue a snapshot + of the project; Start renders the jobs one after another at the output resolution to + numbered PNG files, loading each job's world and shader pack as needed, with + Pause/Resume, Cancel, progress, time left and a log line per frame. Jobs can be + reordered, duplicated, run again, removed or opened as a project. The queue is saved + with the app; an interrupted job resumes, skipping frames already on disk, and quitting + while it runs asks first. The viewport shows the frame being rendered meanwhile. +- Output resolution: an Output section with presets (720p to 4K) or a custom size. With + Render size "Output" (the default) the viewport renders at that resolution, fitted + inside a frame guide, and Save PNG saves that size; "Viewport" keeps the old behaviour. + Custom and hand-edited sizes are rounded to even numbers. +- Orbit helper: "Orbit…" in the timeline header writes camera keys around a circle (centre, + radius, height, start angle, turns either way, start and duration; starting where the + camera is) plus a Look at key on the centre, replacing keys in that range. One undo step. +- Timeline playback: Play/Pause (header button or K) and Loop play the in/out range in + real time, dropping frames rather than slowing down. The path tracer shows the preview + while playing; shader packs follow the playhead's time even when stopped. The preview + draws the camera path with its keys while the Timeline tab is open, and the viewport + darkens what lies outside the output's aspect (frame guide). +- Undo and redo: an Edit menu with Undo (Cmd/Ctrl-Z) and Redo (Shift-Cmd/Ctrl-Z) for scene + and timeline edits, up to 100 steps. A drag or slider pull is one step; flying the camera + isn't recorded. New and Open clear the history. +- Timeline key editing: click, Shift-click and box selection; drag keys (snapped to + frames, Alt for free); Delete; Cmd/Ctrl-C and -V to copy and paste keys at the playhead + (also between projects); right-click to change a key's mode or turn on Constant speed. +- Timeline panel: a bottom panel with Timeline and Render queue tabs. The dope sheet lists + Camera, Sun, Sky and Fog values with a stopwatch, value fields and ◀ ◆ ▶ each, a time + ruler with the playhead, and key diamonds shaped by mode. With a stopwatch on, changes + set a key at the playhead; the fly camera never does and offers "Key camera" instead. +- Frame clock for animation (`FrameInput::clock`): each path-traced animation frame gets + its own noise (still images are unchanged), and shader packs get `frameTimeCounter`, + `frameTime` and real previous-frame matrices on consecutive frames, so their waves, + clouds, TAA and motion blur can follow the timeline. The viewport passes the playhead's + clock. +- Project files: a File menu with New, Open…, Save and Save As… (Cmd/Ctrl-N, -O, -S, + Shift-Cmd/Ctrl-S) reads and writes `*.aktis.toml` (world, packs, engine, scene, + timeline, output). The title shows the file and `•` for unsaved changes; New and Open + ask before discarding them. A project whose world is missing opens with notes and keeps + its timeline. +- Keyframe timeline model (`aktis_scene::timeline`): one track per animatable scene value, + key modes step/linear/smooth/ease, angles taking the shorter way round, a centripetal + Catmull-Rom camera path with optional constant speed, Look at, and `[timeline]` TOML. + Not in the app yet. +- Camera roll: `[camera] roll` in degrees (default 0; positive turns the camera clockwise), + a Roll slider in the Camera panel, applied by the preview, the path tracer and shader + packs. Old scene files load level. +- Animation (M7) design: `docs/subsystems/animation.md` (per-property keyframe tracks, + camera paths, timeline panel, playback, output, ffmpeg video, render queue), ADR 0018, + the planned `*.aktis.toml` project-file format in `scene.md`, and the M7 task list in the + roadmap. No code yet. +- Shader-pack shadow pass: packs with a `shadow` program draw the world into a shadow map + (`shadowtex0`/`shadowtex1`, `shadowcolor0–7` with their formats and clears, + `shadowMapResolution`, `shadowDistance`, `shadowIntervalSize`) before the frame, so BSL + and Complementary render shadows. +- Shader-pack shadow filtering: with `shadowHardwareFiltering` on, shadow compares + (`shadow2D`, `texture` on a `sampler2DShadow`) blend four compares as GL's linear filter + does, so shadow edges are soft. Set per pack through a pipeline constant (ADR 0017). + `shadowtexNearest` turns it off. `shadowcolor` is sampled linear unless + `shadowcolorNNearest` is set. +- Shader-pack custom textures: `texture..`, `customTexture.` and + `texture.noise` PNGs, sampled with the filtering their `.mcmeta` gives. Complementary's + clouds take their real shape. Raw and resource-location textures are logged as + unsupported. +- Shader-pack per-buffer blends: `blend..`. - Cargo workspace with crates `aktis-assets`, `aktis-world`, `aktis-scene`, `aktis-render`, `aktis-pt`, `aktis-sp` and `aktis-app`. - `RenderEngine` trait with stub Path Tracer and Shader Pack engines. - Scene data (camera, sun, sky, fog) with a TOML format. - Resource location parsing and resource-pack priority stack. +- Minecraft install discovery for the vanilla launcher and Prism Launcher: lists instances, + their version, client jar, saves and resource packs (`aktis_assets::install`). +- Reading asset files from the client jar and resource packs (zip or folder), highest-priority + source first, with listing and `pack.mcmeta` descriptions (`AssetStack::read`, `list`). +- Blockstate parsing (`variants` and `multipart`, including `OR`/`AND`/negated conditions) and + model selection with deterministic per-position weighted picks (`BlockStateDef`). +- Block model resolution and baking: parent chains, texture variables, elements with face, + element and blockstate rotations, `uvlock`, tints, cullfaces and the 26.x model additions + (texture objects, free/multi-axis element rotation, `shade_direction_override`, + `light_emission`) (`ModelBaker`). +- Block texture array: loads referenced textures (first animation frame), scales them to one + layer size, builds linear-light mips and classifies alpha as opaque/cutout/translucent + (`TextureArray`). +- World loading for 26.3 saves: `level.dat` (name, version, spawn), 26.x dimension folders, + region files and section palettes (26.x and older forms) into a sparse block grid for a + selection; only fully generated chunks are loaded (`World::load`). +- CPU meshing: per-section opaque/cutout/translucent vertex data from a block grid, + with neighbour face culling, fixed plains tints, shading normals and emitted light + (`aktis_render::mesh`). +- `BlockStateDef::select` and `Selected` for position-independent weighted model lists; + `BlockGrid::set`. +- Rasterized preview engine (`PreviewRenderer`): uploads a meshed world and its texture array + and renders it with per-face shading, sun diffuse, alpha-tested and blended passes, reverse-Z + depth and a sky colour into an offscreen texture (ADR 0006). +- `RenderEngine::output()` and `EngineOutput`; `RenderError::DeviceLimit` / `Gpu`; RGBA8 + texture readback (`aktis_render::readback`). +- `Camera::forward()`, `Camera::right()` and `Sun::direction()` with documented conventions. +- Progressive engines: `RenderEngine::reset()` and `progress()` (`Progress`). The viewport + keeps adding sample passes while a progressive engine is selected and shows the preview + while the camera moves. +- Path-tracer acceleration structure (`aktis_pt::accel::QuadGrid`): the preview's quads sorted + into an 8³-brick grid, with a CPU reference ray traversal (front/both faces, alpha-test + callback, preview-matching ties for coplanar faces) (ADR 0007). +- Path Tracer engine on the GPU (`aktis_pt::PathTracer`): uploads the quad grid and block + textures and traces it in a compute shader. Its albedo view matches the preview pixel for + pixel on test blocks; select "Path Tracer" in the Render panel (the preview is shown while + the camera moves). The engine choice is saved. +- Path-traced view (the Path Tracer's default): sunlight with shadow rays, a constant sky, + diffuse bounces with Russian roulette, anti-aliasing; samples accumulate over frames + (progress in the viewport) and are tonemapped with exposure and an ACES curve (ADR 0008). + The albedo view remains as a debug view; View and Exposure controls in the Render panel. +- Preetham daylight sky for the path tracer: sky colour and brightness from the sun's + position and haze, sunlight dimmed and reddened by the atmosphere, a visible sun disk and + soft shadows from its size; fades to black after sunset. +- The path tracer splits each pass into bands of rows (at most ~524 k pixels each, one GPU + submission per band), so large images don't trip the Windows GPU watchdog. +- Opt-in path-tracer benchmark on a generated world (`AKTIS_BENCH=1`, no game assets needed) + and path-view timing in the real-world test. +- Path-tracer controls in the Render panel: samples target, bounces, a progress bar with + render time and ms per sample, Pause/Resume, Restart and "Continue ×2"; view, samples and + bounces are remembered between runs. +- PNG export: "Save PNG…" in the Render panel saves the selected engine's current image at + the viewport's size (`aktis_render::export`); `EngineOutput` now carries its texture. +- Path-tracer materials: cutout textures (leaves, flowers) let light through their holes for + shadows and bounces; translucent blocks (glass, water) are partly see-through and tint the + light and shadows behind them; emissive surfaces (lava) glow and light their surroundings. +- `camera.exposure` (EV), `sun.angular_diameter` and `sky.turbidity` in the scene format; + Size and Haze sliders in the Sun panel. +- Shared block texture upload (`aktis_render::textures`). +- Shared camera math (`aktis_render::camera::CameraRig`): view/projection matrices and primary + rays from the same camera, used by every engine. - egui application shell (`aktis`). +- Viewer: `aktis --jar --world [--radius N] [--center x,z]` loads the + area around spawn on a background thread and shows it in the preview viewport; fly camera + (WASD, Space/Shift, Ctrl to sprint, right-drag to look, scroll for speed), frame-rate + readout and world stats. The app requests the adapter's full wgpu limits so large block + texture arrays fit. +- Project panel: choose a Minecraft instance (auto-discovered or an added folder via a native + dialog) and a world, set the selection centre, chunk radius and Y range, then load in the + background with progress and Cancel. Choices, camera, sun and fly speed are saved, and the + last world reopens on start. +- Simple water and lava in the preview: fluid blocks, waterlogged blocks and seagrass/kelp get + a box with a level-based surface height; water is translucent and tinted, lava is opaque and + glows. +- Resource packs on top of the client jar: `AssetStack::open(jar, packs)` and + `aktis --pack ` (repeatable, later packs win). Packs that can't be opened are left + out; packs made for another game version are used with a warning (pack formats from + `pack.mcmeta` vs. the jar's `version.json`). The "Loaded" box lists the packs and warnings. +- Resource Packs section in the project panel: enable packs from the instance's + `resourcepacks/` or add any zip/folder, order them (top wins), see each pack's description + and a warning for missing or other-version packs, and Apply them to the world on screen + (keeps the camera and reuses the loaded blocks instead of reading chunks again). Choices + are saved per instance. +- "Max texture size" in the Resource Packs section (16–512 px, default 128): high-resolution + pack textures are scaled down to it to bound GPU memory, with a memory estimate; the + "Loaded" box shows the texture array's size and memory (ADR 0009). +- LabPBR maps: `_n.png` (normal, AO, height) and `_s.png` (smoothness, + F0/metals, porosity/SSS, emission) from resource packs are loaded into arrays aligned with + the block textures, with defaults for textures without maps and decoders following LabPBR + 1.3 (`aktis_assets::decode_normal`, `decode_specular`). The "Loaded" box counts the maps. + The path tracer binds them, and two debug views ("Normal map", "Specular map") show the + stored texels of the surface under each pixel. +- Normal mapping in the path tracer: LabPBR normal maps tilt how surfaces catch sunlight and + scatter bounced light (`aktis_pt::shading` holds the tangent-frame math, mirrored in the + shader). Worlds without maps render exactly as before. +- Specular materials in the path tracer from LabPBR specular maps: smoothness, dielectric + reflectance, the eight LabPBR metals (exact conductor Fresnel) and albedo-coloured metals, + with sharp sun reflections on smooth surfaces (GGX, Smith, Fresnel, multiple importance + sampling; `aktis_pt::brdf`, ADR 0010). +- Emission maps in the path tracer: the LabPBR specular map's alpha makes texels glow; a + block glows with the brighter of its light level and its map (`aktis_pt::color::emission`). +- "PBR materials" checkbox in the path tracer's settings: switches the LabPBR maps on and off + without reloading (off renders like a world without maps); saved with the other settings + and disabled when the loaded packs have no maps (`PathTracerSettings::pbr`). +- Milestone M3 (PBR & packs) is complete: tested with a real LabPBR pack and smoke-tested on + macOS. +- Denoiser features in the path tracer: every path pass also accumulates the first surface's + albedo (a metal's reflectance, tinted by glass in front) and shading normal, the inputs + Intel Open Image Denoise will take (`PathTracer::read_features`, `aktis_pt::Features`). + Two new views, "Albedo AOV" and "Normal AOV", show them. +- `aktis_render::readback::read_buffer` copies a GPU buffer to the CPU. +- Optional `denoise` Cargo feature that links Intel Open Image Denoise 2.5.1 + (`aktis_pt::denoise`; the app logs whether the denoiser works at start-up), with + `scripts/fetch-oidn.sh` to download the pinned official package and + `scripts/bundle-oidn.sh` to ship it. Release archives are built with the feature and carry + the OIDN libraries and licences (ADR 0011). CI also builds and tests with the feature; the + release workflow can be run by hand as a dry run that publishes nothing. +- Denoising in the path tracer (with the `denoise` feature): the path view's colour and + features are read back (`PathTracer::denoise_input`), denoised by OIDN on the CPU on the + calling thread or a worker thread (`aktis_pt::denoise::{denoise, Denoiser}`), and shown + tonemapped (`PathTracer::show_denoised`, `show_raw`). Results for an image that has moved + on are ignored. A 1280×720 image takes about 150 ms. +- Blocks that glow by their block state now glow in the path tracer and look bright in the + preview: glowstone, sea lanterns, torches, lanterns, froglights, lit furnaces, redstone + lamps and torches, campfires, candles (by count), sea pickles under water, respawn anchors + and more (`aktis_render::mesh::light_level`, Aktis's own table of the documented levels). +- Glowing blocks are sampled as lights in the path tracer: each surface sends a shadow ray to + a point on a glowing quad picked by its power, combined with bounce hits by multiple + importance sampling (ADR 0012). Lamps, torches and lava light their surroundings with far + less noise (12× lower error in a test at 16 spp); scenes with glowing blocks take about a + third longer per sample. +- Water and lava surfaces slope: each top corner's height comes from the fluid around it, so + flowing water runs down from its source in a continuous surface, dips at drops and rises + to meet water above (both engines). The path tracer traces such non-flat faces as two + triangles, split exactly as the preview draws them (ADR 0007 addendum). +- Real water in the path tracer: water surfaces reflect and refract (index 1.33, Fresnel), + water absorbs light with depth so shallows are clear and deep water turns blue, the + camera can be under water, and sunlight and lamps reach under water through the surface + (ADR 0013). Water's vanilla texture is no longer used by the path tracer. +- Entity reading: `World::load_entities` reads paintings, item frames, glow item frames and + block/item display entities (position, rotation, variant, facing, item, block state, + transformation, billboard) from the world's entity region files, including riders, in both + the 26.x and older NBT spellings. +- Item models: item definitions (`items/.json`: model, composite, condition, select, + range dispatch) with layer tints, model `display` transforms, and `builtin/generated` + sprites extruded into 1/16-thick 3D models (`ItemDefinition`, `ModelBaker::bake_item`). + Special renderers (chests, banners, heads, shields, shulker boxes…) are reported, not + drawn. +- Paintings, item frames and glow item frames (with their item), block displays and item + displays are drawn in the preview and the path tracer. Glowing blocks shown by block + displays light their surroundings. Maps in frames show the map item, not the map picture; + billboarded displays don't turn to the camera. +- Height fog: new scene fields `fog.height_falloff`, `base_height`, `color` and `anisotropy` + next to `density`, and a Fog panel. The path tracer scatters light in the fog (haze, light + shafts, fog shadows, glow around the sun and lamps); the preview fades to the fog colour. + Old scene files load without fog. +- Denoise controls in the Render panel (builds with the `denoise` feature): Denoise on/off, + denoise automatically when finished, Denoised / Raw switch, Denoise now (when finished or + paused) and a status line; saved between runs. Save PNG… saves the denoised image when it + is shown (denoising first if needed) and suggests a `… denoised.png` name. The overlay + says "· denoised". +- The opt-in real-world path-tracer test (`pt_real.rs`) takes resource packs and a texture + size cap, and with LabPBR maps also times and saves the path view with PBR off and the map + views. Real-world and real-pack timings are in the path-tracer docs. It also meshes the + selection's entities, takes a camera (`AKTIS_TEST_CAMERA`) and, built with `denoise`, + times denoising a 64-spp image; end-of-M4 numbers are in the path-tracer docs. - Documentation system (`docs/`), `CLAUDE.md` agent guide, and ADRs 0001–0005. - GitHub Actions: CI on macOS and Windows, docs check, tag-based releases; Dependabot. + +- Shader-pack census test (`aktis-sp/tests/pack_census.rs`, opt-in with + `AKTIS_TEST_SHADERPACK`): every `world0` stage of a pack through glslang → naga → MSL and + HLSL, plus BSL's `gbuffers_terrain` as a GPU render pipeline (M5 spike; BSL v10.1.8: 59 of + 63 stages compile with the spike patch). + +- Shader-pack loading (`aktis_sp::ShaderPack`): zip or folder packs, dimension folders, + option discovery, preprocessed `shaders.properties` (program enables, custom uniforms), + programs with their fallbacks, and the macros Iris defines (`MC_VERSION` 260300 for 26.3). + +- Shader-pack program compiler (`aktis_sp::ProgramCompiler`): directive comments, glslang + preprocessing, a token patcher from legacy to core GLSL (ADR 0014), SPIR-V and validated + naga modules with one layout per program (uniform block offsets, texture/sampler bindings, + vertex input and varying locations, draw buffers, consts). BSL v10.1.8: every program of + its default pipeline compiles; errors name the pack file and line. + +- Saved block and sky light (`BlockGrid::light`): `BlockLight` / `SkyLight` of every section + of the loaded chunks, with rules for the arrays the game leaves out; `LoadStats::unlit` + counts chunks saved without light. + +- Shader-pack geometry: the mesher records each quad's block (`QuadOrigin`); a 2D block + atlas with per-tile mips and LabPBR atlases (`aktis_sp::atlas`); `block.properties` block + ids (`aktis_sp::block_ids`); pack vertices with Iris's terrain attributes, saved light and + block ids (`aktis_sp::geometry`, ADR 0015). + +- Shader-pack uniforms (`aktis_sp::uniforms`): ~100 built-ins computed from the scene + (camera, sun on the game's daily arc, still-image time and weather, saved light at the + eye), per-draw matrices, the custom-uniform expression language of `shaders.properties`, + and std140 block writing by name (ADR 0016). Terrain `gl_Vertex` is camera-relative, as in + Iris. + +- Shader-pack pipeline runner (`aktis_sp::runner::ShaderPackRenderer`): colour buffers + with pack formats, Iris's clears and main/alt ping-pong, history buffers, depth copies, + terrain (with the cutout alpha test) → deferred → water → composite → final → upright + output; blend and alpha-test properties, `texture.noise`, a generated lightmap and + shadow stand-ins. BSL's whole default pipeline builds and runs. + +- Shader-pack sky: the sky disc, stars, sun and moon for `gbuffers_skybasic` and + `gbuffers_skytextured`, with the sun and moon textures from the client jar (26.x + `celestial/` and older layouts). BSL draws its sky, clouds and sun. +- Shader packs in the app: Render → Shader Pack with a pack picker per instance (its + `shaderpacks/` plus added packs), Rescan, Reload, build status and a Problems list. Packs + compile on a worker thread while the preview shows; the view is live while moving and + renders 16 warm-up frames when still; Save PNG… saves the pack's image. `--shaderpack + ` renders with a pack for one run. +- `RenderEngine::warm_up` for real-time engines with a warm-up; `ShaderPackEngine` is a + working engine; `aktis_sp::find_packs`. +- Opt-in real-world shader-pack test (`aktis-sp/tests/pack_real.rs`): renders a save with a + pack and saves a PNG. BSL v10.1.8 renders the scene recognizably by day and night. + +### Changed +- The Project panel's Radius is now **Detail radius**; the budget message says "Detail + radius lowered…". +- Water at the edge of the selection no longer dips: blocks past the edge count as + unknown rather than air when shaping the water surface. +- The Project panel's warning above radius 32 is replaced by the memory estimate. +- Shader packs need much less memory on big worlds: pack vertices are 44 bytes instead of + 52 (`mc_Entity` and `at_midBlock` are stored as integers; packs still read the exact + values), and the world is turned into pack vertices and uploaded section by section + instead of all at once. Radius 64 on the test save with BSL: 5.6 GiB instead of + 13.4 GiB, the build no longer peaks at 18.6 GiB, and it takes ~5 s instead of ~6–7 s. +- Worlds load faster: chunks are parsed in parallel (radius 64 on the test save: 0.66 s → + 0.25 s), with the same result as before. +- Only the engine in use keeps world geometry on the GPU (ADR 0020): a load builds the + mesh and quad grid only for the Preview / Path Tracer engines, the CPU mesh isn't kept + (shader-pack builds mesh on their own thread), and switching engine frees the old + engine's geometry and builds the new one's in the background ("Building the world's + geometry for this engine…"). Radius 64 on the test save: 6.2 GiB instead of 14 GiB + with BSL. The Loaded box shows Preview, Path tracer and Shader pack memory separately. +- Meshing drops the vertex lists' spare capacity (the CPU mesh is ~30 % smaller). +- "Preparing …" no longer claims the preview is shown meanwhile (the Shader Pack + engine keeps no preview geometry). +- The Render panel's shader-pack hover texts no longer say packs have no shadows. +- Shader packs get the game's fog colour as `fogColor` (and colortex0's clear): plains fog + `#C0D8FF`, moved towards the sky colour at short render distances. It used to be the sky + colour, so terrain that Complementary fades out at the render-distance edge stood out + against the sky below the horizon. BSL's horizon is paler, as in game. +- Shader packs: `modf` and `frexp`, Iris's core uniforms and attributes used without a + declaration, and `gl_VertexID`/`gl_InstanceID` now compile. Every enabled Complementary + program except the Distant Horizons ones compiles, including its clouds pass. +- Shader packs: textures a program never uses are dropped, and textures sampled the same + way share one sampler, so packs that declare many textures fit Metal's 16 samplers per + stage. Complementary Reimagined now builds and draws terrain (no clouds or shadows yet); + BSL's image is unchanged. +- Roadmap: M6 (shader-pack compatibility) planned and started; the shader-pack + compatibility table records Complementary r5.10's census in detail. +- README and docs: M5 status (BSL renders), shader-pack performance and compatibility table. +- Shader packs sample the block atlas raw (gamma-encoded), like the game's textures, instead + of as sRGB (packs linearize it themselves). +- Shader-pack geometry pulls atlas UVs 1/16 px into their tile, so faces no longer + sample the neighbouring texture at their edges. +- Roadmap: M4 and M5 (shader packs MVP) marked done. +- `AssetStack::push` now opens the source and returns a `Result`. +- README: current status (M1–M4 done) and feature list instead of the M0 placeholder. +- `World::open` now reads `level.dat` and fails on a corrupt one. +- The default camera pitch is now +20 (looking slightly down) instead of −20 (up). +- Mesh vertices are now 16 bytes with section-local positions and no index data (half the + memory). + +### Fixed +- The app's saved state (`app.ron`) never restored: the timeline's `in`/`out` failed to + decode from RON, so every start fell back to the defaults (engine, shader pack choices, + scene, timeline, queue…). Saved states written by earlier builds now restore too. +- The shader-pack status reports 0 s compiling when the compiled pack is reused (it showed + the few nanoseconds the reuse took), as documented. +- A shader pack whose programs need more samplers per stage than the GPU allows (16 on + Metal; Complementary needs 24) crashed in wgpu; those programs are now skipped and listed + as problems. +- Shader-pack buffers with formats that have no alpha (`RGB16F`, `R11F_G11F_B10F`, …) kept + an alpha channel; they now read alpha 1, as in the game. +- Cargo no longer warns about the unused `workspace.package.homepage` field (it duplicated + `repository` and no crate inherited it). +- The opt-in real-model test (`model_real.rs`) failed on resource packs that ship a stray + blockstate for a block the game doesn't have; such blockstates are now reported only. +- The opt-in real-world path-tracer test compared the path view instead of the albedo view + with the preview (broken since the path view became the default). +- Blocks saved in their default state (26.x stores them as a bare name without properties) + were invisible: grass blocks, logs, deepslate, tall plants and more. Missing properties now + get default values before the model is chosen (`BlockStateDef::fill_defaults`). +- The grass block's green side overlay (and other faces drawn over a coplanar face) was + hidden by the depth test. +- Right-drag look left the cursor wherever the mouse ended up, often at the window edge; the + cursor is now hidden and held in place during the drag and reappears where it started. +- The app viewport showed the preview too dark and saturated (sRGB decoded twice); egui now + gets a non-sRGB view of the output. +- Model faces whose `texture` omits the `#` (vanilla `heavy_core`) now resolve as texture + variables instead of as a texture named `minecraft:all`. diff --git a/CLAUDE.md b/CLAUDE.md index b4eec43..66520d8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -118,6 +118,7 @@ crates/ aktis-sp/ shader-pack engine (OptiFine/Iris pipeline) aktis-app/ egui desktop app, binary name `aktis` docs/ documentation system (index: docs/README.md) +scripts/ build/release helpers (OIDN download and bundling, ADR 0011) .github/ CI, release workflow, templates ``` @@ -135,7 +136,8 @@ engines never depend on each other. - WGSL shaders go in `crates//shaders/*.wgsl` and are loaded with `include_str!`. - No `unsafe` without a `// SAFETY:` comment and a mention in the report. - Unit tests live next to the code; cross-crate tests go in `crates//tests/`. -- GPU tests that need a real adapter must skip gracefully when none is available (CI has no GPU). +- GPU tests that need a real adapter must skip gracefully when none is available, and treat + a software adapter (`wgpu::DeviceType::Cpu`, e.g. WARP on Windows CI) as none (CI has no GPU). ## 8. Git setup (for context only; never run write commands) diff --git a/Cargo.lock b/Cargo.lock index e434fcc..f9554ce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -56,13 +56,23 @@ dependencies = [ "eframe", "egui", "env_logger", + "glam", "log", + "pollster", + "rfd", + "ron", + "serde", + "serde_json", + "sysinfo", + "toml", ] [[package]] name = "aktis-assets" version = "0.1.0" dependencies = [ + "directories", + "glam", "image 0.25.10", "log", "serde", @@ -81,7 +91,12 @@ dependencies = [ "aktis-world", "bytemuck", "glam", + "image 0.25.10", "log", + "naga", + "oidn", + "pollster", + "rayon", "thiserror 2.0.21", "wgpu", ] @@ -90,10 +105,15 @@ dependencies = [ name = "aktis-render" version = "0.1.0" dependencies = [ + "aktis-assets", "aktis-scene", "aktis-world", "bytemuck", + "glam", + "image 0.25.10", "log", + "pollster", + "rayon", "thiserror 2.0.21", "wgpu", ] @@ -103,6 +123,8 @@ name = "aktis-scene" version = "0.1.0" dependencies = [ "glam", + "log", + "ron", "serde", "thiserror 2.0.21", "toml", @@ -116,9 +138,17 @@ dependencies = [ "aktis-render", "aktis-scene", "aktis-world", + "bytemuck", + "glam", + "image 0.25.10", "log", + "naga", + "pollster", + "serde_json", + "shaderc", "thiserror 2.0.21", "wgpu", + "zip", ] [[package]] @@ -128,8 +158,10 @@ dependencies = [ "aktis-assets", "fastanvil", "fastnbt", + "flate2", "glam", "log", + "rayon", "serde", "thiserror 2.0.21", ] @@ -456,6 +488,15 @@ dependencies = [ "error-code", ] +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + [[package]] name = "codespan-reporting" version = "0.13.1" @@ -565,6 +606,25 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-utils" version = "0.8.23" @@ -583,6 +643,27 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" +[[package]] +name = "directories" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16f5094c54661b38d03bd7e50df373292118db60b585c08a411c6d840017fe7d" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.2", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -596,6 +677,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" dependencies = [ "bitflags 2.13.2", + "block2 0.6.2", + "libc", "objc2 0.6.5", ] @@ -1492,6 +1575,15 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" +[[package]] +name = "link-cplusplus" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f78c730aaa7d0b9336a299029ea49f9ee53b0ed06e9202e8cb7db9bae7b8c82" +dependencies = [ + "cc", +] + [[package]] name = "linux-raw-sys" version = "0.4.15" @@ -1606,6 +1698,7 @@ dependencies = [ "naga-types", "num-traits", "once_cell", + "petgraph", "rustc-hash 1.1.0", "spirv", "thiserror 2.0.21", @@ -1681,6 +1774,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "ntapi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" +dependencies = [ + "winapi", +] + [[package]] name = "num-integer" version = "0.1.47" @@ -1817,6 +1919,7 @@ dependencies = [ "objc2-core-foundation", "objc2-core-graphics", "objc2-foundation 0.3.2", + "objc2-uniform-type-identifiers 0.3.2", ] [[package]] @@ -1934,6 +2037,16 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "objc2-io-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15" +dependencies = [ + "libc", + "objc2-core-foundation", +] + [[package]] name = "objc2-io-surface" version = "0.3.2" @@ -2035,7 +2148,7 @@ dependencies = [ "objc2-link-presentation", "objc2-quartz-core 0.2.2", "objc2-symbols", - "objc2-uniform-type-identifiers", + "objc2-uniform-type-identifiers 0.2.2", "objc2-user-notifications", ] @@ -2062,6 +2175,16 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7902ac02859fc1f7045f8b598c63f1ae0cc7efeaa06a9bc9f3d9a3c955974fa4" +dependencies = [ + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-user-notifications" version = "0.2.2" @@ -2075,6 +2198,17 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "oidn" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c750490adf2813dad251dace8cff2f57b6d67cd2d29e3127ba9e9bd13b46e32" +dependencies = [ + "bitflags 2.13.2", + "num_enum 0.7.6", + "pkg-config", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -2087,6 +2221,12 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + [[package]] name = "orbclient" version = "0.3.55" @@ -2364,6 +2504,26 @@ dependencies = [ "objc2-quartz-core 0.3.2", ] +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + [[package]] name = "read-fonts" version = "0.41.0" @@ -2402,6 +2562,16 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror 2.0.21", +] + [[package]] name = "regex" version = "1.13.2" @@ -2437,6 +2607,34 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" +[[package]] +name = "rfd" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4b9d4857b10297ffb0f64cae711e983a7aeaee561848d56d429d3858bd8ed93" +dependencies = [ + "block2 0.6.2", + "dispatch2", + "js-sys", + "libc", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-uniform-type-identifiers 0.3.2", + "percent-encoding", + "pollster", + "raw-window-handle", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "web-sys", + "windows-sys 0.61.2", +] + [[package]] name = "ron" version = "0.12.3" @@ -2450,6 +2648,12 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "roxmltree" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" + [[package]] name = "rustc-hash" version = "1.1.0" @@ -2604,6 +2808,29 @@ dependencies = [ "serde_core", ] +[[package]] +name = "shaderc" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ab2a6e36d1c1e2320c87e2b806a3e7b0dffaa67b82c14a39dad6cf7637208ae" +dependencies = [ + "libc", + "shaderc-sys", +] + +[[package]] +name = "shaderc-sys" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdceb85b2c6d2c27b95ffe2d341063dfded0aca8046f7f60c544bbeaeaf8bcae" +dependencies = [ + "cmake", + "libc", + "link-cplusplus", + "pkg-config", + "roxmltree", +] + [[package]] name = "shlex" version = "2.0.1" @@ -2748,6 +2975,20 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "sysinfo" +version = "0.40.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ebe31c61260d7bc4bfc204a2d096c428a4c9ef59ca48bfa693d17fec4f129ad" +dependencies = [ + "libc", + "memchr", + "ntapi", + "objc2-core-foundation", + "objc2-io-kit", + "windows", +] + [[package]] name = "tar" version = "0.4.46" @@ -3417,6 +3658,22 @@ dependencies = [ "web-sys", ] +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + [[package]] name = "winapi-util" version = "0.1.11" @@ -3426,6 +3683,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + [[package]] name = "windows" version = "0.62.2" diff --git a/Cargo.toml b/Cargo.toml index cd942f8..e7960d9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,6 @@ edition = "2024" rust-version = "1.95" license = "MIT OR Apache-2.0" repository = "https://github.com/TriBinary/aktis" -homepage = "https://github.com/TriBinary/aktis" authors = ["Trilleo"] publish = false @@ -36,12 +35,15 @@ glam = { version = "0.34", features = ["serde", "bytemuck"] } serde = { version = "1", features = ["derive"] } serde_json = "1" toml = "1" +# Tests only: decode eframe's saved state the way eframe does (same version as eframe uses). +ron = "0.12" # --- Minecraft formats --- zip = { version = "9", default-features = false, features = ["deflate"] } image = { version = "0.25", default-features = false, features = ["png"] } fastanvil = "0.32" fastnbt = "2" +flate2 = "1" # --- utilities --- thiserror = "2" @@ -51,12 +53,18 @@ env_logger = "0.11" rayon = "1" directories = "6" rfd = "0.18" +# Total system RAM for the memory budget's Auto setting (ADR 0020); only the memory part. +sysinfo = { version = "0.40", default-features = false, features = ["system"] } + +# shaderc: GLSL -> SPIR-V for shader packs (aktis-sp, ADR 0004). Always builds glslang from +# source (no system/Vulkan SDK library); needs CMake, Python 3 and a C++ toolchain. +shaderc = { version = "0.10", features = ["build-from-source"] } # --- planned (declared here, not yet used by any crate) --- -# shaderc: GLSL -> SPIR-V for shader packs (aktis-sp). Builds glslang from source; needs CMake + C++ toolchain. -shaderc = "0.10" -# oidn: Intel Open Image Denoise (aktis-pt). Needs the OIDN runtime library; see docs/dev/getting-started.md. -oidn = "2" +# oidn: Intel Open Image Denoise (aktis-pt, optional feature `denoise`, ADR 0011). Links the +# OIDN library from OIDN_DIR (scripts/fetch-oidn.sh) or pkg-config; the crate's version follows +# OIDN's, keep it on the release scripts/fetch-oidn.sh pins. +oidn = "2.5" [workspace.lints.rust] unsafe_code = "warn" diff --git a/README.md b/README.md index 2eea26b..446768d 100644 --- a/README.md +++ b/README.md @@ -10,26 +10,44 @@ two engines: Runs on **macOS (Apple Silicon)** and **Windows**. -> **Status: early development (M0, scaffold).** Nothing renders yet; see the -> [roadmap](docs/roadmap.md). +> **Status: beta (0.1.0).** All planned milestones (M1–M8) are done and tested by hand on +> macOS. Windows is built and tested in CI but not yet smoke-tested by hand. Expect rough +> edges; see the [changelog](CHANGELOG.md) for known limitations and the +> [roadmap](docs/roadmap.md) for what's next. -## Features (planned) +## Features -- Open any Java Edition world and select an area to render +- Open any Java Edition world (26.3) from the vanilla launcher or Prism Launcher and select + an area to render - Vanilla look from your own Minecraft installation, with resource packs stacked on top -- LabPBR materials (normal and specular maps) -- Progressive GPU path tracing with denoising -- OptiFine/Iris shader-pack rendering -- Simple UI with sensible defaults -- Animation and video rendering (later) +- Fly-through preview of the selected area +- Progressive GPU path tracing with LabPBR materials (normal and specular maps, metals, + emission) and denoising (Open Image Denoise) +- Glowing blocks that light their surroundings, refracting water, height fog with light shafts +- Paintings, item frames and block/item display entities +- OptiFine/Iris shader packs with shadows and custom textures (BSL and Complementary + Reimagined tested), compiled for Metal and DX12/Vulkan +- Animation: keyframe timeline for camera, sun, sky and fog, real-time playback, render + queue, PNG sequences and MP4/MOV video through your own ffmpeg +- Big worlds: a memory budget, and far terrain out to 512 chunks in every engine around a + detail area that follows the camera +- Project files (`*.aktis.toml`) and a simple UI with sensible defaults +- Not yet: shader-pack options, biome tints, mobs and block entities, headless rendering ## Requirements - Minecraft Java Edition installed (Aktis reads vanilla textures from your copy; it never ships Mojang assets) - A GPU with Metal (macOS) or DirectX 12 / Vulkan (Windows) support +- Optional: [ffmpeg](https://ffmpeg.org/) for video output -## Building +## Download + +Prebuilt archives for macOS (Apple Silicon and Intel) and Windows x64 are attached to each +[GitHub release](https://github.com/TriBinary/aktis/releases). They aren't signed yet: on +macOS, right-click → Open the first time. + +## Building from source ```sh git clone https://github.com/TriBinary/aktis.git diff --git a/crates/aktis-app/Cargo.toml b/crates/aktis-app/Cargo.toml index 9970cad..453245b 100644 --- a/crates/aktis-app/Cargo.toml +++ b/crates/aktis-app/Cargo.toml @@ -21,10 +21,24 @@ aktis-pt.workspace = true aktis-sp.workspace = true eframe.workspace = true egui.workspace = true +glam.workspace = true +serde.workspace = true +rfd.workspace = true +sysinfo.workspace = true anyhow.workspace = true +toml.workspace = true log.workspace = true env_logger.workspace = true +[dev-dependencies] +serde_json.workspace = true +ron.workspace = true +pollster.workspace = true + +[features] +# Denoising with Intel Open Image Denoise (ADR 0011); release builds turn it on. +denoise = ["aktis-pt/denoise"] + [target.'cfg(target_os = "linux")'.dependencies] eframe = { workspace = true, features = ["x11", "wayland"] } diff --git a/crates/aktis-app/build.rs b/crates/aktis-app/build.rs new file mode 100644 index 0000000..245e916 --- /dev/null +++ b/crates/aktis-app/build.rs @@ -0,0 +1,20 @@ +//! With the `denoise` feature on macOS: an `@executable_path` rpath, so a release finds the +//! OIDN libraries shipped next to `aktis`, and (unless `AKTIS_OIDN_RELEASE` is set) one to +//! `$OIDN_DIR/lib` so `cargo run` and the tests find them in a developer's download. See +//! ADR 0011. + +fn main() { + println!("cargo:rerun-if-env-changed=OIDN_DIR"); + println!("cargo:rerun-if-env-changed=AKTIS_OIDN_RELEASE"); + let denoise = std::env::var_os("CARGO_FEATURE_DENOISE").is_some(); + let macos = std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos"); + if !(denoise && macos) { + return; + } + println!("cargo:rustc-link-arg=-Wl,-rpath,@executable_path"); + let release = std::env::var_os("AKTIS_OIDN_RELEASE").is_some(); + if !release && let Some(dir) = std::env::var_os("OIDN_DIR").filter(|d| !d.is_empty()) { + let lib = std::path::Path::new(&dir).join("lib"); + println!("cargo:rustc-link-arg=-Wl,-rpath,{}", lib.display()); + } +} diff --git a/crates/aktis-app/src/animate.rs b/crates/aktis-app/src/animate.rs new file mode 100644 index 0000000..d7effe6 --- /dev/null +++ b/crates/aktis-app/src/animate.rs @@ -0,0 +1,491 @@ +//! Editing rules between the base scene, the timeline and what's shown (M7 task 5a; see +//! `docs/subsystems/animation.md` → "Timeline panel"). +//! +//! The app keeps the **base scene** (saved in projects) and the timeline. What's shown is +//! `timeline.scene_at(base, playhead)` with the fly camera's [`CameraOverride`] on top. An +//! edit of the shown scene goes to a key at the playhead when the property's stopwatch is +//! on (auto-key), else to the base. The fly camera never sets keys: its moves of animated +//! camera values stay in the override until "Key camera" or a playhead move. + +use aktis_scene::timeline::{Interp, Key, Property, Timeline, Value}; +use aktis_scene::{Camera, Scene}; +use glam::Vec3; +use serde::{Deserialize, Serialize}; + +/// Distance of the first Look at key in front of the camera, in blocks. +pub const LOOK_AT_START_DISTANCE: f32 = 16.0; + +/// The fly camera's moves of camera values the timeline animates; `None` = follows the +/// timeline. +#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)] +pub struct CameraOverride { + /// Position, when the position track is on. + pub position: Option, + /// Yaw, when the yaw track or Look at is on. + pub yaw: Option, + /// Pitch, when the pitch track or Look at is on. + pub pitch: Option, +} + +impl CameraOverride { + /// Whether the camera follows the timeline (nothing overridden). + pub fn is_empty(&self) -> bool { + *self == Self::default() + } + + /// Puts the overridden values on `camera`. + pub fn apply(&self, camera: &mut Camera) { + if let Some(p) = self.position { + camera.position = p; + } + if let Some(y) = self.yaw { + camera.yaw = y; + } + if let Some(p) = self.pitch { + camera.pitch = p; + } + } +} + +/// Which camera values the timeline animates: `(position, yaw, pitch)`. A track counts once +/// its stopwatch is on (even without keys, so the next move can be keyed); Look at counts for +/// yaw and pitch once it has keys. +pub fn camera_animated(timeline: &Timeline) -> (bool, bool, bool) { + let on = |p| timeline.track(p).is_some_and(|t| t.enabled); + let look_at = timeline + .track(Property::CameraLookAt) + .is_some_and(|t| t.is_active()); + ( + on(Property::CameraPosition), + on(Property::CameraYaw) || look_at, + on(Property::CameraPitch) || look_at, + ) +} + +/// Whether Look at sets yaw and pitch. +pub fn look_at_active(timeline: &Timeline) -> bool { + timeline + .track(Property::CameraLookAt) + .is_some_and(|t| t.is_active()) +} + +/// The scene shown at `t`: the timeline applied to `base`, then the fly camera's override. +pub fn shown_scene( + timeline: &Timeline, + base: &Scene, + t: f64, + camera_override: &CameraOverride, +) -> Scene { + let mut scene = timeline.scene_at(base, t); + camera_override.apply(&mut scene.camera); + scene +} + +/// `t` moved to the nearest frame. +pub fn snap(timeline: &Timeline, t: f64) -> f64 { + timeline.frame_time(timeline.frame_at(t)) +} + +/// Index of the key of `property` within half a frame of `t`. +pub fn key_here(timeline: &Timeline, property: Property, t: f64) -> Option { + let half = 0.5 / f64::from(timeline.fps.max(1)); + timeline + .track(property)? + .keys + .iter() + .position(|k| (k.time - t).abs() < half) +} + +/// Time of the last key of `property` more than half a frame before `t`. +pub fn previous_key(timeline: &Timeline, property: Property, t: f64) -> Option { + let half = 0.5 / f64::from(timeline.fps.max(1)); + timeline + .track(property)? + .keys + .iter() + .rev() + .map(|k| k.time) + .find(|&time| time < t - half) +} + +/// Time of the first key of `property` more than half a frame after `t`. +pub fn next_key(timeline: &Timeline, property: Property, t: f64) -> Option { + let half = 0.5 / f64::from(timeline.fps.max(1)); + timeline + .track(property)? + .keys + .iter() + .map(|k| k.time) + .find(|&time| time > t + half) +} + +/// Sets the key of `property` at `t` (snapped to a frame) to `value`, keeping the mode of a +/// key already there (new keys are `smooth`). Turns the stopwatch on. +pub fn set_key(timeline: &mut Timeline, property: Property, t: f64, value: Value) { + let time = snap(timeline, t); + let half = 0.5 / f64::from(timeline.fps.max(1)); + let interp = key_here(timeline, property, time) + .and_then(|i| timeline.track(property).map(|tr| tr.keys[i].interp)) + .unwrap_or(Interp::Smooth); + let track = timeline.track_mut(property); + track.enabled = true; + // Replaces a key within half a frame (also one left off-frame by an fps change). + track.keys.retain(|k| (k.time - time).abs() >= half); + track.set_key(Key { + time, + value, + interp, + }); +} + +/// The value of `property` to key or keep, as shown; Look at has no scene field, so its +/// value is the point [`LOOK_AT_START_DISTANCE`] blocks ahead of the camera. +pub fn shown_value(property: Property, shown: &Scene) -> Value { + property.get(shown).unwrap_or_else(|| { + Value::Vec3(shown.camera.position + shown.camera.forward() * LOOK_AT_START_DISTANCE) + }) +} + +/// Applies an edit of the shown scene (`before` → `after`, from the panels or the value +/// fields): each changed property gets a key at `t` when its stopwatch is on, else its base +/// value changes. Returns whether the timeline changed. +pub fn route_edit( + timeline: &mut Timeline, + base: &mut Scene, + before: &Scene, + after: &Scene, + t: f64, +) -> bool { + let mut keyed = false; + for p in Property::ALL { + let (Some(old), Some(new)) = (p.get(before), p.get(after)) else { + continue; + }; + if old == new { + continue; + } + if timeline.track(p).is_some_and(|tr| tr.enabled) { + set_key(timeline, p, t, new); + keyed = true; + } else { + p.set(base, new); + } + } + keyed +} + +/// Applies a fly-camera move (`shown` camera before the move → `flown`): values the +/// timeline animates go to the override (cleared again where they match the timeline); +/// the rest go to the base, as without a timeline. `evaluated` is the timeline's camera at +/// the playhead (without the override). +pub fn apply_fly( + timeline: &Timeline, + base: &mut Scene, + camera_override: &mut CameraOverride, + evaluated: &Camera, + flown: &Camera, +) { + let (pos, yaw, pitch) = camera_animated(timeline); + if pos { + camera_override.position = (flown.position != evaluated.position).then_some(flown.position); + } else { + base.camera.position = flown.position; + camera_override.position = None; + } + if yaw { + camera_override.yaw = (flown.yaw != evaluated.yaw).then_some(flown.yaw); + } else { + base.camera.yaw = flown.yaw; + camera_override.yaw = None; + } + if pitch { + camera_override.pitch = (flown.pitch != evaluated.pitch).then_some(flown.pitch); + } else { + base.camera.pitch = flown.pitch; + camera_override.pitch = None; + } +} + +/// "Key camera": keys the shown camera's position, yaw and pitch at `t` (position only +/// while Look at sets the angles), turning their stopwatches on, and clears the override. +pub fn key_camera( + timeline: &mut Timeline, + camera_override: &mut CameraOverride, + shown: &Camera, + t: f64, +) { + set_key( + timeline, + Property::CameraPosition, + t, + Value::Vec3(shown.position), + ); + if !look_at_active(timeline) { + set_key(timeline, Property::CameraYaw, t, Value::Scalar(shown.yaw)); + set_key( + timeline, + Property::CameraPitch, + t, + Value::Scalar(shown.pitch), + ); + } + *camera_override = CameraOverride::default(); +} + +/// Stopwatch on: enables the track and, when it has no keys, keys the shown value at `t`. +pub fn stopwatch_on(timeline: &mut Timeline, property: Property, shown: &Scene, t: f64) { + let empty = timeline.track(property).is_none_or(|tr| tr.keys.is_empty()); + timeline.track_mut(property).enabled = true; + if empty { + set_key(timeline, property, t, shown_value(property, shown)); + } +} + +/// Stopwatch off (after the user agreed to lose the keys): removes the track; the shown +/// value becomes the base value. +pub fn stopwatch_off(timeline: &mut Timeline, base: &mut Scene, property: Property, shown: &Scene) { + if let Some(value) = property.get(shown) { + property.set(base, value); + } + timeline.tracks.retain(|tr| tr.property != property); +} + +/// ◆: removes the key at `t`, or adds one with the shown value. +pub fn toggle_key_here(timeline: &mut Timeline, property: Property, shown: &Scene, t: f64) { + match key_here(timeline, property, t) { + Some(i) => { + timeline.track_mut(property).keys.remove(i); + } + None => set_key(timeline, property, t, shown_value(property, shown)), + } +} + +// ---- Key editing (task 5b) ---- + +/// A key, identified by its property and time (indices change when keys move). +pub type KeyRef = (Property, f64); + +/// Whether `key` names an existing key. +pub fn key_exists(timeline: &Timeline, key: KeyRef) -> bool { + timeline + .track(key.0) + .is_some_and(|t| t.keys.iter().any(|k| k.time == key.1)) +} + +/// The key `key` names. +fn find_key(timeline: &Timeline, key: KeyRef) -> Option { + timeline + .track(key.0)? + .keys + .iter() + .find(|k| k.time == key.1) + .copied() +} + +/// Puts `key` on `property`, replacing a key within half a frame of it, and turns the +/// stopwatch on. +fn put_key(timeline: &mut Timeline, property: Property, key: Key) { + let half = 0.5 / f64::from(timeline.fps.max(1)); + let track = timeline.track_mut(property); + track.enabled = true; + track.keys.retain(|k| (k.time - key.time).abs() >= half); + track.set_key(key); +} + +/// How far a drag moves keys: the grabbed key (at `grab_time`) lands on the frame nearest +/// `grab_time + raw` (exactly there with `free`), and no key goes before 0 (`earliest` is +/// the earliest dragged key). +pub fn drag_delta(timeline: &Timeline, grab_time: f64, raw: f64, earliest: f64, free: bool) -> f64 { + let target = grab_time + raw; + let target = if free { target } else { snap(timeline, target) }; + (target - grab_time).max(-earliest) +} + +/// `before` with the `selected` keys moved by `delta` seconds; moved keys replace keys they +/// land on. Returns the timeline and the moved keys' new references. +pub fn move_keys(before: &Timeline, selected: &[KeyRef], delta: f64) -> (Timeline, Vec) { + let mut timeline = before.clone(); + let moving: Vec<(Property, Key)> = selected + .iter() + .filter_map(|&r| find_key(before, r).map(|k| (r.0, k))) + .collect(); + for (p, key) in &moving { + timeline.track_mut(*p).keys.retain(|k| k.time != key.time); + } + let mut moved = Vec::with_capacity(moving.len()); + for (p, key) in moving { + let time = key.time + delta; + put_key(&mut timeline, p, Key { time, ..key }); + moved.push((p, time)); + } + (timeline, moved) +} + +/// Removes the `selected` keys (tracks stay, with their stopwatches on). +pub fn delete_keys(timeline: &mut Timeline, selected: &[KeyRef]) { + for &(p, time) in selected { + if let Some(track) = timeline.tracks.iter_mut().find(|t| t.property == p) { + track.keys.retain(|k| k.time != time); + } + } +} + +/// Sets the mode of the `selected` keys. +pub fn set_interp(timeline: &mut Timeline, selected: &[KeyRef], interp: Interp) { + for &(p, time) in selected { + if let Some(track) = timeline.tracks.iter_mut().find(|t| t.property == p) { + for k in track.keys.iter_mut().filter(|k| k.time == time) { + k.interp = interp; + } + } + } +} + +/// Copied keys, with times relative to the earliest one. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct CopiedKeys { + /// The keys: property, offset in seconds, value, mode. + pub keys: Vec, +} + +/// One copied key. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct CopiedKey { + /// The property it was copied from (and is pasted onto). + pub property: Property, + /// Seconds after the earliest copied key. + pub offset: f64, + /// Its value. + pub value: Value, + /// Its mode. + pub interp: Interp, +} + +/// First line of copied keys on the clipboard, so other text is never pasted as keys. +const CLIPBOARD_HEADER: &str = "# aktis keys 1"; + +impl CopiedKeys { + /// The `selected` keys, offsets from the earliest; `None` when none exist. + pub fn copy(timeline: &Timeline, selected: &[KeyRef]) -> Option { + let keys: Vec<(Property, Key)> = selected + .iter() + .filter_map(|&r| find_key(timeline, r).map(|k| (r.0, k))) + .collect(); + let earliest = keys + .iter() + .map(|(_, k)| k.time) + .fold(f64::INFINITY, f64::min); + (!keys.is_empty()).then(|| Self { + keys: keys + .into_iter() + .map(|(property, k)| CopiedKey { + property, + offset: k.time - earliest, + value: k.value, + interp: k.interp, + }) + .collect(), + }) + } + + /// Clipboard text (TOML under [`CLIPBOARD_HEADER`]). + pub fn to_text(&self) -> String { + format!( + "{CLIPBOARD_HEADER}\n{}", + toml::to_string(self).unwrap_or_default() + ) + } + + /// Keys from clipboard text; `None` for any other text. + pub fn from_text(text: &str) -> Option { + let body = text.strip_prefix(CLIPBOARD_HEADER)?; + toml::from_str(body) + .ok() + .filter(|c: &Self| !c.keys.is_empty()) + } + + /// Pastes with the earliest key at the playhead's frame, onto the same properties + /// (stopwatches turned on, keys there replaced). Returns the pasted keys. + pub fn paste(&self, timeline: &mut Timeline, playhead: f64) -> Vec { + let start = snap(timeline, playhead); + let mut pasted = Vec::new(); + for c in &self.keys { + if c.value.kind() != c.property.kind() { + continue; + } + let time = start + c.offset; + put_key( + timeline, + c.property, + Key { + time, + value: c.value, + interp: c.interp, + }, + ); + pasted.push((c.property, time)); + } + pasted + } +} + +/// Group and name shown for a property. +pub fn label(property: Property) -> (&'static str, &'static str) { + match property { + Property::CameraPosition => ("Camera", "Position"), + Property::CameraYaw => ("Camera", "Yaw"), + Property::CameraPitch => ("Camera", "Pitch"), + Property::CameraRoll => ("Camera", "Roll"), + Property::CameraFovY => ("Camera", "FOV"), + Property::CameraExposure => ("Camera", "Exposure"), + Property::CameraLookAt => ("Camera", "Look at"), + Property::SunAzimuth => ("Sun", "Azimuth"), + Property::SunAltitude => ("Sun", "Altitude"), + Property::SunIntensity => ("Sun", "Intensity"), + Property::SunAngularDiameter => ("Sun", "Size"), + Property::SkyIntensity => ("Sky", "Intensity"), + Property::SkyTurbidity => ("Sky", "Haze"), + Property::FogDensity => ("Fog", "Density"), + Property::FogHeightFalloff => ("Fog", "Height falloff"), + Property::FogBaseHeight => ("Fog", "Base height"), + Property::FogColor => ("Fog", "Colour"), + Property::FogAnisotropy => ("Fog", "Forward scattering"), + } +} + +/// Drag speed and allowed range of a property's value field. +pub fn field_range(property: Property) -> (f64, std::ops::RangeInclusive) { + let any = f64::MIN..=f64::MAX; + match property { + Property::CameraPosition | Property::CameraLookAt | Property::FogBaseHeight => (0.1, any), + Property::CameraYaw | Property::SunAzimuth => (0.5, any), + Property::CameraRoll => (0.5, -180.0..=180.0), + Property::CameraPitch => (0.5, -90.0..=90.0), + Property::SunAltitude => (0.5, -90.0..=90.0), + Property::CameraFovY => (0.5, 1.0..=170.0), + Property::CameraExposure => (0.05, -20.0..=20.0), + Property::SunAngularDiameter => (0.05, 0.0..=90.0), + Property::SunIntensity | Property::SkyIntensity => (0.01, 0.0..=f64::MAX), + Property::SkyTurbidity => (0.05, 1.7..=10.0), + Property::FogDensity => (0.001, 0.0..=f64::MAX), + Property::FogHeightFalloff => (0.005, 0.01..=f64::MAX), + Property::FogColor => (0.005, 0.0..=1.0), + Property::FogAnisotropy => (0.01, -0.95..=0.95), + } +} + +/// `mm:ss.ff` (`ff` = frame within the second). +pub fn format_time(t: f64, fps: u32) -> String { + let fps = fps.max(1); + let frame = (t * f64::from(fps)).round().max(0.0) as u64; + let seconds = frame / u64::from(fps); + format!( + "{:02}:{:02}.{:02}", + seconds / 60, + seconds % 60, + frame % u64::from(fps) + ) +} + +#[cfg(test)] +mod tests; diff --git a/crates/aktis-app/src/animate/tests.rs b/crates/aktis-app/src/animate/tests.rs new file mode 100644 index 0000000..4b307cf --- /dev/null +++ b/crates/aktis-app/src/animate/tests.rs @@ -0,0 +1,363 @@ +use super::*; + +fn keyed(timeline: &Timeline, p: Property) -> Vec<(f64, Value)> { + timeline + .track(p) + .map(|t| t.keys.iter().map(|k| (k.time, k.value)).collect()) + .unwrap_or_default() +} + +#[test] +fn edits_key_with_the_stopwatch_on_and_change_the_base_otherwise() { + let mut tl = Timeline::default(); + let mut base = Scene::default(); + stopwatch_on(&mut tl, Property::SunAltitude, &base, 0.0); + let t = 1.0 + 0.4 / 30.0; // between frames: snapped to frame 30 + let before = shown_scene(&tl, &base, t, &CameraOverride::default()); + let mut after = before.clone(); + after.sun.altitude = 12.0; + after.fog.density = 0.05; + assert!(route_edit(&mut tl, &mut base, &before, &after, t)); + assert_eq!( + keyed(&tl, Property::SunAltitude), + [(0.0, Value::Scalar(45.0)), (1.0, Value::Scalar(12.0))], + "auto-key at the playhead's frame" + ); + assert_eq!( + base.sun.altitude, 45.0, + "a keyed value leaves the base alone" + ); + assert_eq!(base.fog.density, 0.05, "no stopwatch: the base changes"); + assert!(tl.track(Property::FogDensity).is_none()); + // Nothing changed: nothing happens. + let same = shown_scene(&tl, &base, t, &CameraOverride::default()); + assert!(!route_edit(&mut tl, &mut base, &same, &same.clone(), t)); +} + +#[test] +fn an_enabled_track_without_keys_still_auto_keys() { + let mut tl = Timeline::default(); + let mut base = Scene::default(); + tl.track_mut(Property::CameraRoll); // stopwatch on, no keys (e.g. last key removed) + let before = base.clone(); + let mut after = before.clone(); + after.camera.roll = 10.0; + route_edit(&mut tl, &mut base, &before, &after, 2.0); + assert_eq!( + keyed(&tl, Property::CameraRoll), + [(2.0, Value::Scalar(10.0))] + ); + assert_eq!(base.camera.roll, 0.0); +} + +#[test] +fn a_disabled_track_edits_the_base() { + let mut tl = Timeline::default(); + let mut base = Scene::default(); + set_key(&mut tl, Property::SkyTurbidity, 0.0, Value::Scalar(6.0)); + tl.track_mut(Property::SkyTurbidity).enabled = false; + let before = base.clone(); + let mut after = before.clone(); + after.sky.turbidity = 4.0; + assert!(!route_edit(&mut tl, &mut base, &before, &after, 0.0)); + assert_eq!(base.sky.turbidity, 4.0); +} + +#[test] +fn rekeying_keeps_the_mode() { + let mut tl = Timeline::default(); + set_key(&mut tl, Property::SunIntensity, 1.0, Value::Scalar(1.0)); + tl.track_mut(Property::SunIntensity).keys[0].interp = Interp::Ease; + set_key(&mut tl, Property::SunIntensity, 1.01, Value::Scalar(2.0)); + let track = tl.track(Property::SunIntensity).unwrap(); + assert_eq!(track.keys.len(), 1); + assert_eq!( + (track.keys[0].value, track.keys[0].interp), + (Value::Scalar(2.0), Interp::Ease) + ); +} + +#[test] +fn the_fly_camera_never_keys() { + let mut tl = Timeline::default(); + let mut base = Scene::default(); + let mut ov = CameraOverride::default(); + // No camera tracks: flying edits the base, as before the timeline. + let evaluated = tl.scene_at(&base, 0.0).camera; + let mut flown = evaluated.clone(); + flown.position.x += 3.0; + flown.yaw = 40.0; + apply_fly(&tl, &mut base, &mut ov, &evaluated, &flown); + assert_eq!((base.camera.position.x, base.camera.yaw), (3.0, 40.0)); + assert!(ov.is_empty()); + + // Position keyed: its move goes to the override; yaw (not keyed) to the base. + set_key( + &mut tl, + Property::CameraPosition, + 0.0, + Value::Vec3(Vec3::new(0.0, 80.0, 0.0)), + ); + let evaluated = tl.scene_at(&base, 0.0).camera; + let mut flown = evaluated.clone(); + flown.position.z += 5.0; + flown.yaw = 50.0; + apply_fly(&tl, &mut base, &mut ov, &evaluated, &flown); + assert_eq!(ov.position, Some(Vec3::new(0.0, 80.0, 5.0))); + assert_eq!((ov.yaw, base.camera.yaw), (None, 50.0)); + assert_eq!(keyed(&tl, Property::CameraPosition).len(), 1, "no new key"); + let shown = shown_scene(&tl, &base, 0.0, &ov); + assert_eq!(shown.camera.position, Vec3::new(0.0, 80.0, 5.0)); + // Flying back onto the timeline clears the override. + let back = tl.scene_at(&base, 0.0).camera; + apply_fly(&tl, &mut base, &mut ov, &back, &back.clone()); + assert!(ov.is_empty()); + assert_eq!(base.camera.yaw, 50.0); + + // Look at keyed: turning goes to the override. + set_key( + &mut tl, + Property::CameraLookAt, + 0.0, + Value::Vec3(Vec3::new(10.0, 64.0, 10.0)), + ); + assert_eq!(camera_animated(&tl), (true, true, true)); + let evaluated = tl.scene_at(&base, 0.0).camera; + let mut flown = evaluated.clone(); + flown.yaw += 15.0; + apply_fly(&tl, &mut base, &mut ov, &evaluated, &flown); + assert_eq!(ov.yaw, Some(evaluated.yaw + 15.0)); + assert_eq!(base.camera.yaw, 50.0); +} + +#[test] +fn key_camera_keys_position_yaw_and_pitch() { + let mut tl = Timeline::default(); + let mut ov = CameraOverride { + position: Some(Vec3::ONE), + ..CameraOverride::default() + }; + let cam = Camera { + position: Vec3::new(1.0, 2.0, 3.0), + yaw: 33.0, + pitch: -12.0, + ..Camera::default() + }; + key_camera(&mut tl, &mut ov, &cam, 2.0); + assert!(ov.is_empty()); + assert_eq!( + keyed(&tl, Property::CameraPosition), + [(2.0, Value::Vec3(cam.position))] + ); + assert_eq!( + keyed(&tl, Property::CameraYaw), + [(2.0, Value::Scalar(33.0))] + ); + assert_eq!( + keyed(&tl, Property::CameraPitch), + [(2.0, Value::Scalar(-12.0))] + ); + for p in [ + Property::CameraPosition, + Property::CameraYaw, + Property::CameraPitch, + ] { + assert!(tl.track(p).unwrap().enabled, "stopwatch turned on"); + } + // With Look at on, only the position is keyed. + let mut tl = Timeline::default(); + set_key( + &mut tl, + Property::CameraLookAt, + 0.0, + Value::Vec3(Vec3::ZERO), + ); + key_camera(&mut tl, &mut ov, &cam, 1.0); + assert_eq!(keyed(&tl, Property::CameraPosition).len(), 1); + assert!(tl.track(Property::CameraYaw).is_none() && tl.track(Property::CameraPitch).is_none()); +} + +#[test] +fn stopwatches() { + let mut tl = Timeline::default(); + let mut base = Scene::default(); + let shown = base.clone(); + stopwatch_on(&mut tl, Property::FogDensity, &shown, 3.0); + assert_eq!( + keyed(&tl, Property::FogDensity), + [(3.0, Value::Scalar(0.0))] + ); + // On again with keys (a disabled track from a file): keys kept, none added. + tl.track_mut(Property::FogDensity).enabled = false; + stopwatch_on(&mut tl, Property::FogDensity, &shown, 5.0); + assert_eq!(keyed(&tl, Property::FogDensity).len(), 1); + // Look at starts 16 blocks ahead of the camera. + stopwatch_on(&mut tl, Property::CameraLookAt, &shown, 0.0); + let ahead = shown.camera.position + shown.camera.forward() * LOOK_AT_START_DISTANCE; + assert_eq!( + keyed(&tl, Property::CameraLookAt), + [(0.0, Value::Vec3(ahead))] + ); + // Off: the track goes, the shown value becomes the base. + let mut shown = shown; + shown.fog.density = 0.07; + stopwatch_off(&mut tl, &mut base, Property::FogDensity, &shown); + assert!(tl.track(Property::FogDensity).is_none()); + assert_eq!(base.fog.density, 0.07); + stopwatch_off(&mut tl, &mut base, Property::CameraLookAt, &shown); + assert!(tl.track(Property::CameraLookAt).is_none()); +} + +#[test] +fn key_navigation_and_toggle() { + let mut tl = Timeline::default(); + let shown = Scene::default(); + for t in [1.0, 2.0, 4.0] { + set_key(&mut tl, Property::SunAzimuth, t, Value::Scalar(t as f32)); + } + let p = Property::SunAzimuth; + assert_eq!(previous_key(&tl, p, 2.0), Some(1.0)); + assert_eq!(next_key(&tl, p, 2.0), Some(4.0)); + assert_eq!(previous_key(&tl, p, 1.0), None); + assert_eq!(next_key(&tl, p, 4.0), None); + assert_eq!( + next_key(&tl, p, 2.01), + Some(4.0), + "within half a frame counts as here" + ); + assert_eq!(key_here(&tl, p, 2.01), Some(1)); + toggle_key_here(&mut tl, p, &shown, 2.0); + assert_eq!(keyed(&tl, p).len(), 2, "removed"); + toggle_key_here(&mut tl, p, &shown, 3.0); + assert_eq!( + keyed(&tl, p)[1], + (3.0, Value::Scalar(shown.sun.azimuth)), + "added" + ); +} + +#[test] +fn time_format_and_snapping() { + assert_eq!(format_time(0.0, 30), "00:00.00"); + assert_eq!(format_time(61.5, 30), "01:01.15"); + assert_eq!(format_time(2.0 - 1.0 / 24.0, 24), "00:01.23"); + let tl = Timeline::default(); + assert_eq!(snap(&tl, 1.01), 1.0); + assert_eq!(snap(&tl, 1.02), 31.0 / 30.0); +} + +// ---- Key editing ---- + +fn three_keys() -> Timeline { + let mut tl = Timeline::default(); + for (t, v) in [(1.0, 10.0), (2.0, 20.0), (3.0, 30.0)] { + set_key(&mut tl, Property::SunAltitude, t, Value::Scalar(v)); + } + set_key(&mut tl, Property::CameraRoll, 2.0, Value::Scalar(5.0)); + tl +} + +#[test] +fn drags_snap_to_frames_unless_free_and_stop_at_zero() { + let tl = Timeline::default(); // 30 fps + // Grabbed key at 1.0 s dragged 0.51 s: lands on frame 45 (1.5 s), not 1.51 s. + assert!((drag_delta(&tl, 1.0, 0.51, 1.0, false) - 0.5).abs() < 1e-9); + // A grabbed key that is off a frame snaps onto one. + let d = drag_delta(&tl, 1.01, 0.0, 1.01, false); + assert!((1.01 + d - 1.0).abs() < 1e-9, "{d}"); + // Alt: exactly where the pointer is. + assert_eq!(drag_delta(&tl, 1.0, 0.51, 1.0, true), 0.51); + // Never before 0: the earliest key stops there. + assert_eq!(drag_delta(&tl, 2.0, -5.0, 0.5, false), -0.5); +} + +#[test] +fn moving_keys_keeps_their_values_and_replaces_what_they_land_on() { + let tl = three_keys(); + let sel = [(Property::SunAltitude, 1.0), (Property::CameraRoll, 2.0)]; + let (moved, refs) = move_keys(&tl, &sel, 1.0); + assert_eq!( + refs, + [(Property::SunAltitude, 2.0), (Property::CameraRoll, 3.0)] + ); + // Altitude: the key from 1.0 replaced the one at 2.0. + assert_eq!( + keyed(&moved, Property::SunAltitude), + [(2.0, Value::Scalar(10.0)), (3.0, Value::Scalar(30.0))] + ); + assert_eq!( + keyed(&moved, Property::CameraRoll), + [(3.0, Value::Scalar(5.0))] + ); + // The original is untouched (drags rebuild from it every frame). + assert_eq!(keyed(&tl, Property::SunAltitude).len(), 3); + // Moving by 0 changes nothing. + assert_eq!(move_keys(&tl, &sel, 0.0).0, tl); +} + +#[test] +fn delete_and_mode_change() { + let mut tl = three_keys(); + set_interp(&mut tl, &[(Property::SunAltitude, 2.0)], Interp::Step); + assert_eq!( + tl.track(Property::SunAltitude).unwrap().keys[1].interp, + Interp::Step + ); + delete_keys( + &mut tl, + &[(Property::SunAltitude, 2.0), (Property::CameraRoll, 2.0)], + ); + assert_eq!(keyed(&tl, Property::SunAltitude).len(), 2); + let roll = tl.track(Property::CameraRoll).unwrap(); + assert!( + roll.keys.is_empty() && roll.enabled, + "track and stopwatch stay" + ); + assert!(key_exists(&tl, (Property::SunAltitude, 3.0))); + assert!(!key_exists(&tl, (Property::SunAltitude, 2.0))); +} + +#[test] +fn paste_puts_the_earliest_key_at_the_playhead() { + let mut tl = three_keys(); + tl.track_mut(Property::SunAltitude).keys[2].interp = Interp::Ease; + let copied = CopiedKeys::copy( + &tl, + &[ + (Property::SunAltitude, 3.0), + (Property::SunAltitude, 2.0), + (Property::CameraRoll, 2.0), + ], + ) + .unwrap(); + // Through the clipboard text, as Cmd-C / Cmd-V do. + let text = copied.to_text(); + let copied = CopiedKeys::from_text(&text).unwrap(); + // Playhead between frames: pasted from the nearest frame (5.0 s). + let pasted = copied.paste(&mut tl, 5.01); + assert_eq!(pasted.len(), 3); + assert!(pasted.contains(&(Property::SunAltitude, 5.0))); + assert!( + pasted.contains(&(Property::SunAltitude, 6.0)), + "offset kept" + ); + assert!( + pasted.contains(&(Property::CameraRoll, 5.0)), + "same property" + ); + let alt = tl.track(Property::SunAltitude).unwrap(); + assert_eq!(alt.keys.len(), 5); + assert_eq!( + (alt.keys[4].time, alt.keys[4].value), + (6.0, Value::Scalar(30.0)) + ); + assert_eq!(alt.keys[4].interp, Interp::Ease, "mode kept"); + // Pasting onto a property without a track turns its stopwatch on. + let mut empty = Timeline::default(); + copied.paste(&mut empty, 0.0); + assert!(empty.track(Property::CameraRoll).unwrap().enabled); + // Other text isn't keys; nothing selected copies nothing. + assert!(CopiedKeys::from_text("hello").is_none()); + assert!(CopiedKeys::from_text("# aktis keys 1\nkeys = []\n").is_none()); + assert!(CopiedKeys::copy(&tl, &[(Property::FogDensity, 1.0)]).is_none()); +} diff --git a/crates/aktis-app/src/app.rs b/crates/aktis-app/src/app.rs new file mode 100644 index 0000000..5954908 --- /dev/null +++ b/crates/aktis-app/src/app.rs @@ -0,0 +1,3641 @@ +//! Top-level application state and layout: project panel on the left, render and scene +//! settings on the right, viewport in the centre. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use aktis_pt::{PathTracer, PtView}; +use aktis_render::preview::PreviewRenderer; +use aktis_render::{GpuContext, RenderEngine}; +use aktis_scene::timeline::Timeline; +use aktis_scene::{Camera, Scene}; +use anyhow::Context; +use eframe::egui_wgpu; +use glam::Vec3; +use serde::{Deserialize, Serialize}; + +use crate::animate::{self, CameraOverride}; +use crate::budget::{Budget, Fitted}; +use crate::cli::Args; +use crate::denoising::{self, DenoiseSettings, Denoising}; +use crate::ffmpeg::{self, Encoder, Ffmpeg}; +use crate::fly::{FlyCamera, MoveKeys}; +use crate::history::History; +use crate::job::{JobKind, JobStatus, JobTarget}; +use crate::job_runner::{JobEngines, JobRunner}; +use crate::loader::{ + LoadPoll, LoadRequest, LoadStage, LoadTask, LoadedWorld, MeshTask, Residency, Reuse, + residency_plan, +}; +use crate::orbit::Orbit; +use crate::output::{self, OutputFormat, OutputSettings, RenderSize}; +use crate::playback::{self, Playback}; +use crate::project::{PanelAction, ProjectPanel, ProjectSettings, SelectionSettings, Shown}; +use crate::project_file::{ + self, EngineChoice, EngineSection, PacksSection, ProjectFile, WorldSection, +}; +use crate::pt_panel::{self, ProgressClock, SavedPtSettings}; +use crate::queue::{self, NewJob, QueueStatus, RenderQueue}; +use crate::shader_pack::{self, PackWorld, SavedShaderPacks, ShaderPackChoice, ShaderPacks}; +use crate::timeline_panel::{self, PanelState}; +use crate::viewport::{Engines, FrameKey, Source, Viewport, frame_guide, pixel_size}; +use aktis_render::catch_out_of_memory; + +/// eframe storage key for [`Saved`]. +const STORAGE_KEY: &str = "aktis"; + +/// File menu shortcuts. +const SHORTCUT_NEW: egui::KeyboardShortcut = + egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::N); +const SHORTCUT_OPEN: egui::KeyboardShortcut = + egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::O); +const SHORTCUT_SAVE: egui::KeyboardShortcut = + egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::S); +const SHORTCUT_SAVE_AS: egui::KeyboardShortcut = egui::KeyboardShortcut::new( + egui::Modifiers::COMMAND.plus(egui::Modifiers::SHIFT), + egui::Key::S, +); + +/// Edit menu shortcuts. +const SHORTCUT_UNDO: egui::KeyboardShortcut = + egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::Z); +const SHORTCUT_REDO: egui::KeyboardShortcut = egui::KeyboardShortcut::new( + egui::Modifiers::COMMAND.plus(egui::Modifiers::SHIFT), + egui::Key::Z, +); + +/// A File menu action that replaces the project, so it asks about unsaved changes first. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ReplaceProject { + New, + Open, + /// Open a queued job's snapshot as an untitled project. + Job(u64), +} + +/// An animation job waiting for "frames already there: Replace / Keep / Cancel". +struct PendingAdd { + project: ProjectFile, + name: String, + kind: JobKind, + frame: u32, + target: JobTarget, + video: Option, + existing: usize, +} + +/// State kept between runs (eframe storage). +#[derive(Debug, Default, Serialize, Deserialize)] +#[serde(default)] +struct Saved { + project: ProjectSettings, + scene: Scene, + speed: Option, + engine: EngineChoice, + path_tracer: SavedPtSettings, + denoise: DenoiseSettings, + shader_packs: SavedShaderPacks, + /// The timeline being edited (also in the project file). + timeline: Timeline, + /// Output settings (also in the project file). + output: OutputSettings, + /// The open project file; `None` = untitled. + project_path: Option, + /// The open project's world when it couldn't be loaded (see `AktisApp::world_override`). + world_override: Option<(WorldSection, PacksSection)>, + /// Playhead time in seconds. + playhead: f64, + /// Bottom panel: open, tab, collapsed groups, zoom. + timeline_panel: PanelState, + /// What size the viewport renders at. + render_size: RenderSize, + /// The render queue. + queue: RenderQueue, + /// The ffmpeg chosen with "Choose…"; `None` = search automatically. + ffmpeg_path: Option, +} + +/// Summary of the uploaded world, for the project panel. +struct WorldInfo { + name: String, + /// Radius loaded (lower than the request's when the memory budget lowered it). + radius: i32, + /// What the memory budget did on this load. + fitted: Option, + /// The centre came from re-centring (M8 task 9), so it may move again. + auto_centre: bool, + /// Far-terrain quads in the preview, while they're on the GPU. + far_quads: Option, + /// Quads of the meshed world (`None` until a mesh was built for an engine). + quads: Option, + /// Preview draws per frame and GPU memory, while its geometry is on the GPU. + preview: Option<(u64, f64)>, + /// Path-tracer GPU memory, while its data is on the GPU. + pt_mib: Option, + /// The path tracer couldn't hold this world (not retried until the next load). + pt_failed: bool, + /// Which engines' geometry is on the GPU. + resident: Residency, + /// Resource packs on top of the jar. + packs: usize, + /// Problems with resource packs, shown under the stats. + pack_warnings: Vec, + load_seconds: f32, + /// Loaded from the project panel (not the command line), so it is reopened next run. + from_panel: bool, + /// What was loaded (the packs panel compares and reuses it for Apply). + request: LoadRequest, + /// The world's blocks, kept so Apply skips reading chunks. + blocks: Reuse, + /// This load reused the previous load's blocks. + reused: bool, + /// Texture array: layers, layer size, size without the cap, layers scaled down, bytes. + textures: TextureInfo, + /// What the shader-pack engine builds its geometry from. + pack_world: Arc, +} + +/// Summary of a world's texture array. +#[derive(Debug, Clone, Copy)] +struct TextureInfo { + layers: u32, + size: u32, + natural_size: u32, + downscaled: u32, + bytes: u64, + /// Layers with a LabPBR normal / specular map. + pbr: (u32, u32), +} + +impl TextureInfo { + fn of(t: &aktis_assets::TextureArray) -> Self { + Self { + layers: t.layer_count(), + size: t.size(), + natural_size: t.natural_size(), + downscaled: t.downscaled(), + bytes: t.bytes(), + pbr: t.pbr_layer_counts(), + } + } + + /// "1250 × 128 px · 104 MiB", plus LabPBR map counts and "(37 scaled down from up to + /// 512 px)" when they apply. Memory includes the PBR maps. + fn label(&self) -> String { + let mut s = format!( + "{} × {} px · {:.0} MiB", + self.layers, + self.size, + self.bytes as f64 / 1048576.0 + ); + if self.pbr != (0, 0) { + s.push_str(&format!( + ", LabPBR: {} normal, {} specular maps", + self.pbr.0, self.pbr.1 + )); + } + if self.downscaled > 0 { + s.push_str(&format!( + " ({} scaled down from up to {} px)", + self.downscaled, self.natural_size + )); + } + s + } +} + +/// A load in progress and what to do when it finishes. +struct PendingLoad { + task: LoadTask, + request: LoadRequest, + from_panel: bool, + /// Started by re-centring (M8 task 9): the centre follows the camera, not the user. + recentre: bool, + /// Camera to restore instead of the default placement (reopening the last session). + camera: Option, +} + +/// Smoothed frame rate, measured only while the viewport redraws continuously. +#[derive(Default)] +struct FrameRate { + /// Exponential moving average of the frame time in seconds; `None` when idle. + avg_dt: Option, +} + +impl FrameRate { + fn update(&mut self, active: bool, dt: f32) { + self.avg_dt = match (active, self.avg_dt) { + (false, _) => None, + (true, None) => Some(dt), + (true, Some(avg)) => Some(avg + (dt - avg) * 0.1), + }; + } + + fn label(&self) -> String { + match self.avg_dt { + Some(dt) if dt > 0.0 => format!("{:.0} FPS ({:.1} ms)", 1.0 / dt, dt * 1000.0), + _ => "idle".to_owned(), + } + } +} + +/// Top-level application state. +pub struct AktisApp { + scene: Scene, + fly: FlyCamera, + project: ProjectPanel, + egui_ctx: egui::Context, + render_state: egui_wgpu::RenderState, + gpu: GpuContext, + preview: PreviewRenderer, + path_tracer: PathTracer, + engine: EngineChoice, + /// The shader-pack engine and its background build. + shader_packs: ShaderPacks, + /// Shader-pack choices per instance (saved). + shader_pack_choices: SavedShaderPacks, + /// The chosen instance's `shaderpacks/` contents and the game folder they belong to + /// (`None` = list it again). + shader_packs_found: Option<(PathBuf, Option>)>, + /// `--shaderpack`: the pack for this run (not saved), and the engine to save instead. + shader_pack_override: Option<(PathBuf, EngineChoice)>, + viewport: Viewport, + /// Bumped whenever the preview's world changes. + world_version: u64, + world: Option, + load: Option, + /// Geometry being built for an engine chosen after the load (ADR 0020). + mesh_task: Option, + /// Last load or render error, shown in the viewport. + error: Option, + frame_rate: FrameRate, + /// Where a right-drag look started (points); the cursor is held there while it lasts. + look_anchor: Option, + /// Result of the last "Save PNG…": the file written, or an error message. + export_status: Option>, + /// The path tracer is paused (keeps its image, adds no samples). + pt_paused: bool, + /// Render time of the path tracer's current image. + pt_clock: ProgressClock, + /// Denoise settings (shown only in builds with OIDN). + denoise_settings: DenoiseSettings, + /// The denoiser worker and its latest result. + denoising: Denoising, + /// The keyframe timeline (M7; edited from task 5 on). + timeline: Timeline, + /// Output resolution, format and destination (M7; used from task 8 on). + output: OutputSettings, + /// The open project file; `None` = untitled. + project_path: Option, + /// What the open project file holds (as last opened or saved), to tell whether there + /// are unsaved changes; `None` for an untitled project. + project_baseline: Option, + /// The project's world and packs when they couldn't be loaded: Save writes these + /// instead of the world on screen until the user loads a world. + world_override: Option<(WorldSection, PacksSection)>, + /// Messages about the open project (missing world, read or write errors); `true` = + /// error. Shown under the menu bar until dismissed. + project_notes: Vec<(bool, String)>, + /// New/Open waiting for the "Save changes?" answer. + confirm: Option, + /// The window title last sent. + title: String, + /// Playhead time in seconds (on a frame); the scene shown is the timeline here. + playhead: f64, + /// The fly camera's moves of animated camera values ("Camera not keyed"). + camera_override: CameraOverride, + /// Bottom panel state. + timeline_panel: PanelState, + /// What size the viewport renders at (saved with the app). + render_size: RenderSize, + /// Undo/redo of the base scene and the timeline (not saved). + history: History, + /// Timeline playback. + playback: Playback, + /// When playback last advanced (`None` while paused). + last_tick: Option, + /// The Orbit dialog's values while it is open. + orbit_dialog: Option, + /// The render queue (saved with the app). + queue: RenderQueue, + /// Start was pressed and the queue hasn't stopped. + queue_running: bool, + /// The chunk a re-centring load failed at (not retried until the camera moves on). + recentre_failed: Option<(i32, i32)>, + /// The queue's current job (preparing or rendering). + queue_job: Option, + /// The runner of the current job once it renders. + job: Option, + /// The world load the queue started for its job. + queue_loading: Option, + /// The current job's shader pack (built instead of the editor's while the queue runs). + queue_pack: Option, + /// The current job's engine: its geometry is kept on the GPU while the queue prepares + /// or renders it, whichever engine the viewport shows (ADR 0020). + queue_engine: Option, + /// The editor's world when Start was pressed (loaded back when the queue stops). + editor_world: Option, + /// An animation job waiting for Replace / Keep / Cancel. + queue_add: Option, + /// "Stop rendering and quit?" is open. + quit_confirm: bool, + /// Quit was confirmed: let the window close. + allow_close: bool, + /// The ffmpeg chosen with "Choose…" (saved); `None` = search. + ffmpeg_choice: Option, + /// The ffmpeg in use, or why there is none. + ffmpeg: Result, + /// The running encode and its job. + encoder: Option<(u64, Encoder)>, +} + +/// Cursor grab while looking around. winit can lock the cursor in place on macOS; Windows +/// (and X11) only support confining it to the window, so there the cursor is put back where +/// the drag started when it ends. +const LOOK_GRAB: egui::CursorGrab = if cfg!(target_os = "macos") { + egui::CursorGrab::Locked +} else { + egui::CursorGrab::Confined +}; + +impl AktisApp { + /// Creates the app on eframe's wgpu device, restores saved choices and starts loading: + /// the world from `args` if given, else the last session's world. + pub fn new(cc: &eframe::CreationContext<'_>, args: Args) -> anyhow::Result { + let render_state = cc + .wgpu_render_state + .clone() + .context("Aktis needs eframe's wgpu renderer")?; + let gpu = GpuContext { + device: render_state.device.clone(), + queue: render_state.queue.clone(), + }; + let saved: Saved = cc + .storage + .and_then(|s| eframe::get_value(s, STORAGE_KEY)) + .unwrap_or_default(); + let preview = PreviewRenderer::new(&gpu); + let history = History::new(&saved.scene, &saved.timeline); + let mut path_tracer = PathTracer::new(&gpu); + path_tracer.settings = saved.path_tracer.to_settings(); + let mut app = Self { + scene: saved.scene, + fly: FlyCamera { + speed: saved.speed.unwrap_or(FlyCamera::default().speed), + }, + project: ProjectPanel::new(saved.project), + egui_ctx: cc.egui_ctx.clone(), + render_state, + gpu, + preview, + path_tracer, + engine: saved.engine, + shader_packs: ShaderPacks::default(), + shader_pack_choices: saved.shader_packs, + shader_packs_found: None, + shader_pack_override: None, + viewport: Viewport::default(), + world_version: 0, + world: None, + load: None, + mesh_task: None, + error: None, + frame_rate: FrameRate::default(), + look_anchor: None, + export_status: None, + pt_paused: false, + pt_clock: ProgressClock::default(), + denoise_settings: saved.denoise, + denoising: Denoising::default(), + timeline: saved.timeline, + output: saved.output, + project_baseline: None, + project_path: saved.project_path, + world_override: saved.world_override, + project_notes: Vec::new(), + confirm: None, + title: String::new(), + playhead: saved.playhead, + camera_override: CameraOverride::default(), + timeline_panel: saved.timeline_panel, + render_size: saved.render_size, + history, + playback: Playback::default(), + last_tick: None, + orbit_dialog: None, + queue: saved.queue.restored(), + queue_running: false, + recentre_failed: None, + queue_job: None, + job: None, + queue_loading: None, + queue_pack: None, + queue_engine: None, + editor_world: None, + queue_add: None, + quit_confirm: false, + allow_close: false, + ffmpeg: ffmpeg::find(saved.ffmpeg_path.as_deref()), + ffmpeg_choice: saved.ffmpeg_path, + encoder: None, + }; + match &app.ffmpeg { + Ok(f) => log::info!("ffmpeg {} at {}", f.version, f.path.display()), + Err(e) => log::info!("video encoding unavailable: {e}"), + } + app.playhead = animate::snap( + &app.timeline, + app.playhead.clamp(0.0, app.timeline.duration), + ); + // Compare the restored session with the file on disk (the session may hold unsaved + // changes from the last run). + if let Some(path) = &app.project_path { + match ProjectFile::read(path) { + Ok(file) => app.project_baseline = Some(file), + Err(e) => { + log::warn!("last project: {e:#}"); + app.project_notes.push(( + false, + format!( + "The project file can't be read any more ({e:#}); Save writes it again." + ), + )); + } + } + } + if let Some(pack) = args.shaderpack { + app.shader_pack_override = Some((pack, app.engine)); + app.engine = EngineChoice::ShaderPack; + } + let sel = app.project.settings.selection.normalized(); + if let (Some(jar), Some(world)) = (args.jar, args.world) { + let request = LoadRequest { + jar, + packs: args.packs, + max_texture_size: aktis_assets::clamp_texture_size_cap( + app.project.settings.max_texture_size, + ), + world, + radius: args.radius, + far_radius: args.far_radius.unwrap_or(sel.far_radius), + center: args.center, + min_y: sel.min_y, + max_y: sel.max_y, + memory_budget_gb: args.memory_budget_gb.unwrap_or(sel.memory_budget_gb), + }; + app.start_load(request, false, None, None); + } else if app.project.settings.reopen { + match app.project.settings.request(app.project.instances()) { + Some(request) => { + let camera = Some(app.scene.camera.clone()); + app.start_load(request, true, camera, None); + } + None => log::info!("last world is no longer available; not reopening it"), + } + } + Ok(app) + } + + /// Starts a background load. `camera` is kept instead of the default placement; `reuse` + /// skips reading chunks (only for a request with the same blocks). + fn start_load( + &mut self, + request: LoadRequest, + from_panel: bool, + camera: Option, + reuse: Option, + ) { + log::info!( + "loading {} (radius {}, y {}..{}, {} packs{})", + request.world.display(), + request.radius, + request.min_y, + request.max_y, + request.packs.len(), + if reuse.is_some() { + ", reusing blocks" + } else { + "" + } + ); + let ctx = self.egui_ctx.clone(); + self.error = None; + // Replacing a running load drops (cancels) it. + self.load = Some(PendingLoad { + task: LoadTask::spawn( + request.clone(), + reuse, + self.wanted_residency(), + Some(Budget::new(request.memory_budget_gb, self.engines_in_use())), + move || ctx.request_repaint(), + ), + request, + from_panel, + recentre: false, + camera, + }); + } + + /// Re-centring (M8 task 9, far-terrain.md → "Re-centring"): when the camera is more than + /// half the detail radius (at least 2 chunks) from the detail area's centre, loads a new + /// detail area (and far terrain) around it in the background, keeping the camera; the + /// old world stays on screen until the new one is in. Not while loading, playing back + /// or rendering jobs, and not when the user chose the centre. + fn maybe_recentre(&mut self) { + let Some(w) = &self.world else { return }; + let auto_centre = w.request.center.is_none() || w.auto_centre; + if !auto_centre + || self.load.is_some() + || self.queue_running + || self.job_active() + || self.playback.is_playing() + { + return; + } + let camera = self.shown_scene().camera; + let Some(target) = + crate::loader::recentre_target(camera.position, w.blocks.center, w.radius) + else { + return; + }; + let chunk = (target.0.div_euclid(16), target.1.div_euclid(16)); + if self.recentre_failed == Some(chunk) { + return; + } + let request = LoadRequest { + center: Some(target), + ..w.request.clone() + }; + log::info!( + "re-centring the detail area on {}, {} (camera left it)", + target.0, + target.1 + ); + let from_panel = w.from_panel; + let error = self.error.take(); + self.start_load(request, from_panel, Some(camera), None); + self.error = error; + if let Some(l) = &mut self.load { + l.recentre = true; + } + } + + fn poll_load(&mut self) { + let Some(pending) = &mut self.load else { + return; + }; + if let LoadPoll::Finished(result) = pending.task.poll() { + let pending = self.load.take().expect("load is running"); + match result { + Ok(w) => { + self.recentre_failed = None; + self.install_world(*w, &pending); + } + Err(e) => { + if pending.recentre + && let Some((x, z)) = pending.request.center + { + // Don't retry the same place every frame. + self.recentre_failed = Some((x.div_euclid(16), z.div_euclid(16))); + } + self.error = Some(format!("{e:#}")); + } + } + } + } + + fn install_world(&mut self, w: LoadedWorld, pending: &PendingLoad) { + // The previous world's geometry goes first, so both are never on the GPU together. + self.mesh_task = None; + self.preview.clear_world(); + self.path_tracer.clear_world(); + self.shader_packs.release_world(); + let pack_world = Arc::new(PackWorld { + grid: Arc::clone(&w.grid), + entities: Arc::clone(&w.entities), + assets: w.assets, + celestial: w.celestial, + render_distance: (w.radius as f32 + 0.5) * 16.0, + far: w.far.clone(), + }); + if let Some(camera) = &pending.camera { + self.scene.camera = camera.clone(); + } else { + self.scene.camera = overview_camera(w.center.as_vec3(), &self.scene.camera); + } + log::info!("world '{}' loaded in {:.1} s", w.name, w.seconds); + self.world = Some(WorldInfo { + blocks: Reuse { + name: w.name.clone(), + center: w.center, + grid: w.grid, + entities: w.entities, + radius: w.radius, + fitted: w.fitted.clone(), + far: w.far.clone(), + }, + reused: w.reused, + fitted: w.fitted, + textures: TextureInfo::of(pack_world.assets.textures()), + pack_world, + name: w.name, + radius: w.radius, + auto_centre: pending.recentre, + far_quads: None, + quads: None, + preview: None, + pt_mib: None, + pt_failed: false, + resident: Residency::default(), + packs: w.packs_used, + pack_warnings: w.pack_warnings, + load_seconds: w.seconds, + from_panel: pending.from_panel, + request: pending.request.clone(), + }); + self.world_version += 1; + self.error = None; + if let Some(mesh) = w.mesh { + let wanted = Residency { + preview: true, + path_tracer: w.quad_grid.is_some(), + }; + self.upload_geometry( + wanted, + &mesh, + w.quad_grid.as_ref(), + (w.far_mesh.as_ref(), w.far_field.as_ref()), + ); + } + } + + /// The geometry the viewport's engine and the queue's current job need (ADR 0020). + fn wanted_residency(&self) -> Residency { + self.engines_in_use() + .into_iter() + .map(Residency::for_engine) + .fold(Residency::default(), Residency::union) + } + + /// The engines in use: the viewport's and the queue's current job's (the memory budget + /// sizes a load for the costliest). + fn engines_in_use(&self) -> Vec { + let job = self + .job + .as_ref() + .map(|j| j.spec().engine) + .or(self.queue_engine); + std::iter::once(self.engine).chain(job).collect() + } + + /// Whether `engine`'s geometry for the world on screen is on the GPU (shader packs are + /// checked by the queue with `ShaderPacks::ready_for`). + fn engine_resident(&self, engine: EngineChoice) -> bool { + let need = Residency::for_engine(engine); + self.world.as_ref().is_some_and(|w| { + // Asking only for `need` frees nothing that matters here; only the build counts. + residency_plan(need, w.resident, w.pt_failed).1.is_empty() + }) + } + + /// Uploads freshly built geometry for `wanted` and records what is on the GPU. + fn upload_geometry( + &mut self, + wanted: Residency, + mesh: &aktis_render::mesh::WorldMesh, + quad_grid: Option<&aktis_pt::accel::QuadGrid>, + (far_mesh, far_field): ( + Option<&aktis_render::lod::FarMesh>, + Option<&aktis_pt::far::FarField>, + ), + ) { + let Some(w) = &mut self.world else { + return; + }; + w.quads = Some(mesh.stats.quads as u64); + let textures = w.pack_world.assets.textures(); + // Uploads run in an out-of-memory error scope: a GPU that can't hold the world + // disables that engine with a message instead of ending the app (ADR 0020). + let device = &self.gpu.device; + if wanted.preview { + match catch_out_of_memory(device, || { + self.preview.upload_world(&self.gpu, mesh, textures) + }) + .and_then(|r| r) + { + Ok(()) => { + // Far terrain is drawn by the preview (M8 task 6); without GPU memory + // for it the detail area still shows. + if let Some(far) = far_mesh + && let Err(e) = catch_out_of_memory(device, || { + self.preview.upload_far(&self.gpu, far, mesh.origin) + }) + { + log::error!("far terrain upload failed: {e}"); + self.preview.clear_far(); + self.error = Some(format!("Can't show the far terrain: {e}")); + } + let stats = self.preview.stats(); + w.preview = Some((stats.draws, stats.gpu_bytes as f64 / 1048576.0)); + w.far_quads = (stats.far_quads > 0).then_some(stats.far_quads); + w.resident.preview = true; + } + Err(e) => { + log::error!("upload failed: {e}"); + self.preview.clear_world(); + self.error = Some(format!("Can't show this world: {e}")); + } + } + } + if let (true, Some(grid)) = (wanted.path_tracer, quad_grid) { + // The preview works without the path tracer, so a failure only disables it. + match catch_out_of_memory(device, || { + self.path_tracer + .upload_world(&self.gpu, grid, mesh.origin, textures) + }) + .and_then(|r| r) + { + Ok(()) => { + // Far terrain (M8 task 7); without memory for it the near world still + // renders. + if let Some(field) = far_field + && let Err(e) = catch_out_of_memory(device, || { + self.path_tracer.upload_far(&self.gpu, field) + }) + .and_then(|r| r) + { + log::error!("path tracer far terrain upload failed: {e}"); + self.path_tracer.clear_far(); + self.error = + Some(format!("The path tracer can't show the far terrain: {e}")); + } + w.pt_mib = Some(self.path_tracer.stats().gpu_bytes as f64 / 1048576.0); + w.resident.path_tracer = true; + } + Err(e) => { + log::error!("path tracer upload failed: {e}"); + self.path_tracer.clear_world(); + w.pt_failed = true; + self.error = Some( + "The path tracer can't hold this world (see the log); the preview \ + still works." + .to_owned(), + ); + } + } + } + log::info!( + "world '{}' on the GPU: preview {:?}, path tracer {:?} MiB", + w.name, + w.preview.map(|p| p.1.round()), + w.pt_mib.map(f64::round) + ); + self.viewport.invalidate(); + } + + /// Keeps on the GPU exactly the geometry the engines in use need (ADR 0020): frees the + /// rest and builds what is missing on a worker thread from the kept blocks. + fn sync_residency(&mut self) { + // A finished build for the world on screen. + if let Some(task) = &mut self.mesh_task + && let Some(geometry) = task.poll() + { + let version = task.world_version; + self.mesh_task = None; + if version == self.world_version { + let wanted = geometry + .wanted + .missing_from(self.world.as_ref().map(|w| w.resident).unwrap_or_default()); + self.upload_geometry( + wanted, + &geometry.mesh, + geometry.quad_grid.as_ref(), + (geometry.far_mesh.as_ref(), geometry.far_field.as_ref()), + ); + } + } + let job_engine = self + .job + .as_ref() + .map(|j| j.spec().engine) + .or(self.queue_engine); + let pack_wanted = self.engine == EngineChoice::ShaderPack + || job_engine == Some(EngineChoice::ShaderPack) + || self.queue_pack.is_some(); + if !pack_wanted { + self.shader_packs.release_world(); + } + // A running load brings its own geometry. + if self.load.is_some() { + return; + } + let wanted = self.wanted_residency(); + let Some(w) = &mut self.world else { + self.mesh_task = None; + return; + }; + let (free, missing) = residency_plan(wanted, w.resident, w.pt_failed); + let mut freed = false; + if free.preview { + self.preview.clear_world(); + w.resident.preview = false; + w.preview = None; + w.far_quads = None; + freed = true; + } + if free.path_tracer { + self.path_tracer.clear_world(); + w.resident.path_tracer = false; + w.pt_mib = None; + freed = true; + } + if freed { + log::info!( + "freed engine geometry no longer in use: now {:?}", + w.resident + ); + self.viewport.invalidate(); + } + if missing.is_empty() { + self.mesh_task = None; + } else if self + .mesh_task + .as_ref() + .is_none_or(|t| t.world_version != self.world_version || t.wanted != missing) + { + let ctx = self.egui_ctx.clone(); + self.mesh_task = Some(MeshTask::spawn( + Arc::clone(&w.pack_world), + self.world_version, + missing, + move || ctx.request_repaint(), + )); + } + } + + /// Right-drag look: hides and grabs the cursor for the drag and turns the camera by raw + /// mouse motion (which keeps coming while the cursor is held still), then shows the cursor + /// again where the drag started. Returns whether the camera is being turned. + fn mouse_look(&mut self, ctx: &egui::Context, response: &egui::Response) -> bool { + if self.look_anchor.is_none() && response.drag_started_by(egui::PointerButton::Secondary) { + let anchor = ctx + .input(|i| i.pointer.press_origin()) + .or_else(|| response.interact_pointer_pos()); + if let Some(anchor) = anchor { + self.look_anchor = Some(anchor); + ctx.send_viewport_cmd(egui::ViewportCommand::CursorGrab(LOOK_GRAB)); + ctx.send_viewport_cmd(egui::ViewportCommand::CursorVisible(false)); + } + } + let Some(anchor) = self.look_anchor else { + return false; + }; + let (motion, still_down) = ctx.input(|i| { + let motion: egui::Vec2 = i + .events + .iter() + .filter_map(|e| match e { + egui::Event::MouseMoved(d) => Some(*d), + _ => None, + }) + .fold(egui::Vec2::ZERO, |a, d| a + d); + (motion, i.pointer.secondary_down()) + }); + if motion != egui::Vec2::ZERO { + self.fly_camera(|fly, camera| fly.look(camera, motion)); + } + if !still_down { + self.look_anchor = None; + ctx.send_viewport_cmd(egui::ViewportCommand::CursorGrab(egui::CursorGrab::None)); + ctx.send_viewport_cmd(egui::ViewportCommand::CursorPosition(anchor)); + ctx.send_viewport_cmd(egui::ViewportCommand::CursorVisible(true)); + } + true + } + + /// Game folder of the chosen instance (the key for shader-pack choices; empty without + /// one). + fn instance_key(&self) -> PathBuf { + self.project.settings.instance.clone().unwrap_or_default() + } + + /// The shader pack to render with: `--shaderpack`, else the instance's choice. + fn chosen_shader_pack(&self) -> Option { + if let Some(pack) = &self.queue_pack { + return Some(pack.clone()); + } + match &self.shader_pack_override { + Some((p, _)) => Some(p.clone()), + None => self + .shader_pack_choices + .get(&self.instance_key()) + .and_then(|c| c.selected.clone()), + } + } + + /// Picks up a finished shader-pack build and, with the Shader Pack engine selected, + /// starts one when the pack or the world changed. + fn sync_shader_pack(&mut self) { + let world = self + .world + .as_ref() + .map(|w| (self.world_version, &w.pack_world)); + if self.shader_packs.poll(world) { + self.viewport.invalidate(); + } + // Wait for a running load: its world would make the build start over. + let wanted = self.engine == EngineChoice::ShaderPack || self.queue_pack.is_some(); + if wanted && self.load.is_none() { + let pack = self.chosen_shader_pack(); + let ctx = self.egui_ctx.clone(); + let world = self + .world + .as_ref() + .map(|w| (self.world_version, &w.pack_world)); + self.shader_packs + .sync(&self.gpu, pack.as_deref(), world, move || { + ctx.request_repaint() + }); + } + } + + /// The Render panel's shader-pack section. + fn shader_pack_ui(&mut self, ui: &mut egui::Ui) { + let key = self.instance_key(); + // List the instance's shaderpacks/ when the instance changed or after Rescan. + if self + .shader_packs_found + .as_ref() + .is_none_or(|(k, found)| k != &key || found.is_none() && !k.as_os_str().is_empty()) + { + let found = (!key.as_os_str().is_empty()) + .then(|| aktis_sp::find_packs(&key.join("shaderpacks"))); + self.shader_packs_found = Some((key.clone(), found)); + } + let status = self.shader_packs.status(); + let errors = self.shader_packs.errors().to_vec(); + let found = &mut self.shader_packs_found.as_mut().expect("listed").1; + let choice: &mut ShaderPackChoice = self.shader_pack_choices.entry(key).or_default(); + let action = shader_pack::ui( + ui, + choice, + found, + self.shader_pack_override.as_ref().map(|(p, _)| p.as_path()), + &status, + &errors, + ); + if action.reload { + self.shader_packs.reload(); + } + } + + /// The scene shown: the timeline at the playhead, then the fly camera's override. + fn shown_scene(&self) -> Scene { + animate::shown_scene( + &self.timeline, + &self.scene, + self.playhead, + &self.camera_override, + ) + } + + /// Moves the shown camera with the fly camera; animated values go to the override, the + /// rest to the base (`animate::apply_fly`). + fn fly_camera(&mut self, f: impl FnOnce(&FlyCamera, &mut Camera)) { + let evaluated = self.timeline.scene_at(&self.scene, self.playhead).camera; + let mut camera = evaluated.clone(); + self.camera_override.apply(&mut camera); + f(&self.fly, &mut camera); + animate::apply_fly( + &self.timeline, + &mut self.scene, + &mut self.camera_override, + &evaluated, + &camera, + ); + // Flying isn't an edit: it never becomes an undo step. + self.history.absorb_camera(&self.scene.camera); + } + + /// The camera-path overlay: only with the Preview engine selected and the Timeline tab + /// open. + fn path_overlay(&self) -> Option { + let timeline_shown = + self.timeline_panel.open && self.timeline_panel.tab == timeline_panel::Tab::Timeline; + if self.engine != EngineChoice::Preview || !timeline_shown { + return None; + } + playback::path_overlay(&self.timeline, self.playhead) + } + + /// Opens the Orbit dialog around the selection's centre at the camera's height (without + /// a world: 32 blocks ahead of the camera). + fn open_orbit_dialog(&mut self) { + let camera = self.shown_scene().camera; + let centre = match &self.world { + Some(w) => { + let c = w.blocks.center.as_vec3() + Vec3::new(0.5, 0.0, 0.5); + Vec3::new(c.x, camera.position.y, c.z) + } + None => { + let f = camera.forward(); + let ahead = Vec3::new(f.x, 0.0, f.z).normalize_or(Vec3::Z) * 32.0; + camera.position + ahead + } + }; + self.orbit_dialog = Some(Orbit::around(centre, &camera, self.playhead)); + } + + /// Whether the render queue runs (the engines, world and shader pack belong to it; + /// Render, Output, the Project panel, playback and New/Open are locked). + fn job_active(&self) -> bool { + self.queue_running || self.engines_busy() + } + + /// Whether a job's runner holds the engines (the viewport shows its frame). + fn engines_busy(&self) -> bool { + self.job.as_ref().is_some_and(|j| j.status().is_active()) + } + + /// Runs the queue for this frame: the job's slice of work, its status in the list, and + /// between jobs the next one's world load and shader-pack build. + fn step_queue(&mut self, ctx: &egui::Context) { + if let Some((id, encoder)) = &self.encoder { + match encoder.try_result() { + None => { + ctx.request_repaint_after(std::time::Duration::from_millis(200)); + return; + } + Some(result) => { + let id = *id; + self.encoder = None; + self.finish_encode(id, result); + } + } + } + if let Some(job) = &mut self.job { + let mut engines = JobEngines { + preview: &mut self.preview, + pt: &mut self.path_tracer, + sp: &mut self.shader_packs.engine, + }; + job.step(&self.gpu, &mut engines); + let status = job.status().clone(); + let done = job.done(); + if let Some(entry) = self.queue_job.and_then(|id| self.queue.get_mut(id)) { + entry.frames_done = done; + entry.status = match &status { + JobStatus::Rendering | JobStatus::Pausing => QueueStatus::Rendering, + JobStatus::Paused => QueueStatus::Paused, + JobStatus::Done => QueueStatus::Done, + JobStatus::Failed(e) => QueueStatus::Failed(e.clone()), + JobStatus::Cancelled => QueueStatus::Cancelled, + }; + } + match status { + JobStatus::Rendering | JobStatus::Pausing => { + ctx.request_repaint(); + return; + } + JobStatus::Paused => return, + ended => { + // The viewport's scheduler takes the engines back. + self.job = None; + let id = self.queue_job.take(); + self.viewport.invalidate(); + if ended == JobStatus::Cancelled { + self.finish_queue(); + return; + } + // A video job encodes its frames next. + if let Some(id) = id.filter(|&id| { + ended == JobStatus::Done + && self.queue.get(id).is_some_and(|j| j.video.is_some()) + }) { + self.start_encode(id); + return; + } + } + } + } + if !self.queue_running { + return; + } + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + let id = match self.queue_job.or_else(|| self.queue.next_waiting()) { + Some(id) => id, + None => return self.finish_queue(), + }; + self.queue_job = Some(id); + let Some(entry) = self.queue.get(id).cloned() else { + self.queue_job = None; + return; + }; + let project = match entry.project() { + Ok(p) => p, + Err(e) => return self.fail_queued(id, e), + }; + let request = match project.request() { + Ok(r) => r, + Err(missing) => return self.fail_queued(id, missing.join(" ")), + }; + if entry.encode_only { + // Encode again: the frames are on disk; no world or engine needed. + return self.start_encode(id); + } + if let Some(e) = self.queue.get_mut(id) { + e.status = QueueStatus::Preparing; + } + // The job's world: wait for a running load, else load it if it isn't on screen. + if self.load.is_some() { + return; + } + let shown = self.world.as_ref().map(|w| &w.request); + if queue::needs_load(&request, shown) { + if self.queue_loading.as_ref() == Some(&request) { + // Loaded and still not on screen: the load failed. + let why = self + .error + .clone() + .unwrap_or_else(|| "loading the world failed".to_owned()); + self.queue_loading = None; + return self.fail_queued(id, why); + } + self.start_queue_load(request.clone()); + self.queue_loading = Some(request); + return; + } + self.queue_loading = None; + // The job's engine geometry (built on demand, ADR 0020). + self.queue_engine = Some(project.engine.kind); + if project.engine.kind != EngineChoice::ShaderPack + && !self.engine_resident(project.engine.kind) + { + return; + } + // The job's shader pack: built for this world before rendering. + if project.engine.kind == EngineChoice::ShaderPack { + let Some(pack) = project.engine.shader_pack.clone() else { + return self.fail_queued(id, "The job names no shader pack.".to_owned()); + }; + self.queue_pack = Some(pack.clone()); + match self.shader_packs.ready_for(&pack, self.world_version) { + None => return, + Some(Err(e)) => return self.fail_queued(id, format!("shader pack: {e}")), + Some(Ok(())) => {} + } + } + let max = self.gpu.device.limits().max_texture_dimension_2d; + let spec = match entry.spec(max) { + Ok(spec) => spec, + Err(e) => return self.fail_queued(id, e), + }; + // A video's `_frames/` folder doesn't exist before its first run. + if let JobTarget::Sequence { dir, .. } = &spec.target + && let Err(e) = std::fs::create_dir_all(dir) + { + return self.fail_queued(id, format!("can't create {}: {e}", dir.display())); + } + if let Some(e) = self.queue.get_mut(id) { + e.replace = false; + e.status = QueueStatus::Rendering; + e.frames_done = 0; + } + self.playback.pause(); + let mut engines = JobEngines { + preview: &mut self.preview, + pt: &mut self.path_tracer, + sp: &mut self.shader_packs.engine, + }; + self.job = Some(JobRunner::start(spec, &mut engines)); + self.viewport.invalidate(); + ctx.request_repaint(); + } + + /// Starts ffmpeg over job `id`'s frames (all must be on disk). + fn start_encode(&mut self, id: u64) { + let Some(entry) = self.queue.get(id).cloned() else { + return; + }; + let (project, spec) = match entry.project().and_then(|p| Ok((p, entry.spec(u32::MAX)?))) { + Ok(x) => x, + Err(e) => return self.fail_queued(id, e), + }; + let (Some(video), JobTarget::Sequence { dir, name }) = (entry.video.clone(), &spec.target) + else { + return self.fail_queued(id, "The job has no video to encode.".to_owned()); + }; + if !project.output.format.is_video() { + return self.fail_queued(id, "The job's format isn't a video.".to_owned()); + } + let ffmpeg = match &self.ffmpeg { + Ok(f) => f.path.clone(), + Err(e) => { + let why = format!("{e}. {}", ffmpeg::install_hint()); + return self.fail_queued(id, why); + } + }; + let missing = spec + .frames + .clone() + .filter(|&f| !spec.path(f).is_file()) + .count(); + if missing > 0 { + return self.fail_queued( + id, + format!( + "{missing} frame(s) missing in {}; Run again renders them.", + dir.display() + ), + ); + } + let input = ffmpeg::EncodeInput { + format: project.output.format, + quality: project.output.quality, + fps: project.timeline.fps, + pattern: crate::job::frame_pattern(dir, name, spec.frames.end.saturating_sub(1)), + start_number: u64::from(spec.frames.start) + 1, + frames: spec.frame_count(), + output: video, + }; + match Encoder::spawn(&ffmpeg, &input) { + Ok(encoder) => { + if let Some(e) = self.queue.get_mut(id) { + e.status = QueueStatus::Encoding; + e.encode_only = false; + } + self.queue_job = Some(id); + self.encoder = Some((id, encoder)); + } + Err(e) => self.fail_queued(id, e), + } + } + + /// ffmpeg finished for job `id`: Done (frames deleted unless Keep frames) or Failed (the + /// frames stay for Encode again). + fn finish_encode(&mut self, id: u64, result: Result<(), String>) { + self.queue_job = None; + let Some(entry) = self.queue.get(id).cloned() else { + return; + }; + if let Err(e) = result { + return self.fail_queued(id, e); + } + let keep = entry + .project() + .map(|p| p.output.keep_frames) + .unwrap_or(true); + if let (false, Ok(spec)) = (keep, entry.spec(u32::MAX)) { + for f in spec.frames.clone() { + let _ = std::fs::remove_file(spec.path(f)); + } + if let JobTarget::Sequence { dir, .. } = &spec.target { + // Only if nothing else is in it. + let _ = std::fs::remove_dir(dir); + } + } + log::info!( + "render queue: encoded {}", + entry.video.as_deref().unwrap_or(Path::new("?")).display() + ); + if let Some(e) = self.queue.get_mut(id) { + e.status = QueueStatus::Done; + } + } + + /// Loads a job's world, keeping the editor's camera. + fn start_queue_load(&mut self, request: LoadRequest) { + let from_panel = self.world.as_ref().is_none_or(|w| w.from_panel); + let reuse = self + .world + .as_ref() + .filter(|w| w.request.same_blocks(&request)) + .map(|w| w.blocks.clone()); + let camera = Some(self.scene.camera.clone()); + self.start_load(request, from_panel, camera, reuse); + } + + /// Marks job `id` failed; the queue goes on with the next one. + fn fail_queued(&mut self, id: u64, message: String) { + log::error!("render queue: job failed: {message}"); + if let Some(e) = self.queue.get_mut(id) { + e.status = QueueStatus::Failed(message); + } + self.queue_job = None; + } + + /// Start: runs the waiting jobs from the top. + fn start_queue(&mut self) { + if self.queue_running || self.queue.next_waiting().is_none() { + return; + } + log::info!("render queue: start"); + self.queue_running = true; + self.editor_world = self + .load + .as_ref() + .map(|l| l.request.clone()) + .or_else(|| self.world.as_ref().map(|w| w.request.clone())); + } + + /// The queue stopped (no waiting jobs, or Cancel): the editor's world and shader pack + /// come back if a job changed them. + fn finish_queue(&mut self) { + log::info!("render queue: stopped"); + self.queue_running = false; + self.queue_job = None; + self.queue_loading = None; + self.queue_pack = None; + self.queue_engine = None; + if let Some(e) = self + .queue + .jobs + .iter_mut() + .find(|j| j.status == QueueStatus::Preparing) + { + e.status = QueueStatus::Queued; + } + if let Some(request) = self.editor_world.take() { + let shown = self.world.as_ref().map(|w| &w.request); + let loading = self.load.as_ref().map(|l| &l.request); + if loading != Some(&request) && queue::needs_load(&request, shown) { + self.start_queue_load(request); + } + } + self.viewport.invalidate(); + } + + /// Cancel: stops the running (or preparing) job and the queue. + fn cancel_queue(&mut self) { + if let Some((_, encoder)) = self.encoder.take() { + encoder.kill(); + } + if let Some(job) = &mut self.job { + let mut engines = JobEngines { + preview: &mut self.preview, + pt: &mut self.path_tracer, + sp: &mut self.shader_packs.engine, + }; + job.cancel(&mut engines); + } + if let Some(e) = self.queue_job.and_then(|id| self.queue.get_mut(id)) { + e.status = QueueStatus::Cancelled; + } + self.job = None; + self.finish_queue(); + } + + /// File name for a job's frames: the project's name, else the world's. + fn job_name(&self) -> String { + let project = self.project_path.as_ref().map(|p| { + let name = project_file::display_name(Some(p)); + let suffix = format!(".{}", project_file::EXTENSION); + match name.to_lowercase().strip_suffix(&suffix) { + Some(stem) => name[..stem.len()].to_owned(), + None => name, + } + }); + let world = self.world.as_ref().map(|w| w.name.clone()); + file_stem(&project.or(world).unwrap_or_else(|| "aktis".to_owned())) + } + + /// "Add animation…" / "Add still…": asks where the frames go, then queues a snapshot of + /// the project (asking about frames already there). + fn add_job(&mut self, kind: JobKind) { + let frame = self.timeline.frame_at(self.playhead); + let mut name = self.job_name(); + let mut video = None; + let format = self.output.format; + let target = match kind { + JobKind::Animation if format.is_video() => { + let ext = format.extension(); + let mut dialog = rfd::FileDialog::new() + .set_title("Save video") + .add_filter(format.label(), &[ext]) + .set_file_name(format!("{name}.{ext}")); + if let Some(dir) = self.output.path.as_ref().and_then(|p| p.parent()) { + dialog = dialog.set_directory(dir); + } + let Some(path) = dialog.save_file() else { + return; + }; + let path = with_extension(path, ext); + self.output.path = Some(path.clone()); + // Frames go next to the video: `