gioser

tawasuyu/llimphi

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

Rust 229TOML 101Markdown 82Shell 24052 Sutichaykuna

⎇ 333dca1d5fb473825c9128d402d4cc4e2a5176fc llimphi-3d/examples/voxel_dimensiones.rs Rust · 433 siq'ikuna · 14.8 KB Ñawpa willay Pi imata llamkarqan ch'uya

feat(3d): cosechar efectos genéricos de supay + refrescar voxel/director 333dca1d5 · Sergio ·

1//! Demo de M5 — **dimensiones / mundos paralelos**. Tres mundos voxel
2//! independientes (Jardín, Inframundo, Cristal), cada uno con su grid, su cielo,
3//! su sol y sus entidades. La cámara ve la dimensión activa; "viajar" = cambiar
4//! cuál se renderiza.
5//!
6//! - **Arrastrar**: orbita. **Rueda**: zoom.
7//! - **Tab / N**: siguiente dimensión. **P**: anterior. **1/2/3**: ir a una.
8//! - Las entidades de la dimensión activa orbitan solas.
9//!
10//! `cargo run -p llimphi-3d --example voxel_dimensiones --release`
11//! `… --release -- --shot` → vuelca un PNG por dimensión a /tmp/m5_*.png
12
13use std::sync::{Arc, Mutex};
14use std::time::Duration;
15
16use llimphi_3d::glam::Vec3;
17use llimphi_3d::{Atmosphere, Camera3d, Dimension, Entity3d, Multiverse, VoxelGrid};
18use llimphi_ui::llimphi_hal::{wgpu, Hal};
19use llimphi_ui::llimphi_layout::taffy::prelude::{percent, Size, Style};
20use llimphi_ui::llimphi_layout::LayoutTree;
21use llimphi_ui::llimphi_raster::peniko::Color;
22use llimphi_ui::llimphi_raster::{vello, Renderer};
23use llimphi_ui::{
24    mount, paint_gpu, App, DragPhase, Handle, Key, KeyEvent, KeyState, Modifiers, NamedKey, View,
25    WheelDelta,
26};
27
28const FMT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
29const DIM: u32 = 64;
30
31// ── Construcción de los tres mundos ─────────────────────────────────────────
32
33fn world_jardin(d: u32) -> Dimension {
34    Dimension::new("Jardín", VoxelGrid::demo_scene([d, d, d]))
35        .with_sky([20, 30, 26])
36        .with_sun([0.5, 1.0, 0.35])
37        .with_atmosphere(Atmosphere {
38            sky_zenith: [70, 130, 90],
39            sky_horizon: [196, 222, 188],
40            fog_density: 0.22 / d as f32,
41            god_rays: 0.0,
42        })
43        .with_entities(orbit_entities(
44            d,
45            &[[235, 70, 70], [70, 220, 110], [90, 130, 250], [240, 200, 60]],
46        ))
47}
48
49fn world_inframundo(d: u32) -> Dimension {
50    let mut g = VoxelGrid::new([d, d, d]);
51    // Piso de lava (damero rojo/naranja).
52    for z in 0..d {
53        for x in 0..d {
54            let chk = ((x / 4 + z / 4) % 2) == 0;
55            let c = if chk { [150, 45, 22] } else { [185, 70, 28] };
56            for y in 0..2 {
57                g.set(x, y, z, c);
58            }
59        }
60    }
61    // Estalagmitas (columnas que se afinan hacia arriba).
62    for &(sx, sz, h) in &[(d / 4, d / 4, d * 2 / 5), (d * 3 / 4, d / 3, d / 2), (d / 2, d * 3 / 4, d * 3 / 5), (d / 5, d * 4 / 5, d * 3 / 10)] {
63        for y in 2..(2 + h).min(d) {
64            let t = (y - 2) as f32 / h as f32;
65            let r = ((1.0 - t) * 3.0).round() as i32;
66            for dx in -r..=r {
67                for dz in -r..=r {
68                    let x = sx as i32 + dx;
69                    let z = sz as i32 + dz;
70                    if x >= 0 && z >= 0 {
71                        let shade = 60 + (t * 70.0) as u8;
72                        g.set(x as u32, y, z as u32, [120 + shade / 2, 50, 30]);
73                    }
74                }
75            }
76        }
77    }
78    Dimension::new("Inframundo", g)
79        .with_sky([28, 8, 8])
80        .with_sun([0.35, 0.7, 0.5])
81        .with_atmosphere(Atmosphere {
82            sky_zenith: [60, 12, 10],
83            sky_horizon: [180, 70, 24],
84            fog_density: 0.4 / d as f32,
85            god_rays: 0.0,
86        })
87        .with_entities(orbit_entities(d, &[[255, 140, 30], [255, 90, 20], [255, 200, 60]]))
88}
89
90fn world_cristal(d: u32) -> Dimension {
91    let mut g = VoxelGrid::new([d, d, d]);
92    // Cristales octaédricos flotando en el vacío (sin piso).
93    let crystals: [(u32, u32, u32, [u8; 3]); 6] = [
94        (d / 2, d * 3 / 4, d / 2, [120, 220, 255]),
95        (d / 3, d / 2, d * 2 / 3, [200, 160, 255]),
96        (d * 2 / 3, d * 3 / 5, d / 3, [160, 255, 220]),
97        (d / 4, d * 2 / 3, d / 4, [255, 240, 200]),
98        (d * 3 / 4, d / 2, d * 3 / 4, [180, 200, 255]),
99        (d / 2, d / 3, d * 4 / 5, [220, 180, 255]),
100    ];
101    for (cx, cy, cz, col) in crystals {
102        let r = 4i32;
103        for dx in -r..=r {
104            for dy in -r..=r {
105                for dz in -r..=r {
106                    if dx.abs() + dy.abs() + dz.abs() <= r {
107                        let x = cx as i32 + dx;
108                        let y = cy as i32 + dy;
109                        let z = cz as i32 + dz;
110                        if x >= 0 && y >= 0 && z >= 0 {
111                            g.set(x as u32, y as u32, z as u32, col);
112                        }
113                    }
114                }
115            }
116        }
117    }
118    Dimension::new("Cristal", g)
119        .with_sky([10, 10, 22])
120        .with_sun([0.4, 0.8, 0.45])
121        .with_atmosphere(Atmosphere {
122            sky_zenith: [24, 18, 60],
123            sky_horizon: [120, 90, 200],
124            fog_density: 0.28 / d as f32,
125            god_rays: 0.0,
126        })
127        .with_entities(orbit_entities(d, &[[120, 240, 255], [220, 180, 255]]))
128}
129
130/// Entidades distribuidas en una órbita ecuatorial (se animan girando).
131fn orbit_entities(d: u32, colors: &[[u8; 3]]) -> Vec<Entity3d> {
132    let n = colors.len();
133    let df = d as f32;
134    (0..n)
135        .map(|k| {
136            let a = k as f32 / n as f32 * std::f32::consts::TAU;
137            Entity3d {
138                pos: [df * 0.5 + a.cos() * df * 0.42, df * 0.45, df * 0.5 + a.sin() * df * 0.42],
139                half: [df * 0.05, df * 0.05, df * 0.05],
140                color: colors[k],
141            }
142        })
143        .collect()
144}
145
146fn build_multiverse(d: u32) -> Multiverse {
147    Multiverse::new(vec![world_jardin(d), world_inframundo(d), world_cristal(d)])
148}
149
150fn rotate_y(e: &mut Entity3d, center: [f32; 3], ang: f32) {
151    let dx = e.pos[0] - center[0];
152    let dz = e.pos[2] - center[2];
153    let (s, c) = ang.sin_cos();
154    e.pos[0] = center[0] + dx * c - dz * s;
155    e.pos[2] = center[2] + dx * s + dz * c;
156}
157
158// ── App interactiva ─────────────────────────────────────────────────────────
159
160#[derive(Clone)]
161enum Msg {
162    Orbit(f32, f32),
163    Zoom(f32),
164    Tick,
165    Next,
166    Prev,
167    Go(usize),
168}
169
170struct Model {
171    yaw: f32,
172    pitch: f32,
173    dist: f32,
174    active: usize,
175    names: Vec<String>,
176    skies: Vec<[u8; 3]>,
177    mv: Arc<Mutex<Multiverse>>,
178}
179
180struct DimApp;
181
182impl App for DimApp {
183    type Model = Model;
184    type Msg = Msg;
185
186    fn title() -> &'static str {
187        "llimphi-3d · dimensiones"
188    }
189    fn initial_size() -> (u32, u32) {
190        (1000, 720)
191    }
192
193    fn init(handle: &Handle<Msg>) -> Model {
194        handle.spawn_periodic(Duration::from_millis(33), || Msg::Tick);
195        let mv = build_multiverse(DIM);
196        Model {
197            yaw: 35_f32.to_radians(),
198            pitch: 30_f32.to_radians(),
199            dist: DIM as f32 * 1.7,
200            active: mv.active(),
201            names: mv.names(),
202            skies: mv.skies(),
203            mv: Arc::new(Mutex::new(mv)),
204        }
205    }
206
207    fn window_title(model: &Model) -> Option<String> {
208        Some(format!(
209            "llimphi-3d · {} ({}/{})  —  Tab=siguiente",
210            model.names[model.active],
211            model.active + 1,
212            model.names.len()
213        ))
214    }
215
216    fn on_key(_model: &Model, ev: &KeyEvent) -> Option<Msg> {
217        if !matches!(ev.state, KeyState::Pressed) {
218            return None;
219        }
220        match &ev.key {
221            Key::Named(NamedKey::Tab) => Some(Msg::Next),
222            Key::Character(c) => match c.as_str() {
223                "n" | "N" => Some(Msg::Next),
224                "p" | "P" => Some(Msg::Prev),
225                "1" => Some(Msg::Go(0)),
226                "2" => Some(Msg::Go(1)),
227                "3" => Some(Msg::Go(2)),
228                _ => None,
229            },
230            _ => None,
231        }
232    }
233
234    fn on_wheel(_m: &Model, delta: WheelDelta, _c: (f32, f32), _mods: Modifiers) -> Option<Msg> {
235        Some(Msg::Zoom(delta.y))
236    }
237
238    fn update(mut model: Model, msg: Msg, _handle: &Handle<Msg>) -> Model {
239        match msg {
240            Msg::Orbit(dx, dy) => {
241                model.yaw -= dx * 0.008;
242                model.pitch += dy * 0.008;
243            }
244            Msg::Zoom(dy) => {
245                let f = (1.0 + dy * 0.1).clamp(0.5, 1.5);
246                model.dist = (model.dist * f).clamp(DIM as f32 * 0.5, DIM as f32 * 4.0);
247            }
248            Msg::Tick => {
249                // Anima las entidades de la dimensión activa.
250                let mut mv = model.mv.lock().unwrap();
251                let c = [DIM as f32 * 0.5, DIM as f32 * 0.45, DIM as f32 * 0.5];
252                for e in &mut mv.active_dim_mut().entities {
253                    rotate_y(e, c, 0.02);
254                }
255            }
256            Msg::Next => {
257                model.mv.lock().unwrap().next();
258                model.active = model.mv.lock().unwrap().active();
259            }
260            Msg::Prev => {
261                model.mv.lock().unwrap().prev();
262                model.active = model.mv.lock().unwrap().active();
263            }
264            Msg::Go(i) => {
265                let mut mv = model.mv.lock().unwrap();
266                mv.switch(i);
267                model.active = mv.active();
268            }
269        }
270        model
271    }
272
273    fn view(model: &Model) -> View<Msg> {
274        let camera = Camera3d::orbit(Vec3::ZERO, model.yaw, model.pitch, model.dist);
275        let mv = model.mv.clone();
276
277        let canvas = View::new(fill())
278            .gpu_paint_with(move |device, queue, encoder, target, _rect, vp| {
279                mv.lock().unwrap().render(device, queue, encoder, target, vp, &camera);
280            })
281            .draggable(|phase, dx, dy| match phase {
282                DragPhase::Move => Some(Msg::Orbit(dx, dy)),
283                DragPhase::End => None,
284            });
285
286        View::new(fill()).children(vec![canvas])
287    }
288}
289
290fn fill() -> Style {
291    Style {
292        size: Size {
293            width: percent(1.0),
294            height: percent(1.0),
295        },
296        ..Default::default()
297    }
298}
299
300fn main() {
301    let args: Vec<String> = std::env::args().collect();
302    if args.iter().any(|a| a == "--shot") {
303        shot();
304        return;
305    }
306    llimphi_ui::run::<DimApp>();
307}
308
309/// Vuelca un PNG por dimensión por el compositor real (mount → paint_gpu).
310fn shot() {
311    const W: u32 = 1000;
312    const H: u32 = 720;
313    let mv = Arc::new(Mutex::new(build_multiverse(DIM)));
314    let camera = Camera3d::orbit(Vec3::ZERO, 35_f32.to_radians(), 30_f32.to_radians(), DIM as f32 * 1.7);
315
316    let hal = pollster::block_on(Hal::new(None)).expect("hal");
317    let mut renderer = Renderer::new(&hal).expect("renderer");
318    let count = mv.lock().unwrap().count();
319
320    for i in 0..count {
321        let (name, sky) = {
322            let mut g = mv.lock().unwrap();
323            g.switch(i);
324            (g.active_name().to_string(), g.active_dim().sky)
325        };
326        let model_mv = mv.clone();
327        let cam = camera;
328        let canvas: View<Msg> = View::new(fill()).gpu_paint_with(
329            move |device, queue, encoder, target, _rect, vp| {
330                model_mv.lock().unwrap().render(device, queue, encoder, target, vp, &cam);
331            },
332        );
333        let view: View<Msg> = View::new(fill()).children(vec![canvas]);
334
335        let mut layout = LayoutTree::new();
336        let mounted = mount(&mut layout, view);
337        let computed = layout.compute(mounted.root, (W as f32, H as f32)).expect("layout");
338
339        let inter = hal.device.create_texture(&wgpu::TextureDescriptor {
340            label: Some("inter"),
341            size: wgpu::Extent3d {
342                width: W,
343                height: H,
344                depth_or_array_layers: 1,
345            },
346            mip_level_count: 1,
347            sample_count: 1,
348            dimension: wgpu::TextureDimension::D2,
349            format: FMT,
350            usage: wgpu::TextureUsages::STORAGE_BINDING
351                | wgpu::TextureUsages::TEXTURE_BINDING
352                | wgpu::TextureUsages::RENDER_ATTACHMENT
353                | wgpu::TextureUsages::COPY_SRC,
354            view_formats: &[],
355        });
356        let inter_view = inter.create_view(&wgpu::TextureViewDescriptor::default());
357        renderer
358            .render_to_view(&hal, &vello::Scene::new(), &inter_view, W, H, Color::from_rgba8(sky[0], sky[1], sky[2], 255))
359            .expect("base");
360
361        let mut enc = hal
362            .device
363            .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("gpu") });
364        let any = paint_gpu(&mounted, &computed, &hal.device, &hal.queue, &mut enc, &inter_view, (W, H));
365        hal.queue.submit(std::iter::once(enc.finish()));
366        let _ = hal.device.poll(wgpu::PollType::wait_indefinitely());
367        assert!(any, "gpu_painter no corrió");
368
369        let out = format!("/tmp/m5_{i}_{}.png", name.to_lowercase());
370        write_png(&hal, &inter, W, H, &out);
371        eprintln!("dimensión {i} = {name} → {out}");
372    }
373}
374
375fn write_png(hal: &Hal, target: &wgpu::Texture, w: u32, h: u32, path: &str) {
376    use std::fs::File;
377    use std::io::BufWriter;
378    let unpadded = (w * 4) as usize;
379    let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize;
380    let padded = unpadded.div_ceil(align) * align;
381    let buf = hal.device.create_buffer(&wgpu::BufferDescriptor {
382        label: Some("readback"),
383        size: (padded * h as usize) as u64,
384        usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
385        mapped_at_creation: false,
386    });
387    let mut enc = hal
388        .device
389        .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
390    enc.copy_texture_to_buffer(
391        wgpu::TexelCopyTextureInfo {
392            texture: target,
393            mip_level: 0,
394            origin: wgpu::Origin3d::ZERO,
395            aspect: wgpu::TextureAspect::All,
396        },
397        wgpu::TexelCopyBufferInfo {
398            buffer: &buf,
399            layout: wgpu::TexelCopyBufferLayout {
400                offset: 0,
401                bytes_per_row: Some(padded as u32),
402                rows_per_image: Some(h),
403            },
404        },
405        wgpu::Extent3d {
406            width: w,
407            height: h,
408            depth_or_array_layers: 1,
409        },
410    );
411    hal.queue.submit(std::iter::once(enc.finish()));
412    let slice = buf.slice(..);
413    let (tx, rx) = std::sync::mpsc::channel();
414    slice.map_async(wgpu::MapMode::Read, move |r| {
415        let _ = tx.send(r);
416    });
417    let _ = hal.device.poll(wgpu::PollType::wait_indefinitely());
418    rx.recv().unwrap().unwrap();
419    let data = slice.get_mapped_range();
420    let mut pixels = Vec::with_capacity((w * h * 4) as usize);
421    for row in 0..h as usize {
422        let s = row * padded;
423        pixels.extend_from_slice(&data[s..s + unpadded]);
424    }
425    drop(data);
426    buf.unmap();
427    let file = File::create(path).expect("png");
428    let mut penc = png::Encoder::new(BufWriter::new(file), w, h);
429    penc.set_color(png::ColorType::Rgba);
430    penc.set_depth(png::BitDepth::Eight);
431    let mut wr = penc.write_header().unwrap();
432    wr.write_image_data(&pixels).unwrap();
433}