summaryrefslogtreecommitdiff
path: root/examples/noc/src/fluid_resistance.zig
diff options
context:
space:
mode:
Diffstat (limited to 'examples/noc/src/fluid_resistance.zig')
-rw-r--r--examples/noc/src/fluid_resistance.zig83
1 files changed, 83 insertions, 0 deletions
diff --git a/examples/noc/src/fluid_resistance.zig b/examples/noc/src/fluid_resistance.zig
new file mode 100644
index 0000000..8b479fd
--- /dev/null
+++ b/examples/noc/src/fluid_resistance.zig
@@ -0,0 +1,83 @@
+//! Example 2.5: Fluid Resistance. Nine movers fall under gravity and drag
+//! in the lower half; a click starts them over with new masses.
+const std = @import("std");
+const sk = @import("sketch");
+const vec = sk.math;
+
+pub const name = "fluid_resistance";
+pub const width = 640;
+pub const height = 360;
+
+const Liquid = struct {
+ area: sk.Rect,
+ c: f32,
+
+ /// Processing's test is strict on all four sides; `Rect.contains`
+ /// includes the top and left edge, which no mover lands on exactly.
+ fn contains(l: Liquid, m: Mover) bool {
+ return l.area.contains(m.position[0], m.position[1]);
+ }
+ fn calculateDrag(l: Liquid, m: Mover) vec.Vec {
+ const speed = vec.length(m.velocity);
+ return vec.withLength(-m.velocity, l.c * speed * speed);
+ }
+};
+const liquid: Liquid = .{ .area = .{ .x = 0, .y = height / 2, .w = width, .h = height / 2 }, .c = 0.1 };
+
+const Mover = struct {
+ mass: f32 = 1,
+ radius: f32 = 8,
+ position: vec.Vec = .{ 0, 0 },
+ velocity: vec.Vec = .{ 0, 0 },
+ acceleration: vec.Vec = .{ 0, 0 },
+
+ fn applyForce(m: *Mover, force: vec.Vec) void {
+ m.acceleration += vec.scale(force, 1 / m.mass);
+ }
+ fn update(m: *Mover) void {
+ m.velocity += m.acceleration;
+ m.position += m.velocity;
+ m.acceleration = .{ 0, 0 };
+ }
+ fn checkEdges(m: *Mover) void {
+ if (m.position[1] > height - m.radius) {
+ m.velocity[1] *= -0.9;
+ m.position[1] = height - m.radius;
+ }
+ }
+};
+
+pub const State = struct {
+ movers: [9]Mover = @splat(.{}),
+ rng: std.Random.Xoshiro256 = .init(25),
+ clock: sk.Clock = .{},
+};
+
+pub fn init(s: *State) void {
+ reset(s);
+}
+
+fn reset(s: *State) void {
+ for (&s.movers, 0..) |*m, i| {
+ const mass = std.math.lerp(0.5, 3, s.rng.random().float(f32));
+ m.* = .{ .mass = mass, .radius = mass * 8, .position = .{ 40 + @as(f32, @floatFromInt(i)) * 70, 0 } };
+ }
+}
+
+pub fn update(s: *State, in: *const sk.Input) void {
+ for (in.events) |e| if (e.kind == .mouse_down) reset(s);
+ for (0..s.clock.steps(in)) |_| for (&s.movers) |*m| {
+ if (liquid.contains(m.*)) m.applyForce(liquid.calculateDrag(m.*));
+ m.applyForce(.{ 0, 0.1 * m.mass });
+ m.update();
+ m.checkEdges();
+ };
+}
+
+const mover_pen: sk.draw.Pen = .{ .fill = sk.Color.gray(127).alpha(127), .stroke = .black, .width = 2 };
+
+pub fn draw(s: *const State, f: *sk.Frame) void {
+ f.clear(sk.Color.white);
+ f.fill(liquid.area, sk.Color.gray(220));
+ for (s.movers) |m| sk.draw.circle(f, m.position, m.radius, mover_pen);
+}