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