diff options
Diffstat (limited to 'examples/noc/src/system_of_systems.zig')
| -rw-r--r-- | examples/noc/src/system_of_systems.zig | 79 |
1 files changed, 79 insertions, 0 deletions
diff --git a/examples/noc/src/system_of_systems.zig b/examples/noc/src/system_of_systems.zig new file mode 100644 index 0000000..d02938c --- /dev/null +++ b/examples/noc/src/system_of_systems.zig @@ -0,0 +1,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); + } + } +} |
