Stabilizing a Dual-Sun System: Solving the Three-Body Problem in Three.js

How I implemented gravitational physics in Three.js to build a simulation of a sentient ocean inspired by Stanisław Lem's Solaris.

Originally published on Medium, November 2024

In Stanisław Lem's Solaris, the ocean-covered planet circles two suns — a massive red giant and a smaller, faster blue dwarf. By all rights, this system should be gravitationally chaotic, the planet's orbit eventually degrading into collision or ejection. But Lem imagined something extraordinary: the ocean itself actively stabilizes the system, constantly adjusting the planet's mass distribution to counteract the competing gravitational pulls.

When I set out to create a simulation of Solaris in Three.js, this gravitational dance became more than narrative flavor — it was a technical challenge I needed to solve. How do you visualize an alien intelligence performing real-time orbital engineering? To understand what I was simulating, I first needed to understand why the problem was so hard in the first place.

→ Experience the live simulation (Zoom out to see both suns. Watch the shimmer. Look at the Ocean's surface.)

The Three-Body Problem: From Newton to Poincaré to Chaos

In 1687, Isaac Newton formulated his law of universal gravitation. Equipped with this discovery, humans were able to predict the exact position of two celestial bodies orbiting each other. The Universe seemed complete. Then Newton tried to add a third body. The math disintegrated. With three gravitating objects there was no general solution. Newton himself was frustrated by this limitation, particularly when trying to understand the Moon's orbit perturbed by the Sun's influence, writing in 1684 that "to define these motions by exact laws admitting of easy calculation exceeds, if I am not mistaken, the force of any human mind."

For the next two centuries, the three-body problem consumed the world's greatest mathematical minds. Leonhard Euler found specific configurations where three bodies could maintain stable orbits — special cases, not the general solution everyone sought. Joseph-Louis Lagrange discovered five points where a small object could orbit stably in a two-body system, the gravitational sweet spots we now use for space telescopes. Mathematicians developed perturbation theory, treating the third body as a small disturbance and calculating approximate orbits that worked beautifully for practical astronomy. They were making progress, finding workarounds, getting close enough for navigation and prediction.

No one had found the general solution, but surely it existed somewhere, waiting to be discovered.

Then in the 1880s, Henri Poincaré shattered that hope.

Working on the three-body problem for a mathematical competition, Poincaré discovered something disturbing: infinitesimally small changes in starting positions produced wildly different outcomes. The trajectories didn't follow predictable patterns — they tangled into what he called "homoclinic tangles," so complex they could never be captured by simple equations.

The three-body problem had no general solution not because mathematicians weren't clever enough, but because the system itself was fundamentally unpredictable. Poincaré had discovered what we now call chaos: deterministic systems that are nonetheless impossible to predict. The clockwork universe was dead.

Lem's Solution: A Living Stabiliser

Lem understood the three-body problem. In Solaris, scientists observe that "the planet's orbit was in no way subject to the expected variations: it was stable, as stable as the orbit of a planet in our own solar system." This shouldn't be possible. The living Ocean "seems to have a unique function: it supports an optimal orbit of the planet around the Sun."

The Ocean doesn't solve the equations — it rewrites them continuously. By shifting its vast colloidal mass, creating asymmetries and density variations across its planetary surface, it generates the precise gravitational perturbations needed to maintain stability. Where Poincaré found chaos in fixed trajectories, Lem imagined an entity performing real-time orbital engineering.

This is active stabilization on a cosmic scale. The Ocean treats the three-body problem not as a mathematical puzzle requiring an elegant solution, but as a control problem demanding constant intervention. It's the difference between finding the perfect static balance and never stopping the corrections — like a tightrope walker shifting their weight pole moment by moment.

The scientists catalog the Ocean's "giant, meaningless in appearance, constructions," never quite grasping that these elaborate structures might be the Ocean's gravitational calculations made visible. The alien intelligence doesn't communicate. It simply refuses to fall.

For my Three.js simulation, this gave me both a conceptual framework and a visual challenge: show the Ocean actively working against gravitational chaos, with surface patterns that reveal its engineering in action.

Translating Theory to WebGL

In my Three.js simulation, I needed to visualize something that Lem left mysterious: how does the Ocean stabilize its orbit? The answer lay in treating the problem not as mathematics, but as real-time control theory.

The Dual-Sun System

I created two suns with fundamentally unstable orbits. The red giant moves slowly (0.08 rad/s) along a 250-unit radius orbit, while the blue dwarf races faster (0.12 rad/s) at 220 units. Their gravitational interference creates chaotic perturbations — exactly the kind of orbital decay Poincaré proved was inevitable.

I implemented this by calculating the gravitational chaos directly:

const sunInterference = Math.sin(redSunAngle - blueSunAngle) *
    Math.cos(time * 0.3);
const resonanceEffect = Math.sin(time * 0.17) *
    Math.cos(time * 0.23);

These competing frequencies would normally cause 8% orbital deviations — catastrophic for any planet. But then the Ocean intervenes.

The Ocean's Active Stabilization

Rather than letting chaos run wild, I implemented what the Ocean does: continuous, real-time correction. The Ocean "senses" the gravitational chaos and counteracts 95% of it, leaving only 5% visible as surface shimmer — proof of work being done.

const oceanCorrectionFactor = 0.95;
const stabilizedChaosX = chaosX * (1.0 - oceanCorrectionFactor);

This isn't a cheat — it's the point. The Ocean is actively computing gravitational corrections and implementing them through mass redistribution.

Visualizing the Engineering

The real challenge was making this invisible work visible. In the fragment shader, I created "engineering zones" that appear where the Ocean is working hardest. When both suns align, you see pulsing patterns on the Ocean's surface — FBM-based noise that simulates the Ocean's calculations made manifest:

float redEngineering = calculateEngineeringZone(uRedSunPos, uRedSunColor, 0);
float blueEngineering = calculateEngineeringZone(uBlueSunPos, uBlueSunColor, 1);

These patterns intensify when gravitational chaos peaks. The Ocean doesn't just stabilize — it shows you it's working, through glowing neural-like activity across its surface. Wave interference patterns, pulsing zones aligned with each sun, organic flow textures — all suggesting an alien intelligence performing planetary-scale engineering in real time.

The Feedback Loop

The engineering zones don't exist in isolation — they're part of a continuous feedback loop where physics drives visuals, creating a system that feels alive.

When gravitational chaos peaks (both suns aligned or opposed), the totalChaos value spikes. This triggers two visual responses simultaneously:

First, the suns themselves react. Their glow intensity pulses in response to the gravitational stress they're experiencing:

const chaosPulse = 1.0 + (totalChaos * 0.15);
sun.glowMesh.material.opacity = 0.25 * pulse * chaosPulse;
sun.light.intensity = baseLightIntensity * chaosPulse;

When chaos is high, the suns shine brighter — not because they're physically brighter, but because they're under more gravitational strain. It's visual stress made literal.

Second, the Ocean's engineering zones intensify. The same totalChaos value that brightens the suns also drives the shader's engineering calculations. Higher chaos means more pulsing, more wave interference, more visible work across the Ocean's surface.

The result is a system that breathes: during moments of alignment, you see the suns shimmer and glow while the Ocean's surface erupts with coordinated pulsing patterns. During stable moments, everything calms — the suns dim slightly, the engineering zones fade to a subtle shimmer.

Results

In practice, the system creates natural rhythms that emerge from the orbital mechanics. When both suns align (roughly every 30 seconds in my timing), chaos peaks — the suns shimmer visibly, their coronas pulse brighter, and the Ocean's surface lights up with intense engineering activity. When the suns are perpendicular, the system relaxes: the shimmer fades, the engineering zones dim to a gentle glow, and everything breathes easier.

The most striking visual effect happens where engineering zones overlap. When both suns are above the horizon, you see distinct red and blue pulsing patterns on opposite sides of the Ocean. But where their zones meet, they blend into purple — the Ocean simultaneously stabilizing against both gravitational pulls, its work visible in the interference pattern.

Viewers typically notice the shimmer first: Why are the suns wobbling slightly? Then they spot the pulsing patterns on the Ocean surface. The connection between the two is never explicitly stated, but it's intuitive: something down there is responding to something up there. That implicit understanding — that sense of invisible work made partially visible — creates exactly the kind of alien mystery Lem was describing.

Conclusion

The result is a simulation that captures what makes Lem's Ocean so unsettling: it doesn't communicate through language or symbols. It communicates through work — through the constant, tireless effort of keeping its world stable. Every glowing pattern on the surface, every pulsing engineering zone, every shimmer of residual chaos is the Ocean saying something we can observe but never fully understand: I am here. I am thinking. I refuse to fall.

Newton couldn't solve the three-body problem. Poincaré proved it was unsolvable. But Lem imagined something that didn't need to solve it — something that simply never stops correcting. In building this simulation, I found myself less interested in the equations and more fascinated by what it means to visualize alien thought made manifest in physics.