tawasuyu/llimphi
Sovereign retained-mode GPU UI framework in Rust (wgpu+vello+taffy+parley), Elm loop, 40+ widgets.
⎇ dba855e446ca2bd4e7d146bdc168fb232cad15a4
llimphi-compositor/examples/ripple_demo.rs
Ñawpa willay
Pi imata llamkarqan
ch'uya
refresh: stack al día (vello 0.7 / wgpu 27 / parley 0.6) + motor 3D voxel
1//! Filmstrip headless del **ripple/InkWell** (Bloque 8 de PARIDAD-FLUTTER):
2//! una fila de botones, cada uno con una salpicadura Material disparada en el
3//! mismo punto (arriba-izquierda) pero **observada a un progreso creciente** —
4//! de la onda recién nacida (izquierda) a casi extinta (derecha). Muestra el
5//! círculo expandiéndose desde el tap, recortado al contorno redondeado del
6//! botón, y atenuándose con el fade.
7//!
8//! Prueba el camino `View::ripple` → `RippleRegistry::trigger`/`paint` →
9//! `node_rrect` (clip) → píxeles, sin runtime ni winit. El press real lo
10//! sintetiza el runtime (`llimphi-ui`); acá lo emulamos llamando `trigger`.
11//!
12//! `cargo run -p llimphi-compositor --example ripple_demo -- [out.png]`
13
14use std::fs::File;
15use std::io::BufWriter;
16use std::time::{Duration, Instant};
17
18use llimphi_compositor::{mount, paint, RippleRegistry, View};
19use llimphi_hal::{wgpu, Hal};
20use llimphi_layout::taffy::prelude::{length, FlexDirection, Size, Style};
21use llimphi_layout::taffy::{AlignItems, JustifyContent, LengthPercentage, Rect};
22use llimphi_layout::LayoutTree;
23use llimphi_raster::peniko::Color;
24use llimphi_raster::{vello, Renderer};
25use llimphi_text::{Alignment, Typesetter};
26
27const W: u32 = 1180;
28const H: u32 = 240;
29const FMT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
30const FRAMES: usize = 6;
31const DUR: Duration = Duration::from_millis(500);
32/// Punto del tap relativo al rect de cada botón (arriba-izquierda) — la onda
33/// crece desde ahí hacia el rincón opuesto, bien visible en el filmstrip.
34const TAP: (f32, f32) = (38.0, 36.0);
35
36fn rgb(r: u8, g: u8, b: u8) -> Color {
37 Color::from_rgba8(r, g, b, 255)
38}
39
40fn main() {
41 let out = std::env::args().nth(1).unwrap_or_else(|| "ripple.png".to_string());
42 let fg = rgb(235, 238, 245);
43 let surface = rgb(44, 52, 70);
44 let ink = Color::from_rgba8(255, 255, 255, 90); // onda blanca semitransparente
45
46 // Una fila de FRAMES botones con ripple (key = columna). Layout real con
47 // gap/padding → cada botón tiene su propio rect computado (sin transform,
48 // que el paint del ripple no contempla en v1).
49 let botones: Vec<View<()>> = (0..FRAMES)
50 .map(|i| {
51 let pct = (i as f32 / (FRAMES as f32 - 1.0) * 100.0).round() as i32;
52 View::<()>::new(Style {
53 size: Size { width: length(150.0), height: length(140.0) },
54 align_items: Some(AlignItems::Center),
55 justify_content: Some(JustifyContent::Center),
56 ..Default::default()
57 })
58 .fill(surface)
59 .radius(20.0)
60 .ripple(i as u64, ink)
61 .children(vec![View::<()>::new(Style {
62 size: Size { width: length(130.0), height: length(20.0) },
63 ..Default::default()
64 })
65 .text_aligned(format!("{pct}%"), 14.0, fg, Alignment::Center)])
66 })
67 .collect();
68 let root = View::<()>::new(Style {
69 size: Size { width: length(W as f32), height: length(H as f32) },
70 flex_direction: FlexDirection::Row,
71 align_items: Some(AlignItems::Center),
72 justify_content: Some(JustifyContent::Center),
73 gap: Size { width: length(20.0), height: length(0.0) },
74 padding: Rect {
75 left: LengthPercentage::length(20.0),
76 right: LengthPercentage::length(20.0),
77 top: LengthPercentage::length(0.0),
78 bottom: LengthPercentage::length(0.0),
79 },
80 ..Default::default()
81 })
82 .children(botones);
83
84 let mut layout = LayoutTree::new();
85 let mounted = mount(&mut layout, root);
86 let computed = layout.compute(mounted.root, (W as f32, H as f32)).expect("layout");
87
88 // Pintá los botones, luego superponé una salpicadura por columna observada
89 // a un progreso creciente (cada registro disparó en t0, se observa a
90 // t0 + paso·i). Todas escriben en la misma escena.
91 let mut ts = Typesetter::new();
92 let mut scene = vello::Scene::new();
93 paint(&mut scene, &mounted, &computed, &mut ts, None, None);
94
95 let t0 = Instant::now();
96 let step = DUR / (FRAMES as u32 - 1);
97 for i in 0..FRAMES {
98 let mut reg = RippleRegistry::new();
99 reg.trigger(i as u64, TAP.0, TAP.1, ink, DUR, t0);
100 let now = t0 + step * i as u32;
101 reg.paint(&mut scene, &mounted, &computed, now);
102 }
103
104 // Volcado a PNG.
105 let hal = pollster::block_on(Hal::new(None)).expect("hal");
106 let mut renderer = Renderer::new(&hal).expect("renderer");
107 let target = hal.device.create_texture(&wgpu::TextureDescriptor {
108 label: Some("dump-ripple"),
109 size: wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
110 mip_level_count: 1,
111 sample_count: 1,
112 dimension: wgpu::TextureDimension::D2,
113 format: FMT,
114 usage: wgpu::TextureUsages::STORAGE_BINDING
115 | wgpu::TextureUsages::RENDER_ATTACHMENT
116 | wgpu::TextureUsages::COPY_SRC,
117 view_formats: &[],
118 });
119 let view = target.create_view(&wgpu::TextureViewDescriptor::default());
120 let bg = rgb(244, 245, 248);
121 renderer.render_to_view(&hal, &scene, &view, W, H, bg).expect("render_to_view");
122 write_png(&hal, &target, &out);
123 eprintln!(
124 "ripple_demo: escrito {out} ({W}x{H}) — {FRAMES} botones, la misma onda \
125 de {}ms observada a 0→100% (crece desde el tap y se desvanece)",
126 DUR.as_millis()
127 );
128}
129
130fn write_png(hal: &Hal, target: &wgpu::Texture, path: &str) {
131 let unpadded = (W * 4) as usize;
132 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize;
133 let padded = unpadded.div_ceil(align) * align;
134 let buf = hal.device.create_buffer(&wgpu::BufferDescriptor {
135 label: Some("readback"),
136 size: (padded * H as usize) as u64,
137 usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
138 mapped_at_creation: false,
139 });
140 let mut enc = hal
141 .device
142 .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
143 enc.copy_texture_to_buffer(
144 wgpu::TexelCopyTextureInfo {
145 texture: target,
146 mip_level: 0,
147 origin: wgpu::Origin3d::ZERO,
148 aspect: wgpu::TextureAspect::All,
149 },
150 wgpu::TexelCopyBufferInfo {
151 buffer: &buf,
152 layout: wgpu::TexelCopyBufferLayout {
153 offset: 0,
154 bytes_per_row: Some(padded as u32),
155 rows_per_image: Some(H),
156 },
157 },
158 wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
159 );
160 hal.queue.submit(std::iter::once(enc.finish()));
161 let slice = buf.slice(..);
162 let (tx, rx) = std::sync::mpsc::channel();
163 slice.map_async(wgpu::MapMode::Read, move |r| {
164 let _ = tx.send(r);
165 });
166 hal.device.poll(wgpu::PollType::wait_indefinitely());
167 rx.recv().unwrap().unwrap();
168 let data = slice.get_mapped_range();
169 let mut pixels = Vec::with_capacity((W * H * 4) as usize);
170 for row in 0..H as usize {
171 let s = row * padded;
172 pixels.extend_from_slice(&data[s..s + unpadded]);
173 }
174 drop(data);
175 buf.unmap();
176 let file = File::create(path).expect("png");
177 let mut enc = png::Encoder::new(BufWriter::new(file), W, H);
178 enc.set_color(png::ColorType::Rgba);
179 enc.set_depth(png::BitDepth::Eight);
180 let mut w = enc.write_header().unwrap();
181 w.write_image_data(&pixels).unwrap();
182}