oapi.set_pause(true)
-- get the object handles for the Sun and for Earth
sun = oapi.get_objhandle('Sun')
mars = oapi.get_objhandle('Mars')
-- find the state vectors for the Sun
q_sun = oapi.get_globalpos(sun)
p_sun = oapi.get_globalvel(sun)
-- find the state vectors for Mars
q_mar = oapi.get_globalpos(mars)
p_mar = oapi.get_globalvel(mars)
-- get two points on Mars' equatorial plane - separated by about 90 degrees
pos1 = {lng = 0.0000, lat = 0.0000, rad = 3000000.0}
pos2 = {lng = 1.5708, lat = 0.0000, rad = 3000000.0}
marspos1 = oapi.equ_to_global(mars, pos1)
marspos2 = oapi.equ_to_global(mars, pos2)
-- calculate the unit vectors normal to the orbital and equatorial planes
vec1 = vec.sub( q_sun, q_mar )
vec2 = vec.sub( p_sun, p_mar )
vec1 = vec.div( vec1, vec.length( vec1 ) )
vec2 = vec.div( vec2, vec.length( vec2 ) )
normal1 = vec.crossp( vec2, vec1 )
vec1 = vec.sub( marspos1, q_mar)
vec2 = vec.sub( marspos2, q_mar)
vec1 = vec.div( vec1, vec.length( vec1 ) )
vec2 = vec.div( vec2, vec.length( vec2 ) )
normal2 = vec.crossp( vec2, vec1 )
-- calculate the unit vector that points towards the vernal equinox
vernal = vec.crossp( normal1, normal2)
vernal = vec.div( vernal, vec.length( vernal ) )
-- set up a co-ordinate system in Mars' orbital plane with the x-axis pointing to the
-- vernal equinox
x_hat = vernal
z_hat = normal1
y_hat = vec.crossp( x_hat, z_hat)
-- calculate the earth-centric position of the Sun in the co-ordinate system
sunpos = vec.sub( q_sun, q_mar )
x_coord = vec.dotp( sunpos, x_hat )
y_coord = vec.dotp( sunpos, y_hat )
z_coord = vec.dotp( sunpos, z_hat )
-- calculate the solar longitude in degrees
longitude = 180 * math.atan2( y_coord, x_coord ) / 3.141592654
if longitude < 0 then longitude = longitude + 360 end
oapi.set_pause(false)