This project started with a dual motivation. First, a deep curiosity for physical systems and the desire to build a pure, deterministic chaotic simulator from scratch. Second, a perfect opportunity to experiment with WebAssembly (WASM) compilation. The goal was to write raw, high-performance C++ code using SDL3 and deploy it directly into modern web browsers with near-native performance, leaving all graphics computation to the GPU via WebGL.
Visit the page of the repo to see what's the result !
- Pure C++ Physics Engine: Exact Lagrangian mechanics solved in real-time.
- The Butterfly Effect in Action: Simulates 3 independent pendulums simultaneously to witness chaotic divergence.
- Persistent Visual Trails: Renders thousands of past frames into a non-fading geometric fractal without dragging down the CPU.
- WASM & Native Ready: Compiles into standard desktop executables or cross-platform web bundles using Emscripten.
A double pendulum cannot be easily solved with standard Newtonian forces (
By applying the Euler-Lagrange equations, we obtain two highly non-linear, coupled second-order differential equations that calculate the angular accelerations (
To compute the next position, the engine relies on a Semi-Implicit Euler Integrator:
$\omega_{next} = \omega + \alpha \cdot dt$ $\theta_{next} = \theta + \omega_{next} \cdot dt$
While incredibly fast and perfect for real-time video games, this numerical approximation introduces tiny floating-point rounding errors at every single millisecond. In a closed loop, these errors act as an artificial, invisible friction. Over time, the system bleeds its initial kinetic energy, forcing the pendulums to slow down and eventually drop into a repetitive, stable orbit (a predictable "sink hole" loop).
To counteract this artificial numerical damping and keep the simulation chaotic forever, a tiny "kick" of energy is injected back into the angular velocities at the end of every physics step:
omega1 *= 1.0001;
omega2 *= 1.0001;You need
- g++ compatible for C++11
- SDL3
- Cmake
- emscripten
mkdir build_native && cd build_nativecmake ..
cmake --build ../pendulum_nativemkdir build_web && cd build_web
example for Mac Intel (adjust the path of your Emscripten.cmake ):
cmake .. -DCMAKE_TOOLCHAIN_FILE=/usr/local/Cellar/emscripten/4.0.17/libexec/cmake/Modules/Platform/Emscripten.cmakecmake --build .python3 -m http.server 8080