"""Generate synthetic videos of several small bouncing balls.""" import argparse import json import math from pathlib import Path import cv2 import imageio.v2 as imageio import numpy as np WIDTH = 196 HEIGHT = 196 FRAMES = 24 FPS = 12 MIN_BALLS = 3 MAX_BALLS = 5 MIN_RADIUS = 7 MAX_RADIUS = 12 MIN_SPEED = 4.0 MAX_SPEED = 8.0 def color_name(h, s, v): degrees = h * 2 if s < 45 and v > 220: return "white" if degrees < 15 or degrees >= 345: return "red" if degrees < 40: return "orange" if degrees < 70: return "yellow" if degrees < 165: return "green" if degrees < 200: return "cyan" if degrees < 250: return "blue" if degrees < 290: return "purple" if degrees < 345: return "pink" return "red" def keep_inside(ball): radius = ball["radius"] ball["x"] = min(max(ball["x"], radius), WIDTH - radius) ball["y"] = min(max(ball["y"], radius), HEIGHT - radius) def bounce_off_walls(ball): radius = ball["radius"] if ball["x"] < radius: ball["x"] = radius + (radius - ball["x"]) ball["vx"] = abs(ball["vx"]) elif ball["x"] > WIDTH - radius: ball["x"] = (WIDTH - radius) - (ball["x"] - (WIDTH - radius)) ball["vx"] = -abs(ball["vx"]) if ball["y"] < radius: ball["y"] = radius + (radius - ball["y"]) ball["vy"] = abs(ball["vy"]) elif ball["y"] > HEIGHT - radius: ball["y"] = (HEIGHT - radius) - (ball["y"] - (HEIGHT - radius)) ball["vy"] = -abs(ball["vy"]) def resolve_ball_collisions(balls): """Resolve pairwise elastic collisions and separate overlapping balls.""" for i, ball_a in enumerate(balls): for ball_b in balls[i + 1:]: dx = ball_b["x"] - ball_a["x"] dy = ball_b["y"] - ball_a["y"] min_distance = ball_a["radius"] + ball_b["radius"] distance_sq = dx * dx + dy * dy if distance_sq >= min_distance * min_distance: continue if distance_sq < 1e-12: nx, ny, distance = 1.0, 0.0, 0.0 else: distance = math.sqrt(distance_sq) nx, ny = dx / distance, dy / distance overlap = min_distance - distance total_mass = ball_a["mass"] + ball_b["mass"] ball_a["x"] -= nx * overlap * ball_b["mass"] / total_mass ball_a["y"] -= ny * overlap * ball_b["mass"] / total_mass ball_b["x"] += nx * overlap * ball_a["mass"] / total_mass ball_b["y"] += ny * overlap * ball_a["mass"] / total_mass relative_vx = ball_b["vx"] - ball_a["vx"] relative_vy = ball_b["vy"] - ball_a["vy"] velocity_along_normal = relative_vx * nx + relative_vy * ny if velocity_along_normal < 0: inverse_mass_a = 1.0 / ball_a["mass"] inverse_mass_b = 1.0 / ball_b["mass"] impulse = ( -2.0 * velocity_along_normal / (inverse_mass_a + inverse_mass_b) ) ball_a["vx"] -= impulse * nx * inverse_mass_a ball_a["vy"] -= impulse * ny * inverse_mass_a ball_b["vx"] += impulse * nx * inverse_mass_b ball_b["vy"] += impulse * ny * inverse_mass_b def create_balls(rng): num_balls = int(rng.integers(MIN_BALLS, MAX_BALLS + 1)) base_hue = int(rng.integers(0, 180)) balls = [] for index in range(num_balls): radius = int(rng.integers(MIN_RADIUS, MAX_RADIUS + 1)) for _ in range(1000): x = float(rng.uniform(radius, WIDTH - radius)) y = float(rng.uniform(radius, HEIGHT - radius)) if all( (x - other["x"]) ** 2 + (y - other["y"]) ** 2 >= (radius + other["radius"] + 2) ** 2 for other in balls ): break else: raise RuntimeError("Could not place balls without overlap") speed = float(rng.uniform(MIN_SPEED, MAX_SPEED)) angle = float(rng.uniform(0, 2 * math.pi)) hue = int(round( base_hue + index * 180.0 / num_balls + rng.integers(-8, 9) )) % 180 saturation = int(rng.integers(175, 256)) value = int(rng.integers(210, 256)) rgb = cv2.cvtColor( np.uint8([[[hue, saturation, value]]]), cv2.COLOR_HSV2RGB )[0, 0] balls.append({ "x": x, "y": y, "vx": speed * math.cos(angle), "vy": speed * math.sin(angle), "radius": radius, "mass": float(radius * radius), "color": color_name(hue, saturation, value), "color_rgb": [int(c) for c in rgb], }) return balls def make_video(path, rng): balls = create_balls(rng) background_rgb = [int(c) for c in rng.integers(8, 33, size=3)] ball_metadata = [ { "color": ball["color"], "color_rgb": ball["color_rgb"], "radius": ball["radius"], "initial_position": [round(ball["x"], 2), round(ball["y"], 2)], "initial_velocity": [ round(ball["vx"], 3), round(ball["vy"], 3), ], } for ball in balls ] with imageio.get_writer( path, fps=FPS, codec="libx264", pixelformat="yuv420p", macro_block_size=1, output_params=["-preset", "ultrafast", "-crf", "28"], ) as writer: for _ in range(FRAMES): frame = np.empty((HEIGHT, WIDTH, 3), dtype=np.uint8) frame[:, :] = background_rgb for ball in balls: cv2.circle( frame, (int(round(ball["x"])), int(round(ball["y"]))), ball["radius"], ball["color_rgb"], thickness=-1, lineType=cv2.LINE_AA, ) writer.append_data(frame) for ball in balls: ball["x"] += ball["vx"] ball["y"] += ball["vy"] bounce_off_walls(ball) resolve_ball_collisions(balls) for ball in balls: keep_inside(ball) return { "num_balls": len(balls), "colors": [ball["color"] for ball in balls], "background_rgb": background_rgb, "balls": ball_metadata, "num_frames": FRAMES, "fps": FPS, "width": WIDTH, "height": HEIGHT, } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--count", type=int, default=3000) parser.add_argument("--seed", type=int, default=42) parser.add_argument("--output", type=Path, default=Path("bouncing-balls")) args = parser.parse_args() videos_dir = args.output / "videos" videos_dir.mkdir(parents=True, exist_ok=True) records = [] for i in range(args.count): filename = f"videos/{i:06d}.mp4" rng = np.random.default_rng(args.seed + i) info = make_video(args.output / filename, rng) records.append({"file_name": filename, **info}) if (i + 1) % 250 == 0 or i + 1 == args.count: print(f"Generated {i + 1}/{args.count} videos", flush=True) with (args.output / "metadata.jsonl").open("w") as f: for record in records: f.write(json.dumps(record) + "\n") print(f"Done: {args.count} videos in {args.output}", flush=True) if __name__ == "__main__": main()