#include <iostream>
#include <cmath>
#include <windows.h>
#include <conio.h>
#define Rearth 6378.14
#define GMearth 398600.4415
#define Pi 3.141597
using namespace std;
int main (){
int runprogram = 1;
double perigee, apogee, rapogee, rperigee;
double time = 0;
double timerate = 1;
char key;
cout << "Enter desired apogee altitude in KM: " << endl;
cin >> apogee;
cout << "Enter desired perigee altitude in KM: " << endl;
cin >> perigee;
rapogee = apogee + Rearth; //Radius of Earth + apogee
rperigee = perigee + Rearth; //Radius of Earth + perigee
double semimajor = (rapogee + rperigee) / 2; //Semi-major axis
double eccentricity = (rapogee - rperigee) / (rapogee + rperigee); //Eccentricity of orbit
double meanmotion = sqrt((GMearth / (semimajor*semimajor*semimajor))); //Mean motion (vector used to calculate how much of an orbit has been completed during a time interval)
while (runprogram == 1){ //Loops the program
if (_kbhit())
{key = _getch();
if (key == 114)
timerate = timerate - 1;
else if (key == 116)
timerate = timerate + 1; //Time acceleration controls
if (timerate < 1)
timerate = 1;} //Time acceleration can't fall below 1
time = time + timerate; //Progression of time as program loops
double meananomaly = meanmotion * time; //Mean anomaly (fraction of orbit completed)
double eccentricanomaly0 = meananomaly; //Iteration to work out Eccentric Anomaly angle
double Margin = 1.0E-8;
while (true)
{
double eccentricanomaly = eccentricanomaly0 - (eccentricanomaly0-eccentricity*sin(eccentricanomaly0)-meananomaly)/(1.0-eccentricity*cos(eccentricanomaly0));
if (abs(eccentricanomaly - eccentricanomaly0) < Margin)
{
eccentricanomaly0 = eccentricanomaly;
break;
}
eccentricanomaly0 = eccentricanomaly; //End of iteration
}
double trueanomaly = acos((cos(eccentricanomaly0) - eccentricity) / (1 - (eccentricity * cos(eccentricanomaly0)))); //True anomaly (angle between perigee and current point in orbit)
double radius = semimajor * (1 - (eccentricity * cos(eccentricanomaly0)));
double altitude = radius - 6378.14; //Altitude calculation
double flightpath = atan((eccentricity * sin(trueanomaly)) / (1 + (eccentricity * cos(trueanomaly))));
double velocity = (sqrt(GMearth * semimajor * (1 - (eccentricity*eccentricity)))) / (radius * cos(flightpath)); //Velocity calculation
int period = 2 * Pi * (sqrt((semimajor*semimajor*semimajor)/GMearth)); //Orbit period
double completeorbits = time / period; //Complete orbits
cout << "To slow time, press 'r'\n" << "To speed up time, press 't'\n\n" << endl;
cout << "Current vectors:\n" << endl;
cout << "Altitude: " << altitude << " KM" << endl;
cout << "Velocity: " << velocity << " KM/Sec\n" << endl;
cout << "Orbital period: " << period << " Sec" << endl;
cout << "Complete orbits: " << completeorbits << endl; //Outputs
system ("cls");}
return 0;
}