Exemple #1
0
        private void DisplaySelected_Click(object sender, EventArgs e)
        {
            if (listView1.FocusedItem != null && listView1.FocusedItem.Index != -1)
            {
                if (CommonData.HasManeuvers)
                {
                    IAgStkObject passiveSatObj = CreatorFunctions.GetCreateSatellite("PassiveCheck");
                    IAgSatellite passiveSat    = passiveSatObj as IAgSatellite;
                    passiveSat.VO.OrbitSystems.InertialByWindow.IsVisible = false;
                    passiveSat.VO.OrbitSystems.RemoveAll();
                    passiveSat.VO.OrbitSystems.Add("Satellite/" + CommonData.TargetName + " VVLH System");
                    passiveSat.SetPropagatorType(AgEVePropagatorType.ePropagatorAstrogator);
                    IAgVADriverMCS passiveDriver = passiveSat.Propagator as IAgVADriverMCS;

                    IAgVAMCSInitialState          intState = passiveDriver.MainSequence[0] as IAgVAMCSInitialState;
                    IAgVAMCSPropagate             prop     = passiveDriver.MainSequence[1] as IAgVAMCSPropagate;
                    IAgVAStoppingConditionElement sc1      = prop.StoppingConditions[0];
                    IAgVAStoppingCondition        sc       = sc1.Properties as IAgVAStoppingCondition;
                    sc.Trip = CommonData.RunList[listView1.FocusedItem.Index].PropTime;

                    AgVAElementCartesian element = intState.Element as AgVAElementCartesian;
                    intState.OrbitEpoch = CommonData.RunList[listView1.FocusedItem.Index].ManeuverTime;
                    element.Vx          = CommonData.RunList[listView1.FocusedItem.Index].Vx;
                    element.Vy          = CommonData.RunList[listView1.FocusedItem.Index].Vy;
                    element.Vz          = CommonData.RunList[listView1.FocusedItem.Index].Vz;
                    element.X           = CommonData.RunList[listView1.FocusedItem.Index].X;
                    element.Y           = CommonData.RunList[listView1.FocusedItem.Index].Y;
                    element.Z           = CommonData.RunList[listView1.FocusedItem.Index].Z;

                    passiveDriver.RunMCS();
                }
                else
                {
                    MessageBox.Show("Actor satellite has no maneuvers. Visualization is simply the Actor's current trjectory");
                }
            }
        }
        private void Calculate_Click(object sender, EventArgs e)
        {
            int check = FieldCheck();

            if (check == 0)
            {
                compComplete = false;
                AllPlaneCrossingsList.Clear();
                IAgCrdnPlaneNormal orbitPlane;
                IAgStkObject       crossObj;
                IAgCrdnProvider    crossVgt;
                IAgStkObject       satRefObj = CreatorFunctions.GetCreateSatellite(PlaneSatellite.Text);
                IAgSatellite       satRef    = (IAgSatellite)satRefObj;
                IAgCrdnProvider    vgtPrv    = satRefObj.Vgt;

                //Create reference plane
                string planeName = PlaneSatellite.Text + "_OrbitPlane";
                orbitPlane = AWBFunctions.GetCreatePlaneNormal(vgtPrv, vgtPrv.Points["Center"], vgtPrv.Vectors["Velocity"], vgtPrv.Vectors["Orbit_Normal"], planeName, "Orbit plane referencing orbit normal");

                //Loop for each crossing object. Create angle, calc scalar, extrema time array, and conditionals if required
                string angleName;
                string extremaName;
                string conditionName;
                string cScalName;
                string condEventArrayName;
                foreach (var cObject in crossingObjects)
                {
                    //Initialize new plane crossing group
                    PlaneCrossingGroup crossingGroup = new PlaneCrossingGroup();
                    IAgScenario        scenario      = CommonData.StkRoot.CurrentScenario as IAgScenario;
                    crossingGroup.AnalysisStartTime        = scenario.StartTime;
                    crossingGroup.AnalysisStopTime         = scenario.StopTime;
                    crossingGroup.PlaneReferenceObjectName = satRefObj.InstanceName;
                    crossingGroup.CrossingObjectName       = cObject;

                    //Compute required VGT component names
                    crossObj           = CommonData.StkRoot.GetObjectFromPath(ObjectClass.Text + "/" + cObject);
                    crossVgt           = crossObj.Vgt;
                    angleName          = crossObj.InstanceName + "x" + satRefObj.InstanceName + "_Angle";
                    cScalName          = angleName;
                    extremaName        = crossObj.InstanceName + "x" + satRefObj.InstanceName + "_CrossingTimes";
                    conditionName      = crossObj.InstanceName + "x" + satRefObj.InstanceName + "_CrossingBounds";
                    condEventArrayName = crossObj.InstanceName + "x" + satRefObj.InstanceName + "_BoundedCrossingTimes";

                    //Create angle from current crossing object position to reference plane
                    IAgCrdnAngleToPlane planeAngle = AWBFunctions.GetCreateAngleToPlane(crossVgt, vgtPrv.Planes[planeName], crossVgt.Vectors["Position"], angleName, "Angle from satellite position to" + satRefObj.InstanceName + "orbit plane");

                    //Create calc scalar of angle
                    IAgCrdnCalcScalarAngle calcScalarAngle = AWBFunctions.GetCreateAngleCalcScalar(crossVgt, (IAgCrdnAngle)planeAngle, cScalName);

                    //Create Extrema time array to find exact crossing times
                    IAgCrdnEventArrayExtrema extrema = AWBFunctions.GetCreateEventArrayExtrema(crossVgt, (IAgCrdnCalcScalar)calcScalarAngle, extremaName, AgECrdnExtremumConstants.eCrdnExtremumMinimum, false);

                    //If conditional then create condition and condition crossing event
                    IAgCrdnEventArrayConditionCrossings conditionCrossings = null;
                    if (ConditionalCrossing.Checked)
                    {
                        //create condition
                        IAgCrdnConditionScalarBounds condition = AWBFunctions.GetCreateConditionScalarBounds(crossVgt, (IAgCrdnCalcScalar)calcScalarAngle, conditionName, AgECrdnConditionThresholdOption.eCrdnConditionThresholdOptionInsideMinMax);
                        AWBFunctions.SetAngleConditionScalarBounds(condition, Double.Parse(ConditionalLB.Text), Double.Parse(ConditionalUB.Text));

                        //Create condition crossing event
                        if (crossVgt.EventArrays.Contains(condEventArrayName))
                        {
                            conditionCrossings = (IAgCrdnEventArrayConditionCrossings)crossVgt.EventArrays[condEventArrayName];
                        }
                        else
                        {
                            conditionCrossings = (IAgCrdnEventArrayConditionCrossings)crossVgt.EventArrays.Factory.CreateEventArrayConditionCrossings(condEventArrayName, "");
                        }
                        conditionCrossings.Condition            = condition as IAgCrdnCondition;
                        conditionCrossings.SatisfactionCrossing =
                            AgECrdnSatisfactionCrossing.eCrdnSatisfactionCrossingNone;
                        //if (OffOnSat.Checked && OnOffSat.Checked)
                        //{
                        //    conditionCrossings.SatisfactionCrossing =
                        //        AgECrdnSatisfactionCrossing.eCrdnSatisfactionCrossingNone;
                        //}
                        //else if (OffOnSat.Checked && !OnOffSat.Checked)
                        //{
                        //    conditionCrossings.SatisfactionCrossing =
                        //        AgECrdnSatisfactionCrossing.eCrdnSatisfactionCrossingIn;
                        //}
                        //else if (!OffOnSat.Checked && OnOffSat.Checked)
                        //{
                        //    conditionCrossings.SatisfactionCrossing =
                        //        AgECrdnSatisfactionCrossing.eCrdnSatisfactionCrossingOut;
                        //}
                    }
                    //Extract Data
                    IAgCrdnEventArray      extremaArray = (IAgCrdnEventArray)extrema;
                    IAgCrdnFindTimesResult extremaTimes = extremaArray.FindTimes();
                    IAgCrdnEventArray      boundedArray = null;
                    IAgCrdnFindTimesResult boundedTimes = null;
                    if (extremaTimes.IsValid)
                    {
                        int numTimes = extremaTimes.Times.Length;
                        if (ConditionalCrossing.Checked)
                        {
                            boundedArray = conditionCrossings as IAgCrdnEventArray;
                            boundedTimes = boundedArray.FindTimes();
                            if (boundedTimes.Times.Length != 2 * numTimes)
                            {
                                MessageBox.Show("A bounded crossing time may be outside the analysis interval. Check results.");
                            }
                        }
                        PlaneCrossing crossing;
                        for (int i = 0; i < numTimes; i++)
                        {
                            crossing = new PlaneCrossing();
                            crossing.CrossingTime = extremaTimes.Times.GetValue(i).ToString();
                            if (ConditionalCrossing.Checked)
                            {
                                crossing.IsBounded  = true;
                                crossing.LowerBound = Double.Parse(ConditionalLB.Text);
                                crossing.UpperBound = Double.Parse(ConditionalUB.Text);

                                if (boundedTimes.Times.Length != 2 * numTimes)
                                {
                                    try
                                    {
                                        crossing.LowerBoundCrossingTime = boundedTimes.Times.GetValue(2 * i).ToString();
                                        crossing.UpperBoundCrossingTime = boundedTimes.Times.GetValue(2 * i + 1).ToString();
                                    }
                                    catch (Exception) //Index out of range
                                    {
                                        crossing.LowerBoundCrossingTime = "";
                                        crossing.UpperBoundCrossingTime = "";
                                    }
                                }
                                else
                                {
                                    crossing.LowerBoundCrossingTime = boundedTimes.Times.GetValue(2 * i).ToString();
                                    crossing.UpperBoundCrossingTime = boundedTimes.Times.GetValue(2 * i + 1).ToString();
                                }
                            }
                            crossingGroup.PlaneCrossings.Add(crossing);
                        }
                    }
                    AllPlaneCrossingsList.Add(crossingGroup);
                    compComplete = true;

                    //Add components to timeline view
                    if (AddToTimeline.Checked)
                    {
                        string cmd1 = null;
                        string cmd2 = null;
                        if (ConditionalCrossing.Checked)
                        {
                            cmd1 = "Timeline * TimeComponent Remove ContentView \"Scenario Availability\"" + " \"" + ObjectClass.Text + "/" + crossObj.InstanceName + " " + condEventArrayName + " Time Array\"";
                            cmd2 = "Timeline * TimeComponent Add ContentView \"Scenario Availability\" DisplayName \"" + condEventArrayName + "\"" + " \"" + ObjectClass.Text + "/" + crossObj.InstanceName + " " + condEventArrayName + " Time Array\"";
                        }
                        else
                        {
                            cmd1 = "Timeline * TimeComponent Remove ContentView \"Scenario Availability\"" + " \"" + ObjectClass.Text + "/" + crossObj.InstanceName + " " + extremaName + " Time Array\"";
                            cmd2 = "Timeline * TimeComponent Add ContentView \"Scenario Availability\" DisplayName \"" + extremaName + "\"" + " \"" + ObjectClass.Text + "/" + crossObj.InstanceName + " " + extremaName + " Time Array\"";
                        }

                        try
                        {
                            CommonData.StkRoot.ExecuteCommand(cmd1);
                        }
                        catch (Exception)
                        {
                        }
                        try
                        {
                            CommonData.StkRoot.ExecuteCommand(cmd2);
                            CommonData.StkRoot.ExecuteCommand("Timeline * Refresh");
                        }
                        catch (Exception exception)
                        {
                            //likely no timeline exists
                        }
                    }
                }

                //Export options
                if (compComplete && ExportToTxt.Checked)
                {
                    ReadWrite.WritePlaneCrossingOutput(satRefObj.InstanceName, AllPlaneCrossingsList);
                }
                MessageBox.Show("Computation Complete!");
            }
        }
        private void Generate_Click(object sender, EventArgs e)
        {
            CommonData.StkRoot.ExecuteCommand("BatchGraphics * On");
            IAgConstellation myConst;

            if ((string)ImportType.SelectedItem == "TLE/TCE")
            {
                string      filepath      = TCEFile.Text;
                IAgScenario scenario      = (IAgScenario)CommonData.StkRoot.CurrentScenario;
                string      startTime     = scenario.StartTime;
                string      stopTime      = scenario.StopTime;
                string      constellation = null;
                string      cmd;

                try
                {
                    IAgExecCmdResult result = CommonData.StkRoot.ExecuteCommand("DoesObjExist / */Constellation/Assets");
                    if ((string)ConstType.SelectedItem == "Default Constellation")
                    {
                        if (result[0] == "0")
                        {
                            IAgConstellation assets = (IAgConstellation)CommonData.StkRoot.CurrentScenario.Children.New(AgESTKObjectType.eConstellation, "Assets");
                        }
                        constellation = "Assets";
                    }
                    else if ((string)ConstType.SelectedItem == "Existing Constellation")
                    {
                        result = CommonData.StkRoot.ExecuteCommand("DoesObjExist / */Constellation/" + ExistingConst.Text);
                        if (result[0] == "0")
                        {
                            IAgConstellation assets = (IAgConstellation)CommonData.StkRoot.CurrentScenario.Children.New(AgESTKObjectType.eConstellation, ExistingConst.Text);
                        }
                        constellation = ExistingConst.Text;
                    }
                    else if ((string)ConstType.SelectedItem == "New Constellation")
                    {
                        result = CommonData.StkRoot.ExecuteCommand("DoesObjExist / */Constellation/" + ConstName.Text);
                        if (result[0] == "0")
                        {
                            IAgConstellation assets = (IAgConstellation)CommonData.StkRoot.CurrentScenario.Children.New(AgESTKObjectType.eConstellation, ConstName.Text);
                        }
                        constellation = ConstName.Text;
                    }
                    //must parse satellites into constellation because of bug associated with ImportTLEFile connect command
                    //Get list of sats prior to import
                    result = CommonData.StkRoot.ExecuteCommand("ShowNames * Class Satellite");
                    string[] prevSatArray = null;
                    if (result[0] != "None")
                    {
                        prevSatArray = result[0].Split(null);
                    }

                    //Import TLE
                    cmd = "ImportTLEFile * " + "\"" + filepath + "\"" + " AutoPropagate On TimeStep 30.0 StartStop " + "\"" + startTime + "\" " + "\"" + stopTime + "\"";
                    CommonData.StkRoot.ExecuteCommand(cmd);

                    myConst = CommonData.StkRoot.GetObjectFromPath("Constellation/" + constellation) as IAgConstellation;
                    IAgSatellite sat;
                    //Compare prev satellite list to new satellite list
                    result = CommonData.StkRoot.ExecuteCommand("ShowNames * Class Satellite");
                    string[] newSatArray = null;
                    if (result[0] != "None")
                    {
                        newSatArray = result[0].Split(null);
                    }
                    if (prevSatArray == null)
                    {
                        if (newSatArray != null)
                        {
                            foreach (var item in newSatArray)
                            {
                                if (item != "")
                                {
                                    string newItem = item.Split('/').Last();
                                    string objPath = "Satellite/" + newItem;
                                    myConst.Objects.Add(objPath);
                                    sat = CommonData.StkRoot.GetObjectFromPath(item.ToString()) as IAgSatellite;
                                    if (CoordSystem.SelectedIndex == 0)
                                    {
                                        sat.VO.OrbitSystems.FixedByWindow.IsVisible    = true;
                                        sat.VO.OrbitSystems.InertialByWindow.IsVisible = false;
                                    }
                                    cmd = "VO */" + item.ToString() + " ModelDetail Set ModelLabel 2000000000 MarkerLabel 2000000000";
                                    CommonData.StkRoot.ExecuteCommand(cmd);
                                }
                            }
                        }
                    }
                    else
                    {
                        bool exists = false;
                        foreach (var newSat in newSatArray)
                        {
                            if (newSat != "")
                            {
                                exists = false;
                                foreach (var prevSat in prevSatArray)
                                {
                                    if (prevSat == newSat)
                                    {
                                        exists = true;
                                    }
                                }
                                if (exists != true)
                                {
                                    string newItem = newSat.Split('/').Last();
                                    string objPath = "Satellite/" + newItem;
                                    myConst.Objects.Add(objPath);
                                    sat = CommonData.StkRoot.GetObjectFromPath(objPath) as IAgSatellite;
                                    if (CoordSystem.SelectedIndex == 0)
                                    {
                                        sat.VO.OrbitSystems.FixedByWindow.IsVisible    = true;
                                        sat.VO.OrbitSystems.InertialByWindow.IsVisible = false;
                                    }
                                    cmd = "VO */" + objPath + " ModelDetail Set ModelLabel 2000000000 MarkerLabel 2000000000";
                                    CommonData.StkRoot.ExecuteCommand(cmd);
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Could not load asset(s)");
                }
            }
            else if ((string)ImportType.SelectedItem == "Orbital Elements")
            {
                int check = FieldCheck();
                if (check == 0)
                {
                    int errorNum = 0;
                    try
                    {
                        errorNum = 1;
                        IAgStkObject sat   = CreatorFunctions.GetCreateSatellite(NameValue.Text);
                        IAgSatellite mySat = sat as IAgSatellite;
                        if (CoordSystem.SelectedIndex == 0)
                        {
                            mySat.VO.OrbitSystems.FixedByWindow.IsVisible    = true;
                            mySat.VO.OrbitSystems.InertialByWindow.IsVisible = false;
                            string cmd = "VO */Satellite/" + NameValue.Text + " ModelDetail Set ModelLabel 2000000000 MarkerLabel 2000000000";
                            CommonData.StkRoot.ExecuteCommand(cmd);
                        }
                        ((IAgSatellite)mySat).SetPropagatorType(AgEVePropagatorType.ePropagatorJ2Perturbation);
                        IAgOrbitStateClassical keplerian;
                        keplerian = ((IAgOrbitStateClassical)((IAgVePropagatorJ2Perturbation)((IAgSatellite)mySat).Propagator).InitialState.Representation.ConvertTo(AgEOrbitStateType.eOrbitStateClassical));
                        keplerian.SizeShapeType = AgEClassicalSizeShape.eSizeShapeSemimajorAxis;
                        ((IAgVePropagatorJ2Perturbation)((IAgSatellite)mySat).Propagator).InitialState.Representation.AssignClassical(AgECoordinateSystem.eCoordinateSystemICRF, Double.Parse(SMAValue.Text), Double.Parse(EccValue.Text), Double.Parse(IncValue.Text), Double.Parse(AoPValue.Text), Double.Parse(RAANValue.Text), Double.Parse(TAValue.Text));
                        ((IAgVePropagatorJ2Perturbation)((IAgSatellite)mySat).Propagator).Propagate();
                        IAgExecCmdResult result = CommonData.StkRoot.ExecuteCommand("DoesObjExist / */Constellation/Assets");
                        errorNum = 2;
                        if ((string)ConstType.SelectedItem == "Default Constellation")
                        {
                            IAgStkObject     conste = CreatorFunctions.GetCreateConstellation("Assets");
                            IAgConstellation assets = conste as IAgConstellation;

                            string objPath = "Satellite/" + NameValue.Text;
                            assets.Objects.Add(objPath);
                        }
                        else if ((string)ConstType.SelectedItem == "Existing Constellation")
                        {
                            IAgConstellation assets  = (IAgConstellation)CommonData.StkRoot.GetObjectFromPath("Constellation/" + ExistingConst.Text);
                            string           objPath = "Satellite/" + NameValue.Text;
                            assets.Objects.Add(objPath);
                        }
                        else if ((string)ConstType.SelectedItem == "New Constellation")
                        {
                            IAgConstellation assets  = (IAgConstellation)CommonData.StkRoot.CurrentScenario.Children.New(AgESTKObjectType.eConstellation, ConstName.Text);
                            string           objPath = "Satellite/" + NameValue.Text;
                            assets.Objects.Add(objPath);
                        }
                    }
                    catch (Exception)
                    {
                        string errorMes = null;
                        if (errorNum == 1)
                        {
                            errorMes = "Could not load satellite- Improper Orbital Elements";
                        }
                        else if (errorNum == 2)
                        {
                            errorMes = "Could not add satellite to constellation";
                        }
                        MessageBox.Show(errorMes);
                    }
                }
            }
            else if ((string)ImportType.SelectedItem == "Satellite Database")
            {
                string           sscString = null;
                string           satName   = null;
                int              errorNum  = 0;
                string           errorSsc  = null;
                string           objPath   = null;
                IAgSatellite     mySat     = null;
                IAgConstellation assets    = null;
                IAgScenario      scenario  = CommonData.StkRoot.CurrentScenario as IAgScenario;
                string           startTime = scenario.StartTime;
                string           stopTime  = scenario.StopTime;
                string           cmd;
                int              errorId = 0;
                CommonData.StkRoot.ExecuteCommand("BatchGraphics * On");
                foreach (var item in _selectedSatList)
                {
                    //Determine the proper satellite name based on catalog
                    errorId = 5;
                    int        index      = CommonData.SatCatItemList.IndexOf(CommonData.SatCatItemList.Where(p => p.Ssc == item).FirstOrDefault());
                    SatCatItem currentSat = CommonData.SatCatItemList[index];
                    if (currentSat.OtherName != "Unspecified")
                    {
                        string otherName = currentSat.OtherName.Replace(" ", "_");
                        otherName = Regex.Replace(otherName, @"[^0-9a-zA-Z_]+", "");
                        //CommonData.StkRoot.ExecuteCommand("Rename */" + objPath + " " + otherName);
                        objPath = "Satellite/" + otherName;
                        satName = otherName;
                    }
                    else if (currentSat.CommonName != "Unspecified")
                    {
                        string commonName = currentSat.CommonName.Replace(" ", "_");
                        commonName = Regex.Replace(commonName, @"[^0-9a-zA-Z_]+", "");
                        objPath    = "Satellite/" + commonName;
                        satName    = commonName;
                    }
                    else
                    {
                        objPath = "Satellite/" + item;
                        satName = item;
                    }

                    //SSCString = "SSCNumber " + item + " ";
                    //cmd = "ImportTLEFile * " + "\"" + CommonData.SatDatabaseLocation + "\"" +SSCString+ "AutoPropagate On TimeStep 30.0 StartStop " + "\"" + startTime + "\" " + "\"" + stopTime + "\"";
                    try
                    {
                        errorId = 1;
                        //Create or get handle to satellite based on given name
                        mySat = (IAgSatellite)CreatorFunctions.GetCreateSatellite(satName);
                        //Erase old TLE data and replace it with new data from specified file
                        mySat.SetPropagatorType(AgEVePropagatorType.ePropagatorSGP4);
                        IAgVePropagatorSGP4 tleprop = mySat.Propagator as IAgVePropagatorSGP4;
                        tleprop.Segments.RemoveAllSegs();//clear before adding new
                        tleprop.CommonTasks.AddSegsFromFile(item, CommonData.Preferences.SatDatabaseLocation);
                        tleprop.Propagate();
                        mySat.Graphics.Resolution.Orbit = 20;
                        //Change trajectory representation to fixed if required. Inertial by default
                        if (CoordSystem.SelectedIndex == 0)
                        {
                            mySat.VO.OrbitSystems.FixedByWindow.IsVisible    = true;
                            mySat.VO.OrbitSystems.InertialByWindow.IsVisible = false;
                            string cmd1 = "VO */Satellite/" + satName + " ModelDetail Set ModelLabel 2000000000 MarkerLabel 2000000000";
                            CommonData.StkRoot.ExecuteCommand(cmd1);
                        }
                        else if (CoordSystem.SelectedIndex == 1)
                        {
                            mySat.VO.OrbitSystems.FixedByWindow.IsVisible    = false;
                            mySat.VO.OrbitSystems.InertialByWindow.IsVisible = true;
                            string cmd1 = "VO */Satellite/" + satName + " ModelDetail Set ModelLabel 2000000000 MarkerLabel 2000000000";
                            CommonData.StkRoot.ExecuteCommand(cmd1);
                        }

                        //Get handle to constellation or create if necessary. Add satellite to constellation
                        if ((string)ConstType.SelectedItem == "Default Constellation")
                        {
                            errorId = 2;
                            assets  = CreatorFunctions.GetCreateConstellation("Assets") as IAgConstellation;
                        }
                        else if ((string)ConstType.SelectedItem == "Existing Constellation")
                        {
                            errorId = 3;
                            assets  = CreatorFunctions.GetCreateConstellation(ExistingConst.Text) as IAgConstellation;
                        }
                        else if ((string)ConstType.SelectedItem == "New Constellation")
                        {
                            errorId = 4;
                            assets  = CreatorFunctions.GetCreateConstellation(ConstName.Text) as IAgConstellation;
                        }

                        if (!assets.Objects.Contains("Satellite/" + satName))
                        {
                            objPath = "Satellite/" + satName;
                            assets.Objects.Add(objPath);
                        }

                        errorId = 8;
                        CreatorFunctions.ChangeSatColor(objPath, index);

                        //Create sensor if applicable. Place sensor in appropiate constellation for sensors
                        if (currentSat.Fov != 0 && SensorToggle.Checked)
                        {
                            try
                            {
                                errorId = 6;
                                IAgStkObject assetsObject = assets as IAgStkObject;
                                IAgStkObject sat          = CommonData.StkRoot.GetObjectFromPath(objPath);
                                IAgSensor    sensor       = CreatorFunctions.GetCreateSensor(sat, sat.InstanceName + "_Sensor") as IAgSensor;
                                IAgStkObject sensorObject = sensor as IAgStkObject;
                                sensor.CommonTasks.SetPatternSimpleConic(currentSat.Fov / 2, 1);
                                sensor.VO.ProjectionType      = AgESnVOProjectionType.eProjectionEarthIntersections;
                                sensor.VO.PercentTranslucency = 70;

                                errorId = 7;
                                assets  = CreatorFunctions.GetCreateConstellation(assetsObject.InstanceName + "_Sensors") as IAgConstellation;
                                try
                                {
                                    assets.Objects.AddObject(sensorObject);
                                }
                                catch (Exception)
                                {
                                    //Likely already in the constellation
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                    catch (Exception)
                    {
                        string errorIdString = null;
                        if (errorId == 1)
                        {
                            errorIdString = "- Could not load from database";
                        }
                        else if (errorId == 2)
                        {
                            errorIdString = "- Could not add to Default constellation";
                        }
                        else if (errorId == 3)
                        {
                            errorIdString = "- Could not add to existing constellation";
                        }
                        else if (errorId == 4)
                        {
                            errorIdString = "- Could not add to new constellation";
                        }
                        else if (errorId == 5)
                        {
                            errorIdString = "- Could not change satellite name";
                        }
                        else if (errorId == 6)
                        {
                            errorIdString = "- Could not load sensor or update sensor properties";
                        }
                        else if (errorId == 7)
                        {
                            errorIdString = "- Could not add sensor to constellation";
                        }
                        else if (errorId == 8)
                        {
                            errorIdString = "- Could not change satellite color";
                        }
                        errorSsc = errorSsc + item + errorIdString + "\n\r";
                        errorNum++;
                    }
                }
                if (errorNum != 0)
                {
                    MessageBox.Show("Error loading the following satellites: \n\r" + errorSsc);
                }
                CommonData.StkRoot.ExecuteCommand("BatchGraphics * Off");
            }
            else if ((string)ImportType.SelectedItem == "Ephemeris")
            {
                try
                {
                    IAgConstellation assets        = null;
                    string           constellation = null;
                    if ((string)ConstType.SelectedItem == "Default Constellation")
                    {
                        IAgStkObject obj = CreatorFunctions.GetCreateConstellation("Assets");
                        assets        = obj as IAgConstellation;
                        constellation = "Assets";
                    }
                    else if ((string)ConstType.SelectedItem == "Existing Constellation")
                    {
                        IAgStkObject obj = CreatorFunctions.GetCreateConstellation(ExistingConst.Text);
                        assets        = obj as IAgConstellation;
                        constellation = ExistingConst.Text;
                    }
                    else if ((string)ConstType.SelectedItem == "New Constellation")
                    {
                        IAgStkObject obj = CreatorFunctions.GetCreateConstellation(ConstName.Text);
                        assets        = obj as IAgConstellation;
                        constellation = ConstName.Text;
                    }
                    string   filepath   = TCEFile.Text;
                    string[] separator1 = { "\\" };
                    string[] separator2 = { "." };
                    string   fileName   = filepath.Split(separator1, StringSplitOptions.None).Last();
                    string   satName    = fileName.Split(separator2, StringSplitOptions.None).First();
                    satName = Regex.Replace(satName, @"[^0-9a-zA-Z_]+", "");
                    IAgStkObject satObj = CreatorFunctions.GetCreateSatellite(satName);
                    IAgSatellite sat    = satObj as IAgSatellite;
                    sat.SetPropagatorType(AgEVePropagatorType.ePropagatorStkExternal);
                    IAgVePropagatorStkExternal prop = sat.Propagator as IAgVePropagatorStkExternal;
                    prop.Filename = filepath;
                    if (TimeSlip.Checked)
                    {
                        try
                        {
                            prop.Override = true;
                            prop.EphemerisStartEpoch.SetExplicitTime(SlipTime.Text);
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("Could not apply time slip");
                        }
                    }
                    prop.Propagate();
                    try
                    {
                        assets.Objects.AddObject(satObj);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Could not add to constellation");
                    }

                    if (CoordSystem.SelectedIndex == 0)
                    {
                        sat.VO.OrbitSystems.FixedByWindow.IsVisible    = true;
                        sat.VO.OrbitSystems.InertialByWindow.IsVisible = false;
                        string cmd = "VO */Satellite/" + satName + " ModelDetail Set ModelLabel 2000000000 MarkerLabel 2000000000";
                        CommonData.StkRoot.ExecuteCommand(cmd);
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Error loading ephemeris");
                }
            }
            CommonData.StkRoot.ExecuteCommand("BatchGraphics * Off");
            PopulateExistingConstellations();
        }
        //create satellite function
        private void CreateSatellite(string objId, string source, string fpath)
        {
            IAgStkObject sat = null;

            try
            {
                string sname = objId + "_" + source.Replace(' ', '_').Trim();

                //create new if non-existant or get handle
                sat = CreatorFunctions.GetCreateSatellite(sname);

                //handle to satellite
                IAgSatellite zsat = sat as IAgSatellite;
                //Erase old TLE data and replace it with new data from specified file
                zsat.SetPropagatorType(AgEVePropagatorType.ePropagatorSGP4);
                IAgVePropagatorSGP4 tleprop = zsat.Propagator as IAgVePropagatorSGP4;
                tleprop.Segments.RemoveAllSegs();//clear before adding new
                tleprop.CommonTasks.AddSegsFromFile(objId, fpath);
                tleprop.Propagate();
                zsat.Graphics.Resolution.Orbit = 10;


                if (CoordSystem.SelectedIndex == 0)
                {
                    zsat.VO.OrbitSystems.FixedByWindow.IsVisible    = true;
                    zsat.VO.OrbitSystems.InertialByWindow.IsVisible = false;
                    string cmd = "VO */Satellite/" + sname + " ModelDetail Set ModelLabel 2000000000 MarkerLabel 2000000000";
                    try
                    {
                        CommonData.StkRoot.ExecuteCommand(cmd);
                    }
                    catch (Exception)
                    {
                    }
                }

                //Place into constellation
                IAgConstellation assets = null;
                if ((string)ConstType.SelectedItem == "Default Constellation")
                {
                    IAgStkObject conste = CreatorFunctions.GetCreateConstellation("Assets");
                    assets = conste as IAgConstellation;
                }
                else if ((string)ConstType.SelectedItem == "Existing Constellation")
                {
                    assets = (IAgConstellation)CommonData.StkRoot.GetObjectFromPath("Constellation/" + ExistingConst.Text);
                }
                else if ((string)ConstType.SelectedItem == "New Constellation")
                {
                    IAgStkObject conste = CreatorFunctions.GetCreateConstellation(ConstName.Text.Replace(" ", "_"));
                    assets = conste as IAgConstellation;
                }
                string objPath = "Satellite/" + sname;
                if (assets.Objects.IndexOf(objPath) == -1 && assets != null)
                {
                    assets.Objects.Add(objPath);
                }
            }
            catch (Exception ex)
            {
                //Identify the satellite with an issue
                MessageBox.Show(ex.Message + "\n" + "SSC: " + objId);
                //unload satellite if possible so there is not an empty object in STK from an error
                //try
                //{
                //    sat.Unload();
                //}
                //catch (Exception)
                //{
                //}
            }
        }
Exemple #5
0
        //Main Function
        private void Generate_Click(object sender, EventArgs e)
        {
            int check = FieldCheck();

            if (check == 0)
            {
                RemoveProximityGeometry();
                try
                {
                    CommonData.StkRoot.UnitPreferences.SetCurrentUnit("Distance", "km");
                    CommonData.RunList.Clear();
                    CommonData.TargetName = TargetSat.Text;
                    CommonData.ActorName  = ActorSat.Text;
                    //Set user bounds for safety
                    double userMinRange = Double.Parse(SphericalMag.Text) / 1000;
                    double userMinR     = Double.Parse(RMag.Text) / 1000;
                    double userMinI     = Double.Parse(IMag.Text) / 1000;
                    double userMinC     = Double.Parse(CMag.Text) / 1000;

                    IAgScenario  scenario = CommonData.StkRoot.CurrentScenario as IAgScenario;
                    IAgStkObject satObj   = CommonData.StkRoot.GetObjectFromPath("Satellite/" + ActorSat.Text);
                    IAgSatellite sat      = satObj as IAgSatellite;

                    //Get all maneuver end times for actor satellite
                    IAgDataProviderGroup   maneuverDpGroup = satObj.DataProviders["Astrogator Maneuver Ephemeris Block Final"] as IAgDataProviderGroup;
                    IAgDataPrvTimeVar      maneuverDp      = maneuverDpGroup.Group["Cartesian Elems"] as IAgDataPrvTimeVar;
                    IAgDrResult            result          = maneuverDp.Exec(scenario.StartTime, scenario.StopTime, 60);
                    IAgDrDataSetCollection maneuverData    = result.DataSets;



                    //If there is maneuvers, run iterations for each maneuver. If no maneuvers then just pull closest RIC data for entire trajectory
                    if (maneuverData.Count != 0)
                    {
                        CommonData.HasManeuvers = true;

                        //Get maneuver numbers
                        IAgDataPrvInterval summaryDp     = satObj.DataProviders["Maneuver Summary"] as IAgDataPrvInterval;
                        IAgDrResult        summaryResult = summaryDp.Exec(scenario.StartTime, scenario.StopTime);
                        Array maneuverNumbers            = summaryResult.DataSets.GetDataSetByName("Maneuver Number").GetValues();
                        int   maxManeuverNum             = maneuverNumbers.Length;

                        //Get handles to cartesian position and velocity to seed passive safety runs
                        IAgDataProviderGroup cartPos   = satObj.DataProviders["Cartesian Position"] as IAgDataProviderGroup;
                        IAgDataPrvTimeVar    cartPosDP = cartPos.Group["ICRF"] as IAgDataPrvTimeVar;

                        IAgDataProviderGroup cartVel   = satObj.DataProviders["Cartesian Velocity"] as IAgDataProviderGroup;
                        IAgDataPrvTimeVar    cartVelDP = cartVel.Group["ICRF"] as IAgDataPrvTimeVar;

                        //Create passive safety satellite. Set to Astrogator and pull handles to initial state and propagate segments
                        IAgStkObject passiveSatObj = CreatorFunctions.GetCreateSatellite("PassiveCheck");
                        IAgSatellite passiveSat    = passiveSatObj as IAgSatellite;
                        passiveSat.SetPropagatorType(AgEVePropagatorType.ePropagatorAstrogator);
                        IAgVADriverMCS passiveDriver = passiveSat.Propagator as IAgVADriverMCS;

                        IAgVAMCSInitialState          intState = passiveDriver.MainSequence[0] as IAgVAMCSInitialState;
                        IAgVAMCSPropagate             prop     = passiveDriver.MainSequence[1] as IAgVAMCSPropagate;
                        IAgVAStoppingConditionElement sc1      = prop.StoppingConditions[0];
                        IAgVAStoppingCondition        sc       = sc1.Properties as IAgVAStoppingCondition;
                        sc.Trip = PropTime.Text;

                        AgVAElementCartesian element = intState.Element as AgVAElementCartesian;
                        Array    epoch;
                        Array    vx;
                        Array    vy;
                        Array    vz;
                        Array    x;
                        Array    y;
                        Array    z;
                        String   epochCur;
                        DateTime dateCur;
                        //Assign cartesian elements to PassiveCheck satellite from actor maneuver maneuver data. Run each iteration to see if resulting trajectory violates constraints
                        for (int i = 0; i < maxManeuverNum; i++)
                        {
                            //Get maneuver time and offset in time by 0.25 sec to account for boundrary conditions around impulsive maneuvers
                            epoch    = maneuverData[0 + (i * 7)].GetValues();
                            epochCur = epoch.GetValue(0).ToString();
                            dateCur  = DateTime.Parse(epochCur);
                            dateCur  = dateCur.AddMilliseconds(250);
                            //dateCur = DateTime.ParseExact(epochCur, "dd MMM yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture);
                            epochCur = dateCur.ToString("dd MMM yyyy HH:mm:ss.fff");

                            //Get cartesian state vector for given time
                            result = cartPosDP.ExecSingle(epochCur);
                            x      = result.DataSets.GetDataSetByName("x").GetValues();
                            y      = result.DataSets.GetDataSetByName("y").GetValues();
                            z      = result.DataSets.GetDataSetByName("z").GetValues();

                            result = cartVelDP.ExecSingle(epochCur);
                            vx     = result.DataSets.GetDataSetByName("x").GetValues();
                            vy     = result.DataSets.GetDataSetByName("y").GetValues();
                            vz     = result.DataSets.GetDataSetByName("z").GetValues();

                            //Create passive run output to be used in visualization
                            PassiveRun run = new PassiveRun();
                            run.UserMinRange    = Double.Parse(SphericalMag.Text) / 1000;
                            run.UserMinR        = Double.Parse(RMag.Text) / 1000;
                            run.UserMinI        = Double.Parse(IMag.Text) / 1000;
                            run.UserMinC        = Double.Parse(CMag.Text) / 1000;
                            intState.OrbitEpoch = epochCur;
                            element.Vx          = Double.Parse(vx.GetValue(0).ToString());
                            element.Vy          = Double.Parse(vy.GetValue(0).ToString());
                            element.Vz          = Double.Parse(vz.GetValue(0).ToString());
                            element.X           = Double.Parse(x.GetValue(0).ToString());
                            element.Y           = Double.Parse(y.GetValue(0).ToString());
                            element.Z           = Double.Parse(z.GetValue(0).ToString());

                            passiveDriver.RunMCS();

                            run.Vx       = Double.Parse(vx.GetValue(0).ToString());
                            run.Vy       = Double.Parse(vy.GetValue(0).ToString());
                            run.Vz       = Double.Parse(vz.GetValue(0).ToString());
                            run.X        = Double.Parse(x.GetValue(0).ToString());
                            run.Y        = Double.Parse(y.GetValue(0).ToString());
                            run.Z        = Double.Parse(z.GetValue(0).ToString());
                            run.PropTime = Double.Parse(PropTime.Text);

                            //Pull closest point to target for each iteration and save to passive run output
                            IAgDataProvider psatDp = passiveSatObj.DataProviders["RIC Coordinates"] as IAgDataProvider;
                            psatDp.PreData = "Satellite/" + TargetSat.Text;
                            IAgDataPrvTimeVar psatDpTimeVar = psatDp as IAgDataPrvTimeVar;
                            IAgDrResult       psatDp2       = psatDpTimeVar.Exec(scenario.StartTime, scenario.StopTime, Double.Parse(TimeStep.Text));
                            run.Range         = psatDp2.DataSets.GetDataSetByName("Range").GetValues();
                            run.Intrack       = psatDp2.DataSets.GetDataSetByName("In-Track").GetValues();
                            run.Crosstrack    = psatDp2.DataSets.GetDataSetByName("Cross-Track").GetValues();
                            run.Radial        = psatDp2.DataSets.GetDataSetByName("Radial").GetValues();
                            run.MinRange      = MathFunctions.ArrayMin(run.Range);
                            run.MinIntrack    = MathFunctions.ArrayMinAbs(run.Intrack);
                            run.MinCrosstrack = MathFunctions.ArrayMinAbs(run.Crosstrack);
                            run.MinRadial     = MathFunctions.ArrayMinAbs(run.Radial);
                            //run.ManeuverTime = epoch.GetValue(0).ToString();
                            run.ManeuverTime = epochCur;

                            //spherical
                            if (radioButton1.Checked)
                            {
                                run.IsSpherical = true;
                                if (run.MinRange < userMinRange)
                                {
                                    run.Safe = false;
                                }
                                else
                                {
                                    run.Safe = true;
                                }
                            }
                            //independent axis
                            else
                            {
                                run.IsSpherical = false;
                                if (Math.Abs(run.MinIntrack) < userMinI && Math.Abs(run.MinRadial) < userMinR && Math.Abs(run.MinCrosstrack) < userMinC)
                                {
                                    bool tripped = false;
                                    for (int j = 0; j < run.Range.Length; j++)
                                    {
                                        if (Math.Abs(Double.Parse(run.Intrack.GetValue(j).ToString())) < userMinI && Math.Abs(Double.Parse(run.Radial.GetValue(j).ToString())) < userMinR && Math.Abs(Double.Parse(run.Crosstrack.GetValue(j).ToString())) < userMinC)
                                        {
                                            run.Safe = false;
                                            tripped  = true;
                                            break;
                                        }
                                    }
                                    if (!tripped)
                                    {
                                        run.Safe = true;
                                    }
                                }
                                else
                                {
                                    run.Safe = true;
                                }
                            }

                            CommonData.RunList.Add(run);
                        }
                    }
                    else
                    {
                        CommonData.HasManeuvers = false;
                        PassiveRun      run   = new PassiveRun();
                        IAgDataProvider satDp = satObj.DataProviders["RIC Coordinates"] as IAgDataProvider;
                        satDp.PreData = "Satellite/" + TargetSat.Text;
                        IAgDataPrvTimeVar satDpTimeVar = satDp as IAgDataPrvTimeVar;
                        IAgDrResult       satDp2       = satDpTimeVar.Exec(scenario.StartTime, scenario.StopTime, Double.Parse(TimeStep.Text));
                        run.Range         = satDp2.DataSets.GetDataSetByName("Range").GetValues();
                        run.Intrack       = satDp2.DataSets.GetDataSetByName("In-Track").GetValues();
                        run.Crosstrack    = satDp2.DataSets.GetDataSetByName("Cross-Track").GetValues();
                        run.Radial        = satDp2.DataSets.GetDataSetByName("Radial").GetValues();
                        run.MinRange      = MathFunctions.ArrayMin(run.Range);
                        run.MinIntrack    = MathFunctions.ArrayMinAbs(run.Intrack);
                        run.MinCrosstrack = MathFunctions.ArrayMinAbs(run.Crosstrack);
                        run.MinRadial     = MathFunctions.ArrayMinAbs(run.Radial);
                        run.ManeuverTime  = "N/A";

                        //spherical
                        if (radioButton1.Checked)
                        {
                            run.IsSpherical = true;
                            if (run.MinRange < userMinRange)
                            {
                                run.Safe = false;
                            }
                            else
                            {
                                run.Safe = true;
                            }
                        }
                        //independent axis
                        else
                        {
                            run.IsSpherical = false;
                            if (Math.Abs(run.MinIntrack) < userMinI && Math.Abs(run.MinRadial) < userMinR && Math.Abs(run.MinCrosstrack) < userMinC)
                            {
                                bool tripped = false;
                                for (int j = 0; j < run.Range.Length; j++)
                                {
                                    if (Math.Abs(Double.Parse(run.Intrack.GetValue(j).ToString())) < userMinI && Math.Abs(Double.Parse(run.Radial.GetValue(j).ToString())) < userMinR && Math.Abs(Double.Parse(run.Crosstrack.GetValue(j).ToString())) < userMinC)
                                    {
                                        run.Safe = false;
                                        tripped  = true;
                                        break;
                                    }
                                }
                                if (!tripped)
                                {
                                    run.Safe = true;
                                }
                            }
                            else
                            {
                                run.Safe = true;
                            }
                        }

                        CommonData.RunList.Add(run);
                    }
                    CommonData.BeenRun = true;
                }
                catch (Exception)
                {
                    MessageBox.Show("Passive Safety Check Failed");
                }
            }
        }