tawasuyu/llimphi
Sovereign retained-mode GPU UI framework in Rust (wgpu+vello+taffy+parley), Elm loop, 40+ widgets.
chore: refresco desde el monorepo — vello 0.9 / wgpu 29, 120 miembros
1//! Filmstrip headless de **animateContentSize** (Bloque 15 de
2//! PARIDAD-FLUTTER): un card con `View::animated_size(key, dur)`
3//! arranca con tamaño 80×40 y, tras el primer frame, se reasigna a
4//! 320×120. Renderizamos cinco frames simulando `Instant::now()` a
5//! 0/60/120/180/240 ms — los del medio muestran el tween en curso, el
6//! último ya está asentado.
7//!
8//! Verifica que el camino `reconcile_size_anim` parcha `style.size`
9//! ANTES del mount/compute, así el layout cascade ve el tamaño
10//! interpolado y los siblings reflowean (aquí el padre es un row con
11//! `gap`; el segundo hijo se va corriendo según crece el primero).
12//!
13//! `cargo run -p llimphi-compositor --example animated_size_demo -- [out.png]`
14
15use std::fs::File;
16use std::io::BufWriter;
17use std::time::{Duration, Instant};
18
19use llimphi_compositor::{
20 measure_text_node, mount, paint, reconcile_size_anim, SizeAnimRegistry, View,
21};
22use llimphi_hal::{wgpu, Hal};
23use llimphi_layout::taffy;
24use llimphi_layout::taffy::prelude::{length, percent, FlexDirection, Size, Style};
25use llimphi_layout::taffy::{AlignItems, JustifyContent, Rect};
26use llimphi_layout::LayoutTree;
27use llimphi_raster::peniko::Color;
28use llimphi_raster::{vello, Renderer};
29use llimphi_text::{Alignment, Typesetter};
30
31const FRAME_W: u32 = 360;
32const FRAME_H: u32 = 200;
33const NUM_FRAMES: u32 = 5;
34const W: u32 = FRAME_W * NUM_FRAMES;
35const H: u32 = FRAME_H;
36const FMT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
37
38const KEY: u64 = 1;
39const DUR_MS: u64 = 200;
40const FRAME_STEP_MS: u64 = 60;
41
42fn rgb(r: u8, g: u8, b: u8) -> Color {
43 Color::from_rgba8(r, g, b, 255)
44}
45
46/// Card animable cuya `target_size` se elige según el frame (frame 0 =
47/// 80×40, resto = 320×120). El gap del row y el segundo hijo (un fixed
48/// 60×40) garantizan que el sibling reflowee al crecer el card.
49fn build_view(target_size: (f32, f32), accent: Color, fg: Color, panel: Color) -> View<()> {
50 let card = View::<()>::new(Style {
51 size: Size {
52 width: length(target_size.0),
53 height: length(target_size.1),
54 },
55 align_items: Some(AlignItems::CENTER),
56 justify_content: Some(JustifyContent::CENTER),
57 ..Default::default()
58 })
59 .fill(accent)
60 .radius(12.0)
61 .text_aligned("animated", 14.0, panel, Alignment::Center)
62 .animated_size(KEY, Duration::from_millis(DUR_MS));
63
64 let companion = View::<()>::new(Style {
65 size: Size {
66 width: length(60.0_f32),
67 height: length(40.0_f32),
68 },
69 align_items: Some(AlignItems::CENTER),
70 justify_content: Some(JustifyContent::CENTER),
71 ..Default::default()
72 })
73 .fill(panel)
74 .radius(8.0)
75 .border(1.0, rgb(180, 184, 196))
76 .text_aligned("sib", 11.0, fg, Alignment::Center);
77
78 View::<()>::new(Style {
79 flex_direction: FlexDirection::Row,
80 size: Size {
81 width: percent(1.0_f32),
82 height: percent(1.0_f32),
83 },
84 align_items: Some(AlignItems::CENTER),
85 justify_content: Some(JustifyContent::FLEX_START),
86 gap: Size {
87 width: length(12.0_f32),
88 height: length(0.0_f32),
89 },
90 padding: Rect {
91 left: length(16.0_f32),
92 right: length(16.0_f32),
93 top: length(16.0_f32),
94 bottom: length(16.0_f32),
95 },
96 ..Default::default()
97 })
98 .fill(rgb(245, 247, 250))
99 .children(vec![card, companion])
100}
101
102fn main() {
103 let out = std::env::args()
104 .nth(1)
105 .unwrap_or_else(|| "animated_size.png".to_string());
106
107 let theme = llimphi_theme::Theme::light();
108 let accent = theme.accent;
109 let fg = Color::from_rgba8(30, 34, 44, 255);
110 let panel = theme.bg_panel;
111
112 let mut reg = SizeAnimRegistry::new();
113 let t0 = Instant::now();
114
115 let hal = pollster::block_on(Hal::new(None)).expect("hal");
116 let mut renderer = Renderer::new(&hal).expect("renderer");
117 let target = hal.device.create_texture(&wgpu::TextureDescriptor {
118 label: Some("dump-animated-size"),
119 size: wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
120 mip_level_count: 1,
121 sample_count: 1,
122 dimension: wgpu::TextureDimension::D2,
123 format: FMT,
124 usage: wgpu::TextureUsages::STORAGE_BINDING
125 | wgpu::TextureUsages::RENDER_ATTACHMENT
126 | wgpu::TextureUsages::COPY_SRC,
127 view_formats: &[],
128 });
129 let view_tex = target.create_view(&wgpu::TextureViewDescriptor::default());
130 let [r, g, b, _] = theme.bg_app.components;
131 let bg = Color::from_rgba8((r * 255.0) as u8, (g * 255.0) as u8, (b * 255.0) as u8, 255);
132
133 // Componemos UNA scene grande con los 5 frames lado-a-lado. Cada
134 // frame es un sub-tree de `View` posicionado con offset horizontal
135 // vía translate del paint — más simple: para cada sub-scene
136 // renderizamos a un buffer y lo blitteamos? Lo más directo: armamos
137 // un root flex Row de 5 frames con un divider mínimo.
138 let mut frames: Vec<View<()>> = Vec::with_capacity(NUM_FRAMES as usize);
139 let mut ts = Typesetter::new();
140 for i in 0..NUM_FRAMES {
141 // Target size: frame 0 = 80×40 (asentado); resto = 320×120 (target nuevo).
142 let target_size = if i == 0 { (80.0, 40.0) } else { (320.0, 120.0) };
143 let mut frame_view = build_view(target_size, accent, fg, panel);
144 let when = t0 + Duration::from_millis(i as u64 * FRAME_STEP_MS);
145 // Reconcilá el size en el árbol del frame. Después del frame 0
146 // el registry conoce target=80×40. En el frame 1 el target nuevo
147 // arranca el tween; los frames 2-4 lo continúan.
148 let animating = reconcile_size_anim(&mut frame_view, &mut reg, when);
149 // Pintamos cada frame en una columna fija dentro de un row root.
150 // El alto fijo + width fijo hace que el rect del frame esté
151 // delimitado; el contenido del frame ocupa todo el alto.
152 let frame_box = View::<()>::new(Style {
153 size: Size {
154 width: length(FRAME_W as f32),
155 height: length(FRAME_H as f32),
156 },
157 flex_direction: FlexDirection::Column,
158 ..Default::default()
159 })
160 .fill(rgb(228, 232, 240))
161 .children(vec![
162 View::<()>::new(Style {
163 size: Size {
164 width: percent(1.0_f32),
165 height: length(20.0_f32),
166 },
167 ..Default::default()
168 })
169 .text_aligned(
170 format!(
171 "t = {} ms{}",
172 i as u64 * FRAME_STEP_MS,
173 if animating { " (animando)" } else { "" }
174 ),
175 11.0,
176 fg,
177 Alignment::Center,
178 ),
179 View::<()>::new(Style {
180 size: Size {
181 width: percent(1.0_f32),
182 height: length((FRAME_H - 20) as f32),
183 },
184 ..Default::default()
185 })
186 .children(vec![frame_view]),
187 ]);
188 frames.push(frame_box);
189 }
190 let root = View::<()>::new(Style {
191 flex_direction: FlexDirection::Row,
192 size: Size {
193 width: length(W as f32),
194 height: length(H as f32),
195 },
196 ..Default::default()
197 })
198 .children(frames);
199
200 let mut layout = LayoutTree::new();
201 let mounted = mount(&mut layout, root);
202 let computed = {
203 let tmap = &mounted.text_measures;
204 layout
205 .compute_with_measure(mounted.root, (W as f32, H as f32), |nid, known, avail| {
206 match tmap.get(&nid) {
207 Some(tm) => measure_text_node(&mut ts, tm, known, avail),
208 None => taffy::Size::ZERO,
209 }
210 })
211 .expect("layout")
212 };
213 let mut scene = vello::Scene::new();
214 paint(&mut scene, &mounted, &computed, &mut ts, None, None);
215 renderer
216 .render_to_view(&hal, &scene, &view_tex, W, H, bg)
217 .expect("render_to_view");
218
219 write_png(&hal, &target, &out);
220 eprintln!(
221 "animated_size_demo: escrito {out} ({W}x{H}) — 5 frames del card que \
222 crece de 80x40 a 320x120 en 200 ms. El sibling (cuadrado 'sib') se \
223 corre hacia la derecha por el gap del row a medida que el card crece.",
224 );
225}
226
227fn write_png(hal: &Hal, target: &wgpu::Texture, path: &str) {
228 let unpadded = (W * 4) as usize;
229 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize;
230 let padded = unpadded.div_ceil(align) * align;
231 let buf = hal.device.create_buffer(&wgpu::BufferDescriptor {
232 label: Some("readback"),
233 size: (padded * H as usize) as u64,
234 usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
235 mapped_at_creation: false,
236 });
237 let mut enc = hal
238 .device
239 .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
240 enc.copy_texture_to_buffer(
241 wgpu::TexelCopyTextureInfo {
242 texture: target,
243 mip_level: 0,
244 origin: wgpu::Origin3d::ZERO,
245 aspect: wgpu::TextureAspect::All,
246 },
247 wgpu::TexelCopyBufferInfo {
248 buffer: &buf,
249 layout: wgpu::TexelCopyBufferLayout {
250 offset: 0,
251 bytes_per_row: Some(padded as u32),
252 rows_per_image: Some(H),
253 },
254 },
255 wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
256 );
257 hal.queue.submit(std::iter::once(enc.finish()));
258 let slice = buf.slice(..);
259 let (tx, rx) = std::sync::mpsc::channel();
260 slice.map_async(wgpu::MapMode::Read, move |r| {
261 let _ = tx.send(r);
262 });
263 let _ = hal.device.poll(wgpu::PollType::wait_indefinitely());
264 rx.recv().unwrap().unwrap();
265 let data = slice.get_mapped_range();
266 let mut pixels = Vec::with_capacity((W * H * 4) as usize);
267 for row in 0..H as usize {
268 let s = row * padded;
269 pixels.extend_from_slice(&data[s..s + unpadded]);
270 }
271 drop(data);
272 buf.unmap();
273 let file = File::create(path).expect("png");
274 let mut enc = png::Encoder::new(BufWriter::new(file), W, H);
275 enc.set_color(png::ColorType::Rgba);
276 enc.set_depth(png::BitDepth::Eight);
277 let mut w = enc.write_header().unwrap();
278 w.write_image_data(&pixels).unwrap();
279}