summaryrefslogtreecommitdiff
path: root/examples/noc/src/additive_blending.zig
blob: a40a8836212e57601eb2b21ac2e3fdc52a850a6b (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
//! Example 4.9: Additive Blending. The smoke of 4.8 tinted magenta, three
//! particles a step, and drawn with `f.blend(.add)` (`blendMode(ADD)`),
//! so where they pile up they glow towards white. The pointer's x sets
//! the wind.
const std = @import("std");
const sk = @import("sketch");
const vec = sk.math;
const windArrow = @import("smoke.zig").windArrow;

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

/// A particle lives 41 steps (100 down by 2.5 until below 0), and three
/// are added a step.
const max_particles = 128;
const origin: vec.Vec = .{ width / 2, height - 75 };

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

    fn init(rng: std.Random) Particle {
        return .{ .position = origin, .velocity = .{ rng.floatNorm(f32) * 0.3, rng.floatNorm(f32) * 0.3 - 1 } };
    }
};

pub const State = struct {
    rng: std.Random.Xoshiro256 = .init(49),
    particles: sk.List(Particle, max_particles) = .{},
    wind: f32 = 0,
    clock: sk.Clock = .{},
};

pub fn update(s: *State, in: *const sk.Input) void {
    for (0..s.clock.steps(in)) |_| {
        s.wind = std.math.lerp(-0.2, 0.2, in.mouse_x / width);
        var i = s.particles.count();
        while (i > 0) {
            i -= 1;
            const p = &s.particles.slice()[i];
            p.velocity += vec.Vec{ s.wind, 0 };
            p.position += p.velocity;
            p.lifespan -= 2.5;
            if (p.lifespan < 0) _ = s.particles.orderedRemove(i);
        }
        for (0..3) |_| s.particles.appendBounded(.init(s.rng.random())) catch {};
    }
}

const magenta = sk.Color.hex(0xff64ff);

pub fn draw(s: *const State, f: *sk.Frame) void {
    f.clear(.black);
    f.blend(.add);
    const texture = f.host.loadImage("assets/texture.png");
    for (s.particles.constSlice()) |p| {
        if (p.lifespan == 100) continue; // added this step: not shown yet
        f.imageAt(texture, .translate(p.position[0], p.position[1]), .{ .tint = magenta.alphaFloat(p.lifespan / 255) });
    }
    windArrow(f, s.wind);
}