# Installing and loading necessary packages
install.packages("plotly")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.3'
## (as 'lib' is unspecified)
install.packages("ggplot2")
## Installing package into '/cloud/lib/x86_64-pc-linux-gnu-library/4.3'
## (as 'lib' is unspecified)
library(plotly, ggplot2)
## Loading required package: ggplot2
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
# Earth sphere generation
theta <- seq(0, 2*pi, length.out = 100)
phi <- seq(-pi/2, pi/2, length.out = 50) # Restricting phi to half a sphere for a sphere
r <- 1 # Radius of the sphere
x_sphere <- outer(cos(theta), cos(phi)) * r
y_sphere <- outer(sin(theta), cos(phi)) * r
z_sphere <- outer(rep(1, length(theta)), sin(phi)) * r

# Plot Earth as a sphere
my_plot <- plot_ly() %>%
  add_surface(x = ~x_sphere, y = ~y_sphere, z = ~z_sphere,
              colorscale = list(c(0, "#0000FF"), c(1, "#006600")),
              showscale = FALSE)

# Larger elliptical Moon orbit 
moon_radius = 1.27250 # Adjust this for Earth-Moon distance scaling
theta <- seq(0, 2*pi, length.out = 29) # Dividing the orbit into 29 points for 29 moons
a = moon_radius * 2  # Major axis
b = moon_radius * 1.8 # Minor axis
moon_x <- a * cos(theta) 
moon_y <- b * sin(theta)
moon_z <- rep(0, length(theta)) # Same plane as Earth's equator

# Calculate moon phase (assumed to be circular for simplicity)
moon_phase <- seq(0, 1, length.out = 29) # 0 for new moon, 0.5 for full moon

# Calculate scaling factor for moon size based on distance from Earth
moon_distances <- sqrt(moon_x^2 + moon_y^2 + moon_z^2)
max_distance <- max(moon_distances)
size_scaling_factor <- 100 # Adjust this factor to control the size of moons relative to their distance
moon_sizes <- 1 + (size_scaling_factor * (max_distance - moon_distances))

# Moon appearance with shaded colours representing moon phase and scaled sizes
my_plot <- my_plot %>%
  add_trace(x = moon_x,
            y = moon_y,
            z = moon_z,
            type = "scatter3d",
            mode = "markers",  # Represent as a single point
            marker = list(size = moon_sizes,
                          color = moon_phase,
                          colorscale = list(c(0, '#000000'), c(0.5, '#999999'), c(1, '#FFFFFF')),
                          cmin = 0, cmax = 1)) 

# Layout and display
my_plot <- my_plot %>%
  layout(title = 'Earth with 29 Moon positions with Phases')

my_plot