From 0c86bb8e88bc2eaec640583250389f8626bc16a8 Mon Sep 17 00:00:00 2001 From: Preetham Pemmasani <75422607+ppmpreetham@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:33:58 +0530 Subject: [PATCH] add demos --- demos/.gitignore | 2 + demos/Cargo.lock | 493 +++++++++++++++++++++++++++++++++ demos/Cargo.toml | 35 +++ demos/README.md | 21 ++ demos/src/bin/editor.rs | 317 +++++++++++++++++++++ demos/src/bin/failed.rs | 433 +++++++++++++++++++++++++++++ demos/src/bin/gambit.rs | 567 ++++++++++++++++++++++++++++++++++++++ demos/src/bin/glass.rs | 86 ++++++ demos/src/bin/morning.rs | 523 +++++++++++++++++++++++++++++++++++ demos/src/bin/phantom.rs | 361 ++++++++++++++++++++++++ demos/src/bin/pipeline.rs | 229 +++++++++++++++ demos/src/bin/shaders.rs | 129 +++++++++ demos/src/bin/velvet.rs | 323 ++++++++++++++++++++++ demos/src/canvas.rs | 71 +++++ demos/src/lib.rs | 163 +++++++++++ demos/src/menu.rs | 101 +++++++ 16 files changed, 3854 insertions(+) create mode 100644 demos/.gitignore create mode 100644 demos/Cargo.lock create mode 100644 demos/Cargo.toml create mode 100644 demos/README.md create mode 100644 demos/src/bin/editor.rs create mode 100644 demos/src/bin/failed.rs create mode 100644 demos/src/bin/gambit.rs create mode 100644 demos/src/bin/glass.rs create mode 100644 demos/src/bin/morning.rs create mode 100644 demos/src/bin/phantom.rs create mode 100644 demos/src/bin/pipeline.rs create mode 100644 demos/src/bin/shaders.rs create mode 100644 demos/src/bin/velvet.rs create mode 100644 demos/src/canvas.rs create mode 100644 demos/src/lib.rs create mode 100644 demos/src/menu.rs diff --git a/demos/.gitignore b/demos/.gitignore new file mode 100644 index 00000000..510cb5c2 --- /dev/null +++ b/demos/.gitignore @@ -0,0 +1,2 @@ +target/ +.reanimate/ diff --git a/demos/Cargo.lock b/demos/Cargo.lock new file mode 100644 index 00000000..7fa08537 --- /dev/null +++ b/demos/Cargo.lock @@ -0,0 +1,493 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "accesskit" +version = "0.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e883d1d28c5fd5568c79ed2d2bd48d9f2fd3945c8974ed0f53690ceddb051be" +dependencies = [ + "uuid", +] + +[[package]] +name = "accesskit_consumer" +version = "0.39.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3da8f27636015191b2264ee1df681503170a632cafd832fdc1edfdd4e3a2fd3" +dependencies = [ + "accesskit", + "hashbrown", +] + +[[package]] +name = "accesskit_windows" +version = "0.35.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "498668b90da9995302a0055aaecad4756932333da2ddef6baee1c00844c430fc" +dependencies = [ + "accesskit", + "accesskit_consumer", + "hashbrown", + "static_assertions", + "windows", + "windows-core", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "blenderui" +version = "0.5.1" +dependencies = [ + "blenderui-macros", + "blenderui-sys", + "blenderui-table", + "blenderui-tailwind", + "blenderui-vlist", + "foldhash", + "miniz_oxide 0.8.9", + "ndk-context", + "paste", + "smallvec", + "taffy", + "unicode-linebreak", +] + +[[package]] +name = "blenderui-macros" +version = "0.5.1" +dependencies = [ + "blenderui-tailwind", +] + +[[package]] +name = "blenderui-paint" +version = "0.5.1" + +[[package]] +name = "blenderui-sys" +version = "0.5.1" +dependencies = [ + "bui-a11y", + "cmake", +] + +[[package]] +name = "blenderui-table" +version = "0.5.1" +dependencies = [ + "blenderui-paint", +] + +[[package]] +name = "blenderui-tailwind" +version = "0.5.1" + +[[package]] +name = "blenderui-vlist" +version = "0.5.1" +dependencies = [ + "blenderui-paint", +] + +[[package]] +name = "bui-a11y" +version = "0.5.1" +dependencies = [ + "accesskit", + "accesskit_windows", +] + +[[package]] +name = "bui-demos" +version = "0.0.0" +dependencies = [ + "blenderui", + "png", +] + +[[package]] +name = "cc" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "crc32fast" +version = "1.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "png" +version = "0.17.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" +dependencies = [ + "bitflags", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "taffy" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31f7bd2d97198df05186f93a3a3c306845f40e8b3c22bf9279cdd7e5cf5fea7d" +dependencies = [ + "serde", + "slotmap", + "smallvec", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-linebreak" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" + +[[package]] +name = "uuid" +version = "1.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "zlib-rs" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" diff --git a/demos/Cargo.toml b/demos/Cargo.toml new file mode 100644 index 00000000..ee1bb930 --- /dev/null +++ b/demos/Cargo.toml @@ -0,0 +1,35 @@ +[package] +name = "bui-demos" +version = "0.0.0" +edition = "2024" +publish = false +description = "Small demos built on BUI: shader components, glass UI, a Blender-style CI pipeline and a motion editor." + +# Standalone: not a member of bindings/rust's workspace, so the main tree is untouched. +[workspace] + +[dependencies] +blenderui = { path = "../bindings/rust/blenderui" } +png = "0.17" + +[profile.dev] +debug = "line-tables-only" + +[profile.dev.package."*"] +debug = false + +[lints.clippy] +all = { level = "warn", priority = -2 } +pedantic = { level = "warn", priority = -2 } +perf = { level = "warn", priority = -1 } +complexity = { level = "warn", priority = -1 } +cast_possible_truncation = "allow" +cast_sign_loss = "allow" +cast_precision_loss = "allow" +too_many_lines = "allow" +similar_names = "allow" +many_single_char_names = "allow" +unreadable_literal = "allow" +missing_const_for_fn = "warn" +use_self = "warn" +redundant_clone = "warn" diff --git a/demos/README.md b/demos/README.md new file mode 100644 index 00000000..679314a5 --- /dev/null +++ b/demos/README.md @@ -0,0 +1,21 @@ +# BUI demos + +Small demos built on BUI's Rust API (`blenderui`). Source only, a few KB each. `demos/` is its own +cargo workspace, so it never touches `bindings/rust`'s build. + +| Demo | Run | What BUI does in it | +|---|---|---| +| Shader components | `cargo run --release --bin shaders` | three `ShaderEffect` canvases: plasma button (hover), aurora card (cursor), ripple field (click) | +| Glass UI | `cargo run --release --bin glass` | a shader background under CSS glass: `backdrop-filter: blur() saturate()`, Blender widgets inside | +| CI pipeline | `cargo run --release --bin pipeline` | a GitHub Actions workflow as a Blender node graph, painted with `Painter`; run it, make the test job fail | +| Motion editor | `cargo run --release --bin editor` | After Effects-style layout: shader layer + painted layers, keyframes, timeline, effect controls that key at the playhead | +| Gambit | `cargo run --release --bin gambit` | a noir chess collage raymarched on the GPU: a half-resolution scene pass into a `RenderTarget`, then a full-resolution halftone composite. No UI: click anywhere and the queen slams down. `-- --frames DIR` renders frames off-screen and times the compile and both passes | +| Windows Failed | `cargo run --release --bin failed` | a Y2K blue poster wall (shader). No UI: the first click is a cascade of Win9x error dialogs (CSS keyframes, a shake, a glitch), each later one a single warning; every ✕ and OK closes its warning and opens another, and kernel panics pop up at random. `-- --storyboard DIR` clicks through it headlessly | +| Velvet Menu | `cargo run --release --bin velvet` | a Persona-style main menu for a tech app: an underwater shader, a tilted heavy-italic menu where the selection snaps forward on a red slash (hover or ↑/↓), Enter / click opens a sub-menu that follows the arrows, C / Esc closes. Laid out in `rem` on a 1280 x 720 canvas sized to the window, so it stays sharp. `-- --storyboard DIR` drives it headlessly | +| Phantom | `cargo run --release --bin phantom` | a Persona 5-style menu for the same app: a shader scene (red room, spinning starburst, star, ink slash) under ransom-note type, every letter its own font, tilt and box; the selection's letters pop onto coloured blocks, Enter slams in the sub-menu card | +| Morning | `cargo run --release --bin morning` | a pinch folds a full-screen page into its card in a stack (cloned from `ref/testanim.mp4`): the page washes out, shrinks onto its card and goes dark while the stack zooms up behind it, its three cards fanning in. Pinch on a trackpad or touch screen to scrub it (letting go finishes the way you were going); Space folds, Escape opens, a click does either | + +`src/menu.rs` (the commands and the selection state) and `src/canvas.rs` (a design canvas that fits the window crisply) are shared by the two menus. `src/lib.rs` is shared by all of them: the window, the shader + software fallback (`Fx`, with an optional pre-pass into a render target), the clock, `--screenshot out.png` (off-screen, software), scripted headless runs and GPU stills. +Without a GPU, each shader draws its flat fallback colour. + +Build output goes to `demos/target/` (ignored). Delete it to reclaim the space. diff --git a/demos/src/bin/editor.rs b/demos/src/bin/editor.rs new file mode 100644 index 00000000..af0911dd --- /dev/null +++ b/demos/src/bin/editor.rs @@ -0,0 +1,317 @@ +//! An After Effects-style motion editor on BUI: menu bar, project and effects panels, a composition +//! (a GPU shader background layer under `Painter`-drawn layers), effect controls whose sliders set +//! keyframes at the playhead, and a timeline with clips, keyframe diamonds and a scrubbable playhead. +//! `cargo run --release --bin editor` + +use std::sync::Arc; + +use bui_demos::{now, run, Fx}; +use blenderui::prelude::*; + +const DUR: f32 = 5.0; +const FPS: f32 = 24.0; +const COMP: (f32, f32) = (640.0, 360.0); +const ROW_H: f32 = 24.0; + +/// A layer's transform: position in 0..1 of the comp, uniform scale, rotation in degrees. +#[derive(Clone, Copy)] +struct Xf { + x: f32, + y: f32, + s: f32, + r: f32, +} + +#[derive(Clone, Copy)] +enum Shape { + Rect(f32, f32), + Circle(f32), + Text(&'static str), +} + +#[derive(Clone)] +struct Layer { + name: &'static str, + label: u32, + fill: u32, + shape: Shape, + span: (f32, f32), + keys: Vec<(f32, Xf)>, +} + +impl Layer { + /// The transform at `t`: smoothstep between the keyframes around it, held before and after. + fn at(&self, t: f32) -> Xf { + let k = &self.keys; + let (first, last) = (k[0], k[k.len() - 1]); + if t <= first.0 { return first.1; } + if t >= last.0 { return last.1; } + let i = k.windows(2).position(|w| t < w[1].0).unwrap_or(0); + let ((a, xa), (b, xb)) = (k[i], k[i + 1]); + let u = (t - a) / (b - a); + let u = u * u * (3.0 - 2.0 * u); + let l = |p: f32, q: f32| p + (q - p) * u; + Xf { x: l(xa.x, xb.x), y: l(xa.y, xb.y), s: l(xa.s, xb.s), r: l(xa.r, xb.r) } + } + + /// Sets a keyframe at `t` (the stopwatch is on for every property, as after a first key). + fn key(&mut self, t: f32, f: impl FnOnce(&mut Xf)) { + let mut v = self.at(t); + f(&mut v); + if let Some(i) = self.keys.iter().position(|k| (k.0 - t).abs() < 0.5 / FPS) { + self.keys[i].1 = v; + } else { + let i = self.keys.partition_point(|k| k.0 < t); + self.keys.insert(i, (t, v)); + } + } +} + +const fn xf(x: f32, y: f32, s: f32, r: f32) -> Xf { + Xf { x, y, s, r } +} + +fn layers() -> Vec { + vec![ + Layer { name: "nav icon", label: 0x9b8bd9, fill: 0xeeeeff, shape: Shape::Rect(54.0, 54.0), span: (0.0, 5.0), + keys: vec![(0.0, xf(0.2, 0.2, 1.0, 0.0)), (1.4, xf(0.2, 0.2, 1.4, 90.0)), (3.2, xf(0.2, 0.2, 1.0, 180.0))] }, + Layer { name: "btn bg", label: 0x5aa0d8, fill: 0x2f6fb0, shape: Shape::Circle(64.0), span: (0.0, 5.0), + keys: vec![(0.0, xf(0.2, 0.2, 1.0, 0.0)), (2.0, xf(0.5, 0.5, 1.6, 0.0)), (4.0, xf(0.8, 0.78, 1.0, 0.0))] }, + Layer { name: "unleash shrimpfish", label: 0x4caf50, fill: 0xffffff, shape: Shape::Text("UNLEASH · CROSS-MEDIA"), span: (0.5, 5.0), + keys: vec![(0.5, xf(-0.3, 0.42, 1.0, 0.0)), (1.6, xf(0.5, 0.42, 1.0, 0.0)), (4.5, xf(1.3, 0.42, 1.0, 0.0))] }, + Layer { name: "divider", label: 0xe87d0d, fill: 0xe87d0d, shape: Shape::Rect(360.0, 6.0), span: (0.0, 5.0), + keys: vec![(0.0, xf(0.5, 0.6, 0.0, 0.0)), (1.0, xf(0.5, 0.6, 1.0, 0.0)), (4.0, xf(0.5, 0.6, 1.0, 0.0)), (5.0, xf(0.5, 0.6, 0.0, 0.0))] }, + Layer { name: "selection box", label: 0x4a6fe0, fill: 0x4a6fe0, shape: Shape::Rect(180.0, 100.0), span: (1.8, 5.0), + keys: vec![(1.8, xf(0.3, 0.75, 0.2, 0.0)), (3.0, xf(0.7, 0.3, 1.0, 15.0))] }, + ] +} + +// Layer 6, "nav bg": a real GPU shader layer. U[0] = comp time (it scrubs with the playhead). +const NAV_BG: &str = " +vec4 effect(vec2 p) { + vec2 uv = p / box_size; + float w = 0.5 + 0.5 * sin(uv.x * 9.0 + U[0] * 2.0 + sin(uv.y * 5.0 + U[0])); + vec3 a = vec3(0.16, 0.36, 0.55); vec3 b = vec3(0.55, 0.82, 0.95); + vec3 c = mix(a, b, uv.y * 0.8 + w * 0.2); + return vec4(c * (0.85 + 0.15 * w), 1.0); +}"; + +fn paint_comp(b: Bounds, p: &mut Painter, layers: &[Layer], t: f32, sel: usize) { + let (ox, oy, sx) = (b.origin.x, b.origin.y, b.size.width / COMP.0); + for (i, l) in layers.iter().enumerate().rev() { + if t < l.span.0 || t > l.span.1 { continue; } + let v = l.at(t); + let (cx, cy) = (ox + v.x * b.size.width, oy + v.y * b.size.height); + let (sin, cos) = v.r.to_radians().sin_cos(); + let quad = |w: f32, h: f32| -> [(f32, f32); 4] { + let (hw, hh) = (w * v.s * sx / 2.0, h * v.s * sx / 2.0); + [(-hw, -hh), (hw, -hh), (hw, hh), (-hw, hh)].map(|(x, y)| (cx + x * cos - y * sin, cy + x * sin + y * cos)) + }; + let (w, h) = match l.shape { + Shape::Rect(w, h) => { + p.polygon(&quad(w, h), rgb(l.fill)); + (w, h) + } + Shape::Circle(d) => { + let r = d * v.s * sx / 2.0; + p.oval(Bounds { origin: point(cx - r, cy - r), size: size(r * 2.0, r * 2.0) }, rgb(l.fill), rgb(0xffffff), 1.0); + (d, d) + } + Shape::Text(s) => { + let fs = 22.0 * v.s * sx; + p.text(cx - s.chars().count() as f32 * fs * 0.29, cy - fs * 0.6, s, fs, rgb(l.fill)); + (s.chars().count() as f32 * 13.0, 30.0) + } + }; + if i == sel { + let mut q = quad(w + 10.0, h + 10.0).to_vec(); + q.push(q[0]); + p.line(&q, rgb(0xe8b30d), 1.5); + for &(x, y) in &q[..4] { + p.fill(Bounds { origin: point(x - 3.0, y - 3.0), size: size(6.0, 6.0) }, rgb(0xe8b30d)); + } + } + } +} + +fn paint_timeline(b: Bounds, p: &mut Painter, layers: &[Layer], t: f32, sel: usize) { + let (ox, oy, w) = (b.origin.x, b.origin.y, b.size.width); + let x_of = |s: f32| ox + s / DUR * w; + p.fill(b, rgb(0x2a2a2a)); + p.fill(Bounds { origin: point(ox, oy), size: size(w, ROW_H) }, rgb(0x262626)); + for f in 0..=(DUR * 2.0) as i32 { + let s = f as f32 * 0.5; + let x = x_of(s); + p.line(&[(x, oy + if f % 2 == 0 { 12.0 } else { 18.0 }), (x, oy + ROW_H)], rgb(0x777777), 1.0); + if f % 2 == 0 { p.text(x + 3.0, oy + 2.0, &format!("{:02}:00f", f / 2), 10.0, rgb(0x999999)); } + } + for (i, l) in layers.iter().enumerate() { + let y = oy + ROW_H * (i as f32 + 1.0); + if i == sel { p.fill(Bounds { origin: point(ox, y), size: size(w, ROW_H) }, rgb(0x3a3f48)); } + p.line(&[(ox, y + ROW_H), (ox + w, y + ROW_H)], rgb(0x1e1e1e), 1.0); + p.quad(Bounds { origin: point(x_of(l.span.0), y + 3.0), size: size(x_of(l.span.1) - x_of(l.span.0), ROW_H - 6.0) }, + 3.0, rgba((l.label << 8) | 0xbb), rgb(0x000000), 0.0); + for k in &l.keys { + let (x, c) = (x_of(k.0), y + ROW_H / 2.0); + p.polygon(&[(x, c - 5.0), (x + 5.0, c), (x, c + 5.0), (x - 5.0, c)], rgb(0xe8b30d)); + } + } + // the shader layer's track + let y = oy + ROW_H * (layers.len() as f32 + 1.0); + p.quad(Bounds { origin: point(ox, y + 3.0), size: size(w, ROW_H - 6.0) }, 3.0, rgba(0xb6a7ffbb), rgb(0x000000), 0.0); + let x = x_of(t); + p.line(&[(x, oy), (x, oy + b.size.height)], rgb(0xe5534b), 1.0); + p.polygon(&[(x - 6.0, oy), (x + 6.0, oy), (x, oy + 10.0)], rgb(0xe8b30d)); +} + +const CSS: &str = r" +html { height: 100%; } +body { margin: 0; display: flex; flex-direction: column; height: 100%; background: #232323; color: #c8c8c8; font-size: 12px; } +.menu { display: flex; gap: 16px; height: 22px; align-items: center; padding: 0 10px; background: #2b2b2b; border-bottom: 1px solid #111; } +.menu b { color: #9b8bff; } +.top { flex: 1; display: flex; gap: 2px; padding: 2px; } +.pane { background: #2f2f2f; border: 1px solid #151515; overflow: auto; } +.pane h4 { margin: 0; font-weight: 500; padding: 4px 8px; background: #262626; color: #aaa; } +.item { padding: 2px 12px; } +.item:hover { background: #3a3a3a; } +.left { width: 210px; } .right { width: 250px; } +.view { flex: 1; display: flex; flex-direction: column; } +.stage { flex: 1; display: flex; align-items: center; justify-content: center; background: #161616; } +.comp { position: relative; width: 640px; height: 360px; } +.cv { position: absolute; left: 0; top: 0; width: 640px; height: 360px; } +.ctl { display: flex; gap: 8px; align-items: center; padding: 4px 8px; background: #262626; } +.tc { color: #e8b30d; font-family: monospace; font-size: 14px; width: 92px; } +.scrub { flex: 1; } +.fx { padding: 6px 12px; } +.fx .r { display: flex; justify-content: space-between; margin-top: 8px; color: #999; } +.fx .r span { color: #e8b30d; } +.tl { height: 196px; display: flex; margin: 0 2px 2px; border-top: 1px solid #111; } +.names { width: 260px; background: #2f2f2f; border-right: 1px solid #111; } +.lrow { height: 24px; display: flex; align-items: center; gap: 8px; padding: 0 8px; border-bottom: 1px solid #222; } +.lrow.sel { background: #41464f; } +.lrow small { margin-left: auto; color: #e8b30d; } +.sw { width: 10px; height: 10px; border-radius: 2px; } +.track { flex: 1; } +"; + +struct Editor { + nav_bg: Fx, + layers: Arc>, + sel: usize, + t: f32, + /// Wall clock and comp time when play started. + playing: Option<(f32, f32)>, +} + +impl Editor { + fn set_t(&mut self, t: f32) { + self.t = (t / (1.0 / FPS)).round() * (1.0 / FPS); + self.t = self.t.clamp(0.0, DUR); + } + + fn jump_key(&mut self, dir: f32) { + let keys = &self.layers[self.sel].keys; + let t = self.t; + let next = if dir > 0.0 { + keys.iter().map(|k| k.0).find(|&k| k > t + 1e-3) + } else { + keys.iter().rev().map(|k| k.0).find(|&k| k < t - 1e-3) + }; + if let Some(k) = next { self.t = k; } + } +} + +impl Render for Editor { + fn render(&mut self, w: &mut Window, cx: &mut Context) -> impl IntoElement { + if let Some((wall, from)) = self.playing { + self.t = (from + now() - wall) % DUR; + w.request_animation_frame(); + } + let (t, sel) = (self.t, self.sel); + let frame = (t * FPS).round() as i32; + let tc = format!("0:00:{:02}:{:02}", frame / FPS as i32, frame % FPS as i32); + let cur = self.layers[sel].at(t); + + let (lc, lt) = (self.layers.clone(), self.layers.clone()); + let comp = div().class("comp") + .child(self.nav_bg.canvas(move |_| vec![t]).class("cv")) + .child(canvas(move |b, p| paint_comp(b, p, &lc, t, sel)).class("cv")); + + let mut names = div().class("names").child(div().class("lrow").child("# Layer name")); + for (i, l) in self.layers.iter().enumerate() { + names = names.child(div().class(if i == sel { "lrow sel" } else { "lrow" }) + .child(div().class("sw").bg(rgb(l.label))) + .child(format!("{} {}", i + 1, l.name)) + .child(small().child(format!("{} ◆", l.keys.len()))) + .on_click(cx.listener(move |this, _, _, cx| { this.sel = i; cx.notify(); }))); + } + names = names.child(div().class("lrow").child(div().class("sw").bg(rgb(0xb6a7ff))) + .child(format!("{} nav bg (GPU shader)", self.layers.len() + 1))); + + // effect controls: each slider keys its property at the playhead + let prop = |name: &'static str, val: f32, lo: f32, hi: f32, set: fn(&mut Xf, f32)| { + div().child(div().class("r").child(name).child(span().child(format!("{val:.2}")))) + .child(input().input_type("range").min(f64::from(lo)).max(f64::from(hi)).step(f64::from((hi - lo) / 200.0)) + .value(format!("{val}")) + .on_input(cx.listener(move |this: &mut Self, e: &ChangeEvent, _, cx| { + let (t, s) = (this.t, this.sel); + Arc::make_mut(&mut this.layers)[s].key(t, |x| set(x, e.number as f32)); + cx.notify(); + }))) + }; + let fx = div().class("fx").child(b().child(self.layers[sel].name)) + .child(prop("Position X", cur.x, -0.3, 1.3, |x, v| x.x = v)) + .child(prop("Position Y", cur.y, 0.0, 1.0, |x, v| x.y = v)) + .child(prop("Scale", cur.s, 0.0, 3.0, |x, v| x.s = v)) + .child(prop("Rotation", cur.r, -360.0, 360.0, |x, v| x.r = v)); + + let item = |s: &'static str| div().class("item").child(s); + html().styled() + .child(head().child(style().child(CSS))) + .child(body() + .child(div().class("menu").child(b().child("Ae")) + .children(["File", "Edit", "Composition", "Layer", "Effect", "Animation", "View", "Window", "Help"].map(span_of))) + .child(div().class("top") + .child(div().class("pane left").child(h4().child("Project")) + .child(item("▣ Main")).child(item("▣ nav-out")).child(item("▤ iphone image.psd")).child(item("▸ new-ui Layers")) + .child(h4().child("Effects & Presets")) + .children(["▸ 3D Channel", "▸ Blur & Sharpen", "▸ Color Correction", "▸ Distort", "▸ Generate", "▸ Keying", "▸ Noise & Grain", "▸ Stylize"].map(item))) + .child(div().class("pane view") + .child(div().class("stage").child(comp)) + .child(div().class("ctl") + .child(button().child(if self.playing.is_some() { "❚❚" } else { "▶" }) + .on_click(cx.listener(|this, _, _, cx| { + this.playing = if this.playing.is_some() { None } else { Some((now(), this.t)) }; + cx.notify(); + }))) + .child(button().child("◆◀").on_click(cx.listener(|this, _, _, cx| { this.jump_key(-1.0); cx.notify(); }))) + .child(button().child("▶◆").on_click(cx.listener(|this, _, _, cx| { this.jump_key(1.0); cx.notify(); }))) + .child(div().class("tc").child(tc)) + .child(input().class("scrub").input_type("range").min(0.0).max(f64::from(DUR)).step(f64::from(1.0 / FPS)) + .value(format!("{t}")) + .on_input(cx.listener(|this, e: &ChangeEvent, _, cx| { + this.playing = None; + this.set_t(e.number as f32); + cx.notify(); + }))) + .child(span().child("50% · Full · Active Camera")))) + .child(div().class("pane right").child(h4().child("Effect Controls")).child(fx))) + .child(div().class("tl") + .child(names) + .child(canvas(move |b, p| paint_timeline(b, p, <, t, sel)).class("track")))) + } +} + +fn span_of(s: &'static str) -> Div { + span().child(s) +} + +fn main() { + run(1240.0, 680.0, "BUI · motion editor", || Editor { + nav_bg: Fx::new("nav_bg", NAV_BG, 1, [80, 150, 200]), + layers: Arc::new(layers()), + sel: 1, + t: 0.0, + playing: None, + }); +} diff --git a/demos/src/bin/failed.rs b/demos/src/bin/failed.rs new file mode 100644 index 00000000..fbb3187e --- /dev/null +++ b/demos/src/bin/failed.rs @@ -0,0 +1,433 @@ +//! Windows Failed: a Y2K blue collage on BUI. A GPU shader paints the poster wall (ragged blue and +//! white panels, flowing ink, scanlines, grain). No UI: the first click on the wall pops a +//! cascade of "Windows Failed" dialogs, with a screen shake and a shader glitch; every later click +//! pops one more. Every ✕ and OK works: the warning closes, and another one opens somewhere else. +//! From the first click, kernel panics (a terminal, sticker captions, a star) pop up at random +//! every few seconds. +//! +//! Motion ("energetic"): pops of 180-280 ms with an overshoot, the burst staggered in under half a +//! second (windows 60 ms apart, then stickers 35 ms apart, then the star); hard shadows land 40 ms +//! after their windows; the replaced burst exits in 160 ms, accelerating; the ink, the spinning +//! star and the cursor keep the wall alive. +//! +//! `cargo run --release --bin failed` +//! `-- --storyboard DIR` clicks through it headlessly and saves frames along BUI's virtual clock; +//! `-- --frames DIR` renders the background shader off-screen on the GPU. + +use std::time::Duration; + +use blenderui::prelude::*; +use bui_demos::{arg, gpu_stills, now, run_with, save_png, Fx, Script}; + +/// U[0] = time, U[1] = seconds since the last click (< 0: none). +const WALL: &str = r" +float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); } +float vnoise(vec2 p) { + vec2 i = floor(p); vec2 f = fract(p); f = f * f * (3.0 - 2.0 * f); + return mix(mix(hash(i), hash(i + vec2(1.0, 0.0)), f.x), mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), f.x), f.y); +} +float fbm(vec2 p) { return 0.5 * vnoise(p) + 0.25 * vnoise(p * 2.03 + 1.7) + 0.125 * vnoise(p * 4.1 + 9.2) + 0.0625 * vnoise(p * 8.3 + 3.1); } + +vec4 effect(vec2 p) { + float t = U[0]; float g = U[1]; + vec2 uv = p / box_size; + // a click tears the wall: horizontal slices jump sideways for a quarter second, easing out + if (g >= 0.0 && g < 0.28) { + float k = 1.0 - g / 0.28; + float band = floor(uv.y * 28.0); + float r = hash(vec2(band, floor(t * 40.0))); + uv.x += step(0.55, r) * (r - 0.55) * 0.5 * k * k; + } + // poster panels: ragged columns, some white, some blue, black seams + float cx = uv.x * 6.0 + 0.35 * vnoise(vec2(uv.y * 2.0, 3.0)); + float col = floor(cx); + float blueCol = step(0.5, hash(vec2(col, 7.0))); + float seam = step(0.465, abs(fract(cx) - 0.5)); + float bar = step(0.985, fract(uv.y * 3.0 + hash(vec2(col, 1.0)))); + // ink: a slow, domain-warped flow, with a glossy streak inside it + vec2 q = uv * vec2(box_size.x / box_size.y, 1.0) * 2.2; + float w = fbm(q * 1.3 + vec2(t * 0.04, -t * 0.03)); + float n = fbm(q + 1.6 * w + vec2(0.0, t * 0.05) + col * 0.37); + float ink = smoothstep(0.5, 0.53, n); + float gloss = smoothstep(0.6, 0.63, n) * (1.0 - smoothstep(0.64, 0.7, n)); + vec3 white = vec3(0.95, 0.95, 0.97); vec3 blue = vec3(0.06, 0.06, 0.95); vec3 deep = vec3(0.01, 0.01, 0.3); + vec3 c = blueCol < 0.5 ? mix(white, blue, ink) : mix(blue, deep, ink); + c = mix(c, vec3(0.6, 0.65, 1.0), gloss * 0.85); + c *= 1.0 - 0.95 * max(seam, bar); + // xerox print: halftone in the blue, scanlines, grain, crushed contrast + vec2 cell = fract(p / 5.0) - 0.5; + c *= 1.0 - 0.18 * blueCol * step(length(cell), 0.25); + c *= 0.92 + 0.08 * sin(p.y * 1.5708); + c += (hash(p + fract(t * 7.0) * 50.0) - 0.5) * 0.09; + c = clamp((c - 0.06) * 1.15, 0.0, 1.0); + // the first frames of a click flash inverted + if (g >= 0.0 && g < 0.05) c = vec3(1.0) - c; + return vec4(c, 1.0); +} +"; + +const CSS: &str = r" +html { height: 100%; } +body { margin: 0; height: 100%; position: relative; overflow: hidden; background: #1010f0; cursor: pointer; user-select: none; + font-family: Inter, system-ui, sans-serif; -webkit-font-smoothing: antialiased; } +.wall { position: absolute; left: 0; top: 0; width: 100%; height: 100%; } +.type { position: absolute; color: #000; font-weight: 900; letter-spacing: -4px; line-height: 0.9; white-space: nowrap; } +.stage { position: absolute; left: 0; top: 0; width: 100%; height: 100%; } +.place { position: absolute; } + +/* -- a Windows 9x dialog, as stuck on a poster: thick ink outline, hard offset shadow -- */ +.win { position: absolute; width: 380px; } +.shade { position: absolute; left: 7px; top: 7px; width: 380px; height: 152px; background: #000; + animation: shade 200ms cubic-bezier(0.2, 0, 0, 1) backwards; } +.box { position: relative; height: 148px; border: 2px solid #000; background: #cdcdcd; + box-shadow: inset 2px 2px 0 #fff, inset -2px -2px 0 #7b7b7b; + animation: pop 260ms cubic-bezier(0.2, 0, 0, 1) backwards; } +.title { display: flex; align-items: center; height: 34px; margin: 3px; padding: 0 6px 0 12px; background: #1414ff; + color: #fff; font-family: Consolas, monospace; font-weight: 700; font-size: 21px; letter-spacing: 0.5px; + animation: flicker 180ms steps(3) backwards; } +.title span { flex: 1; } +.x { position: relative; width: 22px; height: 22px; background: #fff; border: 2px solid #000; color: #000; font-size: 15px; + line-height: 20px; text-align: center; font-family: Consolas, monospace; font-weight: 700; cursor: pointer; + transition-property: background-color, color, transform; transition-duration: 80ms; transition-timing-function: ease-out; } +.x::after { content: ''; position: absolute; left: -9px; top: -9px; right: -9px; bottom: -9px; } /* a 40 px hit area */ +.x:hover { background: #000; color: #fff; } +.x:active { transform: scale(0.96); } +/* a closed warning: quick, accelerating, a little shrink; it stays invisible until the next action */ +.closing { animation: close 140ms cubic-bezier(0.3, 0, 1, 1) forwards; pointer-events: none; } +@keyframes close { to { opacity: 0; transform: scale(0.92); } } +.msg { padding: 18px 18px 0 22px; font-size: 22px; color: #111; letter-spacing: -0.3px; } +.ok { display: flex; align-items: center; justify-content: center; margin: 14px 18px 0 auto; width: 92px; height: 26px; + background: #cdcdcd; color: #111; font-size: 14px; cursor: pointer; + box-shadow: inset 2px 2px 0 #fff, inset -2px -2px 0 #7b7b7b, 0 0 0 1px #000; } +.ok:active { box-shadow: inset -2px -2px 0 #fff, inset 2px 2px 0 #7b7b7b, 0 0 0 1px #000; padding-top: 2px; } + +/* -- sticker captions and stars -- */ +.sticker { padding: 7px 16px 9px; background: #1414ff; color: #fff; font-size: 21px; letter-spacing: 0.2px; + border: 2px solid #fff; box-shadow: 0 0 0 2px #000, 4px 4px 0 2px #000; white-space: nowrap; + animation: snap 200ms cubic-bezier(0.2, 0, 0, 1) backwards; } +.spin { animation: spin 14s linear infinite; } +.star { width: 70px; height: 70px; background: #1414ff; + clip-path: polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%); + animation: star 280ms cubic-bezier(0.2, 0, 0, 1) backwards; } + +/* -- the kernel panic billboard -- */ +.term { width: 440px; padding: 16px 18px; background: #050505; + border: 6px solid #f2f2f2; box-shadow: 0 0 0 2px #000, 8px 8px 0 2px #000; + color: #eaeaea; font-family: Consolas, monospace; font-size: 10.5px; line-height: 1.45; + animation: crt 320ms cubic-bezier(0.2, 0, 0, 1) backwards; } +.term div { animation: line 90ms ease-out backwards; white-space: nowrap; overflow: hidden; } +.cursor { display: inline-block; width: 7px; height: 12px; background: #eaeaea; animation: blink 1s steps(2) infinite; } + +/* -- motion. Entrances decelerate; the overshoot is in the keyframes, so every pop lands the same. + `backwards` fill: a finished pop drops its transform and is a plain box again (no layer) -- */ +@keyframes pop { 0% { opacity: 0; transform: translate(-16px, 22px) scale(0.5); } + 55% { opacity: 1; transform: translate(2px, -3px) scale(1.07); } + 78% { transform: translate(0, 0) scale(0.98); } + 100% { opacity: 1; transform: translate(0, 0) scale(1); } } +@keyframes shade { 0% { opacity: 0; transform: translate(-7px, -7px); } 100% { opacity: 1; transform: translate(0, 0); } } +@keyframes flicker { 0% { opacity: 0; } 50% { opacity: 1; } 75% { opacity: 0.35; } 100% { opacity: 1; } } +@keyframes snap { 0% { opacity: 0; transform: scale(0.3) rotate(-14deg); } + 60% { opacity: 1; transform: scale(1.12) rotate(3deg); } + 100% { opacity: 1; transform: scale(1) rotate(0deg); } } +@keyframes star { 0% { opacity: 0; transform: scale(0) rotate(-120deg); } + 65% { opacity: 1; transform: scale(1.2) rotate(10deg); } + 100% { opacity: 1; transform: scale(1) rotate(0deg); } } +@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } +@keyframes crt { 0% { opacity: 0; transform: scale(1.15, 0.02); } + 45% { opacity: 1; transform: scale(1.02, 0.06); } + 100% { opacity: 1; transform: scale(1, 1); } } +@keyframes line { from { opacity: 0; transform: translateX(-6px); } to { opacity: 1; transform: translateX(0); } } +@keyframes blink { from { opacity: 1; } to { opacity: 0; } } +/* two names for one shake, alternated per click, so each click restarts it */ +@keyframes shakeA { 0% { transform: translate(0, 0); } 20% { transform: translate(-7px, 3px); } 45% { transform: translate(6px, -2px); } + 70% { transform: translate(-3px, 1px); } 100% { transform: translate(0, 0); } } +@keyframes shakeB { 0% { transform: translate(0, 0); } 20% { transform: translate(-7px, 3px); } 45% { transform: translate(6px, -2px); } + 70% { transform: translate(-3px, 1px); } 100% { transform: translate(0, 0); } } +.shake0 { animation: shakeA 320ms ease-in-out; } .shake1 { animation: shakeB 320ms ease-in-out; } +/* the panic a new one replaces: out faster than it came in, accelerating, falling a little */ +.out { animation: out 160ms cubic-bezier(0.3, 0, 1, 1) forwards; } +@keyframes out { to { opacity: 0; transform: translateY(12px) scale(0.97); } } +"; + +const MESSAGES: [&str; 5] = ["Wake. Up. You.", "Still loading you.", "Fatal: too much.", "Retry? Never.", "Not responding."]; +const STICKERS: [&str; 10] = ["wake up.", "ctrl+z yea", "re==L00d", "// ignore", "overheat.", "한숨 (ah!)", + "404 feelings", "sudo stay", "brb rebooting", "not responding"]; +const TILTS: [f32; 6] = [-6.0, 4.0, -3.0, 7.0, -8.0, 5.0]; +const KERNEL: [&str; 12] = [ + "BUG: unable to handle kernel paging request at ffff88014b4a0000", + "IP: __memmove+0x24/0x1a0", + "PGD 21f4067 P4D 21f4067 PUD 21f7067", + "PMD 10059b063 PTE 800000014b4a0161", + "Oops: 0003 [#1] SMP", + "Modules linked in: coretemp kvm_intel kvm irqbypass snd_hda_intel", + " crct10dif_pclmul crc32_pclmul ghash_clmulni_intel iTCO_wdt", + "CPU: 2 PID: 494 Comm: loadkeys Not tainted 4.11.8-1-ARCH", + "task: ffff880151149600 task.stack: ffffc90000c3c000", + "RIP: 0010:__memmove+0x24/0x1a0", + "RSP: 0018:ffffc90000c3fe18 EFLAGS: 00010282", + "Kernel panic - not syncing: Fatal exception", +]; +const WINDOWS: usize = 5; + +/// Places an absolutely positioned element. +fn at(d: Div, x: f32, y: f32) -> Div { + d.css("left", format!("{x}px")).css("top", format!("{y}px")) +} + +/// Starts an element's entrance `ms` after it appears (each element keeps its own clock). +fn after(d: Div, ms: usize) -> Div { + d.css("animation-delay", format!("{ms}ms")) +} + +/// A cheap, deterministic scatter in 0..1 (the golden-ratio sequence), so nothing repeats a spot. +fn scatter(k: u32, phase: f32) -> f32 { + (k as f32 * 0.618_034 + phase).fract() +} + +/// One warning dialog. `id` keys its elements, so each keeps its own animation clock. +struct Warning { + id: u32, + x: f32, + y: f32, + /// Entrance delay (a cascade staggers its windows). + delay: usize, + /// Whether the body shows a message (a cascade's back windows show only their title bars). + message: bool, + /// Closed: playing its exit, gone at the next action. + closing: bool, +} + +impl Warning { + fn view(&self, cx: &mut Context) -> Div { + let (id, delay) = (self.id, self.delay); + // ✕ and OK both work... and open another warning. They stop the click there, or it would + // reach the wall and start a cascade too. + let dismiss = |d: Div| d.attr("role", "button").on_click(cx.listener(move |this, _, _, cx| { + cx.stop_propagation(); + this.close(id, cx); + })); + let mut b = after(div().class("box"), delay) + .child(after(div().class("title"), delay) + .child(span().child("Windows Failed")) + .child(dismiss(div().id(format!("x{id}")).class("x").attr("aria-label", "Close").child("✕")))); + if self.message { + b = b.child(div().class("msg").child(MESSAGES[id as usize % MESSAGES.len()])) + .child(dismiss(div().id(format!("ok{id}")).class("ok").child("OK"))); + } + // a z-index per warning, rising: BUI then paints each warning's subtree (its text too) as one + // run, in order. Without it a lower warning's text drew over the boxes of the ones above it + at(div().id(format!("w{id}")).class(if self.closing { "win closing" } else { "win" }), self.x, self.y) + .css("z-index", format!("{}", id + 1)) + .child(after(div().class("shade"), delay + 40)) + .child(b) + } +} + +/// A kernel panic: the terminal, sticker captions over it and a star, popping up at a random +/// place and tilt from time to time. `n` keys its elements and seeds it. +struct Panic { + n: u32, + x: f32, + y: f32, + tilt: f32, +} + +impl Panic { + fn new(n: u32) -> Self { + Self { n, x: 20.0 + scatter(n, 0.2) * 560.0, y: 40.0 + scatter(n * 7, 0.65) * 470.0, tilt: -8.0 + scatter(n * 3, 0.4) * 13.0 } + } + + /// `leaving`: the panic a new one replaced, on its way out (invisible until the next). + fn view(&self, leaving: bool) -> Div { + let (n, x, y) = (self.n, self.x, self.y); + let mut term = div().class("term"); + for (i, l) in KERNEL.iter().enumerate() { + term = term.child(after(div(), 200 + i * 22).child(*l)); + } + term = term.child(after(div(), 200 + KERNEL.len() * 22).child(span().class("cursor"))); + let mut out = div().id(format!("p{n}")).class(if leaving { "stage out" } else { "stage" }) + .child(at(div().id(format!("p{n}t")).class("place"), x, y).css("transform", format!("rotate({}deg)", self.tilt)) + .child(term)); + // captions land on the terminal once it is on, then the star on its corner + let spots = [(250.0, 150.0), (420.0, 160.0), (300.0, 222.0)]; + for (k, (dx, dy)) in spots.into_iter().enumerate() { + let s = n as usize * 3 + k; + let tilt = TILTS[s % TILTS.len()]; + out = out.child(at(div().id(format!("p{n}s{k}")).class("place"), x + dx, y + dy) + .css("transform", format!("rotate({tilt}deg)")) + .child(after(div().class("sticker"), 420 + k * 35).child(STICKERS[s % STICKERS.len()]))); + } + out.child(at(div().id(format!("p{n}star")).class("place"), x + 230.0, y - 30.0) + .child(div().class("spin").child(after(div().class("star"), 560)))) + } +} + +struct Failed { + wall: Fx, + /// In paint order: the newest on top. + warnings: Vec, + panic: Option, + leaving: Option, + /// When the next panic pops up (`now()`); none until the first click. + next_panic: Option, + /// Cascades opened (each one's position comes from it). + cascades: u32, + /// Warnings opened, ever: the next warning's id. + opened: u32, + clicked: Option, +} + +impl Failed { + /// Every action starts here: what was closing by now has finished its exit, and goes. + fn act(&mut self) { + self.warnings.retain(|w| !w.closing); + self.clicked = Some(now()); + } + + fn open(&mut self, x: f32, y: f32, delay: usize, message: bool) { + self.warnings.push(Warning { id: self.opened, x, y, delay, message, closing: false }); + self.opened += 1; + } + + /// A panic replaces the last one; the next comes 2.5 to 6 s later. + fn panic(&mut self) { + let n = self.panic.as_ref().map_or(1, |p| p.n + 1); + self.leaving = self.panic.replace(Panic::new(n)); + self.next_panic = Some(now() + 2.5 + 3.5 * scatter(n, 0.9)); + } + + /// A click on the wall. The first is a cascade of five, and starts the panics; every later one + /// is one more warning, somewhere else. + fn wall_click(&mut self, cx: &mut Context) { + if self.cascades > 0 { + self.act(); + self.spawn(); + cx.notify(); + return; + } + self.act(); + self.cascades += 1; + let k = self.cascades; + let (x, y) = (150.0 + scatter(k, 0.0) * 300.0, 80.0 + scatter(k, 0.3) * 170.0); + for i in 0..WINDOWS { + self.open(x + i as f32 * 24.0, y + i as f32 * 30.0, i * 60, i + 1 == WINDOWS); + } + if self.next_panic.is_none() { + self.panic(); + } + cx.notify(); + } + + /// ✕ or OK: that warning closes, and another one opens somewhere else. + fn close(&mut self, id: u32, cx: &mut Context) { + self.act(); + if let Some(w) = self.warnings.iter_mut().find(|w| w.id == id) { + w.closing = true; + } + self.spawn(); + cx.notify(); + } + + /// One warning, popping up at a spot the last ones didn't use. + fn spawn(&mut self) { + let k = self.opened; + self.open(60.0 + scatter(k, 0.11) * 560.0, 40.0 + scatter(k * 3, 0.47) * 420.0, 0, true); + } +} + +impl Render for Failed { + fn render(&mut self, w: &mut Window, cx: &mut Context) -> impl IntoElement { + w.request_animation_frame(); + if self.next_panic.is_some_and(|t| now() >= t) { + self.panic(); + } + let clicked = self.clicked; + let wall = self.wall.canvas(move |_| { + let t = now(); + [t, clicked.map_or(-1.0, |c| t - c)] + }).class("wall"); + let words = [("IOI", 860.0, 30.0, 150.0, 0.0), ("DaLE", 880.0, 236.0, 92.0, 4.0), ("NEVATI", 690.0, 410.0, 118.0, -3.0), + ("UPLINK", 705.0, 535.0, 96.0, 2.0), ("ERRO", 760.0, 650.0, 130.0, -1.0)]; + // the shake restarts on every action: its two identical keyframes alternate + let mut stage = div().class(if self.opened == 0 { "stage".to_string() } else { format!("stage shake{}", self.opened % 2) }); + for (word, x, y, size, tilt) in words { + stage = stage.child(at(div().class("type"), x, y) + .css("font-size", format!("{size}px")).css("transform", format!("rotate({tilt}deg)")).child(word)); + } + if let Some(p) = &self.leaving { + stage = stage.child(p.view(true)); + } + if let Some(p) = &self.panic { + stage = stage.child(p.view(false)); + } + for warning in &self.warnings { + stage = stage.child(warning.view(cx)); + } + // no UI: a click anywhere on the wall starts it (and starts another cascade) + html() + .child(head().child(style().child(CSS))) + .child(body().id("wall").child(wall).child(stage) + .on_click(cx.listener(|this, _, _, cx| this.wall_click(cx)))) + } +} + +/// Clicks through the demo in a headless window and saves frames along the virtual clock: a +/// cascade (and the first panic), closing warnings with ✕ and OK (each opens another), then +/// more clicks on the wall (one warning each). +fn storyboard(dir: String) -> Script { + Box::new(move |cx, win| { + let shot = |cx: &mut App, name: &str| { + let (w, h, px) = cx.draw(win); + save_png(&format!("{dir}/{name}.png"), w, h, &px); + }; + let click = |cx: &mut App, id: &str| { + let b = cx.element_bounds(win, id).unwrap_or_else(|| panic!("no #{id}")); + cx.simulate_click(win, b.origin.x + b.size.width / 2.0, b.origin.y + b.size.height / 2.0); + }; + let play = |cx: &mut App, name: &str, steps: &[u64]| { + let mut at = 0; + for &ms in steps { + cx.advance_clock(Duration::from_millis(ms - at)); + at = ms; + shot(cx, &format!("{name}-{ms:04}ms")); + } + }; + let wall = |cx: &mut App| cx.simulate_click(win, 1060.0, 790.0); + shot(cx, "00-idle"); + wall(cx); + play(cx, "01-cascade", &[0, 40, 90, 150, 220, 300, 380, 460, 600, 1000]); + // close the front warning (id 4) with ✕: it goes, warning 5 pops up elsewhere + click(cx, "x4"); + play(cx, "02-close", &[0, 60, 120, 200, 400]); + // OK works the same, and neither starts a cascade + for id in 5..=8 { + click(cx, &format!("{}{id}", if id % 2 == 1 { "ok" } else { "x" })); + cx.advance_clock(Duration::from_millis(500)); + } + shot(cx, "03-after-closing-5"); + // later clicks on the wall: one warning each, no cascade + wall(cx); + play(cx, "04-wall-again", &[0, 80, 400]); + wall(cx); + wall(cx); + cx.advance_clock(Duration::from_millis(500)); + shot(cx, "05-wall-three-times"); + }) +} + +fn wall() -> Fx { + Fx::new("wall", WALL, 2, [16, 16, 240]) +} + +fn main() { + if let Some(dir) = arg("--frames") { + let fx = wall(); + let stills = [("wall", [3.0f32, -1.0]), ("wall-glitch", [3.1, 0.12])]; + if gpu_stills(&dir, 1100, 800, stills, |g, f| g.draw(fx.effect(), &[], f)).is_none() { + eprintln!("wall shader: {:?}", fx.error()); + } + return; + } + let make = || Failed { wall: wall(), warnings: Vec::new(), panic: None, leaving: None, next_panic: None, cascades: 0, opened: 0, clicked: None }; + run_with(1100.0, 800.0, "BUI · Windows Failed", make, arg("--storyboard").map(storyboard)); +} diff --git a/demos/src/bin/gambit.rs b/demos/src/bin/gambit.rs new file mode 100644 index 00000000..8365ee3e --- /dev/null +++ b/demos/src/bin/gambit.rs @@ -0,0 +1,567 @@ +//! Gambit: a noir chess collage, rendered by GPU shaders on BUI. A marble queen hangs over a +//! chessboard in perspective, a pawn rocks on its rim, poker chips tumble, chains sway, and it all +//! sits on drifting halftone smoke. There is no UI: a click anywhere is a move, which lifts the +//! queen and slams her down: a flash, a shock ring through the dots, the pawn knocked flat (it +//! gets back up), the chips spun up. +//! +//! Two passes: the raymarched scene at `SCENE_RES` into a render target, then a full-resolution +//! composite (halftone, sparkles, grade) that samples it. Everything that changes per frame (each +//! piece's position, every rotation's sine and cosine, the move's curves) is computed once here on +//! the CPU and handed to the shaders as floats, named by `slots!`. +//! +//! `cargo run --release --bin gambit` +//! `-- --frames DIR` renders frames off-screen on the GPU to DIR and times the passes (no window); + +use std::fmt::Write as _; +use std::rc::Rc; + +use blenderui::prelude::*; +use blenderui::{GpuTarget, RenderTarget, TargetFormat}; +use bui_demos::{arg, gpu_stills, now, run, Fx}; + +/// Declares the shader floats once: the Rust indices (`Slot::QY as usize`) and the GLSL names +/// (`#define QY U[4]`) come from the same list. +macro_rules! slots { + ($($name:ident),* $(,)?) => { + #[derive(Clone, Copy)] + #[allow(clippy::upper_case_acronyms)] + enum Slot { $($name),* } + const SLOT_NAMES: &[&str] = &[$(stringify!($name)),*]; + }; +} + +slots!( + T, SHOCK, FLASH, // time, seconds since the queen landed (< 0: never), the landing's flash + QX, QY, QZ, QC, QS, QYC, QYS, // queen: position, tilt (cos, sin), turn + HC, HS, HPC, HPS, HYC, HYS, // hanging piece: sway, its tilt and turn + FY, FC, FS, // the far piece: height, roll + BC, BS, // the board pawn's lean + C0Y, C1Y, C2Y, C0C, C0S, C1C, C1S, C2C, C2S, C0YC, C0YS, C1YC, C1YS, C2YC, C2YS, CBC, CBS, // chips + GC, GS, GBEND, // the foreground chain: swing and bend + KY, KC, KS, // crown + LX, LY, LZ, // light direction + CX, CY, CZ, // camera position + MARCH, REFLECT, SHADOWS, BOUNCES, TAPS, // loop bounds (see `Pose::at`) +); +const N: usize = SLOT_NAMES.len(); + +/// The scene pass's resolution: the raymarch runs at this size, the composite at the window's. +const SCENE_RES: (u32, u32) = (800, 450); + +// A move is `age` seconds old (< 0: none yet). The queen lifts for 0.22 s (ease-out), then drops +// onto a damped spring and lands at IMPACT. +const IMPACT: f32 = 0.34; + +fn slam(age: f32) -> f32 { + if age < 0.0 { + return 0.0; + } + if age < 0.22 { + let u = age / 0.22; + return 0.45 * (1.0 - (1.0 - u) * (1.0 - u)); + } + let a = age - 0.22; + 0.45 * (-a * 3.2).exp() * (a * 13.0).cos() - 0.35 * (-a * 2.4).exp() * (a * 13.0).min(std::f32::consts::PI).sin() +} + +fn settle(age: f32) -> f32 { + if age < 0.0 { 0.0 } else { 1.0 - (-age * 1.6).exp() } +} + +fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { + let u = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); + u * u * (3.0 - 2.0 * u) +} + +/// The board pawn, knocked over at impact (a gravity ease-in, a small bounce), up again after 4 s. +fn topple(age: f32) -> f32 { + if age < IMPACT { + return 0.0; + } + let a = age - IMPACT; + let down = (a / 0.42).clamp(0.0, 1.0).powi(2); + let b = (a - 0.42).max(0.0); + let bounce = 0.12 * (-b * 7.0).exp() * (b * 16.0).sin().abs(); + (down - bounce) * (1.0 - smoothstep(4.0, 5.6, a)) +} + +/// Every shader float for time `t` and a move `age` seconds old. +struct Pose([f32; N]); + +impl Pose { + const fn set(&mut self, s: Slot, v: f32) { + self.0[s as usize] = v; + } + + fn turn(&mut self, c: Slot, s: Slot, angle: f32) { + let (sin, cos) = angle.sin_cos(); + self.set(c, cos); + self.set(s, sin); + } + + fn at(t: f32, age: f32) -> Self { + let mut u = Self([0.0; N]); + let since = if age >= IMPACT { age - IMPACT } else { -1.0 }; + u.set(Slot::T, t); + u.set(Slot::SHOCK, since); + u.set(Slot::FLASH, if since >= 0.0 { (-since * 7.0).exp() } else { 0.0 }); + // the queen breathes and turns; a move lifts and slams her + let slm = slam(age); + u.set(Slot::QX, -0.5); + u.set(Slot::QY, 1.55 + 0.1 * (t * 0.55).sin() + slm); + u.set(Slot::QZ, -1.55); + u.turn(Slot::QC, Slot::QS, 0.17 + 0.03 * (t * 0.4).sin() - 0.08 * slm); + u.turn(Slot::QYC, Slot::QYS, t * 0.12); + // the hanging piece swings on its chain + let sw = 0.12 * (t * 0.7).sin(); + u.turn(Slot::HC, Slot::HS, sw); + u.turn(Slot::HPC, Slot::HPS, 2.6 + sw * 0.5); + u.turn(Slot::HYC, Slot::HYS, -t * 0.2); + u.set(Slot::FY, 3.85 + 0.15 * (t * 0.3 + 1.0).sin()); + u.turn(Slot::FC, Slot::FS, 1.9 + t * 0.05); + // the board pawn rocks on its rim until a move knocks it flat + let lean = 0.55 + 0.08 * (t * 1.3).sin(); + u.turn(Slot::BC, Slot::BS, lean + (1.3 - lean) * topple(age)); + // chips bob and turn; a move spins them up + let spin = t * 0.9 + 9.0 * settle(age); + for (i, (y, (c, s), (yc, ys))) in [ + (Slot::C0Y, (Slot::C0C, Slot::C0S), (Slot::C0YC, Slot::C0YS)), + (Slot::C1Y, (Slot::C1C, Slot::C1S), (Slot::C1YC, Slot::C1YS)), + (Slot::C2Y, (Slot::C2C, Slot::C2S), (Slot::C2YC, Slot::C2YS)), + ].into_iter().enumerate() { + let f = i as f32; + u.set(y, 1.55 - 0.47 * f + 0.06 * (t * 0.8 + f * 2.0).sin()); + u.turn(c, s, 0.5 + 0.4 * f + 0.15 * (t * 0.5 + f).sin()); + u.turn(yc, ys, spin * (1.0 + 0.3 * f)); + } + u.turn(Slot::CBC, Slot::CBS, t * 0.1); + u.turn(Slot::GC, Slot::GS, 2.38 + 0.05 * (t * 0.6).sin()); + u.set(Slot::GBEND, 0.1 * (t * 0.5).sin()); + u.set(Slot::KY, 2.25 + 0.06 * (t * 0.7).sin()); + u.turn(Slot::KC, Slot::KS, t * 0.3); + // the key light drifts; the camera dollies in on first light, then breathes + let l = [-0.55 + 0.35 * (t * 0.17).sin(), 0.85, -0.3f32]; + let n = (l[0] * l[0] + l[1] * l[1] + l[2] * l[2]).sqrt(); + u.set(Slot::LX, l[0] / n); + u.set(Slot::LY, l[1] / n); + u.set(Slot::LZ, l[2] / n); + let intro = (1.0 - smoothstep(0.0, 4.0, t)).powi(2); + u.set(Slot::CX, 0.3 + 0.3 * (t * 0.09).sin()); + u.set(Slot::CY, 2.3 + 0.08 * (t * 0.21).sin() + 0.4 * intro); + u.set(Slot::CZ, -7.0 + 0.3 * (t * 0.06).sin() - 2.2 * intro); + // Loop bounds come in as floats, not literals. Direct3D compiles effects at its top + // optimization level: it inlines every call and unrolls every loop it can count, so each + // `map` call site and each counted step became another copy of the whole scene (33 s to + // the first frame). Bounds it can't see stay loops; with one march, one normal tap and + // one shadow loop there are four copies of `map` in all. + u.set(Slot::MARCH, 72.0); + u.set(Slot::REFLECT, 28.0); + u.set(Slot::SHADOWS, 14.0); + u.set(Slot::BOUNCES, 2.0); + u.set(Slot::TAPS, 4.0); + u + } +} + +/// Shared by both passes. +const NOISE: &str = r" +float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); } +float vnoise(vec2 p) { + vec2 i = floor(p); vec2 f = fract(p); f = f * f * (3.0 - 2.0 * f); + return mix(mix(hash(i), hash(i + vec2(1.0, 0.0)), f.x), mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), f.x), f.y); +} +float fbm(vec2 p) { + float s = 0.0; float a = 0.5; + for (int i = 0; i < 5; i++) { s += a * vnoise(p); p = p * 2.03 + vec2(1.7, 9.2); a *= 0.5; } + return s; +} +"; + +const SCENE: &str = r" +float smin(float a, float b, float k) { float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0); return mix(b, a, h) - k * h * (1.0 - h); } +// rotations by a (cos, sin) from the CPU; rotx/rotz with a literal angle fold to constants +vec3 rz(vec3 p, float c, float s) { return vec3(c * p.x - s * p.y, s * p.x + c * p.y, p.z); } +vec3 ry(vec3 p, float c, float s) { return vec3(c * p.x + s * p.z, p.y, -s * p.x + c * p.z); } +vec3 rotx(vec3 p, float a) { float c = cos(a); float s = sin(a); return vec3(p.x, c * p.y - s * p.z, s * p.y + c * p.z); } +vec3 rotz(vec3 p, float a) { return rz(p, cos(a), sin(a)); } +vec3 roty(vec3 p, float a) { return ry(p, cos(a), sin(a)); } +float box2(vec2 p, vec2 b, float r) { vec2 d = abs(p) - b + r; return length(max(d, vec2(0.0))) + min(max(d.x, d.y), 0.0) - r; } +float box3(vec3 p, vec3 b, float r) { vec3 d = abs(p) - b + r; return length(max(d, vec3(0.0))) + min(max(d.x, max(d.y, d.z)), 0.0) - r; } +float trap(vec2 p, float r1, float r2, float he) { + vec2 k1 = vec2(r2, he); vec2 k2 = vec2(r2 - r1, 2.0 * he); + p.x = abs(p.x); + vec2 ca = vec2(p.x - min(p.x, (p.y < 0.0) ? r1 : r2), abs(p.y) - he); + vec2 cb = p - k1 + k2 * clamp(dot(k1 - p, k2) / dot(k2, k2), 0.0, 1.0); + float s = (cb.x < 0.0 && ca.y < 0.0) ? -1.0 : 1.0; + return s * sqrt(min(dot(ca, ca), dot(cb, cb))); +} +vec3 sector(vec3 p, float n) { + float sec = 6.2831853 / n; float a = atan2(p.z, p.x); + float an = mod(a + sec * 0.5, sec) - sec * 0.5; float r = length(p.xz); + return vec3(cos(an) * r, p.y, sin(an) * r); +} + +float pawn(vec3 p) { + vec2 q = vec2(length(p.xz), p.y); + float d = box2(q - vec2(0.0, 0.08), vec2(0.42, 0.08), 0.04); + d = smin(d, length(q - vec2(0.37, 0.2)) - 0.07, 0.05); + d = smin(d, trap(q - vec2(0.0, 0.55), 0.3, 0.12, 0.35), 0.08); + d = smin(d, box2(q - vec2(0.0, 0.92), vec2(0.25, 0.035), 0.03), 0.05); + d = smin(d, length(q - vec2(0.0, 1.17)) - 0.24, 0.05); + return d; +} +float queen(vec3 p) { + vec2 q = vec2(length(p.xz), p.y); + float d = box2(q - vec2(0.0, 0.09), vec2(0.52, 0.09), 0.05); + d = smin(d, length(q - vec2(0.44, 0.24)) - 0.08, 0.05); + d = smin(d, box2(q - vec2(0.0, 0.36), vec2(0.4, 0.04), 0.03), 0.05); + d = smin(d, trap(q - vec2(0.0, 0.95), 0.34, 0.13, 0.6), 0.12); + d = smin(d, box2(q - vec2(0.0, 1.58), vec2(0.31, 0.035), 0.03), 0.06); + d = smin(d, box2(q - vec2(0.0, 1.68), vec2(0.24, 0.03), 0.03), 0.04); + d = smin(d, trap(q - vec2(0.0, 1.92), 0.15, 0.31, 0.2), 0.06); + // the coronet's points (an angle per sample: only near the top) + if (p.y > 1.8) d = smin(d, length(sector(p, 8.0) - vec3(0.29, 2.14, 0.0)) - 0.065, 0.04); + return min(d, length(q - vec2(0.0, 2.3)) - 0.1); +} +float chip(vec3 p) { + vec2 d = abs(vec2(length(p.xz), p.y)) - vec2(0.45, 0.04); + return min(max(d.x, d.y), 0.0) + length(max(d, vec2(0.0))) - 0.012; +} +float chipInk(vec3 p) { + float a = atan2(p.z, p.x); float r = length(p.xz); + float edge = step(0.5, fract(a * 6.0 / 6.2831853)) * step(0.33, r); + float ring = step(abs(r - 0.27), 0.025); + return max(edge, ring); +} +float clink(vec3 p) { + vec3 q = vec3(p.x, max(abs(p.y) - 0.13, 0.0), p.z); + return length(vec2(length(q.xy) - 0.17, q.z)) - 0.045; +} +// links along +y from 0 to len, every other one turned a quarter; whole links only, never cut +float chain(vec3 p, float len) { + float ca = floor(p.y + 0.5); float cb = floor(p.y) + 0.5; + float da = ca >= 0.0 && ca <= len ? clink(vec3(p.x, p.y - ca, p.z)) : 1e3; + float db = cb >= 0.0 && cb <= len ? clink(vec3(p.z, p.y - cb, p.x)) : 1e3; + return max(min(da, db), max(-p.y - 0.4, p.y - len - 0.4)); +} +// a court card's face: an inner frame, a large diamond pip and two corner pips +float cardInk(vec2 c) { + vec2 a = abs(c); + float frame = step(abs(max(a.x - 0.25, a.y - 0.39)), 0.008); + float pip = step(a.x / 0.11 + a.y / 0.16, 1.0); + vec2 k = vec2(a.x - 0.25, a.y - 0.39); + float corner = step(abs(k.x) / 0.03 + abs(k.y) / 0.045, 1.0) * step(0.0, c.x * c.y); + return max(max(frame, pip), corner); +} +float crown(vec3 p) { + vec2 q = vec2(length(p.xz), p.y); + float d = box2(q - vec2(0.32, 0.08), vec2(0.03, 0.08), 0.02); + vec3 c = sector(p, 6.0); + vec3 pa = c - vec3(0.32, 0.14, 0.0); vec3 ba = vec3(0.05, 0.3, 0.0); + float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0); + d = min(d, length(pa - ba * h) - mix(0.05, 0.012, h)); + return min(d, length(c - vec3(0.375, 0.47, 0.0)) - 0.04); +} + +vec2 opU(vec2 a, vec2 b) { return a.x < b.x ? a : b; } +// the distance to a segment from the origin along `d`, `len` long: a capsule's core +float seg(vec3 q, vec3 d, float len) { return length(q - d * clamp(dot(q, d), 0.0, len)); } + +vec2 chipAt(vec3 p, vec3 c, float zc, float zs, float tilt, float yc, float ys) { + vec3 q = p - c; + float b = length(q) - 0.3; + if (b > 0.2) return vec2(b, 3.0); + q = ry(rotx(rz(q, zc, zs), tilt), yc, ys) / 0.55; + return vec2(chip(q) * 0.55, 3.0 + 0.5 * chipInk(q)); +} + +// Each object is first a cheap bound around its pivot; it is turned and measured only when near. +vec2 map(vec3 p) { + vec2 res = vec2(1e5, 0.0); + // the queen (material 1: white marble) + vec3 q = p - vec3(QX, QY, QZ); + float b = length(q - vec3(0.15, 1.1, 0.0)) - 1.6; + res = opU(res, vec2(b > 0.2 ? b : queen(ry(rotx(rz(q, QC, QS), -0.1), QYC, QYS) / 0.95) * 0.95, 1.0)); + // the hanging piece and its chain (4: metal) + vec3 h = rz(p - vec3(2.0, 4.9, 1.0), HC, HS); + vec3 k = -rotz(h, 0.62); + b = seg(k, vec3(0.0, 1.0, 0.0), 2.1) - 0.35; + res = opU(res, vec2(b > 0.2 ? b : chain(k / 0.8, 2.6) * 0.8, 4.0)); + q = h - vec3(1.25, -2.05, 0.0); + b = length(q) - 1.75; + res = opU(res, vec2(b > 0.2 ? b : pawn(ry(rz(q, HPC, HPS), HYC, HYS) / 1.1) * 1.1, 1.0)); + // the far piece (2: dark marble) + q = p - vec3(0.95, FY, 3.2); + b = length(q) - 1.6; + res = opU(res, vec2(b > 0.2 ? b : pawn(rotx(rz(q, FC, FS), 0.4) / 0.85) * 0.85, 2.0)); + // the pawn on the board, leaning on its rim + q = p - vec3(1.1, 0.0, 1.0); + b = length(q - vec3(0.0, 0.45, 0.0)) - 1.2; + res = opU(res, vec2(b > 0.2 ? b : pawn((rz(q - vec3(0.33, 0.0, 0.0), BC, BS) + vec3(0.33, 0.0, 0.0)) / 0.75) * 0.75, 1.0)); + // poker chips (3, ink in the fraction) + res = opU(res, chipAt(p, vec3(2.35, C0Y, -1.5), C0C, C0S, 1.25, C0YC, C0YS)); + res = opU(res, chipAt(p, vec3(2.63, C1Y, -1.35), C1C, C1S, 1.0, C1YC, C1YS)); + res = opU(res, chipAt(p, vec3(2.51, C2Y, -1.2), C2C, C2S, 0.75, C2YC, C2YS)); + q = p - vec3(1.9, 0.025, -0.4); + b = length(q) - 0.3; + if (b > 0.2) res = opU(res, vec2(b, 3.0)); + else { q = ry(q, CBC, CBS) / 0.55; res = opU(res, vec2(chip(q) * 0.55, 3.0 + 0.5 * chipInk(q))); } + // the foreground chain, bottom left, bending as it sways + q = p - vec3(-2.3, 2.3, -3.0); + b = seg(q, vec3(0.69, -0.723, 0.0), 2.7) - 0.4; + if (b > 0.2) res = opU(res, vec2(b, 4.0)); + else { q = rz(q, GC, GS); q = rotz(q, GBEND * q.y); res = opU(res, vec2(chain(q / 0.6, 4.4) * 0.48, 4.0)); } + // crown (4) and card (5, ink in the fraction) + q = p - vec3(-1.95, KY, -1.5); + b = length(q) - 1.0; + if (b > 0.2) return opU(res, vec2(b, 5.0)); + res = opU(res, vec2(crown(ry(rotz(rotx(q, 0.35), -0.3), KC, KS)), 4.0)); + vec3 cd = rotz(roty(q - vec3(-0.25, -0.35, 0.25), -0.35), 0.35); + return opU(res, vec2(box3(cd, vec3(0.32, 0.46, 0.008), 0.03), 5.0 + 0.5 * cardInk(cd.xy))); +} + +// the tetrahedral gradient, as a loop: one `map` in the compiled shader, not four +vec3 normalAt(vec3 p) { + vec3 n = vec3(0.0); + for (int k = 0; k < int(TAPS); k++) { + float f = float(k); + vec3 e = 2.0 * vec3(mod(floor((f + 3.0) * 0.5), 2.0), mod(floor(f * 0.5), 2.0), mod(f, 2.0)) - 1.0; + n += e * map(p + e * 0.0015).x; + } + return normalize(n); +} + +float march(vec3 ro, vec3 rd, float tmax, int steps, out float id) { + float t = 0.05; id = -1.0; + for (int i = 0; i < steps; i++) { + vec2 h = map(ro + rd * t); + if (h.x < 0.002 * t) { id = h.y; return t; } + t += h.x * 0.9; + if (t > tmax) break; + } + return -1.0; +} + +float shadow(vec3 ro, vec3 rd) { + float r = 1.0; float t = 0.06; + for (int i = 0; i < int(SHADOWS); i++) { + float h = map(ro + rd * t).x; + r = min(r, 9.0 * h / t); + t += clamp(h, 0.08, 0.5); + if (r < 0.01 || t > 6.0) break; + } + return clamp(r, 0.0, 1.0); +} + +float shade(vec3 p, vec3 n, vec3 rd, float id) { + vec3 L = vec3(LX, LY, LZ); + float dif = clamp(dot(n, L), 0.0, 1.0); + float bac = clamp(dot(n, normalize(vec3(0.7, 0.2, 0.8))), 0.0, 1.0); + float fre = pow(1.0 - clamp(dot(n, -rd), 0.0, 1.0), 3.0); + float spe = pow(clamp(dot(n, normalize(L - rd)), 0.0, 1.0), 60.0); + float alb = 0.8; float gloss = 0.8; + if (id < 1.5) { vec2 m = p.xy * 3.0 + p.z * 2.0; alb = 0.95 - 0.25 * smoothstep(0.55, 0.8, 0.55 * vnoise(m) + 0.3 * vnoise(m * 2.1) + 0.15 * vnoise(m * 4.3)); } + else if (id < 2.5) { alb = 0.34; gloss = 0.6; } + else if (id < 3.75) { alb = id > 3.25 ? 0.88 : 0.16; gloss = 0.5; } + else if (id < 4.5) { alb = 0.55; gloss = 1.8; } + else { alb = id > 5.25 ? 0.12 : 0.95; gloss = 0.3; } + float ao = clamp(map(p + n * 0.12).x / 0.12, 0.3, 1.0); + return alb * (0.06 + 0.85 * dif + 0.2 * bac) * ao + gloss * spe + 0.3 * fre * ao; +} + +// Pass 1, at SCENE_RES: r = the lit surface, g = its coverage (the rest is the halftone, drawn in +// pass 2 at full resolution), b = 1 where the ray meets the floor plane. +vec4 effect(vec2 p) { + vec2 uv = (p - 0.5 * box_size) / box_size.y; uv.y = -uv.y; + vec3 ro = vec3(CX, CY, CZ); + vec3 ww = normalize(vec3(0.4, 1.7, 0.0) - ro); + vec3 uu = normalize(cross(vec3(0.0, 1.0, 0.0), ww)); + vec3 vv = cross(ww, uu); + vec3 rd = normalize(uv.x * uu + uv.y * vv + 1.75 * ww); + // One march for the camera ray and, off a white square, its reflection: one call site. + vec4 board = vec4(0.0, 0.0, 0.0, 1.0); + for (int bounce = 0; bounce < int(BOUNCES); bounce++) { + // nothing lies past the board or beyond z = 5: rays stop there + float tb = rd.y < 0.0 ? -ro.y / rd.y : -1.0; + float id; + float far = bounce == 0 ? (tb > 0.0 ? min(tb, 14.0) : 14.0) : 8.0; + float t = march(ro, rd, far, bounce == 0 ? int(MARCH) : int(REFLECT), id); + if (t > 0.0) { + vec3 hit = ro + rd * t; + float c = shade(hit, normalAt(hit), rd, id); + // far pieces let the halftone through: a double exposure + if (bounce == 0) return vec4(c, 1.0 - clamp((t - 9.0) * 0.15, 0.0, 0.4), 0.0, 1.0); + board.r += 0.18 * c; + break; + } + if (bounce > 0 || tb < 0.0) break; + vec3 pos = ro + rd * tb; + vec2 g = (pos.xz - vec2(0.45, 0.6)) / 0.62; + float inside = step(abs(g.x), 6.0) * step(abs(g.y), 6.0); + float chk = mod(floor(g.x) + floor(g.y), 2.0); + vec2 fg = abs(fract(g) - 0.5); + float seam = smoothstep(0.5, 0.485, max(fg.x, fg.y)); + float sq = mix(0.05, 0.8, chk) * mix(0.55, 1.0, seam); + vec3 L = vec3(LX, LY, LZ); + vec3 rr = reflect(rd, vec3(0.0, 1.0, 0.0)); + float sh = inside > 0.5 ? shadow(pos + vec3(0.0, 0.002, 0.0), L) : 1.0; + float fade = exp(-0.11 * max(tb - 4.0, 0.0)) * smoothstep(-0.45, 0.25, -rd.y * 2.0 + 0.1); + board = vec4(sq * (0.25 + 0.75 * sh) + 0.35 * pow(clamp(dot(rr, L), 0.0, 1.0), 40.0), + inside * fade * (1.0 - 0.25 * smoothstep(8.0, 14.0, tb)), 1.0, 1.0); + // a glossy board: the pieces reflect in the white squares (the black ones hide it) + if (chk < 0.5 || inside < 0.5) break; + ro = pos + vec3(0.0, 0.01, 0.0); + rd = rr; + } + return board; +} +"; + +const COMPOSITE: &str = r" +float halftone(vec2 p, float t, float shock, vec2 shockAt) { + float cell = max(7.0, box_size.y / 56.0); + vec2 c = (floor(p / cell) + 0.5) * cell; + vec2 u = c / box_size.y; + float smoke = fbm(u * 2.6 + vec2(t * 0.025, -t * 0.018)); + float light = 0.3 + 1.0 * exp(-5.0 * dot(u - vec2(0.85, 0.02), u - vec2(0.85, 0.02))) + + 0.7 * exp(-7.0 * dot(u - vec2(1.6, 0.3), u - vec2(1.6, 0.3))); + float holes = 1.0 - 0.95 * exp(-30.0 * dot(u - vec2(0.24, 0.1), u - vec2(0.24, 0.1))) + - 0.9 * exp(-22.0 * dot(u - vec2(1.13, 0.34), u - vec2(1.13, 0.34))); + float L = clamp(smoke * light * holes * 1.25, 0.0, 1.0); + // the shock ring of a landing rolls out through the dots + if (shock >= 0.0) { + float dr = length(u - shockAt) - shock * 0.9; + L += 0.6 * exp(-dr * dr * 400.0) * exp(-shock * 1.2); + } + // the dots fade in on first light, scattered + L *= smoothstep(0.0, 1.0, t * 0.7 - hash(c) * 0.8); + float rad = 0.5 * cell * sqrt(clamp(L, 0.0, 1.0)); + return smoothstep(rad + 0.8, rad - 0.8, length(p - c)) * (0.3 + 0.55 * L); +} + +float sparkle(vec2 p, float t) { + float cell = box_size.y / 9.0; + vec2 id = floor(p / cell); + float h = hash(id + 3.1); + if (h < 0.72) return 0.0; + vec2 c = (id + vec2(hash(id + 7.0), hash(id + 1.3))) * cell; + vec2 d = abs(p - c) / (box_size.y / 720.0); + float tw = pow(0.5 + 0.5 * sin(t * (1.5 + 2.0 * h) + h * 40.0), 6.0); + float star = exp(-length(d) * 0.35) + 0.6 * exp(-d.x * 0.9) * exp(-d.y * 0.04) + 0.6 * exp(-d.y * 0.9) * exp(-d.x * 0.04); + return star * tw * 0.8; +} + +// Pass 2, at full resolution: the halftone smoke, the scene over it, sparkles and the grade. +vec4 effect(vec2 p) { + float t = T; + vec2 uv = (p - 0.5 * box_size) / box_size.y; uv.y = -uv.y; + vec2 n = input_size(0); + float sc = max(box_size.x / n.x, box_size.y / n.y); + vec4 s = input_raw(0, (p - 0.5 * box_size) / sc + 0.5 * n); + float bg = 0.025 + 0.05 * (1.0 - length(uv)) + halftone(p, t, SHOCK, vec2(0.6, 0.62)); + bg *= 1.0 - 0.4 * s.b; + float col = mix(bg, s.r, s.g); + col += sparkle(p, t) * (0.55 + 0.45 * s.g); + // grade: a soft shoulder, vignette, grain, first light, the flash of a landing queen + col *= 1.0 - 0.55 * pow(length(uv * vec2(0.85, 1.1)), 2.2); + col = col / (1.0 + 0.35 * col) * 1.3; + col += (hash(p + fract(t * 13.0) * 91.7) - 0.5) * 0.06; + col *= smoothstep(0.0, 2.2, t); + col += 0.16 * FLASH; + return vec4(vec3(clamp(col, 0.0, 1.0)), 1.0); +} +"; + +/// The two passes: the raymarched scene, and the composite that samples it. +fn shaders() -> (Fx, Fx) { + let defines = SLOT_NAMES.iter().enumerate().fold(String::new(), |mut s, (i, n)| { + let _ = writeln!(s, "#define {n} U[{i}]"); + s + }); + (Fx::new("gambit_scene", &format!("{defines}{NOISE}{SCENE}"), N, [12, 12, 12]), + Fx::sampling("gambit", &format!("{defines}{NOISE}{COMPOSITE}"), 1, N, [12, 12, 12])) +} + +fn target() -> RenderTarget { + RenderTarget::new(SCENE_RES.0, SCENE_RES.1, TargetFormat::Rgba16F).expect("scene render target") +} + +const CSS: &str = r" +html { height: 100%; } +body { margin: 0; height: 100%; position: relative; background: #050505; overflow: hidden; cursor: pointer; } +.scene { position: absolute; left: 0; top: 0; width: 100%; height: 100%; } +"; + +struct Gambit { + scene: Fx, + composite: Fx, + target: Rc, + /// When the last move was made (`now()`), if any. + moved: Option, + /// Whether the shaders' compile logs have been reported (once, after the first GPU frames). + reported: bool, +} + +impl Render for Gambit { + fn render(&mut self, w: &mut Window, cx: &mut Context) -> impl IntoElement { + w.request_animation_frame(); + if !self.reported && now() > 1.0 { + self.reported = true; + eprintln!("scene shader: {:?}, composite shader: {:?}", self.scene.error(), self.composite.error()); + } + let moved = self.moved; + let (pass, target) = (self.scene.effect().clone(), self.target.clone()); + let scene = self.composite.canvas_after(vec![target.texture()], + move |b, p, f| p.effect_to(b, &target, &pass, &[], f), + move |_| { + let t = now(); + Pose::at(t, moved.map_or(-1.0, |m| t - m)).0 + }).class("scene"); + // no UI: a click anywhere is a move + html() + .child(head().child(style().child(CSS))) + .child(body().child(scene).on_click(cx.listener(|this, _, _, cx| { + this.moved = Some(now()); + cx.notify(); + }))) + } +} + +/// Renders GPU frames off-screen through a move, then times each pass. +fn frames(dir: &str) { + let (scene, fx) = shaders(); + let rt = target(); + let frame = |gpu: &mut GpuTarget, f: &[f32]| gpu.draw_to(&rt, scene.effect(), &[], f) && gpu.draw(fx.effect(), &[rt.texture()], f); + let stills = [("intro", 1.2, -1.0), ("t09", 9.0, -1.0), ("lift", 9.2, 0.2), ("impact", 9.4, 0.4), ("fallen", 10.3, 1.3), ("after", 15.0, 6.0)] + .map(|(name, t, age)| (name, Pose::at(t, age).0)); + let start = std::time::Instant::now(); + let Some(mut gpu) = gpu_stills(dir, 1280, 720, stills, frame) else { + eprintln!("scene shader: {:?}, composite shader: {:?}", scene.error(), fx.error()); + return; + }; + // the first frame compiles both shaders: this is the wait before the first picture + eprintln!("compile + 6 stills: {:.1} s", start.elapsed().as_secs_f64()); + // the cost of each pass once compiled (pixels() waits for the GPU) + let time = |gpu: &mut GpuTarget, what: &str, f: &dyn Fn(&mut GpuTarget, &[f32]) -> bool| { + let start = std::time::Instant::now(); + for i in 0..30 { + f(gpu, &Pose::at(5.0 + i as f32 / 60.0, -1.0).0); + let _ = gpu.pixels(); + } + eprintln!("{what}: {:.1} ms", start.elapsed().as_secs_f64() * 1000.0 / 30.0); + }; + time(&mut gpu, "scene pass", &|g, f| g.draw_to(&rt, scene.effect(), &[], f)); + time(&mut gpu, "composite pass", &|g, f| g.draw(fx.effect(), &[rt.texture()], f)); + time(&mut gpu, "1280x720 frame", &frame); +} + +fn main() { + if let Some(dir) = arg("--frames") { + frames(&dir); + return; + } + run(1280.0, 720.0, "BUI · Gambit", || { + let (scene, composite) = shaders(); + Gambit { scene, composite, target: Rc::new(target()), moved: None, reported: false } + }); +} diff --git a/demos/src/bin/glass.rs b/demos/src/bin/glass.rs new file mode 100644 index 00000000..9977bcb6 --- /dev/null +++ b/demos/src/bin/glass.rs @@ -0,0 +1,86 @@ +//! Glass UI: a GPU shader paints moving light orbs, and the panels over it are real BUI CSS glass +//! (`backdrop-filter: blur() saturate()`, translucent fill, rim light) holding Blender widgets. +//! `cargo run --release --bin glass` + +use bui_demos::{now, run, Fx}; +use blenderui::prelude::*; + +// U[0] = time. Orbs on a faint grid: plenty of edges and colour for the glass to blur. +const ORBS: &str = " +vec4 effect(vec2 p) { + vec2 uv = p / box_size; float a = box_size.x / box_size.y; + vec2 q = uv * vec2(a, 1.0); + vec3 c = vec3(0.02, 0.03, 0.08); + float t = U[0]; + c += vec3(1.0, 0.3, 0.5) * 0.06 / (0.02 + distance(q, vec2(a * (0.5 + 0.35 * sin(t * 0.3)), 0.5 + 0.3 * cos(t * 0.25)))); + c += vec3(0.2, 0.6, 1.0) * 0.06 / (0.02 + distance(q, vec2(a * (0.5 + 0.35 * sin(t * 0.3 + 1.7)), 0.5 + 0.3 * cos(t * 0.25 + 2.3)))); + c += vec3(0.4, 1.0, 0.5) * 0.06 / (0.02 + distance(q, vec2(a * (0.5 + 0.35 * sin(t * 0.3 + 3.4)), 0.5 + 0.3 * cos(t * 0.25 + 4.6)))); + c += vec3(1.0, 0.8, 0.2) * 0.06 / (0.02 + distance(q, vec2(a * (0.5 + 0.35 * sin(t * 0.3 + 5.1)), 0.5 + 0.3 * cos(t * 0.25 + 6.9)))); + float g = step(0.97, fract(uv.x * 30.0)) + step(0.97, fract(uv.y * 30.0 * (1.0 / a))); + return vec4(c + 0.03 * g, 1.0); +}"; + +const CSS: &str = r" +body { margin: 0; width: 900px; height: 560px; position: relative; font-size: 13px; color: #fff; } +.bg { position: absolute; left: 0; top: 0; width: 900px; height: 560px; } +.glass { position: absolute; border-radius: 22px; padding: 18px 22px; + background: rgba(255,255,255,0.12); border: 1px solid rgba(255,255,255,0.35); + backdrop-filter: blur(22px) saturate(1.6); + box-shadow: 0 12px 40px rgba(0,0,0,0.35), inset 0 1px 0 rgba(255,255,255,0.4); } +.glass h3 { margin: 0 0 10px; font-size: 15px; } +.row { display: flex; justify-content: space-between; margin: 6px 0; opacity: 0.9; } +#display { left: 50px; top: 50px; width: 300px; } +#clock { left: 560px; top: 70px; width: 270px; height: 190px; text-align: center; } +#clock .big { font-size: 56px; font-weight: 300; margin-top: 16px; } +#music { left: 140px; top: 300px; width: 360px; } +#dock { left: 560px; top: 330px; width: 270px; height: 56px; display: flex; gap: 18px; align-items: center; justify-content: center; border-radius: 28px; } +.ico { width: 34px; height: 34px; border-radius: 17px; background: rgba(255,255,255,0.18); text-align: center; line-height: 34px; } +.ico:hover { background: rgba(255,255,255,0.38); } +.bar { height: 6px; border-radius: 3px; background: rgba(255,255,255,0.25); margin-top: 10px; } +.bar div { width: 40%; height: 6px; border-radius: 3px; background: #fff; } +"; + +struct Glass { + orbs: Fx, + brightness: f32, + wifi: bool, + playing: bool, +} + +impl Render for Glass { + fn render(&mut self, w: &mut Window, cx: &mut Context) -> impl IntoElement { + w.request_animation_frame(); + let bg = self.orbs.canvas(|_| vec![now()]).class("bg"); + let play = if self.playing { "❚❚" } else { "▶" }; + html().styled() + .child(head().child(style().child(CSS))) + .child(body() + .child(bg) + .child(div().id("display").class("glass").child(h3().child("Display")) + .child(div().class("row").child(span().child("Brightness")).child(span().child(format!("{:.0}%", self.brightness)))) + .child(input().input_type("range").min(0.0).max(100.0).value(format!("{}", self.brightness)) + .on_input(cx.listener(|this, e: &ChangeEvent, _, cx| { this.brightness = e.number as f32; cx.notify(); }))) + .child(div().class("row").child(label().child(input().input_type("checkbox").checked(self.wifi) + .on_change(cx.listener(|this, e: &ChangeEvent, _, cx| { this.wifi = e.checked; cx.notify(); }))) + .child(" Wi-Fi")))) + .child(div().id("clock").class("glass").child(div().class("big").child("12:00")) + .child(p().child("backdrop-filter on a live GPU shader"))) + .child(div().id("music").class("glass").child(h3().child("Now playing")) + .child(div().class("row").child(span().child("Orbital Drift")).child(span().child("2:41 / 4:10"))) + .child(div().class("bar").child(div())) + .child(div().class("row").child(button().child(play).on_click(cx.listener(|this, _, _, cx| { this.playing = !this.playing; cx.notify(); }))) + .child(span().child("◀◀ ▶▶")))) + .child(div().id("dock").class("glass") + .child(div().class("ico").child("☀")).child(div().class("ico").child("♫")) + .child(div().class("ico").child("✉")).child(div().class("ico").child("⚙")))) + } +} + +fn main() { + run(900.0, 560.0, "BUI · glass UI", || Glass { + orbs: Fx::new("orbs", ORBS, 1, [20, 30, 70]), + brightness: 70.0, + wifi: true, + playing: true, + }); +} diff --git a/demos/src/bin/morning.rs b/demos/src/bin/morning.rs new file mode 100644 index 00000000..58683737 --- /dev/null +++ b/demos/src/bin/morning.rs @@ -0,0 +1,523 @@ +//! Morning: a pinch folds a full-screen page into its card in a stack of cards, and spreading +//! opens it again (cloned from `ref/testanim.mp4`). The page washes out, shrinks onto its card, +//! goes dark as the stack fades in behind it, and the stack zooms up to rest; its three little +//! cards fan into the card as they go. +//! +//! One number drives it all: `progress`, 0 the page, 1 the stack. A pinch on a touch screen or a +//! trackpad (`on_pinch`, or ctrl + wheel, which is how Windows trackpads pinch) scrubs it under the +//! fingers, and letting go finishes the way they were going; Space / Enter fold, Escape opens, +//! a click on the page folds and a click on its card opens. +//! +//! `cargo run --release --bin morning`, `-- --storyboard DIR` for headless frames. + +use std::sync::OnceLock; +use std::time::Duration; + +use blenderui::motion::MotionValue; +use blenderui::prelude::*; +use blenderui::vars; +use bui_demos::canvas::{rem, rem_css, Fit}; +use bui_demos::{arg, run_with, save_png, Script}; + +const DESIGN: (f32, f32) = (390.0, 844.0); +/// Seconds for a whole fold (the reference: the stack settles 1 s after the fingers close). +const FOLD: f32 = 1.0; +/// The page's card: its glow, which the page turns into as it folds. +const HOME_GLOW: (&str, f32) = ("#b06c8c", 0.85); +/// Progress per wheel line of a ctrl + wheel pinch. +const PINCH: f32 = 0.09; +/// Fingers closing to this scale fold the page all the way (it ends at about 0.65 of the screen). +const PINCH_FOLD: f32 = 0.65; +/// A pinch with no event for this many frames has let go (no "fingers up" comes from a trackpad). +const LET_GO: u32 = 8; + +/// A box in design pixels. +#[derive(Clone, Copy)] +struct Rect { + x: f32, + y: f32, + w: f32, + h: f32, +} + +const fn rect(x: f32, y: f32, w: f32, h: f32) -> Rect { + Rect { x, y, w, h } +} + +impl Rect { + fn lerp(self, to: Self, t: f32) -> Self { + rect(lerp(self.x, to.x, t), lerp(self.y, to.y, t), lerp(self.w, to.w, t), lerp(self.h, to.h, t)) + } + + fn scaled(self, k: f32) -> Self { + rect(self.x * k, self.y * k, self.w * k, self.h * k) + } + + fn place(self, d: Div) -> Div { + d.css("left", rem(self.x)).css("top", rem(self.y)).css("width", rem(self.w)).css("height", rem(self.h)) + } +} + +fn lerp(a: f32, b: f32, t: f32) -> f32 { + a + (b - a) * t +} + +/// `u` through `a..b` as 0..1. +fn span(u: f32, a: f32, b: f32) -> f32 { + ((u - a) / (b - a)).clamp(0.0, 1.0) +} + +fn ease_in(t: f32) -> f32 { + t * t * t +} + +fn ease_out(t: f32) -> f32 { + 1.0 - (1.0 - t).powi(3) +} + +/// Where the fold is at `u` (0 the page, 1 the stack), read off the reference frame by frame. +struct Fold { + /// The stack's zoom about the screen centre and its drop (it starts small and low). + zoom: f32, + drop: f32, + stack_alpha: f32, + /// The page's box on screen and how far it has become its card (0..1). + page: Rect, + card: f32, + /// White wash, then the card's dark, over the page. + wash: f32, + dark: f32, + blur: f32, + /// The page's own chrome (status bar, the field at the bottom). + chrome: f32, +} + +const FULL: Rect = rect(0.0, 0.0, DESIGN.0, DESIGN.1); +const CENTRE: (f32, f32) = (DESIGN.0 / 2.0, DESIGN.1 / 2.0); +/// The page's card in the stack at rest. +const HOME: Rect = rect(12.0, 290.0, 366.0, 244.0); + +impl Fold { + fn at(u: f32) -> Self { + // times as fractions of the second the fold takes (ms / 1000) + let z = ease_out(span(u, 0.44, 1.0)); + let (zoom, drop) = (lerp(0.72, 1.0, z), lerp(70.0, 0.0, z)); + let card = ease_in(span(u, 0.0, 0.528)); + let target = Self::through(zoom, drop, HOME); + let up = span(u, 0.317, 0.484).min(1.0 - span(u, 0.546, 0.85)); + Self { + zoom, + drop, + stack_alpha: span(u, 0.22, 0.484), + page: FULL.lerp(target, card), + card, + wash: 0.6 * span(u, 0.044, 0.37) * (1.0 - span(u, 0.396, 0.546)), + dark: span(u, 0.37, 0.546), + blur: 5.0 * up, + chrome: 1.0 - span(u, 0.07, 0.334), + } + } + + /// `r` (stack coordinates) on screen. + fn through(zoom: f32, drop: f32, r: Rect) -> Rect { + rect(CENTRE.0 + (r.x - CENTRE.0) * zoom, CENTRE.1 + (r.y - CENTRE.1) * zoom + drop, r.w * zoom, r.h * zoom) + } + + /// A point of the page's layout at full size (`page`) and on its card (`card`, card + /// coordinates), inside the page box now. + fn inner(&self, page: Rect, card: Rect) -> Rect { + page.lerp(card.scaled(self.zoom), self.card) + } +} + +/// The stack, top to bottom: title, box (stack coordinates), what is drawn in it. +const STACK: [(&str, Rect, Look); 6] = [ + ("Weekend Plans", rect(12.0, -74.0, 366.0, 76.0), Look::Pill), + ("Twisted Blades Rogue Build", rect(12.0, 10.0, 366.0, 74.0), Look::Pill), + ("Personality Quiz", rect(12.0, 92.0, 366.0, 190.0), Look::Quiz), + ("Good Morning", HOME, Look::Home), + ("Brainstorming Presents", rect(12.0, 542.0, 366.0, 92.0), Look::Pill), + ("Brunch Recipe Ideas", rect(12.0, 642.0, 366.0, 210.0), Look::Brunch), +]; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Look { + Pill, + Quiz, + Home, + Brunch, +} + +/// The page's three cards: full size on the page, then fanned on its card. +struct Snap { + page: Rect, + card: Rect, + turn: (f32, f32), +} + +const QUOTE: Snap = Snap { page: rect(44.0, 278.0, 150.0, 140.0), card: rect(92.0, 140.0, 76.0, 96.0), turn: (-3.0, -9.0) }; +const FRIDAY: Snap = Snap { page: rect(70.0, 492.0, 160.0, 152.0), card: rect(138.0, 130.0, 80.0, 104.0), turn: (-1.0, -3.0) }; +const PHOTO: Snap = Snap { page: rect(190.0, 322.0, 160.0, 196.0), card: rect(188.0, 120.0, 104.0, 108.0), turn: (4.0, 10.0) }; + +const CSS: &str = r" +html { height: 100%; background: #121013; } +body { margin: 0; height: 100%; overflow: hidden; background: #121013; color: #fff; + font-family: 'Segoe UI', Inter, sans-serif; } +.abs { position: absolute; } +.screen { position: absolute; overflow: hidden; } +.stack { position: absolute; left: 0px; top: 0px; width: 390px; height: 844px; transform-origin: 195px 422px; } +.card { position: absolute; overflow: hidden; border-radius: 28px; background: #2e2a2f; } +.glow { position: absolute; left: 8%; width: 84%; top: 42%; height: 110%; border-radius: 50%; filter: blur(34px); } +.card h3 { position: absolute; left: 0px; right: 0px; margin: 0; text-align: center; font-size: 19px; + font-weight: 700; color: #f2cfdc; letter-spacing: -0.2px; } +.pill h3 { top: 26px; color: #ece6ea; font-size: 17px; } +.doc { position: absolute; border-radius: 9px; background: #f4f1ee; box-shadow: 0 6px 18px rgba(0,0,0,0.35); } +.doc i { position: absolute; left: 12px; height: 4px; border-radius: 2px; background: #b9b2b6; } +.page { position: absolute; overflow: hidden; } +.paint { position: absolute; left: 0px; top: 0px; width: 100%; height: 100%; } +.peach { background: linear-gradient(172deg, #f8e6df 0%, #f3c9c3 40%, #efb7a8 100%); } +.blob { position: absolute; border-radius: 50%; } +.title { position: absolute; left: 0px; right: 0px; text-align: center; font-weight: 800; color: #fff; + line-height: 0.95; letter-spacing: -1px; } +.snap { position: absolute; overflow: hidden; border-radius: 14px; background: #fbf8f4; + box-shadow: 0 10px 26px rgba(120,60,60,0.22); } +.snap .in { position: absolute; left: 0px; top: 0px; transform-origin: 0px 0px; } +.quote .words { margin: 0; position: absolute; left: 14px; top: 14px; width: 124px; font-family: Georgia, serif; + font-size: 15.5px; line-height: 1.18; color: #3a302c; } +.label { position: absolute; font-size: 10px; color: #9a8f8a; } +.friday .day { position: absolute; left: 16px; top: 18px; font-size: 26px; color: #2a2522; font-weight: 700; } +.friday .date { position: absolute; left: 16px; top: 48px; font-size: 26px; color: #5b5350; } +.chrome { position: absolute; left: 0px; top: 0px; width: 390px; height: 844px; } +.clock { position: absolute; left: 34px; top: 15px; font-size: 15px; font-weight: 600; color: #3b302e; } +.field { position: absolute; left: 16px; top: 772px; width: 358px; height: 44px; border-radius: 22px; + background: rgba(255,255,255,0.42); color: #9b8c88; font-size: 14px; } +.field .ask { position: absolute; left: 44px; top: 12px; } +.field .plus { position: absolute; left: 18px; top: 8px; font-size: 20px; font-weight: 400; color: #8c7d79; } +.home { position: absolute; left: 128px; top: 829px; width: 134px; height: 5px; border-radius: 3px; } +.island { position: absolute; left: 134px; top: 11px; width: 122px; height: 35px; border-radius: 18px; + background: #000; } +"; + +fn css() -> &'static str { + static CSS_REM: OnceLock = OnceLock::new(); + CSS_REM.get_or_init(|| rem_css(CSS)) +} + +struct Morning { + progress: MotionValue, + /// The frame of a pinch's last event and which way it went (+1 folding). + pinch: Option<(u32, f32)>, + frames: u32, +} + +impl Morning { + /// Runs the fold to `to` (0 or 1) at the reference's pace from wherever it is. + fn go(&mut self, to: f32) { + self.pinch = None; + let duration = FOLD * (to - self.progress.get()).abs(); + drop(self.progress.animate(to, vars! { duration: duration, ease: "none" })); + } + + fn key(&mut self, e: &KeyDownEvent, _: &mut Window, cx: &mut Context) { + match e.keystroke.key.as_str() { + "space" | "Return" | "KP_Enter" | "Down" => self.go(1.0), + "Escape" | "Up" | "BackSpace" => self.go(0.0), + _ => return, + } + cx.stop_propagation(); + cx.notify(); + } + + fn folded(&self) -> bool { + self.progress.get() > 0.5 + } + + /// The fingers moved: `fold` of the way towards the stack (negative: towards the page). + fn scrub(&mut self, fold: f32) { + self.progress.stop(); + self.progress.set((self.progress.get() + fold).clamp(0.0, 1.0)); + self.pinch = Some((self.frames, fold.signum())); + } + + /// Fingers closing by `1 + delta` (a scale) fold in proportion: `PINCH_FOLD` is the whole way. + fn pinch(&mut self, e: &PinchEvent) { + self.scrub((1.0 + e.delta).max(0.01).ln() / PINCH_FOLD.ln()); + } + + /// ctrl + wheel: spreading (wheel away) opens, pinching folds. + fn wheel(&mut self, e: &ScrollWheelEvent) { + if e.modifiers.control { + self.scrub(-e.pixels.map_or(e.delta, |p| p / 120.0) * PINCH); + } + } +} + +fn card_paint(glow: &str, strength: f32) -> Div { + div().class("paint").child(div().class("glow").css("background", glow).css("opacity", format!("{strength}"))) +} + +/// The little photo: a person in a yellow jacket under bare branches. +fn photo() -> Div { + canvas(|b, p| { + let (x, y, w, h) = (b.origin.x, b.origin.y, b.size.width, b.size.height); + let at = |u: f32, v: f32| (x + u * w, y + v * h); + p.fill(b, rgb(0x00d9_dbd7)); + p.fill(Bounds { origin: point(x, y + h * 0.55), size: size(w, h * 0.45) }, rgb(0x00b9_bcb4)); + for (i, (u0, v0, u1, v1)) in [(0.0, 0.1, 0.55, 0.35), (0.2, 0.0, 0.4, 0.42), (0.55, 0.05, 1.0, 0.3), + (0.75, 0.0, 0.62, 0.38), (0.05, 0.4, 0.3, 0.2)].into_iter().enumerate() { + p.line(&[at(u0, v0), at(u1, v1)], rgb(0x0040_3a36), if i < 2 { 2.2 } else { 1.4 }); + } + p.polygon(&[at(0.22, 1.0), at(0.3, 0.62), at(0.5, 0.55), at(0.72, 0.62), at(0.82, 1.0)], rgb(0x00e8_b03c)); + p.oval(Bounds { origin: point(x + w * 0.38, y + h * 0.3), size: size(w * 0.25, h * 0.28) }, rgb(0x00e3_bda2), rgba(0), 0.0); + p.oval(Bounds { origin: point(x + w * 0.36, y + h * 0.25), size: size(w * 0.29, h * 0.16) }, rgb(0x002b_221d), rgba(0), 0.0); + }) + .class("paint") +} + +/// Brunch from above: a plate, two yolks, oranges, herbs. +fn food() -> Div { + canvas(|b, p| { + let (x, y, w, h) = (b.origin.x, b.origin.y, b.size.width, b.size.height); + let oval = |p: &mut Painter, u: f32, v: f32, rw: f32, rh: f32, c: u32| { + p.oval(Bounds { origin: point(x + (u - rw) * w, y + (v - rh) * h), size: size(2.0 * rw * w, 2.0 * rh * h) }, + rgb(c), rgba(0), 0.0); + }; + p.fill(b, rgb(0x003a_2218)); + oval(p, 0.5, 0.62, 0.3, 0.46, 0x00ec_e5da); + oval(p, 0.5, 0.62, 0.25, 0.38, 0x00f4_efe6); + oval(p, 0.1, 0.3, 0.09, 0.16, 0x00d9_5f22); + oval(p, 0.1, 0.3, 0.06, 0.11, 0x00f0_8a3c); + oval(p, 0.9, 0.78, 0.08, 0.15, 0x00e0_7a2a); + oval(p, 0.86, 0.25, 0.07, 0.12, 0x00a8_3a24); + oval(p, 0.42, 0.55, 0.12, 0.2, 0x00ff_fbf2); + oval(p, 0.42, 0.55, 0.05, 0.08, 0x00f6_a51c); + oval(p, 0.6, 0.7, 0.12, 0.2, 0x00ff_fbf2); + oval(p, 0.6, 0.7, 0.05, 0.08, 0x00f6_a51c); + for (u, v) in [(0.3, 0.75), (0.52, 0.42), (0.7, 0.52), (0.35, 0.4), (0.62, 0.9)] { + oval(p, u, v, 0.025, 0.04, 0x004e_7a2c); + } + }) + .class("paint") +} + +/// The stack's cards, in screen coordinates for this frame. +fn stack_card(f: &Fold, i: usize) -> Div { + let (title, at, look) = STACK[i]; + let card = Fold::through(f.zoom, f.drop, at).place(div().id(format!("card{i}")).class("card")) + .css("border-radius", rem(28.0 * f.zoom)).css("z-index", format!("{}", i + 1)); + // the contents keep their rest layout, zoomed with the stack + let mut inner = div().class("abs").css("left", "0").css("top", "0").css("width", rem(at.w)).css("height", rem(at.h)) + .css("transform-origin", "0 0").css("transform", format!("scale({})", f.zoom)); + inner = match look { + Look::Pill => inner.class("pill").child(card_paint("#4a3f47", 0.45)), + Look::Quiz => inner.child(card_paint("#86588a", 0.6)) + .child(rect(112.0, 128.0, 118.0, 80.0).place(div().class("doc").css("background", "#cfc8cb").css("transform", "rotate(-5deg)"))) + .child(rect(136.0, 128.0, 118.0, 80.0).place(div().class("doc").css("background", "#d9d3d5").css("transform", "rotate(5deg)"))) + .child(doc_lines(rect(124.0, 116.0, 118.0, 92.0))), + Look::Home => inner.child(card_paint(HOME_GLOW.0, HOME_GLOW.1)), + Look::Brunch => inner.child(card_paint("#8a5246", 0.7)) + .child(rect(104.0, 108.0, 158.0, 110.0).place(div().class("abs").css("overflow", "hidden") + .css("border-radius", rem(12.0)).child(food()))), + }; + // the page's own card is drawn by the page once it has folded onto it + if look != Look::Home { + inner = inner.child(h3().child(title)); + } + card.child(inner) +} + +fn doc_lines(at: Rect) -> Div { + let mut d = at.place(div().class("doc")); + for (k, w) in [86.0, 70.0, 92.0, 54.0, 78.0].into_iter().enumerate() { + d = d.child(div().css("width", rem(w)).css("top", rem(12.0 + k as f32 * 13.0)).css("position", "absolute") + .css("left", rem(12.0)).css("height", rem(4.0)).css("border-radius", rem(2.0)).css("background", "#bdb5b9")); + } + d +} + +/// One of the page's cards at this frame: its page layout scaled into the box it has now. +fn snap(f: &Fold, s: &Snap, class: &'static str, content: Div) -> Div { + let at = f.inner(s.page, s.card); + let k = at.w / s.page.w; + at.place(div().class("snap").class(class)) + .css("border-radius", rem(lerp(14.0, 9.0, f.card))) + .css("transform", format!("rotate({}deg)", lerp(s.turn.0, s.turn.1, f.card))) + .child(content.class("in").css("width", rem(s.page.w)).css("height", rem(s.page.h)) + .css("transform", format!("scale({k})"))) +} + +fn page(f: &Fold) -> Div { + let bx = f.page; + let t = f.card; + let mut page = bx.place(div().id("page").class("page")) + .css("border-radius", rem(lerp(0.0, 28.0 * f.zoom, t))).css("z-index", "20"); + if f.blur > 0.05 || f.wash > 0.01 { + page = page.css("filter", format!("blur({}px) grayscale({})", f.blur, (f.wash * 1.4).min(1.0))); + } + // the warm page: peach, a magenta bloom on the right and an orange one low left + let k = bx.w / DESIGN.0; + let blob = |x: f32, y: f32, w: f32, h: f32, c: &str, blur: f32| { + rect(x, y, w, h).scaled(k).place(div().class("blob")).css("background", c) + .css("filter", format!("blur({}px)", blur * k)) + }; + let warm = div().class("paint peach") + .child(blob(170.0, 40.0, 300.0, 520.0, "#e486cf", 70.0)) + .child(blob(-80.0, 250.0, 300.0, 340.0, "#f49a6c", 70.0)) + .child(blob(40.0, -120.0, 300.0, 260.0, "#fbeee8", 60.0)); + page = page.child(warm) + .child(div().class("paint").css("background", "#f1eeee").css("opacity", format!("{}", f.wash))) + .child(card_paint(HOME_GLOW.0, HOME_GLOW.1).css("background", "#2e2a2f").css("opacity", format!("{}", f.dark))); + + // "Good Morning": the page's headline becomes the card's title + let size = lerp(72.0, 27.0 * f.zoom, t); + let top = lerp(118.0, 22.0 * f.zoom, t); + let tint = mix(0x00ff_ffff, 0x00f2_cfdc, f.dark); + page = page.child(div().class("title").css("top", rem(top)).css("font-size", rem(size)) + .css("color", format!("#{tint:06x}")).css("opacity", format!("{}", 1.0 - 0.45 * f.wash / 0.6)) + .child("Good").child(br()).child("Morning")); + + page = page + .child(snap(f, "E, "quote", div() + .child(div().class("words").child("I thrive in new environments and welcome the adventures of learning.")) + .child(div().class("label").css("left", rem(14.0)).css("top", rem(114.0)).child("Daily Affirmation")))) + .child(snap(f, &FRIDAY, "friday", div() + .child(div().class("day").child("Friday")).child(div().class("date").child("Oct 27")) + .child(div().class("label").css("left", rem(16.0)).css("top", rem(124.0)).child("Daily Overview")))) + .child(snap(f, &PHOTO, "photo", div().child(photo()))); + + if f.chrome > 0.0 { + let o = format!("{}", f.chrome); + let mut bars = div().class("abs bars").css("left", rem(318.0)).css("top", rem(19.0)).css("width", rem(20.0)).css("height", rem(11.0)); + for (i, h) in [4.0, 6.0, 8.5, 11.0].into_iter().enumerate() { + bars = bars.child(i_().css("left", rem(i as f32 * 4.5)).css("height", rem(h))); + } + page = page.child(div().class("chrome").css("opacity", o).css("transform", format!("scale({k})")) + .css("transform-origin", "0 0") + .child(div().class("clock").child("11:01")).child(bars) + .child(div().class("abs").css("left", rem(344.0)).css("top", rem(19.0)).css("width", rem(22.0)) + .css("height", rem(11.0)).css("border-radius", rem(3.0)).css("background", "#3b302e")) + .child(div().class("field").child(div().class("plus").child("+")).child(div().class("ask").child("Share with Dot"))) + .child(div().class("home").css("background", "#2a2220"))); + } + page +} + +/// `a` to `b` (0xRRGGBB) by `t`. +fn mix(a: u32, b: u32, t: f32) -> u32 { + let ch = |s: u32| { + let (x, y) = (((a >> s) & 255) as f32, ((b >> s) & 255) as f32); + (lerp(x, y, t).round() as u32) << s + }; + ch(16) | ch(8) | ch(0) +} + +fn i_() -> Div { + div().css("position", "absolute").css("bottom", "0").css("width", rem(3.0)).css("border-radius", rem(1.0)) + .css("background", "#3b302e") +} + +impl Render for Morning { + fn render(&mut self, w: &mut Window, cx: &mut Context) -> impl IntoElement { + w.request_animation_frame(); + if w.focused_id().is_none() && self.frames > 0 { + w.focus_id("root"); + } + self.frames += 1; + // a pinch that has gone quiet has let go: on to the end it was heading for + if let Some((at, dir)) = self.pinch + && self.frames - at > LET_GO + { + // a little way is enough to commit to the way the fingers went + let u = self.progress.get(); + let fold = if dir > 0.0 { u > 0.2 } else { u > 0.8 }; + self.go(if fold { 1.0 } else { 0.0 }); + } + let fit = Fit::new(w, DESIGN); + let f = Fold::at(self.progress.get()); + + let mut stack = div().class("stack").css("opacity", format!("{}", f.stack_alpha)); + if f.blur > 0.05 { + stack = stack.css("filter", format!("blur({}px)", f.blur)); + } + for i in 0..STACK.len() { + stack = stack.child(stack_card(&f, i)); + } + let page = page(&f).on_click(cx.listener(|this, _, _, cx| { + if this.folded() { + this.go(0.0); + } else { + this.go(1.0); + } + cx.notify(); + })); + let screen = div().class("screen") + .css("left", rem(fit.ox)).css("top", rem(fit.oy)).css("width", rem(DESIGN.0)).css("height", rem(DESIGN.1)) + .child(stack).child(page).child(div().class("island").css("z-index", "40")); + + html().css("font-size", fit.root_font()) + .child(head().child(style().child(css()))) + .child(body().id("root").attr("tabindex", "0") + .on_key_down(cx.listener(Self::key)) + .on_pinch(cx.listener(|this, e: &PinchEvent, _, cx| { + this.pinch(e); + cx.notify(); + })) + .on_scroll_wheel(cx.listener(|this, e: &ScrollWheelEvent, _, cx| { + this.wheel(e); + cx.notify(); + })) + .child(screen)) + } +} + +/// The reference's timing: 120 ms at rest, the fold, rest; then the way back, then a pinch and a +/// spread. +fn storyboard(dir: String) -> Script { + Box::new(move |cx, win| { + let shot = |cx: &mut App, name: &str| { + let (w, h, px) = cx.draw(win); + save_png(&format!("{dir}/{name}.png"), w, h, &px); + }; + let tick = |cx: &mut App, ms: u64| cx.advance_clock(Duration::from_millis(ms)); + // a first frame, then the pointer comes in (the kit takes keys once it has) + shot(cx, "start"); + tick(cx, 300); + cx.simulate_mouse_move(win, 5.0, 5.0); + // fold: frame n at n x 40 ms, numbered like the reference's (0001 = 0 ms) + for n in 0..44u64 { + if n == 3 { + cx.simulate_key(win, "", "space"); + } + shot(cx, &format!("fold-{:04}", n + 1)); + tick(cx, 40); + } + cx.simulate_key(win, "", "Escape"); + for n in 0..26u64 { + shot(cx, &format!("open-{:04}", n + 1)); + tick(cx, 40); + } + // fingers closing a little (to 0.8): the page follows them, then on letting go folds + for n in 0..30u64 { + if n < 6 { + cx.simulate_magnify(win, 195.0, 420.0, -0.037); + } + shot(cx, &format!("pinch-{:04}", n + 1)); + tick(cx, 40); + } + // spreading them opens it again + for n in 0..30u64 { + if n < 6 { + cx.simulate_magnify(win, 195.0, 420.0, 0.04); + } + shot(cx, &format!("spread-{:04}", n + 1)); + tick(cx, 40); + } + }) +} + +fn main() { + let (w, h) = arg("--size").and_then(|s| s.split_once('x').and_then(|(a, b)| Some((a.parse().ok()?, b.parse().ok()?)))) + .unwrap_or(DESIGN); + let make = || Morning { progress: MotionValue::new(0.0), pinch: None, frames: 0 }; + run_with(w, h, "BUI · Morning", make, arg("--storyboard").map(storyboard)); +} diff --git a/demos/src/bin/phantom.rs b/demos/src/bin/phantom.rs new file mode 100644 index 00000000..defd1276 --- /dev/null +++ b/demos/src/bin/phantom.rs @@ -0,0 +1,361 @@ +//! Phantom: a Persona 5-style main menu for a tech app, on BUI. A GPU shader paints the scene (a +//! red room, a black-and-white starburst spinning out on the right, a white star behind the menu, +//! a black blot, halftone, a red brush slash); over it, ransom-note type: every letter its own +//! font, size, tilt and box. The selected command's letters pop onto red, white and cyan blocks; +//! Enter / click / Confirm opens its sub-menu, C / Escape / Close puts it away. +//! +//! Motion ("energetic"): a selection re-pops its letters one after another (18 ms apart, 200 ms +//! each, overshooting), the pointer shard snaps in behind; a confirm flashes the scene and slams +//! the card in; the starburst keeps turning outward underneath. +//! +//! `cargo run --release --bin phantom` +//! `-- --storyboard DIR` drives it headlessly and saves frames along BUI's virtual clock +//! (`-- --size 1920x1080` for another window size); `-- --frames DIR` renders the scene on the GPU. + +use std::sync::OnceLock; +use std::time::Duration; + +use blenderui::prelude::*; +use bui_demos::canvas::{rem, rem_css, Fit}; +use bui_demos::menu::{MenuState, ENTRIES}; +use bui_demos::{arg, gpu_stills, now, run_with, save_png, Fx, Script}; + +/// U[0] = time, U[1] = seconds since the last confirm (< 0: none). +const SCENE: &str = r" +float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); } +float vnoise(vec2 p) { + vec2 i = floor(p); vec2 f = fract(p); f = f * f * (3.0 - 2.0 * f); + return mix(mix(hash(i), hash(i + vec2(1.0, 0.0)), f.x), mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), f.x), f.y); +} +// a five-point jagged star's radius factor at angle a (a triangle wave around the circle) +float jag(float a, float n, float depth) { return 1.0 + depth * abs(fract(a * n / 6.2831853) - 0.5) * 2.0; } +// distance to the segment a-b +float seg(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a; vec2 ba = b - a; return length(pa - ba * clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0)); } + +vec4 effect(vec2 p) { + float t = U[0]; float pulse = U[1]; + vec2 uv = p / box_size; + float asp = box_size.x / box_size.y; + vec2 q = vec2(uv.x * asp, uv.y); + // the red room: a deep red wall, window frames, grime + vec3 col = mix(vec3(0.45, 0.0, 0.03), vec3(0.86, 0.04, 0.09), 0.55 * smoothstep(0.0, 0.7, uv.x) + 0.45 * vnoise(q * 2.5 + t * 0.04)); + float fx = abs(fract(q.x * 1.3 + 0.15 * uv.y) - 0.5); + float fy = abs(fract(uv.y * 2.2 + 0.1) - 0.5); + col *= 1.0 - 0.5 * max(smoothstep(0.43, 0.46, fx), smoothstep(0.44, 0.47, fy) * step(fx, 0.43)); + col *= 0.78 + 0.22 * vnoise(q * 24.0); + // the starburst: black and white jagged rings turning outward, on the right + vec2 d = q - vec2(asp * 0.86, 0.6); + float r = length(d); float a = atan2(d.y, d.x) + t * 0.05; + float rings = fract(r * 15.0 / jag(a, 5.0, 0.6) - t * 0.25); + vec3 burst = vec3(step(0.5, rings) * 0.88 + 0.05); + float edge = q.x - asp * 0.6 - 0.06 * sin(uv.y * 11.0) - 0.04 * (fract(uv.y * 5.0) - 0.5); + col = mix(col, burst, smoothstep(-0.002, 0.002, edge)); + // the white star behind the menu, inked + vec2 s = q - vec2(asp * 0.44, 0.47); + float sr = length(s) / (0.3 * jag(atan2(s.y, s.x) + 0.3, 5.0, 0.75)); + col = mix(col, vec3(0.02), smoothstep(1.02, 1.0, sr)); + col = mix(col, vec3(0.93), smoothstep(0.985, 0.965, sr)); + // a black blot over the middle, ragged + vec2 b = (q - vec2(asp * 0.64, 0.66)) / vec2(0.3, 0.42); + float blot = length(b) + 0.12 * vnoise(q * 9.0) - 0.06; + col = mix(col, vec3(0.02), smoothstep(1.0, 0.98, blot)); + // halftone, white on the black, top of the blot + vec2 cell = fract(q * 46.0) - 0.5; + float tone = smoothstep(0.38, 0.05, length(q - vec2(asp * 0.66, 0.32))); + col = mix(col, vec3(0.9), step(length(cell), 0.28 * tone) * step(blot, 1.0)); + // the red brush slash + float stroke = min(seg(q, vec2(asp * 0.56, 0.14), vec2(asp * 0.52, 0.52)), seg(q, vec2(asp * 0.52, 0.52), vec2(asp * 0.7, 0.6))); + float w = 0.045 + 0.012 * vnoise(q * 30.0); + col = mix(col, vec3(0.02), smoothstep(w + 0.008, w + 0.004, stroke)); + col = mix(col, vec3(0.78, 0.02, 0.04), smoothstep(w, w - 0.004, stroke)); + // a confirm: the scene flashes + if (pulse >= 0.0) col = mix(col, vec3(1.0), 0.5 * exp(-pulse * 10.0)); + return vec4(col, 1.0); +} +"; + +const CSS: &str = r" +html { height: 100%; } +body { margin: 0; height: 100%; position: relative; overflow: hidden; background: #8a0010; user-select: none; + font-family: Inter, system-ui, sans-serif; -webkit-font-smoothing: antialiased; } +.scene { position: absolute; left: 0; top: 0; width: 100%; height: 100%; } +.abs { position: absolute; } +.ui { left: 0; top: 0; } + +/* -- ransom-note letters: each one its own font, size, tilt and box -- */ +.g { display: inline-block; line-height: 1; padding: 1px 3px; margin: 0 -1px; color: #fff; + text-shadow: 2px 2px 0 #000, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000; } +.g.ink { background: #050505; color: #fff; text-shadow: none; } +.g.paper { background: #f2f2f2; color: #050505; text-shadow: none; } +.g.blood { background: #e0001b; color: #fff; text-shadow: none; } +.g.sky { background: #3fe8ff; color: #050505; text-shadow: none; } +.g.pop { animation: pop 200ms cubic-bezier(0.2, 0, 0, 1) backwards; } + +/* -- the menu -- */ +.item { cursor: pointer; white-space: nowrap; transform: rotate(-3deg); transform-origin: right center; + animation: drop 320ms cubic-bezier(0.2, 0, 0, 1) backwards; } +.item .strip { padding: 2px 8px 4px; background: #050505; + clip-path: polygon(2% 8%, 100% 0, 97% 100%, 0 92%); } +.item.on .strip { background: transparent; clip-path: none; } +.item.on { transform: rotate(-6deg) scale(1.22); transition-property: transform; transition-duration: 180ms; + transition-timing-function: cubic-bezier(0.34, 1.56, 0.64, 1); } +.shard { position: absolute; right: -46px; top: -6px; width: 52px; height: 46px; background: #3fe8ff; + clip-path: polygon(0 40%, 100% 0, 30% 100%); animation: shard 180ms cubic-bezier(0.2, 0, 0, 1) 60ms backwards; } + +/* -- the labels: tilted, inked, stuck on -- */ +.label { white-space: nowrap; transform-origin: left center; animation: slam 260ms cubic-bezier(0.2, 0, 0, 1) backwards; } +.card { background: #f2f2f2; color: #050505; padding: 6px 16px; box-shadow: 6px 6px 0 #050505; font-weight: 800; } +.card.black { background: #050505; color: #fff; box-shadow: 6px 6px 0 #f2f2f2; text-align: center; } +.card small { display: block; font-size: 13px; letter-spacing: 1px; font-weight: 700; } +.hint { background: #050505; color: #fff; padding: 2px 10px; font-size: 22px; font-style: italic; font-weight: 700; + border: 2px solid #fff; transform: rotate(-4deg); animation: slam 200ms cubic-bezier(0.2, 0, 0, 1) backwards; } +.keys { right: 26px; bottom: 18px; display: flex; gap: 10px; } +.key { display: flex; align-items: center; gap: 6px; padding: 4px 10px; background: #f2f2f2; color: #050505; + border: 3px solid #050505; font-size: 20px; font-weight: 800; font-style: italic; cursor: pointer; transform: rotate(-3deg); + transition-property: transform; transition-duration: 120ms; } +.key:active { transform: rotate(-3deg) scale(0.96); } +.cap { width: 22px; height: 22px; border: 2px solid #050505; font-size: 12px; font-style: normal; + display: flex; align-items: center; justify-content: center; } + +/* -- the sub-menu a confirm slams in -- */ +.panel { z-index: 30; right: 40px; top: 330px; width: 360px; padding: 16px 22px 20px; background: #050505; + border: 4px solid #f2f2f2; box-shadow: 10px 10px 0 #e0001b; transform: rotate(-4deg); + animation: panelin 260ms cubic-bezier(0.2, 0, 0, 1) backwards; } +.panel .head { margin-bottom: 10px; } +.row { display: flex; justify-content: space-between; gap: 16px; padding: 6px 10px; font-size: 16px; font-weight: 800; color: #fff; + transition-property: background-color; transition-duration: 80ms; + animation: rowin 200ms cubic-bezier(0.2, 0, 0, 1) backwards; } +.row:hover { background: #e0001b; } +.row b { font-weight: 600; color: #bdbdbd; font-style: italic; font-variant-numeric: tabular-nums; } +.out { animation: panelout 140ms cubic-bezier(0.3, 0, 1, 1) forwards; pointer-events: none; } + +/* -- motion -- */ +@keyframes pop { 0% { opacity: 0; transform: scale(0.4) rotate(-20deg); } 60% { opacity: 1; transform: scale(1.25) rotate(4deg); } + 100% { opacity: 1; transform: scale(1) rotate(0deg); } } +@keyframes drop { from { opacity: 0; transform: rotate(-3deg) translateY(-24px); } to { opacity: 1; transform: rotate(-3deg) translateY(0); } } +@keyframes shard { from { opacity: 0; transform: translateX(-30px) scale(0.3); } to { opacity: 1; transform: translateX(0) scale(1); } } +@keyframes slam { from { opacity: 0; transform: scale(1.6); } to { opacity: 1; transform: scale(1); } } +@keyframes panelin { 0% { opacity: 0; transform: rotate(-4deg) translateX(140px) scale(1.1); } + 70% { opacity: 1; transform: rotate(-4deg) translateX(-8px) scale(0.98); } + 100% { opacity: 1; transform: rotate(-4deg) translateX(0) scale(1); } } +@keyframes rowin { from { opacity: 0; transform: translateX(36px); } to { opacity: 1; transform: translateX(0); } } +@keyframes panelout { to { opacity: 0; transform: rotate(-4deg) translateX(60px); } } +"; + +fn css() -> &'static str { + static CSS_REM: OnceLock = OnceLock::new(); + CSS_REM.get_or_init(|| rem_css(CSS)) +} + +const DESIGN: (f32, f32) = (1280.0, 720.0); +/// Where each command's right edge sits (x, y) and its type size, on the design canvas. +const AT: [(f32, f32, f32); 9] = [ + (720.0, 128.0, 40.0), (735.0, 176.0, 36.0), (712.0, 218.0, 38.0), (690.0, 260.0, 40.0), (668.0, 304.0, 36.0), + (650.0, 344.0, 38.0), (700.0, 386.0, 36.0), (680.0, 430.0, 38.0), (650.0, 474.0, 36.0), +]; +const FONTS: [&str; 7] = ["Inter", "Georgia", "Impact", "Consolas", "Times New Roman", "Arial Black", "Courier New"]; + +/// A small deterministic hash, so each letter keeps its look from frame to frame. +const fn mix(a: u32, b: u32) -> u32 { + let mut h = a.wrapping_mul(0x9E37_79B9) ^ b.wrapping_mul(0x85EB_CA6B); + h ^= h >> 15; + h = h.wrapping_mul(0x2C1B_3C6D); + h ^ (h >> 12) +} + +/// How loud a ransom word is. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Voice { + /// White letters, now and then inked or on paper. + Plain, + /// Every letter on a block: red, white, cyan, black. Each pops in, keyed by `pick`. + Loud { pick: u32 }, +} + +/// `text` as a ransom note: each letter its own font, size, tilt, case and box (`seed` fixes them). +fn ransom(text: &str, seed: u32, size: f32, voice: Voice) -> Div { + let mut out = div().css("display", "inline-block"); + for (k, ch) in text.chars().enumerate() { + if ch == ' ' { + out = out.child(span().css("display", "inline-block").css("width", rem(size * 0.3))); + continue; + } + let h = mix(seed, k as u32 + 1); + let font = FONTS[(h % FONTS.len() as u32) as usize]; + let scale = 0.82 + f32::from((h >> 3) as u8 % 41) / 100.0; + let tilt = f32::from((h >> 11) as u8 % 19) - 9.0; + let lower = (h >> 17).is_multiple_of(3); + let shown: String = if lower { ch.to_lowercase().collect() } else { ch.to_uppercase().collect() }; + let class = match voice { + Voice::Plain => match (h >> 20) % 7 { 0 => "g ink", 1 => "g paper", _ => "g" }, + Voice::Loud { .. } => ["g blood", "g paper", "g sky", "g ink", "g paper"][((h >> 20) % 5) as usize], + }; + let mut g = span().class(class).css("font-family", font).css("font-size", rem(size * scale)) + .css("transform", format!("rotate({tilt}deg)")).css("font-weight", if (h >> 24).is_multiple_of(2) { "900" } else { "700" }); + if let Voice::Loud { pick } = voice { + g = g.id(format!("g{seed}-{pick}-{k}")).class("pop").css("animation-delay", format!("{}ms", k * 18)); + } + out = out.child(g.child(shown)); + } + out +} + +/// Places an absolutely positioned element (design px). +fn at(d: Div, x: f32, y: f32) -> Div { + d.class("abs").css("left", rem(x)).css("top", rem(y)) +} + +struct Phantom { + scene: Fx, + menu: MenuState, + /// Frames rendered: the page takes keyboard focus once one exists. + frames: u32, +} + +impl Phantom { + fn panel(&self, i: usize, leaving: bool) -> Div { + let entry = &ENTRIES[i]; + let mut p = div().id(format!("panel{i}-{}", self.menu.confirms)).class(if leaving { "abs panel out" } else { "abs panel" }) + .child(div().class("head").child(ransom(entry.name, 900 + i as u32, 30.0, Voice::Loud { pick: self.menu.confirms }))); + for (k, (name, value)) in entry.rows.iter().enumerate() { + p = p.child(div().class("row").css("animation-delay", format!("{}ms", 110 + k * 40)) + .child(span().child(*name)).child(b().child(*value))); + } + p + } +} + +impl Render for Phantom { + fn render(&mut self, w: &mut Window, cx: &mut Context) -> impl IntoElement { + w.request_animation_frame(); + if w.focused_id().is_none() && self.frames > 0 { + w.focus_id("root"); + } + self.frames += 1; + let fit = Fit::new(w, DESIGN); + let m = &self.menu; + + let confirmed = m.confirmed; + let scene = self.scene.canvas(move |_| { + let t = now(); + [t, confirmed.map_or(-1.0, |c| t - c)] + }).class("scene"); + + // the commands, right-aligned down the white star, each a ransom note on a black strip + let mut menu = at(div(), fit.ox, fit.oy).css("width", rem(DESIGN.0)).css("height", rem(DESIGN.1)); + for (i, entry) in ENTRIES.iter().enumerate() { + let on = i == m.sel; + let (right, y, size) = AT[i]; + let voice = if on { Voice::Loud { pick: m.picks } } else { Voice::Plain }; + let mut d = div().id(format!("m{i}")).class(if on { "abs item on" } else { "abs item" }) + .css("right", rem(DESIGN.0 - right)).css("top", rem(y)).css("animation-delay", format!("{}ms", 150 + i * 30)) + .css("z-index", if on { "20" } else { "10" }) + .child(div().class("strip").child(ransom(entry.name, 100 + i as u32, size, voice))); + if on { + d = d.child(div().id(format!("shard{}", m.picks)).class("shard")); + } + menu = menu.child(d + .on_hover(cx.listener(move |this, over: &bool, _, cx| if *over && this.menu.select(i) { cx.notify() })) + .on_click(cx.listener(move |this, _, _, cx| { + this.menu.select(i); + this.menu.confirm(); + cx.notify(); + }))); + } + // the labels around it + let (ox, oy) = (fit.ox, fit.oy); + let label = |x: f32, y: f32, tilt: f32, delay: usize| { + at(div().class("label"), ox + x, oy + y).css("transform", format!("rotate({tilt}deg)")) + .css("animation-delay", format!("{delay}ms")) + }; + let top = div() + .child(label(790.0, 22.0, -10.0, 300).child(ransom("Don't break", 7, 30.0, Voice::Plain))) + .child(label(1000.0, 46.0, -4.0, 360).child(div().class("card").child(ransom("PROD", 8, 44.0, Voice::Plain)))); + let right = fit.w - DESIGN.0 + 950.0 - ox; + let cards = div() + .child(label(right, 186.0, -3.0, 420).child(div().class("card").css("font-size", rem(20.0)).child("Acme Cloud"))) + .child(label(right - 14.0, 232.0, -5.0, 470).child(div().class("card black") + .child(ransom("MENU: MAIN", 9, 36.0, Voice::Plain)).child(small().child("select a command")))); + let command = div() + .child(label(400.0, 520.0, -4.0, 480).child(ransom("COMMAND", 11, 76.0, Voice::Plain))) + .child(at(div().id(format!("hint{}", m.sel)).class("hint"), ox + 560.0, oy + 622.0).child(m.hint())) + .child(label(250.0, 500.0, -6.0, 520).child(ransom("152 builds", 12, 26.0, Voice::Plain))) + .child(label(150.0, 622.0, -6.0, 560).child(ransom("$86,683 MRR", 13, 42.0, Voice::Plain))); + + let mut ui = div().class("abs ui").css("width", rem(fit.w)).css("height", rem(fit.h)) + .child(top).child(cards).child(menu).child(command); + if let Some(i) = m.closing { + ui = ui.child(self.panel(i, true)); + } + if let Some(i) = m.open { + ui = ui.child(self.panel(i, false)); + } + ui = ui.child(div().class("abs keys") + .child(div().id("close").class("key").child(div().class("cap").child("C")).child("Close") + .on_click(cx.listener(|this, _, _, cx| if this.menu.close() { cx.notify() }))) + .child(div().id("confirm").class("key").child(div().class("cap").child("⏎")).child("Confirm") + .on_click(cx.listener(|this, _, _, cx| if this.menu.confirm() { cx.notify() })))); + html().css("font-size", fit.root_font()) + .child(head().child(style().child(css()))) + .child(body().id("root").attr("tabindex", "0") + .on_key_down(cx.listener(|this, e: &KeyDownEvent, _, cx| if this.menu.key(&e.keystroke.key) { cx.notify() })) + .child(scene).child(ui)) + } +} + +/// Drives the menu headlessly: first light, the arrow keys and Enter, ↓ with the card open, a +/// click into another command, Close. +fn storyboard(dir: String) -> Script { + Box::new(move |cx, win| { + let shot = |cx: &mut App, name: &str| { + let (w, h, px) = cx.draw(win); + save_png(&format!("{dir}/{name}.png"), w, h, &px); + }; + let centre = |cx: &mut App, id: &str| { + let b = cx.element_bounds(win, id).unwrap_or_else(|| panic!("no #{id}")); + (b.origin.x + b.size.width / 2.0, b.origin.y + b.size.height / 2.0) + }; + let play = |cx: &mut App, name: &str, steps: &[u64]| { + let mut at = 0; + for &ms in steps { + cx.advance_clock(Duration::from_millis(ms - at)); + at = ms; + shot(cx, &format!("{name}-{ms:04}ms")); + } + }; + play(cx, "00-enter", &[0, 150, 300, 500, 900]); + // no click: the pointer only comes into the window (the kit takes keys once it has) + cx.simulate_mouse_move(win, 5.0, 5.0); + cx.simulate_key(win, "", "Down"); + play(cx, "01-down", &[0, 40, 90, 160, 400]); + cx.simulate_key(win, "", "Return"); + play(cx, "02-return", &[0, 80, 160, 500]); + cx.simulate_key(win, "", "Down"); + play(cx, "03-down-while-open", &[0, 400]); + let (x, y) = centre(cx, "m5"); + cx.simulate_click(win, x, y); + play(cx, "04-click", &[0, 500]); + let (x, y) = centre(cx, "close"); + cx.simulate_click(win, x, y); + play(cx, "05-close", &[0, 300]); + }) +} + +fn scene() -> Fx { + Fx::new("phantom", SCENE, 2, [140, 0, 16]) +} + +fn main() { + if let Some(dir) = arg("--frames") { + let fx = scene(); + let stills = [("phantom", [4.0f32, -1.0]), ("phantom-confirm", [4.05, 0.05])]; + if gpu_stills(&dir, 1280, 720, stills, |g, f| g.draw(fx.effect(), &[], f)).is_none() { + eprintln!("phantom shader: {:?}", fx.error()); + } + return; + } + let (w, h) = arg("--size").and_then(|s| s.split_once('x').and_then(|(a, b)| Some((a.parse().ok()?, b.parse().ok()?)))) + .unwrap_or(DESIGN); + let make = || Phantom { scene: scene(), menu: MenuState::default(), frames: 0 }; + run_with(w, h, "BUI · Phantom", make, arg("--storyboard").map(storyboard)); +} diff --git a/demos/src/bin/pipeline.rs b/demos/src/bin/pipeline.rs new file mode 100644 index 00000000..e5288f33 --- /dev/null +++ b/demos/src/bin/pipeline.rs @@ -0,0 +1,229 @@ +//! A GitHub Actions workflow as a Blender node graph, painted with BUI's `Painter` (nodes, bezier +//! links, sockets, progress) and run on a timeline: jobs light up, links flow, the log scrolls. +//! `cargo run --release --bin pipeline` + +use bui_demos::{now, run}; +use blenderui::prelude::*; + +/// Seconds of wall time per scheduled unit. +const PACE: f32 = 0.45; +const NODE_W: f32 = 176.0; +const NODE_H: f32 = 74.0; + +#[derive(Clone, Copy)] +struct Job { + name: &'static str, + color: u32, + x: f32, + y: f32, + /// Units this job runs for. + secs: f32, + /// Indices of the jobs it needs (`needs:` in the workflow). + needs: &'static [usize], +} + +const JOBS: [Job; 8] = [ + Job { name: "actions/checkout", color: 0x6b4c9a, x: 30.0, y: 190.0, secs: 1.0, needs: &[] }, + Job { name: "Lint · clippy", color: 0x4772b3, x: 280.0, y: 30.0, secs: 2.0, needs: &[0] }, + Job { name: "Build · ubuntu", color: 0x2e8b57, x: 280.0, y: 140.0, secs: 4.0, needs: &[0] }, + Job { name: "Build · windows", color: 0x2e8b57, x: 280.0, y: 250.0, secs: 5.0, needs: &[0] }, + Job { name: "Build · macos", color: 0x2e8b57, x: 280.0, y: 360.0, secs: 4.0, needs: &[0] }, + Job { name: "Test · matrix", color: 0xc26a1b, x: 540.0, y: 190.0, secs: 3.0, needs: &[1, 2, 3, 4] }, + Job { name: "Package · wheels", color: 0xb03a5b, x: 770.0, y: 190.0, secs: 2.0, needs: &[5] }, + Job { name: "Publish · release", color: 0xb03a5b, x: 1000.0, y: 190.0, secs: 1.0, needs: &[6] }, +]; +const FLAKY: usize = 5; + +#[derive(Clone, Copy, PartialEq)] +enum State { + Queued, + Running(f32), + Done, + Failed, + Skipped, +} + +/// When each job starts and ends (units), from its `needs`. +fn schedule() -> [(f32, f32); JOBS.len()] { + let mut s = [(0.0, 0.0); JOBS.len()]; + for (i, j) in JOBS.iter().enumerate() { + let start = j.needs.iter().map(|&n| s[n].1).fold(0.0, f32::max); + s[i] = (start, start + j.secs); + } + s +} + +/// Every job's state `t` units into a run; jobs after a failure are skipped. +fn states(t: f32, fail: bool) -> [State; JOBS.len()] { + let s = schedule(); + let mut out = [State::Queued; JOBS.len()]; + for i in 0..JOBS.len() { + let (a, b) = s[i]; + out[i] = if JOBS[i].needs.iter().any(|&n| matches!(out[n], State::Failed | State::Skipped)) { + State::Skipped + } else if t >= b { + if fail && i == FLAKY { State::Failed } else { State::Done } + } else if t >= a { + State::Running((t - a) / (b - a)) + } else { + State::Queued + }; + } + out +} + +const fn tint(s: State) -> u32 { + match s { + State::Running(_) => 0xe8b30d, + State::Done => 0x4caf50, + State::Failed => 0xe5534b, + State::Queued | State::Skipped => 0x8a8a8a, + } +} + +/// A Blender node link: a horizontal-tangent cubic bezier from an output to an input socket. +fn link(p: &mut Painter, (x1, y1): (f32, f32), (x2, y2): (f32, f32), color: u32, width: f32) { + let d = ((x2 - x1) * 0.5).abs().max(40.0); + let pts: [(f32, f32); 25] = std::array::from_fn(|i| { + let t = i as f32 / 24.0; + let u = 1.0 - t; + let (a, b, c, e) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t); + (a * x1 + b * (x1 + d) + c * (x2 - d) + e * x2, a * y1 + b * y1 + c * y2 + e * y2) + }); + p.line(&pts, rgb(color), width); +} + +fn paint_graph(b: Bounds, p: &mut Painter, st: &[State; JOBS.len()], t: f32) { + let (ox, oy) = (b.origin.x, b.origin.y); + p.fill(b, rgb(0x232323)); + // dot grid, like the node editor's background + let mut y = 0.0; + while y < b.size.height { + let mut x = 0.0; + while x < b.size.width { + p.fill(Bounds { origin: point(ox + x, oy + y), size: size(1.5, 1.5) }, rgb(0x333333)); + x += 20.0; + } + y += 20.0; + } + let out_sock = |j: &Job| (ox + j.x + NODE_W, oy + j.y + 34.0); + let in_sock = |j: &Job, k: usize| (ox + j.x, oy + j.y + 34.0 + k as f32 * 9.0); + for (i, j) in JOBS.iter().enumerate() { + for (k, &n) in j.needs.iter().enumerate() { + let c = tint(st[i]); + link(p, out_sock(&JOBS[n]), in_sock(j, k), c, if matches!(st[i], State::Running(_)) { 3.0 } else { 2.2 }); + if let State::Running(_) = st[i] { + // a pulse travelling down the wire + let f = (t * 1.6).fract(); + let ((x1, y1), (x2, y2)) = (out_sock(&JOBS[n]), in_sock(j, k)); + let (x, y) = (x1 + (x2 - x1) * f, y1 + (y2 - y1) * (f * f * (3.0 - 2.0 * f))); + p.oval(Bounds { origin: point(x - 4.0, y - 4.0), size: size(8.0, 8.0) }, rgb(0xffe27a), rgb(0x000000), 0.0); + } + } + } + for (i, j) in JOBS.iter().enumerate() { + let (x, y) = (ox + j.x, oy + j.y); + let s = st[i]; + let ring = match s { State::Running(_) | State::Failed => tint(s), _ => 0x111111 }; + p.quad(Bounds { origin: point(x - 2.0, y - 2.0), size: size(NODE_W + 4.0, NODE_H + 4.0) }, 8.0, rgba(0x00000055), rgb(ring), 2.0); + p.quad(Bounds { origin: point(x, y), size: size(NODE_W, NODE_H) }, 6.0, rgb(0x353535), rgb(0x111111), 1.0); + p.quad(Bounds { origin: point(x, y), size: size(NODE_W, 22.0) }, 6.0, rgb(j.color), rgb(j.color), 0.0); + p.oval(Bounds { origin: point(x + 7.0, y + 7.0), size: size(8.0, 8.0) }, rgb(tint(s)), rgb(0x000000), 1.0); + p.text(x + 21.0, y + 4.0, j.name, 12.0, rgb(0xffffff)); + let label = match s { + State::Queued => "queued".to_string(), + State::Running(f) => format!("running {:.0}%", f * 100.0), + State::Done => format!("success · {:.0}s", j.secs * 10.0), + State::Failed => "failed (exit 1)".to_string(), + State::Skipped => "skipped".to_string(), + }; + p.text(x + 10.0, y + 30.0, &label, 11.0, rgb(0xbbbbbb)); + let frac = match s { State::Running(f) => f, State::Done | State::Failed => 1.0, _ => 0.0 }; + p.quad(Bounds { origin: point(x + 10.0, y + 54.0), size: size(NODE_W - 20.0, 5.0) }, 2.5, rgb(0x222222), rgb(0x222222), 0.0); + if frac > 0.0 { + p.quad(Bounds { origin: point(x + 10.0, y + 54.0), size: size((NODE_W - 20.0) * frac, 5.0) }, 2.5, rgb(tint(s)), rgb(tint(s)), 0.0); + } + if i != 0 { + for k in 0..j.needs.len() { + let (sx, sy) = in_sock(j, k); + p.oval(Bounds { origin: point(sx - 5.0, sy - 5.0), size: size(10.0, 10.0) }, rgb(0xc7c729), rgb(0x000000), 1.0); + } + } + if i != JOBS.len() - 1 { + let (sx, sy) = out_sock(j); + p.oval(Bounds { origin: point(sx - 5.0, sy - 5.0), size: size(10.0, 10.0) }, rgb(0xc7c729), rgb(0x000000), 1.0); + } + } +} + +const CSS: &str = r" +body { margin: 0; display: flex; flex-direction: column; height: 100%; background: #1d1d1d; color: #d9d9d9; font-size: 12px; } +.bar { display: flex; align-items: center; gap: 10px; height: 30px; padding: 0 10px; background: #252525; border-bottom: 1px solid #111; } +.bar .sp { flex: 1; } +html { height: 100%; } +.graph { flex: 1 1 0; min-height: 0; } +.log { height: 150px; flex-shrink: 0; background: #161616; border-top: 1px solid #000; padding: 6px 10px; overflow: auto; font-family: monospace; font-size: 11px; color: #9a9a9a; } +.ok { color: #4caf50; } .run { color: #e8b30d; } .fail { color: #e5534b; } +"; + +struct Pipeline { + started: Option, + fail: bool, +} + +impl Pipeline { + fn elapsed(&self) -> f32 { + self.started.map_or(-1.0, |s| (now() - s) / PACE) + } +} + +impl Render for Pipeline { + fn render(&mut self, w: &mut Window, cx: &mut Context) -> impl IntoElement { + let t = self.elapsed(); + let st = if t < 0.0 { [State::Queued; JOBS.len()] } else { states(t, self.fail) }; + let finished = st.iter().all(|s| matches!(s, State::Done | State::Failed | State::Skipped)); + if self.started.is_some() && !finished { + w.request_animation_frame(); + } + // the log: one line per event that has happened so far + let sch = schedule(); + let mut log = div().class("log"); + if t < 0.0 { + log = log.child(div().child("Press ▶ Run workflow.")); + } + for (i, j) in JOBS.iter().enumerate() { + if st[i] == State::Skipped { continue; } + if t >= sch[i].0 { + log = log.child(div().class("run").child(format!("[{:>5.1}s] ▶ {}", sch[i].0 * 10.0, j.name))); + } + match st[i] { + State::Done => log = log.child(div().class("ok").child(format!("[{:>5.1}s] ✔ {}", sch[i].1 * 10.0, j.name))), + State::Failed => log = log.child(div().class("fail").child(format!("[{:>5.1}s] ✖ {} — 1 test failed on macos-14", sch[i].1 * 10.0, j.name))), + _ => {} + } + } + if finished && t >= 0.0 { + let (c, m) = if self.fail { ("fail", "Workflow failed: downstream jobs skipped") } else { ("ok", "Workflow succeeded") }; + log = log.child(div().class(c).child(m)); + } + html().styled() + .child(head().child(style().child(CSS))) + .child(body() + .child(div().class("bar") + .child(b().child(".github/workflows/ci.yml")) + .child(div().class("sp")) + .child(label().child(input().input_type("checkbox").checked(self.fail) + .on_change(cx.listener(|this, e: &ChangeEvent, _, cx| { this.fail = e.checked; cx.notify(); }))) + .child(" Make the test job fail")) + .child(button().child("▶ Run workflow").on_click(cx.listener(|this, _, _, cx| { + this.started = Some(now()); + cx.notify(); + })))) + .child(canvas(move |b, p| paint_graph(b, p, &st, now())).class("graph")) + .child(log)) + } +} + +fn main() { + run(1210.0, 620.0, "BUI · CI pipeline", || Pipeline { started: None, fail: false }); +} diff --git a/demos/src/bin/shaders.rs b/demos/src/bin/shaders.rs new file mode 100644 index 00000000..b0515dd2 --- /dev/null +++ b/demos/src/bin/shaders.rs @@ -0,0 +1,129 @@ +//! Three GPU shader components on BUI's `ShaderEffect`: a plasma button (hover), an aurora card +//! (follows the cursor) and a ripple field (click). `cargo run --release --bin shaders` + +use bui_demos::{now, run, uv_in, Fx}; +use blenderui::prelude::*; + +// U[0] = time, U[1] = hover 0..1 +const PLASMA: &str = " +vec4 effect(vec2 p) { + vec2 q = p / box_size * 6.0; + float t = U[0] * (1.0 + U[1] * 2.0); + float v = sin(q.x + t) + sin(q.y * 1.3 - t) + sin((q.x + q.y) * 0.7 + t * 0.5) + + sin(length(q - 3.0) * 1.5 - t * 1.2); + vec3 c = 0.5 + 0.5 * cos(vec3(v) + vec3(0.0, 2.1, 4.2) + U[1] * 1.5); + return vec4(c * (0.7 + 0.3 * U[1]), 1.0); +}"; + +// U[0] = time, U[1..2] = cursor uv +const AURORA: &str = " +float h(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5); } +float n(vec2 p) { + vec2 i = floor(p); vec2 f = fract(p); f = f * f * (3.0 - 2.0 * f); + return mix(mix(h(i), h(i + vec2(1.0, 0.0)), f.x), mix(h(i + vec2(0.0, 1.0)), h(i + vec2(1.0, 1.0)), f.x), f.y); +} +float fbm(vec2 p) { return 0.5 * n(p) + 0.25 * n(p * 2.0) + 0.125 * n(p * 4.0) + 0.0625 * n(p * 8.0); } +vec4 effect(vec2 p) { + vec2 uv = p / box_size; uv.y = 1.0 - uv.y; + vec2 m = vec2(U[1], U[2]); + vec2 q = uv * vec2(box_size.x / box_size.y, 1.0) * 3.0; + float a = fbm(q + U[0] * 0.1); + float r = fbm(q + a * 2.0 + vec2(U[0] * 0.15, 0.0) + m * 2.0); + vec3 c = mix(vec3(0.02, 0.05, 0.15), vec3(0.1, 0.9, 0.6), smoothstep(0.3, 0.8, r)); + c = mix(c, vec3(0.6, 0.2, 0.9), smoothstep(0.5, 1.0, a) * 0.7); + c += 0.25 * smoothstep(0.5, 0.0, distance(uv, m)); + return vec4(c, 1.0); +}"; + +// U[0] = time, U[1] = click age (<0: none), U[2..3] = click uv +const RIPPLE: &str = " +vec4 effect(vec2 p) { + vec2 uv = p / box_size; uv.y = 1.0 - uv.y; + float asp = box_size.x / box_size.y; + vec2 c = vec2(U[2], U[3]); + float d = length((uv - vec2(0.5)) * vec2(asp, 1.0)); + float w = sin(d * 40.0 - U[0] * 4.0) * exp(-d * 4.0); + float dk = length((uv - c) * vec2(asp, 1.0)); + float k = U[1] >= 0.0 ? sin(dk * 40.0 - U[1] * 30.0) * exp(-dk * 3.0 - U[1] * 2.0) : 0.0; + float g = 0.5 + 0.5 * (w + k); + vec3 col = mix(vec3(0.02, 0.1, 0.2), vec3(0.2, 0.8, 1.0), g * g); + col += pow(max(0.0, 1.0 - d * 2.0), 3.0) * 0.3; + return vec4(col, 1.0); +}"; + +const CSS: &str = r" +body { margin: 0; padding: 18px; background: #232323; } +.row { display: flex; gap: 18px; } +.card { position: relative; width: 300px; height: 250px; } +.cv { position: absolute; left: 0; top: 0; width: 300px; height: 250px; border-radius: 14px; } +.cap { position: absolute; left: 0; top: 96px; width: 300px; text-align: center; color: #fff; } +.cap h2 { margin: 0; font-size: 22px; } +.cap p { margin: 4px 0 0; font-size: 12px; opacity: 0.8; } +"; + +struct Shaders { + plasma: Fx, + aurora: Fx, + ripple: Fx, + hover: f32, + hover_target: f32, + mouse: (f32, f32), + click: Option<(f32, f32, f32)>, // time, window x, y + reported: bool, +} + +impl Render for Shaders { + fn render(&mut self, w: &mut Window, cx: &mut Context) -> impl IntoElement { + w.request_animation_frame(); + self.hover += (self.hover_target - self.hover) * 0.1; + if !self.reported && now() > 0.5 { + self.reported = true; + for (n, f) in [("plasma", &self.plasma), ("aurora", &self.aurora), ("ripple", &self.ripple)] { + eprintln!("{n}: {:?}", f.error()); + } + } + let hover = self.hover; + let (mx, my) = self.mouse; + let click = self.click; + let plasma = self.plasma.canvas(move |_| vec![now(), hover]).class("cv"); + let aurora = self.aurora.canvas(move |b| { + let [u, v] = uv_in(b, mx, my); + vec![now(), u, v] + }).class("cv"); + let ripple = self.ripple.canvas(move |b| match click { + Some((t0, x, y)) => { + let [u, v] = uv_in(b, x, y); + vec![now(), now() - t0, u, 1.0 - v] + } + None => vec![now(), -1.0, 0.5, 0.5], + }).class("cv"); + let cap = |t: &'static str, s: &'static str| div().class("cap").child(h2().child(t)).child(p().child(s)); + html().styled() + .child(head().child(style().child(CSS))) + .child(body().child(div().class("row") + .child(div().class("card") + .on_hover(cx.listener(|this, over: &bool, _, _| this.hover_target = f32::from(u8::from(*over)))) + .child(plasma).child(cap("Plasma Button", "hover to speed up"))) + .child(div().class("card") + .on_mouse_move(cx.listener(|this, e: &MouseMoveEvent, _, _| this.mouse = (e.position.x.0, e.position.y.0))) + .child(aurora).child(cap("Aurora Card", "follows your cursor"))) + .child(div().class("card") + .on_any_mouse_down(cx.listener(|this, e: &MouseDownEvent, _, _| { + this.click = Some((now(), e.position.x.0, e.position.y.0)); + })) + .child(ripple).child(cap("Ripple Field", "click to drop a wave"))))) + } +} + +fn main() { + run(990.0, 290.0, "BUI · shader components", || Shaders { + plasma: Fx::new("plasma", PLASMA, 2, [120, 60, 200]), + aurora: Fx::new("aurora", AURORA, 3, [20, 120, 100]), + ripple: Fx::new("ripple", RIPPLE, 4, [20, 90, 140]), + hover: 0.0, + hover_target: 0.0, + mouse: (0.0, 0.0), + click: None, + reported: false, + }); +} diff --git a/demos/src/bin/velvet.rs b/demos/src/bin/velvet.rs new file mode 100644 index 00000000..65ed6e35 --- /dev/null +++ b/demos/src/bin/velvet.rs @@ -0,0 +1,323 @@ +//! Velvet Menu: a Persona-style main menu for a tech app, on BUI. A GPU shader is the water +//! (caustics, light shafts, a room far behind, rising motes); over it, a heavy italic menu tilted +//! across the screen. The item under the pointer (or the arrow keys) snaps forward, black on a red +//! slash; Enter / click / Confirm stamps it and slides in its sub-menu, which follows the arrows; +//! C / Escape / Close puts it away. Laid out on a 1280 x 720 canvas in `rem`, sized to the window +//! (see `bui_demos::canvas`), so it stays sharp at any size. +//! +//! Motion ("energetic"): selection snaps in 180 ms with an overshoot, the red slash 160 ms behind +//! it and the pink sliver 40 ms after that; the menu flies in 35 ms per item on first light, the +//! counter counts up; the water, the shards and the motes keep moving underneath. +//! +//! `cargo run --release --bin velvet` +//! `-- --storyboard DIR` drives it headlessly (keys, hover, clicks) and saves frames along BUI's +//! virtual clock (`-- --size 1600x600` for another window size); `-- --frames DIR` renders the +//! water off-screen on the GPU. + +use std::sync::OnceLock; +use std::time::Duration; + +use blenderui::prelude::*; +use bui_demos::canvas::{rem, rem_css, Fit}; +use bui_demos::menu::{MenuState, ENTRIES}; +use bui_demos::{arg, gpu_stills, now, run_with, save_png, Fx, Script}; + +/// U[0] = time, U[1] = seconds since the last confirm (< 0: none). +const WATER: &str = r" +float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); } + +vec4 effect(vec2 p) { + float t = U[0]; float pulse = U[1]; + vec2 uv = p / box_size; + vec2 q = vec2(uv.x * box_size.x / box_size.y, uv.y); + // depth: shallow cyan under the surface, deep blue below + vec3 c = mix(vec3(0.32, 0.95, 1.0), vec3(0.04, 0.55, 0.96), smoothstep(0.0, 0.5, uv.y)); + c = mix(c, vec3(0.0, 0.13, 0.72), smoothstep(0.45, 1.0, uv.y)); + // the room far behind the water: pale pillars and a rail, swaying with the refraction + float sway = 0.012 * sin(uv.y * 14.0 + t * 0.9); + float pillar = smoothstep(0.035, 0.0, abs(fract((q.x + sway) * 1.6 + 0.15) - 0.5) - 0.06); + float rail = smoothstep(0.01, 0.0, abs(uv.y - 0.56 - 0.05 * sin(q.x * 1.7) + sway)); + c = mix(c, c * 1.18 + 0.05, (0.3 * pillar + 0.25 * rail) * smoothstep(0.15, 0.6, uv.y)); + // caustics, brightest near the surface + vec2 z = q * 5.5 + vec2(t * 0.15, t * 0.1); + float k = 0.0; + for (int i = 0; i < 3; i++) { + z = vec2(z.x + sin(z.y + t * 0.6), z.y + cos(z.x - t * 0.5)); + k += 1.0 / (1.0 + 30.0 * abs(sin(z.x) * sin(z.y))); + } + c += vec3(0.55, 0.95, 1.0) * pow(k / 3.0, 2.0) * (1.0 - smoothstep(0.0, 0.75, uv.y)) * 0.9; + // light shafts from the surface + float shaft = (0.5 + 0.5 * sin(q.x * 8.0 + q.y * 3.0 + 2.0 * sin(t * 0.25))) * (0.5 + 0.5 * sin(q.x * 21.0 - q.y * 4.0 + t * 0.35)); + c += vec3(0.6, 0.95, 1.0) * pow(shaft, 3.0) * 0.22 * (1.0 - uv.y); + // motes rising + vec2 g = q * vec2(16.0, 9.0) + vec2(0.0, t * 0.5); + vec2 id = floor(g); + vec2 f = fract(g) - 0.5 - (vec2(hash(id + 1.3), hash(id + 2.1)) - 0.5) * 0.6; + c += step(0.86, hash(id)) * smoothstep(0.07, 0.0, length(f)) * 0.4; + // a confirm lights the water for a moment + if (pulse >= 0.0) c += vec3(0.25, 0.3, 0.35) * exp(-pulse * 7.0); + c += (hash(p + fract(t) * 17.0) - 0.5) * 0.025; + return vec4(clamp(c, 0.0, 1.0), 1.0); +} +"; + +const CSS: &str = r" +html { height: 100%; } +body { margin: 0; height: 100%; position: relative; overflow: hidden; background: #0730c8; user-select: none; + font-family: Inter, system-ui, sans-serif; -webkit-font-smoothing: antialiased; } +.water { position: absolute; left: 0; top: 0; width: 100%; height: 100%; } +.ui { left: 0; top: 0; } +.abs { position: absolute; } + +/* -- the left: an ink slash, drifting shards, MENU running down the edge -- */ +.ink { left: 0; top: 0; width: 520px; height: 100%; background: #f4fbff; + clip-path: polygon(0 0, 62% 0, 38% 46%, 52% 100%, 0 100%); + animation: inkin 420ms cubic-bezier(0.2, 0, 0, 1) backwards; } +.ink2 { left: 0; top: 0; width: 520px; height: 100%; background: #3fd8ff; + clip-path: polygon(30% 52%, 44% 50%, 56% 100%, 40% 100%); opacity: 0.75; + animation: inkin 420ms cubic-bezier(0.2, 0, 0, 1) 80ms backwards; } +.menuword { left: -150px; top: 250px; font-size: 230px; font-weight: 900; letter-spacing: -14px; color: #050505; + transform: rotate(90deg); white-space: nowrap; animation: wordin 520ms cubic-bezier(0.2, 0, 0, 1) backwards; } +.bar { left: 0; top: 0; width: 38px; height: 280px; background: #7a7a7a; } +.shard { width: 34px; height: 46px; clip-path: polygon(50% 0, 100% 60%, 30% 100%); + animation: drift 6s ease-in-out infinite alternate; } + +/* -- the counter -- */ +.wallet { left: 112px; top: 38px; width: 178px; height: 64px; border: 2px solid #000; background: rgba(255,255,255,0.92); + padding: 6px 12px; box-sizing: border-box; animation: drop 360ms cubic-bezier(0.2, 0, 0, 1) 120ms backwards; } +.yen { font-size: 28px; font-weight: 300; color: #000; letter-spacing: -1px; font-variant-numeric: tabular-nums; line-height: 1.1; } +.wallet small { display: block; font-size: 10px; font-weight: 700; font-style: italic; color: #000; } + +/* -- the menu: heavy italics, tilted, each where it sits in the stack -- */ +.item { padding: 0 10px; font-weight: 900; color: #8af4ff; letter-spacing: -3px; white-space: nowrap; line-height: 1; + transform: rotate(-14deg) skewX(-12deg); transform-origin: left center; cursor: pointer; + transition-property: transform, color, opacity; transition-duration: 180ms; + transition-timing-function: cubic-bezier(0.34, 1.56, 0.64, 1); + animation: flyin 340ms cubic-bezier(0.2, 0, 0, 1) backwards; } +.item span { position: relative; display: inline-block; } +.item.on { color: #050505; transform: rotate(-14deg) skewX(-12deg) scale(1.2) translateX(-8px); } +.dim .item { opacity: 0.4; transform: rotate(-14deg) skewX(-12deg) translateX(-30px); } +.dim .item.on { opacity: 1; transform: rotate(-14deg) skewX(-12deg) scale(1.2) translateX(-38px); } +.slash { position: absolute; left: -26px; top: 18%; height: 70%; width: calc(100% + 70px); background: #ff1530; + clip-path: polygon(0 62%, 100% 0, 93% 100%, 2% 100%); transform-origin: left center; + animation: slash 160ms cubic-bezier(0.2, 0, 0, 1) backwards; } +.sliver { position: absolute; left: -12px; top: 6%; height: 80%; width: calc(100% + 92px); background: #ff8fd0; + clip-path: polygon(93% 12%, 100% 4%, 97% 96%, 94.5% 96%); transform-origin: left center; + animation: slash 160ms cubic-bezier(0.2, 0, 0, 1) 40ms backwards; } +/* on the label, not the item: swapping the item's own animation would replay its entrance */ +.stamp { animation: stamp 260ms cubic-bezier(0.2, 0, 0, 1); } + +/* -- the sub-menu a confirm slides in -- */ +.panel { z-index: 30; right: 70px; top: 120px; width: 400px; padding: 18px 26px 22px; background: #f4fbff; + box-shadow: 10px 10px 0 #050505; transform: skewX(-8deg); + animation: panelin 300ms cubic-bezier(0.2, 0, 0, 1) backwards; } +.panel h2 { margin: 0 0 10px; font-size: 34px; font-weight: 900; font-style: italic; color: #050505; letter-spacing: -2px; + border-bottom: 5px solid #ff1530; padding-bottom: 4px; } +.row { display: flex; justify-content: space-between; padding: 8px 10px; font-size: 16px; font-weight: 700; color: #082a6e; + transition-property: background-color, color; transition-duration: 80ms; + animation: rowin 220ms cubic-bezier(0.2, 0, 0, 1) backwards; } +.row:hover { background: #050505; color: #8af4ff; } +.row b { font-weight: 400; color: #5576b0; font-variant-numeric: tabular-nums; } +.out { animation: panelout 150ms cubic-bezier(0.3, 0, 1, 1) forwards; pointer-events: none; } + +/* -- the hint, bottom right -- */ +.hint { z-index: 30; right: 0; bottom: 74px; width: 330px; color: #fff; } +.hint .what { font-size: 30px; font-weight: 700; font-style: italic; letter-spacing: -1px; padding-left: 14px; } +.hint .kind { font-size: 12px; font-weight: 700; padding-left: 14px; border-bottom: 2px solid #fff; } +.keys { z-index: 30; right: 30px; bottom: 22px; display: flex; gap: 10px; color: #fff; font-size: 24px; font-weight: 700; font-style: italic; } +.key { display: flex; align-items: center; gap: 6px; padding: 4px 6px; cursor: pointer; + transition-property: transform; transition-duration: 120ms; } +.key:active { transform: scale(0.96); } +.cap { width: 22px; height: 22px; border: 2px solid #fff; border-radius: 3px; font-size: 12px; font-style: normal; + display: flex; align-items: center; justify-content: center; } + +/* -- motion -- */ +@keyframes inkin { from { opacity: 0; transform: translateX(-60px); } to { opacity: 1; transform: translateX(0); } } +@keyframes wordin { from { opacity: 0; transform: rotate(90deg) translateX(80px); } to { opacity: 1; transform: rotate(90deg) translateX(0); } } +@keyframes drop { from { opacity: 0; transform: translateY(-16px); } to { opacity: 1; transform: translateY(0); } } +@keyframes drift { from { transform: translate(0, 0) rotate(0deg); } to { transform: translate(14px, -22px) rotate(24deg); } } +@keyframes flyin { from { opacity: 0; transform: rotate(-14deg) skewX(-12deg) translateX(140px); } + to { opacity: 1; transform: rotate(-14deg) skewX(-12deg) translateX(0); } } +@keyframes slash { 0% { transform: scaleX(0); } 70% { transform: scaleX(1.08); } 100% { transform: scaleX(1); } } +@keyframes stamp { 0% { transform: scale(1); } 40% { transform: scale(1.18); } 100% { transform: scale(1); } } +@keyframes panelin { from { opacity: 0; transform: skewX(-8deg) translateX(120px); } to { opacity: 1; transform: skewX(-8deg) translateX(0); } } +@keyframes rowin { from { opacity: 0; transform: translateX(40px); } to { opacity: 1; transform: translateX(0); } } +@keyframes panelout { to { opacity: 0; transform: skewX(-8deg) translateX(60px); } } +"; + +/// Where each entry sits on the design canvas: x, y, font size (design px). +const AT: [(f32, f32, f32); 9] = [ + (500.0, 168.0, 62.0), (585.0, 232.0, 48.0), (562.0, 270.0, 56.0), (510.0, 318.0, 62.0), (590.0, 374.0, 50.0), + (548.0, 418.0, 54.0), (540.0, 470.0, 50.0), (520.0, 522.0, 56.0), (556.0, 574.0, 50.0), +]; + +/// The counter in the top-left box, counted up on first light. +const REQUESTS: f32 = 73_797.0; +const DESIGN: (f32, f32) = (1280.0, 720.0); + +fn css() -> &'static str { + static CSS_REM: OnceLock = OnceLock::new(); + CSS_REM.get_or_init(|| rem_css(CSS)) +} + +struct Velvet { + water: Fx, + menu: MenuState, + started: f32, + /// Frames rendered: the page takes keyboard focus once one exists. + frames: u32, +} + +impl Velvet { + fn panel(&self, i: usize, leaving: bool) -> Div { + let entry = &ENTRIES[i]; + let mut p = div().id(format!("panel{i}-{}", self.menu.confirms)).class(if leaving { "abs panel out" } else { "abs panel" }) + .child(h2().child(entry.name)); + for (k, (name, value)) in entry.rows.iter().enumerate() { + p = p.child(div().class("row").css("animation-delay", format!("{}ms", 120 + k * 40)) + .child(span().child(*name)).child(b().child(*value))); + } + p + } +} + +/// Places an absolutely positioned element (design px). +fn at(d: Div, x: f32, y: f32) -> Div { + d.class("abs").css("left", rem(x)).css("top", rem(y)) +} + +impl Render for Velvet { + fn render(&mut self, w: &mut Window, cx: &mut Context) -> impl IntoElement { + w.request_animation_frame(); + // keys come to the page without a click: focus it once its first frame exists + if w.focused_id().is_none() && self.frames > 0 { + w.focus_id("root"); + } + self.frames += 1; + let fit = Fit::new(w, DESIGN); + + let confirmed = self.menu.confirmed; + let water = self.water.canvas(move |_| { + let t = now(); + [t, confirmed.map_or(-1.0, |c| t - c)] + }).class("water"); + // the counter counts up on first light (ease-out cubic) + let k = ((now() - self.started - 0.3) / 0.9).clamp(0.0, 1.0); + let n = (REQUESTS * (1.0 - (1.0 - k).powi(3))).round() as u32; + let requests = format!("{},{:03}", n / 1000, n % 1000); + + let mut left = div() + .child(div().class("abs bar")) + .child(div().class("abs ink")).child(div().class("abs ink2")); + for (i, (x, y, color, delay)) in [(250.0, 120.0, "#ff6fd8", 0), (330.0, 300.0, "#3fd8ff", 1500), (180.0, 470.0, "#9b6bff", 800), + (420.0, 560.0, "#ff6fd8", 2300), (90.0, 610.0, "#3fd8ff", 400)].into_iter().enumerate() { + left = left.child(at(div().class("shard"), x, y).css("background", color) + .css("animation-delay", format!("-{delay}ms")).css("transform", format!("rotate({}deg)", i * 40))); + } + left = left.child(div().class("abs menuword").child("MENU")); + + let m = &self.menu; + let mut menu = at(div(), fit.ox, fit.oy).css("width", rem(DESIGN.0)).css("height", rem(DESIGN.1)) + .class(if m.open.is_some() { "dim" } else { "" }); + for (i, entry) in ENTRIES.iter().enumerate() { + let on = i == m.sel; + let (x, y, size) = AT[i]; + let mut d = at(div().id(format!("m{i}")), x, y).class(if on { "item on" } else { "item" }) + .css("font-size", rem(size)).css("animation-delay", format!("{}ms", 200 + i * 35)) + .css("z-index", if on { "20" } else { "10" }); + if on { + // keyed by the pick, so the slash snaps in again on each selection + d = d.child(div().id(format!("slash{}", m.picks)).class("slash")) + .child(div().id(format!("sliver{}", m.picks)).class("sliver")); + } + // the stamp is on the label, keyed by the confirm so a second Enter stamps again + let label = if on && m.open == Some(i) { span().id(format!("stamp{}", m.confirms)).class("stamp") } else { span() }; + menu = menu.child(d.child(label.child(entry.name)) + .on_hover(cx.listener(move |this, over: &bool, _, cx| if *over && this.menu.select(i) { cx.notify() })) + .on_click(cx.listener(move |this, _, _, cx| { + this.menu.select(i); + this.menu.confirm(); + cx.notify(); + }))); + } + let mut ui = div().class("abs ui").css("width", rem(fit.w)).css("height", rem(fit.h)) + .child(left) + .child(div().class("abs wallet").child(div().class("yen").child(requests)).child(small().child("requests today"))) + .child(menu); + if let Some(i) = m.closing { + ui = ui.child(self.panel(i, true)); + } + if let Some(i) = m.open { + ui = ui.child(self.panel(i, false)); + } + ui = ui + .child(div().class("abs hint").child(div().class("what").child(m.hint())).child(div().class("kind").child("Command"))) + .child(div().class("abs keys") + .child(div().id("confirm").class("key").child(div().class("cap").child("⏎")).child("Confirm") + .on_click(cx.listener(|this, _, _, cx| if this.menu.confirm() { cx.notify() }))) + .child(div().id("close").class("key").child(div().class("cap").child("C")).child("Close") + .on_click(cx.listener(|this, _, _, cx| if this.menu.close() { cx.notify() })))); + html().css("font-size", fit.root_font()) + .child(head().child(style().child(css()))) + .child(body().id("root").attr("tabindex", "0") + .on_key_down(cx.listener(|this, e: &KeyDownEvent, _, cx| if this.menu.key(&e.keystroke.key) { cx.notify() })) + .child(water).child(ui)) + } +} + +/// Drives the menu headlessly with no click first: the arrow keys and Enter straight away, a +/// hover, Enter again, a click into another sub-menu, Close. +fn storyboard(dir: String) -> Script { + Box::new(move |cx, win| { + let shot = |cx: &mut App, name: &str| { + let (w, h, px) = cx.draw(win); + save_png(&format!("{dir}/{name}.png"), w, h, &px); + }; + let centre = |cx: &mut App, id: &str| { + let b = cx.element_bounds(win, id).unwrap_or_else(|| panic!("no #{id}")); + (b.origin.x + b.size.width / 2.0, b.origin.y + b.size.height / 2.0) + }; + let play = |cx: &mut App, name: &str, steps: &[u64]| { + let mut at = 0; + for &ms in steps { + cx.advance_clock(Duration::from_millis(ms - at)); + at = ms; + shot(cx, &format!("{name}-{ms:04}ms")); + } + }; + play(cx, "00-enter", &[0, 150, 300, 450, 700, 1200]); + // no click: the pointer only comes into the window (the kit takes keys once it has) + cx.simulate_mouse_move(win, 5.0, 5.0); + cx.simulate_key(win, "", "Down"); + play(cx, "01-down", &[0, 60, 120, 200, 400]); + cx.simulate_key(win, "", "Return"); + play(cx, "02-return", &[0, 80, 300, 600]); + cx.simulate_key(win, "", "Down"); + play(cx, "03-down-while-open", &[0, 300]); + let (x, y) = centre(cx, "m6"); + cx.simulate_click(win, x, y); + play(cx, "04-click", &[0, 80, 600]); + let (x, y) = centre(cx, "close"); + cx.simulate_click(win, x, y); + play(cx, "05-close", &[0, 80, 300]); + }) +} + +fn water() -> Fx { + Fx::new("water", WATER, 2, [14, 110, 230]) +} + +fn main() { + if let Some(dir) = arg("--frames") { + let fx = water(); + let stills = [("water", [4.0f32, -1.0]), ("water-confirm", [4.1, 0.05])]; + if gpu_stills(&dir, 1280, 720, stills, |g, f| g.draw(fx.effect(), &[], f)).is_none() { + eprintln!("water shader: {:?}", fx.error()); + } + return; + } + let (w, h) = arg("--size").and_then(|s| s.split_once('x').and_then(|(a, b)| Some((a.parse().ok()?, b.parse().ok()?)))) + .unwrap_or(DESIGN); + let make = || Velvet { water: water(), menu: MenuState::default(), started: now(), frames: 0 }; + run_with(w, h, "BUI · Velvet Menu", make, arg("--storyboard").map(storyboard)); +} diff --git a/demos/src/canvas.rs b/demos/src/canvas.rs new file mode 100644 index 00000000..a17e57ba --- /dev/null +++ b/demos/src/canvas.rs @@ -0,0 +1,71 @@ +//! A design canvas that fits any window crisply. A demo lays out at a design size in CSS pixels; +//! [`rem_css`] rewrites those pixels as `rem`, and [`Fit`] sets the root font size to the scale, so +//! BUI lays everything out at the window's real size. (Scaling a finished layout with a CSS +//! `transform` instead resamples it: text and turned layers come out soft at large sizes.) + +use blenderui::prelude::*; + +/// How a design canvas sits in a window: `scale` fits it whole, and the canvas grows (`w`, `h` in +/// design pixels) to fill the rest; (`ox`, `oy`) centres the design inside it. +#[derive(Clone, Copy)] +pub struct Fit { + pub scale: f32, + pub w: f32, + pub h: f32, + pub ox: f32, + pub oy: f32, +} + +impl Fit { + #[must_use] + pub fn new(window: &Window, design: (f32, f32)) -> Self { + let vp = window.viewport_size(); + let scale = (vp.width.0 / design.0).min(vp.height.0 / design.1).max(0.1); + let (w, h) = (vp.width.0 / scale, vp.height.0 / scale); + Self { scale, w, h, ox: (w - design.0) / 2.0, oy: (h - design.1) / 2.0 } + } + + /// The root font size that makes `1rem` one design pixel x 16 at this scale. + #[must_use] + pub fn root_font(&self) -> String { + format!("{}px", 16.0 * self.scale) + } +} + +/// A length in design pixels, as `rem`. +#[must_use] +pub fn rem(design_px: f32) -> String { + format!("{}rem", design_px / 16.0) +} + +/// `css` with every `px` written as `rem` (16 design pixels each). +#[must_use] +pub fn rem_css(css: &str) -> String { + let mut out = String::with_capacity(css.len() + css.len() / 8); + let b = css.as_bytes(); + let mut i = 0; + while i < b.len() { + // a number: digits with at most one '.', not part of a name (`h2`, `#3fd8ff`) + let starts = (b[i].is_ascii_digit() || (b[i] == b'.' && b.get(i + 1).is_some_and(u8::is_ascii_digit))) + && !(i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'#')); + if starts { + let mut j = i; + while j < b.len() && (b[j].is_ascii_digit() || b[j] == b'.') { + j += 1; + } + if css[j..].starts_with("px") { + let v: f32 = css[i..j].parse().unwrap_or(0.0); + out.push_str(&rem(v)); + i = j + 2; + continue; + } + out.push_str(&css[i..j]); + i = j; + continue; + } + let ch = css[i..].chars().next().unwrap_or(' '); + out.push(ch); + i += ch.len_utf8(); + } + out +} diff --git a/demos/src/lib.rs b/demos/src/lib.rs new file mode 100644 index 00000000..a8a53a4a --- /dev/null +++ b/demos/src/lib.rs @@ -0,0 +1,163 @@ +//! Shared by every demo: the one place that opens a window, declares a GPU shader with its +//! software fallback, and keeps the clock. Demos hold their own state in their `Render` struct. + +use std::rc::Rc; +use std::sync::{Arc, OnceLock}; +use std::time::Instant; + +use blenderui::GpuTarget; +use blenderui::prelude::*; + +pub mod canvas; +pub mod menu; + +/// Seconds since the first call (the shaders' clock). +#[must_use] +pub fn now() -> f32 { + static START: OnceLock = OnceLock::new(); + START.get_or_init(Instant::now).elapsed().as_secs_f32() +} + +/// A GPU pixel shader and the flat image drawn where there is no GPU (software renderer). +pub struct Fx { + effect: Rc, + fallback: Arc, +} + +impl Fx { + /// `glsl` defines `vec4 effect(vec2 p)`; `floats` is how many `U[i]` it reads. + /// + /// # Panics + /// When the declaration itself is invalid (the compile log arrives once drawn, see [`Fx::error`]). + #[must_use] + pub fn new(name: &str, glsl: &str, floats: usize, fallback_rgb: [u8; 3]) -> Self { + Self::sampling(name, glsl, 0, floats, fallback_rgb) + } + + /// [`Fx::new`] for a shader that also samples `inputs` textures (`input_color` / `input_raw`). + /// + /// # Panics + /// As [`Fx::new`]. + #[must_use] + pub fn sampling(name: &str, glsl: &str, inputs: usize, floats: usize, fallback_rgb: [u8; 3]) -> Self { + let effect = ShaderEffect::new(name, glsl, inputs, floats).unwrap_or_else(|e| panic!("{e}")); + let px: Vec = (0..16 * 16).flat_map(|_| [fallback_rgb[0], fallback_rgb[1], fallback_rgb[2], 255]).collect(); + Self { effect: Rc::new(effect), fallback: Arc::new(Image::from_rgba(16, 16, &px).expect("fallback image")) } + } + + /// The shader itself (off-screen drawing with `GpuTarget`, or a pass inside another canvas). + #[must_use] + pub const fn effect(&self) -> &Rc { + &self.effect + } + + /// The GPU compile log of the last attempt ("" when fine). + #[must_use] + pub fn error(&self) -> String { + self.effect.error() + } + + /// A canvas running the shader; `floats` is evaluated per frame with the box's own geometry + /// (`origin`, `size` in logical pixels) so a demo can turn window coordinates into box UV. + pub fn canvas>(&self, floats: impl Fn(Bounds) -> F + 'static) -> Div { + self.canvas_after(Vec::new(), |_, _, _| {}, floats) + } + + /// [`Fx::canvas`] sampling `inputs`, with `pass` recorded first each frame (given the same + /// floats): an `effect_to` into a render target this shader then reads. + pub fn canvas_after>(&self, inputs: Vec, pass: impl Fn(Bounds, &mut Painter, &[f32]) + 'static, + floats: impl Fn(Bounds) -> F + 'static) -> Div { + let (e, fb) = (self.effect.clone(), self.fallback.clone()); + canvas(move |b, p| { + let f = floats(b); + pass(b, p, f.as_ref()); + p.effect(b, &e, &inputs, f.as_ref(), Some(&fb)); + }) + } +} + +/// A point in window coordinates as 0..1 UV inside `b`, y up (GLSL convention). +#[must_use] +pub fn uv_in(b: Bounds, x: f32, y: f32) -> [f32; 2] { + [(x - b.origin.x) / b.size.width.max(1.0), 1.0 - (y - b.origin.y) / b.size.height.max(1.0)] +} + +/// What drives a headless run: it gets the app and the window, and can click, step the virtual +/// clock (`advance_clock`) and draw. +pub type Script = Box; + +/// The value after `flag` on the command line (`--screenshot out.png`). +#[must_use] +pub fn arg(flag: &str) -> Option { + std::env::args().skip_while(|a| a != flag).nth(1) +} + +/// Opens one GPU window and runs `make`'s view in it. With `--screenshot out.png` it renders one +/// frame off-screen instead (software renderer: shaders show their fallback) and saves it. +pub fn run(w: f32, h: f32, title: &str, make: impl FnOnce() -> V + 'static) { + let shot = arg("--screenshot").map(|path| -> Script { + Box::new(move |cx, win| { + let (pw, ph, pixels) = cx.draw(win); + save_png(&path, pw, ph, &pixels); + }) + }); + run_with(w, h, title, make, shot); +} + +/// [`run`], or with a `script` the same view in a headless window (software renderer, virtual +/// clock) that the script drives instead. +/// +/// # Panics +/// When the window cannot be opened. +pub fn run_with(w: f32, h: f32, title: &str, make: impl FnOnce() -> V + 'static, + script: Option