diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-16 21:28:20 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-16 21:28:20 -0300 |
| commit | 6933f99ddb2d7103515d26838496309a807bba26 (patch) | |
| tree | 991c2fe7d4a57957222876e190fa4d16a0fb889c /examples/noc/src/additive_blending.zig | |
| parent | 82fca5c9f29124f37f6dcd08e73e6999ce44a69d (diff) | |
| download | sketchbook-6933f99ddb2d7103515d26838496309a807bba26.tar.gz sketchbook-6933f99ddb2d7103515d26838496309a807bba26.zip | |
Move standalone sketches into sketchbook examples
Diffstat (limited to 'examples/noc/src/additive_blending.zig')
| -rw-r--r-- | examples/noc/src/additive_blending.zig | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/examples/noc/src/additive_blending.zig b/examples/noc/src/additive_blending.zig new file mode 100644 index 0000000..a40a883 --- /dev/null +++ b/examples/noc/src/additive_blending.zig @@ -0,0 +1,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); +} |
