app: cherry-pick rune's pause and sound fixes onto the checkout

Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch
ported, carrying the four commits of upstream issues 1320 (a pause while
a clip is layered holds the layer's picture and time) and 1325 (a video's
sound is read ahead of the clock and leads it). Both were written against
eb9f1104 and ported across the refactors since. The faults are the first
two and the third in docs/rune-upstream.md; the app's workarounds in
review.rs stay until the fixes arrive upstream.
This commit is contained in:
vhaudiquet committed 2026-11-22 22:16:30 +01:00
1 parent 80fef698ce
commit 5bf262b82b
3795 files changed
+663463 -28

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
[package]
name = "cursed-settings"
version = "0.0.1"
edition.workspace = true
license.workspace = true
publish = false
[dependencies]
rune = { workspace = true, default-features = true, features = ["keys-overlay"] }
rune-motion = { workspace = true }
rune-kit = { workspace = true, default-features = true }
rune-theme-opencode = { workspace = true }
rune-fx = { workspace = true }
rune-light = { workspace = true }
wgpu = { workspace = true, features = ["std", "parking_lot", "wgsl"] }
bytemuck = { workspace = true }
[target.'cfg(target_vendor = "apple")'.dependencies]
wgpu = { workspace = true, features = ["metal"] }
[target.'cfg(target_os = "windows")'.dependencies]
wgpu = { workspace = true, features = ["dx12"] }
[target.'cfg(all(not(target_vendor = "apple"), not(target_arch = "wasm32"), not(target_os = "windows")))'.dependencies]
wgpu = { workspace = true, features = ["vulkan"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
wgpu = { workspace = true, features = ["webgpu"] }
[lints]
workspace = true
@@ -0,0 +1 @@
{"events": [{"t": 0.6083, "type": "move", "x": 600.01, "y": 420.0}, {"t": 0.6167, "type": "move", "x": 600.04, "y": 419.99}, {"t": 0.625, "type": "move", "x": 600.15, "y": 419.95}, {"t": 0.6333, "type": "move", "x": 600.34, "y": 419.88}, {"t": 0.6417, "type": "move", "x": 600.65, "y": 419.78}, {"t": 0.65, "type": "move", "x": 601.1, "y": 419.62}, {"t": 0.6583, "type": "move", "x": 601.72, "y": 419.42}, {"t": 0.6667, "type": "move", "x": 602.52, "y": 419.14}, {"t": 0.675, "type": "move", "x": 603.52, "y": 418.8}, {"t": 0.6833, "type": "move", "x": 604.74, "y": 418.39}, {"t": 0.6917, "type": "move", "x": 606.18, "y": 417.9}, {"t": 0.7, "type": "move", "x": 607.87, "y": 417.33}, {"t": 0.7083, "type": "move", "x": 609.81, "y": 416.67}, {"t": 0.7167, "type": "move", "x": 612.0, "y": 415.92}, {"t": 0.725, "type": "move", "x": 614.46, "y": 415.08}, {"t": 0.7333, "type": "move", "x": 617.2, "y": 414.14}, {"t": 0.7417, "type": "move", "x": 620.2, "y": 413.11}, {"t": 0.75, "type": "move", "x": 623.48, "y": 411.98}, {"t": 0.7583, "type": "move", "x": 627.02, "y": 410.75}, {"t": 0.7667, "type": "move", "x": 630.84, "y": 409.41}, {"t": 0.775, "type": "move", "x": 634.93, "y": 407.98}, {"t": 0.7833, "type": "move", "x": 639.27, "y": 406.43}, {"t": 0.7917, "type": "move", "x": 643.87, "y": 404.78}, {"t": 0.8, "type": "move", "x": 648.71, "y": 403.02}, {"t": 0.8083, "type": "move", "x": 653.79, "y": 401.14}, {"t": 0.8167, "type": "move", "x": 659.08, "y": 399.15}, {"t": 0.825, "type": "move", "x": 664.59, "y": 397.04}, {"t": 0.8333, "type": "move", "x": 670.29, "y": 394.8}, {"t": 0.8417, "type": "move", "x": 676.17, "y": 392.44}, {"t": 0.85, "type": "move", "x": 682.2, "y": 389.96}, {"t": 0.8583, "type": "move", "x": 688.39, "y": 387.33}, {"t": 0.8667, "type": "move", "x": 694.7, "y": 384.58}, {"t": 0.875, "type": "move", "x": 701.11, "y": 381.68}, {"t": 0.8833, "type": "move", "x": 707.62, "y": 378.64}, {"t": 0.8917, "type": "move", "x": 714.19, "y": 375.46}, {"t": 0.9, "type": "move", "x": 720.82, "y": 372.14}, {"t": 0.9083, "type": "move", "x": 727.47, "y": 368.67}, {"t": 0.9167, "type": "move", "x": 734.13, "y": 365.07}, {"t": 0.925, "type": "move", "x": 740.79, "y": 361.32}, {"t": 0.9333, "type": "move", "x": 747.42, "y": 357.43}, {"t": 0.9417, "type": "move", "x": 754.01, "y": 353.42}, {"t": 0.95, "type": "move", "x": 760.54, "y": 349.28}, {"t": 0.9583, "type": "move", "x": 767.0, "y": 345.03}, {"t": 0.9667, "type": "move", "x": 773.36, "y": 340.67}, {"t": 0.975, "type": "move", "x": 779.63, "y": 336.22}, {"t": 0.9833, "type": "move", "x": 785.78, "y": 331.7}, {"t": 0.9917, "type": "move", "x": 791.81, "y": 327.11}, {"t": 1.0, "type": "move", "x": 797.71, "y": 322.47}, {"t": 1.0083, "type": "move", "x": 803.46, "y": 317.79}, {"t": 1.0167, "type": "move", "x": 809.06, "y": 313.11}, {"t": 1.025, "type": "move", "x": 814.5, "y": 308.43}, {"t": 1.0333, "type": "move", "x": 819.78, "y": 303.77}, {"t": 1.0417, "type": "move", "x": 824.89, "y": 299.15}, {"t": 1.05, "type": "move", "x": 829.82, "y": 294.59}, {"t": 1.0583, "type": "move", "x": 834.57, "y": 290.11}, {"t": 1.0667, "type": "move", "x": 839.14, "y": 285.72}, {"t": 1.075, "type": "move", "x": 843.52, "y": 281.44}, {"t": 1.0833, "type": "move", "x": 847.71, "y": 277.29}, {"t": 1.0917, "type": "move", "x": 851.7, "y": 273.28}, {"t": 1.1, "type": "move", "x": 855.5, "y": 269.43}, {"t": 1.1083, "type": "move", "x": 859.09, "y": 265.74}, {"t": 1.1167, "type": "move", "x": 862.49, "y": 262.23}, {"t": 1.125, "type": "move", "x": 865.68, "y": 258.9}, {"t": 1.1333, "type": "move", "x": 868.67, "y": 255.77}, {"t": 1.1417, "type": "move", "x": 871.46, "y": 252.83}, {"t": 1.15, "type": "move", "x": 874.04, "y": 250.1}, {"t": 1.1583, "type": "move", "x": 876.42, "y": 247.58}, {"t": 1.1667, "type": "move", "x": 878.59, "y": 245.27}, {"t": 1.175, "type": "move", "x": 880.57, "y": 243.16}, {"t": 1.1833, "type": "move", "x": 882.34, "y": 241.26}, {"t": 1.1917, "type": "move", "x": 883.93, "y": 239.57}, {"t": 1.2, "type": "move", "x": 885.33, "y": 238.07}, {"t": 1.2083, "type": "move", "x": 886.54, "y": 236.77}, {"t": 1.2167, "type": "move", "x": 887.59, "y": 235.66}, {"t": 1.225, "type": "move", "x": 888.46, "y": 234.72}, {"t": 1.2333, "type": "move", "x": 889.18, "y": 233.95}, {"t": 1.2417, "type": "move", "x": 889.76, "y": 233.33}, {"t": 1.25, "type": "move", "x": 890.2, "y": 232.85}, {"t": 1.2583, "type": "move", "x": 890.53, "y": 232.5}, {"t": 1.2667, "type": "move", "x": 890.76, "y": 232.26}, {"t": 1.275, "type": "move", "x": 890.89, "y": 232.11}, {"t": 1.2833, "type": "move", "x": 890.97, "y": 232.03}, {"t": 1.2917, "type": "move", "x": 891.0, "y": 232.0}, {"t": 1.3, "type": "move", "x": 891.0, "y": 232.0}, {"t": 1.42, "type": "tap", "x": 891, "y": 232, "hold": 0.09}, {"t": 2.8283, "type": "move", "x": 891.0, "y": 232.0}, {"t": 2.8367, "type": "move", "x": 890.99, "y": 232.03}, {"t": 2.845, "type": "move", "x": 890.98, "y": 232.08}, {"t": 2.8533, "type": "move", "x": 890.95Line truncated
@@ -0,0 +1,119 @@
#!/usr/bin/env python3
"""Writes showcase.json: a pointer that glides between controls and flips them one after another.
Coordinates are window points (960x660). Run: python3 showcase.py > showcase.json
"""
import json
import math
events = []
pos = [600.0, 420.0]
clock = 0.0
def glide(to, dur=0.55, at=None):
"""An eased, slightly arced move sampled at 120 Hz."""
global pos, clock
if at is not None:
clock = at
x0, y0 = pos
x1, y1 = to
n = max(2, int(dur * 120))
dx, dy = x1 - x0, y1 - y0
bend = 0.08 * math.hypot(dx, dy)
nx, ny = (-dy, dx) if (dx or dy) else (0, 0)
ln = math.hypot(nx, ny) or 1.0
for k in range(1, n + 1):
f = k / n
e = f * f * f * (f * (f * 6 - 15) + 10)
arc = math.sin(math.pi * e) * bend
events.append({
"t": round(clock + dur * f, 4),
"type": "move",
"x": round(x0 + dx * e + nx / ln * arc, 2),
"y": round(y0 + dy * e + ny / ln * arc, 2),
})
clock += dur
pos = [x1, y1]
def tap(to, dur=0.55, at=None, settle=0.12):
glide(to, dur, at)
global clock
clock += settle
events.append({"t": round(clock, 4), "type": "tap", "x": to[0], "y": to[1], "hold": 0.09})
clock += 0.1
def wait(s):
global clock
clock += s
NAV = {"general": (70, 78), "appearance": (82, 108), "network": (72, 138), "security": (70, 168),
"accessibility": (84, 198), "developer": (76, 228)}
SW1, SW2 = (891, 166), (891, 232)
wait(0.6)
# General: lightning, then the spotlight.
tap((891, 232), 0.7) # Lightning-fast startup
wait(1.3)
tap((891, 355), 0.6) # Show in Spotlight
wait(1.9)
tap((891, 355), 0.25) # ...and back off
wait(0.4)
# Network: firewall, static IP.
tap(NAV["network"], 0.55)
wait(0.5)
tap(SW1, 0.6) # Firewall
wait(1.4)
tap((891, 481), 0.6) # Static IP
wait(1.0)
# Security: electric fence, then get too close.
tap(NAV["security"], 0.55)
wait(0.5)
tap(SW1, 0.6) # Electric fence
wait(1.0)
glide((640, 530), 0.55)
wait(0.6)
glide((700, 570), 0.3)
# Accessibility: haptics Strong, frosting, contrast.
tap(NAV["accessibility"], 0.55)
wait(0.5)
tap((869, 478), 0.6) # Haptic feedback: Strong
wait(0.8)
tap((560, 300), 0.45) # Just clicking around.
wait(0.7)
tap(SW2, 0.6) # Reduce transparency
wait(1.4)
tap(SW1, 0.45) # Increase contrast
wait(1.8)
tap(SW1, 0.2)
wait(0.3)
# Developer: hot reload, flush.
tap(NAV["developer"], 0.55)
wait(0.5)
tap(SW1, 0.6) # Hot reload
wait(1.6)
tap((873, 301), 0.5) # Flush cache
wait(1.8)
# Appearance: Dark, then wander with the torch.
tap(NAV["appearance"], 0.55)
wait(0.5)
tap((801, 166), 0.6) # Dark
wait(0.9)
glide((470, 330), 0.6)
glide((300, 470), 0.6)
glide((150, 590), 0.45)
# Restore Defaults.
tap((115, 630), 0.5)
wait(2.3)
json.dump({"events": events}, open(__file__.replace(".py", ".json"), "w"))
print(f"{clock:.2f} s, {len(events)} events")
+26
View File
@@ -0,0 +1,26 @@
#!/bin/sh
# Render the showcase clip headless and encode it (H.264, yuv420p, 60 fps) plus a poster and
# review stills into captures/cursed-show. Raw frames are deleted.
# Run from the repo root: sh examples/cursed-settings/showcase.sh
set -e
cargo build --release -p cursed-settings 2>&1 | grep -E '^error|-->' | head -40 || true
cargo build --release -p cursed-settings -q
bin="${CARGO_TARGET_DIR:-target}/release/cursed-settings"
out=captures/cursed-show
rm -rf "$out" && mkdir -p "$out"
script=examples/cursed-settings/scripts/showcase.json
secs=${SECS:-39.8}
frames=$(python3 -c "print(int($secs * 60))")
for theme in ${THEMES:-light dark}; do
dir=$(mktemp -d)
"$bin" --cursor --theme "$theme" --scale 2 --script "$script" --frames "$frames" --fps 60 --out "$dir" > "$out/$theme.log" 2>&1
ffmpeg -loglevel error -y -framerate 60 -i "$dir/frame_%04d.png" -c:v libx264 -preset slow -crf 18 -pix_fmt yuv420p -r 60 -movflags +faststart "$out/showcase-$theme.mp4"
# Review stills: a moment after each punchline lands.
for t in ${REVIEW:-1.6 1.8 1.9 2.2 3.9 4.6 5.3 8.6 9.0 9.8 11.0 13.9 14.5 15.6 16.0 18.5 21.9 24.3 28.5 30.0 30.6 31.0 31.6 32.4 34.3 34.5 35.4 36.6 37.7 39.0}; do
n=$(python3 -c "print(f'{int(round($t * 60)):04d}')")
[ -f "$dir/frame_$n.png" ] && sips -s format jpeg -s formatOptions 80 -Z 1280 "$dir/frame_$n.png" --out "$out/$theme-$t.jpg" > /dev/null
done
cp "$dir/frame_$(python3 -c "print(f'{int(9.8 * 60):04d}')").png" "$out/poster-$theme.png"
rm -rf "$dir"
done
ls -la "$out" | head -80
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
# Build, then render headless stills of every scene into captures/cursed (both themes).
# Run from the repo root: sh examples/cursed-settings/snap.sh
set -e
cargo build --release -p cursed-settings 2>&1 | grep -E '^(error|warning: unused)|-->|^\s+\|' | head -80 || true
cargo build --release -p cursed-settings -q
bin="${CARGO_TARGET_DIR:-target}/release/cursed-settings"
out=captures/cursed
rm -rf "$out" && mkdir -p "$out"
for theme in light dark; do
for scene in ${SCENES:-general network security fire fence dark spotlight contrast frosted hot flushed}; do
"$bin" --scene "$scene" --theme "$theme" --scale 1 --at "${AT:-2.0}" --snap "$out/$scene-$theme.png" > "$out/$scene-$theme.log" 2>&1 || echo "FAIL $scene $theme"
done
done
ls "$out"
@@ -0,0 +1,148 @@
//! Scene lighting for the gags: brightness, dark mode (lights out and torch), spotlight,
//! contrast, and the lightning strike's flash.
use rune_light::{Light, Settings, TextPolicy};
use rune_motion::{Animated, Spring, Vec2};
use super::{Gags, In, mix, smooth};
impl Gags {
pub(super) fn lighting(
&mut self,
i: &In,
storm: f32,
flash: f32,
flash_at: [f32; 2],
anim: &mut bool,
) -> (Vec<Light>, Settings, f32) {
let p = &i.s.p;
let t = i.t;
let rm = p.reduce_motion;
let tg = &i.targets;
let px = |q: [f32; 2]| [q[0] * i.scale, q[1] * i.scale];
let mut lights: Vec<Light> = Vec::new();
let mut amb = 0.1 + 0.9 * p.brightness.clamp(0.0, 1.0);
amb *= mix(1.0, 0.32, storm);
let dark_on = p.appearance == 1;
self.dark.set(dark_on, t, rm);
let (darkness, torch) = if self.dark.is_on() {
let u = self.dark.since(t);
let flick = if rm {
smooth(0.0, 0.2, u)
} else if u < 0.05 {
0.85
} else if u < 0.11 {
0.1
} else if u < 0.17 {
0.92
} else if u < 0.23 {
0.45
} else {
1.0
};
let from = self.dark.from;
let d = mix(from, 1.0, flick);
(d, smooth(0.0, 0.18, u - if rm { 0.2 } else { 0.6 }))
} else {
let d = self.dark.at(t);
(d, 0.0)
};
*anim |= self.dark.moving(t) || self.dark.is_on() && self.dark.since(t) < 1.0;
amb *= mix(1.0, 0.006, darkness);
if torch > 0.0 {
if let Some(q) = i.pointer {
self.torch = q;
}
let q = self.torch;
let lp = [q[0] + 80.0, q[1] + 130.0];
let (a, b) = (px(q), px(lp));
let h = 260.0;
out_light(&mut lights, Light::point(b[0], b[1], h * i.scale)
.color([1.0, 0.95, 0.87])
.intensity(7.0)
.radius(9.0 * i.scale)
.range(1800.0 * i.scale)
.spot([a[0] - b[0], a[1] - b[1], -h * i.scale], 0.56)
.specular(1.3)
.scaled(torch));
}
let spot_switched = self.spot.set(p.spotlight, t, rm);
let sv = self.spot.at(t);
*anim |= self.spot.moving(t);
if let Some((r, _)) = tg.search {
let target = Vec2 { x: r.x + r.w * 0.5, y: r.y + r.h * 0.5 };
let sp = self.spot_pos.get_or_insert_with(|| Animated::new(target));
if spot_switched && p.spotlight && !rm {
// Swing in from off-stage, upper right.
sp.set(Vec2 { x: i.vp.x + i.vp.w + 60.0, y: i.vp.y + 40.0 });
}
if rm {
sp.set(target);
} else {
sp.animate_to(target, Spring::new(1.15, 0.16), i.now);
}
*anim |= sv > 0.0 && !sp.is_settled(i.now);
if sv > 0.003 {
let q = sp.sample(i.now);
let q = [q.x, q.y];
let lp = [q[0] + 150.0, q[1] - 90.0];
let h = 420.0;
let (a, b) = (px(q), px(lp));
out_light(&mut lights, Light::point(b[0], b[1], h * i.scale)
.color([1.0, 0.93, 0.8])
.intensity(4.5)
.radius(5.0 * i.scale)
.range(2400.0 * i.scale)
.spot([a[0] - b[0], a[1] - b[1], -h * i.scale], 0.27)
.specular(1.5)
.scaled(sv));
}
}
amb *= mix(1.0, 0.025, sv);
self.contrast.set(p.contrast, t, rm);
let cv = self.contrast.at(t);
*anim |= self.contrast.moving(t);
if cv > 0.003 {
let lp = px([i.vp.x - 90.0, i.vp.y + i.vp.h * 0.32]);
out_light(&mut lights, Light::point(lp[0], lp[1], 26.0 * i.scale)
.color([1.0, 0.88, 0.72])
.intensity(6.0)
.radius(12.0 * i.scale)
.range(4000.0 * i.scale)
.specular(1.6)
.scaled(cv));
}
amb *= mix(1.0, 0.28, cv);
if flash > 0.003 {
let q = px([flash_at[0] + 30.0, flash_at[1] - 120.0]);
out_light(&mut lights, Light::point(q[0], q[1], 300.0 * i.scale)
.color([0.85, 0.9, 1.0])
.intensity(6.0)
.radius(30.0 * i.scale)
.range(5000.0 * i.scale)
.scaled(flash));
}
let gloom = darkness.max(sv * 0.85).max(cv * 0.6);
let settings = Settings {
ambient: [amb, amb, amb * 1.05],
text: TextPolicy { floor: mix(0.82, 0.08, gloom), ceiling: 1.3, lit: 1.0, specular: 0.12 },
rim: 0.8 + 0.8 * cv,
contact_ao: 0.35 + 0.2 * cv,
albedo_floor: 0.05,
background_gloss: 0.35,
..Default::default()
};
let lit = ((1.0 - amb) * 8.0 + (flash + torch + sv + cv) * 8.0).clamp(0.0, 1.0);
(lights, settings, lit)
}
}
fn out_light(v: &mut Vec<Light>, l: Light) {
v.push(l);
}
+729
View File
@@ -0,0 +1,729 @@
//! The punchlines. Each frame turns the settings (and where Rune drew their targets) into
//! rune-fx layers and rune-light lights. Every gag runs on an envelope that springs from where
//! it is toward on or off, so turning one off mid-flight cools it instead of cutting it.
mod lighting;
use std::f32::consts::{PI, TAU};
use rune_fx::{
BlurMode, DistortParams, ElectricParams, ElectricStyle, FireParams, FireStyle, Fx, FxLayer, GlowParams,
LensParams, MotionBlurParams, MotionSamples, OneShots, Pose, PulseParams, PulseStyle, Rect, Rgb, Shape, rgb,
};
use rune_light::{Light, Settings};
use rune_motion::{Animated, Spring, Vec2};
use crate::ui::node;
use crate::{Cursed, Page};
/// How long the cache takes to go down the drain.
pub const FLUSH_SECONDS: f32 = 1.3;
/// The emptied card fading back in afterwards.
const FLUSH_REVEAL: f32 = 0.35;
pub const SRC_NODE: u32 = 0;
const STRIKE_WINDUP: f32 = 0.32;
// ---------------------------------------------------------------- envelopes
/// Step response of a spring with Rune's (duration, bounce) parameters.
fn step(u: f32, dur: f32, bounce: f32) -> f32 {
if u <= 0.0 {
return 0.0;
}
let w = TAU / dur.max(1e-3);
if bounce <= 1e-3 {
1.0 - (1.0 + w * u) * (-w * u).exp()
} else {
let z = 1.0 - bounce.min(0.95);
let wd = w * (1.0 - z * z).sqrt();
1.0 - (-z * w * u).exp() * ((wd * u).cos() + z * w / wd * (wd * u).sin())
}
}
fn smooth(e0: f32, e1: f32, x: f32) -> f32 {
let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0);
t * t * (3.0 - 2.0 * t)
}
fn mix(a: f32, b: f32, t: f32) -> f32 {
a + (b - a) * t
}
/// A switched envelope: 0 off, 1 on, sprung from wherever it was when the switch flipped.
#[derive(Clone, Copy, Debug)]
pub struct Env {
on: Option<bool>,
t0: f32,
from: f32,
up: (f32, f32),
down: f32,
delay: f32,
reduced: bool,
}
impl Env {
fn new(up: f32, bounce: f32, down: f32) -> Env {
Env { on: None, t0: -1e3, from: 0.0, up: (up, bounce), down, delay: 0.0, reduced: false }
}
fn delay(mut self, d: f32) -> Env {
self.delay = d;
self
}
/// The first sight is the resting state, not a transition.
fn set(&mut self, on: bool, t: f32, reduced: bool) -> bool {
match self.on {
None => {
self.on = Some(on);
self.from = on as u8 as f32;
false
}
Some(o) if o != on => {
self.from = self.at(t);
self.on = Some(on);
self.t0 = t;
self.reduced = reduced;
true
}
_ => false,
}
}
fn is_on(&self) -> bool {
self.on == Some(true)
}
fn since(&self, t: f32) -> f32 {
t - self.t0
}
fn shape(&self) -> (f32, f32, f32) {
if self.reduced {
return (0.18, 0.0, 0.0);
}
if self.is_on() { (self.up.0, self.up.1, self.delay) } else { (self.down, 0.0, 0.0) }
}
fn at(&self, t: f32) -> f32 {
let target = if self.is_on() { 1.0 } else { 0.0 };
let (dur, bounce, delay) = self.shape();
self.from + (target - self.from) * step(t - self.t0 - delay, dur, bounce)
}
fn moving(&self, t: f32) -> bool {
let (dur, bounce, delay) = self.shape();
self.since(t) < delay + dur * (1.3 + 2.5 * bounce)
}
}
// ---------------------------------------------------------------- frame inputs and outputs
#[derive(Clone, Copy, Debug)]
pub enum Anchor {
Under(u16),
Over(u16),
/// Above everything but the pointer.
Top,
}
pub struct Lay {
pub layer: FxLayer,
pub anchor: Anchor,
}
/// Where Rune drew each target this frame (points) and its opacity.
#[derive(Default)]
pub struct Targets {
pub fast: Option<(Rect, f32)>,
pub search: Option<(Rect, f32)>,
pub firewall: Option<(Rect, f32)>,
pub allowed: Option<(Rect, f32)>,
pub ip: Option<(Rect, f32)>,
pub fence: Option<(Rect, f32)>,
pub perimeter: Option<(Rect, f32)>,
pub reload: Option<(Rect, f32)>,
pub cache: Option<(Rect, f32)>,
pub sel: Option<(Rect, f32)>,
}
pub struct In<'a> {
pub s: &'a Cursed,
pub t: f32,
pub now: f64,
/// Device px per pt.
pub scale: f32,
/// The window in points.
pub vp: Rect,
pub pointer: Option<[f32; 2]>,
pub dark_theme: bool,
/// The selection colour under the glass (linear).
pub glass_tint: [f32; 3],
pub targets: Targets,
}
pub struct Out {
pub lays: Vec<Lay>,
pub lights: Vec<Light>,
pub settings: Settings,
/// How much of the lit frame shows over the plain one (0 skips lighting).
pub lit: f32,
/// The cache card's pose track while it drains, with its rest rect.
pub flush: Option<(MotionBlurParams, MotionSamples, Rect)>,
pub anim: bool,
}
pub struct Gags {
fire: Env,
fire_x: f32,
charge: Env,
fence: Env,
dark: Env,
contrast: Env,
spot: Env,
spot_pos: Option<Animated<Vec2>>,
frost: Env,
hot: Env,
fast: Option<bool>,
strike: Option<f32>,
drop: Option<Animated<Vec2>>,
torch: [f32; 2],
taps: Option<u32>,
shocks: OneShots<[f32; 2]>,
}
impl Default for Gags {
fn default() -> Self {
Gags {
fire: Env::new(0.9, 0.12, 0.55).delay(0.24),
fire_x: 0.0,
charge: Env::new(0.35, 0.0, 0.5),
fence: Env::new(0.45, 0.0, 0.4).delay(0.2),
dark: Env::new(0.22, 0.0, 0.5),
contrast: Env::new(0.6, 0.0, 0.5),
spot: Env::new(0.5, 0.0, 0.55),
spot_pos: None,
frost: Env::new(0.5, 0.0, 0.45),
hot: Env::new(1.6, 0.0, 2.4).delay(0.1),
fast: None,
strike: None,
drop: None,
torch: [480.0, 330.0],
taps: None,
shocks: OneShots::new(4),
}
}
}
fn center(r: Rect) -> [f32; 2] {
[r.x + r.w * 0.5, r.y + r.h * 0.5]
}
fn rounded(r: Rect, radius: f32) -> Shape {
Shape::rounded(r.x, r.y, r.w, r.h, radius)
}
fn lin3(c: Rgb) -> [f32; 3] {
c.0
}
/// Black-body-ish ramp for heating metal: dull red, orange, yellow-white.
fn glow_of(h: f32) -> Rgb {
let a = lin3(rgb(0x7a1204));
let b = lin3(rgb(0xff4a12));
let c = lin3(rgb(0xffb347));
let k = h.clamp(0.0, 1.0);
let (p, q, u) = if k < 0.6 { (a, b, k / 0.6) } else { (b, c, (k - 0.6) / 0.4) };
Rgb([mix(p[0], q[0], u), mix(p[1], q[1], u), mix(p[2], q[2], u)])
}
/// Signed distance to a rounded rect and the nearest point on its border.
fn border_point(r: Rect, radius: f32, p: [f32; 2]) -> (f32, [f32; 2]) {
let c = center(r);
let half = [r.w * 0.5 - radius, r.h * 0.5 - radius];
let q = [p[0] - c[0], p[1] - c[1]];
let cl = [q[0].clamp(-half[0], half[0]), q[1].clamp(-half[1], half[1])];
let d = [q[0] - cl[0], q[1] - cl[1]];
let len = d[0].hypot(d[1]);
if len > 1e-3 {
let n = [d[0] / len, d[1] / len];
(len - radius, [c[0] + cl[0] + n[0] * radius, c[1] + cl[1] + n[1] * radius])
} else {
// Inside the core: push out to the nearest side.
let dx = half[0] + radius - q[0].abs();
let dy = half[1] + radius - q[1].abs();
if dx < dy {
(-dx, [c[0] + q[0].signum() * (half[0] + radius), p[1]])
} else {
(-dy, [p[0], c[1] + q[1].signum() * (half[1] + radius)])
}
}
}
fn arc_shape(a: [f32; 2], b: [f32; 2]) -> Shape {
let x = a[0].min(b[0]);
let y = a[1].min(b[1]);
Shape::rounded(x, y, (a[0] - b[0]).abs().max(2.0), (a[1] - b[1]).abs().max(2.0), 0.0)
}
impl Gags {
pub fn frame(&mut self, i: &In) -> Out {
let s = i.s;
let p = &s.p;
let t = i.t;
let rm = p.reduce_motion;
let tg = &i.targets;
let light_ui = !i.dark_theme;
// Emissive light vanishes on a white window: there it reads as ink, deep and opaque.
let (volt, volt_core, volt_occ, volt_k) =
if light_ui { (rgb(0x1f5cff), rgb(0x7fa6ff), 0.95, 1.5) } else { (rgb(0x5a9bff), rgb(0xeaf3ff), 0.12, 1.0) };
let mut lays: Vec<Lay> = Vec::new();
let mut anim = false;
let mut push = |layer: FxLayer, anchor: Anchor| lays.push(Lay { layer: layer.at(t).reduced(rm), anchor });
let light_theme = !i.dark_theme;
// ---- Firewall: a wall of fire along the top of "Allowed apps"; off leaves embers.
if self.fire.set(p.firewall, t, rm) && p.firewall {
self.fire_x = tg.firewall.map_or(0.0, |(r, _)| center(r)[0]);
}
anim |= self.fire.moving(t);
if let Some((a, alpha)) = tg.allowed {
let g = self.fire.at(t).max(0.0);
let since = self.fire.since(t);
if self.fire.is_on() && since < 0.8 && !rm
&& let Some((sw, _)) = tg.firewall
{
// The spark: winds up, shoots from the switch to the card's edge, blooms there.
let from = center(sw);
let to = [self.fire_x.clamp(a.x + 12.0, a.x + a.w - 12.0), a.y];
let d = [to[0] - from[0], to[1] - from[1]];
let len = d[0].hypot(d[1]).max(1.0);
push(
Fx::pulse(PulseParams {
style: PulseStyle::Ping { from, dir: [d[0] / len, d[1] / len], travel: len },
color: rgb(0xff7a1a),
core: rgb(0xfff1d6),
t0: self.fire.t0,
duration: 0.26,
head_radius: 2.4,
intensity: alpha,
..Default::default()
})
.on(Shape::circle(from[0], from[1], 6.0)),
Anchor::Top,
);
anim = true;
}
if g > 0.003 {
let ix = self.fire_x.clamp(a.x, a.x + a.w);
let span = if self.fire.is_on() && !rm { step(since - 0.24, 0.85, 0.0) } else { 1.0 };
let x0 = mix(ix, a.x, span);
let x1 = mix(ix, a.x + a.w, span);
let shape = Shape::rounded(x0, a.y, (x1 - x0).max(14.0), a.h, 8.0);
push(
Fx::fire(FireParams {
height: 46.0 * g,
scale: 17.0,
speed: 1.5,
intensity: g.min(1.0) * alpha * if light_theme { 1.5 } else { 1.0 },
embers: 18,
ember_rise: 62.0,
occlusion: if light_theme { 0.9 } else { 0.3 },
base_glow: 0.55,
..Default::default()
})
.on(shape)
.seed(5),
Anchor::Under(node::ALLOWED),
);
push(
Fx::distort(DistortParams::HeatHaze { height: 70.0 * g, scale: 10.0, speed: 2.0, amount: 1.3 * g * alpha, whole_shape: false })
.on(Shape::rounded(x0, a.y - 30.0 * g, (x1 - x0).max(14.0), a.h, 8.0)),
Anchor::Over(node::ALLOWED),
);
}
if !self.fire.is_on() && self.fire.since(t) < 2.4 && !rm {
let k = 1.0 - smooth(0.2, 2.4, self.fire.since(t));
push(
Fx::fire(FireParams {
style: FireStyle::Embers,
embers: 26,
ember_rise: 44.0,
ember_life: 1.9,
ember_size: 0.9,
intensity: k * alpha,
..Default::default()
})
.on(rounded(a, 8.0))
.seed(6),
Anchor::Over(node::ALLOWED),
);
anim = true;
}
}
// ---- Static IP: the address field crackles with static.
self.charge.set(p.static_ip, t, rm);
anim |= self.charge.moving(t);
if let Some((f, alpha)) = tg.ip {
let c = self.charge.at(t);
if c > 0.003 {
let burst = if self.charge.is_on() { (-self.charge.since(t) / 0.4).exp() } else { 0.0 };
let base = ElectricParams::charged();
push(
Fx::electric(ElectricParams {
color: volt,
core: volt_core,
intensity: 0.85 * volt_k * c * alpha,
forks: 0.3 + 0.6 * burst,
amplitude: base.amplitude + 2.6 * burst,
glow: (base.glow * 0.6 + 2.0 * burst).max(1.0),
flicker: 0.25 * burst,
occlusion: volt_occ,
..base
})
.on(rounded(f, 6.0))
.seed(9),
Anchor::Over(node::IP),
);
}
}
// ---- Electric fence: a charge runs from the switch to the perimeter, which goes live.
self.fence.set(p.fence, t, rm);
anim |= self.fence.moving(t);
if let Some((pr, alpha)) = tg.perimeter {
let v = self.fence.at(t);
let since = self.fence.since(t);
let blue = volt;
if self.fence.is_on() && since < 0.45
&& let Some((sw, _)) = tg.fence
{
let a = center(sw);
let b = [pr.x + pr.w - 24.0, pr.y + 2.0];
let e = if since < 0.2 { 1.0 } else { (-(since - 0.2) / 0.08).exp() };
push(
Fx::electric(ElectricParams {
style: ElectricStyle::Arc { a, b },
color: blue,
amplitude: 7.0,
frequency: 2.0,
strands: 2,
forks: 0.6,
core: volt_core,
glow: 3.5,
intensity: e * volt_k * alpha,
occlusion: volt_occ,
..Default::default()
})
.on(arc_shape(a, b))
.seed(2 + (since * 20.0) as u32),
Anchor::Top,
);
anim = true;
}
if v > 0.003 {
push(
Fx::electric(ElectricParams {
style: ElectricStyle::Border,
color: blue,
amplitude: 3.6,
frequency: 2.6,
speed: 3.4,
core: volt_core,
glow: 2.8,
forks: 0.5,
strands: 2,
intensity: v * volt_k * alpha,
occlusion: volt_occ,
..Default::default()
})
.on(rounded(pr, 8.0))
.seed(7),
Anchor::Over(node::PERIMETER),
);
// Come close and it bites.
if let Some(q) = i.pointer {
let (d, n) = border_point(pr, 8.0, q);
let reach = 60.0;
if v > 0.5 && d.abs() < reach {
let k = (1.0 - d.abs() / reach).powf(0.8) * v * alpha;
push(
Fx::electric(ElectricParams {
style: ElectricStyle::Arc { a: n, b: q },
color: blue,
amplitude: 3.0 + d.abs() * 0.08,
frequency: 2.4,
strands: 2,
forks: 0.7,
fork_len: 14.0,
core: volt_core,
glow: 3.0,
flicker: 0.6,
intensity: k * volt_k,
occlusion: volt_occ,
..Default::default()
})
.on(arc_shape(n, q))
.seed(31 + (t * 11.0) as u32),
Anchor::Top,
);
push(
Fx::glow(GlowParams { color: blue, core: volt_core, radius: 6.0, intensity: k, hot: 0.8, occlusion: if light_ui { 0.6 } else { 0.0 }, ..Default::default() })
.on(Shape::circle(q[0], q[1], 2.5))
.over(),
Anchor::Top,
);
anim = true;
}
}
}
}
// ---- Lightning-fast startup: lightning strikes the switch.
if let Some(prev) = self.fast
&& !prev
&& p.fast_startup
&& s.page == Page::General
{
self.strike = Some(t);
}
self.fast = Some(p.fast_startup);
let mut flash = 0.0f32;
let mut flash_at = [0.0f32; 2];
let mut storm = 0.0f32;
if let (Some(t0), Some((sw, alpha))) = (self.strike, tg.fast) {
// Anticipation: the sky darkens first, then the bolt lands and the room recovers.
let windup = if rm { 0.0 } else { STRIKE_WINDUP };
let w = t - t0;
storm = if rm { 0.0 } else { smooth(0.0, windup, w) * (1.0 - smooth(windup + 0.15, windup + 0.9, w)) };
let u = w - windup;
if u < 0.0 {
anim = true;
} else if u < 1.4 {
anim = true;
let e = if rm {
1.0 - smooth(0.0, 0.3, u)
} else if u < 0.05 {
1.0
} else if u < 0.1 {
0.12
} else if u < 0.17 {
1.0
} else {
(-(u - 0.17) / 0.09).exp()
};
let b = center(sw);
let a = [b[0] + 46.0, i.vp.y - 12.0];
if e > 0.01 {
push(
Fx::electric(ElectricParams {
style: ElectricStyle::Arc { a, b },
color: if light_ui { rgb(0x2a5cff) } else { rgb(0x9cc4ff) },
core: if light_ui { rgb(0x9bb8ff) } else { rgb(0xffffff) },
amplitude: 15.0,
frequency: 1.5,
speed: 6.0,
core_width: 1.3,
strands: 3,
forks: 0.95,
fork_len: 30.0,
glow: 4.5,
flicker: 0.0,
intensity: e * alpha * volt_k,
occlusion: if light_ui { 0.95 } else { 0.15 },
..Default::default()
})
.on(arc_shape(a, b))
.seed(if u < 0.1 { 3 } else { 4 }),
Anchor::Top,
);
}
// The bolt lands: the window rings like a struck bell.
if !rm {
let full = Shape::rounded(i.vp.x, i.vp.y, i.vp.w, i.vp.h, 0.0);
let t1 = t0 + windup;
push(
Fx::distort(DistortParams::Shockwave { at: b, reach: 420.0, width: 26.0, amount: 12.0, chroma: 0.2, t0: t1, duration: 1.1 }).on(full),
Anchor::Top,
);
}
// The switch stays hot for a moment.
let ember = (-u / 0.5).exp() * alpha;
push(
Fx::glow(GlowParams { color: rgb(0x8fb8ff), core: rgb(0xffffff), radius: 4.0, intensity: 0.6 * ember, hot: 0.7, occlusion: if light_ui { 0.6 } else { 0.15 }, ..Default::default() })
.on(Shape::rounded(sw.x, sw.y, sw.w, sw.h, 4.0)),
Anchor::Top,
);
flash = e;
flash_at = b;
} else {
self.strike = None;
}
}
// ---- Reduce transparency: the sidebar's glass selection frosts over.
self.frost.set(p.reduce_transparency, t, rm);
anim |= self.frost.moving(t);
if let Some((r, alpha)) = tg.sel {
let c = Vec2 { x: r.x + r.w * 0.5, y: r.y + r.h * 0.5 };
let d = self.drop.get_or_insert_with(|| Animated::new(c));
if rm {
d.set(c);
} else {
d.animate_to(c, Spring::new(0.55, 0.0), i.now);
}
anim |= !d.is_settled(i.now);
let dc = d.sample(i.now);
let f = self.frost.at(t);
push(
Fx::lens(LensParams {
bevel: 7.0,
depth: 6.0,
dispersion: 0.12,
magnification: 1.03,
presence: alpha,
frost: f,
shadow: 0.18,
rim: 1.3,
tint: Rgb(i.glass_tint),
tint_amount: 0.92 * f,
second: Some(Shape::rounded(dc.x - r.w * 0.5, dc.y - r.h * 0.5, r.w, r.h, 6.0)),
union_k: 18.0,
..Default::default()
})
.on(rounded(r, 6.0)),
Anchor::Over(node::NAV),
);
}
// ---- Hot reload: the reload button glows red-hot and the air above it shimmers.
self.hot.set(p.hot_reload, t, rm);
anim |= self.hot.moving(t);
if let Some((b, alpha)) = tg.reload {
let h = self.hot.at(t).clamp(0.0, 1.2);
if h > 0.004 {
anim = true;
push(
Fx::glow(GlowParams {
color: glow_of(h),
core: rgb(0xffe6c0),
radius: 5.0 + 7.0 * h,
intensity: 0.9 * h * alpha,
hot: 0.35 * h,
breathe: 0.18,
breathe_period: 1.9,
occlusion: if light_theme { 0.7 } else { 0.1 },
..Default::default()
})
.on(rounded(b, 6.0)),
Anchor::Under(node::RELOAD),
);
let ht = FireParams::heat();
push(
Fx::fire(FireParams { intensity: ht.intensity * 1.5 * h * alpha, height: 13.0 * h, occlusion: if light_theme { 1.0 } else { 0.1 }, ..ht })
.on(rounded(b, 6.0))
.seed(2),
Anchor::Under(node::RELOAD),
);
push(
Fx::distort(DistortParams::HeatHaze { height: 52.0, scale: 9.0, speed: 2.2, amount: 1.1 * h * alpha, whole_shape: false }).on(rounded(b, 6.0)),
Anchor::Over(node::RELOAD),
);
}
}
// ---- Haptic feedback: Strong means every click shakes the window.
if let Some(prev) = self.taps
&& s.taps != prev
&& p.haptics == 2
&& let Some(q) = i.pointer
{
self.shocks.trigger(t, q);
}
self.taps = Some(s.taps);
self.shocks.prune(t, 1.4);
for (sh, k) in self.shocks.live(t, 1.4) {
anim = true;
let at = sh.data;
let full = Shape::rounded(i.vp.x, i.vp.y, i.vp.w, i.vp.h, 0.0);
push(
Fx::distort(DistortParams::Shockwave { at, reach: 320.0, width: 22.0, amount: 13.0, chroma: 0.5, t0: sh.t0, duration: 1.15 })
.on(full)
.opacity(k),
Anchor::Top,
);
push(
Fx::pulse(PulseParams {
style: PulseStyle::Ripple { at },
color: if light_ui { rgb(0x4a6cff) } else { rgb(0x8fb0ff) },
core: if light_ui { rgb(0x8ea4ff) } else { rgb(0xffffff) },
reach: 300.0,
width: 2.0,
t0: sh.t0,
duration: 1.0,
intensity: if light_ui { 0.6 } else { 0.35 },
occlusion: if light_ui { 0.7 } else { 0.0 },
..Default::default()
})
.on(full)
.over()
.opacity(k),
Anchor::Top,
);
}
// ---- Flush cache: the list spirals down the drain, with real shutter blur.
let mut flush = None;
if let (Some(t0), Some((c, _))) = (s.flush_t0, tg.cache) {
let u = t - t0;
if u <= FLUSH_SECONDS + FLUSH_REVEAL {
anim = true;
let rest = c;
let cc = center(c);
let drain = [cc[0], c.y + c.h + 36.0];
let pose_at = move |tt: f32| -> Pose { flush_pose(tt - t0, rest, cc, drain, rm) };
let mp = MotionBlurParams {
mode: BlurMode::Shutter,
shutter_angle: if rm { 0.0 } else { 200.0 },
max_samples: 48,
..Default::default()
};
let samples = MotionSamples::from_track(&mp, rest, t, i.scale, pose_at);
flush = Some((mp, samples, rest));
}
}
let (lights, settings, lit) = self.lighting(i, storm, flash, flash_at, &mut anim);
Out { lays, lights, settings, lit, flush, anim }
}
}
/// The drain: a wind-up, then an accelerating spiral that shrinks into the plughole; then the
/// emptied card fades back in where it was.
fn flush_pose(u: f32, rest: Rect, cc: [f32; 2], drain: [f32; 2], rm: bool) -> Pose {
let _ = rest;
if u <= 0.0 {
return Pose::default();
}
if u >= FLUSH_SECONDS {
let k = smooth(0.0, FLUSH_REVEAL, u - FLUSH_SECONDS);
return Pose { opacity: k, ..Default::default() };
}
if rm {
return Pose { opacity: 1.0 - smooth(0.0, FLUSH_SECONDS * 0.6, u), ..Default::default() };
}
let wind = 0.2;
if u < wind {
let w = (PI * u / wind).sin();
return Pose { rotation: -0.035 * w, scale: 1.0 + 0.02 * w, y: -3.0 * w, ..Default::default() };
}
let v = ((u - wind) / (FLUSH_SECONDS - wind)).clamp(0.0, 1.0);
let k = v.powf(2.2);
let r0 = (cc[1] - drain[1]).abs();
let ang = -PI * 0.5 + k * TAU * 1.1;
let r = r0 * (1.0 - k);
let x = drain[0] + r * ang.cos();
let y = drain[1] + r * ang.sin();
Pose {
x: x - cc[0],
y: y - cc[1],
rotation: k * TAU * 1.35,
scale: mix(1.0, 0.03, k.powf(0.75)),
opacity: 1.0 - smooth(0.8, 1.0, v),
}
}
+581
View File
@@ -0,0 +1,581 @@
//! The compositor: Rune builds the settings window as usual; this draws it into one HDR frame
//! with the gags' effect layers slotted under or over the elements they belong to (by mark),
//! lights the whole window with rune-light when a gag needs the lights, and resolves once with
//! dither. With nothing burning it draws the plain UI and asks for no frames.
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU8, Ordering};
use rune::compose::{Compositor, Frame, is_glyph};
use rune::render::{Instance, KIND_RECT};
use rune_fx::{Fx, FxFrame, FxLayer, FxOptions, FxRenderer, Rect, Shape};
use rune_light::{Light, LightRenderer, Prim, Scene as LightScene};
use crate::Cursed;
use crate::gags::{Anchor, FLUSH_SECONDS, Gags, In, SRC_NODE, Targets};
use crate::ui::{mark_material, mark_node, mat, node};
const HDR: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
// ---------------------------------------------------------------- GPU resources
struct Tex {
tex: wgpu::Texture,
view: wgpu::TextureView,
}
fn tex(device: &wgpu::Device, label: &str, size: (u32, u32), usage: wgpu::TextureUsages) -> Tex {
let tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: HDR,
usage,
view_formats: &[],
});
let view = tex.create_view(&Default::default());
Tex { tex, view }
}
const SHADERS: &str = r#"
@group(0) @binding(0) var src: texture_2d<f32>;
@group(0) @binding(1) var<uniform> alpha: vec4f;
struct V { @builtin(position) pos: vec4f }
@vertex
fn vs(@builtin(vertex_index) vi: u32) -> V {
let p = vec2f(f32((vi << 1u) & 2u), f32(vi & 2u));
var o: V;
o.pos = vec4f(p * 2.0 - 1.0, 0.0, 1.0);
return o;
}
fn pcg(v: u32) -> u32 {
let s = v * 747796405u + 2891336453u;
let w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u;
return (w >> 22u) ^ w;
}
fn u01(n: u32) -> f32 { return f32(pcg(n) >> 8u) * (1.0 / 16777216.0); }
fn to_srgb(c: vec3f) -> vec3f {
let lo = c * 12.92;
let hi = 1.055 * pow(max(c, vec3f(0.0)), vec3f(1.0 / 2.4)) - 0.055;
return select(hi, lo, c <= vec3f(0.0031308));
}
fn from_srgb(c: vec3f) -> vec3f {
let lo = c / 12.92;
let hi = pow((max(c, vec3f(0.0)) + 0.055) / 1.055, vec3f(2.4));
return select(hi, lo, c <= vec3f(0.04045));
}
fn dithered(pos: vec2f) -> vec3f {
let ip = vec2u(pos);
let c = textureLoad(src, vec2i(ip), 0);
let n = u01(ip.x + pcg(ip.y)) + u01(ip.x * 7919u + pcg(ip.y + 104729u)) - 1.0;
return clamp(to_srgb(clamp(c.rgb, vec3f(0.0), vec3f(1.0))) + vec3f(n / 255.0), vec3f(0.0), vec3f(1.0));
}
// Linear HDR scene -> 8-bit target with TPDF dither, once.
@fragment
fn fs_resolve_srgb(in: V) -> @location(0) vec4f { return vec4f(from_srgb(dithered(in.pos.xy)), 1.0); }
@fragment
fn fs_resolve_unorm(in: V) -> @location(0) vec4f { return vec4f(dithered(in.pos.xy), 1.0); }
// The lit window (sRGB-encoded by rune-light's composite) over the linear scene.
@fragment
fn fs_blit(in: V) -> @location(0) vec4f {
let c = textureLoad(src, vec2i(in.pos.xy), 0);
return vec4f(from_srgb(c.rgb) * alpha.x, alpha.x);
}
"#;
struct Fullscreen {
pipeline: wgpu::RenderPipeline,
bgl: wgpu::BindGroupLayout,
}
fn fullscreen(device: &wgpu::Device, module: &wgpu::ShaderModule, entry: &str, format: wgpu::TextureFormat, blend: Option<wgpu::BlendState>) -> Fullscreen {
let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some(entry),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None },
count: None,
},
],
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some(entry), bind_group_layouts: &[Some(&bgl)], immediate_size: 0 });
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(entry),
layout: Some(&layout),
vertex: wgpu::VertexState { module, entry_point: Some("vs"), compilation_options: Default::default(), buffers: &[] },
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module,
entry_point: Some(entry),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState { format, blend, write_mask: wgpu::ColorWrites::ALL })],
}),
multiview_mask: None,
cache: None,
});
Fullscreen { pipeline, bgl }
}
/// Whole-frame GPU time from timestamps on the compositor's own passes, read back a couple of
/// frames later without stalling.
struct Timer {
qs: wgpu::QuerySet,
resolve: wgpu::Buffer,
read: wgpu::Buffer,
/// 0 idle, 4 written, 1 copy recorded, 2 mapping, 3 mapped.
state: Arc<AtomicU8>,
period: f32,
recording: bool,
}
impl Timer {
fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Option<Timer> {
if !device.features().contains(wgpu::Features::TIMESTAMP_QUERY) {
return None;
}
let qs = device.create_query_set(&wgpu::QuerySetDescriptor { label: Some("cursed ts"), ty: wgpu::QueryType::Timestamp, count: 2 });
let buf = |label, usage| device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: 16, usage, mapped_at_creation: false });
let resolve = buf("cursed ts resolve", wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC);
let read = buf("cursed ts read", wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ);
Some(Timer { qs, resolve, read, state: Arc::new(AtomicU8::new(0)), period: queue.get_timestamp_period(), recording: false })
}
/// Collects a finished reading (ms) and decides whether this frame records one. Last frame's queries are
/// resolved here, a command buffer later: Metal orders work by resource, so a resolve in the same encoder
/// can run before the final pass's end-of-pass sample lands.
fn begin(&mut self, enc: &mut wgpu::CommandEncoder) -> Option<f32> {
let mut out = None;
match self.state.load(Ordering::Acquire) {
4 => {
enc.resolve_query_set(&self.qs, 0..2, &self.resolve, 0);
enc.copy_buffer_to_buffer(&self.resolve, 0, &self.read, 0, 16);
self.state.store(1, Ordering::Release);
}
1 => {
self.state.store(2, Ordering::Release);
let st = self.state.clone();
self.read.slice(..).map_async(wgpu::MapMode::Read, move |r| st.store(if r.is_ok() { 3 } else { 0 }, Ordering::Release));
}
3 => {
if let Ok(data) = self.read.slice(..).get_mapped_range() {
let t: &[u64] = bytemuck::cast_slice(&data);
out = (t[1] > t[0]).then(|| (t[1] - t[0]) as f32 * self.period / 1e6);
}
self.read.unmap();
self.state.store(0, Ordering::Release);
}
_ => {}
}
self.recording = self.state.load(Ordering::Acquire) == 0;
out
}
/// The query set when this frame records. The writes go on the compositor's own render passes: Metal may
/// overlap a resource-free marker pass with the work around it, so empty marker passes read near zero.
fn query(&self) -> Option<wgpu::QuerySet> {
self.recording.then(|| self.qs.clone())
}
fn end(&mut self) {
if self.recording {
self.state.store(4, Ordering::Release);
}
}
}
struct Res {
size: (u32, u32),
format: wgpu::TextureFormat,
scene: Tex,
backdrop: Tex,
node: Tex,
base: Tex,
text: Tex,
lit: Tex,
light: Option<LightRenderer>,
fx: FxRenderer,
resolve: Fullscreen,
blit: Fullscreen,
resolve_bg: wgpu::BindGroup,
blit_bg: wgpu::BindGroup,
blit_alpha: wgpu::Buffer,
timer: Option<Timer>,
}
impl Res {
fn new(device: &wgpu::Device, queue: &wgpu::Queue, size: (u32, u32), format: wgpu::TextureFormat, ui: &mut rune::render::Renderer) -> Res {
use wgpu::TextureUsages as U;
ui.add_format(device, HDR);
let rt = U::RENDER_ATTACHMENT | U::TEXTURE_BINDING;
let scene = tex(device, "cursed scene", size, rt | U::COPY_SRC);
let backdrop = tex(device, "cursed backdrop", size, U::TEXTURE_BINDING | U::COPY_DST);
let node = tex(device, "cursed node layer", size, rt);
let base = tex(device, "cursed base", size, rt);
let text = tex(device, "cursed text", size, rt);
let lit = tex(device, "cursed lit", size, rt);
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("cursed"), source: wgpu::ShaderSource::Wgsl(SHADERS.into()) });
let resolve = fullscreen(device, &module, if format.is_srgb() { "fs_resolve_srgb" } else { "fs_resolve_unorm" }, format, None);
let blit = fullscreen(device, &module, "fs_blit", HDR, Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING));
let blit_alpha = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("cursed blit alpha"),
size: 16,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let bind = |f: &Fullscreen, v: &wgpu::TextureView| {
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &f.bgl,
entries: &[
wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(v) },
wgpu::BindGroupEntry { binding: 1, resource: blit_alpha.as_entire_binding() },
],
})
};
let resolve_bg = bind(&resolve, &scene.view);
let blit_bg = bind(&blit, &lit.view);
Res {
size,
format,
light: None,
fx: FxRenderer::new(device, HDR, FxOptions { dither: false }),
timer: Timer::new(device, queue),
scene,
backdrop,
node,
base,
text,
lit,
resolve,
blit,
resolve_bg,
blit_bg,
blit_alpha,
}
}
}
fn pass<'e>(
enc: &'e mut wgpu::CommandEncoder,
view: &'e wgpu::TextureView,
clear: Option<[f32; 4]>,
timestamp_writes: Option<wgpu::RenderPassTimestampWrites<'e>>,
) -> wgpu::RenderPass<'e> {
let load = clear.map_or(wgpu::LoadOp::Load, |c| wgpu::LoadOp::Clear(wgpu::Color { r: c[0] as f64, g: c[1] as f64, b: c[2] as f64, a: c[3] as f64 }));
enc.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("cursed"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations { load, store: wgpu::StoreOp::Store },
})],
depth_stencil_attachment: None,
timestamp_writes,
occlusion_query_set: None,
multiview_mask: None,
})
}
// ---------------------------------------------------------------- the compositor
#[derive(Default)]
pub struct Gfx {
res: Option<Res>,
gags: Gags,
animating: bool,
view_pending: bool,
total_gpu: (f64, u32),
frames: u32,
lit_frames: u32,
max_layers: usize,
}
/// How a marked rect stands on the UI plane (device px).
fn prim(ins: &Instance, material: u8, s: f32) -> Option<Prim> {
if ins.fill[3] < 0.02 {
return None;
}
let a = ins.fill[3].max(1e-4);
let p = Prim::from_rune(ins.rect, ins.radii).albedo([ins.fill[0] / a, ins.fill[1] / a, ins.fill[2] / a]);
Some(match material {
mat::CARD => p.raised(5.0 * s).bevel(5.0 * s, 1.5 * s).gloss(0.45, 0.45),
mat::CONTROL => p.on(5.0 * s).raised(2.5 * s).bevel(4.0 * s, 1.2 * s).gloss(0.6, 0.35),
mat::SEL => p.raised(1.5 * s).bevel(4.0 * s, 0.8 * s).gloss(0.5, 0.4),
_ => return None,
})
}
impl Compositor<Cursed> for Gfx {
fn features(&self) -> wgpu::Features {
wgpu::Features::TIMESTAMP_QUERY
}
fn animating(&self) -> bool {
self.animating || self.view_pending
}
fn summary(&mut self, _device: &wgpu::Device) -> Option<String> {
let (sum, n) = self.total_gpu;
let gpu = if n > 0 { format!("gpu frame mean {:.3} ms over {n} timed frames", sum / n as f64) } else { "no GPU timestamps".to_owned() };
Some(format!("cursed-settings: {gpu}; {} frames, {} lit, at most {} effect layers", self.frames, self.lit_frames, self.max_layers))
}
fn render(&mut self, f: &mut Frame<'_, Cursed>) {
if self.res.as_ref().is_none_or(|r| r.size != f.size || r.format != f.format) {
self.res = Some(Res::new(f.device, f.queue, f.size, f.format, f.ui));
}
self.view_pending = false;
f.device.poll(wgpu::PollType::Poll).ok();
let res = self.res.as_mut().unwrap();
let gpu_ms = res.timer.as_mut().and_then(|t| t.begin(f.encoder));
let rt = &mut *f.rt;
let scale = rt.env.scale;
let now = rt.t;
let t = now as f32;
let (w, h) = f.size;
let vp = Rect::new(0.0, 0.0, w as f32 / scale, h as f32 / scale);
let pointer = rt.pointer().map(|p| [p.0, p.1]);
// ---- state the compositor owns: the clock, flush timing, the demo pointer
let mut dirty = false;
{
let st = &mut rt.state;
st.now = now;
if st.flush_requested {
st.flush_requested = false;
st.flush_t0 = Some(t);
dirty = true;
}
if st.flush_t0.is_some_and(|t0| t > t0 + FLUSH_SECONDS + 0.4) {
st.flush_t0 = None;
dirty = true;
}
if st.show_cursor && st.cursor != pointer {
st.cursor = pointer;
dirty = true;
}
}
if dirty {
rt.invalidate();
self.view_pending = true;
}
// ---- the gags
let rect = |k: &str| rt.presented(k).filter(|(r, _)| r[2] > 0.0 && r[3] > 0.0).map(|(r, a)| (Rect::new(r[0], r[1], r[2], r[3]), a));
let targets = Targets {
fast: rect("fast-switch"),
search: rect("search"),
firewall: rect("firewall-switch"),
allowed: rect("allowed-card"),
ip: rect("ip-field"),
fence: rect("fence-switch"),
perimeter: rect("perimeter-card"),
reload: rect("reload-btn"),
cache: rect("cache-card"),
sel: rect("nav-sel"),
};
let dark_theme = crate::ui::dark_theme(&rt.state, rt.env.system_dark);
let tint = rune_theme_opencode::kit(dark_theme).c.layer_03;
let out = self.gags.frame(&In {
s: &rt.state,
t,
now,
scale,
vp,
pointer,
dark_theme,
glass_tint: [tint.r, tint.g, tint.b],
targets,
});
let mut anim = out.anim;
let lit_on = out.lit > 0.002;
let flushing = out.flush.is_some();
// ---- partition Rune's instances
let inst = &rt.instances;
let marks = &rt.marks;
let mut main: Vec<Instance> = Vec::with_capacity(inst.len());
let (mut base, mut text, mut nodel, mut top) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
let mut prims: Vec<Prim> = Vec::new();
let mut first: HashMap<u16, usize> = HashMap::new();
let mut last: HashMap<u16, usize> = HashMap::new();
for (i, ins) in inst.iter().enumerate() {
let m = marks.get(i).copied().unwrap_or(0);
let nd = mark_node(m);
if nd == node::CURSOR {
top.push(*ins);
continue;
}
first.entry(nd).or_insert(main.len());
if flushing && nd == node::CACHE {
nodel.push(*ins);
} else {
main.push(*ins);
if lit_on {
if is_glyph(ins) {
text.push(*ins);
} else {
base.push(*ins);
if ins.params[1] == KIND_RECT
&& let Some(p) = prim(ins, mark_material(m), scale)
{
prims.push(p);
}
}
}
}
last.insert(nd, main.len());
}
// ---- where each effect layer goes in the main list
enum Op {
Blit,
Fx(usize),
}
let end = main.len();
let mut ops: Vec<(usize, Op)> = Vec::new();
if lit_on {
ops.push((end, Op::Blit));
}
let mut lays = out.lays;
if let Some((p, samples, rest)) = out.flush {
let layer = Fx::motion_blur(p, samples).on(Shape::rounded(rest.x, rest.y, rest.w, rest.h, 8.0)).source(SRC_NODE, vp).at(t);
lays.push(crate::gags::Lay { layer, anchor: Anchor::Over(node::CACHE) });
}
let mut layers: Vec<FxLayer> = Vec::new();
let mut needs_bd: Vec<bool> = Vec::new();
for l in lays {
anim |= l.layer.is_animating();
let pos = match l.anchor {
Anchor::Under(n) => first.get(&n).copied(),
Anchor::Over(n) => last.get(&n).copied(),
Anchor::Top => Some(end),
};
let Some(pos) = pos else { continue };
// Lit, the window is one image: effects go on top of it.
let pos = if lit_on { end } else { pos };
needs_bd.push(l.layer.fx.needs_backdrop());
ops.push((pos, Op::Fx(layers.len())));
layers.push(l.layer);
}
ops.sort_by_key(|o| o.0);
self.max_layers = self.max_layers.max(layers.len());
// ---- upload and draw
let clear = rt.clear_color();
let ranges = f.ui.prepare_lists(f.device, f.queue, &mut rt.text.atlas, &[&main, &base, &text, &nodel, &top], f.size);
let sources = [&res.node.view];
res.fx.prepare(f.device, f.queue, &FxFrame { viewport: [w, h], scale, layers: &layers, backdrop: Some(&res.backdrop.view), sources: &sources });
let enc = &mut *f.encoder;
let tq = res.timer.as_ref().and_then(Timer::query);
let mut began = false;
let mut stamp = |end: bool| {
let first = !std::mem::replace(&mut began, true);
tq.as_ref().filter(|_| first || end).map(|q| wgpu::RenderPassTimestampWrites {
query_set: q,
beginning_of_pass_write_index: first.then_some(0),
end_of_pass_write_index: end.then_some(1),
})
};
if !nodel.is_empty() {
let mut p = pass(enc, &res.node.view, Some([0.0; 4]), stamp(false));
f.ui.draw_range(&mut p, HDR, ranges[3].clone());
}
let mut lit_drawn = false;
if lit_on {
let a = clear[3].max(1e-4);
{
let mut p = pass(enc, &res.base.view, Some([clear[0] / a, clear[1] / a, clear[2] / a, 1.0]), stamp(false));
f.ui.draw_range(&mut p, HDR, ranges[1].clone());
}
{
let mut p = pass(enc, &res.text.view, Some([0.0; 4]), None);
f.ui.draw_range(&mut p, HDR, ranges[2].clone());
}
let mut lights: Vec<Light> = out.lights;
if lights.is_empty() {
// Ambient only (the brightness slider): one dark light keeps the pass running.
lights.push(Light::point(0.0, 0.0, 1.0).intensity(0.0));
}
let mut st = out.settings;
st.time = t;
let light = res.light.get_or_insert_with(|| LightRenderer::new(f.device, f.queue, w, h, HDR));
lit_drawn = light.render(f.device, f.queue, enc, &LightScene { prims: &prims, lights: &lights, settings: st, emission: None }, &res.base.view, &res.text.view, &res.lit.view);
f.queue.write_buffer(&res.blit_alpha, 0, bytemuck::cast_slice(&[out.lit, 0.0, 0.0, 0.0]));
self.lit_frames += 1;
}
let mut cursor = 0usize;
let mut rp = pass(enc, &res.scene.view, Some(clear), stamp(false)).forget_lifetime();
let main_range = ranges[0].clone();
for (pos, op) in ops {
if pos > cursor {
f.ui.draw_range(&mut rp, HDR, main_range.start + cursor as u32..main_range.start + pos as u32);
cursor = pos;
}
match op {
Op::Blit => {
if lit_drawn {
rp.set_pipeline(&res.blit.pipeline);
rp.set_bind_group(0, &res.blit_bg, &[]);
rp.draw(0..3, 0..1);
}
}
Op::Fx(i) => {
if needs_bd[i] {
drop(rp);
enc.copy_texture_to_texture(
wgpu::TexelCopyTextureInfo { texture: &res.scene.tex, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
wgpu::TexelCopyTextureInfo { texture: &res.backdrop.tex, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
);
rp = pass(enc, &res.scene.view, None, None).forget_lifetime();
}
res.fx.draw_layer(&mut rp, i);
}
}
}
if cursor < end {
f.ui.draw_range(&mut rp, HDR, main_range.start + cursor as u32..main_range.end);
}
f.ui.draw_range(&mut rp, HDR, ranges[4].clone());
drop(rp);
{
let mut p = pass(enc, f.target, Some([0.0, 0.0, 0.0, 1.0]), stamp(true));
p.set_pipeline(&res.resolve.pipeline);
p.set_bind_group(0, &res.resolve_bg, &[]);
p.draw(0..3, 0..1);
}
if let Some(tm) = res.timer.as_mut() {
tm.end();
}
if let Some(g) = gpu_ms {
self.total_gpu.0 += g as f64;
self.total_gpu.1 += 1;
}
self.frames += 1;
self.animating = anim;
}
}
+21
View File
@@ -0,0 +1,21 @@
//! Sidebar icons the OpenCode catalog doesn't have, drawn in its 16 point stroke style.
use rune::Icon;
pub static SUN: Icon = Icon {
name: "sun",
view: 16.0,
body: r#"<circle cx="8" cy="8" r="2.75" stroke="currentColor"/><path d="M8 1.5V3M8 13V14.5M1.5 8H3M13 8H14.5M3.4 3.4L4.46 4.46M11.54 11.54L12.6 12.6M3.4 12.6L4.46 11.54M11.54 4.46L12.6 3.4" stroke="currentColor"/>"#,
};
pub static SHIELD: Icon = Icon {
name: "shield",
view: 16.0,
body: r#"<path d="M8 1.75L13 3.5V7.5C13 10.6 10.9 13.1 8 14.25C5.1 13.1 3 10.6 3 7.5V3.5L8 1.75Z" stroke="currentColor" stroke-linejoin="round"/>"#,
};
pub static PERSON: Icon = Icon {
name: "person-circle",
view: 16.0,
body: r#"<circle cx="8" cy="8" r="6.25" stroke="currentColor"/><circle cx="8" cy="5.25" r="1" fill="currentColor"/><path d="M4.75 7H11.25M8 7V9.25M8 9.25L6.5 12M8 9.25L9.5 12" stroke="currentColor" stroke-linejoin="round"/>"#,
};
+218
View File
@@ -0,0 +1,218 @@
//! Cursed Settings: a believable settings window where every control does exactly what its
//! label says. The Firewall switch builds a wall of fire, the electric fence electrifies the
//! perimeter, Dark mode turns the lights off. Effects come from rune-fx and rune-light, drawn
//! inside Rune's frame through the compositor hook (`gfx.rs`); `gags/` decides what burns.
#![forbid(unsafe_code)]
mod gags;
mod gfx;
mod icons;
mod ui;
use rune::{AppSpec, TextEdit, Tx};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Page {
General,
Appearance,
Network,
Security,
Accessibility,
Developer,
}
pub const PAGES: [Page; 6] = [Page::General, Page::Appearance, Page::Network, Page::Security, Page::Accessibility, Page::Developer];
impl Page {
fn meta(self) -> (&'static str, &'static str) {
match self {
Page::General => ("General", "general"),
Page::Appearance => ("Appearance", "appearance"),
Page::Network => ("Network", "network"),
Page::Security => ("Security", "security"),
Page::Accessibility => ("Accessibility", "accessibility"),
Page::Developer => ("Developer", "developer"),
}
}
pub fn title(self) -> &'static str { self.meta().0 }
pub fn id(self) -> &'static str { self.meta().1 }
}
pub const APPEARANCES: [&str; 3] = ["Light", "Dark", "Auto"];
pub const HAPTICS: [&str; 3] = ["Off", "Light", "Strong"];
/// Every setting, at its default.
#[derive(Clone, Debug)]
pub struct Prefs {
pub launch_at_login: bool,
pub fast_startup: bool,
pub spotlight: bool,
pub auto_update: bool,
/// 0 Light, 1 Dark, 2 Auto.
pub appearance: usize,
pub brightness: f32,
pub firewall: bool,
pub stealth: bool,
pub static_ip: bool,
pub fence: bool,
pub lock_on_sleep: bool,
pub contrast: bool,
pub reduce_transparency: bool,
pub reduce_motion: bool,
/// 0 Off, 1 Light, 2 Strong.
pub haptics: usize,
pub hot_reload: bool,
pub flushed: bool,
}
impl Default for Prefs {
fn default() -> Self {
Prefs {
launch_at_login: true,
fast_startup: false,
spotlight: false,
auto_update: true,
appearance: 2,
brightness: 1.0,
firewall: false,
stealth: false,
static_ip: false,
fence: false,
lock_on_sleep: true,
contrast: false,
reduce_transparency: false,
reduce_motion: false,
haptics: 1,
hot_reload: false,
flushed: false,
}
}
}
pub struct Cursed {
pub page: Page,
pub p: Prefs,
pub search: TextEdit,
pub ip: TextEdit,
/// Presses so far; the compositor turns new ones into haptic feedback at the pointer.
pub taps: u32,
/// Flush requested by the button; the compositor stamps `flush_t0` on its clock.
pub flush_requested: bool,
pub flush_t0: Option<f32>,
/// When the restore-defaults toast goes away (compositor clock).
pub toast_until: Option<f64>,
/// The compositor's clock at the last frame.
pub now: f64,
/// Demo recordings draw a pointer (`--cursor`).
pub show_cursor: bool,
pub cursor: Option<[f32; 2]>,
}
impl Cursed {
fn new() -> Cursed {
Cursed {
page: Page::General,
p: Prefs::default(),
search: TextEdit::default(),
ip: TextEdit::new("192.168.1.42"),
taps: 0,
flush_requested: false,
flush_t0: None,
toast_until: None,
now: 0.0,
show_cursor: rune::extra_args().iter().any(|a| a == "--cursor"),
cursor: None,
}
}
/// Everything back to its default, calmly: each gag cools down on its own envelope.
pub fn restore(&mut self) {
self.p = Prefs::default();
self.flush_t0 = None;
self.toast_until = Some(self.now + 4.5);
}
}
/// While the toast shows or the cache drains, time moves state forward on its own.
fn poll(s: &mut Cursed, _clock: f64, _tx: &mut Tx) -> bool {
let mut changed = false;
if s.toast_until.is_some_and(|u| s.now >= u) {
s.toast_until = None;
changed = true;
}
if let Some(t0) = s.flush_t0
&& s.now as f32 >= t0 + gags::FLUSH_SECONDS
&& !s.p.flushed
{
s.p.flushed = true;
changed = true;
}
changed
}
fn page(p: Page) -> impl Fn(&mut Cursed) {
move |s| s.page = p
}
fn main() {
rune::run_with(
AppSpec {
title: "Settings",
size: (960.0, 660.0),
min_size: Some((860.0, 600.0)),
init: Cursed::new,
view: ui::view,
scenes: &[
("default", |_| {}),
("general", |s| page(Page::General)(s)),
("appearance", |s| page(Page::Appearance)(s)),
("network", |s| page(Page::Network)(s)),
("security", |s| page(Page::Security)(s)),
("accessibility", |s| page(Page::Accessibility)(s)),
("developer", |s| page(Page::Developer)(s)),
("fire", |s| {
s.page = Page::Network;
s.p.firewall = true;
s.p.static_ip = true;
}),
("fence", |s| {
s.page = Page::Security;
s.p.fence = true;
}),
("dark", |s| {
s.page = Page::Appearance;
s.p.appearance = 1;
}),
("spotlight", |s| s.p.spotlight = true),
("contrast", |s| {
s.page = Page::Accessibility;
s.p.contrast = true;
}),
("frosted", |s| {
s.page = Page::Accessibility;
s.p.reduce_transparency = true;
}),
("hot", |s| {
s.page = Page::Developer;
s.p.hot_reload = true;
}),
("flushed", |s| {
s.page = Page::Developer;
s.p.flushed = true;
}),
("reduced-fire", |s| {
s.page = Page::Network;
s.p.firewall = true;
s.p.reduce_motion = true;
}),
],
fonts: rune_theme_opencode::FONTS,
families: rune_theme_opencode::FAMILIES,
setup: None,
poll: Some(poll),
on_key: None,
},
gfx::Gfx::default(),
);
}
+663
View File
@@ -0,0 +1,663 @@
//! The settings window, in OpenCode's settings design language: a sidebar of pages, then
//! titled sections of rows with a control on the right. Nothing here knows about effects
//! except the marks that tell the compositor which element is which.
use rune::tok::motion;
use rune::{Align, Color, Cx, Drag, El, Phase, Shape, Spring, TextStyle, Transition, Tx, canvas, col, el, icon, row, spacer, text};
use rune_kit::{Badge, BadgeVariant, Button, ButtonVariant, ControlSize, Kit, SegmentedControl, Select, Switch, TextInput, Toast, ToastRegion};
use rune_theme_opencode::icons as oc;
use crate::{APPEARANCES, Cursed, HAPTICS, PAGES, Page, icons};
pub const SIDEBAR_W: f32 = 232.0;
const NAV_PITCH: f32 = 30.0;
const NAV_H: f32 = 28.0;
// ---------------------------------------------------------------- marks
/// A mark: lighting material and effect node. Bit 31 keeps every explicit mark non-zero (0 inherits).
pub fn mk(material: u8, node: u16) -> u32 {
(1 << 31) | ((material as u32) << 16) | node as u32
}
pub fn mark_node(m: u32) -> u16 {
(m & 0xFFFF) as u16
}
pub fn mark_material(m: u32) -> u8 {
((m >> 16) & 0xFF) as u8
}
/// How a rect stands on the UI plane when the lights are on.
pub mod mat {
/// Flat: no occluder.
pub const NONE: u8 = 0;
pub const CARD: u8 = 1;
pub const CONTROL: u8 = 2;
pub const SEL: u8 = 3;
}
/// Effect anchors.
pub mod node {
pub const NAV: u16 = 1;
pub const SEARCH: u16 = 2;
pub const ALLOWED: u16 = 10;
pub const IP: u16 = 11;
pub const PERIMETER: u16 = 20;
pub const RELOAD: u16 = 30;
pub const CACHE: u16 = 31;
pub const TOAST: u16 = 0xFFFE;
pub const CURSOR: u16 = 0xFFFF;
}
// ---------------------------------------------------------------- type
const TITLE: TextStyle = TextStyle::new(15.0, 640.0).lh(22.0);
const SECTION: TextStyle = TextStyle::new(13.0, 530.0).lh(16.0);
/// A press that counts as a tap (haptic feedback follows taps).
fn tap(f: impl Fn(&mut Cursed) + 'static) -> impl Fn(&mut Cursed) + 'static {
move |s: &mut Cursed| {
f(s);
s.taps += 1;
}
}
pub fn dark_theme(s: &Cursed, system_dark: bool) -> bool {
match s.p.appearance {
0 => false,
_ => system_dark,
}
}
pub fn view(s: &Cursed, cx: &mut Cx<Cursed>) -> El {
cx.reduced_motion(s.p.reduce_motion);
let k = rune_theme_opencode::kit(dark_theme(s, cx.system_dark()));
let hair = 1.0 / cx.env().scale;
let c = &k.c;
let mut overlays = Vec::new();
if s.toast_until.is_some() {
let toast = Toast::new("restored", "Defaults restored")
.description("The fire department has been notified.")
.icon(k, &oc::CIRCLE_CHECK)
.build(k);
overlays.push(ToastRegion::new().toast(toast).build(k).mark(mk(mat::NONE, node::TOAST)));
}
if s.show_cursor
&& let Some(p) = s.cursor
{
overlays.push(pointer(p));
}
let base = row()
.key("window")
.fill(c.bg_base)
.child(sidebar(s, k))
.child(el().key("sidebar-edge").w(hair).h_full().fill(c.border_base))
.child(content(s, k, hair));
rune_kit::root(base, overlays)
}
// ---------------------------------------------------------------- sidebar
fn sidebar(s: &Cursed, k: &Kit) -> El {
let c = &k.c;
let w = SIDEBAR_W - 24.0;
let idx = PAGES.iter().position(|p| *p == s.page).unwrap_or(0);
let mut nav = el()
.key("nav")
.w(w)
.h(PAGES.len() as f32 * NAV_PITCH)
.mark(mk(mat::NONE, node::NAV))
.child(
el().key("nav-sel")
.absolute(0.0, idx as f32 * NAV_PITCH)
.size(w, NAV_H)
.radius(6.0)
.fill(c.layer_03)
.lead(motion::LEAD, motion::DEFAULT)
.mark(mk(mat::SEL, node::NAV)),
);
for (i, p) in PAGES.into_iter().enumerate() {
let selected = i == idx;
let glyph = match p {
Page::General => &oc::SETTINGS_GEAR,
Page::Appearance => &icons::SUN,
Page::Network => &oc::GLOBE,
Page::Security => &icons::SHIELD,
Page::Accessibility => &icons::PERSON,
Page::Developer => &oc::CONSOLE,
};
nav = nav.child(
row()
.key(format!("nav-{}", p.id()))
.role("tab")
.label(p.title())
.absolute(0.0, i as f32 * NAV_PITCH)
.size(w, NAV_H)
.px(8.0)
.gap(8.0)
.center_y()
.radius(6.0)
.hover(if selected { Color::TRANSPARENT } else { c.hover })
.on_press(tap(move |s: &mut Cursed| s.page = p))
.child(icon(glyph, 16.0).key("icon").color(if selected { c.icon_base } else { c.icon_muted }))
.child(text(p.title()).key("label").font(k.ty.ui).color(if selected { c.text_base } else { c.text_muted })),
);
}
col()
.key("sidebar")
.w(SIDEBAR_W)
.h_full()
.fill(c.page)
.px(12.0)
.pt(20.0)
.pb(16.0)
.gap(16.0)
.child(
TextInput::new(&s.search)
.placeholder("Search")
.leading_icon(&oc::MAGNIFYING_GLASS)
.width(Some(w))
.on_edit(|s: &mut Cursed| &mut s.search)
.build(k)
.key("search")
.mark(mk(mat::CONTROL, node::SEARCH)),
)
.child(nav)
.child(spacer())
.child(
Button::new("Restore Defaults")
.variant(ButtonVariant::Neutral)
.on_press(tap(|s: &mut Cursed| s.restore()))
.build(k)
.key("restore")
.mark(mk(mat::CONTROL, 0)),
)
}
// ---------------------------------------------------------------- content
fn content(s: &Cursed, k: &Kit, hair: f32) -> El {
let page = match s.page {
Page::General => general(s, k, hair),
Page::Appearance => appearance(s, k, hair),
Page::Network => network(s, k, hair),
Page::Security => security(s, k, hair),
Page::Accessibility => accessibility(s, k, hair),
Page::Developer => developer(s, k, hair),
};
col().key("content").grow(1.0).h_full().fill(k.c.bg_base).child(
page.key(format!("page-{}", s.page.id()))
.w_full()
.px(40.0)
.pt(32.0)
.gap(24.0)
.transition(Transition::asymmetric(Transition::opacity(), Transition::identity()))
.opacity_motion(Spring::new(0.18, 0.0)),
)
}
fn header(k: &Kit, title: &str, desc: &str) -> El {
col()
.key("header")
.gap(2.0)
.child(text(title).key("title").font(TITLE).color(k.c.text_base))
.child(text(desc).key("desc").font(k.ty.ui).color(k.c.text_muted))
}
/// A titled list of rows with hairlines between them. `node` anchors effects to the card.
fn section(k: &Kit, hair: f32, key: &str, title: &str, trailing: Option<El>, node: u16, rows: Vec<El>) -> El {
let c = &k.c;
let mut inner = col().key("rows").w_full().mark(mk(mat::NONE, node));
let n = rows.len();
for (i, r) in rows.into_iter().enumerate() {
inner = inner.child(r);
if i + 1 < n {
inner = inner.child(el().key(format!("sep{i}")).h(hair).w_full().fill(c.border_base));
}
}
let mut head = row().key("head").w_full().h(24.0).center_y().justify_between().child(text(title).key("title").font(SECTION).color(c.text_base));
if let Some(t) = trailing {
head = head.child(t);
}
col().key(key).w_full().gap(10.0).child(head).child(
col()
.key(format!("{key}-card"))
.w_full()
.radius(8.0)
.fill(c.layer_01)
.border(0.5, c.border_muted)
.px(16.0)
.mark(mk(mat::CARD, node))
.child(inner),
)
}
fn setting(k: &Kit, key: &str, title: &str, desc: &str, control: El) -> El {
row()
.key(key)
.w_full()
.py(12.0)
.gap(16.0)
.center_y()
.child(
col()
.key("copy")
.grow(1.0)
.shrink()
.gap(1.0)
.child(text(title).key("title").font(k.ty.ui_medium).color(k.c.text_base))
.child(text(desc).key("desc").font(k.ty.ui).color(k.c.text_muted)),
)
.child(control)
}
fn switch(k: &Kit, key: &str, on: bool, label: &str, flip: impl Fn(&mut Cursed) + 'static) -> El {
Switch::new(on).label(label).hide_label().on_toggle(tap(flip)).build(k).key(key).mark(mk(mat::CONTROL, 0))
}
fn toggle_row(k: &Kit, key: &str, title: &str, desc: &str, on: bool, flip: impl Fn(&mut Cursed) + 'static) -> El {
setting(k, key, title, desc, switch(k, &format!("{key}-switch"), on, title, flip))
}
/// A plain row: a name with a trailing value.
fn item(k: &Kit, key: &str, lead: El, name: &str, trailing: El) -> El {
row()
.key(key)
.w_full()
.h(44.0)
.gap(10.0)
.center_y()
.child(lead)
.child(text(name).key("name").font(k.ty.ui_medium).color(k.c.text_base).grow(1.0))
.child(trailing)
}
fn app_tile(key: &str, letter: &str, color: Color) -> El {
row()
.key(key)
.size(22.0, 22.0)
.radius(5.5)
.fill(color)
.center()
.child(text(letter).key("letter").font(TextStyle::new(11.0, 640.0)).color(Color::WHITE))
}
fn muted(k: &Kit, key: &str, s: &str) -> El {
text(s).key(key).font(k.ty.ui).color(k.c.text_muted)
}
fn hx(h: u32) -> Color {
rune::color::hex(&format!("#{h:06x}")).unwrap_or(Color::BLACK)
}
// ---------------------------------------------------------------- pages
fn general(s: &Cursed, k: &Kit, hair: f32) -> El {
let p = &s.p;
let mut layer = Vec::new();
col()
.child(header(k, "General", "Startup, search and updates."))
.child(section(
k,
hair,
"startup",
"Startup",
None,
0,
vec![
toggle_row(k, "login", "Launch at login", "Open OpenCode when you log in.", p.launch_at_login, |s| {
s.p.launch_at_login = !s.p.launch_at_login
}),
toggle_row(k, "fast", "Lightning-fast startup", "Skip the splash screen and open instantly.", p.fast_startup, |s| {
s.p.fast_startup = !s.p.fast_startup
}),
],
))
.child(section(
k,
hair,
"search",
"Search",
None,
0,
vec![
toggle_row(k, "spotlight", "Show in Spotlight", "Let Spotlight find your sessions and settings.", p.spotlight, |s| {
s.p.spotlight = !s.p.spotlight
}),
setting(
k,
"language",
"Language",
"Used for menus and messages.",
Select::new("lang", &["English"]).current(Some("English")).build(k, &mut layer),
),
],
))
.child(section(
k,
hair,
"updates",
"Updates",
None,
0,
vec![toggle_row(k, "updates", "Automatic updates", "Download and install updates in the background.", p.auto_update, |s| {
s.p.auto_update = !s.p.auto_update
})],
))
}
fn appearance(s: &Cursed, k: &Kit, hair: f32) -> El {
let p = &s.p;
col()
.child(header(k, "Appearance", "How OpenCode looks."))
.child(section(
k,
hair,
"theme",
"Theme",
None,
0,
vec![
setting(
k,
"mode",
"Appearance",
"Match the system, or pick one.",
SegmentedControl::new(&APPEARANCES, Some(p.appearance))
.width(Some(204.0))
.on_pick(|s: &mut Cursed, i: usize, tx: &mut Tx| {
s.p.appearance = i;
s.taps += 1;
tx.color_motion(Spring::new(0.4, 0.0));
})
.build(k)
.key("mode-control")
.mark(mk(mat::CONTROL, 0)),
),
setting(k, "brightness", "Brightness", "How bright the window is.", slider(k, p.brightness)),
],
))
.child(section(
k,
hair,
"text",
"Text",
None,
0,
vec![
setting(k, "size", "Text size", "Used across the app.", Select::new("size", &["13 pt"]).current(Some("13 pt")).build(k, &mut Vec::new())),
setting(k, "font", "Code font", "Used in diffs and the terminal.", Select::new("font", &["IBM Plex Mono"]).current(Some("IBM Plex Mono")).build(k, &mut Vec::new())),
],
))
}
fn network(s: &Cursed, k: &Kit, hair: f32) -> El {
let p = &s.p;
let allow = |key: &str, letter: &str, col_: u32, name: &str| {
item(k, key, app_tile("tile", letter, hx(col_)), name, muted(k, "state", "Allow incoming connections"))
};
col()
.child(header(k, "Network", "Firewall and addresses."))
.child(section(
k,
hair,
"firewall",
"Firewall",
None,
0,
vec![toggle_row(k, "firewall", "Firewall", "Block incoming connections from unknown apps.", p.firewall, |s| {
s.p.firewall = !s.p.firewall
})],
))
.child(section(
k,
hair,
"allowed",
"Allowed apps",
None,
crate::ui::node::ALLOWED,
vec![
allow("opencode", "O", 0x1d1d1f, "OpenCode"),
allow("rune", "R", 0x6d4aff, "Rune"),
allow("display", "S", 0x2f80ed, "Studio Display Updater"),
],
))
.child(section(
k,
hair,
"address",
"Address",
None,
0,
vec![
toggle_row(k, "static", "Static IP", "Use a fixed address instead of DHCP.", p.static_ip, |s| s.p.static_ip = !s.p.static_ip),
setting(
k,
"ip",
"IP address",
"This Mac's address on the local network.",
TextInput::new(&s.ip)
.width(Some(168.0))
.disabled(!p.static_ip)
.on_edit(|s: &mut Cursed| &mut s.ip)
.build(k)
.key("ip-field")
.mark(mk(mat::CONTROL, node::IP)),
),
],
))
}
fn security(s: &Cursed, k: &Kit, hair: f32) -> El {
let p = &s.p;
let door = |key: &str, name: &str, state: &str| {
item(
k,
key,
el().key("dot").size(8.0, 8.0).radius(4.0).fill(k.c.success.icon).ml(7.0).mr(7.0),
name,
Badge::new(state).variant(BadgeVariant::Subtle).build(k),
)
};
col()
.child(header(k, "Security", "Locks, passwords and the perimeter."))
.child(section(
k,
hair,
"protection",
"Protection",
None,
0,
vec![
toggle_row(k, "fence", "Electric fence", "Protect the perimeter of your network.", p.fence, |s| s.p.fence = !s.p.fence),
toggle_row(k, "sleep", "Require password after sleep", "Ask for your password when the display wakes.", p.lock_on_sleep, |s| {
s.p.lock_on_sleep = !s.p.lock_on_sleep
}),
],
))
.child(section(
k,
hair,
"perimeter",
"Perimeter",
None,
node::PERIMETER,
vec![
door("front", "Front door", "Locked"),
door("back", "Back door", "Locked"),
door("ssh", "Port 22", "Closed"),
door("server", "Port 4096", "OpenCode only"),
],
))
}
fn accessibility(s: &Cursed, k: &Kit, hair: f32) -> El {
let p = &s.p;
col()
.child(header(k, "Accessibility", "Display, motion and feedback."))
.child(section(
k,
hair,
"display",
"Display",
None,
0,
vec![
toggle_row(k, "contrast", "Increase contrast", "Make edges and text stand out more.", p.contrast, |s| s.p.contrast = !s.p.contrast),
toggle_row(k, "transparency", "Reduce transparency", "Make glass surfaces solid.", p.reduce_transparency, |s| {
s.p.reduce_transparency = !s.p.reduce_transparency
}),
],
))
.child(section(
k,
hair,
"motion",
"Motion",
None,
0,
vec![toggle_row(k, "reduce", "Reduce motion", "Calmer, shorter animations.", p.reduce_motion, |s| {
s.p.reduce_motion = !s.p.reduce_motion
})],
))
.child(section(
k,
hair,
"feedback",
"Feedback",
None,
0,
vec![setting(
k,
"haptics",
"Haptic feedback",
"How strongly clicks are felt.",
SegmentedControl::new(&HAPTICS, Some(p.haptics))
.width(Some(204.0))
.on_pick(|s: &mut Cursed, i: usize, _: &mut Tx| {
s.p.haptics = i;
s.taps += 1;
})
.build(k)
.key("haptics-control")
.mark(mk(mat::CONTROL, 0)),
)],
))
}
fn developer(s: &Cursed, k: &Kit, hair: f32) -> El {
let p = &s.p;
let c = &k.c;
let mut reload = Button::new("Reload now").on_press(tap(|_: &mut Cursed| {})).build(k).key("reload-btn").mark(mk(mat::CONTROL, node::RELOAD));
if p.hot_reload {
reload = reload.fill(hx(0xd8401a)).motion(Spring::new(1.6, 0.0));
} else {
reload = reload.motion(Spring::new(2.0, 0.0));
}
let size = |key: &str, name: &str, v: &str| item(k, key, icon(&oc::FOLDER, 16.0).key("icon").color(c.icon_muted).ml(3.0).mr(3.0), name, muted(k, "size", v));
let rows = if p.flushed {
vec![row().key("empty").w_full().h(44.0).center_y().child(muted(k, "label", "Nothing cached."))]
} else {
vec![
size("shaders", "Shader cache", "1.2 GB"),
size("thumbs", "Thumbnails", "640 MB"),
size("snapshots", "Session snapshots", "512 MB"),
]
};
let flush = Button::new("Flush cache")
.control_size(ControlSize::Regular)
.disabled(p.flushed || s.flush_t0.is_some())
.on_press(tap(|s: &mut Cursed| s.flush_requested = true))
.build(k)
.key("flush-btn")
.mark(mk(mat::CONTROL, 0));
col()
.child(header(k, "Developer", "Builds, reloads and caches."))
.child(section(
k,
hair,
"reloading",
"Reloading",
None,
0,
vec![
toggle_row(k, "hot", "Hot reload", "Reload the app when files change.", p.hot_reload, |s| s.p.hot_reload = !s.p.hot_reload),
setting(k, "reload", "Reload renderer", "Rebuild shaders and reload the window.", reload),
],
))
.child(section(
k,
hair,
"cache",
if p.flushed { "Cache · Zero KB" } else { "Cache · 2.4 GB" },
Some(flush),
node::CACHE,
rows,
))
}
// ---------------------------------------------------------------- controls
fn slider(k: &Kit, v: f32) -> El {
let c = &k.c;
let (w, h, kd, bar) = (168.0, 20.0, 16.0, 4.0);
let travel = w - kd;
let to_value = move |x: f32| ((x - kd / 2.0) / travel).clamp(0.0, 1.0);
row()
.key("brightness-control")
.gap(10.0)
.center_y()
.child(icon(&icons::SUN, 14.0).key("dim").color(c.icon_faint))
.child(
el().key("brightness-slider")
.role("slider")
.label("Brightness")
.size(w, h)
.motion(motion::SNAPPY)
.on_drag(move |s: &mut Cursed, d: &mut Drag, tx: &mut Tx| {
let knob = kd / 2.0 + s.p.brightness * travel;
match d.phase {
Phase::Down => {
d.data = s.p.brightness;
if (d.x - knob).abs() > kd / 2.0 + 3.0 {
s.p.brightness = to_value(d.x);
}
}
Phase::Move => {
let knob = kd / 2.0 + d.data * travel;
let grab = if (d.start_x - knob).abs() <= kd / 2.0 + 3.0 { d.start_x - knob } else { 0.0 };
s.p.brightness = to_value(d.x - grab);
tx.instant();
}
Phase::Up => { if d.cancelled() { s.p.brightness = d.data; } }
}
})
.child(el().key("track").size(w, bar).absolute(0.0, (h - bar) / 2.0).radius(bar / 2.0).fill(c.layer_04))
.child(el().key("fill").size(kd / 2.0 + v * travel, bar).absolute(0.0, (h - bar) / 2.0).radius(bar / 2.0).fill(c.icon_base))
.child(
el().key("knob")
.size(kd, kd)
.absolute(v * travel, (h - kd) / 2.0)
.radius(kd / 2.0)
.fill(c.knob_on)
.border(0.5, c.border_strong)
.shadow(1.0, 3.0, k.dark_a(0.18))
.mark(mk(mat::CONTROL, 0)),
),
)
.child(icon(&icons::SUN, 18.0).key("bright").color(c.icon_muted))
.child(text(format!("{:.0}%", v * 100.0)).key("value").w(36.0).font(k.ty.ui).color(c.text_muted).align(Align::End))
}
/// The demo pointer: a black arrow with a white keyline, tip at `p`.
fn pointer(p: [f32; 2]) -> El {
let arrow = [[0.0, 0.0], [0.0, 16.5], [4.1, 12.7], [6.9, 19.2], [9.4, 18.1], [6.7, 11.8], [12.2, 11.8]];
let mut ring = arrow.to_vec();
ring.push(arrow[0]);
canvas(Shape::new().fill(arrow.to_vec(), Color::BLACK).stroke(ring, 1.3, Color::WHITE))
.key("demo-pointer")
.size(14.0, 21.0)
.absolute(p[0], p[1])
.mark(mk(mat::NONE, node::CURSOR))
}