Example #1
0
        private void stationIncludedButton_ItemClick(object sender, ItemClickEventArgs e)
        {
            RouteStation station = stationsView.GetFocusedRow() as RouteStation;

            if (station != null)
            {
                if (station.Included)
                {
                    if (MessageBox.Show("Are you sure that you want to remove this station?",
                                        Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        if (m_route.IsTransitionStation(station))
                        {
                            MessageBox.Show("This station is part of outcome routing and must be included.",
                                            Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return;
                        }

                        station.Included = false;
                    }
                }
                else
                {
                    station.Included = true;
                }
            }
        }
Example #2
0
        // ================================

        /// <summary>Call this function to reset the game</summary>
        /// <param name="ResetLogs">Whether the logs should be reset</param>
        internal static void Reset(bool ResetLogs)
        {
            // track manager
            for (int i = 0; i < TrackManager.Tracks.Length; i++)
            {
                TrackManager.Tracks[i] = new TrackManager.Track();
            }
            // train manager
            TrainManager.Trains = new TrainManager.Train[] { };
            // game
            Interface.ClearMessages();
            CurrentInterface = InterfaceType.Normal;
            RouteComment     = "";
            RouteImage       = "";
            RouteAccelerationDueToGravity = 9.80665;
            RouteRailGauge              = 1.435;
            RouteInitialAirPressure     = 101325.0;
            RouteInitialAirTemperature  = 293.15;
            RouteInitialElevation       = 0.0;
            RouteSeaLevelAirPressure    = 101325.0;
            RouteSeaLevelAirTemperature = 293.15;
            Stations = new RouteStation[] { };
            CurrentRoute.Sections = new Section[] { };
            BufferTrackPositions  = new double[] { };
            //Messages = new Message[] { };
            MarkerTextures           = new Texture[] { };
            PointsOfInterest         = new PointOfInterest[] { };
            PrecedingTrainTimeDeltas = new double[] { };
            PrecedingTrainSpeedLimit = double.PositiveInfinity;
            CurrentRoute.BogusPretrainInstructions = new BogusPretrainInstruction[] { };
            TrainName  = "";
            TrainStart = TrainStartMode.EmergencyBrakesNoAts;
            CurrentRoute.NoFogStart   = (float)Math.Max(1.33333333333333 * Interface.CurrentOptions.ViewingDistance, 800.0);
            CurrentRoute.NoFogEnd     = (float)Math.Max(2.66666666666667 * Interface.CurrentOptions.ViewingDistance, 1600.0);
            CurrentRoute.PreviousFog  = new Fog(CurrentRoute.NoFogStart, CurrentRoute.NoFogEnd, Color24.Grey, 0.0);
            CurrentRoute.CurrentFog   = new Fog(CurrentRoute.NoFogStart, CurrentRoute.NoFogEnd, Color24.Grey, 0.5);
            CurrentRoute.NextFog      = new Fog(CurrentRoute.NoFogStart, CurrentRoute.NoFogEnd, Color24.Grey, 1.0);
            InfoTotalTriangles        = 0;
            InfoTotalTriangleStrip    = 0;
            InfoTotalQuads            = 0;
            InfoTotalQuadStrip        = 0;
            InfoTotalPolygon          = 0;
            InfoStaticOpaqueFaceCount = 0;
            if (ResetLogs)
            {
                LogRouteName       = "";
                LogTrainName       = "";
                LogDateTime        = DateTime.Now;
                CurrentScore       = new Score();
                ScoreMessages      = new ScoreMessage[] { };
                ScoreLogs          = new ScoreLog[64];
                ScoreLogCount      = 0;
                BlackBoxEntries    = new BlackBoxEntry[256];
                BlackBoxEntryCount = 0;
                BlackBoxNextUpdate = 0.0;
            }
            // renderer
            Renderer.Reset();
        }
Example #3
0
 public BusStation(RouteStation station)
 {
     id        = "[" + station.no + "]";
     number    = station.name;
     address   = station.address;
     lat       = Convert.ToDouble(station.lon);
     lon       = Convert.ToDouble(station.lat);
     stationId = station.stationId.ToString();
     district  = station.address.Split(',').LastOrDefault();
 }
Example #4
0
        void allStationsListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            RouteStation station
                = allStationsListBox.SelectedValue as RouteStation;

            if (station != null)
            {
                LoadStationDetails(station);
            }
        }
Example #5
0
 private void Init()
 {
     m_session                  = Scout.Core.Data.GetUnitOfWork();
     m_item                     = null;
     m_process                  = null;
     m_routeStation             = null;
     tasksGrid.DataSource       = null;
     inspectionsGrid.DataSource = null;
     ClearEditors();
     snText.Focus();
 }
Example #6
0
        public ServiceStationForm(RouteStation station)
        {
            InitializeComponent();

            m_station    = station;
            m_unitOfWork = station.Session;

            Init();
            Bind();
            WireEvents();
        }
Example #7
0
        private bool StationIsIncluded(RouteStation station)
        {
            if (station.Included == false)
            {
                MessageBox.Show(
                    "This station is not currently included in the route and cannot be set as the first station.",
                    Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return(false);
            }

            return(true);
        }
Example #8
0
 private void Clear()
 {
     stationText.Text        = "";
     domainText.Text         = "";
     snText.Text             = "";
     currentStationText.Text = "";
     m_item    = null;
     m_station = null;
     allStationsListBox.DataSource = null;
     routesListBox.SelectedValue   = null;
     snText.Focus();
 }
Example #9
0
        private void LoadStationDetails(RouteStation station)
        {
            m_station = station;

            if (m_station == null)
            {
                Clear();
                return;
            }

            stationText.Text = m_station.Station.Name;
            domainText.Text  = m_station.Station.Domain.Label;
        }
Example #10
0
        // ================================

        internal static void Reset()
        {
            // track manager
            TrackManager.CurrentTrack = new TrackManager.Track();
            // train manager
            TrainManager.Trains = new TrainManager.Train[] { };
            // game
            Interface.ClearMessages();
            RouteComment = "";
            RouteImage   = "";
            RouteAccelerationDueToGravity = 9.80665;
            RouteRailGauge              = 1.435;
            RouteInitialAirPressure     = 101325.0;
            RouteInitialAirTemperature  = 293.15;
            RouteInitialElevation       = 0.0;
            RouteSeaLevelAirPressure    = 101325.0;
            RouteSeaLevelAirTemperature = 293.15;
            Stations = new RouteStation[] { };
            CurrentRoute.Sections = new Section[] { };
            BufferTrackPositions  = new double[] { };
            MarkerTextures        = new Texture[] { };
            PointsOfInterest      = new PointOfInterest[] { };
            CurrentRoute.BogusPretrainInstructions = new BogusPretrainInstruction[] { };
            TrainName  = "";
            TrainStart = TrainStartMode.EmergencyBrakesNoAts;
            CurrentRoute.PreviousFog = new Fog(0.0f, 0.0f, Color24.Grey, 0.0);
            CurrentRoute.CurrentFog  = new Fog(0.0f, 0.0f, Color24.Grey, 0.5);
            CurrentRoute.NextFog     = new Fog(0.0f, 0.0f, Color24.Grey, 1.0);
            CurrentRoute.NoFogStart  = (float)Backgrounds.BackgroundImageDistance + 200.0f;
            CurrentRoute.NoFogEnd    = 2.0f * CurrentRoute.NoFogStart;
            InfoTotalTriangles       = 0;
            InfoTotalTriangleStrip   = 0;
            InfoTotalQuads           = 0;
            InfoTotalQuadStrip       = 0;
            InfoTotalPolygon         = 0;
            // object manager
            ObjectManager.Objects                     = new StaticObject[16];
            ObjectManager.ObjectsUsed                 = 0;
            ObjectManager.ObjectsSortedByStart        = new int[] { };
            ObjectManager.ObjectsSortedByEnd          = new int[] { };
            ObjectManager.ObjectsSortedByStartPointer = 0;
            ObjectManager.ObjectsSortedByEndPointer   = 0;
            ObjectManager.LastUpdatedTrackPosition    = 0.0;
            ObjectManager.AnimatedWorldObjects        = new ObjectManager.AnimatedWorldObject[4];
            ObjectManager.AnimatedWorldObjectsUsed    = 0;
            // renderer / sound
            Renderer.Reset();
            Sounds.StopAllSounds();
            GC.Collect();
        }
Example #11
0
        private bool VerifyFirstStationChange(RouteStation station)
        {
            string msg = "Are you sure that you";

            msg += " that you want to set station";
            msg += " {0} as the first station?";

            StringBuilder sb = new StringBuilder();

            sb.AppendFormat(msg, station.Name);

            DialogResult result = MessageBox.Show(sb.ToString(),
                                                  Application.ProductName, MessageBoxButtons.YesNo,
                                                  MessageBoxIcon.Question);

            return(result == DialogResult.Yes);
        }
Example #12
0
        private void LoadStationConfiguration()
        {
            RouteStation station = stationsView.GetFocusedRow() as RouteStation;

            if (station != null)
            {
                if (!station.Included)
                {
                    MessageBox.Show("This station is not included in the current route.", Application.ProductName,
                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                ServiceStationForm form = new ServiceStationForm(station);
                form.StartPosition = FormStartPosition.CenterParent;
                form.ShowDialog();
            }
        }
Example #13
0
        public void CreateSpecificRoute(int routeId, DateTime departTime, int vehicleId)
        {
            using (var uow = UnitOfWorkProvider.Create())
            {
                var route = routeRepository.GetById(routeId, r => r.RouteStations);
                createSpecificRouteQuery.RouteId = routeId;
                var routeStationsTemplates = createSpecificRouteQuery.Execute().ToList();
                var seatDTOs = ListSeatsOfVehicle(vehicleId);

                foreach (var routeStationTemplate in routeStationsTemplates)
                {
                    var routeStation = new RouteStation();
                    Mapper.Map(routeStationTemplate, routeStation);
                    routeStation.DepartFromFirstStation = departTime;
                    var routeStationForGettingStation = routeStationRepository.GetById(routeStationTemplate.ID, routeStationTemplat => routeStationTemplat.Station);

                    var station = stationRepository.GetById(routeStationForGettingStation.Station.ID, s => s.RouteStations);

                    routeStation.Route = route;
                    route.RouteStations.Add(routeStation);

                    routeStation.Station = station;
                    station.RouteStations.Add(routeStation);

                    if (seatDTOs != null)
                    {
                        foreach (var seatDTO in seatDTOs)
                        {
                            var seat    = seatRepository.GetById(seatDTO.ID, s => s.Programs);
                            var program = new Program
                            {
                                IsSeatOccupied = false,
                                RouteStation   = routeStation,
                                Seat           = seat
                            };
                            seat.Programs.Add(program);
                            programRepository.Insert(program);
                            routeStation.Programs.Add(program);
                        }
                    }
                    routeStationRepository.Insert(routeStation);
                }
                uow.Commit();
            }
        }
Example #14
0
        void stationsView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            RouteStation station = stationsView.GetFocusedRow() as RouteStation;

            if (station != null)
            {
                if (station.Included)
                {
                    stationIncludedButton.Caption    = "Remove Station";
                    stationIncludedButton.ImageIndex = 0;
                }
                else
                {
                    stationIncludedButton.Caption    = "Include Station";
                    stationIncludedButton.ImageIndex = 1;
                }
            }
        }
Example #15
0
        private void setfirstStationButton_ItemClick(object sender, ItemClickEventArgs e)
        {
            RouteStation station = stationsView.GetFocusedRow() as RouteStation;

            if (station != null)
            {
                if (!StationIsIncluded(station))
                {
                    return;
                }

                if (!VerifyFirstStationChange(station))
                {
                    return;
                }

                m_route.SetFirstStation(station);
            }
        }
Example #16
0
        public void MoveUnitToNewStation(RouteStationProcess process,
                                         RouteStation station)
        {
            InventoryItem item  = process.Item;
            ServiceRoute  route = process.Station.ServiceRoute;

            Scout.Core.Service <ITransactionService>().CreateTransaction("STATIONTRANS", item,
                                                                         process.Station.FullLocation,
                                                                         station.FullLocation,
                                                                         "Unit was manually moved to a new station.",
                                                                         "");


            if (item.CurrentProcess != null)
            {
                item.CurrentProcess.PrevProcess = item.CurrentProcess;
            }

            RouteStationProcess newProcess =
                route.CreateRouteStationProcess(station, item);

            item.CurrentProcess = newProcess;
            item.ChangeDomain(newProcess.Station.Station.Domain);
        }
Example #17
0
        public static RouteStation ReadStationXML(string fileName, bool PreviewOnly, Texture[] daytimeTimetableTextures, Texture[] nighttimeTimetableTextures, int CurrentStation, ref bool passAlarm, ref CsvRwRouteParser.StopRequest stopRequest)
        {
            RouteStation station = new RouteStation
            {
                Stops = new StationStop[] { }
            };

            stopRequest.Early              = new RequestStop();
            stopRequest.OnTime             = new RequestStop();
            stopRequest.Late               = new RequestStop();
            stopRequest.OnTime.Probability = 75;
            //The current XML file to load
            XmlDocument currentXML = new XmlDocument();

            //Load the object's XML file
            currentXML.Load(fileName);
            string Path = System.IO.Path.GetDirectoryName(fileName);

            //Check for null
            if (currentXML.DocumentElement != null)
            {
                XmlNodeList DocumentNodes = currentXML.DocumentElement.SelectNodes("/openBVE/Station");
                //Check this file actually contains OpenBVE station nodes
                if (DocumentNodes != null)
                {
                    foreach (XmlNode n in DocumentNodes)
                    {
                        if (n.ChildNodes.OfType <XmlElement>().Any())
                        {
                            foreach (XmlNode c in n.ChildNodes)
                            {
                                //string[] Arguments = c.InnerText.Split(new char[] { ',' });
                                switch (c.Name.ToLowerInvariant())
                                {
                                case "name":
                                    if (!string.IsNullOrEmpty(c.InnerText))
                                    {
                                        station.Name = c.InnerText;
                                    }
                                    else
                                    {
                                        Interface.AddMessage(MessageType.Error, false, "Station name was empty in XML file " + fileName);
                                    }
                                    break;

                                case "arrivaltime":
                                    if (!string.IsNullOrEmpty(c.InnerText))
                                    {
                                        if (!Interface.TryParseTime(c.InnerText, out station.ArrivalTime))
                                        {
                                            Interface.AddMessage(MessageType.Error, false, "Station arrival time was invalid in XML file " + fileName);
                                        }
                                    }
                                    break;

                                case "departuretime":
                                    if (!string.IsNullOrEmpty(c.InnerText))
                                    {
                                        if (!Interface.TryParseTime(c.InnerText, out station.DepartureTime))
                                        {
                                            Interface.AddMessage(MessageType.Error, false, "Station arrival time was invalid in XML file " + fileName);
                                        }
                                    }
                                    break;

                                case "type":
                                    switch (c.InnerText.ToLowerInvariant())
                                    {
                                    case "c":
                                    case "changeends":
                                        station.Type = StationType.ChangeEnds;
                                        break;

                                    case "j":
                                    case "jump":
                                        station.Type = StationType.Jump;
                                        break;

                                    case "t":
                                    case "terminal":
                                        station.Type = StationType.Terminal;
                                        break;

                                    default:
                                        station.Type = StationType.Normal;
                                        break;
                                    }
                                    break;

                                case "jumpindex":
                                    if (!string.IsNullOrEmpty(c.InnerText))
                                    {
                                        if (!NumberFormats.TryParseIntVb6(c.InnerText, out station.JumpIndex))
                                        {
                                            Interface.AddMessage(MessageType.Error, false, "Station jump index was invalid in XML file " + fileName);
                                            station.Type = StationType.Normal;
                                        }
                                    }
                                    else
                                    {
                                        Interface.AddMessage(MessageType.Error, false, "Station jump index was empty in XML file " + fileName);
                                        station.Type = StationType.Normal;
                                    }
                                    break;

                                case "passalarm":
                                    if (!string.IsNullOrEmpty(c.InnerText))
                                    {
                                        if (c.InnerText.ToLowerInvariant() == "1" || c.InnerText.ToLowerInvariant() == "true")
                                        {
                                            passAlarm = true;
                                        }
                                        else
                                        {
                                            passAlarm = false;
                                        }
                                    }
                                    break;

                                case "doors":
                                    int  door     = 0;
                                    bool doorboth = false;
                                    if (!string.IsNullOrEmpty(c.InnerText))
                                    {
                                        switch (c.InnerText.ToLowerInvariant())
                                        {
                                        case "l":
                                        case "left":
                                            door = -1;
                                            break;

                                        case "r":
                                        case "right":
                                            door = 1;
                                            break;

                                        case "n":
                                        case "none":
                                        case "neither":
                                            door = 0;
                                            break;

                                        case "b":
                                        case "both":
                                            doorboth = true;
                                            break;

                                        default:
                                            if (!NumberFormats.TryParseIntVb6(c.InnerText, out door))
                                            {
                                                Interface.AddMessage(MessageType.Error, false, "Door side was invalid in XML file " + fileName);
                                                door = 0;
                                            }
                                            break;
                                        }
                                    }
                                    station.OpenLeftDoors  = door < 0.0 | doorboth;
                                    station.OpenRightDoors = door > 0.0 | doorboth;
                                    break;

                                case "forcedredsignal":
                                    if (!string.IsNullOrEmpty(c.InnerText))
                                    {
                                        if (c.InnerText.ToLowerInvariant() == "1" || c.InnerText.ToLowerInvariant() == "true")
                                        {
                                            station.ForceStopSignal = true;
                                        }
                                        else
                                        {
                                            station.ForceStopSignal = false;
                                        }
                                    }
                                    break;

                                case "system":
                                    switch (c.InnerText.ToLowerInvariant())
                                    {
                                    case "0":
                                    case "ATS":
                                        station.SafetySystem = SafetySystem.Ats;
                                        break;

                                    case "1":
                                    case "ATC":
                                        station.SafetySystem = SafetySystem.Atc;
                                        break;

                                    default:
                                        Interface.AddMessage(MessageType.Error, false, "An invalid station safety system was specified in XML file " + fileName);
                                        station.SafetySystem = SafetySystem.Ats;
                                        break;
                                    }
                                    break;

                                case "arrivalsound":
                                    string arrSound  = string.Empty;
                                    double arrRadius = 30.0;
                                    if (!c.ChildNodes.OfType <XmlElement>().Any())
                                    {
                                        foreach (XmlNode cc in c.ChildNodes)
                                        {
                                            switch (c.Name.ToLowerInvariant())
                                            {
                                            case "filename":
                                                try
                                                {
                                                    arrSound = OpenBveApi.Path.CombineFile(Path, cc.InnerText);
                                                }
                                                catch
                                                {
                                                    Interface.AddMessage(MessageType.Error, false, "Arrival sound filename is invalid in XML file " + fileName);
                                                }
                                                break;

                                            case "radius":
                                                if (!double.TryParse(cc.InnerText, out arrRadius))
                                                {
                                                    Interface.AddMessage(MessageType.Error, false, "Arrival sound radius was invalid in XML file " + fileName);
                                                }
                                                break;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        try
                                        {
                                            arrSound = OpenBveApi.Path.CombineFile(Path, c.InnerText);
                                        }
                                        catch
                                        {
                                            Interface.AddMessage(MessageType.Error, false, "Arrival sound filename is invalid in XML file " + fileName);
                                        }
                                    }
                                    if (File.Exists(arrSound))
                                    {
                                        station.ArrivalSoundBuffer = Program.Sounds.RegisterBuffer(arrSound, arrRadius);
                                    }
                                    else
                                    {
                                        Interface.AddMessage(MessageType.Error, false, "Arrival sound file does not exist in XML file " + fileName);
                                    }
                                    break;

                                case "stopduration":
                                    double stopDuration;
                                    if (!double.TryParse(c.InnerText, out stopDuration))
                                    {
                                        Interface.AddMessage(MessageType.Error, false, "Stop duration is invalid in XML file " + fileName);
                                    }
                                    else
                                    {
                                        if (stopDuration < 5.0)
                                        {
                                            stopDuration = 5.0;
                                        }
                                        station.StopTime = stopDuration;
                                    }
                                    break;

                                case "passengerratio":
                                    double ratio;
                                    if (!double.TryParse(c.InnerText, out ratio))
                                    {
                                        Interface.AddMessage(MessageType.Error, false, "Passenger ratio is invalid in XML file " + fileName);
                                    }
                                    else
                                    {
                                        if (ratio < 0.0)
                                        {
                                            Interface.AddMessage(MessageType.Error, false, "Passenger ratio must be non-negative in XML file " + fileName);
                                            ratio = 100.0;
                                        }
                                        station.PassengerRatio = ratio * 0.01;
                                    }
                                    break;

                                case "departuresound":
                                    string depSound  = string.Empty;
                                    double depRadius = 30.0;
                                    if (!c.ChildNodes.OfType <XmlElement>().Any())
                                    {
                                        foreach (XmlNode cc in c.ChildNodes)
                                        {
                                            switch (c.Name.ToLowerInvariant())
                                            {
                                            case "filename":
                                                try
                                                {
                                                    depSound = OpenBveApi.Path.CombineFile(Path, cc.InnerText);
                                                }
                                                catch
                                                {
                                                    Interface.AddMessage(MessageType.Error, false, "Departure sound filename is invalid in XML file " + fileName);
                                                }
                                                break;

                                            case "radius":
                                                if (!double.TryParse(cc.InnerText, out depRadius))
                                                {
                                                    Interface.AddMessage(MessageType.Error, false, "Departure sound radius was invalid in XML file " + fileName);
                                                }
                                                break;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        try
                                        {
                                            depSound = OpenBveApi.Path.CombineFile(Path, c.InnerText);
                                        }
                                        catch
                                        {
                                            Interface.AddMessage(MessageType.Error, false, "Departure sound filename is invalid in XML file " + fileName);
                                        }
                                    }
                                    if (File.Exists(depSound))
                                    {
                                        station.DepartureSoundBuffer = Program.Sounds.RegisterBuffer(depSound, depRadius);
                                    }
                                    else
                                    {
                                        Interface.AddMessage(MessageType.Error, false, "Departure sound file does not exist in XML file " + fileName);
                                    }
                                    break;

                                case "timetableindex":
                                    if (!PreviewOnly)
                                    {
                                        int ttidx = -1;
                                        if (!string.IsNullOrEmpty(c.InnerText))
                                        {
                                            if (NumberFormats.TryParseIntVb6(c.InnerText, out ttidx))
                                            {
                                                if (ttidx < 0)
                                                {
                                                    Interface.AddMessage(MessageType.Error, false, "Timetable index must be non-negative in XML file " + fileName);
                                                    ttidx = -1;
                                                }
                                                else if (ttidx >= daytimeTimetableTextures.Length & ttidx >= nighttimeTimetableTextures.Length)
                                                {
                                                    Interface.AddMessage(MessageType.Error, false, "Timetable index references a non-loaded texture in XML file " + fileName);
                                                    ttidx = -1;
                                                }
                                                station.TimetableDaytimeTexture   = ttidx >= 0 & ttidx < daytimeTimetableTextures.Length ? daytimeTimetableTextures[ttidx] : null;
                                                station.TimetableNighttimeTexture = ttidx >= 0 & ttidx < nighttimeTimetableTextures.Length ? nighttimeTimetableTextures[ttidx] : null;
                                                break;
                                            }
                                        }
                                        if (ttidx == -1)
                                        {
                                            if (CurrentStation > 0)
                                            {
                                                station.TimetableDaytimeTexture   = Program.CurrentRoute.Stations[CurrentStation - 1].TimetableDaytimeTexture;
                                                station.TimetableNighttimeTexture = Program.CurrentRoute.Stations[CurrentStation - 1].TimetableNighttimeTexture;
                                            }
                                            else if (daytimeTimetableTextures.Length > 0 & nighttimeTimetableTextures.Length > 0)
                                            {
                                                station.TimetableDaytimeTexture   = daytimeTimetableTextures[0];
                                                station.TimetableNighttimeTexture = nighttimeTimetableTextures[0];
                                            }
                                        }
                                    }
                                    break;

                                case "reopendoor":
                                    double reopenDoor;
                                    if (!double.TryParse(c.InnerText, out reopenDoor))
                                    {
                                        Interface.AddMessage(MessageType.Error, false, "ReopenDoor is invalid in XML file " + fileName);
                                        reopenDoor = 0.0;
                                    }
                                    else
                                    {
                                        if (reopenDoor < 0.0)
                                        {
                                            Interface.AddMessage(MessageType.Error, false, "ReopenDoor must be non-negative in XML file " + fileName);
                                            reopenDoor = 0.0;
                                        }
                                    }
                                    station.ReopenDoor = 0.01 * reopenDoor;
                                    break;

                                case "reopenstationlimit":
                                    int reopenStationLimit;
                                    if (!int.TryParse(c.InnerText, out reopenStationLimit))
                                    {
                                        Interface.AddMessage(MessageType.Error, false, "ReopenStationLimit is invalid in XML file " + fileName);
                                        reopenStationLimit = 5;
                                    }
                                    else
                                    {
                                        if (reopenStationLimit < 0)
                                        {
                                            Interface.AddMessage(MessageType.Error, false, "ReopenStationLimit must be non-negative in XML file " + fileName);
                                            reopenStationLimit = 0;
                                        }
                                    }
                                    station.ReopenStationLimit = reopenStationLimit;
                                    break;

                                case "interferenceindoor":
                                    double interferenceInDoor;
                                    if (!double.TryParse(c.InnerText, out interferenceInDoor))
                                    {
                                        Interface.AddMessage(MessageType.Error, false, "InterferenceInDoor is invalid in XML file " + fileName);
                                        interferenceInDoor = 0.0;
                                    }
                                    else
                                    {
                                        if (interferenceInDoor < 0.0)
                                        {
                                            Interface.AddMessage(MessageType.Error, false, "InterferenceInDoor must be non-negative in XML file " + fileName);
                                            interferenceInDoor = 0.0;
                                        }
                                    }
                                    station.InterferenceInDoor = interferenceInDoor;
                                    break;

                                case "maxinterferingobjectrate":
                                    int maxInterferingObjectRate;
                                    if (!int.TryParse(c.InnerText, out maxInterferingObjectRate))
                                    {
                                        Interface.AddMessage(MessageType.Error, false, "MaxInterferingObjectRate is invalid in XML file " + fileName);
                                        maxInterferingObjectRate = Program.RandomNumberGenerator.Next(1, 99);
                                    }
                                    else
                                    {
                                        if (maxInterferingObjectRate <= 0 || maxInterferingObjectRate >= 100)
                                        {
                                            Interface.AddMessage(MessageType.Error, false, "MaxInterferingObjectRate must be positive, less than 100 in XML file " + fileName);
                                            maxInterferingObjectRate = Program.RandomNumberGenerator.Next(1, 99);
                                        }
                                    }
                                    station.MaxInterferingObjectRate = maxInterferingObjectRate;
                                    break;

                                case "requeststop":
                                    station.Type     = StationType.RequestStop;
                                    station.StopMode = StationStopMode.AllRequestStop;
                                    foreach (XmlNode cc in c.ChildNodes)
                                    {
                                        switch (cc.Name.ToLowerInvariant())
                                        {
                                        case "aibehaviour":
                                            switch (cc.InnerText.ToLowerInvariant())
                                            {
                                            case "fullspeed":
                                            case "0":
                                                //With this set, the AI driver will not attempt to brake, but pass through at linespeed
                                                stopRequest.FullSpeed = true;
                                                break;

                                            case "normalbrake":
                                            case "1":
                                                //With this set, the AI driver breaks to a near stop whilst passing through the station
                                                stopRequest.FullSpeed = false;
                                                break;
                                            }
                                            break;

                                        case "playeronly":
                                            station.StopMode = StationStopMode.PlayerRequestStop;
                                            break;

                                        case "distance":
                                            if (!string.IsNullOrEmpty(cc.InnerText))
                                            {
                                                double d;
                                                if (!NumberFormats.TryParseDoubleVb6(cc.InnerText, out d))
                                                {
                                                    Interface.AddMessage(MessageType.Error, false, "Request stop distance is invalid in XML file " + fileName);
                                                    break;
                                                }
                                                stopRequest.TrackPosition -= Math.Abs(d);
                                            }
                                            break;

                                        case "earlytime":
                                            if (!string.IsNullOrEmpty(cc.InnerText))
                                            {
                                                if (!Interface.TryParseTime(cc.InnerText, out stopRequest.Early.Time))
                                                {
                                                    Interface.AddMessage(MessageType.Error, false, "Request stop early time was invalid in XML file " + fileName);
                                                }
                                            }
                                            break;

                                        case "latetime":
                                            if (!string.IsNullOrEmpty(cc.InnerText))
                                            {
                                                if (!Interface.TryParseTime(cc.InnerText, out stopRequest.Late.Time))
                                                {
                                                    Interface.AddMessage(MessageType.Error, false, "Request stop late time was invalid in XML file " + fileName);
                                                }
                                            }
                                            break;

                                        case "stopmessage":
                                            if (cc.ChildNodes.OfType <XmlElement>().Any())
                                            {
                                                foreach (XmlNode cd in cc.ChildNodes)
                                                {
                                                    switch (cd.Name.ToLowerInvariant())
                                                    {
                                                    case "early":
                                                        if (!string.IsNullOrEmpty(cd.InnerText))
                                                        {
                                                            stopRequest.Early.StopMessage = cd.InnerText;
                                                        }
                                                        break;

                                                    case "ontime":
                                                        if (!string.IsNullOrEmpty(cd.InnerText))
                                                        {
                                                            stopRequest.OnTime.StopMessage = cd.InnerText;
                                                        }
                                                        break;

                                                    case "late":
                                                        if (!string.IsNullOrEmpty(cd.InnerText))
                                                        {
                                                            stopRequest.Late.StopMessage = cd.InnerText;
                                                        }
                                                        break;

                                                    case "#text":
                                                        stopRequest.Early.StopMessage  = cc.InnerText;
                                                        stopRequest.OnTime.StopMessage = cc.InnerText;
                                                        stopRequest.Late.StopMessage   = cc.InnerText;
                                                        break;
                                                    }
                                                }
                                            }
                                            break;

                                        case "passmessage":
                                            if (cc.ChildNodes.OfType <XmlElement>().Any())
                                            {
                                                foreach (XmlNode cd in cc.ChildNodes)
                                                {
                                                    switch (cd.Name.ToLowerInvariant())
                                                    {
                                                    case "early":
                                                        if (!string.IsNullOrEmpty(cd.InnerText))
                                                        {
                                                            stopRequest.Early.PassMessage = cd.InnerText;
                                                        }
                                                        break;

                                                    case "ontime":
                                                        if (!string.IsNullOrEmpty(cd.InnerText))
                                                        {
                                                            stopRequest.OnTime.PassMessage = cd.InnerText;
                                                        }
                                                        break;

                                                    case "late":
                                                        if (!string.IsNullOrEmpty(cd.InnerText))
                                                        {
                                                            stopRequest.Late.PassMessage = cd.InnerText;
                                                        }
                                                        break;

                                                    case "#text":
                                                        stopRequest.Early.PassMessage  = cc.InnerText;
                                                        stopRequest.OnTime.PassMessage = cc.InnerText;
                                                        stopRequest.Late.PassMessage   = cc.InnerText;
                                                        break;
                                                    }
                                                }
                                            }
                                            break;

                                        case "probability":
                                            foreach (XmlNode cd in cc.ChildNodes)
                                            {
                                                switch (cd.Name.ToLowerInvariant())
                                                {
                                                case "early":
                                                    if (!string.IsNullOrEmpty(cd.InnerText))
                                                    {
                                                        if (!NumberFormats.TryParseIntVb6(cd.InnerText, out stopRequest.Early.Probability))
                                                        {
                                                            Interface.AddMessage(MessageType.Error, false, "Request stop early probability was invalid in XML file " + fileName);
                                                        }
                                                    }
                                                    break;

                                                case "ontime":
                                                    if (!string.IsNullOrEmpty(cd.InnerText))
                                                    {
                                                        if (!NumberFormats.TryParseIntVb6(cd.InnerText, out stopRequest.OnTime.Probability))
                                                        {
                                                            Interface.AddMessage(MessageType.Error, false, "Request stop ontime probability was invalid in XML file " + fileName);
                                                        }
                                                    }
                                                    break;

                                                case "late":
                                                    if (!string.IsNullOrEmpty(cd.InnerText))
                                                    {
                                                        if (!NumberFormats.TryParseIntVb6(cd.InnerText, out stopRequest.OnTime.Probability))
                                                        {
                                                            Interface.AddMessage(MessageType.Error, false, "Request stop late probability was invalid in XML file " + fileName);
                                                        }
                                                    }
                                                    break;

                                                case "#text":
                                                    if (!NumberFormats.TryParseIntVb6(cd.InnerText, out stopRequest.OnTime.Probability))
                                                    {
                                                        Interface.AddMessage(MessageType.Error, false, "Request stop probability was invalid in XML file " + fileName);
                                                    }
                                                    break;
                                                }
                                            }

                                            break;

                                        case "maxcars":
                                            if (!NumberFormats.TryParseIntVb6(cc.InnerText, out stopRequest.MaxNumberOfCars))
                                            {
                                                Interface.AddMessage(MessageType.Error, false, "Request stop maximum cars was invalid in XML file " + fileName);
                                            }
                                            break;
                                        }
                                    }

                                    break;
                                }
                            }
                        }
                    }
                    return(station);
                }
            }
            //We couldn't find any valid XML, so return false
            throw new InvalidDataException();
        }
Example #18
0
        public static void Main(string[] args)
        {
            //For unicode output
            Console.OutputEncoding = System.Text.Encoding.Unicode;

            goto GetNewData;
            #region Load Old Data

            _stationTotal         = Xml2Object <ObservableCollection <StationTotal> >("StationList.xml");
            _busRoute             = Xml2Object <ObservableCollection <BusRoute> >("FullBusRoute.xml");
            _busStationCollection = Xml2Object <ObservableCollection <BusStationCollection> >("StationInfo.xml");
            _busContent           = Xml2Object <ObservableCollection <BusContent> >("StationDetail.xml");

            newBusNameList     = Xml2Object <BusNameList>("BusNameList.xml");
            codedBusNameList   = Xml2Object <CodedBusNameList>("CodedBusNameList.xml");
            generalStationList = Xml2Object <GeneralStationList>("GeneralStationList.xml");

            //TODO: skip to update data here
            //goto UpdateData;

            #endregion

GetNewData:
            _stationTotal         = Xml2Object <ObservableCollection <StationTotal> >("StationList.xml");
            _busRoute             = Xml2Object <ObservableCollection <BusRoute> >("FullBusRoute.xml");
            _busStationCollection = Xml2Object <ObservableCollection <BusStationCollection> >("StationInfo.xml");
            _busContent           = Xml2Object <ObservableCollection <BusContent> >("StationDetail.xml");

            #region Get List of buses

            //Reuse data
            string       lobHtml     = GetHttpAsString("http://www.buyttphcm.com.vn/TTLT.aspx");
            HtmlDocument lobDocument = new HtmlDocument();

            //goto GetBusesCode;

            lobDocument.LoadHtml(lobHtml);

            newBusNameList.busNameCollection = new ObservableCollection <BusName>();

            var nodes =
                lobDocument.DocumentNode.SelectNodes("//select[@id='ctl00_ContentPlaceHolder1_DropDownList1']/option");
            foreach (HtmlNode htmlNode in nodes)
            {
                BusName newBusName = new BusName();
                newBusName.number = htmlNode.Attributes["value"].Value;

                if (newBusName.number == "0")
                {
                    continue;
                }

                newBusName.name = UTF8Decode(htmlNode.NextSibling.InnerText);

                newBusNameList.busNameCollection.Add(newBusName);
                Console.WriteLine(newBusName.name);
            }

            //Object2Xml(newBusNameList, "BusNameList");

            #endregion

            #region Get Buses text data

            foreach (BusName busName in newBusNameList.busNameCollection)
            {
                lobHtml = GetHttpAsString("http://www.buyttphcm.com.vn/Detail_TTLT.aspx?sl=" + busName.number);

                lobHtml = UTF8Decode(lobHtml);
                lobDocument.LoadHtml(lobHtml);

                BusTextData newBusTextData = new BusTextData();

                nodes =
                    lobDocument.DocumentNode.SelectNodes(
                        "//div[@id='ctl00_ContentPlaceHolder1_UpdatePanel2']/table[2]");

                newBusTextData.go       = nodes[0].SelectNodes(".//tr[3]/td[@class='conten']")[0].InnerText.Trim();
                newBusTextData.back     = nodes[0].SelectNodes(".//tr[4]/td[@class='conten']")[0].InnerText.Trim();
                newBusTextData.timeInfo = nodes[0].SelectNodes(".//tr[5]/td[@class='conten']")[0].InnerText.Trim();

                busName.busTextData = newBusTextData;

                Console.WriteLine(newBusTextData.go);
                Console.WriteLine(newBusTextData.back);
                Console.WriteLine(newBusTextData.timeInfo);

                Console.WriteLine(busName.name + " - Bus Text Data added!");
            }

            Object2Xml(newBusNameList, "BusNameList");

            #endregion

            #region Get Buses name code

GetBusesCode:

            codedBusNameList.codedBusNameCollection = new ObservableCollection <BusCodedName>();

            lobHtml = GetHttpAsString("http://mapbus.ebms.vn/routeoftrunk.aspx");
            lobDocument.LoadHtml(lobHtml);

            nodes = lobDocument.DocumentNode.SelectNodes("//select[@id='lstTuyen']/option");
            foreach (HtmlNode htmlNode in nodes)
            {
                BusCodedName newBusName = new BusCodedName();
                newBusName.number = Convert.ToInt32(htmlNode.Attributes["value"].Value);

                if (newBusName.number == 0)
                {
                    continue;
                }

                newBusName.name = UTF8Decode(htmlNode.NextSibling.InnerText);

                codedBusNameList.codedBusNameCollection.Add(newBusName);
                Console.WriteLine("Coded: " + newBusName.number + " - " + newBusName.name);
            }

            #endregion

            #region Get List Route Station

GetListRouteStation:

            foreach (BusCodedName bus in codedBusNameList.codedBusNameCollection)
            {
                bus.directionRouteCollection = new ObservableCollection <DirectionRoute>();

                //Go Direction

                DirectionRoute directionGoRoute = new DirectionRoute();
                directionGoRoute.isGo = true;

                lobHtml =
                    GetHttpAsString("http://mapbus.ebms.vn/ajax.aspx?action=listRouteStations&rid=" + bus.number +
                                    "&isgo=true");
                if (lobHtml == "null")
                {
                    Console.WriteLine("Bus: " + bus.name + " don't have route. Skip");
                    continue;
                }
                lobHtml = UTF8Decode(lobHtml);
                JObject jObject = new JObject();
                jObject = JObject.Parse(lobHtml);

                RootRouteStation rootRouteGoStation = jObject.ToObject <RootRouteStation>();

                directionGoRoute.routeStationCollection = new ObservableCollection <RouteStation>();
                directionGoRoute.routePoints            = new ObservableCollection <GPSPoint>();

                foreach (ROW row in rootRouteGoStation.TABLE[0].ROW)
                {
                    RouteStation newRouteStation = new RouteStation();
                    newRouteStation.no        = Convert.ToInt32(row.COL[0].DATA);
                    newRouteStation.stationId = Convert.ToInt32(row.COL[1].DATA);
                    if (row.COL[2].DATA != "")
                    {
                        newRouteStation.nextStationId = Convert.ToInt32(row.COL[2].DATA);
                    }
                    newRouteStation.route = row.COL[3].DATA;
                    ObservableCollection <GPSPoint> gpsPoints = ConvertStringToGPSPoints(row.COL[3].DATA);
                    foreach (GPSPoint point in gpsPoints)
                    {
                        directionGoRoute.routePoints.Add(point);
                    }
                    newRouteStation.name    = row.COL[7].DATA;
                    newRouteStation.lon     = row.COL[9].DATA;
                    newRouteStation.lat     = row.COL[8].DATA;
                    newRouteStation.address = row.COL[12].DATA;

                    directionGoRoute.routeStationCollection.Add(newRouteStation);

                    Console.WriteLine("New station added: " + newRouteStation.stationId);
                }

                bus.directionRouteCollection.Add(directionGoRoute);

                //Back Direction

                DirectionRoute directionBackRoute = new DirectionRoute();
                directionBackRoute.isGo = false;

                lobHtml =
                    GetHttpAsString("http://mapbus.ebms.vn/ajax.aspx?action=listRouteStations&rid=" + bus.number +
                                    "&isgo=false");
                lobHtml = UTF8Decode(lobHtml);
                jObject = new JObject();
                jObject = JObject.Parse(lobHtml);

                RootRouteStation rootRouteBackStation = jObject.ToObject <RootRouteStation>();

                directionBackRoute.routeStationCollection = new ObservableCollection <RouteStation>();
                directionBackRoute.routePoints            = new ObservableCollection <GPSPoint>();

                foreach (ROW row in rootRouteBackStation.TABLE[0].ROW)
                {
                    RouteStation newRouteStation = new RouteStation();
                    newRouteStation.no        = Convert.ToInt32(row.COL[0].DATA);
                    newRouteStation.stationId = Convert.ToInt32(row.COL[1].DATA);
                    if (row.COL[2].DATA != "")
                    {
                        newRouteStation.nextStationId = Convert.ToInt32(row.COL[2].DATA);
                    }
                    newRouteStation.route = row.COL[3].DATA;
                    ObservableCollection <GPSPoint> gpsPoints = ConvertStringToGPSPoints(row.COL[3].DATA);
                    foreach (GPSPoint point in gpsPoints)
                    {
                        directionBackRoute.routePoints.Add(point);
                    }
                    newRouteStation.name    = row.COL[7].DATA;
                    newRouteStation.lon     = row.COL[9].DATA;
                    newRouteStation.lat     = row.COL[8].DATA;
                    newRouteStation.address = row.COL[12].DATA;

                    directionBackRoute.routeStationCollection.Add(newRouteStation);

                    Console.WriteLine("New station added: " + newRouteStation.stationId);
                }

                bus.directionRouteCollection.Add(directionBackRoute);
            }

            #endregion

            #region Caculate RouteStation

            generalStationList.generalStationCollection = new ObservableCollection <GeneralStation>();

            foreach (BusCodedName bus in codedBusNameList.codedBusNameCollection)
            {
                if (bus.directionRouteCollection.Count == 0)
                {
                    continue;
                }
                //Go Direction
                foreach (RouteStation station in bus.directionRouteCollection[0].routeStationCollection)
                {
                    GeneralStation generalStation =
                        generalStationList.generalStationCollection.FirstOrDefault(i => i.stationId == station.stationId);
                    if (generalStation != null)
                    {
                        //Existed in list
                        //TODO: code here
                        ThroughStationBus thStationBus = new ThroughStationBus();
                        thStationBus.name      = bus.name;
                        thStationBus.number    = bus.number.ToString();
                        thStationBus.direction = DirectionType.Go;

                        generalStation.throughStationBusCollection.Add(thStationBus);
                    }
                    else
                    {
                        //Not existed
                        GeneralStation newGeneralStation = new GeneralStation(station);
                        newGeneralStation.throughStationBusCollection = new ObservableCollection <ThroughStationBus>();

                        ThroughStationBus thStationBus = new ThroughStationBus();
                        thStationBus.name      = bus.name;
                        thStationBus.number    = bus.number.ToString();
                        thStationBus.direction = DirectionType.Go;

                        newGeneralStation.throughStationBusCollection.Add(thStationBus);
                        Console.WriteLine("New General Station Added: " + newGeneralStation.stationId);

                        generalStationList.generalStationCollection.Add(newGeneralStation);
                    }
                }

                //Back Direction
                foreach (RouteStation station in bus.directionRouteCollection[1].routeStationCollection)
                {
                    GeneralStation generalStation =
                        generalStationList.generalStationCollection.FirstOrDefault(i => i.stationId == station.stationId);
                    if (generalStation != null)
                    {
                        //Existed in list
                        //TODO: code here
                        ThroughStationBus thStationBus = new ThroughStationBus();
                        thStationBus.name      = bus.name;
                        thStationBus.number    = bus.number.ToString();
                        thStationBus.direction = DirectionType.Go;

                        bool isBoth = false;

                        foreach (ThroughStationBus directionBus in generalStation.throughStationBusCollection)
                        {
                            if (directionBus.number == thStationBus.number)
                            {
                                directionBus.direction = DirectionType.Both;
                                isBoth = true;
                                break;
                            }
                        }

                        if (!isBoth)
                        {
                            generalStation.throughStationBusCollection.Add(thStationBus);
                        }
                    }
                    else
                    {
                        //Not existed
                        GeneralStation newGeneralStation = new GeneralStation(station);
                        newGeneralStation.throughStationBusCollection = new ObservableCollection <ThroughStationBus>();

                        ThroughStationBus thStationBus = new ThroughStationBus();
                        thStationBus.name      = bus.name;
                        thStationBus.number    = bus.number.ToString();
                        thStationBus.direction = DirectionType.Back;

                        newGeneralStation.throughStationBusCollection.Add(thStationBus);
                        Console.WriteLine("New General Station Added: " + newGeneralStation.stationId);

                        generalStationList.generalStationCollection.Add(newGeneralStation);
                    }
                }
            }

            #endregion

            //Write to file
            Object2Xml(codedBusNameList, "CodedBusNameList");
            Object2Xml(generalStationList, "GeneralStationList");

UpdateData:
            //Update old data to new one, using old structure

            //Update StationDetail
            foreach (BusName bus in newBusNameList.busNameCollection)
            {
                bool isOldData = false;
                foreach (BusContent content in _busContent)
                {
                    if (bus.number == content.id)
                    {
                        content.id     = bus.number;
                        content.name   = bus.name;
                        content.go     = bus.busTextData.go;
                        content.back   = bus.busTextData.back;
                        content.detail = bus.busTextData.timeInfo;
                        isOldData      = true;
                        break;
                    }
                }

                if (!isOldData)
                {
                    BusContent content = new BusContent();
                    content.id     = bus.number;
                    content.name   = bus.name;
                    content.go     = bus.busTextData.go;
                    content.back   = bus.busTextData.back;
                    content.detail = bus.busTextData.timeInfo;
                    _busContent.Add(content);
                }
            }

            //Write Data
            Object2Xml(_busContent, "StationDetail");

            //Update StationInfo
            foreach (BusCodedName bus in codedBusNameList.codedBusNameCollection)
            {
                bool isOldData = false;
                foreach (BusStationCollection content in _busStationCollection)
                {
                    string name   = bus.name.Split(']')[0].TrimStart('[');
                    int    busNum = 0;
                    try
                    {
                        busNum = Convert.ToInt32(name);
                    }
                    catch (Exception)
                    {
                        //Cannot convert - new bus staton collection
                        Console.WriteLine("New strange name bus detected: " + name);
                    }
                    if (busNum == Convert.ToInt32(content.id))
                    {
                        content.id            = busNum.ToString();
                        content.goDirection   = new ObservableCollection <BusStation>();
                        content.backDirection = new ObservableCollection <BusStation>();
                        if (bus.directionRouteCollection[0].isGo)
                        {
                            //Correct go direction
                            int i = 1;
                            foreach (RouteStation station in bus.directionRouteCollection[0].routeStationCollection)
                            {
                                BusStation newStation = new BusStation(station);
                                newStation.id = "[" + i + "]";
                                i++;
                                content.goDirection.Add(newStation);
                            }
                            i = 1;
                            foreach (RouteStation station in bus.directionRouteCollection[1].routeStationCollection)
                            {
                                BusStation newStation = new BusStation(station);
                                newStation.id = "[" + i + "]";
                                i++;
                                content.backDirection.Add(newStation);
                            }
                        }
                        else
                        {
                            foreach (RouteStation station in bus.directionRouteCollection[0].routeStationCollection)
                            {
                                BusStation newStation = new BusStation(station);
                                content.backDirection.Add(newStation);
                            }
                            foreach (RouteStation station in bus.directionRouteCollection[1].routeStationCollection)
                            {
                                BusStation newStation = new BusStation(station);
                                content.goDirection.Add(newStation);
                            }
                        }
                        isOldData = true;
                        Console.WriteLine("Old bus: " + content.id);
                        break;
                    }
                }

                if (!isOldData)
                {
                    BusStationCollection newStationCollection = new BusStationCollection();
                    newStationCollection.id            = bus.name.Split(']')[0].TrimStart('[');
                    newStationCollection.goDirection   = new ObservableCollection <BusStation>();
                    newStationCollection.backDirection = new ObservableCollection <BusStation>();
                    if (bus.directionRouteCollection.Count == 0)
                    {
                        continue;
                    }
                    if (bus.directionRouteCollection[0].isGo)
                    {
                        //Correct go direction
                        int i = 1;
                        foreach (RouteStation station in bus.directionRouteCollection[0].routeStationCollection)
                        {
                            BusStation newStation = new BusStation(station);
                            newStation.id = "[" + i + "]";
                            i++;
                            newStationCollection.goDirection.Add(newStation);
                        }
                        i = 1;
                        foreach (RouteStation station in bus.directionRouteCollection[1].routeStationCollection)
                        {
                            BusStation newStation = new BusStation(station);
                            newStation.id = "[" + i + "]";
                            i++;
                            newStationCollection.backDirection.Add(newStation);
                        }
                    }
                    else
                    {
                        foreach (RouteStation station in bus.directionRouteCollection[0].routeStationCollection)
                        {
                            BusStation newStation = new BusStation(station);
                            newStationCollection.backDirection.Add(newStation);
                        }
                        foreach (RouteStation station in bus.directionRouteCollection[1].routeStationCollection)
                        {
                            BusStation newStation = new BusStation(station);
                            newStationCollection.goDirection.Add(newStation);
                        }
                    }

                    Console.WriteLine("Strange bus added to updated data: " + bus.name);
                }
            }

            //Write Data
            Object2Xml(_busStationCollection, "StationInfo");

            //Update FullBusRoute
            foreach (BusCodedName bus in codedBusNameList.codedBusNameCollection)
            {
                bool isOldData = false;
                foreach (BusRoute content in _busRoute)
                {
                    string name   = bus.name.Split(']')[0].TrimStart('[');
                    int    busNum = 0;
                    try
                    {
                        busNum = Convert.ToInt32(name);
                    }
                    catch (Exception)
                    {
                        //Cannot convert - new bus staton collection
                        Console.WriteLine("New strange name bus detected: " + name);
                    }
                    if (busNum == Convert.ToInt32(content.id))
                    {
                        content.id            = busNum.ToString();
                        content.goDirection   = new ObservableCollection <LocationPointWithId>();
                        content.backDirection = new ObservableCollection <LocationPointWithId>();
                        if (bus.directionRouteCollection[0].isGo)
                        {
                            //Correct go direction
                            int i = 1;
                            foreach (GPSPoint station in bus.directionRouteCollection[0].routePoints)
                            {
                                LocationPointWithId newStation = new LocationPointWithId(station);
                                newStation.id = "[" + i + "]";
                                i++;
                                content.goDirection.Add(newStation);
                            }
                            i = 1;
                            foreach (GPSPoint station in bus.directionRouteCollection[1].routePoints)
                            {
                                LocationPointWithId newStation = new LocationPointWithId(station);
                                newStation.id = "[" + i + "]";
                                i++;
                                content.backDirection.Add(newStation);
                            }
                        }
                        else
                        {
                            int i = 1;
                            foreach (GPSPoint station in bus.directionRouteCollection[0].routePoints)
                            {
                                LocationPointWithId newStation = new LocationPointWithId(station);
                                newStation.id = "[" + i + "]";
                                i++;
                                content.backDirection.Add(newStation);
                            }
                            i = 1;
                            foreach (GPSPoint station in bus.directionRouteCollection[1].routePoints)
                            {
                                LocationPointWithId newStation = new LocationPointWithId(station);
                                newStation.id = "[" + i + "]";
                                i++;
                                content.goDirection.Add(newStation);
                            }
                        }
                        isOldData = true;
                        Console.WriteLine("Old bus: " + content.id);
                        break;
                    }
                }

                if (!isOldData)
                {
                    BusRoute newStationCollection = new BusRoute();
                    newStationCollection.id            = bus.name.Split(']')[0].TrimStart('[');
                    newStationCollection.goDirection   = new ObservableCollection <LocationPointWithId>();
                    newStationCollection.backDirection = new ObservableCollection <LocationPointWithId>();
                    if (bus.directionRouteCollection.Count == 0)
                    {
                        continue;
                    }
                    if (bus.directionRouteCollection[0].isGo)
                    {
                        //Correct go direction
                        int i = 1;
                        foreach (GPSPoint station in bus.directionRouteCollection[0].routePoints)
                        {
                            LocationPointWithId newStation = new LocationPointWithId(station);
                            newStation.id = "[" + i + "]";
                            i++;
                            newStationCollection.goDirection.Add(newStation);
                        }
                        i = 1;
                        foreach (GPSPoint station in bus.directionRouteCollection[1].routePoints)
                        {
                            LocationPointWithId newStation = new LocationPointWithId(station);
                            newStation.id = "[" + i + "]";
                            i++;
                            newStationCollection.backDirection.Add(newStation);
                        }
                    }
                    else
                    {
                        int i = 1;
                        foreach (GPSPoint station in bus.directionRouteCollection[0].routePoints)
                        {
                            LocationPointWithId newStation = new LocationPointWithId(station);
                            newStation.id = "[" + i + "]";
                            i++;
                            newStationCollection.backDirection.Add(newStation);
                        }
                        i = 1;
                        foreach (GPSPoint station in bus.directionRouteCollection[1].routePoints)
                        {
                            LocationPointWithId newStation = new LocationPointWithId(station);
                            newStation.id = "[" + i + "]";
                            i++;
                            newStationCollection.goDirection.Add(newStation);
                        }
                    }

                    Console.WriteLine("Strange bus added to updated data: " + bus.name);
                }
            }

            //Write Data
            Object2Xml(_busRoute, "FullBusRoute");

            //Update StationList.xml
            _stationTotal = new ObservableCollection <StationTotal>();
            int          StationListIndex = 0;
            UtmConverter converter;
            foreach (GeneralStation station in generalStationList.generalStationCollection)
            {
                StationTotal newStation = new StationTotal();
                newStation.id = StationListIndex.ToString();
                StationListIndex++;
                converter = new UtmConverter();
                converter.ToUTM(Convert.ToDouble(station.lat), Convert.ToDouble(station.lon));
                //newStation.latitude = converter.X;
                //newStation.longitude = converter.Y;
                newStation.latitude        = Convert.ToDouble(station.lon);
                newStation.longitude       = Convert.ToDouble(station.lat);
                newStation.stationId       = station.stationId.ToString();
                newStation.addressNum      = station.name;
                newStation.addressStreet   = station.address;
                newStation.addressDistrict = station.address.Split(',').LastOrDefault().Trim();

                newStation.busList = new ObservableCollection <Bus>();
                foreach (ThroughStationBus throughStationBus in station.throughStationBusCollection)
                {
                    Bus newBus = new Bus();
                    newBus.busNumber = throughStationBus.name.Split(']')[0].TrimStart('[');
                    if (newBus.busNumber.Contains("-"))
                    {
                        break;
                    }
                    else
                    {
                        newBus.busNumber = Convert.ToInt32(newBus.busNumber).ToString();
                    }
                    newBus.name         = throughStationBus.name;
                    newBus.busDirection = new ObservableCollection <Direction>();
                    if (throughStationBus.direction == DirectionType.Go)
                    {
                        Direction newD = new Direction();
                        newD.direction = 0.ToString();
                        newBus.busDirection.Add(newD);
                        Console.WriteLine("Go Direction added: " + newBus.busNumber);
                    }
                    if (throughStationBus.direction == DirectionType.Back)
                    {
                        Direction newD = new Direction();
                        newD.direction = 1.ToString();
                        newBus.busDirection.Add(newD);
                        Console.WriteLine("Back Direction added: " + newBus.busNumber);
                    }
                    if (throughStationBus.direction == DirectionType.Both)
                    {
                        Direction newD = new Direction();
                        newD.direction = 0.ToString();
                        newBus.busDirection.Add(newD);

                        Direction newD2 = new Direction();
                        newD2.direction = 1.ToString();
                        newBus.busDirection.Add(newD2);

                        Console.WriteLine("Both Direction added: " + newBus.busNumber);
                    }

                    newStation.busList.Add(newBus);
                    Console.WriteLine("New bus added: " + newBus.busNumber);
                }

                _stationTotal.Add(newStation);
                Console.WriteLine("Station added: " + newStation.stationId);
            }

            //Write Data
            Object2Xml(_stationTotal, "StationList");
        }
Example #19
0
 public ICollection <StationMaterialsTask> GetStationMaterialTasks(IUnitOfWork uow, RouteStation station)
 {
     return(RoutingRepository.GetStationMaterialTasks(uow, station));
 }
        public RouteDTO FormatRouteToRouteDTO(Route route)
        {
            RouteDTO     routeDTO = new RouteDTO();
            RouteStation cur      = route.LastStation;

            routeDTO.DestStationName = cur.Station.StationName;
            string         prevLine          = null;
            Stack <string> instructionStack  = new Stack <string>();
            Stack <string> routeStationCodes = new Stack <string>();
            int            numStations       = 0;

            while (cur != null)
            {
                RouteStation prevStation = cur.PrevStation;
                if (prevStation != null)
                {
                    HashSet <string> matchingLines = GetMatchingLines(cur.Station.AlternativeStationCodes, prevStation.Station.AlternativeStationCodes);
                    //mrt line for this station can be determined
                    if (matchingLines.Count == 1)
                    {
                        string matchedLine = matchingLines.First();
                        //if mrt line for the determined station is not the same as prev mrt line
                        if (prevLine != null && prevLine != matchedLine)
                        {
                            instructionStack.Push(string.Format(Consts.CHANGE_LINE_FORMAT, matchedLine, prevLine));
                        }
                        instructionStack.Push(string.Format(Consts.GO_TO_NEXT_STATION_FORMAT, matchedLine, prevStation.Station.StationName,
                                                            cur.Station.StationName));

                        prevLine = matchedLine;
                    }
                    else
                    {
                        //if there is more than 1 possible mrt line
                        foreach (string line in matchingLines)
                        {
                            if (prevLine == null)
                            {
                                prevLine = cur.Station.AlternativeStationCodes.First().Substring(0, 2);
                            }
                            if (line == prevLine)
                            {
                                instructionStack.Push(string.Format(Consts.GO_TO_NEXT_STATION_FORMAT, prevLine, prevStation.Station.StationName,
                                                                    cur.Station.StationName));
                            }
                        }
                    }
                }
                routeStationCodes.Push(cur.Station.GetStationCodeByMrtLine(prevLine));

                if (cur.PrevStation == null)
                {
                    routeDTO.SourceStationName = cur.Station.StationName;
                }

                cur = cur.PrevStation;
                numStations++;
            }


            List <string> instructions = new List <string>();

            while (instructionStack.Count > 0)
            {
                instructions.Add(instructionStack.Pop());
            }

            List <string> routeStations = new List <string>();

            while (routeStationCodes.Count > 0)
            {
                routeStations.Add(routeStationCodes.Pop());
            }
            routeDTO.Instructions   = instructions;
            routeDTO.TotalDurations = route.TotalDuration;
            routeDTO.TotalStations  = numStations;
            routeDTO.RouteStations  = routeStations;

            return(routeDTO);
        }
Example #21
0
        /// <inheritdoc/>
        public override void Update(double TimeElapsed)
        {
            if (State == TrainState.Pending)
            {
                // pending train
                bool   forceIntroduction = !IsPlayerTrain && TrainManagerBase.currentHost.SimulationState != SimulationState.MinimalisticSimulation;
                double time = 0.0;
                if (!forceIntroduction)
                {
                    for (int i = 0; i < TrainManagerBase.CurrentRoute.Stations.Length; i++)
                    {
                        if (TrainManagerBase.CurrentRoute.Stations[i].StopMode == StationStopMode.AllStop | TrainManagerBase.CurrentRoute.Stations[i].StopMode == StationStopMode.PlayerPass)
                        {
                            if (TrainManagerBase.CurrentRoute.Stations[i].ArrivalTime >= 0.0)
                            {
                                time = TrainManagerBase.CurrentRoute.Stations[i].ArrivalTime;
                            }
                            else if (TrainManagerBase.CurrentRoute.Stations[i].DepartureTime >= 0.0)
                            {
                                time = TrainManagerBase.CurrentRoute.Stations[i].DepartureTime - TrainManagerBase.CurrentRoute.Stations[i].StopTime;
                            }

                            break;
                        }
                    }

                    time -= TimetableDelta;
                }

                if (TrainManagerBase.CurrentRoute.SecondsSinceMidnight >= time | forceIntroduction)
                {
                    bool introduce = true;
                    if (!forceIntroduction)
                    {
                        if (CurrentSectionIndex >= 0 && TrainManagerBase.CurrentRoute.Sections.Length > CurrentSectionIndex)
                        {
                            if (!TrainManagerBase.CurrentRoute.Sections[CurrentSectionIndex].IsFree())
                            {
                                introduce = false;
                            }
                        }
                    }

                    if (this == TrainManagerBase.PlayerTrain && TrainManagerBase.currentHost.SimulationState != SimulationState.Loading)
                    {
                        /* Loading has finished, but we still have an AI train in the current section
                         * This may be caused by an iffy RunInterval value, or simply by having no sections							 *
                         *
                         * We must introduce the player's train as otherwise the cab and loop sounds are missing
                         * NOTE: In this case, the signalling cannot prevent the player from colliding with
                         * the AI train
                         */

                        introduce = true;
                    }

                    if (introduce)
                    {
                        // train is introduced
                        State = TrainState.Available;
                        for (int j = 0; j < Cars.Length; j++)
                        {
                            if (Cars[j].CarSections.Length != 0)
                            {
                                if (j == DriverCar && IsPlayerTrain && TrainManagerBase.CurrentOptions.InitialViewpoint == 0)
                                {
                                    Cars[j].ChangeCarSection(CarSectionType.Interior);
                                }
                                else
                                {
                                    /*
                                     * HACK: Load in exterior mode first to ensure everything is cached
                                     * before switching immediately to not visible
                                     * https://github.com/leezer3/OpenBVE/issues/226
                                     * Stuff like the R142A really needs to downsize the textures supplied,
                                     * but we have no control over external factors....
                                     */
                                    Cars[j].ChangeCarSection(CarSectionType.Exterior);
                                    if (IsPlayerTrain && TrainManagerBase.CurrentOptions.InitialViewpoint == 0)
                                    {
                                        Cars[j].ChangeCarSection(CarSectionType.NotVisible, true);
                                    }
                                }
                            }

                            Cars[j].FrontBogie.ChangeSection(!IsPlayerTrain ? 0 : -1);
                            Cars[j].RearBogie.ChangeSection(!IsPlayerTrain ? 0 : -1);
                            Cars[j].Coupler.ChangeSection(!IsPlayerTrain ? 0 : -1);

                            if (Cars[j].Specs.IsMotorCar && Cars[j].Sounds.Loop != null)
                            {
                                Cars[j].Sounds.Loop.Play(Cars[j], true);
                            }
                        }
                    }
                }
            }
            else if (State == TrainState.Available)
            {
                // available train
                UpdatePhysicsAndControls(TimeElapsed);
                if (CurrentSpeed > CurrentRouteLimit)
                {
                    if (previousRouteLimit != CurrentRouteLimit || TrainManagerBase.CurrentOptions.GameMode == GameMode.Arcade)
                    {
                        /*
                         * HACK: If the limit has changed, or we are in arcade mode, notify the player
                         *       This conforms to the original behaviour, but doesn't need to raise the message from the event.
                         */
                        TrainManagerBase.currentHost.AddMessage(Translations.GetInterfaceString("message_route_overspeed"), MessageDependency.RouteLimit, GameMode.Normal, MessageColor.Orange, double.PositiveInfinity, null);
                    }
                }

                if (TrainManagerBase.CurrentOptions.Accessibility)
                {
                    if (previousRouteLimit != CurrentRouteLimit)
                    {
                        //Show for 10s and announce the current speed limit if screen reader present
                        TrainManagerBase.currentHost.AddMessage(Translations.GetInterfaceString("message_route_newlimit"), MessageDependency.AccessibilityHelper, GameMode.Normal, MessageColor.White, TrainManagerBase.currentHost.InGameTime + 10.0, null);
                    }

                    Section nextSection = TrainManagerBase.CurrentRoute.NextSection(FrontCarTrackPosition());
                    if (nextSection != null)
                    {
                        //If we find an appropriate signal, and the distance to it is less than 500m, announce if screen reader is present
                        //Aspect announce to be triggered via a separate keybind
                        double tPos = nextSection.TrackPosition - FrontCarTrackPosition();
                        if (!nextSection.AccessibilityAnnounced && tPos < 500)
                        {
                            string s = Translations.GetInterfaceString("message_route_nextsection").Replace("[distance]", $"{tPos:0.0}") + "m";
                            TrainManagerBase.currentHost.AddMessage(s, MessageDependency.AccessibilityHelper, GameMode.Normal, MessageColor.White, TrainManagerBase.currentHost.InGameTime + 10.0, null);
                            nextSection.AccessibilityAnnounced = true;
                        }
                    }
                    RouteStation nextStation = TrainManagerBase.CurrentRoute.NextStation(FrontCarTrackPosition());
                    if (nextStation != null)
                    {
                        //If we find an appropriate signal, and the distance to it is less than 500m, announce if screen reader is present
                        //Aspect announce to be triggered via a separate keybind
                        double tPos = nextStation.DefaultTrackPosition - FrontCarTrackPosition();
                        if (!nextStation.AccessibilityAnnounced && tPos < 500)
                        {
                            string s = Translations.GetInterfaceString("message_route_nextstation").Replace("[distance]", $"{tPos:0.0}") + "m".Replace("[name]", nextStation.Name);
                            TrainManagerBase.currentHost.AddMessage(s, MessageDependency.AccessibilityHelper, GameMode.Normal, MessageColor.White, TrainManagerBase.currentHost.InGameTime + 10.0, null);
                            nextStation.AccessibilityAnnounced = true;
                        }
                    }
                }
                previousRouteLimit = CurrentRouteLimit;
                if (TrainManagerBase.CurrentOptions.GameMode == GameMode.Arcade)
                {
                    if (CurrentSectionLimit == 0.0)
                    {
                        TrainManagerBase.currentHost.AddMessage(Translations.GetInterfaceString("message_signal_stop"), MessageDependency.PassedRedSignal, GameMode.Normal, MessageColor.Red, double.PositiveInfinity, null);
                    }
                    else if (CurrentSpeed > CurrentSectionLimit)
                    {
                        TrainManagerBase.currentHost.AddMessage(Translations.GetInterfaceString("message_signal_overspeed"), MessageDependency.SectionLimit, GameMode.Normal, MessageColor.Orange, double.PositiveInfinity, null);
                    }
                }

                if (AI != null)
                {
                    AI.Trigger(TimeElapsed);
                }
            }
            else if (State == TrainState.Bogus)
            {
                // bogus train
                if (AI != null)
                {
                    AI.Trigger(TimeElapsed);
                }
            }

            //Trigger point sounds if appropriate
            for (int i = 0; i < Cars.Length; i++)
            {
                CarSound c = null;
                if (Cars[i].FrontAxle.PointSoundTriggered)
                {
                    Cars[i].FrontAxle.PointSoundTriggered = false;
                    int bufferIndex = Cars[i].FrontAxle.RunIndex;
                    if (bufferIndex > Cars[i].FrontAxle.PointSounds.Length - 1)
                    {
                        //If the switch sound does not exist, return zero
                        //Required to handle legacy trains which don't have idx specific run sounds defined
                        bufferIndex = 0;
                    }

                    if (Cars[i].FrontAxle.PointSounds == null || Cars[i].FrontAxle.PointSounds.Length == 0)
                    {
                        //No point sounds defined at all
                        continue;
                    }

                    c = (CarSound)Cars[i].FrontAxle.PointSounds[bufferIndex];
                    if (c.Buffer == null)
                    {
                        c = (CarSound)Cars[i].FrontAxle.PointSounds[0];
                    }
                }

                if (c != null)
                {
                    double spd   = Math.Abs(CurrentSpeed);
                    double pitch = spd / 12.5;
                    double gain  = pitch < 0.5 ? 2.0 * pitch : 1.0;
                    if (pitch > 0.2 && gain > 0.2)
                    {
                        c.Play(pitch, gain, Cars[i], false);
                    }
                }
            }
        }
Example #22
0
        private void LoadEditors(RouteStation station)
        {
            // Guard
            if (station == null)
            {
                return;
            }

            ClearEditors();
            m_routeStation = station;

            Bind();

            LoadOutcomes();
            LoadDocuments();
            LoadFailures();
            processBinding.Clear();
            processBinding.ResetBindings(false);

            // Verify there is a step configuration
            // for this part at this station
            if (!ConfigDefinedForPart(m_item.Part))
            {
                return;
            }

            // Sort the collection by seq no.
            m_process.SortResultsBySeqNo();

            try
            {
                stepsLayout.SuspendLayout();
                foreach (RouteStationResult result in m_process.Results)
                {
                    processBinding.Add(result);

                    Control control;

                    if (result.Step.ResultList != null)
                    {
                        control = new StationStepLookUpMapper().MapFrom(result);
                        stepsLayout.AddItem(result.Step.DisplayPrompt, control);
                    }
                    else
                    {
                        control = new StationStepTextEditMapper().MapFrom(result);
                        stepsLayout.AddItem(result.Step.DisplayPrompt, control);
                    }

                    // Additional Layout Item Formatting
                    LayoutControlItem layoutItem =
                        stepsLayout.GetItemByControl(control);
                    if (layoutItem != null)
                    {
                        //Make the required fields captions bold.
                        if (result.Step.Required)
                        {
                            layoutItem.AppearanceItemCaption.Font =
                                new Font("Verdana", 8.25F, FontStyle.Bold);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Scout.Core.UserInteraction.Dialog.ShowMessage(ex.Message,
                                                              UserMessageType.Error);
            }
            finally
            {
                stepsLayout.ResumeLayout(true);
            }
        }