summaryrefslogtreecommitdiff
path: root/examples/noc/src/fluid_resistance.zig
blob: 8b479fd354c70e33b090e1c00239c326dd97a98c (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
80
81
82
83
//! Example 2.5: Fluid Resistance. Nine movers fall under gravity and drag
//! in the lower half; a click starts them over with new masses.
const std = @import("std");
const sk = @import("sketch");
const vec = sk.math;

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

const Liquid = struct {
    area: sk.Rect,
    c: f32,

    /// Processing's test is strict on all four sides; `Rect.contains`
    /// includes the top and left edge, which no mover lands on exactly.
    fn contains(l: Liquid, m: Mover) bool {
        return l.area.contains(m.position[0], m.position[1]);
    }
    fn calculateDrag(l: Liquid, m: Mover) vec.Vec {
        const speed = vec.length(m.velocity);
        return vec.withLength(-m.velocity, l.c * speed * speed);
    }
};
const liquid: Liquid = .{ .area = .{ .x = 0, .y = height / 2, .w = width, .h = height / 2 }, .c = 0.1 };

const Mover = struct {
    mass: f32 = 1,
    radius: f32 = 8,
    position: vec.Vec = .{ 0, 0 },
    velocity: vec.Vec = .{ 0, 0 },
    acceleration: vec.Vec = .{ 0, 0 },

    fn applyForce(m: *Mover, force: vec.Vec) void {
        m.acceleration += vec.scale(force, 1 / m.mass);
    }
    fn update(m: *Mover) void {
        m.velocity += m.acceleration;
        m.position += m.velocity;
        m.acceleration = .{ 0, 0 };
    }
    fn checkEdges(m: *Mover) void {
        if (m.position[1] > height - m.radius) {
            m.velocity[1] *= -0.9;
            m.position[1] = height - m.radius;
        }
    }
};

pub const State = struct {
    movers: [9]Mover = @splat(.{}),
    rng: std.Random.Xoshiro256 = .init(25),
    clock: sk.Clock = .{},
};

pub fn init(s: *State) void {
    reset(s);
}

fn reset(s: *State) void {
    for (&s.movers, 0..) |*m, i| {
        const mass = std.math.lerp(0.5, 3, s.rng.random().float(f32));
        m.* = .{ .mass = mass, .radius = mass * 8, .position = .{ 40 + @as(f32, @floatFromInt(i)) * 70, 0 } };
    }
}

pub fn update(s: *State, in: *const sk.Input) void {
    for (in.events) |e| if (e.kind == .mouse_down) reset(s);
    for (0..s.clock.steps(in)) |_| for (&s.movers) |*m| {
        if (liquid.contains(m.*)) m.applyForce(liquid.calculateDrag(m.*));
        m.applyForce(.{ 0, 0.1 * m.mass });
        m.update();
        m.checkEdges();
    };
}

const mover_pen: sk.draw.Pen = .{ .fill = sk.Color.gray(127).alpha(127), .stroke = .black, .width = 2 };

pub fn draw(s: *const State, f: *sk.Frame) void {
    f.clear(sk.Color.white);
    f.fill(liquid.area, sk.Color.gray(220));
    for (s.movers) |m| sk.draw.circle(f, m.position, m.radius, mover_pen);
}