tawasuyu

tawasuyu/llimphi

Sovereign retained-mode GPU UI framework in Rust (wgpu+vello+taffy+parley), Elm loop, 40+ widgets.

Rust 660Markdown 302TOML 157RON 312382 Definiciones

⎇ main llimphi-compositor/examples/anim_demo.rs Rust · 271 líneas · 11.7 KB Historia Quién tocó qué crudo

chore: refresco desde el monorepo — vello 0.9 / wgpu 29, 120 miembros d251eb32b · Sergio ·

1//! Filmstrip headless de **animaciones implícitas**, tres filas:
2//!
3//! - **Fila 1** — `View::animated`: el mismo nodo cuyo `fill` cambia de rojo a
4//!   azul, reconciliado a 6 instantes crecientes — crossfade rojo→púrpura→azul.
5//! - **Fila 2** — `View::animated_enter`: el fade-in de ENTRADA de un nodo, de
6//!   opacidad 0 a opaco, a los mismos 6 progresos.
7//! - **Fila 3** — `View::animated_exit`: el fade-out de SALIDA de un nodo
8//!   (capturado mientras vivía, reproducido como fantasma), de opaco a 0.
9//!
10//! Prueba el camino completo View.animated[_enter|_exit] → AnimRegistry →
11//! paint/paint_range/replay_ghosts → píxeles.
12//!
13//! `cargo run -p llimphi-compositor --example anim_demo -- [out.png]`
14
15use std::fs::File;
16use std::io::BufWriter;
17use std::time::{Duration, Instant};
18
19use llimphi_compositor::{mount, paint, paint_range, AnimRegistry, View};
20use llimphi_hal::{wgpu, Hal};
21use llimphi_layout::taffy::prelude::{length, FlexDirection, Size, Style};
22use llimphi_layout::taffy::{AlignItems, JustifyContent};
23use llimphi_layout::LayoutTree;
24use llimphi_raster::peniko::Color;
25use llimphi_raster::{vello, Renderer};
26use llimphi_text::{Alignment, Typesetter};
27use vello::kurbo::Affine;
28
29const W: u32 = 1180;
30const H: u32 = 580;
31/// Y de la fila de crossfade, de fade-in de entrada y de fade-out de salida.
32const ROW_FADE_Y: f64 = 40.0;
33const ROW_ENTER_Y: f64 = 220.0;
34const ROW_EXIT_Y: f64 = 400.0;
35const FMT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
36const FRAMES: usize = 6;
37const DUR: Duration = Duration::from_millis(500);
38
39fn rgb(r: u8, g: u8, b: u8) -> Color {
40    Color::from_rgba8(r, g, b, 255)
41}
42
43/// Una tarjeta animada (key=1) con `fill`, transladada (vía `transform`) a su
44/// columna `i` y con el `fill` que la `view` "quiere" este frame.
45fn card_shell(col: usize, row_y: f64, label: &str, fg: Color) -> View<()> {
46    View::<()>::new(Style {
47        size: Size { width: length(170.0), height: length(140.0) },
48        align_items: Some(AlignItems::CENTER),
49        justify_content: Some(JustifyContent::CENTER),
50        flex_direction: FlexDirection::Column,
51        ..Default::default()
52    })
53    .transform(Affine::translate((20.0 + col as f64 * 190.0, row_y)))
54    .radius(18.0)
55    .children(vec![View::<()>::new(Style {
56        size: Size { width: length(150.0), height: length(20.0) },
57        ..Default::default()
58    })
59    .text_aligned(label.to_string(), 13.0, fg, Alignment::Center)])
60}
61
62fn card(fill: Color, col: usize, label: &str, fg: Color) -> View<()> {
63    card_shell(col, ROW_FADE_Y, label, fg).fill(fill).animated(1, DUR)
64}
65
66/// Tarjeta con animación de ENTRADA: su primera aparición sube de opacidad 0
67/// a opaco. La key se varía por columna (key=10+col) para que cada registro la
68/// trate como una entrada nueva e independiente.
69fn card_enter(col: usize, label: &str, fg: Color) -> View<()> {
70    card_shell(col, ROW_ENTER_Y, label, fg)
71        .fill(rgb(60, 90, 220))
72        .animated_enter(10 + col as u64, DUR)
73}
74
75/// Tarjeta con animación de SALIDA: cuando desaparece, el runtime reproduce su
76/// subescena capturada con opacidad decreciente. Verde para distinguir la fila.
77fn card_exit(col: usize, label: &str, fg: Color) -> View<()> {
78    card_shell(col, ROW_EXIT_Y, label, fg)
79        .fill(rgb(40, 160, 90))
80        .animated_exit(20 + col as u64, DUR)
81}
82
83fn main() {
84    let out = std::env::args().nth(1).unwrap_or_else(|| "anim.png".to_string());
85    let red = rgb(220, 60, 60);
86    let blue = rgb(60, 90, 220);
87    let white = rgb(245, 245, 250);
88
89    // Un registro por columna: cada uno se asienta en rojo y arranca el tween
90    // a azul en t0, pero se OBSERVA a un instante distinto (i * paso). Así el
91    // filmstrip muestra la misma transición a 6 progresos.
92    let t0 = Instant::now();
93    let step = DUR / (FRAMES as u32 - 1);
94
95    let mut cards = Vec::new();
96    for i in 0..FRAMES {
97        let mut reg = AnimRegistry::new();
98        // Frame de asentamiento (rojo) en t0.
99        {
100            let mut layout = LayoutTree::new();
101            let mut m = mount(&mut layout, card(red, i, "", white));
102            reg.reconcile(&mut m, t0);
103        }
104        // Frame de detección del cambio a azul (arranca el reloj en t0).
105        {
106            let mut layout = LayoutTree::new();
107            let mut m = mount(&mut layout, card(blue, i, "", white));
108            reg.reconcile(&mut m, t0);
109        }
110        // Frame de observación: el nodo `card` se reconcilia a t0 + i*paso y su
111        // `fill` queda con el valor interpolado. Lo dejamos para pintar.
112        let now = t0 + step * i as u32;
113        let pct = (i as f32 / (FRAMES as f32 - 1.0) * 100.0).round() as i32;
114        let mut layout = LayoutTree::new();
115        let mut m = mount(&mut layout, card(blue, i, &format!("{pct}%"), white));
116        let computed = layout.compute(m.root, (W as f32, H as f32)).expect("layout");
117        reg.reconcile(&mut m, now);
118        cards.push((m, computed));
119
120        // Fila de entrada: la PRIMERA aparición ARRANCA el tween (en t0), así
121        // que el frame de observación a `now` ve el progreso correcto. Si se
122        // reconciliara una sola vez en `now`, el tween arrancaría y se
123        // observaría en el mismo instante → siempre t=0 (invisible).
124        let mut reg_enter = AnimRegistry::new();
125        {
126            let mut layout = LayoutTree::new();
127            let mut me = mount(&mut layout, card_enter(i, "", white));
128            reg_enter.reconcile(&mut me, t0);
129        }
130        let mut layout = LayoutTree::new();
131        let mut me = mount(&mut layout, card_enter(i, &format!("{pct}%"), white));
132        let computed = layout.compute(me.root, (W as f32, H as f32)).expect("layout");
133        reg_enter.reconcile(&mut me, now);
134        cards.push((me, computed));
135    }
136
137    // Fila de SALIDA: cada columna corre el ciclo real captura→fantasma→replay.
138    // (1) frame VIVO en t0: se reconcilia y se captura su subescena con
139    // `paint_range`. (2) frame AUSENTE en t0: la key desaparece → se promueve a
140    // fantasma (start=t0). (3) `replay_ghosts` a t0+paso·i lo pinta con la
141    // opacidad decreciente sobre `ghost_scene`, que luego se compone.
142    let mut ts_exit = Typesetter::new();
143    let mut ghost_scene = vello::Scene::new();
144    for i in 0..FRAMES {
145        let mut reg = AnimRegistry::new();
146        // (1) Vivo: reconcilia y captura su subárbol (root = idx 0).
147        {
148            let mut layout = LayoutTree::new();
149            let mut mv = mount(&mut layout, card_exit(i, "", white));
150            let computed = layout.compute(mv.root, (W as f32, H as f32)).expect("layout");
151            reg.reconcile(&mut mv, t0);
152            let n = mv.nodes.len();
153            let mut sub = vello::Scene::new();
154            paint_range(&mut sub, &mv, &computed, &mut ts_exit, None, None, 0, n, Affine::IDENTITY);
155            // El snapshot vivo se guarda con el `Anim` del propio nodo (el que
156            // trae `.animated_exit`) y el centro de su rect — es lo mismo que
157            // hace el runtime en `eventloop::redraw`.
158            let anim = mv.nodes[0].anim.expect("el root lleva animated_exit");
159            let centro = computed
160                .get(mv.nodes[0].id)
161                .map(|r| (r.x + r.w * 0.5, r.y + r.h * 0.5))
162                .unwrap_or((0.0, 0.0));
163            reg.store_live_exit(20 + i as u64, sub, centro, &anim);
164        }
165        // (2) Ausente: la key se va → fantasma con start=t0.
166        {
167            let mut layout = LayoutTree::new();
168            let mut empty = mount(&mut layout, card_shell(i, ROW_EXIT_Y, "", white));
169            layout.compute(empty.root, (W as f32, H as f32)).expect("layout");
170            reg.reconcile(&mut empty, t0);
171        }
172        // (3) Observación: el fantasma se reproduce al progreso `now`.
173        let now = t0 + step * i as u32;
174        let pct = (i as f32 / (FRAMES as f32 - 1.0) * 100.0).round() as i32;
175        reg.replay_ghosts(&mut ghost_scene, now, W as f32, H as f32);
176        // Rótulo del progreso sobre la tarjeta (fuera del fantasma, siempre nítido).
177        let mut layout = LayoutTree::new();
178        let mut lbl = mount(&mut layout, card_shell(i, ROW_EXIT_Y, &format!("{pct}%"), rgb(40, 50, 60)));
179        let lc = layout.compute(lbl.root, (W as f32, H as f32)).expect("layout");
180        // Sólo el texto (sin fill): reusa la tarjeta vacía como portador del label.
181        lbl.nodes[0].fill = None;
182        cards.push((lbl, lc));
183    }
184
185    // Pinta las columnas (cada una su árbol ya reconciliado) en una escena, y
186    // por debajo de los rótulos compone los fantasmas de la fila de salida.
187    let mut ts = Typesetter::new();
188    let mut scene = vello::Scene::new();
189    scene.append(&ghost_scene, None);
190    for (m, computed) in &cards {
191        paint(&mut scene, m, computed, &mut ts, None, None);
192    }
193
194    // Volcado a PNG.
195    let hal = pollster::block_on(Hal::new(None)).expect("hal");
196    let mut renderer = Renderer::new(&hal).expect("renderer");
197    let target = hal.device.create_texture(&wgpu::TextureDescriptor {
198        label: Some("dump-anim"),
199        size: wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
200        mip_level_count: 1,
201        sample_count: 1,
202        dimension: wgpu::TextureDimension::D2,
203        format: FMT,
204        usage: wgpu::TextureUsages::STORAGE_BINDING
205            | wgpu::TextureUsages::RENDER_ATTACHMENT
206            | wgpu::TextureUsages::COPY_SRC,
207        view_formats: &[],
208    });
209    let view = target.create_view(&wgpu::TextureViewDescriptor::default());
210    let bg = rgb(244, 245, 248);
211    renderer.render_to_view(&hal, &scene, &view, W, H, bg).expect("render_to_view");
212    write_png(&hal, &target, &out);
213    eprintln!(
214        "anim_demo: escrito {out} ({W}x{H}) — fila 1: crossfade rojo→azul · \
215         fila 2: fade-in de entrada · fila 3: fade-out de salida · {FRAMES} pasos"
216    );
217}
218
219fn write_png(hal: &Hal, target: &wgpu::Texture, path: &str) {
220    let unpadded = (W * 4) as usize;
221    let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize;
222    let padded = unpadded.div_ceil(align) * align;
223    let buf = hal.device.create_buffer(&wgpu::BufferDescriptor {
224        label: Some("readback"),
225        size: (padded * H as usize) as u64,
226        usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
227        mapped_at_creation: false,
228    });
229    let mut enc = hal
230        .device
231        .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
232    enc.copy_texture_to_buffer(
233        wgpu::TexelCopyTextureInfo {
234            texture: target,
235            mip_level: 0,
236            origin: wgpu::Origin3d::ZERO,
237            aspect: wgpu::TextureAspect::All,
238        },
239        wgpu::TexelCopyBufferInfo {
240            buffer: &buf,
241            layout: wgpu::TexelCopyBufferLayout {
242                offset: 0,
243                bytes_per_row: Some(padded as u32),
244                rows_per_image: Some(H),
245            },
246        },
247        wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
248    );
249    hal.queue.submit(std::iter::once(enc.finish()));
250    let slice = buf.slice(..);
251    let (tx, rx) = std::sync::mpsc::channel();
252    slice.map_async(wgpu::MapMode::Read, move |r| {
253        let _ = tx.send(r);
254    });
255    let _ = hal.device.poll(wgpu::PollType::wait_indefinitely());
256    rx.recv().unwrap().unwrap();
257    let data = slice.get_mapped_range();
258    let mut pixels = Vec::with_capacity((W * H * 4) as usize);
259    for row in 0..H as usize {
260        let s = row * padded;
261        pixels.extend_from_slice(&data[s..s + unpadded]);
262    }
263    drop(data);
264    buf.unmap();
265    let file = File::create(path).expect("png");
266    let mut enc = png::Encoder::new(BufWriter::new(file), W, H);
267    enc.set_color(png::ColorType::Rgba);
268    enc.set_depth(png::BitDepth::Eight);
269    let mut w = enc.write_header().unwrap();
270    w.write_image_data(&pixels).unwrap();
271}