main.js entry 1.9 KB
Copy main.js
SimKit.define({
title: "Damped pendulum (RK4)",
dt: 1 / 480, speed: 1, height: 340,
params: {
L: { label: "Length", unit: "m", min: 0.2, max: 3, value: 1.2, step: 0.05 },
g: { label: "Gravity", unit: "m/s²", min: 1, max: 25, value: 9.81, step: 0.01 },
damp: { label: "Damping", unit: "1/s", min: 0, max: 1.5, value: 0.08, step: 0.01 },
th0: { label: "Start angle", unit: "°", min: 5, max: 170, value: 70, step: 1 }
},
init(P, S) { S.y = [P.th0 * Math.PI / 180, 0]; S.drag = false; },
pointer(e, P, S) { // drag the bob with a mouse or a finger
if (e.type === "down") S.drag = true;
if (S.drag && e.type !== "up") S.y = [Math.atan2(e.x - e.W / 2, e.y - e.H * 0.12), 0];
if (e.type === "up") S.drag = false;
},
step(dt, P, S, t) {
if (S.drag) return;
S.y = SimKit.rk4((tt, y) => [y[1], -(P.g / P.L) * Math.sin(y[0]) - P.damp * y[1]], t, S.y, dt);
},
draw(g, W, H, P, S) {
const px = W / 2, py = H * 0.12, len = Math.min(H * 0.72, W * 0.4), th = S.y[0];
const bx = px + len * Math.sin(th), by = py + len * Math.cos(th);
g.strokeStyle = "#ccc"; g.lineWidth = 1; g.beginPath(); g.arc(px, py, len, 0.1, Math.PI - 0.1); g.stroke();
g.strokeStyle = "#333"; g.lineWidth = 3; g.beginPath(); g.moveTo(px, py); g.lineTo(bx, by); g.stroke();
g.fillStyle = "#c03030"; g.beginPath(); g.arc(bx, by, 16, 0, 2 * Math.PI); g.fill();
g.fillStyle = "#333"; g.fillRect(px - 30, py - 6, 60, 6);
SimKit.sch.label(g, "angle " + (th * 180 / Math.PI).toFixed(1) + "° period (small angles) T ≈ " + (2 * Math.PI * Math.sqrt(P.L / P.g)).toFixed(2) + " s", W / 2, H - 12, "#444");
},
scope: {
span: 12, unit: "",
traces: [
{ label: "Angle (°)", color: "#5aa0ff", get: S => S.y[0] * 180 / Math.PI },
{ label: "Energy ×10", color: "#7be07b", get: (S, P) => 10 * (0.5 * P.L * P.L * S.y[1] ** 2 + P.g * P.L * (1 - Math.cos(S.y[0]))) }
]
}
});