Skip to main content

hotpatch/
hotpatch.rs

1//! Hot-patching game code: change a system while the game runs, and the
2//! running game picks up the new code without losing any state.
3//!
4//! ```sh
5//! cargo install dioxus-cli@0.7.10   # once; installs `dx`
6//! dx serve --hot-patch --example hotpatch --features hotpatch
7//! ```
8//!
9//! Then edit `spin` or `wobble` below and save: the crabs change behavior
10//! within a second, mid-spin, where they were.
11
12use ponko::*;
13
14/// Every crab turns. Try a different speed, or `-=` to turn the other way.
15// ANCHOR: spin
16fn spin(ctx: &mut Ctx) {
17    let dt = ctx.dt();
18    for t in ctx.world.query::<&mut Transform2D>().iter() {
19        t.rotation += -6.0 * dt;
20    }
21}
22// ANCHOR_END: spin
23
24/// Crabs breathe. Try a bigger amplitude, or a different shape.
25fn wobble(ctx: &mut Ctx) {
26    let time = ctx.sim_time() as f32;
27    for (t, crab) in ctx.world.query::<(&mut Transform2D, &Crab)>().iter() {
28        let s = 1.0 + 0.15 * (time * 3.0 + crab.0).sin();
29        t.scale = vec2(s, s);
30    }
31}
32
33/// Prints the first crab's rotation once a second, so you can see that
34/// state carries over a patch.
35fn report(ctx: &mut Ctx) {
36    let tick = ctx.sim_tick();
37    if tick.is_multiple_of(60)
38        && let Some(t) = ctx.world.query::<&Transform2D>().iter().next()
39    {
40        println!("tick {tick:>5}  rotation {:>7.2}", t.rotation);
41    }
42}
43
44/// A phase, so crabs don't all move together.
45struct Crab(f32);
46
47fn main() {
48    Game::new("Crabby Engine: hot patching", 1280, 720)
49        .sim_system(spin)
50        .sim_system(wobble)
51        .sim_system(report)
52        .run(|ctx| {
53            let crab = ctx.load_texture("crab.png");
54            for i in 0..12 {
55                let at = vec2(160.0 + (i % 6) as f32 * 190.0, 220.0 + (i / 6) as f32 * 280.0);
56                ctx.world
57                    .spawn((Transform2D::at(at), Sprite::new(crab), Crab(i as f32 * 0.7)));
58            }
59        });
60}