summaryrefslogtreecommitdiff
path: root/examples/noc/src/system_of_systems.zig
blob: d02938cbd95204b12cd53021c7713ff0c0af2ed3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//! Nature of Code, Example 4.4: A System of Systems. Click to add emitters.
const std = @import("std");
const sk = @import("sketch");
const vec = sk.math;

pub const name = "system_of_systems";
pub const width = 640;
pub const height = 360;

/// A particle lives 128 steps (255 down by 2 until below 0), and an emitter
/// adds one a step: 128 at once.
const max_particles = 136;
const max_emitters = 32;

const Particle = struct {
    position: vec.Vec,
    velocity: vec.Vec,
    lifespan: f32 = 255,

    fn init(rng: std.Random, origin: vec.Vec) Particle {
        const lerp = std.math.lerp;
        return .{ .position = origin, .velocity = .{ lerp(-1, 1, rng.float(f32)), lerp(-2, 0, rng.float(f32)) } };
    }
    fn update(p: *Particle) void {
        p.velocity += vec.Vec{ 0, 0.05 }; // gravity
        p.position += p.velocity;
        p.lifespan -= 2;
    }
    fn isDead(p: Particle) bool {
        return p.lifespan < 0;
    }
};

const Emitter = struct {
    origin: vec.Vec,
    particles: sk.List(Particle, max_particles) = .{},

    fn run(e: *Emitter) void {
        var i = e.particles.count();
        while (i > 0) {
            i -= 1;
            const p = &e.particles.slice()[i];
            p.update();
            if (p.isDead()) _ = e.particles.orderedRemove(i);
        }
    }
};

pub const State = struct {
    rng: std.Random.Xoshiro256 = .init(4),
    emitters: sk.List(Emitter, max_emitters) = .{},
    clock: sk.Clock = .{},
};

pub fn update(s: *State, in: *const sk.Input) void {
    for (in.events) |e| if (e.kind == .mouse_down) {
        s.emitters.appendBounded(.{ .origin = .{ e.x, e.y } }) catch {};
    };
    for (0..s.clock.steps(in)) |_| for (s.emitters.slice()) |*emitter| {
        emitter.run();
        emitter.particles.appendBounded(.init(s.rng.random(), emitter.origin)) catch {};
    };
}

pub fn draw(s: *const State, f: *sk.Frame) void {
    f.clear(sk.Color.white);
    for (s.emitters.constSlice()) |*emitter| {
        // Processing shows each particle as it updates them, newest first.
        // The one just added is not shown until next frame.
        const shown = emitter.particles.constSlice();
        var i = shown.len -| 1;
        while (i > 0) {
            i -= 1;
            const a = shown[i].lifespan / 255;
            const pen: sk.draw.Pen = .{ .fill = sk.Color.gray(127).alphaFloat(a), .stroke = sk.Color.black.alphaFloat(a), .width = 2 };
            sk.draw.circle(f, shown[i].position, 4, pen);
        }
    }
}