Astronomy: The Math of Solar Cycles
How do we model the visual passage of a day? In the real world, the colors of the sky, the brightness of the landscape, and the trajectories of the sun and moon are governed by Earth’s axial rotation and atmospheric light scattering.
To recreate this cycle in a web browser, we must combine Polar Orbit geometry with Multi-Stop Color Vector Interpolation. In this column, we study these mathematical principles and build a Procedural Day & Night Observatory Suite in p5.js.
The Astronomy Glossary
- Solar Orbit: The elliptical trajectory of the sun across the sky dome, modeled in 2D using polar coordinate angles.
- Color Interpolation (Lerp): Linearly blending two RGB color vectors to calculate intermediate shades at a specific fraction: $0 \le f \le 1$.
- Ambient Shading: Scaling the color value of landscape layers based on the solar position to match the surrounding sky brightness.
1. Polar Orbit Coordinates
To simulate the sun and moon rising and setting, we model their positions on a circular trajectory centered at the middle of the sky. The angle of rotation $\theta$ is mapped directly to a 24-hour clock cycle:
\[\theta = \left(\frac{\text{Time}}{24}\right) \cdot 2\pi - \frac{\pi}{2}\]Subtracting $\frac{\pi}{2}$ ensures that the sun peaks at noon ($\text{Time} = 12\text{h}$) when $\theta = \frac{\pi}{2}$ (pointing straight up). The sun and moon are exactly $180^\circ$ ($\pi$ radians) out of phase:
- Sun: $x_{\text{sun}} = R_x \cdot \cos(\theta), \quad y_{\text{sun}} = R_y \cdot \sin(\theta)$
- Moon: $x_{\text{moon}} = R_x \cdot \cos(\theta + \pi), \quad y_{\text{moon}} = R_y \cdot \sin(\theta + \pi)$
2. Multi-Stop Gradient Interpolation
Sky gradients cannot be represented as a simple transition between two colors. Sunrise has orange and pink stops, noon is bright cyan, sunset is magenta, and midnight is deep indigo.
We solve this by defining a multi-stop color look-up table at 4 key stops (0h, 6h, 12h, 18h). For any current virtual time $T$, we identify the surrounding stops $T_1$ and $T_2$ and calculate the local interpolation fraction $f$:
\(f = \frac{T - T_1}{T_2 - T_1}\) \(\text{Color}_{\text{Result}} = (1 - f) \cdot \text{Color}_{1} + f \cdot \text{Color}_{2}\)
We evaluate this formula for both the top and bottom sky colors, drawing a seamless vertical gradient band across the canvas.
Procedural Day & Night Observatory
Select atmosphere themes, toggle play modes, and slide the 24h clock scroller to sweep through sunrise, midday, dusk, and midnight.
Explore the codebase and run standalone project builds via: shubhamkrshandilya/day-and-night