// Every tweakable value in the playground lives here: the defaults, the slider // ranges shown in the settings panel, and saving/restoring between visits. const STORAGE_KEY = "polygon-playground:settings:v1"; const prefersReducedMotion = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches; /** Starting values. Change these to change what a first-time visitor sees. */ export const DEFAULTS = Object.freeze({ // Shapes shape: "cubes", // "cubes" | "spheres" | "mix" count: 100, size: 0.035, // edge length as a fraction of the container (the cube is 1 unit wide) variety: 0, // 0 = all the same size, 1 = sizes vary by ±60% // Physics gravityMode: "camera", // "camera" (down = bottom of the screen) | "world" | "zero" gravity: 10, // m/s² bounce: 0.9, // restitution friction: 0.1, // View autoSpin: !prefersReducedMotion, spinSpeed: 10, // OrbitControls units: 1 ≈ one orbit per minute theme: "auto", // "auto" | "ink" | "night" | "prism" }); /** Numeric settings and the range each slider allows. */ export const RANGES = Object.freeze({ count: { min: 10, max: 300, step: 10 }, size: { min: 0.015, max: 0.08, step: 0.005 }, variety: { min: 0, max: 1, step: 0.05 }, gravity: { min: 0.5, max: 30, step: 0.5 }, bounce: { min: 0, max: 1, step: 0.05 }, friction: { min: 0, max: 1, step: 0.05 }, spinSpeed: { min: 1, max: 30, step: 1 }, }); /** Settings that pick from a fixed list. */ export const OPTIONS = Object.freeze({ shape: ["cubes", "spheres", "mix"], gravityMode: ["camera", "world", "zero"], theme: ["auto", "ink", "night", "prism"], }); /** Changing one of these rebuilds the shapes from scratch. */ export const REBUILD_KEYS = Object.freeze(["shape", "count", "size", "variety"]); const clamp = (value, min, max) => Math.min(max, Math.max(min, value)); /** Coerce an untrusted value (e.g. from localStorage) into a valid setting, or undefined. */ function sanitize(key, value) { if (key in RANGES) { if (typeof value !== "number" || !Number.isFinite(value)) return undefined; return clamp(value, RANGES[key].min, RANGES[key].max); } if (key in OPTIONS) return OPTIONS[key].includes(value) ? value : undefined; if (typeof DEFAULTS[key] === "boolean") return typeof value === "boolean" ? value : undefined; return undefined; } export function loadSettings() { const settings = { ...DEFAULTS }; try { const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "{}"); for (const key of Object.keys(DEFAULTS)) { const value = sanitize(key, saved?.[key]); if (value !== undefined) settings[key] = value; } } catch { // Storage can be unavailable (private mode, file://, blocked cookies). Defaults are fine. } return settings; } export function saveSettings(settings) { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(settings)); } catch { // Not being able to persist is harmless. } }