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
|
//! Example 4.8: Image Texture System (smoke). Particles rise from an
//! emitter, each a soft image centred on it (Processing's
//! `imageMode(CENTER)`, here `f.imageAt`) and fading with its lifespan
//! (`tint(255, lifespan)`). The pointer's x sets a wind, drawn as an arrow.
const std = @import("std");
const sk = @import("sketch");
const vec = sk.math;
pub const name = "smoke";
pub const width = 640;
pub const height = 360;
/// A particle lives 51 steps (100 down by 2 until below 0), and one is
/// added a step.
const max_particles = 56;
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(48),
particles: sk.List(Particle, max_particles) = .{},
/// From the pointer's x: -0.2 at the left edge, 0.2 at the right.
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;
if (p.lifespan < 0) _ = s.particles.orderedRemove(i);
}
s.particles.appendBounded(.init(s.rng.random())) catch {};
}
}
pub fn draw(s: *const State, f: *sk.Frame) void {
f.clear(.black);
const texture = f.host.loadImage("assets/texture.png");
for (s.particles.constSlice()) |p| {
// Processing shows a particle as it updates it: not yet the new one.
if (p.lifespan == 100) continue;
f.imageAt(texture, .translate(p.position[0], p.position[1]), .{ .tint = sk.Color.white.alphaFloat(p.lifespan / 255) });
}
windArrow(f, s.wind);
}
/// The wind as an arrow from the top middle, 500 times its length.
pub fn windArrow(f: *sk.Frame, wind: f32) void {
const pen: sk.draw.Pen = .{ .stroke = .white, .xf = .place(.{ width / 2, 50 }, if (wind < 0) std.math.pi else 0) };
const len = @abs(wind) * 500;
sk.draw.line(f, .{ 0, 0 }, .{ len, 0 }, pen);
sk.draw.line(f, .{ len, 0 }, .{ len - 4, 2 }, pen);
sk.draw.line(f, .{ len, 0 }, .{ len - 4, -2 }, pen);
}
|