diff --git a/.gitignore b/.gitignore index fdab9c6cdc..c78c509839 100644 --- a/.gitignore +++ b/.gitignore @@ -365,5 +365,4 @@ ASALocalRun/ healthchecksdb # Backup folder for Package Reference Convert tool in Visual Studio 2017 -MigrationBackup/ -/Source/RunActivity/Properties/launchSettings.json +MigrationBackup/ \ No newline at end of file diff --git a/Source/ORTS.Common/Input/UserCommand.cs b/Source/ORTS.Common/Input/UserCommand.cs index ede4219cb4..c06a814728 100644 --- a/Source/ORTS.Common/Input/UserCommand.cs +++ b/Source/ORTS.Common/Input/UserCommand.cs @@ -24,7 +24,6 @@ public enum UserCommand [GetString("Game Change Cab")] GameChangeCab, [GetString("Game Request Control")] GameRequestControl, [GetString("Game Multi Player Dispatcher")] GameMultiPlayerDispatcher, - [GetString("Game Multi Player Dispatcher Beta")] GameMultiPlayerDispatcherBeta, [GetString("Game Multi Player Texting")] GameMultiPlayerTexting, [GetString("Game Switch Manual Mode")] GameSwitchManualMode, [GetString("Game Reset Out Of Control Mode")] GameResetOutOfControlMode, @@ -62,8 +61,6 @@ public enum UserCommand [GetString("Debug Precipitation Decrease")] DebugPrecipitationDecrease, [GetString("Debug Precipitation Liquidity Increase")] DebugPrecipitationLiquidityIncrease, [GetString("Debug Precipitation Liquidity Decrease")] DebugPrecipitationLiquidityDecrease, - [GetString("Debug Daylight Offset Increase")] DebugDaylightOffsetIncrease, - [GetString("Debug Daylight Offset Decrease")] DebugDaylightOffsetDecrease, [GetString("Debug Weather Change")] DebugWeatherChange, [GetString("Debug Clock Forwards")] DebugClockForwards, [GetString("Debug Clock Backwards")] DebugClockBackwards, diff --git a/Source/ORTS.Settings/InputSettings.cs b/Source/ORTS.Settings/InputSettings.cs index d2ea54f6c8..e94ace6e7e 100644 --- a/Source/ORTS.Settings/InputSettings.cs +++ b/Source/ORTS.Settings/InputSettings.cs @@ -480,8 +480,6 @@ static void InitializeCommands(UserCommandInput[] Commands) Commands[(int)UserCommand.DebugLockShadows] = new UserCommandKeyInput(0x1F, KeyModifiers.Control | KeyModifiers.Alt); Commands[(int)UserCommand.DebugLogger] = new UserCommandKeyInput(0x58); Commands[(int)UserCommand.DebugLogRenderFrame] = new UserCommandKeyInput(0x58, KeyModifiers.Alt); - Commands[(int)UserCommand.DebugDaylightOffsetDecrease] = new UserCommandKeyInput(0x0C, KeyModifiers.Shift | KeyModifiers.Alt); - Commands[(int)UserCommand.DebugDaylightOffsetIncrease] = new UserCommandKeyInput(0x0D, KeyModifiers.Shift | KeyModifiers.Alt); Commands[(int)UserCommand.DebugOvercastDecrease] = new UserCommandKeyInput(0x0C, KeyModifiers.Control); Commands[(int)UserCommand.DebugOvercastIncrease] = new UserCommandKeyInput(0x0D, KeyModifiers.Control); Commands[(int)UserCommand.DebugPhysicsForm] = new UserCommandKeyInput(0x3D, KeyModifiers.Alt); @@ -522,7 +520,6 @@ static void InitializeCommands(UserCommandInput[] Commands) Commands[(int)UserCommand.GameExternalCabController] = new UserCommandKeyInput(0x29); Commands[(int)UserCommand.GameFullscreen] = new UserCommandKeyInput(0x1C, KeyModifiers.Alt); Commands[(int)UserCommand.GameMultiPlayerDispatcher] = new UserCommandKeyInput(0x0A, KeyModifiers.Control); - Commands[(int)UserCommand.GameMultiPlayerDispatcherBeta] = new UserCommandKeyInput(0x0A, KeyModifiers.Control | KeyModifiers.Shift); Commands[(int)UserCommand.GameMultiPlayerTexting] = new UserCommandKeyInput(0x14, KeyModifiers.Alt); Commands[(int)UserCommand.GamePause] = new UserCommandKeyInput(Keys.Pause); Commands[(int)UserCommand.GamePauseMenu] = new UserCommandKeyInput(0x01); diff --git a/Source/Orts.Simulation/Simulation/AIs/AI.cs b/Source/Orts.Simulation/Simulation/AIs/AI.cs index 6331fea0f4..c33219bb1b 100644 --- a/Source/Orts.Simulation/Simulation/AIs/AI.cs +++ b/Source/Orts.Simulation/Simulation/AIs/AI.cs @@ -21,40 +21,37 @@ * Currently, AI trains are created at startup and moved down 1000 meters to make them * invisible. This is done so the rendering code can discover the model it needs to draw. * - * */ -// // Flag to print deadlock info // #define DEBUG_DEADLOCK // #define DEBUG_TRACEINFO -// +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; using Orts.Formats.Msts; using Orts.MultiPlayer; using Orts.Simulation.Physics; using Orts.Simulation.RollingStocks; -using Orts.Simulation.Timetables; using Orts.Simulation.RollingStocks.SubSystems; -using Orts.Simulation.Signalling; +using Orts.Simulation.Timetables; using ORTS.Common; using ORTS.Scripting.Api; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; namespace Orts.Simulation.AIs { public class AI { public readonly Simulator Simulator; - public List AITrains = new List();// active AI trains + public List AITrains = new List(); // Active AI trains - public StartTrains StartList = new StartTrains(); // trains yet to be started - public List AutoGenTrains = new List(); // auto-generated trains - public double clockTime; // clock time : local time before activity start, common time from simulator after start - private bool localTime; // if true : clockTime is local time + public StartTrains StartList = new StartTrains(); // Trains yet to be started + public List AutoGenTrains = new List(); // Auto-generated trains + public double clockTime; // Clock time: local time before activity start, common time from simulator after start + private bool localTime; // If true: clockTime is local time public List TrainsToRemove = new List(); public List TrainsToAdd = new List(); public List TrainsToRemoveFromAI = new List(); @@ -68,14 +65,12 @@ public class AI public AI(Simulator simulator, CancellationToken cancellation, double activityStartTime) { Simulator = simulator; -#if WITH_PATH_DEBUG +#if WITH_PATH_DEBUG if (File.Exists(@"C:\temp\checkpath.txt")) { File.Delete(@"C:\temp\checkpath.txt"); } - - #endif if (simulator.Activity != null && simulator.Activity.Tr_Activity.Tr_Activity_File.Traffic_Definition != null) { @@ -83,20 +78,20 @@ public AI(Simulator simulator, CancellationToken cancellation, double activitySt foreach (var sd in activityFile.Traffic_Definition.ServiceDefinitionList) { AITrain train = CreateAITrain(sd, activityFile.Traffic_Definition.TrafficFile.TrafficDefinition, simulator.TimetableMode); - if (cancellation.IsCancellationRequested) // ping loader watchdog + if (cancellation.IsCancellationRequested) // Ping loader watchdog return; } } - // prerun trains + // Prerun trains PrerunAI(cancellation); clockTime = Simulator.ClockTime; localTime = false; } - // constructor for Timetable trains - // trains allready have a number - must not be changed! + // Constructor for Timetable trains + // Trains allready have a number - must not be changed! public AI(Simulator simulator, List allTrains, ref double ClockTime, int playerTrainOriginalTrain, TTTrain.FormCommand playerTrainFormedOfType, TTTrain playerTrain, CancellationToken cancellation) { Simulator = simulator; @@ -122,35 +117,33 @@ public AI(Simulator simulator, List allTrains, ref double ClockTime, in AutoGenTrains.Add(train); Simulator.AutoGenDictionary.Add(train.Number, train); } - - // set train details else { + // Set train details train.TrainType = Train.TRAINTYPE.AI_NOTSTARTED; train.AI = this; - if (train.Cars.Count > 0) train.Cars[0].Headlight = 2;//AI train always has light on + if (train.Cars.Count > 0) train.Cars[0].Headlight = 2; // AI train always has light on train.BrakeLine3PressurePSI = 0; - // insert in start list - + // Insert in start list StartList.InsertTrain(train); Simulator.StartReference.Add(train.Number); } } - // clear dictionary (no trains yet exist) + // Clear dictionary (no trains yet exist) Simulator.TrainDictionary.Clear(); Simulator.NameDictionary.Clear(); - // prerun trains + // Prerun trains PrerunAI(playerTrainOriginalTrain, playerTrainFormedOfType, playerTrain, cancellation); ClockTime = clockTime; localTime = false; } - // restore game state + // Restore game state public AI(Simulator simulator, BinaryReader inf) { Debug.Assert(simulator.Trains != null, "Cannot restore AI without Simulator.Trains."); @@ -162,9 +155,9 @@ public AI(Simulator simulator, BinaryReader inf) { string trainType = inf.ReadString(); - // activity mode trains if (String.Equals(trainType, "AI")) { + // Activity mode trains AITrain aiTrain = new AITrain(Simulator, inf, this); AITrains.Add(aiTrain); Simulator.Trains.Add(aiTrain); @@ -172,11 +165,11 @@ public AI(Simulator simulator, BinaryReader inf) if (!Simulator.NameDictionary.ContainsKey(aiTrain.Name.ToLower())) Simulator.NameDictionary.Add(aiTrain.Name.ToLower(), aiTrain); } - - // timetable mode trains - else { + else + { + // Timetable mode trains TTTrain aiTrain = new TTTrain(Simulator, inf, this); - if (aiTrain.TrainType != Train.TRAINTYPE.PLAYER) // add to AITrains except when it is player train + if (aiTrain.TrainType != Train.TRAINTYPE.PLAYER) // Add to AITrains except when it is player train { AITrains.Add(aiTrain); } @@ -231,10 +224,10 @@ public AI(Simulator simulator, BinaryReader inf) if (Simulator.PlayerLocomotive != null) { - if (Simulator.PlayerLocomotive.Train is AITrain) ((AITrain)Simulator.PlayerLocomotive.Train).AI = this; + if (Simulator.PlayerLocomotive.Train is AITrain train) train.AI = this; } - // in timetable mode : find player train and place it in Simulator.Trains on position 0. + // In timetable mode: find player train and place it in Simulator.Trains on position 0. if (Simulator.TimetableMode) { int playerindex = -1; @@ -248,9 +241,8 @@ public AI(Simulator simulator, BinaryReader inf) if (playerindex > 0) { - var tmptrain = Simulator.Trains[playerindex]; - Simulator.Trains[playerindex] = Simulator.Trains[0]; - Simulator.Trains[0] = tmptrain; + // Tuple to swap values + (Simulator.Trains[0], Simulator.Trains[playerindex]) = (Simulator.Trains[playerindex], Simulator.Trains[0]); } Simulator.PlayerLocomotive = Simulator.Trains[0].LeadLocomotive; @@ -258,12 +250,11 @@ public AI(Simulator simulator, BinaryReader inf) } // Restore in autopilot mode - public AI(Simulator simulator, BinaryReader inf, bool autopilot) { Debug.Assert(simulator.Trains != null, "Cannot restore AI without Simulator.Trains."); Simulator = simulator; - string trainType = inf.ReadString(); // may be ignored, can be AI only + string trainType = inf.ReadString(); // May be ignored, can be AI only AITrain aiTrain = new AITrain(Simulator, inf, this); int PlayerLocomotiveIndex = inf.ReadInt32(); if (PlayerLocomotiveIndex >= 0) Simulator.PlayerLocomotive = aiTrain.Cars[PlayerLocomotiveIndex]; @@ -275,14 +266,13 @@ public AI(Simulator simulator) Simulator = simulator; } - // save game state + // Save game state public void Save(BinaryWriter outf) { + RemoveTrains(); // Remove trains waiting to be removed + AddTrains(); // Add trains waiting to be added - RemoveTrains(); // remove trains waiting to be removed - AddTrains(); // add trains waiting to be added - - // in timetable mode, include player train train[0] + // In timetable mode, include player train train[0] if (Simulator.TimetableMode) { outf.Write(AITrains.Count + 1); @@ -329,7 +319,7 @@ public void SaveAutopil(Train train, BinaryWriter outf) else outf.Write(-1); } - // prerun for activity mode + // Prerun for activity mode private void PrerunAI(CancellationToken cancellation) { float firstAITime = StartList.GetNextTime(); @@ -337,13 +327,12 @@ private void PrerunAI(CancellationToken cancellation) { Trace.Write("\n Run AI : " + StartList.Count.ToString() + " "); - // perform update for AI trains upto actual start time - + // Perform update for AI trains upto actual start time clockTime = firstAITime - 1.0f; localTime = true; Simulator.PreUpdate = true; - for (double runTime = firstAITime; runTime < Simulator.ClockTime; runTime += 5.0) // update with 5 secs interval + for (double runTime = firstAITime; runTime < Simulator.ClockTime; runTime += 5.0) // Update with 5 secs interval { int fullsec = Convert.ToInt32(runTime); if (fullsec % 3600 == 0) Trace.Write(" " + (fullsec / 3600).ToString("00") + ":00 "); @@ -351,13 +340,12 @@ private void PrerunAI(CancellationToken cancellation) AIUpdate((float)(runTime - clockTime), Simulator.PreUpdate); Simulator.Signals.Update(true); clockTime = runTime; - if (cancellation.IsCancellationRequested) return; // ping watchdog process + if (cancellation.IsCancellationRequested) return; // Ping watchdog process } } } - - // prerun for timetable mode + // Prerun for timetable mode private void PrerunAI(int playerTrainOriginalTrain, TTTrain.FormCommand playerTrainFormedOfType, TTTrain playerTrain, CancellationToken cancellation) { bool endPreRun = false; @@ -367,13 +355,12 @@ private void PrerunAI(int playerTrainOriginalTrain, TTTrain.FormCommand playerTr { Trace.Write("\n Run AI : " + StartList.Count.ToString() + " "); - // perform update for AI trains upto actual start time - + // Perform update for AI trains upto actual start time clockTime = firstAITime - 1.0f; localTime = true; Simulator.PreUpdate = true; bool activeTrains = false; - for (double runTime = firstAITime; runTime < Simulator.ClockTime && !endPreRun; runTime += 5.0) // update with 5 secs interval + for (double runTime = firstAITime; runTime < Simulator.ClockTime && !endPreRun; runTime += 5.0) // Update with 5 secs interval { var loaderSpan = (float)TimetableInfo.PlayerTrainOriginalStartTime - firstAITime; Simulator.TimetableLoadedFraction = ((float)runTime - firstAITime) / loaderSpan; @@ -389,20 +376,20 @@ private void PrerunAI(int playerTrainOriginalTrain, TTTrain.FormCommand playerTr } clockTime = runTime; - if (cancellation.IsCancellationRequested) return; // ping watchdog process + if (cancellation.IsCancellationRequested) return; // Ping watchdog process } - // prerun finished - check if train from which player train originates has run and is finished + // Prerun finished - check if train from which player train originates has run and is finished bool delayedrun = false; bool OrgTrainNotStarted = false; TTTrain OrgTrain = null; TTTrain PlayTrain = null; - // player train is pre-created - check if it exists already + // Player train is pre-created - check if it exists already if (playerTrainFormedOfType == TTTrain.FormCommand.Created) { PlayTrain = Simulator.Trains.GetAITrainByNumber(0) as TTTrain; - // train exists - set as player train + // Train exists - set as player train if (PlayTrain != null) { PlayTrain.TrainType = Train.TRAINTYPE.PLAYER; @@ -413,14 +400,13 @@ private void PrerunAI(int playerTrainOriginalTrain, TTTrain.FormCommand playerTr Trace.TraceInformation("Player train start delayed as track is not clear"); delayedrun = true; - // reset formed state as train can now be started directly + // Reset formed state as train can now be started directly playerTrainOriginalTrain = -1; } } - - // player train is extracted from pool else if (!String.IsNullOrEmpty(playerTrain.CreateFromPool)) { + // Player train is extracted from pool TimetablePool.TrainFromPool extractResult = TimetablePool.TrainFromPool.Failed; if (Simulator.PoolHolder.Pools.ContainsKey(playerTrain.CreateFromPool)) { @@ -433,29 +419,29 @@ private void PrerunAI(int playerTrainOriginalTrain, TTTrain.FormCommand playerTr Trace.TraceError("Player train {0} : Invalid pool definition : {1} : pool not found", playerTrain.Name, playerTrain.CreateFromPool); } - // switch on outcome + // Switch on outcome switch (extractResult) { - // train formed : no further action + // Train formed: no further action case TimetablePool.TrainFromPool.Formed: break; - // train creation failed : no need to try again (will fail again), so abandone + // Train creation failed: no need to try again (will fail again), so abandone case TimetablePool.TrainFromPool.Failed: throw new InvalidDataException("Session aborted - cannot extract required engine from pool"); - // not created but not failed : hold, try again in 30 secs. + // Not created but not failed: hold, try again in 30 secs. case TimetablePool.TrainFromPool.NotCreated: delayedrun = true; break; - // forced created away from pool : create train + // Forced created away from pool: create train case TimetablePool.TrainFromPool.ForceCreated: break; } } - // player train is formed out of other train + // Player train is formed out of other train else if (playerTrainOriginalTrain > 0 && (playerTrainFormedOfType == TTTrain.FormCommand.TerminationFormed || playerTrainFormedOfType == TTTrain.FormCommand.TerminationTriggered)) { OrgTrainNotStarted = Simulator.Trains.CheckTrainNotStartedByNumber(playerTrainOriginalTrain); @@ -476,11 +462,11 @@ private void PrerunAI(int playerTrainOriginalTrain, TTTrain.FormCommand playerTr } } - // if player train is detached from other train + // If player train is detached from other train else if (playerTrainOriginalTrain > 0 && playerTrainFormedOfType == TTTrain.FormCommand.Detached) { PlayTrain = Simulator.Trains.GetAITrainByNumber(0) as TTTrain; - // train exists - set as player train + // Train exists - set as player train if (PlayTrain != null) { PlayTrain.TrainType = Train.TRAINTYPE.PLAYER; @@ -504,7 +490,7 @@ private void PrerunAI(int playerTrainOriginalTrain, TTTrain.FormCommand playerTr } } - // if player train exists but cannot be placed or has no power + // If player train exists but cannot be placed or has no power else if (playerTrain != null) { bool playerHasValidPosition = false; @@ -523,7 +509,7 @@ private void PrerunAI(int playerTrainOriginalTrain, TTTrain.FormCommand playerTr } } - // if player train exists, also check if it has an engine + // If player train exists, also check if it has an engine if (!delayedrun && playerTrain != null) { if (Simulator.PlayerLocomotive == null) @@ -533,12 +519,12 @@ private void PrerunAI(int playerTrainOriginalTrain, TTTrain.FormCommand playerTr } } - // continue prerun until player train can be started + // Continue prerun until player train can be started if (delayedrun) { - bool dummy = true; // dummy boolead for ActiveTrains + bool dummy = true; // Dummy boolead for ActiveTrains - float deltaTime = 5.0f; // update with 1 sec. interval + float deltaTime = 5.0f; // Update with 1 sec. interval double runTime = Simulator.ClockTime - (double)deltaTime; bool playerTrainStarted = false; @@ -548,13 +534,13 @@ private void PrerunAI(int playerTrainOriginalTrain, TTTrain.FormCommand playerTr Simulator.Signals.Update(true); clockTime = runTime; runTime += deltaTime; - if (cancellation.IsCancellationRequested) // ping loader watchdog + if (cancellation.IsCancellationRequested) // Ping loader watchdog return; int fullsec = Convert.ToInt32(runTime); if (fullsec % 3600 == 0) Trace.Write(" " + (fullsec / 3600).ToString("00") + ":00 "); - if (runTime >= 24 * 3600) // end of day reached + if (runTime >= 24 * 3600) // End of day reached { if (playerTrainOriginalTrain > 0) { @@ -577,13 +563,13 @@ private void PrerunAI(int playerTrainOriginalTrain, TTTrain.FormCommand playerTr { OrgTrainNotStarted = Simulator.Trains.CheckTrainNotStartedByNumber(playerTrainOriginalTrain); OrgTrain = Simulator.Trains.GetAITrainByNumber(playerTrainOriginalTrain) as TTTrain; - playerTrainStarted = (!OrgTrainNotStarted && OrgTrain == null); + playerTrainStarted = !OrgTrainNotStarted && OrgTrain == null; } else if (playerTrainOriginalTrain > 0 && playerTrainFormedOfType == TTTrain.FormCommand.Detached) { PlayTrain = Simulator.Trains.GetAITrainByNumber(0) as TTTrain; - // train exists - set as player train - playerTrainStarted = (PlayTrain != null); + // Train exists - set as player train + playerTrainStarted = PlayTrain != null; if (playerTrain.LeadLocomotive == null) { @@ -599,31 +585,30 @@ private void PrerunAI(int playerTrainOriginalTrain, TTTrain.FormCommand playerTr TimeSpan delayedStart = new TimeSpan((long)(Math.Pow(10, 7) * (clockTime - Simulator.ClockTime))); Trace.TraceInformation("Start delayed by : {0}", delayedStart.ToString()); StartList.RemovePlayerTrain(); - TTTrain playerTTTrain = playerTrain as TTTrain; + TTTrain playerTTTrain = playerTrain; playerTTTrain.InitalizePlayerTrain(); Simulator.ClockTime = runTime; } else { - // remove player train from start list + // Remove player train from start list StartList.RemovePlayerTrain(); Trace.TraceInformation("Player train started on time"); - TTTrain playerTTTrain = playerTrain as TTTrain; + TTTrain playerTTTrain = playerTrain; playerTTTrain.InitalizePlayerTrain(); } } - - // no AI trains ahead of player train else { - // remove player train from start list + // No AI trains ahead of player train + // Remove player train from start list StartList.RemovePlayerTrain(); Trace.TraceInformation("Player train started on time"); - TTTrain playerTTTrain = playerTrain as TTTrain; + TTTrain playerTTTrain = playerTrain; playerTTTrain.InitalizePlayerTrain(); - + clockTime = Simulator.ClockTime = playerTTTrain.StartTime.Value; } @@ -644,15 +629,13 @@ public void ActivityUpdate(float elapsedClockSeconds) public void AIUpdate(float elapsedClockSeconds, bool preUpdate) { - // update clock - + // Update clock if (!localTime) { clockTime = Simulator.ClockTime; } - // check to see if any train to be added - + // Check to see if any train to be added float nextTrainTime = StartList.GetNextTime(); if (nextTrainTime > 0 && nextTrainTime < clockTime) { @@ -662,15 +645,15 @@ public void AIUpdate(float elapsedClockSeconds, bool preUpdate) Simulator.StartReference.Remove(thisTrain.Number); var validPosition = AddToWorld(thisTrain); if (thisTrain.InitialSpeed > 0 && validPosition) - // Add extra run to allow setting signals { + // Add extra run to allow setting signals thisTrain.AIPreUpdate(0); } } } foreach (AITrain train in AITrains) { - if (train.TrainType != Train.TRAINTYPE.AI_INCORPORATED && (train.Cars.Count == 0 && train.TrainType != Train.TRAINTYPE.AI_INCORPORATED || train.Cars[0].Train != train)) + if (train.TrainType != Train.TRAINTYPE.AI_INCORPORATED && ((train.Cars.Count == 0 && train.TrainType != Train.TRAINTYPE.AI_INCORPORATED) || train.Cars[0].Train != train)) TrainsToRemove.Add(train); else train.AIUpdate(elapsedClockSeconds, clockTime, preUpdate); @@ -681,25 +664,24 @@ public void AIUpdate(float elapsedClockSeconds, bool preUpdate) AddTrains(); } - // used in timetable mode + // Used in timetable mode public void TimetableUpdate(float elapsedClockSeconds) { - bool dummy = true; // dummy for activeTrains boolean + bool dummy = true; // Dummy for activeTrains boolean AITTUpdate(elapsedClockSeconds, false, ref dummy); } public bool AITTUpdate(float elapsedClockSeconds, bool preUpdate, ref bool activeTrains) { bool endPreRun = false; - // update clock + // Update clock if (!localTime) { clockTime = Simulator.ClockTime; } - // check to see if any train to be added - + // Check to see if any train to be added float nextTrainTime = StartList.GetNextTime(); if (nextTrainTime > 0 && nextTrainTime < clockTime) { @@ -714,8 +696,7 @@ public bool AITTUpdate(float elapsedClockSeconds, bool preUpdate, ref bool activ } } - // check if any active trains - + // Check if any active trains if (!activeTrains) { foreach (AITrain acttrain in AITrains) @@ -804,7 +785,7 @@ public bool AITTUpdate(float elapsedClockSeconds, bool preUpdate, ref bool activ AddTTTrains(); } } - return (endPreRun); + return endPreRun; } /// @@ -812,12 +793,11 @@ public bool AITTUpdate(float elapsedClockSeconds, bool preUpdate, ref bool activ /// private AITrain CreateAITrain(Service_Definition sd, Traffic_Traffic_Definition trd, bool isTimetableMode) { - // set up a new AI train - // first extract the service definition from the activity file - // this gives the consist and path - - // find related traffic definition + // Set up a new AI train + // First extract the service definition from the activity file + // This gives the consist and path + // Find related traffic definition Traffic_Service_Definition trfDef = null; foreach (Traffic_Service_Definition thisDef in trd.TrafficItems) { @@ -828,12 +808,11 @@ private AITrain CreateAITrain(Service_Definition sd, Traffic_Traffic_Definition break; } } - ServiceFile srvFile = new ServiceFile(Simulator.RoutePath + @"\SERVICES\" + sd.Name + ".SRV"); // read service file + ServiceFile srvFile = new ServiceFile(Simulator.RoutePath + @"\SERVICES\" + sd.Name + ".SRV"); // Read service file AITrain train = CreateAITrainDetail(sd, trfDef, srvFile, isTimetableMode, false); if (train != null) { - // insert in start list - + // Insert in start list StartList.InsertTrain(train); Simulator.StartReference.Add(train.Number); } @@ -847,14 +826,12 @@ private AITrain CreateAITrain(Service_Definition sd, Traffic_Traffic_Definition /// public AITrain CreateAITrainDetail(Service_Definition sd, Traffic_Service_Definition trfDef, ServiceFile srvFile, bool isTimetableMode, bool isInitialPlayerTrain) { - // read consist file - + // Read consist file string consistFileName = Simulator.BasePath + @"\TRAINS\CONSISTS\" + srvFile.Train_Config + ".CON"; ConsistFile conFile = new ConsistFile(consistFileName); string pathFileName = Simulator.RoutePath + @"\PATHS\" + srvFile.PathID + ".PAT"; // Patch Placingproblem - JeroenP - // #if ACTIVITY_EDITOR AIPath aiPath = new AIPath(Simulator.TDB, Simulator.TSectionDat, pathFileName, isTimetableMode, Simulator.orRouteConfig); #else @@ -879,7 +856,7 @@ public AITrain CreateAITrainDetail(Service_Definition sd, Traffic_Service_Defini if (consistFileName.Contains("tilted")) train.IsTilting = true; - // also set Route max speed for speedpost-processing in train.cs + // Also set Route max speed for speedpost-processing in train.cs train.TrainMaxSpeedMpS = (float)Simulator.TRK.Tr_RouteFile.SpeedLimit; train.InitialSpeed = srvFile.TimeTable.InitialSpeed; @@ -892,7 +869,7 @@ public AITrain CreateAITrainDetail(Service_Definition sd, Traffic_Service_Defini train.TcsParametersFileName = conFile.Train.TrainCfg.TcsParametersFileName; - // add wagons + // Add wagons train.Length = 0.0f; foreach (Wagon wagon in conFile.Train.TrainCfg.WagonList) { @@ -934,9 +911,9 @@ public AITrain CreateAITrainDetail(Service_Definition sd, Traffic_Service_Defini { Simulator.PathName = aiPath.pathName; if (MPManager.IsMultiPlayer()) - car.CarID = MPManager.GetUserName() + " - " + car.UiD; //player's train is always named train 0. + car.CarID = MPManager.GetUserName() + " - " + car.UiD; // Player's train is always named train 0. else - car.CarID = "0 - " + car.UiD; //player's train is always named train 0. + car.CarID = "0 - " + car.UiD; // Player's train is always named train 0. if (Simulator.Activity != null && car is MSTSDieselLocomotive mstsDieselLocomotive) { @@ -945,7 +922,7 @@ public AITrain CreateAITrainDetail(Service_Definition sd, Traffic_Service_Defini if (Simulator.Activity != null && car is MSTSSteamLocomotive mstsSteamLocomotive) { - mstsSteamLocomotive.CombinedTenderWaterVolumeUKG = (ORTS.Common.Kg.ToLb(mstsSteamLocomotive.MaxLocoTenderWaterMassKG) / 10.0f) * Simulator.Activity.Tr_Activity.Tr_Activity_Header.FuelWater / 100.0f; + mstsSteamLocomotive.CombinedTenderWaterVolumeUKG = ORTS.Common.Kg.ToLb(mstsSteamLocomotive.MaxLocoTenderWaterMassKG) / 10.0f * Simulator.Activity.Tr_Activity.Tr_Activity_Header.FuelWater / 100.0f; mstsSteamLocomotive.TenderCoalMassKG = mstsSteamLocomotive.MaxTenderCoalMassKG * Simulator.Activity.Tr_Activity.Tr_Activity_Header.FuelCoal / 100.0f; } @@ -958,16 +935,15 @@ public AITrain CreateAITrainDetail(Service_Definition sd, Traffic_Service_Defini car.CarID = "AI" + train.Number.ToString() + " - " + (train.Cars.Count - 1).ToString(); } - // associate location events + // Associate location events Simulator.ActivityRun.AssociateEvents(train); - } catch (Exception error) { Trace.WriteLine(new FileLoadException(wagonFilePath, error)); } - }// for each rail car + } // For each rail car if (train.Cars.Count <= 0) { @@ -975,16 +951,16 @@ public AITrain CreateAITrainDetail(Service_Definition sd, Traffic_Service_Defini return null; } - train.Cars[0].Headlight = 2;//AI train always has light on + train.Cars[0].Headlight = 2; // AI train always has light on // Patch placingproblem JeroenP (1 line) - train.RearTDBTraveller = new Traveller(Simulator.TSectionDat, Simulator.TDB.TrackDB.TrackNodes, aiPath); // create traveller + train.RearTDBTraveller = new Traveller(Simulator.TSectionDat, Simulator.TDB.TrackDB.TrackNodes, aiPath); // Create traveller #if WITH_PATH_DEBUG File.AppendAllText(@"C:\temp\checkpath.txt", "----- New AI Train -----\n"); #endif - train.CreateRoute(false); // create route without use of FrontTDBtraveller - train.CheckFreight(); // check if train is freight or passenger - train.SetDPUnitIDs(); // distributed power + train.CreateRoute(false); // Create route without use of FrontTDBtraveller + train.CheckFreight(); // Check if train is freight or passenger + train.SetDPUnitIDs(); // Distributed power if (!isInitialPlayerTrain || train.InitialSpeed != 0) train.AITrainDirectionForward = true; train.BrakeLine3PressurePSI = 0; @@ -1000,11 +976,9 @@ public AITrain CreateAITrainDetail(Service_Definition sd, Traffic_Service_Defini /// place train on required position /// initialize signals and movement /// - private bool AddToWorld(AITrain thisTrain) { - // clear track and align switches - check state - + // Clear track and align switches - check state bool validPosition = true; Train.TCSubpathRoute tempRoute = thisTrain.CalculateInitialTrainPosition(ref validPosition); @@ -1020,7 +994,7 @@ private bool AddToWorld(AITrain thisTrain) if (validPosition) { - thisTrain.actualWaitTimeS = 0; // reset wait counter // + thisTrain.actualWaitTimeS = 0; // Reset wait counter thisTrain.TrainType = Train.TRAINTYPE.AI; AITrains.Add(thisTrain); aiListChanged = true; @@ -1042,14 +1016,14 @@ private bool AddToWorld(AITrain thisTrain) if (MPManager.IsServer()) { - MPManager.BroadCast((new MSGTrain(thisTrain, thisTrain.Number)).ToString()); + MPManager.BroadCast(new MSGTrain(thisTrain, thisTrain.Number).ToString()); } } else { - thisTrain.StartTime += 30; // try again in half a minute + thisTrain.StartTime += 30; // Try again in half a minute thisTrain.actualWaitTimeS += 30; - if (thisTrain.actualWaitTimeS > 900) // tried for 15 mins + if (thisTrain.actualWaitTimeS > 900) // Tried for 15 mins { TimeSpan timeStart = new TimeSpan((long)(Math.Pow(10, 7) * thisTrain.StartTime.Value)); Trace.TraceWarning("Cannot place AI train {0} ({1}) at time {2}", thisTrain.Name, thisTrain.Number, timeStart.ToString()); @@ -1091,7 +1065,7 @@ private bool AddToWorldTT(TTTrain thisTrain, List nextTrains) bool validPosition = true; Train.TCSubpathRoute tempRoute = null; - // create from pool + // Create from pool if (!String.IsNullOrEmpty(thisTrain.CreateFromPool)) { if (!Simulator.PoolHolder.Pools.ContainsKey(thisTrain.CreateFromPool)) @@ -1110,34 +1084,34 @@ private bool AddToWorldTT(TTTrain thisTrain, List nextTrains) bool actionCompleted = false; - // switch on outcome + // Switch on outcome switch (poolResult) { - // train formed : no further action + // Train formed: no further action case TimetablePool.TrainFromPool.Formed: actionCompleted = true; break; - // train creation delayed through incoming train + // Train creation delayed through incoming train case TimetablePool.TrainFromPool.Delayed: - thisTrain.StartTime += 30; // try again in half a minute + thisTrain.StartTime += 30; // Try again in half a minute StartList.InsertTrain(thisTrain); Simulator.StartReference.Add(thisTrain.Number); actionCompleted = true; break; - // train creation failed : no need to try again (will fail again), so abandone + // Train creation failed: no need to try again (will fail again), so abandone case TimetablePool.TrainFromPool.Failed: actionCompleted = true; break; - // not created but not failed : hold, try again in 30 secs. + // Not created but not failed: hold, try again in 30 secs. case TimetablePool.TrainFromPool.NotCreated: validPosition = false; actionCompleted = false; break; - // forced created away from pool : create train + // Forced created away from pool: create train case TimetablePool.TrainFromPool.ForceCreated: validPosition = true; actionCompleted = false; @@ -1147,15 +1121,15 @@ private bool AddToWorldTT(TTTrain thisTrain, List nextTrains) //Trace.TraceInformation("Train {0} from pool {1} : {2} \n", thisTrain.Name, thisPool.PoolName, poolResult.ToString()); - if (actionCompleted) return (endPreRun); + if (actionCompleted) return endPreRun; } - // create in pool - // note : train is placed in pool in outbound direction + // Create in pool + // Note: train is placed in pool in outbound direction else if (!String.IsNullOrEmpty(thisTrain.CreateInPool)) { - // find place in pool + // Find place in pool int presentTime = Convert.ToInt32(Math.Floor(clockTime)); TimetablePool thisPool = Simulator.PoolHolder.Pools[thisTrain.CreateInPool]; @@ -1164,14 +1138,12 @@ private bool AddToWorldTT(TTTrain thisTrain, List nextTrains) if (PoolStorageState < 0) { Trace.TraceInformation("Train : " + thisTrain.Name + " : no storage room available in pool : " + thisPool.PoolName + " ; engine not created"); - return (endPreRun); + return endPreRun; } } - - // clear track and align switches - check state - else { + // Clear track and align switches - check state tempRoute = thisTrain.CalculateInitialTTTrainPosition(ref validPosition, nextTrains); if (validPosition) { @@ -1181,7 +1153,7 @@ private bool AddToWorldTT(TTTrain thisTrain, List nextTrains) thisTrain.Cars[i].WorldPosition.XNAMatrix.M42 -= 1000; thisTrain.ResetInitialTrainRoute(tempRoute); - validPosition = thisTrain.PostInit(false); // post init train but do not activate + validPosition = thisTrain.PostInit(false); // Post init train but do not activate } } @@ -1193,7 +1165,7 @@ private bool AddToWorldTT(TTTrain thisTrain, List nextTrains) File.AppendAllText(@"C:\temp\checktrain.txt", "Train added to world : " + thisTrain.Number + " ; type = " + thisTrain.TrainType + "\n"); } - thisTrain.actualWaitTimeS = 0; // reset wait counter // + thisTrain.actualWaitTimeS = 0; // Reset wait counter if (!AITrains.Contains(thisTrain)) { @@ -1221,9 +1193,9 @@ private bool AddToWorldTT(TTTrain thisTrain, List nextTrains) #if DEBUG_TRACEINFO Trace.TraceWarning("Delay to placing AI train {0} ({1}) at time {2}", thisTrain.Number, thisTrain.Name, timeStart.ToString()); #endif - thisTrain.StartTime += 30; // try again in half a minute + thisTrain.StartTime += 30; // Try again in half a minute thisTrain.actualWaitTimeS += 30; - if (thisTrain.actualWaitTimeS > 900) // tried for 15 mins + if (thisTrain.actualWaitTimeS > 900) // Tried for 15 mins { timeStart = new TimeSpan((long)(Math.Pow(10, 7) * thisTrain.StartTime.Value)); Trace.TraceWarning("Cannot place AI train {0} ({1}) at time {2}", thisTrain.Number, thisTrain.Name, timeStart.ToString()); @@ -1254,7 +1226,7 @@ private bool AddToWorldTT(TTTrain thisTrain, List nextTrains) } } #endif - return (endPreRun); + return endPreRun; } /// @@ -1268,7 +1240,7 @@ private void RemoveTrains() foreach (AITrain train in TrainsToRemove) { - // check if train is actually still waiting to be added + // Check if train is actually still waiting to be added if (TrainsToAdd.Contains(train)) { TrainsToAdd.Remove(train); @@ -1286,8 +1258,8 @@ private void RemoveTrains() foreach (TrainCar car in train.Cars) { car.Train = null; // WorldPosition.XNAMatrix.M42 -= 1000; - car.IsPartOfActiveTrain = false; // to stop sounds - // remove continers if any + car.IsPartOfActiveTrain = false; // To stop sounds + // Remove continers if any if (car.FreightAnimations?.Animations != null) car.FreightAnimations?.RemoveLoads(); } @@ -1297,7 +1269,7 @@ private void RemoveTrains() if (MPManager.IsServer() && removeList.Count > 0) { - MPManager.BroadCast((new MSGRemoveTrain(removeList)).ToString()); + MPManager.BroadCast(new MSGRemoveTrain(removeList).ToString()); } TrainsToRemove.Clear(); @@ -1305,11 +1277,9 @@ private void RemoveTrains() /// /// Removes an AI train only from the AI train list, but leaves it in the train lists - /// private void RemoveFromAITrains() { - foreach (AITrain train in TrainsToRemoveFromAI) { AITrains.Remove(train); @@ -1336,7 +1306,7 @@ private void AddTrains() private void AddTTTrains() { - foreach (TTTrain train in TrainsToAdd) + foreach (TTTrain train in TrainsToAdd.Cast()) { if (Simulator.TrainDictionary.ContainsKey(train.Number)) Simulator.TrainDictionary.Remove(train.Number); // clear existing entry Simulator.TrainDictionary.Add(train.Number, train); @@ -1354,17 +1324,14 @@ private void AddTTTrains() } TrainsToAdd.Clear(); } - } public class StartTrains : LinkedList { - //================================================================================================// // // Insert item on correct time // - public void InsertTrain(AITrain thisTrain) { if (thisTrain.StartTime == null) @@ -1372,7 +1339,7 @@ public void InsertTrain(AITrain thisTrain) Trace.TraceInformation("Train : " + thisTrain.Name + " : missing start time, train not included"); return; } - + if (this.Count == 0) { this.AddFirst(thisTrain); @@ -1407,18 +1374,17 @@ public void InsertTrain(AITrain thisTrain) // // Get next time // - public float GetNextTime() { if (this.Count == 0) { - return (-1.0f); + return -1.0f; } else { LinkedListNode nextNode = this.First; AITrain nextTrain = nextNode.Value; - return (nextTrain.StartTime.Value); + return nextTrain.StartTime.Value; } } @@ -1427,7 +1393,6 @@ public float GetNextTime() // Get all trains with time < present time and remove these from list // Skip trains which have a valid 'formedof' set // - public List GetTrains(float reqTime) { List itemList = new List(); @@ -1450,7 +1415,7 @@ public List GetTrains(float reqTime) itemsCollected = true; } } - return (itemList); + return itemList; } public List GetTTTrains(float reqTime) @@ -1484,7 +1449,7 @@ public List GetTTTrains(float reqTime) } } - return (itemList); + return itemList; } public void RemovePlayerTrain() @@ -1513,7 +1478,6 @@ public void RemovePlayerTrain() // // Get unstarted train by number and remove it from startlist if required // - public TTTrain GetNotStartedTTTrainByNumber(int reqNumber, bool remove) { LinkedListNode AITrainNode = First; @@ -1523,21 +1487,20 @@ public TTTrain GetNotStartedTTTrainByNumber(int reqNumber, bool remove) if (tttrain.Number == reqNumber || tttrain.OrgAINumber == reqNumber) { if (remove) Remove(AITrainNode); - return (tttrain); + return tttrain; } else { AITrainNode = AITrainNode.Next; } } - return (null); + return null; } //================================================================================================// // // Get unstarted train by number and remove it from startlist if required // - public TTTrain GetNotStartedTTTrainByName(string reqName, bool remove) { LinkedListNode AITrainNode = First; @@ -1547,14 +1510,14 @@ public TTTrain GetNotStartedTTTrainByName(string reqName, bool remove) { TTTrain reqTrain = AITrainNode.Value as TTTrain; if (remove) Remove(AITrainNode); - return (reqTrain); + return reqTrain; } else { AITrainNode = AITrainNode.Next; } } - return (null); + return null; } } diff --git a/Source/Orts.Simulation/Simulation/AIs/AIAuxAction.cs b/Source/Orts.Simulation/Simulation/AIs/AIAuxAction.cs index 7ea6467178..ced6ab925f 100644 --- a/Source/Orts.Simulation/Simulation/AIs/AIAuxAction.cs +++ b/Source/Orts.Simulation/Simulation/AIs/AIAuxAction.cs @@ -21,6 +21,10 @@ * */ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; using Newtonsoft.Json; using Orts.Formats.Msts; using Orts.Formats.OR; @@ -29,11 +33,6 @@ using Orts.Simulation.RollingStocks.SubSystems.Controllers; using Orts.Simulation.Signalling; using ORTS.Common; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using Event = Orts.Common.Event; namespace Orts.Simulation.AIs { @@ -44,20 +43,18 @@ namespace Orts.Simulation.AIs /// AuxActionsContainer /// Used to manage all the action ref object. /// - public class AuxActionsContainer : ActionContainer { - public Train.DistanceTravelledActions genRequiredActions = new Train.DistanceTravelledActions(); // distance travelled Generic action list for AITrain + public Train.DistanceTravelledActions genRequiredActions = new Train.DistanceTravelledActions(); // Distance travelled Generic action list for AITrain public Train.DistanceTravelledActions specRequiredActions = new Train.DistanceTravelledActions(); - Train ThisTrain; + readonly Train ThisTrain; public AuxActionsContainer(Train thisTrain, ORRouteConfig orRouteConfig) { - - if (thisTrain is AITrain && orRouteConfig != null) + if (thisTrain is AITrain train && orRouteConfig != null) { - SetGenAuxActions((AITrain)thisTrain, orRouteConfig); + SetGenAuxActions(train, orRouteConfig); } else { @@ -76,9 +73,9 @@ public AuxActionsContainer(Train thisTrain, BinaryReader inf, string routePath) // GenAuxActions = SetGenAuxActions((AITrain)thisTrain, null); //} ThisTrain = thisTrain; - if (thisTrain is AITrain && thisTrain.Simulator.orRouteConfig != null) + if (thisTrain is AITrain train && thisTrain.Simulator.orRouteConfig != null) { - SetGenAuxActions((AITrain)thisTrain, thisTrain.Simulator.orRouteConfig); + SetGenAuxActions(train, thisTrain.Simulator.orRouteConfig); } int cntAuxActionSpec = inf.ReadInt32(); @@ -127,16 +124,15 @@ public void Save(BinaryWriter outf, int currentClock) #endif AITrain aiTrain = ThisTrain as AITrain; if (SpecAuxActions.Count > 0 && SpecAuxActions[0] != null && - specRequiredActions.First != null && specRequiredActions.First.Value is AuxActSigDelegate) + specRequiredActions.First != null && specRequiredActions.First.Value is AuxActSigDelegate @delegate) // SigDelegate WP is running - - if (((AuxActSigDelegate)specRequiredActions.First.Value).currentMvmtState == AITrain.AI_MOVEMENT_STATE.HANDLE_ACTION && - !(((AuxActSigDelegate)specRequiredActions.First.Value).ActionRef as AIActSigDelegateRef).IsAbsolute) + if (@delegate.currentMvmtState == AITrain.AI_MOVEMENT_STATE.HANDLE_ACTION && + !(@delegate.ActionRef as AIActSigDelegateRef).IsAbsolute) { - int remainingDelay = ((AuxActSigDelegate)specRequiredActions.First.Value).ActualDepart - currentClock; - AIActSigDelegateRef actionRef = ((AuxActSigDelegate)specRequiredActions.First.Value).ActionRef as AIActSigDelegateRef; - if (actionRef.AssociatedWPAction != null) actionRef.AssociatedWPAction.SetDelay(remainingDelay); + int remainingDelay = @delegate.ActualDepart - currentClock; + AIActSigDelegateRef actionRef = @delegate.ActionRef as AIActSigDelegateRef; + actionRef.AssociatedWPAction?.SetDelay(remainingDelay); actionRef.Delay = remainingDelay; } if (!(ThisTrain == ThisTrain.Simulator.OriginalPlayerTrain && (ThisTrain.TrainType == Train.TRAINTYPE.AI_PLAYERDRIVEN || @@ -145,18 +141,18 @@ public void Save(BinaryWriter outf, int currentClock) if (ThisTrain is AITrain && ((aiTrain.MovementState == AITrain.AI_MOVEMENT_STATE.HANDLE_ACTION && aiTrain.nextActionInfo != null && aiTrain.nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.AUX_ACTION && aiTrain.nextActionInfo is AuxActionWPItem) - || ( aiTrain.AuxActionsContain.SpecAuxActions.Count > 0 && + || (aiTrain.AuxActionsContain.SpecAuxActions.Count > 0 && aiTrain.AuxActionsContain.SpecAuxActions[0] is AIActionWPRef && (aiTrain.AuxActionsContain.SpecAuxActions[0] as AIActionWPRef).keepIt != null && (aiTrain.AuxActionsContain.SpecAuxActions[0] as AIActionWPRef).keepIt.currentMvmtState == AITrain.AI_MOVEMENT_STATE.HANDLE_ACTION))) // WP is running { // Do nothing if it is an absolute WP - if (!(aiTrain.AuxActionsContain.SpecAuxActions.Count > 0 && aiTrain.AuxActionsContain.SpecAuxActions[0] is AIActionWPRef && + if (!(aiTrain.AuxActionsContain.SpecAuxActions.Count > 0 && aiTrain.AuxActionsContain.SpecAuxActions[0] is AIActionWPRef && (aiTrain.AuxActionsContain.SpecAuxActions[0] as AIActionWPRef).Delay >= 30000 && (aiTrain.AuxActionsContain.SpecAuxActions[0] as AIActionWPRef).Delay < 40000)) { - int remainingDelay; - if (aiTrain.nextActionInfo != null && aiTrain.nextActionInfo is AuxActionWPItem) remainingDelay = ((AuxActionWPItem)aiTrain.nextActionInfo).ActualDepart - currentClock; - else remainingDelay = ((AIActionWPRef)SpecAuxActions[0]).keepIt.ActualDepart - currentClock; + var remainingDelay = aiTrain.nextActionInfo != null && aiTrain.nextActionInfo is AuxActionWPItem item + ? item.ActualDepart - currentClock + : ((AIActionWPRef)SpecAuxActions[0]).keepIt.ActualDepart - currentClock; ((AIActionWPRef)SpecAuxActions[0]).SetDelay(remainingDelay); } } @@ -187,7 +183,7 @@ public void Save(BinaryWriter outf, int currentClock) List> converted = new List>(); foreach (var action in actionContainer.GenAuxActions) { - if (action.Value.GetType() == typeof(AuxActionHorn)) + if (action.Value.GetType() == typeof(AuxActionHorn)) { AIActionHornRef horn = new AIActionHornRef(thisTrain, (AuxActionHorn)action.Value, 0); List> listInfo = horn.GetCallFunction(); @@ -204,7 +200,7 @@ public void Save(BinaryWriter outf, int currentClock) GenFunctions.Add(function); KeyValuePair info = new KeyValuePair(action.Key, controlStart); converted.Add(info); - // If we use the ControllStart, then we must allow Generic WP to be created. + // If we use the ControllStart, then we must allow Generic WP to be created. AIActionWPRef wp = new AIActionWPRef(thisTrain, (AuxControlStart)action.Value, 0); listInfo = wp.GetCallFunction(); foreach (var function in listInfo) @@ -216,8 +212,8 @@ public void Save(BinaryWriter outf, int currentClock) return converted; } - protected List> SetGenAuxActions(AITrain thisTrain, ORRouteConfig orRouteConfig) // Add here the new Generic Action - { + protected List> SetGenAuxActions(AITrain thisTrain, ORRouteConfig orRouteConfig) // Add here the new Generic Action + { List> loaded = null; #if WITH_GEN_ACTION //AIActionSignalRef actionSignal = new AIActionSignalRef(thisTrain, 0f, 0f, 0, 0, 0, 0); @@ -297,7 +293,7 @@ public void RemoveGenActions(System.Type typeSource, WorldLocation location) #if WITH_PATH_DEBUG File.AppendAllText(@"C:\temp\checkpath.txt", "Remove GenAction for train " + ThisTrain.Number + "\n"); #endif - if ((ThisTrain is AITrain)) + if (ThisTrain is AITrain) { AITrain aiTrain = ThisTrain as AITrain; foreach (var fonction in GenFunctions) @@ -331,7 +327,7 @@ public void ProcessGenAction(AITrain thisTrain, int presentTime, float elapsedCl List itemList = new List(); foreach (var action in genRequiredActions) { - AIActionItem actionItem = action as AIActionItem; + AIActionItem actionItem = action as AIActionItem; if (actionItem.RequiredDistance <= ThisTrain.DistanceTravelledM) { itemList.Add(actionItem); @@ -355,7 +351,7 @@ public AITrain.AI_MOVEMENT_STATE ProcessSpecAction(AITrain thisTrain, int presen { AIActionItem actionItem = action as AIActionItem; if (actionItem.RequiredDistance >= ThisTrain.DistanceTravelledM) - continue; + continue; if (actionItem is AuxActSigDelegate) { var actionRef = (actionItem as AuxActSigDelegate).ActionRef; @@ -370,7 +366,7 @@ public AITrain.AI_MOVEMENT_STATE ProcessSpecAction(AITrain thisTrain, int presen AIActionItem actionItem = action as AIActionItem; tmpMvt = actionItem.ProcessAction(aiTrain, presentTime, elapsedClockSeconds, movementState); if (tmpMvt != movementState) - MvtState = tmpMvt; // Try to avoid override of changed state of previous action + MvtState = tmpMvt; // Try to avoid override of changed state of previous action } return MvtState; } @@ -396,8 +392,8 @@ public void Remove(AuxActionItem action) } if (CountSpec() > 0 && remove == true) SpecAuxActions.Remove(action.ActionRef); - if (ThisTrain is AITrain) - ((AITrain)ThisTrain).ResetActions(true); + if (ThisTrain is AITrain train) + train.ResetActions(true); } public void RemoveAt(int posit) @@ -409,13 +405,11 @@ public void RemoveAt(int posit) { get { - if (key >= SpecAuxActions.Count) - return null; - return SpecAuxActions[key]; + return key >= SpecAuxActions.Count ? null : SpecAuxActions[key]; } set { - + } } @@ -430,7 +424,7 @@ public int CountSpec() } //================================================================================================// - // SPA: Added for use with new AIActionItems + // SPA: Added for use with new AIActionItems /// /// Create Specific Auxiliary Action, like WP /// <\summary> @@ -441,7 +435,7 @@ public void SetAuxAction(Train thisTrain) AIAuxActionsRef thisAction; int specAuxActionsIndex = 0; bool requiredActionsInserted = false; - while (specAuxActionsIndex <= SpecAuxActions.Count-1) + while (specAuxActionsIndex <= SpecAuxActions.Count - 1) { while (SpecAuxActions.Count > 0) { @@ -468,7 +462,7 @@ public void SetAuxAction(Train thisTrain) if (thisTrain is AITrain && thisTrain.TrainType != Train.TRAINTYPE.AI_PLAYERDRIVEN) { AITrain aiTrain = thisTrain as AITrain; - distancesM = thisAction.CalculateDistancesToNextAction(aiTrain, ((AITrain)aiTrain).TrainMaxSpeedMpS, true); + distancesM = thisAction.CalculateDistancesToNextAction(aiTrain, aiTrain.TrainMaxSpeedMpS, true); } else { @@ -489,7 +483,7 @@ public void SetAuxAction(Train thisTrain) else */ { float requiredSpeedMpS = 0; - if (requiredActionsInserted && ((thisAction is AIActSigDelegateRef && !((AIActSigDelegateRef)thisAction).IsAbsolute))) return; + if (requiredActionsInserted && thisAction is AIActSigDelegateRef @ref && !@ref.IsAbsolute) return; validAction = true; AIActionItem newAction = ((AIAuxActionsRef)SpecAuxActions[specAuxActionsIndex]).Handler(distancesM[1], requiredSpeedMpS, distancesM[0], thisTrain.DistanceTravelledM); if (newAction != null) @@ -500,7 +494,7 @@ public void SetAuxAction(Train thisTrain) requiredActionsInserted = true; if ((thisTrain.TrainType == Train.TRAINTYPE.AI_PLAYERDRIVEN || thisTrain.TrainType == Train.TRAINTYPE.AI_PLAYERHOSTING) && thisTrain.requiredActions.Count > 0) { - // check if action already inserted + // Check if action already inserted foreach (Train.DistanceTravelledItem item in thisTrain.requiredActions) { if (item is AuxActionWPItem) @@ -514,7 +508,7 @@ public void SetAuxAction(Train thisTrain) { thisTrain.requiredActions.InsertAction(newAction); continue; - // ((AITrain)thisTrain).nextActionInfo = newAction; // action must be restored through required actions only + // ((AITrain)thisTrain).nextActionInfo = newAction; // Action must be restored through required actions only } } else @@ -535,7 +529,6 @@ public void SetAuxAction(Train thisTrain) /// /// Reset WP Aux Action, if any /// <\summary> - public void ResetAuxAction(Train thisTrain) { if (SpecAuxActions.Count <= 0) @@ -545,7 +538,7 @@ public void ResetAuxAction(Train thisTrain) if (thisAction.SubrouteIndex != thisTrain.TCRoute.activeSubpath) return; thisAction.LinkedAuxAction = false; return; - } + } //================================================================================================// // @@ -560,18 +553,18 @@ public void MoveAuxAction(Train thisTrain) AIAuxActionsRef thisAction; thisAction = (AIAuxActionsRef)SpecAuxActions[0]; if (thisAction is AIActionWPRef && thisAction.SubrouteIndex == thisTrain.TCRoute.activeSubpath && thisAction.TCSectionIndex == thisTrain.PresentPosition[0].TCSectionIndex) - // Waiting point is just in the same section where the train is; move it under the train { + // Waiting point is just in the same section where the train is; move it under the train AuxActionWPItem thisWPItem; - if (thisAITrain.nextActionInfo != null && thisAITrain.nextActionInfo is AuxActionWPItem) + if (thisAITrain.nextActionInfo != null && thisAITrain.nextActionInfo is AuxActionWPItem item) { - thisWPItem = (AuxActionWPItem)thisAITrain.nextActionInfo; + thisWPItem = item; if (thisWPItem.ActionRef == thisAction) { thisWPItem.ActivateDistanceM = thisTrain.PresentPosition[0].DistanceTravelledM - 5; thisAction.LinkedAuxAction = true; } - } + } thisAction.RequiredDistance = thisTrain.PresentPosition[0].TCOffset - 5; } } @@ -587,9 +580,9 @@ public void MoveAuxActionAfterReversal(Train thisTrain) return; AIAuxActionsRef thisAction; thisAction = (AIAuxActionsRef)SpecAuxActions[0]; - if (thisAction is AIActionWPRef && thisAction.SubrouteIndex == thisTrain.TCRoute.activeSubpath+1 && thisAction.TCSectionIndex == thisTrain.PresentPosition[1].TCSectionIndex) - // Waiting point is just in the same section where the train is; move it under the train + if (thisAction is AIActionWPRef && thisAction.SubrouteIndex == thisTrain.TCRoute.activeSubpath + 1 && thisAction.TCSectionIndex == thisTrain.PresentPosition[1].TCSectionIndex) { + // Waiting point is just in the same section where the train is; move it under the train int thisSectionIndex = thisTrain.PresentPosition[1].TCSectionIndex; TrackCircuitSection thisSection = thisTrain.signalRef.TrackCircuitList[thisSectionIndex]; thisAction.RequiredDistance = thisSection.Length - thisTrain.PresentPosition[1].TCOffset - 5; @@ -651,22 +644,20 @@ public static List GetValidActions(this List ///// AuxActionRef ///// info used to figure out one auxiliary action along the route. It's a reference data, not a run data. ///// - public class AIAuxActionsRef : AuxActionRef { public int SubrouteIndex; @@ -690,7 +681,6 @@ public class AIAuxActionsRef : AuxActionRef /// AIAuxActionsRef: Generic Constructor /// The specific datas are used to fire the Action. /// - public AIAuxActionsRef(float requiredSpeedMps, WorldLocation location) { } @@ -730,7 +720,7 @@ public AIAuxActionsRef(Train thisTrain, BinaryReader inf, AuxActionRef.AUX_ACTIO public virtual List> GetCallFunction() { - return default(List>); + return default; } //================================================================================================// @@ -738,8 +728,6 @@ public AIAuxActionsRef(Train thisTrain, BinaryReader inf, AuxActionRef.AUX_ACTIO /// Handler /// Like a fabric, if other informations are needed, please define specific function that can be called on the new object /// - - public virtual AIActionItem Handler(params object[] list) { AIActionItem info = null; @@ -749,7 +737,7 @@ public virtual AIActionItem Handler(params object[] list) info.SetParam((float)list[0], (float)list[1], (float)list[2], (float)list[3]); //info = new AuxActionItem(distance, speed, activateDistance, insertedDistance, - // this, AIActionItem.AI_ACTION_TYPE.AUX_ACTION); + // this, AIActionItem.AI_ACTION_TYPE.AUX_ACTION); } return info; } @@ -759,14 +747,13 @@ public virtual AIActionItem Handler(params object[] list) /// CalculateDistancesToNextAction /// PLease, don't use the default function, redefine it. /// - public virtual float[] CalculateDistancesToNextAction(Train thisTrain, float presentSpeedMpS, bool reschedule) { float[] distancesM = new float[2]; distancesM[1] = 0.0f; distancesM[0] = thisTrain.PresentPosition[0].DistanceTravelledM; - return (distancesM); + return distancesM; } public virtual float[] GetActivationDistances(Train thisTrain, WorldLocation location) @@ -775,13 +762,12 @@ public virtual float[] GetActivationDistances(Train thisTrain, WorldLocation loc distancesM[1] = float.MaxValue; distancesM[0] = float.MaxValue; - return (distancesM); + return distancesM; } //================================================================================================// // // Save // - public virtual void save(BinaryWriter outf, int cnt) { outf.Write(cnt); @@ -807,7 +793,6 @@ public virtual void save(BinaryWriter outf, int cnt) // // Restore // - public void Register(int trainNumber, WorldLocation location) { AskingTrain.Add(new KeyValuePair(trainNumber, location)); @@ -823,7 +808,7 @@ public bool HasAction(int trainNumber, WorldLocation location) { foreach (var info in AskingTrain) { - int number = (int)info.Key; + int number = info.Key; if (number == trainNumber) { WorldLocation locationRegistered = info.Value; @@ -844,7 +829,7 @@ public void RemoveReference(int trainNumber, WorldLocation location) //var info = default (KeyValuePair); foreach (var info in AskingTrain) { - int number = (int)info.Key; + int number = info.Key; if (number == trainNumber) { WorldLocation locationRegistered = info.Value; @@ -868,7 +853,6 @@ public void SetSignalObject(SignalObject signal) /// AIActionWPRef /// info used to figure out a Waiting Point along the route. /// - public class AIActionWPRef : AIAuxActionsRef { public AuxActionWPItem keepIt = null; @@ -886,7 +870,7 @@ public AIActionWPRef(Train thisTrain, float distance, float requiredSpeedMpS, in } public AIActionWPRef(Train thisTrain, BinaryReader inf) - : base (thisTrain, inf) + : base(thisTrain, inf) { Delay = inf.ReadInt32(); OriginalDelay = inf.ReadInt32(); @@ -902,7 +886,7 @@ public AIActionWPRef(Train thisTrain, BinaryReader inf) public AIActionWPRef(Train thisTrain, AuxControlStart myBase, int nop = 0) : base(thisTrain, 0f, 0f, 0, 0, 0, 0, myBase.ActionType) { - Delay = myBase.ActivationDelay; // Generic WP Delay will be the Control Start ActivationDelay + Delay = myBase.ActivationDelay; // Generic WP Delay will be the Control Start ActivationDelay NextAction = AUX_ACTION.WAITING_POINT; IsGeneric = myBase.IsGeneric; } @@ -939,7 +923,7 @@ public override AIActionItem Handler(params object[] list) { info = keepIt; } - return (AIActionItem)info; + return info; } public override AIActionItem CheckGenActions(WorldLocation location, AITrain thisTrain, params object[] list) @@ -959,13 +943,11 @@ public override AIActionItem CheckGenActions(WorldLocation location, AITrain thi return newAction; } - //================================================================================================// /// /// SetDelay /// To fullfill the waiting delay. /// - public void SetDelay(int delay) { #if WITH_PATH_DEBUG @@ -982,15 +964,13 @@ public override float[] CalculateDistancesToNextAction(Train thisTrain, float pr TrackCircuitSection thisSection = thisTrain.signalRef.TrackCircuitList[thisSectionIndex]; float leftInSectionM = thisSection.Length - thisTrain.PresentPosition[0].TCOffset; - // get action route index - if not found, return distances < 0 - + // Get action route index - if not found, return distances < 0 int actionIndex0 = thisTrain.PresentPosition[0].RouteListIndex; int actionRouteIndex = thisTrain.ValidRoute[0].GetRouteIndex(TCSectionIndex, actionIndex0); float activateDistanceTravelledM = thisTrain.PresentPosition[0].DistanceTravelledM + thisTrain.ValidRoute[0].GetDistanceAlongRoute(actionIndex0, leftInSectionM, actionRouteIndex, this.RequiredDistance, thisTrain.AITrainDirectionForward, thisTrain.signalRef); - // if reschedule, use actual speed - + // If reschedule, use actual speed float triggerDistanceM = TriggerDistance; if (thisTrain.TrainType != Train.TRAINTYPE.AI_PLAYERDRIVEN) @@ -1009,18 +989,17 @@ public override float[] CalculateDistancesToNextAction(Train thisTrain, float pr firstPartTime = presentSpeedMpS / (0.25f * aiTrain.MaxDecelMpSS); firstPartRangeM = 0.25f * aiTrain.MaxDecelMpSS * (firstPartTime * firstPartTime); - if (firstPartRangeM < remainingRangeM && thisTrain.SpeedMpS < thisTrain.TrainMaxSpeedMpS) // if distance left and not at max speed - // split remaining distance based on relation between acceleration and deceleration + if (firstPartRangeM < remainingRangeM && thisTrain.SpeedMpS < thisTrain.TrainMaxSpeedMpS) // If distance left and not at max speed { + // Split remaining distance based on relation between acceleration and deceleration secndPartRangeM = (remainingRangeM - firstPartRangeM) * (2.0f * aiTrain.MaxDecelMpSS) / (aiTrain.MaxDecelMpSS + aiTrain.MaxAccelMpSS); } triggerDistanceM = activateDistanceTravelledM - (firstPartRangeM + secndPartRangeM); } else - - // use maximum speed { + // Use maximum speed float deltaTime = thisTrain.TrainMaxSpeedMpS / aiTrain.MaxDecelMpSS; float brakingDistanceM = (thisTrain.TrainMaxSpeedMpS * deltaTime) + (0.5f * aiTrain.MaxDecelMpSS * deltaTime * deltaTime); triggerDistanceM = activateDistanceTravelledM - brakingDistanceM; @@ -1038,12 +1017,12 @@ public override float[] CalculateDistancesToNextAction(Train thisTrain, float pr activateDistanceTravelledM = thisTrain.PresentPosition[0].DistanceTravelledM; distancesM[0] = activateDistanceTravelledM; - return (distancesM); + return distancesM; } else { activateDistanceTravelledM = thisTrain.PresentPosition[0].DistanceTravelledM + thisTrain.ValidRoute[0].GetDistanceAlongRoute(actionIndex0, leftInSectionM, actionRouteIndex, this.RequiredDistance, true, thisTrain.signalRef); - triggerDistanceM = activateDistanceTravelledM - Math.Min(this.RequiredDistance, 300); + triggerDistanceM = activateDistanceTravelledM - Math.Min(this.RequiredDistance, 300); if (activateDistanceTravelledM < thisTrain.PresentPosition[0].DistanceTravelledM && thisTrain.PresentPosition[0].DistanceTravelledM - activateDistanceTravelledM < thisTrain.Length) @@ -1054,7 +1033,7 @@ public override float[] CalculateDistancesToNextAction(Train thisTrain, float pr distancesM[1] = triggerDistanceM; distancesM[0] = activateDistanceTravelledM; - return (distancesM); + return distancesM; } } @@ -1063,7 +1042,7 @@ public override float[] CalculateDistancesToNextAction(Train thisTrain, float pr { List> listInfo = new List>(); - System.Type managed = typeof(SignalObject); + System.Type managed = typeof(SignalObject); KeyValuePair info = new KeyValuePair(managed, this); listInfo.Add(info); return listInfo; @@ -1075,7 +1054,6 @@ public override float[] CalculateDistancesToNextAction(Train thisTrain, float pr /// AIActionHornRef /// Start and Stop the horn /// - public class AIActionHornRef : AIAuxActionsRef { /// @@ -1135,7 +1113,6 @@ public override void save(BinaryWriter outf, int cnt) HornPattern.Save(outf); } - public override AIActionItem Handler(params object[] list) { AIActionItem info = null; @@ -1145,7 +1122,7 @@ public override AIActionItem Handler(params object[] list) info = new AuxActionHornItem(this, AIActionItem.AI_ACTION_TYPE.AUX_ACTION, DurationS, HornPattern); info.SetParam((float)list[0], (float)list[1], (float)list[2], (float)list[3]); } - return (AIActionItem)info; + return info; } //public bool CheckGenActions(System.Type typeSource, float rearDist, float frontDist, WorldLocation location, uint trackNodeIndex) @@ -1158,12 +1135,12 @@ public override AIActionItem CheckGenActions(WorldLocation location, AITrain thi float minDist = Math.Min(Math.Abs(rearDist), frontDist); float[] distances = GetActivationDistances(thisTrain, location); - + #if WITH_PATH_DEBUG File.AppendAllText(@"C:\temp\checkpath.txt", "GenFunctions not yet defined for train:" + thisTrain.Number + " Activation Distance: " + distances[0] + " & train distance: " + (-minDist) + "\n"); #endif - if (distances[0] >= -minDist) // We call the handler to generate an actionRef + if (distances[0] >= -minDist) // We call the handler to generate an actionRef { HornPattern = (AILevelCrossingHornPattern)list[3]; newAction = Handler(distances[0] + thisTrain.DistanceTravelledM, thisTrain.SpeedMpS, distances[0] + thisTrain.DistanceTravelledM, thisTrain.DistanceTravelledM); @@ -1179,21 +1156,21 @@ public override AIActionItem CheckGenActions(WorldLocation location, AITrain thi { System.Type managed = typeof(LevelCrossings); KeyValuePair info = new KeyValuePair(managed, this); - List> listInfo = new List>(); - listInfo.Add(info); + List> listInfo = new List> + { + info + }; return listInfo; } - // Start horn whatever the speed. - + // Start horn whatever the speed. public override float[] CalculateDistancesToNextAction(Train thisTrain, float presentSpeedMpS, bool reschedule) { int thisSectionIndex = thisTrain.PresentPosition[0].TCSectionIndex; TrackCircuitSection thisSection = thisTrain.signalRef.TrackCircuitList[thisSectionIndex]; float leftInSectionM = thisSection.Length - thisTrain.PresentPosition[0].TCOffset; - // get action route index - if not found, return distances < 0 - + // Get action route index - if not found, return distances < 0 int actionIndex0 = thisTrain.PresentPosition[0].RouteListIndex; int actionRouteIndex = thisTrain.ValidRoute[0].GetRouteIndex(TCSectionIndex, actionIndex0); float activateDistanceTravelledM = thisTrain.PresentPosition[0].DistanceTravelledM + thisTrain.ValidRoute[0].GetDistanceAlongRoute(actionIndex0, leftInSectionM, actionRouteIndex, this.RequiredDistance, thisTrain.AITrainDirectionForward, thisTrain.signalRef); @@ -1201,16 +1178,16 @@ public override float[] CalculateDistancesToNextAction(Train thisTrain, float pr distancesM[1] = activateDistanceTravelledM; distancesM[0] = activateDistanceTravelledM; - return (distancesM); + return distancesM; } - // SPA: We use this fonction and not the one from Train in order to leave control to the AuxAction + // SPA: We use this fonction and not the one from Train in order to leave control to the AuxAction public override float[] GetActivationDistances(Train thisTrain, WorldLocation location) { float[] distancesM = new float[2]; distancesM[0] = this.RequiredDistance; // distancesM[1] = this.RequiredDistance + thisTrain.Length; - return (distancesM); + return distancesM; } } @@ -1220,7 +1197,6 @@ public override float[] GetActivationDistances(Train thisTrain, WorldLocation lo /// AIActionControlledStartRef /// Used to start a steam engine when it is an Train /// - public class AIActionControlStartRef : AIAuxActionsRef { public int ActionDuration; @@ -1254,7 +1230,6 @@ public AIActionControlStartRef(Train thisTrain, AuxControlStart myBase, int nop ActionDuration = myBase.ActionDuration; } - public override void save(BinaryWriter outf, int cnt) { #if WITH_PATH_DEBUG @@ -1267,7 +1242,6 @@ public override void save(BinaryWriter outf, int cnt) outf.Write(Delay); } - public override AIActionItem Handler(params object[] list) { AIActionItem info = null; @@ -1280,7 +1254,7 @@ public override AIActionItem Handler(params object[] list) ((AuxActionControlStartItem)info).Duration = ActionDuration; ((AuxActionControlStartItem)info).PreDelay = Delay; } - return (AIActionItem)info; + return info; } public override AIActionItem CheckGenActions(WorldLocation location, AITrain thisTrain, params object[] list) @@ -1292,10 +1266,10 @@ public override AIActionItem CheckGenActions(WorldLocation location, AITrain thi { return null; } - if (Math.Abs(SpeedMps) <= Simulator.MaxStoppedMpS && (int)list[0] >= Delay) // We call the handler to generate an actionRef + if (Math.Abs(SpeedMps) <= Simulator.MaxStoppedMpS && (int)list[0] >= Delay) // We call the handler to generate an actionRef { newAction = Handler(thisTrain.SpeedMpS, (int)list[0]); - + Register(thisTrain.Number, location); #if WITH_PATH_DEBUG File.AppendAllText(@"C:\temp\checkpath.txt", "Caller registered for\n"); @@ -1319,22 +1293,19 @@ public override AIActionItem CheckGenActions(WorldLocation location, AITrain thi /// SetDelay /// To fullfill the waiting delay. /// - public void SetDelay(int delay) { Delay = delay; } - // Start horn whatever the speed. - + // Start horn whatever the speed. public override float[] CalculateDistancesToNextAction(Train thisTrain, float presentSpeedMpS, bool reschedule) { int thisSectionIndex = thisTrain.PresentPosition[0].TCSectionIndex; TrackCircuitSection thisSection = thisTrain.signalRef.TrackCircuitList[thisSectionIndex]; float leftInSectionM = thisSection.Length - thisTrain.PresentPosition[0].TCOffset; - // get action route index - if not found, return distances < 0 - + // Get action route index - if not found, return distances < 0 int actionIndex0 = thisTrain.PresentPosition[0].RouteListIndex; int actionRouteIndex = thisTrain.ValidRoute[0].GetRouteIndex(TCSectionIndex, actionIndex0); float activateDistanceTravelledM = thisTrain.PresentPosition[0].DistanceTravelledM + thisTrain.ValidRoute[0].GetDistanceAlongRoute(actionIndex0, leftInSectionM, actionRouteIndex, this.RequiredDistance, thisTrain.AITrainDirectionForward, thisTrain.signalRef); @@ -1342,16 +1313,16 @@ public override float[] CalculateDistancesToNextAction(Train thisTrain, float pr distancesM[1] = activateDistanceTravelledM; distancesM[0] = activateDistanceTravelledM; - return (distancesM); + return distancesM; } - // SPA: We use this fonction and not the one from Train in order to leave control to the AuxAction + // SPA: We use this fonction and not the one from Train in order to leave control to the AuxAction public override float[] GetActivationDistances(Train thisTrain, WorldLocation location) { float[] distancesM = new float[2]; - distancesM[0] = 0f; // Dès 100m + distancesM[0] = 0f; // Dès 100m (French?) distancesM[1] = 0f; - return (distancesM); + return distancesM; } } @@ -1362,7 +1333,6 @@ public override float[] GetActivationDistances(Train thisTrain, WorldLocation lo /// AIActionSignalRef /// A single Reference object used to add some delay before starting at a Signal /// - public class AIActionSignalRef : AIAuxActionsRef { public AIActionSignalRef(Train thisTrain, float distance, float requiredSpeedMpS, int subrouteIdx, int routeIdx, int sectionIdx, int dir) @@ -1382,7 +1352,7 @@ public override AIActionItem Handler(params object[] list) info.SetParam((float)list[0], (float)list[1], (float)list[2], (float)list[3]); ((AuxActionSignalItem)info).SetDelay(Delay); } - return (AIActionItem)info; + return info; } //================================================================================================// @@ -1390,14 +1360,12 @@ public override AIActionItem Handler(params object[] list) /// SetDelay /// To fullfill the waiting delay. /// - public void SetDelay(int delay) { Delay = delay; } - // Start horn whatever the speed. - + // Start horn whatever the speed public override float[] CalculateDistancesToNextAction(Train thisTrain, float presentSpeedMpS, bool reschedule) { float activateDistanceTravelledM = float.MaxValue; @@ -1413,21 +1381,21 @@ public override float[] CalculateDistancesToNextAction(Train thisTrain, float pr distancesM[1] = activateDistanceTravelledM; distancesM[0] = activateDistanceTravelledM; - return (distancesM); + return distancesM; } } + //================================================================================================// /// /// AIActSigDelegateRef /// An action to delegate the Signal management from a WP /// - public class AIActSigDelegateRef : AIAuxActionsRef { public bool IsAbsolute = false; public AIActionWPRef AssociatedWPAction; public float brakeSection; - protected AuxActSigDelegate AssociatedItem = null; // In order to Unlock the signal when removing Action Reference + protected AuxActSigDelegate AssociatedItem = null; // In order to Unlock the signal when removing Action Reference public AIActSigDelegateRef(Train thisTrain, float distance, float requiredSpeedMpS, int subrouteIdx, int routeIdx, int sectionIdx, int dir, AIActionWPRef associatedWPAction = null) : base(thisTrain, distance, requiredSpeedMpS, subrouteIdx, routeIdx, sectionIdx, dir, AUX_ACTION.SIGNAL_DELEGATE) @@ -1435,15 +1403,15 @@ public AIActSigDelegateRef(Train thisTrain, float distance, float requiredSpeedM AssociatedWPAction = associatedWPAction; NextAction = AUX_ACTION.SIGNAL_DELEGATE; IsGeneric = true; - - brakeSection = distance; // Set to 1 later when applicable + + brakeSection = distance; // Set to 1 later when applicable } public AIActSigDelegateRef(Train thisTrain, BinaryReader inf) : base(thisTrain, inf, AUX_ACTION.SIGNAL_DELEGATE) { Delay = inf.ReadInt32(); - brakeSection = (float)inf.ReadSingle(); + brakeSection = inf.ReadSingle(); IsAbsolute = inf.ReadBoolean(); NextAction = AUX_ACTION.SIGNAL_DELEGATE; #if WITH_PATH_DEBUG @@ -1482,7 +1450,10 @@ public override bool CallFreeAction(Train thisTrain) return true; } else if (AssociatedItem == null) + { return true; + } + return false; } @@ -1492,20 +1463,18 @@ public override AIActionItem Handler(params object[] list) return null; AuxActSigDelegate info = new AuxActSigDelegate(this, AIActionItem.AI_ACTION_TYPE.AUX_ACTION); info.SetParam((float)list[0], (float)list[1], (float)list[2], (float)list[3]); - AssociatedItem = info; - return (AIActionItem)info; + AssociatedItem = info; + return info; } - // SigDelegateRef. - + // SigDelegateRef. public override float[] CalculateDistancesToNextAction(Train thisTrain, float presentSpeedMpS, bool reschedule) { int thisSectionIndex = thisTrain.PresentPosition[0].TCSectionIndex; TrackCircuitSection thisSection = thisTrain.signalRef.TrackCircuitList[thisSectionIndex]; float leftInSectionM = thisSection.Length - thisTrain.PresentPosition[0].TCOffset; - // get action route index - if not found, return distances < 0 - + // Get action route index - if not found, return distances < 0 int actionIndex0 = thisTrain.PresentPosition[0].RouteListIndex; int actionRouteIndex = thisTrain.ValidRoute[0].GetRouteIndex(TCSectionIndex, actionIndex0); float activateDistanceTravelledM = -1; @@ -1523,7 +1492,7 @@ public override float[] CalculateDistancesToNextAction(Train thisTrain, float pr activateDistanceTravelledM = thisTrain.PresentPosition[0].DistanceTravelledM; distancesM[0] = activateDistanceTravelledM; - return (distancesM); + return distancesM; } public void SetEndSignalIndex(int idx) @@ -1536,7 +1505,6 @@ public void SetEndSignalIndex(int idx) /// SetDelay /// To fullfill the waiting delay. /// - public void SetDelay(int delay) { #if WITH_PATH_DEBUG @@ -1546,35 +1514,29 @@ public void SetDelay(int delay) } } - - - #endregion #region AuxActionData - //================================================================================================// /// /// AuxActionItem /// A specific AIActionItem used at run time to manage a specific Auxiliary Action /// - public class AuxActionItem : AIActionItem { public AuxActionRef ActionRef; public bool Triggered = false; public bool Processing = false; public AITrain.AI_MOVEMENT_STATE currentMvmtState = AITrain.AI_MOVEMENT_STATE.INIT_ACTION; - public SignalObject SignalReferenced { get { return ((AIAuxActionsRef)ActionRef).SignalReferenced; } set {} } + public SignalObject SignalReferenced { get { return ((AIAuxActionsRef)ActionRef).SignalReferenced; } set { } } //================================================================================================// /// /// AuxActionItem /// The basic constructor /// - public AuxActionItem(AuxActionRef thisItem, AI_ACTION_TYPE thisAction) : - base ( null, thisAction) + base(null, thisAction) { NextAction = AI_ACTION_TYPE.AUX_ACTION; ActionRef = thisItem; @@ -1584,7 +1546,6 @@ public class AuxActionItem : AIActionItem // // Restore // - public AuxActionItem(BinaryReader inf, Signals signalRef) : base(inf, signalRef) { @@ -1652,8 +1613,6 @@ public override AITrain.AI_MOVEMENT_STATE ProcessAction(Train thisTrain, int pre return currentMvmtState; } - - #if WITH_PATH_DEBUG public override string AsString(AITrain thisTrain) { @@ -1667,7 +1626,6 @@ public override string AsString(AITrain thisTrain) /// AuxActionWPItem /// A specific class used at run time to manage a Waiting Point Action /// - public class AuxActionWPItem : AuxActionItem { int Delay; @@ -1678,7 +1636,6 @@ public class AuxActionWPItem : AuxActionItem /// AuxActionWPItem /// The specific constructor for WP action /// - public AuxActionWPItem(AuxActionRef thisItem, AI_ACTION_TYPE thisAction) : base(thisItem, thisAction) { @@ -1690,7 +1647,6 @@ public class AuxActionWPItem : AuxActionItem /// AsString /// Used by debugging in HUDWindows. /// - public override string AsString(AITrain thisTrain) { return " WP("; @@ -1714,11 +1670,7 @@ public override bool CanActivate(Train thisTrain, float SpeedMpS, bool reschedul } else { - if (Math.Abs(thisTrain.SpeedMpS) <= 0.1f && distancesM[1] <= thisTrain.DistanceTravelledM) - { - return true; - } - return false; + return Math.Abs(thisTrain.SpeedMpS) <= 0.1f && distancesM[1] <= thisTrain.DistanceTravelledM; } } @@ -1750,7 +1702,7 @@ public override AITrain.AI_MOVEMENT_STATE InitAction(Train thisTrain, int presen { AITrain aiTrain = thisTrain as AITrain; - // repeat stopping of train, because it could have been moved by UpdateBrakingState after ProcessAction + // Repeat stopping of train, because it could have been moved by UpdateBrakingState after ProcessAction if (aiTrain.TrainType != Train.TRAINTYPE.AI_PLAYERDRIVEN) { aiTrain.AdjustControlsBrakeMore(aiTrain.MaxDecelMpSS, elapsedClockSeconds, 100); @@ -1758,7 +1710,7 @@ public override AITrain.AI_MOVEMENT_STATE InitAction(Train thisTrain, int presen } int correctedTime = presentTime; // If delay between 40000 and 60000 an uncoupling is performed and delay is returned with the two lowest digits of the original one - aiTrain.TestUncouple( ref Delay); + aiTrain.TestUncouple(ref Delay); // If delay between 30000 and 40000 it is considered an absolute delay in the form 3HHMM, where HH and MM are hour and minute where the delay ends thisTrain.TestAbsDelay(ref Delay, correctedTime); // If delay equal to 60001 it is considered as a command to unconditionally attach to the nearby train; @@ -1782,7 +1734,7 @@ public override AITrain.AI_MOVEMENT_STATE HandleAction(Train thisTrain, int pres { if (thisTrain.TrainType != Train.TRAINTYPE.AI_PLAYERDRIVEN) { - thisTrain.SpeedMpS = 0; + thisTrain.SpeedMpS = 0; } AITrain aiTrain = thisTrain as AITrain; @@ -1869,8 +1821,7 @@ public override AITrain.AI_MOVEMENT_STATE ProcessAction(Train thisTrain, int pre if (thisTrain.AuxActionsContain.CountSpec() > 0) thisTrain.AuxActionsContain.Remove(this); - - #if WITH_PATH_DEBUG +#if WITH_PATH_DEBUG else { File.AppendAllText(@"C:\temp\checkpath.txt", "AITRain " + thisTrain.Number + "! No more AuxActions...\n"); @@ -1880,8 +1831,8 @@ public override AITrain.AI_MOVEMENT_STATE ProcessAction(Train thisTrain, int pre { AITrain aiTrain = thisTrain as AITrain; - //movementState = thisTrain.UpdateStoppedState(); // Don't call UpdateStoppedState(), WP can't touch Signal - movementState = AITrain.AI_MOVEMENT_STATE.BRAKING; + //movementState = thisTrain.UpdateStoppedState(); // Don't call UpdateStoppedState(), WP can't touch Signal + movementState = AITrain.AI_MOVEMENT_STATE.BRAKING; aiTrain.ResetActions(true); #if WITH_PATH_DEBUG File.AppendAllText(@"C:\temp\checkpath.txt", "AITRain " + aiTrain.Number + " is " + movementState.ToString() + " at " + presentTime + "\n"); @@ -1889,7 +1840,7 @@ public override AITrain.AI_MOVEMENT_STATE ProcessAction(Train thisTrain, int pre } break; default: - break; + break; } if (ActionRef.IsGeneric) currentMvmtState = movementState; @@ -1898,15 +1849,11 @@ public override AITrain.AI_MOVEMENT_STATE ProcessAction(Train thisTrain, int pre } - - - //================================================================================================// /// /// AuxActionHornItem /// A specific class used at run time to manage a Horn Action /// - public class AuxActionHornItem : AuxActionItem { [JsonProperty("DurationS")] @@ -1924,7 +1871,6 @@ public class AuxActionHornItem : AuxActionItem /// AuxActionhornItem /// The specific constructor for horn action /// - public AuxActionHornItem(AuxActionRef thisItem, AI_ACTION_TYPE thisAction, int? durationS, AILevelCrossingHornPattern hornPattern) : base(thisItem, thisAction) { @@ -1937,7 +1883,6 @@ public class AuxActionHornItem : AuxActionItem /// AsString /// Used by debugging in HUDWindows. /// - public override string AsString(AITrain thisTrain) { return " Horn("; @@ -2015,7 +1960,7 @@ public override AITrain.AI_MOVEMENT_STATE HandleAction(Train thisTrain, int pres { thisTrain.AuxActionsContain.Remove(this); Triggered = false; - return currentMvmtState; // Restore previous MovementState + return currentMvmtState; // Restore previous MovementState } } else @@ -2052,8 +1997,8 @@ public override AITrain.AI_MOVEMENT_STATE ProcessAction(Train thisTrain, int pre } break; case AITrain.AI_MOVEMENT_STATE.STOPPED: - if (thisTrain is AITrain) - movementState = ((AITrain)thisTrain).UpdateStoppedState(elapsedClockSeconds); + if (thisTrain is AITrain train) + movementState = train.UpdateStoppedState(elapsedClockSeconds); break; default: break; @@ -2071,7 +2016,6 @@ public override AITrain.AI_MOVEMENT_STATE ProcessAction(Train thisTrain, int pre /// AuxActionControlledStartItem /// A specific class used at run time to manage the starting of a steam train /// - public class AuxActionControlStartItem : AuxActionItem { public enum LOCAL_ACTION @@ -2083,8 +2027,8 @@ public enum LOCAL_ACTION END } - public int PreDelay; // PreDelay gives the time in second before the action must take effect - public int Delay; // Delay is the delay of the caller + public int PreDelay; // PreDelay gives the time in second before the action must take effect + public int Delay; // Delay is the delay of the caller public int Duration; // ActionDuration gives how long it takes public int ActualDepart; LOCAL_ACTION localStep = LOCAL_ACTION.NOT_STARTED; @@ -2094,7 +2038,6 @@ public enum LOCAL_ACTION /// AuxActionControlStartItem /// The specific constructor for Controlled Start action /// - public AuxActionControlStartItem(AuxActionRef thisItem, AI_ACTION_TYPE thisAction) : base(thisItem, thisAction) { @@ -2106,7 +2049,6 @@ public enum LOCAL_ACTION /// AsString /// Used by debugging in HUDWindows. /// - public override string AsString(AITrain thisTrain) { return " Steam("; @@ -2162,12 +2104,12 @@ public override AITrain.AI_MOVEMENT_STATE InitAction(Train thisTrain, int presen TrainCar locomotive = thisTrain.FindLeadLocomotive(); if (!(locomotive is MSTSSteamLocomotive)) { - return currentMvmtState; // Restore previous MovementState + return currentMvmtState; // Restore previous MovementState } Processing = true; int correctedTime = presentTime; ActualDepart = correctedTime + (Delay - PreDelay); - localStep = LOCAL_ACTION.INIT_DONE; // NOT_STARTED -> INIT_DONE + localStep = LOCAL_ACTION.INIT_DONE; // NOT_STARTED -> INIT_DONE return AITrain.AI_MOVEMENT_STATE.HANDLE_ACTION; } @@ -2197,7 +2139,7 @@ public override AITrain.AI_MOVEMENT_STATE HandleAction(Train thisTrain, int pres else if (Triggered && localStep == LOCAL_ACTION.END) { thisTrain.AuxActionsContain.Remove(this); - if ((locomotive is MSTSSteamLocomotive)) + if (locomotive is MSTSSteamLocomotive) { steamLocomotive.ToggleCylinderCocks(); } @@ -2210,7 +2152,7 @@ public override AITrain.AI_MOVEMENT_STATE HandleAction(Train thisTrain, int pres locomotive = thisTrain.FindLeadLocomotive(); ((MSTSLocomotive)locomotive).ManualHorn = false; } - return currentMvmtState; // Restore previous MovementState + return currentMvmtState; // Restore previous MovementState } return movementState; } @@ -2241,8 +2183,8 @@ public override AITrain.AI_MOVEMENT_STATE ProcessAction(Train thisTrain, int pre break; case AITrain.AI_MOVEMENT_STATE.STOPPED: - if (thisTrain is AITrain) - movementState = ((AITrain)thisTrain).UpdateStoppedState(elapsedClockSeconds); + if (thisTrain is AITrain train) + movementState = train.UpdateStoppedState(elapsedClockSeconds); break; default: break; @@ -2252,7 +2194,6 @@ public override AITrain.AI_MOVEMENT_STATE ProcessAction(Train thisTrain, int pre return movementState; } - } //================================================================================================// @@ -2260,7 +2201,6 @@ public override AITrain.AI_MOVEMENT_STATE ProcessAction(Train thisTrain, int pre /// AuxActionControlStoppedItem /// A specific class used at run time to manage the starting of a steam train /// - public class AuxActionControlStoppedItem : AuxActionItem { public enum LOCAL_ACTION @@ -2272,8 +2212,8 @@ public enum LOCAL_ACTION END } - public int PreDelay; // PreDelay gives the time in second before the action must take effect - public int Delay; // Delay is the delay of the caller + public int PreDelay; // PreDelay gives the time in second before the action must take effect + public int Delay; // Delay is the delay of the caller public int Duration; // ActionDuration gives how long it takes public int ActualDepart; LOCAL_ACTION localStep = LOCAL_ACTION.NOT_STARTED; @@ -2283,7 +2223,6 @@ public enum LOCAL_ACTION /// AuxActionControlItem /// The specific constructor for Control Stopped action /// - public AuxActionControlStoppedItem(AuxActionRef thisItem, AI_ACTION_TYPE thisAction) : base(thisItem, thisAction) { @@ -2295,7 +2234,6 @@ public enum LOCAL_ACTION /// AsString /// Used by debugging in HUDWindows. /// - public override string AsString(AITrain thisTrain) { return " Steam("; @@ -2351,12 +2289,12 @@ public override AITrain.AI_MOVEMENT_STATE InitAction(Train thisTrain, int presen TrainCar locomotive = thisTrain.FindLeadLocomotive(); if (!(locomotive is MSTSSteamLocomotive)) { - return currentMvmtState; // Restore previous MovementState + return currentMvmtState; // Restore previous MovementState } Processing = true; int correctedTime = presentTime; ActualDepart = correctedTime + (Delay - PreDelay); - localStep = LOCAL_ACTION.INIT_DONE; // NOT_STARTED -> INIT_DONE + localStep = LOCAL_ACTION.INIT_DONE; // NOT_STARTED -> INIT_DONE return AITrain.AI_MOVEMENT_STATE.HANDLE_ACTION; } @@ -2386,7 +2324,7 @@ public override AITrain.AI_MOVEMENT_STATE HandleAction(Train thisTrain, int pres else if (Triggered && localStep == LOCAL_ACTION.END) { thisTrain.AuxActionsContain.Remove(this); - if ((locomotive is MSTSSteamLocomotive)) + if (locomotive is MSTSSteamLocomotive) { steamLocomotive.ToggleCylinderCocks(); } @@ -2399,7 +2337,7 @@ public override AITrain.AI_MOVEMENT_STATE HandleAction(Train thisTrain, int pres locomotive = thisTrain.FindLeadLocomotive(); ((MSTSLocomotive)locomotive).ManualHorn = false; } - return currentMvmtState; // Restore previous MovementState + return currentMvmtState; // Restore previous MovementState } return movementState; } @@ -2430,8 +2368,8 @@ public override AITrain.AI_MOVEMENT_STATE ProcessAction(Train thisTrain, int pre break; case AITrain.AI_MOVEMENT_STATE.STOPPED: - if (thisTrain is AITrain) - movementState = ((AITrain)thisTrain).UpdateStoppedState(elapsedClockSeconds); + if (thisTrain is AITrain train) + movementState = train.UpdateStoppedState(elapsedClockSeconds); break; default: break; @@ -2441,7 +2379,6 @@ public override AITrain.AI_MOVEMENT_STATE ProcessAction(Train thisTrain, int pre return movementState; } - } //================================================================================================// @@ -2449,7 +2386,6 @@ public override AITrain.AI_MOVEMENT_STATE ProcessAction(Train thisTrain, int pre /// AuxActionSignalItem /// A specific class used at run time to manage a Signal Action /// - public class AuxActionSignalItem : AuxActionItem { int Delay; @@ -2461,7 +2397,6 @@ public class AuxActionSignalItem : AuxActionItem /// AuxActionSignalItem /// The specific constructor for Signal action /// - public AuxActionSignalItem(AuxActionRef thisItem, AI_ACTION_TYPE thisAction) : base(thisItem, thisAction) { @@ -2473,7 +2408,6 @@ public class AuxActionSignalItem : AuxActionItem /// AsString /// Used by debugging in HUDWindows. /// - public override string AsString(AITrain thisTrain) { return " SigH("; @@ -2485,7 +2419,7 @@ public override bool CanActivate(Train thisTrain, float SpeedMpS, bool reschedul return false; float[] distancesM = ((AIAuxActionsRef)ActionRef).CalculateDistancesToNextAction(thisTrain, SpeedMpS, reschedule); - if (RequiredDistance < thisTrain.DistanceTravelledM) // trigger point + if (RequiredDistance < thisTrain.DistanceTravelledM) // Trigger point { return true; } @@ -2544,7 +2478,7 @@ public override AITrain.AI_MOVEMENT_STATE HandleAction(Train thisTrain, int pres TrainCar locomotive = thisTrain.FindLeadLocomotive(); ((MSTSLocomotive)locomotive).ManualHorn = false; } - return currentMvmtState; // Restore previous MovementState + return currentMvmtState; // Restore previous MovementState } return movementState; } @@ -2556,7 +2490,6 @@ public override AITrain.AI_MOVEMENT_STATE HandleAction(Train thisTrain, int pres /// AuxActSigDelegate /// Used to postpone the signal clear after WP /// - public class AuxActSigDelegate : AuxActionItem { public int ActualDepart; @@ -2567,7 +2500,6 @@ public class AuxActSigDelegate : AuxActionItem /// AuxActSigDelegate Item /// The specific constructor for AuxActSigDelegate action /// - public AuxActSigDelegate(AuxActionRef thisItem, AI_ACTION_TYPE thisAction) : base(thisItem, thisAction) { @@ -2579,7 +2511,6 @@ public class AuxActSigDelegate : AuxActionItem /// AsString /// Used by debugging in HUDWindows. /// - public override string AsString(AITrain thisTrain) { return " SigDlgt("; @@ -2627,7 +2558,7 @@ public override bool CanActivate(Train thisTrain, float SpeedMpS, bool reschedul if (!reschedule && ((AIActSigDelegateRef)ActionRef).IsAbsolute) { TrackCircuitSection thisSection = thisTrain.signalRef.TrackCircuitList[((AIActSigDelegateRef)ActionRef).TCSectionIndex]; - if (((thisSection.CircuitState.TrainReserved != null && thisSection.CircuitState.TrainReserved.Train == thisTrain) || thisSection.CircuitState.ThisTrainOccupying(thisTrain) ) && + if (((thisSection.CircuitState.TrainReserved != null && thisSection.CircuitState.TrainReserved.Train == thisTrain) || thisSection.CircuitState.ThisTrainOccupying(thisTrain)) && ((AIActSigDelegateRef)ActionRef).EndSignalIndex != -1) return true; } @@ -2639,14 +2570,10 @@ public override bool CanActivate(Train thisTrain, float SpeedMpS, bool reschedul public override bool CanRemove(Train thisTrain) { - if (Processing && (currentMvmtState == AITrain.AI_MOVEMENT_STATE.STOPPED || currentMvmtState == AITrain.AI_MOVEMENT_STATE.HANDLE_ACTION)) - return true; - if (SignalReferenced == null) - return true; - return false; + return (Processing && (currentMvmtState == AITrain.AI_MOVEMENT_STATE.STOPPED || currentMvmtState == AITrain.AI_MOVEMENT_STATE.HANDLE_ACTION)) +|| SignalReferenced == null; } - public override bool ValidAction(Train thisTrain) { bool actionValid = CanActivate(thisTrain, thisTrain.SpeedMpS, true); @@ -2689,7 +2616,7 @@ public override AITrain.AI_MOVEMENT_STATE HandleAction(Train thisTrain, int pres SignalReferenced.UnlockForTrain(thisTrain.Number, thisTrain.TCRoute.activeSubpath); else { -// locked = true; + // locked = true; Trace.TraceWarning("SignalObject trItem={0}, trackNode={1}, wasn't locked for train {2}.", SignalReferenced.trItem, SignalReferenced.trackNode, thisTrain.Number); } @@ -2723,17 +2650,16 @@ public override AITrain.AI_MOVEMENT_STATE HandleAction(Train thisTrain, int pres File.AppendAllText(@"C:\temp\checkpath.txt", "AITRain " + thisTrain.Number + "! No more AuxActions...\n"); } #endif - return (thisTrain is AITrain && (thisTrain as AITrain).MovementState == AITrain.AI_MOVEMENT_STATE.STATION_STOP ? AITrain.AI_MOVEMENT_STATE.STATION_STOP : AITrain.AI_MOVEMENT_STATE.STOPPED); + return thisTrain is AITrain && (thisTrain as AITrain).MovementState == AITrain.AI_MOVEMENT_STATE.STATION_STOP ? AITrain.AI_MOVEMENT_STATE.STATION_STOP : AITrain.AI_MOVEMENT_STATE.STOPPED; } return movementState; } public override AITrain.AI_MOVEMENT_STATE ProcessAction(Train thisTrain, int presentTime, float elapsedClockSeconds, AITrain.AI_MOVEMENT_STATE movementState) { - movementState = base.ProcessAction(thisTrain, presentTime, elapsedClockSeconds, movementState); + movementState = base.ProcessAction(thisTrain, presentTime, elapsedClockSeconds, movementState); return movementState; } } - -#endregion + #endregion } diff --git a/Source/Orts.Simulation/Simulation/AIs/AIPath.cs b/Source/Orts.Simulation/Simulation/AIs/AIPath.cs index 96fdb86982..ab4e6b44cc 100644 --- a/Source/Orts.Simulation/Simulation/AIs/AIPath.cs +++ b/Source/Orts.Simulation/Simulation/AIs/AIPath.cs @@ -22,14 +22,14 @@ * Could this be used for player trains also? * */ -using Orts.Formats.Msts; -using Orts.Formats.OR; -using ORTS.Common; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; +using Orts.Formats.Msts; +using Orts.Formats.OR; +using ORTS.Common; namespace Orts.Simulation.AIs { @@ -42,10 +42,10 @@ public class AIPath #if ACTIVITY_EDITOR public ORRouteConfig orRouteConfig { get; protected set; } #endif - public AIPathNode FirstNode; // path starting node - //public AIPathNode LastVisitedNode; not used anymore + public AIPathNode FirstNode; // Path starting node + //public AIPathNode LastVisitedNode; not used anymore --- TODO: Remove? public List Nodes = new List(); - public string pathName; //name of the path to be able to print it. + public string pathName; // Name of the path to be able to print it. /// /// Creates an AIPath from PAT file information. @@ -84,11 +84,11 @@ public AIPath(TDBFile TDB, TSectionDatFile tsectiondat, string filePath) node.Index = i; TrPathNode tpn = patFile.TrPathNodes[i]; - // find TVNindex to next main node. + // Find TVNindex to next main node. if (tpn.HasNextMainNode) { node.NextMainNode = Nodes[(int)tpn.nextMainNode]; - node.NextMainTVNIndex = node.FindTVNIndex(node.NextMainNode, TDB, tsectiondat, i == 0 ? -1 : Nodes[i-1].NextMainTVNIndex ); + node.NextMainTVNIndex = node.FindTVNIndex(node.NextMainNode, TDB, tsectiondat, i == 0 ? -1 : Nodes[i - 1].NextMainTVNIndex); if (node.JunctionIndex >= 0) node.IsFacingPoint = TestFacingPoint(node.JunctionIndex, node.NextMainTVNIndex); if (node.NextMainTVNIndex < 0) @@ -99,7 +99,7 @@ public AIPath(TDBFile TDB, TSectionDatFile tsectiondat, string filePath) } } - // find TVNindex to next siding node + // Find TVNindex to next siding node if (tpn.HasNextSidingNode) { node.NextSidingNode = Nodes[(int)tpn.nextSidingNode]; @@ -120,14 +120,13 @@ public AIPath(TDBFile TDB, TSectionDatFile tsectiondat, string filePath) FindSidingEnds(); - if (fatalerror) Nodes = null; // invalid path - do not return any nodes + if (fatalerror) Nodes = null; // Invalid path - do not return any nodes } /// /// constructor out of other path /// /// - public AIPath(AIPath otherPath) { TrackDB = otherPath.TrackDB; ; @@ -138,8 +137,7 @@ public AIPath(AIPath otherPath) Nodes.Add(new AIPathNode(otherNode)); } - // set correct node references - + // Set correct node references for (int iNode = 0; iNode <= otherPath.Nodes.Count - 1; iNode++) { AIPathNode otherNode = otherPath.Nodes[iNode]; @@ -190,7 +188,7 @@ private void FindSidingEnds() // kvp.Value.IsLastSwitchUse = true; } - // restore game state + // Restore game state public AIPath(TrackDatabaseFile TDB, TrackSectionsFile tsectiondat, BinaryReader inf) { pathName = inf.ReadString(); @@ -211,13 +209,10 @@ public AIPath(TrackDatabaseFile TDB, TrackSectionsFile tsectiondat, BinaryReader public AIPathNode ReadNode(BinaryReader inf) { int index = inf.ReadInt32(); - if (index < 0 || index > Nodes.Count) - return null; - else - return Nodes[index]; + return index < 0 || index > Nodes.Count ? null : Nodes[index]; } - // save game state + // Save game state public void Save(BinaryWriter outf) { outf.Write(pathName); @@ -234,7 +229,7 @@ public void Save(BinaryWriter outf) public static void WriteNode(BinaryWriter outf, AIPathNode node) { if (node == null) - outf.Write((int)-1); + outf.Write(-1); else outf.Write(node.Index); } @@ -248,9 +243,7 @@ private bool TestFacingPoint(int junctionIndex, int vectorIndex) if (junctionIndex < 0 || vectorIndex < 0) return false; TrackNode tn = TrackDB.TrackNodes[junctionIndex]; - if (tn.TrJunctionNode == null || tn.TrPins[0].Link == vectorIndex) - return false; - return true; + return tn.TrJunctionNode != null && tn.TrPins[0].Link != vectorIndex; } } @@ -292,7 +285,6 @@ public AIPathNode(TrPathNode tpn, TrackPDP pdp, TrackDB trackDB, bool isTimetabl /// Constructor from other AIPathNode /// /// - public AIPathNode(AIPathNode otherNode) { ID = otherNode.ID; @@ -301,8 +293,8 @@ public AIPathNode(AIPathNode otherNode) WaitTimeS = otherNode.WaitTimeS; WaitUntil = otherNode.WaitUntil; NCars = otherNode.NCars; - NextMainNode = null; // set after completion of copying to get correct reference - NextSidingNode = null; // set after completion of copying to get correct reference + NextMainNode = null; // Set after completion of copying to get correct reference + NextSidingNode = null; // Set after completion of copying to get correct reference NextMainTVNIndex = otherNode.NextMainTVNIndex; NextSidingTVNIndex = otherNode.NextSidingTVNIndex; Location = otherNode.Location; @@ -327,60 +319,61 @@ public AIPathNode(AIPathNode otherNode) private void InterpretPathNodeFlags(TrPathNode tpn, TrackPDP pdp, bool isTimetableMode) { if ((tpn.pathFlags & 03) == 0) return; - // bit 0 and/or bit 1 is set. + // Bit 0 and/or bit 1 is set. if ((tpn.pathFlags & 01) != 0) { - // if bit 0 is set: reversal + // If bit 0 is set: reversal Type = AIPathNodeType.Reverse; } else { - // bit 0 is not set, but bit 1 is set:waiting point + // Bit 0 is not set, but bit 1 is set: waiting point Type = AIPathNodeType.Stop; - // tests showed me that value 9 in pdp is generated when the waiting point (or also - //a path start or end point) are dragged within the path editor of the MSTS activity editor; the points are still valid; + // Tests showed me that value 9 in pdp is generated when the waiting point (or also + // a path start or end point) are dragged within the path editor of the MSTS activity editor; the points are still valid; // however, as a contradictory case of the past has been reported, the check is skipped only when the enhanced compatibility flag is on; - if (pdp.IsInvalid && isTimetableMode) // not a valid point + if (pdp.IsInvalid && isTimetableMode) // Not a valid point { Type = AIPathNodeType.Invalid; } } WaitTimeS = (int)((tpn.pathFlags >> 16) & 0xffff); // get the AAAA part. - // computations for absolute wait times are made within AITrain.cs -/* if (WaitTimeS >= 30000 && WaitTimeS < 40000) - { - // real wait time. - // waitTimeS (in decimal notation) = 3HHMM (hours and minuts) - int hour = (WaitTimeS / 100) % 100; - int minute = WaitTimeS % 100; - WaitUntil = 60 * (minute + 60 * hour); - WaitTimeS = 0; - }*/ + // computations for absolute wait times are made within AITrain.cs + // TODO: Remove? + /* if (WaitTimeS >= 30000 && WaitTimeS < 40000) + { + // real wait time. + // waitTimeS (in decimal notation) = 3HHMM (hours and minuts) + int hour = (WaitTimeS / 100) % 100; + int minute = WaitTimeS % 100; + WaitUntil = 60 * (minute + 60 * hour); + WaitTimeS = 0; + }*/ // computations are made within AITrain.cs -/* else if (WaitTimeS >= 40000 && WaitTimeS < 60000) - { - // Uncouple if a wait=stop point - // waitTimeS (in decimal notation) = 4NNSS (uncouple NN cars, wait SS seconds) - // or 5NNSS (uncouple NN cars, keep rear, wait SS seconds) - NCars = (WaitTimeS / 100) % 100; - if (WaitTimeS >= 50000) - NCars = -NCars; - WaitTimeS %= 100; - if (Type == AIPathNodeType.Stop) - Type = AIPathNodeType.Uncouple; - } - else if (WaitTimeS >= 60000) // this is old and should be removed/reused - { - // waitTimes = 6xSSS with waitTime SSS seconds. - WaitTimeS %= 1000; - } */ + /* else if (WaitTimeS >= 40000 && WaitTimeS < 60000) + { + // Uncouple if a wait=stop point + // waitTimeS (in decimal notation) = 4NNSS (uncouple NN cars, wait SS seconds) + // or 5NNSS (uncouple NN cars, keep rear, wait SS seconds) + NCars = (WaitTimeS / 100) % 100; + if (WaitTimeS >= 50000) + NCars = -NCars; + WaitTimeS %= 100; + if (Type == AIPathNodeType.Stop) + Type = AIPathNodeType.Uncouple; + } + else if (WaitTimeS >= 60000) // this is old and should be removed/reused + { + // waitTimes = 6xSSS with waitTime SSS seconds. + WaitTimeS %= 1000; + } */ } - // restore game state + // Restore game state public AIPathNode(BinaryReader inf) { ID = inf.ReadInt32(); @@ -401,7 +394,7 @@ public AIPathNode(BinaryReader inf) Location.Location.Z = inf.ReadSingle(); } - // save game state + // Save game state public void Save(BinaryWriter outf) { outf.Write(ID); @@ -429,7 +422,7 @@ public int FindTVNIndex(AIPathNode nextNode, TrackDatabaseFile TDB, TrackSection int junctionIndexThis = JunctionIndex; int junctionIndexNext = nextNode.JunctionIndex; - // if this is no junction, try to find the TVN index + // If this is no junction, try to find the TVN index if (junctionIndexThis < 0) { try @@ -455,7 +448,7 @@ public int FindTVNIndex(AIPathNode nextNode, TrackDatabaseFile TDB, TrackSection } } - //both this node and the next node are junctions: find the vector node connecting them. + // Both this node and the next node are junctions: find the vector node connecting them. var iCand = -1; for (int i = 0; i < TDB.TrackDB.TrackNodes.Count(); i++) { @@ -516,7 +509,7 @@ public static int FindJunctionOrEndIndex(WorldLocation location, TrackDB trackDB float dz = tn.UiD.Z - location.Location.Z; dz += (tn.UiD.TileZ - location.TileZ) * 2048; float dy = tn.UiD.Y - location.Location.Y; - float d = dx * dx + dy * dy + dz * dz; + float d = (dx * dx) + (dy * dy) + (dz * dz); if (bestDistance2 > d) { bestIndex = j; diff --git a/Source/Orts.Simulation/Simulation/AIs/AITrain.cs b/Source/Orts.Simulation/Simulation/AIs/AITrain.cs index 9df89b8eb4..c0c1a9abee 100644 --- a/Source/Orts.Simulation/Simulation/AIs/AITrain.cs +++ b/Source/Orts.Simulation/Simulation/AIs/AITrain.cs @@ -52,25 +52,25 @@ public class AITrain : Train public int UiD; public AIPath Path; - public float MaxDecelMpSSP = 1.0f; // maximum decelleration - public float MaxAccelMpSSP = 1.0f; // maximum accelleration - public float MaxDecelMpSSF = 0.8f; // maximum decelleration - public float MaxAccelMpSSF = 0.5f; // maximum accelleration - public float MaxDecelMpSS = 0.5f; // maximum decelleration - public float MaxAccelMpSS = 1.0f; // maximum accelleration - public float Efficiency = 1.0f; // train efficiency - public float LastSpeedMpS; // previous speed - public int Alpha10 = 10; // 10*alpha - - public bool PreUpdate; // pre update state - public AIActionItem nextActionInfo; // no next action - public AIActionItem nextGenAction; // Can't remove GenAction if already active but we need to manage the normal Action, so - public float NextStopDistanceM; // distance to next stop node - public int? StartTime; // starting time - public bool PowerState = true; // actual power state : true if power in on - public float MaxVelocityA = 30.0f; // max velocity as set in .con file + public float MaxDecelMpSSP = 1.0f; // maximum decelleration + public float MaxAccelMpSSP = 1.0f; // maximum accelleration + public float MaxDecelMpSSF = 0.8f; // maximum decelleration + public float MaxAccelMpSSF = 0.5f; // maximum accelleration + public float MaxDecelMpSS = 0.5f; // maximum decelleration + public float MaxAccelMpSS = 1.0f; // maximum accelleration + public float Efficiency = 1.0f; // train efficiency + public float LastSpeedMpS; // previous speed + public int Alpha10 = 10; // 10*alpha + + public bool PreUpdate; // pre update state + public AIActionItem nextActionInfo; // no next action + public AIActionItem nextGenAction; // Can't remove GenAction if already active but we need to manage the normal Action, so + public float NextStopDistanceM; // distance to next stop node + public int? StartTime; // starting time + public bool PowerState = true; // actual power state : true if power in on + public float MaxVelocityA = 30.0f; // max velocity as set in .con file public Service_Definition ServiceDefinition = null; // train's service definition in .act file - public bool UncondAttach = false; // if false it states that train will unconditionally attach to a train on its path + public bool UncondAttach = false; // if false it states that train will unconditionally attach to a train on its path public float doorOpenDelay = -1f; public float doorCloseAdvance = -1f; @@ -115,7 +115,7 @@ public enum AI_START_MOVEMENT public AI AI; - // SPA: Add public in order to be able to get these infos in new AIActionItems + // SPA: Add public in order to be able to get these infos in new AIActionItems public static float keepDistanceStatTrainM_P = 10.0f; // stay 10m behind stationary train (pass in station) public static float keepDistanceStatTrainM_F = 50.0f; // stay 50m behind stationary train (freight or pass outside station) public static float followDistanceStatTrainM = 30.0f; // min dist for starting to follow @@ -176,7 +176,7 @@ public AITrain(Simulator simulator) //================================================================================================// /// - /// convert route and build station list + /// Convert route and build station list /// public void CreateRoute() @@ -195,7 +195,7 @@ public void CreateRoute() //================================================================================================// /// - /// convert route and build station list + /// Convert route and build station list /// public void CreateRoute(bool usePosition) @@ -233,14 +233,7 @@ public AITrain(Simulator simulator, BinaryReader inf, AI airef) if (Cars.Count < standardTrainMinCarNo) activityClearingDistanceM = shortClearingDistanceM; int startTimeValue = inf.ReadInt32(); - if (startTimeValue < 0) - { - StartTime = null; - } - else - { - StartTime = startTimeValue; - } + StartTime = startTimeValue < 0 ? null : (int?)startTimeValue; PowerState = inf.ReadBoolean(); Alpha10 = inf.ReadInt32(); @@ -253,21 +246,21 @@ public AITrain(Simulator simulator, BinaryReader inf, AI airef) UncondAttach = inf.ReadBoolean(); doorCloseAdvance = inf.ReadSingle(); doorOpenDelay = inf.ReadSingle(); - if ( !Simulator.TimetableMode && doorOpenDelay <= 0 && doorCloseAdvance > 0 && Simulator.OpenDoorsInAITrains && + if (!Simulator.TimetableMode && doorOpenDelay <= 0 && doorCloseAdvance > 0 && Simulator.OpenDoorsInAITrains && MovementState == AI_MOVEMENT_STATE.STATION_STOP && StationStops.Count > 0) { StationStop thisStation = StationStops[0]; var frontIsFront = thisStation.PlatformReference == thisStation.PlatformItem.PlatformFrontUiD; - foreach (MSTSWagon car in Cars) + foreach (MSTSWagon car in Cars.Cast()) { if (thisStation.PlatformItem.PlatformSide[0]) { - //open left doors + // Open left doors SetDoors(frontIsFront ? DoorSide.Right : DoorSide.Left, true); } if (thisStation.PlatformItem.PlatformSide[1]) { - //open right doors + // Open right doors SetDoors(frontIsFront ? DoorSide.Left : DoorSide.Right, true); } } @@ -278,7 +271,7 @@ public AITrain(Simulator simulator, BinaryReader inf, AI airef) int serviceListCount = inf.ReadInt32(); if (serviceListCount > 0) RestoreServiceDefinition(inf, serviceListCount); - // set signals and actions if train is active train + // Set signals and actions if train is active train bool activeTrain = true; @@ -298,8 +291,8 @@ public AITrain(Simulator simulator, BinaryReader inf, AI airef) CheckSignalObjects(); if (MovementState != AI_MOVEMENT_STATE.SUSPENDED) ObtainRequiredActions(0); } - // associate location events - if (Simulator.ActivityRun != null) Simulator.ActivityRun.AssociateEvents(this); + // Associate location events + Simulator.ActivityRun?.AssociateEvents(this); LastSpeedMpS = SpeedMpS; } @@ -323,7 +316,7 @@ public void RestoreServiceDefinition(BinaryReader inf, int serviceLC) public override void Save(BinaryWriter outf) { - // if something changes in this list, it must be changed also in Save(BinaryWriter outf) within TTTrain.cs + // If something changes in this list, it must be changed also in Save(BinaryWriter outf) within TTTrain.cs outf.Write("AI"); base.Save(outf); outf.Write(UiD); @@ -356,7 +349,7 @@ public override void Save(BinaryWriter outf) else outf.Write(-1); } - // call base save method only + // Call base save method only public void SaveBase(BinaryWriter outf) { base.Save(outf); @@ -384,9 +377,9 @@ public void SaveBase(BinaryWriter outf) AITrainBrakePercent = 0; FirstCar.CurrentElevationPercent = 100f * FirstCar.WorldPosition.XNAMatrix.M32; - // give it a bit more gas if it is uphill + // Give it a bit more gas if it is uphill if (FirstCar.CurrentElevationPercent < -2.0) initialThrottlepercent = 40f; - // better block gas if it is downhill + // Better block gas if it is downhill else if (FirstCar.CurrentElevationPercent > 1.0) initialThrottlepercent = 0f; AdjustControlsBrakeOff(); AITrainThrottlePercent = initialThrottlepercent; @@ -399,7 +392,7 @@ public void SaveBase(BinaryWriter outf) //================================================================================================// /// /// Post Init (override from Train) - /// perform all actions required to start + /// Performs all actions required to start /// public override bool PostInit() @@ -422,7 +415,7 @@ public override bool PostInit() } } #endif - // check deadlocks; do it after placing for player train, like done for it when autopilot option unchecked + // Check deadlocks; do it after placing for player train, like done for it when autopilot option unchecked if (!IsActualPlayerTrain) CheckDeadlock(ValidRoute[0], Number); @@ -431,29 +424,29 @@ public override bool PostInit() var activityFile = Simulator.Activity.Tr_Activity.Tr_Activity_File; LevelCrossingHornPattern = activityFile.AIBlowsHornAtLevelCrossings ? AILevelCrossingHornPattern.CreateInstance(activityFile.AILevelCrossingHornPattern) : null; - // set initial position and state + // Set initial position and state bool atStation = false; - bool validPosition = InitialTrainPlacement(); // Check track and if clear, set occupied + bool validPosition = InitialTrainPlacement(); // Check track and if clear, set occupied if (validPosition) { if (IsFreight) { - MaxAccelMpSS = MaxAccelMpSSF; // set freigth accel and decel + MaxAccelMpSS = MaxAccelMpSSF; // Set freight acceleration and deceleration MaxDecelMpSS = MaxAccelMpSSF; } else { - MaxAccelMpSS = MaxAccelMpSSP; // set passenger accel and decel + MaxAccelMpSS = MaxAccelMpSSP; // Set passenger accel. and decel. MaxDecelMpSS = MaxDecelMpSSP; if (TrainMaxSpeedMpS > 55.0f) { - MaxDecelMpSS = 2.5f * MaxDecelMpSSP; // higher decel for very high speed trains + MaxDecelMpSS = 2.5f * MaxDecelMpSSP; // Higher decel. for very high speed trains } else if (TrainMaxSpeedMpS > 40.0f) { - MaxDecelMpSS = 1.5f * MaxDecelMpSSP; // higher decel for high speed trains + MaxDecelMpSS = 1.5f * MaxDecelMpSSP; // Higher decel. for high speed trains } else @@ -461,7 +454,7 @@ public override bool PostInit() var carF = Cars[0]; var carL = Cars[Cars.Count - 1]; if (carF.IsDriveable && carF.HasPassengerCapacity && (carF is MSTSElectricLocomotive) - && carL.IsDriveable && carL.HasPassengerCapacity && (carL is MSTSElectricLocomotive)) // EMU or DMU train, higher decel + && carL.IsDriveable && carL.HasPassengerCapacity && (carL is MSTSElectricLocomotive)) // EMU or DMU train, higher decel. { MaxAccelMpSS = 1.5f * MaxAccelMpSS; MaxDecelMpSS = 2f * MaxDecelMpSSP; @@ -474,13 +467,13 @@ public override bool PostInit() BuildStationList(activityClearingDistanceM); // This creates problems in push-pull paths -// StationStops.Sort(); + // StationStops.Sort(); if (!atStation && StationStops.Count > 0 && this != Simulator.Trains[0]) { if (MaxVelocityA > 0 && ServiceDefinition != null && ServiceDefinition.ServiceList.Count > 0) { - // gets efficiency from .act file to override TrainMaxSpeedMpS computed from .srv efficiency + // Gets efficiency from .act file to override TrainMaxSpeedMpS computed from .srv efficiency var sectionEfficiency = ServiceDefinition.ServiceList[0].Efficiency; if (Simulator.Settings.ActRandomizationLevel > 0) RandomizeEfficiency(ref sectionEfficiency); if (sectionEfficiency > 0) @@ -488,13 +481,13 @@ public override bool PostInit() } } - InitializeSignals(false); // Get signal information + InitializeSignals(false); // Get signal information if (IsActualPlayerTrain) CheckDeadlock(ValidRoute[0], Number); - TCRoute.SetReversalOffset(Length, false); // set reversal information for first subpath - SetEndOfRouteAction(); // set action to ensure train stops at end of route + TCRoute.SetReversalOffset(Length, false); // Set reversal information for first subpath + SetEndOfRouteAction(); // Set action to ensure train stops at end of route - // check if train starts at station stop + // Check if train starts at station stop AuxActionsContain.SetAuxAction(this); if (StationStops.Count > 0) { @@ -505,12 +498,12 @@ public override bool PostInit() { if (StationStops.Count > 0) { - SetNextStationAction(); // set station details + SetNextStationAction(); // Set station details } if (TrainHasPower()) { - MovementState = AI_MOVEMENT_STATE.INIT; // start in STOPPED mode to collect info + MovementState = AI_MOVEMENT_STATE.INIT; // Start in STOPPED mode to collect info } } } @@ -544,7 +537,7 @@ public override bool PostInit() File.AppendAllText(@"C:\temp\checktrain.txt", "ValPos: " + validPosition.ToString() + "\n"); } - return (validPosition); + return validPosition; } //================================================================================================// @@ -556,23 +549,21 @@ public virtual bool CheckInitialStation() { bool atStation = false; - // get station details - + // Get station details StationStop thisStation = StationStops[0]; if (thisStation.SubrouteIndex != TCRoute.activeSubpath) { - return (false); + return false; } if (thisStation.ActualStopType != StationStop.STOPTYPE.STATION_STOP) { - return (false); + return false; } atStation = CheckStationPosition(thisStation.PlatformItem, thisStation.Direction, thisStation.TCSectionIndex); - // At station : set state, create action item - + // At station: set state, create action item if (atStation) { thisStation.ActualArrival = -1; @@ -591,7 +582,7 @@ public virtual bool CheckInitialStation() #endif } - return (atStation); + return atStation; } //================================================================================================// @@ -601,19 +592,18 @@ public virtual bool CheckInitialStation() public override AI_MOVEMENT_STATE GetAIMovementState() { - return (ControlMode == TRAIN_CONTROL.INACTIVE ? AI_MOVEMENT_STATE.AI_STATIC : MovementState); + return ControlMode == TRAIN_CONTROL.INACTIVE ? AI_MOVEMENT_STATE.AI_STATIC : MovementState; } - //================================================================================================// /// /// Get AI Movement State /// /// - private void RandomizeEfficiency (ref float efficiency) + private void RandomizeEfficiency(ref float efficiency) { efficiency *= 100; - var incOrDecEfficiency = DateTime.Now.Millisecond % 2 == 0 ? true : false; + var incOrDecEfficiency = DateTime.Now.Millisecond % 2 == 0; if (incOrDecEfficiency) efficiency = Math.Min(100, efficiency + RandomizedDelayWithThreshold(20)); // increment it else if (efficiency > 50) efficiency = Math.Max(50, efficiency - RandomizedDelayWithThreshold(20)); // decrement it efficiency /= 100; @@ -645,7 +635,7 @@ public void AIUpdate(float elapsedClockSeconds, double clockTime, bool preUpdate } #endif - PreUpdate = preUpdate; // flag for pre-update phase + PreUpdate = preUpdate; // Flag for pre-update phase #if WITH_PATH_DEBUG int lastIndex = PreviousPosition[0].RouteListIndex; int presentIndex = PresentPosition[0].RouteListIndex; @@ -682,11 +672,10 @@ public void AIUpdate(float elapsedClockSeconds, double clockTime, bool preUpdate AITrainBrakePercent = 100; } - // update position, route clearance and objects - + // Update position, route clearance and objects if (MovementState == AI_MOVEMENT_STATE.AI_STATIC) { - CalculatePositionOfCars(0, 0); //required to make train visible ; set elapsed time to zero to avoid actual movement + CalculatePositionOfCars(0, 0); // Required to make train visible; set elapsed time to zero to avoid actual movement } else { @@ -699,22 +688,19 @@ public void AIUpdate(float elapsedClockSeconds, double clockTime, bool preUpdate AIPreUpdate(elapsedClockSeconds); } - // get through list of objects, determine necesarry actions - + // Get through list of objects, determine necesarry actions CheckSignalObjects(); - // check if state still matches authority level - + // Check if state still matches authority level if (MovementState != AI_MOVEMENT_STATE.INIT && ControlMode == TRAIN_CONTROL.AUTO_NODE && EndAuthorityType[0] != END_AUTHORITY.MAX_DISTANCE) // restricted authority { CheckRequiredAction(); } - // check if reversal point reached and not yet activated - but station stop has preference over reversal point + // Check if reversal point reached and not yet activated - but station stop has preference over reversal point SetReversalAction(); - // check if out of control - if so, remove - + // Check if out of control - if so, remove if (ControlMode == TRAIN_CONTROL.OUT_OF_CONTROL && TrainType != TRAINTYPE.AI_PLAYERHOSTING) { Trace.TraceInformation("Train {0} ({1}) is removed for out of control, reason : {2}", Name, Number, OutOfControlReason.ToString()); @@ -732,8 +718,7 @@ public void AIUpdate(float elapsedClockSeconds, double clockTime, bool preUpdate } } - // switch on action depending on state - + // Switch on action depending on state int presentTime = Convert.ToInt32(Math.Floor(clockTime)); #if WITH_PATH_DEBUG @@ -809,7 +794,6 @@ public void AIUpdate(float elapsedClockSeconds, double clockTime, bool preUpdate MovementState = nextActionInfo.ProcessAction(this, presentTime, elapsedClockSeconds, MovementState); } break; - } #if WITH_PATH_DEBUG //if (Simulator.Settings.EnhancedActCompatibility) @@ -993,8 +977,9 @@ public void AIUpdate(float elapsedClockSeconds, double clockTime, bool preUpdate countRequiredAction = requiredActions.Count; } #endif - // Trace.TraceWarning ("Time {0} Train no. {1} Speed {2} AllowedMaxSpeed {3} Throttle percent {4} Distance travelled {5} Movement State {6} BrakePerCent {7}", - // clockTime, Number, SpeedMpS, AllowedMaxSpeedMpS, AITrainThrottlePercent, DistanceTravelledM, MovementState, AITrainBrakePercent); + // TODO: Can we remove this? + // Trace.TraceWarning ("Time {0} Train no. {1} Speed {2} AllowedMaxSpeed {3} Throttle percent {4} Distance travelled {5} Movement State {6} BrakePerCent {7}", + // clockTime, Number, SpeedMpS, AllowedMaxSpeedMpS, AITrainThrottlePercent, DistanceTravelledM, MovementState, AITrainBrakePercent); } //================================================================================================// @@ -1004,10 +989,8 @@ public void AIUpdate(float elapsedClockSeconds, double clockTime, bool preUpdate public virtual void AIPreUpdate(float elapsedClockSeconds) { - - // calculate delta speed and speed - - float deltaSpeedMpS = (0.01f * AITrainThrottlePercent * MaxAccelMpSS - 0.01f * AITrainBrakePercent * MaxDecelMpSS) * + // Calculate delta speed and speed + float deltaSpeedMpS = ((0.01f * AITrainThrottlePercent * MaxAccelMpSS) - (0.01f * AITrainBrakePercent * MaxDecelMpSS)) * Efficiency * elapsedClockSeconds; if (AITrainBrakePercent > 0 && deltaSpeedMpS < 0 && Math.Abs(deltaSpeedMpS) > SpeedMpS) { @@ -1015,13 +998,12 @@ public virtual void AIPreUpdate(float elapsedClockSeconds) } SpeedMpS = Math.Min(TrainMaxSpeedMpS, Math.Max(0.0f, SpeedMpS + deltaSpeedMpS)); - // calculate position - + // Calculate position float distanceM = SpeedMpS * elapsedClockSeconds; - if (float.IsNaN(distanceM)) distanceM = 0;//sometimes it may become NaN, force it to be 0, so no move + if (float.IsNaN(distanceM)) distanceM = 0; // Sometimes this turns out to be NaN, force it to be 0 and prevent AI movement - // force stop + // Force stop if (distanceM > NextStopDistanceM) { #if DEBUG_REPORTS @@ -1032,7 +1014,8 @@ public virtual void AIPreUpdate(float elapsedClockSeconds) "0.0 > " + NextStopDistanceM.ToString() + " at " + DistanceTravelledM.ToString() + "\n"); #endif - // Trace.TraceWarning("Forced stop for train {0} ({1}) at speed {2}", Number, Name, SpeedMpS); + // TODO: Should this be removed? + // Trace.TraceWarning("Forced stop for train {0} ({1}) at speed {2}", Number, Name, SpeedMpS); if (CheckTrain) { File.AppendAllText(@"C:\temp\checktrain.txt", "Train " + @@ -1047,36 +1030,27 @@ public virtual void AIPreUpdate(float elapsedClockSeconds) SpeedMpS = 0; } - // set speed and position - + // Set speed and position foreach (TrainCar car in Cars) { - if (car.Flipped) - { - car.SpeedMpS = -SpeedMpS; - } - else - { - car.SpeedMpS = SpeedMpS; - } + car.SpeedMpS = car.Flipped ? -SpeedMpS : SpeedMpS; } CalculatePositionOfCars(elapsedClockSeconds, distanceM); DistanceTravelledM += distanceM; - // perform overall update - - if (ValidRoute != null) // no actions required for static objects // + // Perform overall update + if (ValidRoute != null) // no actions required for static objects { - movedBackward = CheckBackwardClearance(); // check clearance at rear // - UpdateTrainPosition(); // position update // - UpdateTrainPositionInformation(); // position linked info // - int SignalObjIndex = CheckSignalPassed(0, PresentPosition[0], PreviousPosition[0]); // check if passed signal // - UpdateSectionState(movedBackward); // update track occupation // - ObtainRequiredActions(movedBackward); // process Actions // - UpdateRouteClearanceAhead(SignalObjIndex, movedBackward, elapsedClockSeconds); // update route clearance // - UpdateSignalState(movedBackward); // update signal state // + movedBackward = CheckBackwardClearance(); // check clearance at rear + UpdateTrainPosition(); // position update + UpdateTrainPositionInformation(); // position linked info + int SignalObjIndex = CheckSignalPassed(0, PresentPosition[0], PreviousPosition[0]); // check if passed signal + UpdateSectionState(movedBackward); // update track occupation + ObtainRequiredActions(movedBackward); // process Actions + UpdateRouteClearanceAhead(SignalObjIndex, movedBackward, elapsedClockSeconds); // update route clearance + UpdateSignalState(movedBackward); // update signal state } } @@ -1098,35 +1072,32 @@ public virtual void SetReversalAction() if (reqSection >= 0 && PresentPosition[1].RouteListIndex >= reqSection && TCRoute.ReversalInfo[TCRoute.activeSubpath].ReversalActionInserted == false) { float reqDistance = SpeedMpS * SpeedMpS * MaxDecelMpSS; - float distanceToReversalPoint = 0; reqDistance = nextActionInfo != null ? Math.Min(nextActionInfo.RequiredDistance, reqDistance) : reqDistance; - - distanceToReversalPoint = ComputeDistanceToReversalPoint(); - // - /// change in authority state - check action + /// Change in authority state - check action /// public virtual void CheckRequiredAction() { - // check if train ahead + // Check if train ahead if (EndAuthorityType[0] == END_AUTHORITY.TRAIN_AHEAD) { if (MovementState != AI_MOVEMENT_STATE.STATION_STOP && MovementState != AI_MOVEMENT_STATE.STOPPED) { if (MovementState != AI_MOVEMENT_STATE.INIT_ACTION && MovementState != AI_MOVEMENT_STATE.HANDLE_ACTION) { - MovementState = AI_MOVEMENT_STATE.FOLLOWING; // start following + MovementState = AI_MOVEMENT_STATE.FOLLOWING; // Start following } } } @@ -1136,20 +1107,20 @@ public virtual void CheckRequiredAction() (nextActionInfo == null || nextActionInfo.NextAction != AIActionItem.AI_ACTION_TYPE.END_OF_AUTHORITY)) { ResetActions(true); - NextStopDistanceM = DistanceToEndNodeAuthorityM[0] - 2.0f * junctionOverlapM; + NextStopDistanceM = DistanceToEndNodeAuthorityM[0] - (2.0f * junctionOverlapM); CreateTrainAction(SpeedMpS, 0.0f, NextStopDistanceM, null, AIActionItem.AI_ACTION_TYPE.END_OF_AUTHORITY); ObtainRequiredActions(0); } } - // first handle outstanding actions + // First handle outstanding actions else if (EndAuthorityType[0] == END_AUTHORITY.END_OF_PATH && (nextActionInfo == null || nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.END_OF_ROUTE)) { ResetActions(false); - if (TCRoute.activeSubpath < TCRoute.TCRouteSubpaths.Count - 1) - NextStopDistanceM = DistanceToEndNodeAuthorityM[0] - activityClearingDistanceM; - else NextStopDistanceM = ComputeDistanceToReversalPoint() - activityClearingDistanceM; + NextStopDistanceM = TCRoute.activeSubpath < TCRoute.TCRouteSubpaths.Count - 1 + ? DistanceToEndNodeAuthorityM[0] - activityClearingDistanceM + : ComputeDistanceToReversalPoint() - activityClearingDistanceM; } } @@ -1157,7 +1128,6 @@ public virtual void CheckRequiredAction() /// /// Check all signal objects /// - public void CheckSignalObjects() { if (CheckTrain) @@ -1173,7 +1143,7 @@ public void CheckSignalObjects() if (thisInfo.speed_isWarning) continue; - // check speedlimit + // Check speedlimit if (CheckTrain) { File.AppendAllText(@"C:\temp\checktrain.txt", @@ -1193,24 +1163,11 @@ public void CheckSignalObjects() { if (!thisInfo.processed) { - bool process_req = true; - - if (ControlMode == TRAIN_CONTROL.AUTO_NODE && - thisInfo.distance_to_train > DistanceToEndNodeAuthorityM[0]) - { - process_req = false; - } - else if (thisInfo.distance_to_train > signalApproachDistanceM || - (MovementState == AI_MOVEMENT_STATE.RUNNING && SpeedMpS > setSpeed) || - MovementState == AI_MOVEMENT_STATE.ACCELERATING) - { - process_req = true; - } - else - { - process_req = false; - } - + var process_req = (ControlMode != TRAIN_CONTROL.AUTO_NODE || + thisInfo.distance_to_train <= DistanceToEndNodeAuthorityM[0]) +&& (thisInfo.distance_to_train > signalApproachDistanceM || + (MovementState == AI_MOVEMENT_STATE.RUNNING && SpeedMpS > setSpeed) || + MovementState == AI_MOVEMENT_STATE.ACCELERATING); if (process_req) { if (thisInfo.ObjectType == ObjectItemInfo.ObjectItemType.Speedlimit) @@ -1233,8 +1190,7 @@ public void CheckSignalObjects() validSpeed = setSpeed; } - // check signal state - + // Check signal state if (thisInfo.ObjectType == ObjectItemInfo.ObjectItemType.Signal && thisInfo.signal_state < MstsSignalAspect.APPROACH_1 && !thisInfo.processed && thisInfo.ObjectDetails.hasPermission != SignalObject.Permission.Granted) @@ -1261,10 +1217,10 @@ thisInfo.distance_to_train > (DistanceToEndNodeAuthorityM[0] - clearingDistanceM AITrainBrakePercent = 100; AITrainThrottlePercent = 0; NextStopDistanceM = validClearingDistanceM; - if (PreUpdate && !Simulator.TimetableMode) ObtainRequiredActions(movedBackward); // fast track to stop train; else a precious update is lost + if (PreUpdate && !Simulator.TimetableMode) ObtainRequiredActions(movedBackward); // Fast track to stop train; else a precious update is lost } } - else if (thisInfo.distance_to_train > 2.0f * signalApproachDistanceM) // set restricted only if not close + else if (thisInfo.distance_to_train > 2.0f * signalApproachDistanceM) // Set restricted only if not close { if (!thisInfo.ObjectDetails.this_sig_noSpeedReduction(SignalFunction.NORMAL)) { @@ -1283,8 +1239,7 @@ thisInfo.distance_to_train > (DistanceToEndNodeAuthorityM[0] - clearingDistanceM } } - // set processed items - must be collected as item can be processed twice (speed and signal) - + // Set processed items - must be collected as item can be processed twice (speed and signal) foreach (ObjectItemInfo thisInfo in processedList) { thisInfo.processed = true; @@ -1295,33 +1250,31 @@ thisInfo.distance_to_train > (DistanceToEndNodeAuthorityM[0] - clearingDistanceM /// /// Check for next station /// - public virtual void SetNextStationAction(bool fromAutopilotSwitch = false) { - // if train is player driven and is at station, do nothing + // If train is player driven and is at station, do nothing if (TrainType == TRAINTYPE.AI_PLAYERDRIVEN && this == Simulator.OriginalPlayerTrain && Simulator.ActivityRun.Current is ActivityTaskPassengerStopAt && ((ActivityTaskPassengerStopAt)Simulator.ActivityRun.Current).IsAtStation(this)) return; - // check if station in this subpath - + // Check if station in this subpath int stationIndex = 0; StationStop thisStation = StationStops[stationIndex]; - while (thisStation.SubrouteIndex < TCRoute.activeSubpath) // station was in previous subpath + while (thisStation.SubrouteIndex < TCRoute.activeSubpath) // Station was in previous subpath { StationStops.RemoveAt(0); - if (StationStops.Count == 0) // no more stations + if (StationStops.Count == 0) // No more stations { return; } thisStation = StationStops[0]; } - if (thisStation.SubrouteIndex > TCRoute.activeSubpath) // station is not in this subpath + if (thisStation.SubrouteIndex > TCRoute.activeSubpath) // Station is not in this subpath { return; } - // get distance to station, but not if just after switch to Autopilot and not during station stop + // Get distance to station, but not if just after switch to Autopilot and not during station stop bool validStop = false; if (!fromAutopilotSwitch || (Simulator.PlayerLocomotive != null && Simulator.ActivityRun != null && !( this == Simulator.OriginalPlayerTrain && Simulator.ActivityRun.Current is ActivityTaskPassengerStopAt && ((ActivityTaskPassengerStopAt)Simulator.ActivityRun.Current).IsAtStation(this)))) @@ -1329,17 +1282,17 @@ public virtual void SetNextStationAction(bool fromAutopilotSwitch = false) while (!validStop) { float[] distancesM = CalculateDistancesToNextStation(thisStation, TrainMaxSpeedMpS, false); - if (distancesM[0] < 0f && !(MovementState == AI_MOVEMENT_STATE.STATION_STOP && distancesM[0] != -1)) // stop is not valid + if (distancesM[0] < 0f && !(MovementState == AI_MOVEMENT_STATE.STATION_STOP && distancesM[0] != -1)) // Stop is not valid { StationStops.RemoveAt(0); if (StationStops.Count == 0) { - return; // no more stations - exit + return; // No more stations - exit } thisStation = StationStops[0]; - if (thisStation.SubrouteIndex > TCRoute.activeSubpath) return; // station not in this subpath - exit + if (thisStation.SubrouteIndex > TCRoute.activeSubpath) return; // Station not in this subpath - exit } else { @@ -1397,27 +1350,26 @@ public virtual void SetNextStationAction(bool fromAutopilotSwitch = false) /// /// Calculate actual distance and trigger distance for next station /// - public float[] CalculateDistancesToNextStation(StationStop thisStation, float presentSpeedMpS, bool reschedule) { TrackCircuitSection thisSection = signalRef.TrackCircuitList[PresentPosition[0].TCSectionIndex]; float leftInSectionM = thisSection.Length - PresentPosition[0].TCOffset; - // get station route index - if not found, return distances < 0 + // Get station route index - if not found, return distances < 0 int stationIndex0 = ValidRoute[0].GetRouteIndex(thisStation.TCSectionIndex, PresentPosition[0].RouteListIndex); int stationIndex1 = ValidRoute[0].GetRouteIndex(thisStation.TCSectionIndex, PresentPosition[1].RouteListIndex); float distanceToTrainM = -1f; - // use front position + // Use front position if (stationIndex0 >= 0) { distanceToTrainM = ValidRoute[0].GetDistanceAlongRoute(PresentPosition[0].RouteListIndex, leftInSectionM, stationIndex0, thisStation.StopOffset, true, signalRef); } - // if front beyond station, use rear position (correct for length) + // If front beyond station, use rear position (correct for length) else if (stationIndex1 >= 0) { thisSection = signalRef.TrackCircuitList[PresentPosition[1].TCSectionIndex]; @@ -1426,20 +1378,19 @@ public float[] CalculateDistancesToNextStation(StationStop thisStation, float pr leftInSectionM, stationIndex1, thisStation.StopOffset, true, signalRef) - Length; } - // if beyond station and train is stopped - return present position + // If beyond station and train is stopped - return present position if (distanceToTrainM < 0f && MovementState == AI_MOVEMENT_STATE.STATION_STOP) { - return (new float[2] { PresentPosition[0].DistanceTravelledM, 0.0f }); + return new float[2] { PresentPosition[0].DistanceTravelledM, 0.0f }; } - // if station not on route at all return negative values + // If station not on route at all return negative values if (distanceToTrainM < 0f && stationIndex0 < 0 && stationIndex1 < 0) { - return (new float[2] { -1f, -1f }); + return new float[2] { -1f, -1f }; } - // if reschedule, use actual speed - + // If reschedule, use actual speed float activateDistanceTravelledM = PresentPosition[0].DistanceTravelledM + distanceToTrainM; float triggerDistanceM = 0.0f; @@ -1453,17 +1404,15 @@ public float[] CalculateDistancesToNextStation(StationStop thisStation, float pr firstPartTime = presentSpeedMpS / (0.25f * MaxDecelMpSS); firstPartRangeM = 0.25f * MaxDecelMpSS * (firstPartTime * firstPartTime); - if (firstPartRangeM < remainingRangeM && SpeedMpS < TrainMaxSpeedMpS) // if distance left and not at max speed - // split remaining distance based on relation between acceleration and deceleration + if (firstPartRangeM < remainingRangeM && SpeedMpS < TrainMaxSpeedMpS) // If distance left and not at max speed { + // Split remaining distance based on relation between acceleration and deceleration secndPartRangeM = (remainingRangeM - firstPartRangeM) * (2.0f * MaxDecelMpSS) / (MaxDecelMpSS + MaxAccelMpSS); } triggerDistanceM = activateDistanceTravelledM - (firstPartRangeM + secndPartRangeM); } - else - - // use maximum speed + else // Use maximum speed { float deltaTime = TrainMaxSpeedMpS / MaxDecelMpSS; float brakingDistanceM = (TrainMaxSpeedMpS * deltaTime) + (0.5f * MaxDecelMpSS * deltaTime * deltaTime); @@ -1474,24 +1423,23 @@ public float[] CalculateDistancesToNextStation(StationStop thisStation, float pr distancesM[0] = activateDistanceTravelledM; distancesM[1] = triggerDistanceM; - return (distancesM); + return distancesM; } //================================================================================================// /// /// Override Switch to Signal control - /// - + /// /// Override Switch to Node control /// - public override void SwitchToNodeControl(int thisSectionIndex) { base.SwitchToNodeControl(thisSectionIndex); if (TrainType != TRAINTYPE.PLAYER) { - if (!((this is AITrain) && (this as AITrain).MovementState == AI_MOVEMENT_STATE.SUSPENDED)) + if (!((this is AITrain) && this.MovementState == AI_MOVEMENT_STATE.SUSPENDED)) { ResetActions(true); - // check if any actions must be processed immediately - + // Check if any actions must be processed immediately ObtainRequiredActions(0); } } @@ -1521,11 +1467,11 @@ public override void SwitchToNodeControl(int thisSectionIndex) public override void UpdateNodeMode() { - // update node mode + // Update node mode END_AUTHORITY oldAuthority = EndAuthorityType[0]; base.UpdateNodeMode(); - // if authoriy type changed, reset actions + // If authoriy type changed, reset actions if (EndAuthorityType[0] != oldAuthority) { ResetActions(true, false); @@ -1537,11 +1483,9 @@ public override void UpdateNodeMode() /// Update AI Static state /// /// - public override void UpdateAIStaticState(int presentTime) { - // start if start time is reached - + // Start if start time is reached if (StartTime.HasValue && StartTime.Value < presentTime && TrainHasPower()) { foreach (var car in Cars) @@ -1558,8 +1502,7 @@ public override void UpdateAIStaticState(int presentTime) return; } - // switch off power for all engines - + // Switch off power for all engines if (PowerState) { foreach (var car in Cars) @@ -1578,46 +1521,42 @@ public override void UpdateAIStaticState(int presentTime) /// /// Update train in stopped state /// - public virtual AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockSeconds) { var AuxActionnextActionInfo = nextActionInfo; var tryBraking = true; - if (SpeedMpS > 0) // if train still running force it to stop + + // TODO: Can we merge these two conditions? + if (SpeedMpS > 0) // If train still running force it to stop { SpeedMpS = 0; - Update(0); // stop the wheels from moving etc + Update(0); // Stop the wheels from moving etc AITrainThrottlePercent = 0; AITrainBrakePercent = 100; } - if (SpeedMpS < 0) // if train still running force it to stop + if (SpeedMpS < 0) // If train still running force it to stop { SpeedMpS = 0; - Update(0); // stop the wheels from moving etc + Update(0); // Stop the wheels from moving etc AITrainThrottlePercent = 0; AITrainBrakePercent = 100; - } - // check if train ahead - if so, determine speed and distance - - if (ControlMode == TRAIN_CONTROL.AUTO_NODE && - EndAuthorityType[0] == END_AUTHORITY.TRAIN_AHEAD) + // Check if there's a train ahead - if so, determine speed and distance + if (ControlMode == TRAIN_CONTROL.AUTO_NODE && EndAuthorityType[0] == END_AUTHORITY.TRAIN_AHEAD) { - - // check if train ahead is in same section + // Check if train ahead is in same section int sectionIndex = PresentPosition[0].TCSectionIndex; int startIndex = ValidRoute[0].GetRouteIndex(sectionIndex, 0); int endIndex = ValidRoute[0].GetRouteIndex(LastReservedSection[0], 0); TrackCircuitSection thisSection = signalRef.TrackCircuitList[sectionIndex]; - Dictionary trainInfo = thisSection.TestTrainAhead(this, - PresentPosition[0].TCOffset, PresentPosition[0].TCDirection); + Dictionary trainInfo = thisSection.TestTrainAhead(this, PresentPosition[0].TCOffset, PresentPosition[0].TCDirection); - // search for train ahead in route sections + // Search for train ahead in route sections for (int iIndex = startIndex + 1; iIndex <= endIndex && trainInfo.Count <= 0; iIndex++) { thisSection = signalRef.TrackCircuitList[ValidRoute[0][iIndex].TCSectionIndex]; @@ -1625,19 +1564,18 @@ public virtual AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockSe } if (trainInfo.Count <= 0) - // train is in section beyond last reserved { + // Train is in section beyond last reserved if (endIndex < ValidRoute[0].Count - 1) { thisSection = signalRef.TrackCircuitList[ValidRoute[0][endIndex + 1].TCSectionIndex]; - trainInfo = thisSection.TestTrainAhead(this, 0.0f, ValidRoute[0][endIndex + 1].Direction); } } - if (trainInfo.Count > 0) // found train + if (trainInfo.Count > 0) // Found train { - foreach (KeyValuePair trainAhead in trainInfo) // always just one + foreach (KeyValuePair trainAhead in trainInfo) // Always just one { Train OtherTrain = trainAhead.Key; if (Math.Abs(OtherTrain.SpeedMpS) < 0.001f && @@ -1647,7 +1585,7 @@ public virtual AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockSe || OtherTrain.PresentPosition[1].TCSectionIndex == TCRoute.TCRouteSubpaths[TCRoute.activeSubpath][TCRoute.TCRouteSubpaths[TCRoute.activeSubpath].Count - 1].TCSectionIndex)) { - // allow creeping closer + // Allow creeping closer CreateTrainAction(creepSpeedMpS, 0.0f, DistanceToEndNodeAuthorityM[0], null, AIActionItem.AI_ACTION_TYPE.TRAIN_AHEAD); MovementState = AI_MOVEMENT_STATE.FOLLOWING; StartMoving(AI_START_MOVEMENT.FOLLOW_TRAIN); @@ -1656,18 +1594,16 @@ public virtual AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockSe else if (Math.Abs(OtherTrain.SpeedMpS) > 0 && DistanceToEndNodeAuthorityM[0] > keepDistanceMovingTrainM) { - // train started moving + // Train started moving MovementState = AI_MOVEMENT_STATE.FOLLOWING; StartMoving(AI_START_MOVEMENT.FOLLOW_TRAIN); } } } - // if train not found, do nothing - state will change next update - + // If train not found, do nothing - state will change next update } - // Other node mode : check distance ahead (path may have cleared) - + // Other node mode: check distance ahead (path may have cleared) else if (ControlMode == TRAIN_CONTROL.AUTO_NODE && EndAuthorityType[0] != END_AUTHORITY.RESERVED_SWITCH && DistanceToEndNodeAuthorityM[0] > activityClearingDistanceM) { @@ -1676,21 +1612,20 @@ public virtual AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockSe } else if (ControlMode == TRAIN_CONTROL.AUTO_NODE && EndAuthorityType[0] == END_AUTHORITY.RESERVED_SWITCH && - DistanceToEndNodeAuthorityM[0] > 2.0f * junctionOverlapM + activityClearingDistanceM) + DistanceToEndNodeAuthorityM[0] > (2.0f * junctionOverlapM) + activityClearingDistanceM) { - NextStopDistanceM = DistanceToEndNodeAuthorityM[0] - 2.0f * junctionOverlapM; + NextStopDistanceM = DistanceToEndNodeAuthorityM[0] - (2.0f * junctionOverlapM); StartMoving(AI_START_MOVEMENT.SIGNAL_CLEARED); } - - // signal node : check state of signal - + // Signal node: check state of signal else if (ControlMode == TRAIN_CONTROL.AUTO_SIGNAL) { MstsSignalAspect nextAspect = MstsSignalAspect.UNKNOWN; bool nextPermission = false; SignalObject nextSignal = null; - // there is a next item and it is the next signal + + // There is a next item and it is the next signal if (nextActionInfo != null && nextActionInfo.ActiveItem != null && nextActionInfo.ActiveItem.ObjectDetails == NextSignalObject[0]) { @@ -1704,16 +1639,16 @@ public virtual AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockSe } nextPermission = nextSignal != null && nextSignal.hasPermission == SignalObject.Permission.Granted; - if (NextSignalObject[0] == null) // no signal ahead so switch Node control + if (NextSignalObject[0] == null) // No signal ahead so switch Node control { SwitchToNodeControl(PresentPosition[0].TCSectionIndex); NextStopDistanceM = DistanceToEndNodeAuthorityM[0]; } - + // TODO: Can we merge these two else if clauses? else if ((nextAspect > MstsSignalAspect.STOP || nextPermission) && nextAspect < MstsSignalAspect.APPROACH_1) { - // check if any other signals within clearing distance + // Check if any other signals within clearing distance bool signalCleared = true; bool withinDistance = true; @@ -1722,15 +1657,15 @@ public virtual AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockSe ObjectItemInfo nextObject = SignalObjectItems[iitem]; if (nextObject.ObjectType == ObjectItemInfo.ObjectItemType.Signal) { - if (nextObject.ObjectDetails != NextSignalObject[0]) // not signal we are waiting for + if (nextObject.ObjectDetails != NextSignalObject[0]) // Not signal we are waiting for { if (nextObject.distance_to_train > 2.0 * clearingDistanceM) { - withinDistance = false; // signal is far enough ahead + withinDistance = false; // Signal is far enough ahead } else if (nextObject.signal_state == MstsSignalAspect.STOP) { - signalCleared = false; // signal is not clear + signalCleared = false; // Signal is not clear NextSignalObject[0].ForcePropagation = true; } } @@ -1740,13 +1675,13 @@ public virtual AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockSe if (signalCleared) { ResetActions(true); - NextStopDistanceM = 5000f; // clear to 5000m, will be updated if required + NextStopDistanceM = 5000f; // Clear to 5000m, will be updated if required StartMoving(AI_START_MOVEMENT.SIGNAL_RESTRICTED); } } else if (nextAspect >= MstsSignalAspect.APPROACH_1) { - // check if any other signals within clearing distance + // Check if any other signals within clearing distance bool signalCleared = true; bool withinDistance = true; @@ -1755,15 +1690,15 @@ public virtual AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockSe ObjectItemInfo nextObject = SignalObjectItems[iitem]; if (nextObject.ObjectType == ObjectItemInfo.ObjectItemType.Signal) { - if (nextObject.ObjectDetails != NextSignalObject[0]) // not signal we are waiting for + if (nextObject.ObjectDetails != NextSignalObject[0]) // Not signal we are waiting for { if (nextObject.distance_to_train > 2.0 * clearingDistanceM) { - withinDistance = false; // signal is far enough ahead + withinDistance = false; // Signal is far enough ahead } else if (nextObject.signal_state == MstsSignalAspect.STOP) { - signalCleared = false; // signal is not clear + signalCleared = false; // Signal is not clear NextSignalObject[0].ForcePropagation = true; } } @@ -1773,26 +1708,27 @@ public virtual AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockSe if (signalCleared) { ResetActions(true); - NextStopDistanceM = 5000f; // clear to 5000m, will be updated if required + NextStopDistanceM = 5000f; // Clear to 5000m, will be updated if required StartMoving(AI_START_MOVEMENT.SIGNAL_CLEARED); } } else if (nextAspect == MstsSignalAspect.STOP) { - // if stop but train is well away from signal allow to close; also if at end of path. - if (DistanceToSignal.HasValue && DistanceToSignal.Value > 5 * signalApproachDistanceM || + // If stop but train is well away from signal allow to close; also if at end of path. + if ((DistanceToSignal.HasValue && DistanceToSignal.Value > 5 * signalApproachDistanceM) || (TCRoute.TCRouteSubpaths[TCRoute.activeSubpath].Count - 1 == PresentPosition[0].RouteListIndex)) { MovementState = AI_MOVEMENT_STATE.ACCELERATING; StartMoving(AI_START_MOVEMENT.PATH_ACTION); } else tryBraking = false; - // else if (IsActualPlayerTrain && NextSignalObject[0].hasPermission == SignalObject.Permission.Granted) - // { - // MovementState = AI_MOVEMENT_STATE.ACCELERATING; - // StartMoving(AI_START_MOVEMENT.PATH_ACTION); - // } + // TODO: Can we remove this? + // else if (IsActualPlayerTrain && NextSignalObject[0].hasPermission == SignalObject.Permission.Granted) + // { + // MovementState = AI_MOVEMENT_STATE.ACCELERATING; + // StartMoving(AI_START_MOVEMENT.PATH_ACTION); + // } } else if (nextActionInfo != null && @@ -1800,8 +1736,8 @@ public virtual AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockSe { if (StationStops[0].SubrouteIndex == TCRoute.activeSubpath && ValidRoute[0].GetRouteIndex(StationStops[0].TCSectionIndex, PresentPosition[0].RouteListIndex) <= PresentPosition[0].RouteListIndex) - // assume to be in station { + // Assume to be in station MovementState = AI_MOVEMENT_STATE.STATION_STOP; if (CheckTrain) @@ -1812,8 +1748,8 @@ public virtual AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockSe } } else - // approaching next station { + // Approaching next station MovementState = AI_MOVEMENT_STATE.BRAKING; if (CheckTrain) @@ -1838,7 +1774,7 @@ public virtual AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockSe } else { - // distanceToReversalPoint) { MovementState = AI_MOVEMENT_STATE.BRAKING; - //>CSComment: better be sure the train will stop in front of signal + //>CSComment: Better be sure the train will stop in front of signal CreateTrainAction(0.0f, 0.0f, distanceSignaltoTrain, SignalObjectItems[0], AIActionItem.AI_ACTION_TYPE.SIGNAL_ASPECT_STOP); Alpha10 = PreUpdate ? 2 : 10; AITrainThrottlePercent = 25; @@ -1875,7 +1811,7 @@ public virtual AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockSe } } } - float distanceToNextSignal = DistanceToSignal.HasValue ? DistanceToSignal.Value : 0.1f; + float distanceToNextSignal = DistanceToSignal ?? 0.1f; if (AuxActionnextActionInfo != null && MovementState == AI_MOVEMENT_STATE.STOPPED && tryBraking && distanceToNextSignal > clearingDistanceM && EndAuthorityType[0] != END_AUTHORITY.RESERVED_SWITCH && DistanceToEndNodeAuthorityM[0] <= 2.0f * junctionOverlapM) // && ControlMode == TRAIN_CONTROL.AUTO_NODE) { @@ -1889,7 +1825,6 @@ public virtual AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockSe /// Train is on turntable /// Dummy method for child instancing /// - public virtual void UpdateTurntableState(float elapsedTimeSeconds, int presentTime) { } @@ -1897,7 +1832,6 @@ public virtual void UpdateTurntableState(float elapsedTimeSeconds, int presentTi /// /// Train is at station /// - public virtual void UpdateStationState(float elapsedClockSeconds, int presentTime) { StationStop thisStation = StationStops[0]; @@ -1907,8 +1841,7 @@ public virtual void UpdateStationState(float elapsedClockSeconds, int presentTim int sixteenHundredHours = 16 * 3600; int actualdepart = thisStation.ActualDepart; - // no arrival / departure time set : update times - + // No arrival / departure time set: update times if (thisStation.ActualStopType == StationStop.STOPTYPE.STATION_STOP) { AtStation = true; @@ -1948,7 +1881,6 @@ public virtual void UpdateStationState(float elapsedClockSeconds, int presentTim arrTimeCT.ToString("HH:mm:ss") + " ; dep. at " + depTimeCT.ToString("HH:mm:ss") + "\n"); } - } else { @@ -1962,12 +1894,12 @@ public virtual void UpdateStationState(float elapsedClockSeconds, int presentTim { if (thisStation.PlatformItem.PlatformSide[0]) { - //open left doors + // Open left doors SetDoors(frontIsFront ? DoorSide.Right : DoorSide.Left, true); } if (thisStation.PlatformItem.PlatformSide[1]) { - //open right doors + // Open right doors SetDoors(frontIsFront ? DoorSide.Left : DoorSide.Right, true); } } @@ -1979,32 +1911,31 @@ public virtual void UpdateStationState(float elapsedClockSeconds, int presentTim { if (thisStation.PlatformItem.PlatformSide[0]) { - //open left doors + // Open left doors SetDoors(frontIsFront ? DoorSide.Right : DoorSide.Left, false); } if (thisStation.PlatformItem.PlatformSide[1]) { - //open right doors + // Open right doors SetDoors(frontIsFront ? DoorSide.Left : DoorSide.Right, false); } } } } } - } - // not yet time to depart - check if signal can be released + // Not yet time to depart - check if signal can be released int correctedTime = presentTime; - if (actualdepart > sixteenHundredHours && presentTime < eightHundredHours) // should have departed before midnight + if (actualdepart > sixteenHundredHours && presentTime < eightHundredHours) // Should have departed before midnight { correctedTime = presentTime + (24 * 3600); } - if (actualdepart < eightHundredHours && presentTime > sixteenHundredHours) // to depart after midnight + if (actualdepart < eightHundredHours && presentTime > sixteenHundredHours) // To depart after midnight { - correctedTime = presentTime - 24 * 3600; + correctedTime = presentTime - (24 * 3600); } #if WITH_PATH_DEBUG @@ -2050,23 +1981,23 @@ public virtual void UpdateStationState(float elapsedClockSeconds, int presentTim if (nextSignal.enabledTrain != null && nextSignal.enabledTrain.Train == this) { - nextSignal.requestClearSignal(ValidRoute[0], routedForward, 0, false, null);// for AI always use direction 0 + nextSignal.requestClearSignal(ValidRoute[0], routedForward, 0, false, null); // For AI always use direction 0 } + thisStation.HoldSignal = false; } return; } - // depart - + // Depart thisStation.Passed = true; Delay = TimeSpan.FromSeconds((presentTime - thisStation.DepartTime) % (24 * 3600)); PreviousStop = thisStation.CreateCopy(); if (thisStation.ActualStopType == StationStop.STOPTYPE.STATION_STOP && MaxVelocityA > 0 && ServiceDefinition != null && ServiceDefinition.ServiceList.Count > 0 && this != Simulator.Trains[0]) - // Recalculate TrainMaxSpeedMpS and AllowedMaxSpeedMpS { + // Recalculate TrainMaxSpeedMpS and AllowedMaxSpeedMpS var actualServiceItemIdx = ServiceDefinition.ServiceList.FindIndex(si => si.PlatformStartID == thisStation.PlatformReference); if (actualServiceItemIdx >= 0 && ServiceDefinition.ServiceList.Count >= actualServiceItemIdx + 2) { @@ -2085,46 +2016,44 @@ public virtual void UpdateStationState(float elapsedClockSeconds, int presentTim } } - // first, check state of signal - + // First, check state of signal if (thisStation.ExitSignal >= 0 && (thisStation.HoldSignal || signalRef.SignalObjects[thisStation.ExitSignal].holdState == HoldState.StationStop)) { if (HoldingSignals.Contains(thisStation.ExitSignal)) HoldingSignals.Remove(thisStation.ExitSignal); var nextSignal = signalRef.SignalObjects[thisStation.ExitSignal]; - // only request signal if in signal mode (train may be in node control) + // Only request signal if in signal mode (train may be in node control) if (ControlMode == TRAIN_CONTROL.AUTO_SIGNAL) { - nextSignal.requestClearSignal(ValidRoute[0], routedForward, 0, false, null); // for AI always use direction 0 + nextSignal.requestClearSignal(ValidRoute[0], routedForward, 0, false, null); // For AI always use direction 0 } } - // check if station is end of path - + // Check if station is end of path bool[] endOfPath = ProcessEndOfPath(presentTime, false); if (endOfPath[0]) { - removeStation = false; // do not remove station from list - is done by path processing + removeStation = false; // Do not remove station from list - is done by path processing } - // check if station has exit signal and this signal is at danger + // Check if station has exit signal and this signal is at danger else if (thisStation.ExitSignal >= 0 && NextSignalObject[0] != null && NextSignalObject[0].thisRef == thisStation.ExitSignal) { MstsSignalAspect nextAspect = GetNextSignalAspect(0); - if (nextAspect == MstsSignalAspect.STOP && !NextSignalObject[0].HasLockForTrain(Number, TCRoute.activeSubpath) && + if (nextAspect == MstsSignalAspect.STOP && !NextSignalObject[0].HasLockForTrain(Number, TCRoute.activeSubpath) && !(TCRoute.TCRouteSubpaths[TCRoute.activeSubpath].Count - 1 == PresentPosition[0].RouteListIndex && - TCRoute.TCRouteSubpaths.Count -1 == TCRoute.activeSubpath)) + TCRoute.TCRouteSubpaths.Count - 1 == TCRoute.activeSubpath)) { - return; // do not depart if exit signal at danger + return; // Do not depart if exit signal at danger } } - // change state if train still exists + // Change state if train still exists if (endOfPath[1]) { if (MovementState == AI_MOVEMENT_STATE.STATION_STOP) { - // if state is still station_stop and ready to depart - change to stop to check action + // If state is still station_stop and ready to depart - change to stop to check action MovementState = AI_MOVEMENT_STATE.STOPPED_EXISTING; if (TrainType != TRAINTYPE.AI_PLAYERHOSTING) AtStation = false; } @@ -2203,29 +2132,27 @@ public virtual void UpdateStationState(float elapsedClockSeconds, int presentTim /// /// Train is braking /// - public virtual void UpdateBrakingState(float elapsedClockSeconds, int presentTime) { - // check if action still required - + // Check if action still required bool clearAction = false; float distanceToGoM = activityClearingDistanceM; - if (nextActionInfo != null && nextActionInfo.RequiredSpeedMpS == 99999f) // RequiredSpeed doesn't matter + if (nextActionInfo != null && nextActionInfo.RequiredSpeedMpS == 99999f) // RequiredSpeed doesn't matter { return; } - if (nextActionInfo == null) // action has been reset - keep status quo + if (nextActionInfo == null) // Action has been reset - keep status quo { - if (ControlMode == TRAIN_CONTROL.AUTO_NODE) // node control : use control distance + if (ControlMode == TRAIN_CONTROL.AUTO_NODE) // Node control: use control distance { distanceToGoM = DistanceToEndNodeAuthorityM[0]; if (EndAuthorityType[0] == END_AUTHORITY.RESERVED_SWITCH) { - distanceToGoM = DistanceToEndNodeAuthorityM[0] - 2.0f * junctionOverlapM; + distanceToGoM = DistanceToEndNodeAuthorityM[0] - (2.0f * junctionOverlapM); } else if (EndAuthorityType[0] == END_AUTHORITY.END_OF_PATH) { @@ -2256,7 +2183,7 @@ public virtual void UpdateBrakingState(float elapsedClockSeconds, int presentTim return; } } - else // action cleared - set running or stopped + else // Action cleared - set running or stopped { if (SpeedMpS > 0) { @@ -2281,8 +2208,7 @@ public virtual void UpdateBrakingState(float elapsedClockSeconds, int presentTim } - // check if speedlimit on signal is cleared - + // Check if speed limit on signal is cleared else if (nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.SPEED_SIGNAL) { if (nextActionInfo.ActiveItem.actual_speed >= AllowedMaxSpeedMpS) @@ -2337,8 +2263,7 @@ public virtual void UpdateBrakingState(float elapsedClockSeconds, int presentTim } } - // check if STOP signal cleared - + // Check if STOP signal cleared else if (nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.SIGNAL_ASPECT_STOP) { var nextSignal = nextActionInfo.ActiveItem.ObjectDetails; @@ -2393,13 +2318,12 @@ public virtual void UpdateBrakingState(float elapsedClockSeconds, int presentTim } } - // check if RESTRICTED signal cleared - + // Check if RESTRICTED signal cleared else if (nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.SIGNAL_ASPECT_RESTRICTED) { if ((nextActionInfo.ActiveItem.signal_state >= MstsSignalAspect.APPROACH_1) || ((nextActionInfo.ActivateDistanceM - PresentPosition[0].DistanceTravelledM) < signalApproachDistanceM) || - (nextActionInfo.ActiveItem.ObjectDetails.this_sig_noSpeedReduction(SignalFunction.NORMAL))) + nextActionInfo.ActiveItem.ObjectDetails.this_sig_noSpeedReduction(SignalFunction.NORMAL)) { clearAction = true; #if DEBUG_REPORTS @@ -2422,8 +2346,7 @@ public virtual void UpdateBrakingState(float elapsedClockSeconds, int presentTim } } - // check if END_AUTHORITY extended - + // Check if END_AUTHORITY extended else if (nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.END_OF_AUTHORITY) { nextActionInfo.ActivateDistanceM = DistanceToEndNodeAuthorityM[0] + DistanceTravelledM; @@ -2490,23 +2413,21 @@ public virtual void UpdateBrakingState(float elapsedClockSeconds, int presentTim } } - // action cleared - reset processed info for object items to determine next action - // clear list of pending action to create new list - + // Action cleared - reset processed info for object items to determine next action + // Clear list of pending action to create new list if (clearAction) { ResetActions(true); MovementState = AI_MOVEMENT_STATE.RUNNING; Alpha10 = PreUpdate ? 2 : 10; - if (SpeedMpS < AllowedMaxSpeedMpS - 3.0f * hysterisMpS) + if (SpeedMpS < AllowedMaxSpeedMpS - (3.0f * hysterisMpS)) { AdjustControlsBrakeOff(); } return; } - // check ideal speed - + // Calculate ideal speed float requiredSpeedMpS = 0; float creepDistanceM = 3.0f * signalApproachDistanceM; @@ -2519,7 +2440,7 @@ public virtual void UpdateBrakingState(float elapsedClockSeconds, int presentTim { if (Cars != null && Cars.Count < 10) { - distanceToGoM = nextActionInfo.ActiveItem.distance_to_train - signalApproachDistanceM / 4; + distanceToGoM = nextActionInfo.ActiveItem.distance_to_train - (signalApproachDistanceM / 4); if (PreUpdate) distanceToGoM -= signalApproachDistanceM * 0.25f; // Be more conservative if braking downhill /* else if (FirstCar != null) @@ -2530,11 +2451,10 @@ public virtual void UpdateBrakingState(float elapsedClockSeconds, int presentTim }*/ } else distanceToGoM = nextActionInfo.ActiveItem.distance_to_train - signalApproachDistanceM; - // distanceToGoM = nextActionInfo.ActiveItem.distance_to_train - signalApproachDistanceM; + // distanceToGoM = nextActionInfo.ActiveItem.distance_to_train - signalApproachDistanceM; } - // check if stopped at station - + // Check if stopped at station if (nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.STATION_STOP) { NextStopDistanceM = distanceToGoM; @@ -2543,8 +2463,7 @@ public virtual void UpdateBrakingState(float elapsedClockSeconds, int presentTim AdjustControlsBrakeMore(MaxDecelMpSS, elapsedClockSeconds, 100); AITrainThrottlePercent = 0; - // train is stopped - set departure time - + // Train is stopped - set departure time if (Math.Abs(SpeedMpS) <= Simulator.MaxStoppedMpS) { MovementState = AI_MOVEMENT_STATE.STATION_STOP; @@ -2576,14 +2495,14 @@ public virtual void UpdateBrakingState(float elapsedClockSeconds, int presentTim { thisStation.ActualArrival = presentTime; - // delta time set if (thisStation.DepartTime < 0) { - thisStation.ActualDepart = presentTime - thisStation.DepartTime; // depart time is negative!! + // Delta time set + thisStation.ActualDepart = presentTime - thisStation.DepartTime; // Depart time is negative! } - // actual time set else { + // Actual time set thisStation.ActualDepart = thisStation.DepartTime; } @@ -2614,8 +2533,8 @@ public virtual void UpdateBrakingState(float elapsedClockSeconds, int presentTim NextStopDistanceM = distanceToGoM; MovementState = nextActionInfo.ProcessAction(this, presentTime, elapsedClockSeconds, MovementState); } - // check speed reduction position reached + // Check speed reduction position reached else if (nextActionInfo.RequiredSpeedMpS > 0) { if (distanceToGoM <= 0.0f) @@ -2636,16 +2555,14 @@ public virtual void UpdateBrakingState(float elapsedClockSeconds, int presentTim } } - // check if approaching reversal point - + // Check if approaching reversal point else if (nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.REVERSAL) { if (Math.Abs(SpeedMpS) < 0.03f && nextActionInfo.ActivateDistanceM - DistanceTravelledM < 10.0f) MovementState = AI_MOVEMENT_STATE.STOPPED; } - // check if stopped at signal - + // Check if stopped at signal else if (nextActionInfo.RequiredSpeedMpS == 0) { NextStopDistanceM = distanceToGoM; @@ -2669,7 +2586,7 @@ public virtual void UpdateBrakingState(float elapsedClockSeconds, int presentTim "Speed : " + FormatStrings.FormatSpeed(SpeedMpS, true) + "\n"); } - // if approaching signal and at approach distance and still moving, force stop + // If approaching signal and at approach distance and still moving, force stop if (distanceToGoM < 0 && SpeedMpS > 0 && nextActionInfo != null && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.SIGNAL_ASPECT_STOP) { @@ -2709,28 +2626,27 @@ public virtual void UpdateBrakingState(float elapsedClockSeconds, int presentTim if (nextActionInfo == null && requiredSpeedMpS == 0) creepDistanceM = clearingDistanceM; - // keep speed within required speed band - - // preset, also valid for reqSpeed > 0 + // Keep speed within required speed band + // Preset, also valid for reqSpeed > 0 float lowestSpeedMpS = requiredSpeedMpS; creepDistanceM = 0.5f * signalApproachDistanceM; if (requiredSpeedMpS == 0) { - // station stop : use 0.5 signalApproachDistanceM as final stop approach + // Station stop: use 0.5 signalApproachDistanceM as final stop approach if (nextActionInfo != null && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.STATION_STOP) { creepDistanceM = 0.0f; lowestSpeedMpS = creepSpeedMpS; } - // signal : use 3 * signalApproachDistanceM as final stop approach to avoid signal overshoot + // Signal: use 3 * signalApproachDistanceM as final stop approach to avoid signal overshoot if (nextActionInfo != null && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.SIGNAL_ASPECT_STOP) { creepDistanceM = 3.0f * signalApproachDistanceM; lowestSpeedMpS = distanceToGoM < creepDistanceM ? (0.5f * creepSpeedMpS) : creepSpeedMpS; } - // otherwise use clearingDistanceM as approach distance + // Otherwise use clearingDistanceM as approach distance else if (nextActionInfo == null && requiredSpeedMpS == 0) { creepDistanceM = clearingDistanceM; @@ -2761,18 +2677,18 @@ public virtual void UpdateBrakingState(float elapsedClockSeconds, int presentTim float maxPossSpeedMpS = lowestSpeedMpS; if (correctedDistanceToGoM > 0) { - maxPossSpeedMpS = (float)Math.Sqrt(0.22f * MaxDecelMpSS * 2.0f * correctedDistanceToGoM + (requiredSpeedMpS * requiredSpeedMpS)); + maxPossSpeedMpS = (float)Math.Sqrt((0.22f * MaxDecelMpSS * 2.0f * correctedDistanceToGoM) + (requiredSpeedMpS * requiredSpeedMpS)); maxPossSpeedMpS = Math.Max(lowestSpeedMpS, maxPossSpeedMpS); } - float idealSpeedMpS = requiredSpeedMpS == 0 ? Math.Min((AllowedMaxSpeedMpS - 2f * hysterisMpS), maxPossSpeedMpS) : Math.Min(AllowedMaxSpeedMpS, maxPossSpeedMpS) - (2f * hysterisMpS); + float idealSpeedMpS = requiredSpeedMpS == 0 ? Math.Min(AllowedMaxSpeedMpS - (2f * hysterisMpS), maxPossSpeedMpS) : Math.Min(AllowedMaxSpeedMpS, maxPossSpeedMpS) - (2f * hysterisMpS); float idealLowBandMpS = Math.Max(0.25f * lowestSpeedMpS, idealSpeedMpS - (3f * hysterisMpS)); float ideal3LowBandMpS = Math.Max(0.5f * lowestSpeedMpS, idealSpeedMpS - (9f * hysterisMpS)); float idealHighBandMpS = Math.Min(AllowedMaxSpeedMpS, Math.Max(lowestSpeedMpS, idealSpeedMpS) + hysterisMpS); float ideal3HighBandMpS = Math.Min(AllowedMaxSpeedMpS, Math.Max(lowestSpeedMpS, idealSpeedMpS) + (2f * hysterisMpS)); float deltaSpeedMpS = SpeedMpS - requiredSpeedMpS; - float idealDecelMpSS = Math.Max((0.5f * MaxDecelMpSS), (deltaSpeedMpS * deltaSpeedMpS / (2.0f * distanceToGoM))); + float idealDecelMpSS = Math.Max(0.5f * MaxDecelMpSS, deltaSpeedMpS * deltaSpeedMpS / (2.0f * distanceToGoM)); float lastDecelMpSS = elapsedClockSeconds > 0 ? ((SpeedMpS - LastSpeedMpS) / elapsedClockSeconds) : idealDecelMpSS; @@ -2818,8 +2734,7 @@ public virtual void UpdateBrakingState(float elapsedClockSeconds, int presentTim " A&B(S): " + AITrainThrottlePercent.ToString() + " - " + AITrainBrakePercent.ToString() + "\n"); } - // keep speed withing band - + // Keep speed within band if (SpeedMpS > AllowedMaxSpeedMpS) { if (AITrainThrottlePercent > 0) @@ -2831,7 +2746,7 @@ public virtual void UpdateBrakingState(float elapsedClockSeconds, int presentTim AdjustControlsBrakeMore(MaxDecelMpSS, elapsedClockSeconds, 20); } - // clamp speed if still too high + // Clamp speed if still too high if (SpeedMpS > AllowedMaxSpeedMpS) { AdjustControlsFixedSpeed(AllowedMaxSpeedMpS); @@ -2856,7 +2771,7 @@ public virtual void UpdateBrakingState(float elapsedClockSeconds, int presentTim AdjustControlsBrakeMore(2.0f * MaxDecelMpSS, elapsedClockSeconds, 10); Alpha10 = PreUpdate ? 1 : 5; } - // if at full brake always perform application as it forces braking in case of brake failure (eg due to wheelslip) + // If at full brake always perform application as it forces braking in case of brake failure (eg. due to wheelslip) else if (AITrainBrakePercent == 100) { AdjustControlsBrakeMore(2.0f * MaxDecelMpSS, elapsedClockSeconds, 50); @@ -2985,13 +2900,13 @@ public virtual void UpdateBrakingState(float elapsedClockSeconds, int presentTim AdjustControlsAccelMore(0.25f * MaxAccelMpSS, elapsedClockSeconds, 10); } - // in preupdate : avoid problems with overshoot due to low update rate - // check if at present speed train would pass beyond end of authority + // In preupdate: avoid problems with overshoot due to low update rate + // Check if at present speed train would pass beyond end of authority if (PreUpdate) { if (requiredSpeedMpS == 0 && (elapsedClockSeconds * SpeedMpS) > distanceToGoM && SpeedMpS > creepSpeedMpS) { - SpeedMpS = (0.5f * SpeedMpS); + SpeedMpS = 0.5f * SpeedMpS; } } @@ -3006,11 +2921,9 @@ public virtual void UpdateBrakingState(float elapsedClockSeconds, int presentTim /// /// Train is accelerating /// - public virtual void UpdateAccelState(float elapsedClockSeconds) { - - // check speed + // Check speed if (((SpeedMpS - LastSpeedMpS) / elapsedClockSeconds) < 0.5f * MaxAccelMpSS) { int stepSize = (!PreUpdate) ? 10 : 40; @@ -3018,7 +2931,7 @@ public virtual void UpdateAccelState(float elapsedClockSeconds) AdjustControlsAccelMore(Efficiency * corrFactor * MaxAccelMpSS, elapsedClockSeconds, stepSize); } - if (SpeedMpS > (AllowedMaxSpeedMpS - ((9.0f - 6.0f * Efficiency) * hysterisMpS))) + if (SpeedMpS > (AllowedMaxSpeedMpS - ((9.0f - (6.0f * Efficiency)) * hysterisMpS))) { AdjustControlsAccelLess(0.0f, elapsedClockSeconds, (int)(AITrainThrottlePercent * 0.5f)); MovementState = AI_MOVEMENT_STATE.RUNNING; @@ -3030,20 +2943,19 @@ public virtual void UpdateAccelState(float elapsedClockSeconds) /// /// Train is following /// - public virtual void UpdateFollowingState(float elapsedClockSeconds, int presentTime) { if (nextActionInfo != null && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.TRAIN_AHEAD && nextActionInfo.ActivateDistanceM - PresentPosition[0].DistanceTravelledM < -5) - if (CheckTrain) - { - File.AppendAllText(@"C:\temp\checktrain.txt", - "Update Train Ahead - now at : " + - PresentPosition[0].TCSectionIndex.ToString() + " " + - PresentPosition[0].TCOffset.ToString() + - " ; speed : " + FormatStrings.FormatSpeed(SpeedMpS, true) + "\n"); - } + if (CheckTrain) + { + File.AppendAllText(@"C:\temp\checktrain.txt", + "Update Train Ahead - now at : " + + PresentPosition[0].TCSectionIndex.ToString() + " " + + PresentPosition[0].TCOffset.ToString() + + " ; speed : " + FormatStrings.FormatSpeed(SpeedMpS, true) + "\n"); + } - if (ControlMode != TRAIN_CONTROL.AUTO_NODE || EndAuthorityType[0] != END_AUTHORITY.TRAIN_AHEAD) // train is gone + if (ControlMode != TRAIN_CONTROL.AUTO_NODE || EndAuthorityType[0] != END_AUTHORITY.TRAIN_AHEAD) // Train is gone { if (CheckTrain) { @@ -3054,10 +2966,10 @@ public virtual void UpdateFollowingState(float elapsedClockSeconds, int presentT } else { - // check if train is in sections ahead + // Check if train is in sections ahead Dictionary trainInfo = null; - // find other train + // Find other train int sectionIndex = ValidRoute[0][PresentPosition[0].RouteListIndex].TCSectionIndex; int startIndex = PresentPosition[0].RouteListIndex; int endSectionIndex = LastReservedSection[0]; @@ -3073,7 +2985,7 @@ public virtual void UpdateFollowingState(float elapsedClockSeconds, int presentT } else { - // ensure train in section is aware of this train in same section if this is required + // Ensure train in section is aware of this train in same section if this is required UpdateTrainOnEnteringSection(thisSection, trainInfo); } @@ -3083,14 +2995,14 @@ public virtual void UpdateFollowingState(float elapsedClockSeconds, int presentT "Train count in section " + sectionIndex.ToString() + " = " + trainInfo.Count.ToString() + "\n"); } - // train not in this section, try reserved sections ahead + // Train not in this section, try reserved sections ahead for (int iIndex = startIndex + 1; iIndex <= endIndex && trainInfo.Count <= 0; iIndex++) { TrackCircuitSection nextSection = signalRef.TrackCircuitList[ValidRoute[0][iIndex].TCSectionIndex]; trainInfo = nextSection.TestTrainAhead(this, 0, ValidRoute[0][iIndex].Direction); } - // if train not ahead, try first section beyond last reserved + // If train not ahead, try first section beyond last reserved if (trainInfo.Count <= 0 && endIndex < ValidRoute[0].Count - 1) { TrackCircuitSection nextSection = signalRef.TrackCircuitList[ValidRoute[0][endIndex + 1].TCSectionIndex]; @@ -3101,10 +3013,10 @@ public virtual void UpdateFollowingState(float elapsedClockSeconds, int presentT } } - // train is found - if (trainInfo.Count > 0) // found train + // Train is found + if (trainInfo.Count > 0) { - foreach (KeyValuePair trainAhead in trainInfo) // always just one + foreach (KeyValuePair trainAhead in trainInfo) // Always just one { Train OtherTrain = trainAhead.Key; @@ -3121,8 +3033,7 @@ public virtual void UpdateFollowingState(float elapsedClockSeconds, int presentT "DistAhd: " + DistanceToEndNodeAuthorityM[0].ToString() + "\n"); } - // update action info with new position - + // Update action info with new position float keepDistanceTrainM = 0f; bool attachToTrain = AttachTo == OtherTrain.Number; @@ -3132,11 +3043,11 @@ public virtual void UpdateFollowingState(float elapsedClockSeconds, int presentT { var rearOrFront = ValidRoute[0][ValidRoute[0].Count - 1].Direction == 1 ? 0 : 1; - if (OtherTrain.TrainType == TRAINTYPE.STATIC || (OtherTrain.PresentPosition[0].TCSectionIndex == + if (OtherTrain.TrainType == TRAINTYPE.STATIC || ((OtherTrain.PresentPosition[0].TCSectionIndex == TCRoute.TCRouteSubpaths[TCRoute.activeSubpath][TCRoute.TCRouteSubpaths[TCRoute.activeSubpath].Count - 1].TCSectionIndex || OtherTrain.PresentPosition[1].TCSectionIndex == - TCRoute.TCRouteSubpaths[TCRoute.activeSubpath][TCRoute.TCRouteSubpaths[TCRoute.activeSubpath].Count - 1].TCSectionIndex) && - (TCRoute.ReversalInfo[TCRoute.activeSubpath].Valid || TCRoute.activeSubpath == TCRoute.TCRouteSubpaths.Count - 1) + TCRoute.TCRouteSubpaths[TCRoute.activeSubpath][TCRoute.TCRouteSubpaths[TCRoute.activeSubpath].Count - 1].TCSectionIndex) && + (TCRoute.ReversalInfo[TCRoute.activeSubpath].Valid || TCRoute.activeSubpath == TCRoute.TCRouteSubpaths.Count - 1)) || UncondAttach) { attachToTrain = true; @@ -3160,35 +3071,30 @@ public virtual void UpdateFollowingState(float elapsedClockSeconds, int presentT else if (nextActionInfo != null) { float deltaDistance = nextActionInfo.ActivateDistanceM - DistanceTravelledM; - if (nextActionInfo.RequiredSpeedMpS > 0.0f) - { - NextStopDistanceM = distanceToTrain - keepDistanceTrainM; - } - else - { - NextStopDistanceM = Math.Min(deltaDistance, (distanceToTrain - keepDistanceTrainM)); - } + NextStopDistanceM = nextActionInfo.RequiredSpeedMpS > 0.0f + ? distanceToTrain - keepDistanceTrainM + : Math.Min(deltaDistance, distanceToTrain - keepDistanceTrainM); - if (deltaDistance < distanceToTrain) // perform to normal braking to handle action + if (deltaDistance < distanceToTrain) // Perform to normal braking to handle action { - MovementState = AI_MOVEMENT_STATE.BRAKING; // not following the train + MovementState = AI_MOVEMENT_STATE.BRAKING; // Not following the train UpdateBrakingState(elapsedClockSeconds, presentTime); return; } } - // check distance and speed + // Check distance and speed if (Math.Abs(OtherTrain.SpeedMpS) < 0.025f) { float brakingDistance = SpeedMpS * SpeedMpS * 0.5f * (0.5f * MaxDecelMpSS); float reqspeed = (float)Math.Sqrt(distanceToTrain * MaxDecelMpSS); - float maxspeed = Math.Max(reqspeed / 2, creepSpeedMpS); // allow continue at creepspeed + float maxspeed = Math.Max(reqspeed / 2, creepSpeedMpS); // Allow continue at creepspeed if (distanceToTrain < keepDistanceStatTrainM_P - 2.0f && attachToTrain) maxspeed = Math.Min(maxspeed, couplingSpeedMpS); - maxspeed = Math.Min(maxspeed, AllowedMaxSpeedMpS); // but never beyond valid speed limit + maxspeed = Math.Min(maxspeed, AllowedMaxSpeedMpS); // But never beyond valid speed limit - // set brake or acceleration as required + // Set brake or acceleration as required if (SpeedMpS > maxspeed) { @@ -3230,7 +3136,7 @@ public virtual void UpdateFollowingState(float elapsedClockSeconds, int presentT else attachToTrain = false; } - // if (distanceToTrain < keepDistanceStatTrainM_P - 4.0f || (distanceToTrain - brakingDistance) <= keepDistanceTrainM) // Other possibility + // if (distanceToTrain < keepDistanceStatTrainM_P - 4.0f || (distanceToTrain - brakingDistance) <= keepDistanceTrainM) // Other possibility if ((distanceToTrain - brakingDistance) <= keepDistanceTrainM) { float reqMinSpeedMpS = attachToTrain ? couplingSpeedMpS : 0; @@ -3248,14 +3154,14 @@ public virtual void UpdateFollowingState(float elapsedClockSeconds, int presentT { AdjustControlsBrakeMore(MaxDecelMpSS, elapsedClockSeconds, 50); - // if too close, force stop or slow down if coupling + // If too close, force stop or slow down if coupling if (distanceToTrain < 0.25 * keepDistanceTrainM) { foreach (TrainCar car in Cars) { - //TODO: next code line has been modified to flip trainset physics in order to get viewing direction coincident with loco direction when using rear cab. + // TODO: next code line has been modified to flip trainset physics in order to get viewing direction coincident with loco direction when using rear cab. // To achieve the same result with other means, without flipping trainset physics, the line should be changed as follows: - // car.SpeedMpS = car.Flipped ? -reqMinSpeedMpS : reqMinSpeedMpS; + // car.SpeedMpS = car.Flipped ? -reqMinSpeedMpS : reqMinSpeedMpS; car.SpeedMpS = car.Flipped ^ (car.IsDriveable && car.Train.IsActualPlayerTrain && ((MSTSLocomotive)car).UsingRearCab) ? -reqMinSpeedMpS : reqMinSpeedMpS; } SpeedMpS = reqMinSpeedMpS; @@ -3285,11 +3191,11 @@ public virtual void UpdateFollowingState(float elapsedClockSeconds, int presentT if (OtherTrain.TrainType == TRAINTYPE.AI || OtherTrain.TrainType == TRAINTYPE.AI_PLAYERHOSTING) { AITrain OtherAITrain = OtherTrain as AITrain; - otherTrainInStation = (OtherAITrain.MovementState == AI_MOVEMENT_STATE.STATION_STOP); + otherTrainInStation = OtherAITrain.MovementState == AI_MOVEMENT_STATE.STATION_STOP; } - bool thisTrainInStation = (nextActionInfo != null && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.STATION_STOP); - if (thisTrainInStation) thisTrainInStation = (StationStops[0].SubrouteIndex == TCRoute.activeSubpath); + bool thisTrainInStation = nextActionInfo != null && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.STATION_STOP; + if (thisTrainInStation) thisTrainInStation = StationStops[0].SubrouteIndex == TCRoute.activeSubpath; if (thisTrainInStation) { var thisStation = StationStops[0]; @@ -3327,20 +3233,19 @@ public virtual void UpdateFollowingState(float elapsedClockSeconds, int presentT { thisStation.ActualArrival = presentTime; - // delta time set + // Delta time set if (thisStation.DepartTime < 0) { - thisStation.ActualDepart = presentTime - thisStation.DepartTime; // depart time is negative!! + thisStation.ActualDepart = presentTime - thisStation.DepartTime; // Depart time is negative } - // actual time set + // Actual time set else { thisStation.ActualDepart = thisStation.DepartTime; } - // if waited behind other train, move remaining track sections to next subroute if required - - // scan sections in backward order + // If waited behind other train, move remaining track sections to next subroute if required + // Scan sections in backward order TCSubpathRoute nextRoute = TCRoute.TCRouteSubpaths[TCRoute.activeSubpath + 1]; for (int iIndex = ValidRoute[0].Count - 1; iIndex > PresentPosition[0].RouteListIndex; iIndex--) @@ -3370,7 +3275,6 @@ public virtual void UpdateFollowingState(float elapsedClockSeconds, int presentT Number.ToString() + " arrives waiting point at " + arrTimeCT.ToString("HH:mm:ss") + "\n"); } - } } } @@ -3378,17 +3282,17 @@ public virtual void UpdateFollowingState(float elapsedClockSeconds, int presentT } else { - // check whether trains are running same direction or not + // Check whether trains are running same direction or not bool runningAgainst = false; if (PresentPosition[0].TCSectionIndex == OtherTrain.PresentPosition[0].TCSectionIndex && PresentPosition[0].TCDirection != OtherTrain.PresentPosition[0].TCDirection) runningAgainst = true; - if ((SpeedMpS > (OtherTrain.SpeedMpS + hysterisMpS) && !runningAgainst)|| + if ((SpeedMpS > (OtherTrain.SpeedMpS + hysterisMpS) && !runningAgainst) || SpeedMpS > (maxFollowSpeedMpS + hysterisMpS) || distanceToTrain < (keepDistanceTrainM - clearingDistanceM)) { AdjustControlsBrakeMore(0.5f * MaxAccelMpSS, elapsedClockSeconds, 10); } - else if ((SpeedMpS < (OtherTrain.SpeedMpS - hysterisMpS) && !runningAgainst) && + else if (SpeedMpS < (OtherTrain.SpeedMpS - hysterisMpS) && !runningAgainst && SpeedMpS < maxFollowSpeedMpS && distanceToTrain > (keepDistanceTrainM + clearingDistanceM)) { @@ -3398,7 +3302,7 @@ distanceToTrain > (keepDistanceTrainM + clearingDistanceM)) } } - // train not found - keep moving, state will change next update + // Train not found - keep moving, state will change next update else AttachTo = -1; } } @@ -3407,16 +3311,14 @@ distanceToTrain > (keepDistanceTrainM + clearingDistanceM)) /// /// Train is running at required speed /// - public virtual void UpdateRunningState(float elapsedClockSeconds) { float topBand = AllowedMaxSpeedMpS > creepSpeedMpS ? AllowedMaxSpeedMpS - ((1.5f - Efficiency) * hysterisMpS) : AllowedMaxSpeedMpS; - float highBand = AllowedMaxSpeedMpS > creepSpeedMpS ? Math.Max(0.5f, AllowedMaxSpeedMpS - ((3.0f - 2.0f * Efficiency) * hysterisMpS)) : AllowedMaxSpeedMpS; - float lowBand = AllowedMaxSpeedMpS > creepSpeedMpS ? Math.Max(0.4f, AllowedMaxSpeedMpS - ((9.0f - 3.0f * Efficiency) * hysterisMpS)) : AllowedMaxSpeedMpS; + float highBand = AllowedMaxSpeedMpS > creepSpeedMpS ? Math.Max(0.5f, AllowedMaxSpeedMpS - ((3.0f - (2.0f * Efficiency)) * hysterisMpS)) : AllowedMaxSpeedMpS; + float lowBand = AllowedMaxSpeedMpS > creepSpeedMpS ? Math.Max(0.4f, AllowedMaxSpeedMpS - ((9.0f - (3.0f * Efficiency)) * hysterisMpS)) : AllowedMaxSpeedMpS; int throttleTop = 90; - // check speed - + // Check speed if (SpeedMpS > AllowedMaxSpeedMpS) { if (AITrainThrottlePercent > 0) @@ -3540,11 +3442,9 @@ public virtual void UpdateRunningState(float elapsedClockSeconds) /// /// Start Moving /// - public virtual void StartMoving(AI_START_MOVEMENT reason) { - // reset brakes, set throttle - + // Reset brakes, set throttle if (reason == AI_START_MOVEMENT.FOLLOW_TRAIN) { MovementState = AI_MOVEMENT_STATE.FOLLOWING; @@ -3561,7 +3461,7 @@ public virtual void StartMoving(AI_START_MOVEMENT reason) MovementState = AI_MOVEMENT_STATE.STOPPED; AITrainThrottlePercent = 0; } - else if (nextActionInfo != null) // train has valid action, so start in BRAKE mode + else if (nextActionInfo != null) // Train has valid action, so start in BRAKE mode { MovementState = AI_MOVEMENT_STATE.BRAKING; Alpha10 = PreUpdate ? 2 : 10; @@ -3577,22 +3477,20 @@ public virtual void StartMoving(AI_START_MOVEMENT reason) } SetPercentsFromTrainToTrainset(); - } //================================================================================================// /// /// Set correct state for train allready in section when entering occupied section /// - public void UpdateTrainOnEnteringSection(TrackCircuitSection thisSection, Dictionary trainsInSection) { - foreach (KeyValuePair trainAhead in trainsInSection) // always just one + foreach (KeyValuePair trainAhead in trainsInSection) // Always just one { Train OtherTrain = trainAhead.Key; - if (OtherTrain.ControlMode == TRAIN_CONTROL.AUTO_SIGNAL) // train is still in signal mode, might need adjusting + if (OtherTrain.ControlMode == TRAIN_CONTROL.AUTO_SIGNAL) // Train is still in signal mode, might need adjusting { - // check directions of this and other train + // Check directions of this and other train int owndirection = -1; int otherdirection = -1; @@ -3600,7 +3498,7 @@ public void UpdateTrainOnEnteringSection(TrackCircuitSection thisSection, Dictio { TrainRouted trainToCheck = trainToCheckInfo.Key; - if (trainToCheck.Train.Number == Number) // this train + if (trainToCheck.Train.Number == Number) // This train { owndirection = trainToCheckInfo.Value; } @@ -3610,9 +3508,9 @@ public void UpdateTrainOnEnteringSection(TrackCircuitSection thisSection, Dictio } } - if (owndirection >= 0 && otherdirection >= 0) // both trains found + if (owndirection >= 0 && otherdirection >= 0) // Both trains found { - if (owndirection != otherdirection) // opposite directions - this train is now ahead of train in section + if (owndirection != otherdirection) // Opposite directions - this train is now ahead of train in section { OtherTrain.SwitchToNodeControl(thisSection.Index); } @@ -3625,7 +3523,6 @@ public void UpdateTrainOnEnteringSection(TrackCircuitSection thisSection, Dictio /// /// Train control routines /// - public void AdjustControlsBrakeMore(float reqDecelMpSS, float timeS, int stepSize) { if (AITrainThrottlePercent > 0) @@ -3641,19 +3538,18 @@ public void AdjustControlsBrakeMore(float reqDecelMpSS, float timeS, int stepSiz } else { - float ds = timeS * (reqDecelMpSS); - SpeedMpS = Math.Max(SpeedMpS - ds, 0); // avoid negative speeds + float ds = timeS * reqDecelMpSS; + SpeedMpS = Math.Max(SpeedMpS - ds, 0); // Avoid negative speeds foreach (TrainCar car in Cars) { - //TODO: next code line has been modified to flip trainset physics in order to get viewing direction coincident with loco direction when using rear cab. + // TODO: next code line has been modified to flip trainset physics in order to get viewing direction coincident with loco direction when using rear cab. // To achieve the same result with other means, without flipping trainset physics, the line should be changed as follows: - // car.SpeedMpS = car.Flipped ? -SpeedMpS : SpeedMpS; + // car.SpeedMpS = car.Flipped ? -SpeedMpS : SpeedMpS; car.SpeedMpS = car.Flipped ^ (car.IsDriveable && car.Train.IsActualPlayerTrain && ((MSTSLocomotive)car).UsingRearCab) ? -SpeedMpS : SpeedMpS; } } SetPercentsFromTrainToTrainset(); - } public void AdjustControlsBrakeLess(float reqDecelMpSS, float timeS, int stepSize) @@ -3671,13 +3567,13 @@ public void AdjustControlsBrakeLess(float reqDecelMpSS, float timeS, int stepSiz } else { - float ds = timeS * (reqDecelMpSS); - SpeedMpS = SpeedMpS + ds; // avoid negative speeds + float ds = timeS * reqDecelMpSS; + SpeedMpS += ds; // avoid negative speeds foreach (TrainCar car in Cars) { - //TODO: next code line has been modified to flip trainset physics in order to get viewing direction coincident with loco direction when using rear cab. + // TODO: next code line has been modified to flip trainset physics in order to get viewing direction coincident with loco direction when using rear cab. // To achieve the same result with other means, without flipping trainset physics, the line should be changed as follows: - // car.SpeedMpS = car.Flipped ? -SpeedMpS : SpeedMpS; + // car.SpeedMpS = car.Flipped ? -SpeedMpS : SpeedMpS; car.SpeedMpS = car.Flipped ^ (car.IsDriveable && car.Train.IsActualPlayerTrain && ((MSTSLocomotive)car).UsingRearCab) ? -SpeedMpS : SpeedMpS; } } @@ -3764,13 +3660,13 @@ public void AdjustControlsAccelMore(float reqAccelMpSS, float timeS, int stepSiz } else if (LastSpeedMpS == 0 || (((SpeedMpS - LastSpeedMpS) / timeS) < 0.5f * MaxAccelMpSS)) { - float ds = timeS * (reqAccelMpSS); + float ds = timeS * reqAccelMpSS; SpeedMpS = LastSpeedMpS + ds; foreach (TrainCar car in Cars) { - //TODO: next code line has been modified to flip trainset physics in order to get viewing direction coincident with loco direction when using rear cab. + // TODO: next code line has been modified to flip trainset physics in order to get viewing direction coincident with loco direction when using rear cab. // To achieve the same result with other means, without flipping trainset physics, the line should be changed as follows: - // car.SpeedMpS = car.Flipped ? -SpeedMpS : SpeedMpS; + // car.SpeedMpS = car.Flipped ? -SpeedMpS : SpeedMpS; car.SpeedMpS = car.Flipped ^ (car.IsDriveable && car.Train.IsActualPlayerTrain && ((MSTSLocomotive)car).UsingRearCab) ? -SpeedMpS : SpeedMpS; } @@ -3800,13 +3696,13 @@ public void AdjustControlsAccelLess(float reqAccelMpSS, float timeS, int stepSiz } else { - float ds = timeS * (reqAccelMpSS); - SpeedMpS = Math.Max(SpeedMpS - ds, 0); // avoid negative speeds + float ds = timeS * reqAccelMpSS; + SpeedMpS = Math.Max(SpeedMpS - ds, 0); // Avoid negative speeds foreach (TrainCar car in Cars) { - //TODO: next code line has been modified to flip trainset physics in order to get viewing direction coincident with loco direction when using rear cab. + // TODO: next code line has been modified to flip trainset physics in order to get viewing direction coincident with loco direction when using rear cab. // To achieve the same result with other means, without flipping trainset physics, the line should be changed as follows: - // car.SpeedMpS = car.Flipped ? -SpeedMpS : SpeedMpS; + // car.SpeedMpS = car.Flipped ? -SpeedMpS : SpeedMpS; car.SpeedMpS = car.Flipped ^ (car.IsDriveable && car.Train.IsActualPlayerTrain && ((MSTSLocomotive)car).UsingRearCab) ? -SpeedMpS : SpeedMpS; } } @@ -3817,9 +3713,9 @@ public void AdjustControlsFixedSpeed(float reqSpeedMpS) { foreach (TrainCar car in Cars) { - //TODO: next code line has been modified to flip trainset physics in order to get viewing direction coincident with loco direction when using rear cab. + // TODO: next code line has been modified to flip trainset physics in order to get viewing direction coincident with loco direction when using rear cab. // To achieve the same result with other means, without flipping trainset physics, the line should be changed as follows: - // car.SpeedMpS = car.Flipped ? -reqSpeedMpS : reqSpeedMpS; + // car.SpeedMpS = car.Flipped ? -reqSpeedMpS : reqSpeedMpS; car.SpeedMpS = car.Flipped ^ (car.IsDriveable && car.Train.IsActualPlayerTrain && ((MSTSLocomotive)car).UsingRearCab) ? -reqSpeedMpS : reqSpeedMpS; } } @@ -3858,33 +3754,31 @@ public void SetPercentsFromTrainToTrainset() /// Update AllowedMaxSpeedMps after station stop /// /// - public void RecalculateAllowedMaxSpeed() { var allowedMaxSpeedPathMpS = Math.Min(allowedAbsoluteMaxSpeedSignalMpS, allowedAbsoluteMaxSpeedLimitMpS); allowedMaxSpeedPathMpS = Math.Min(allowedMaxSpeedPathMpS, allowedAbsoluteMaxTempSpeedLimitMpS); AllowedMaxSpeedMpS = Math.Min(allowedMaxSpeedPathMpS, TrainMaxSpeedMpS); - allowedMaxSpeedSignalMpS = (Math.Min(allowedAbsoluteMaxSpeedSignalMpS, TrainMaxSpeedMpS)); - allowedMaxSpeedLimitMpS = (Math.Min(allowedAbsoluteMaxSpeedLimitMpS, TrainMaxSpeedMpS)); - allowedMaxTempSpeedLimitMpS = (Math.Min(allowedAbsoluteMaxTempSpeedLimitMpS, TrainMaxSpeedMpS)); + allowedMaxSpeedSignalMpS = Math.Min(allowedAbsoluteMaxSpeedSignalMpS, TrainMaxSpeedMpS); + allowedMaxSpeedLimitMpS = Math.Min(allowedAbsoluteMaxSpeedLimitMpS, TrainMaxSpeedMpS); + allowedMaxTempSpeedLimitMpS = Math.Min(allowedAbsoluteMaxTempSpeedLimitMpS, TrainMaxSpeedMpS); } //================================================================================================// /// /// Create waiting point list /// - public void BuildWaitingPointList(float clearingDistanceM) { bool insertSigDelegate = true; - // loop through all waiting points - back to front as the processing affects the actual routepaths + // Loop through all waiting points - back to front as the processing affects the actual routepaths List signalIndex = new List(); for (int iWait = 0; iWait <= TCRoute.WaitingPoints.Count - 1; iWait++) { int[] waitingPoint = TCRoute.WaitingPoints[iWait]; - //check if waiting point is in existing subpath + // Check if waiting point is in existing subpath if (waitingPoint[0] >= TCRoute.TCRouteSubpaths.Count) { Trace.TraceInformation("Waiting point for train " + Name + "(" + Number.ToString() + ") is not on route - point removed"); @@ -3895,7 +3789,7 @@ public void BuildWaitingPointList(float clearingDistanceM) int routeIndex = thisRoute.GetRouteIndex(waitingPoint[1], 0); int lastIndex = routeIndex; - // check if waiting point is in route - else give warning and skip + // Check if waiting point is in route - else give warning and skip if (routeIndex < 0) { Trace.TraceInformation("Waiting point for train " + Name + "(" + Number.ToString() + ") is not on route - point removed"); @@ -3914,18 +3808,16 @@ public void BuildWaitingPointList(float clearingDistanceM) { endSectionFound = true; if (routeIndex < thisRoute.Count - 1) - endSignalIndex = thisSection.EndSignals[direction].thisRef; + endSignalIndex = thisSection.EndSignals[direction].thisRef; } - // check if next section is junction - + // Check if next section is junction else if (nextSection == null || nextSection.CircuitType != TrackCircuitSection.TrackCircuitType.Normal) { endSectionFound = true; } - // try and find next section with signal; if junction is found, stop search - + // Try and find next section with signal; if junction is found, stop search int nextIndex = routeIndex + 1; while (nextIndex < thisRoute.Count - 1 && !endSectionFound) { @@ -3937,7 +3829,7 @@ public void BuildWaitingPointList(float clearingDistanceM) endSectionFound = true; lastIndex = nextIndex; if (lastIndex < thisRoute.Count - 1) - endSignalIndex = nextSection.EndSignals[direction].thisRef; + endSignalIndex = nextSection.EndSignals[direction].thisRef; } else if (nextSection.CircuitType != TrackCircuitSection.TrackCircuitType.Normal) { @@ -3960,13 +3852,13 @@ public void BuildWaitingPointList(float clearingDistanceM) } } - // insertSigDelegate = false; + // insertSigDelegate = false; for (int iWait = 0; iWait <= TCRoute.WaitingPoints.Count - 1; iWait++) { insertSigDelegate = true; int[] waitingPoint = TCRoute.WaitingPoints[iWait]; - //check if waiting point is in existing subpath + // Check if waiting point is in existing subpath if (waitingPoint[0] >= TCRoute.TCRouteSubpaths.Count) { Trace.TraceInformation("Waiting point for train " + Name + "(" + Number.ToString() + ") is not on route - point removed"); @@ -3996,8 +3888,7 @@ public void BuildWaitingPointList(float clearingDistanceM) } } - - // check if waiting point is in route - else give warning and skip + // Check if waiting point is in route - else give warning and skip if (routeIndex < 0) { Trace.TraceInformation("Waiting point for train " + Name + "(" + Number.ToString() + ") is not on route - point removed"); @@ -4059,7 +3950,7 @@ public void BuildWaitingPointList(float clearingDistanceM) { RandomizedWPDelay(ref randomizedDelay); } - action.SetDelay( (randomizedDelay >= 30000 && randomizedDelay < 40000)? randomizedDelay : 0); + action.SetDelay((randomizedDelay >= 30000 && randomizedDelay < 40000) ? randomizedDelay : 0); AuxActionsContain.Add(action); AIActSigDelegateRef delegateAction = new AIActSigDelegateRef(this, waitingPoint[5], 0f, waitingPoint[0], lastIndex, thisRoute[lastIndex].TCSectionIndex, direction, action); signalRef.SignalObjects[signalIndex[iWait]].LockForTrain(this.Number, waitingPoint[0]); @@ -4070,7 +3961,7 @@ public void BuildWaitingPointList(float clearingDistanceM) AuxActionsContain.Add(delegateAction); } - // insertSigDelegate = false; + // insertSigDelegate = false; } } @@ -4079,7 +3970,6 @@ public void BuildWaitingPointList(float clearingDistanceM) /// /// Initialize brakes for AI trains /// - public override void InitializeBrakes() { if (TrainType == TRAINTYPE.AI_PLAYERDRIVEN || TrainType == TRAINTYPE.PLAYER) @@ -4115,7 +4005,6 @@ public override void InitializeBrakes() /// [0] : true : end of route, false : not end of route /// [1] : true : train still exists, false : train is removed and no longer exists /// - public virtual bool[] ProcessEndOfPath(int presentTime, bool checkLoop = true) { bool[] returnValue = new bool[2] { false, true }; @@ -4126,7 +4015,7 @@ public virtual bool[] ProcessEndOfPath(int presentTime, bool checkLoop = true) returnValue[0] = true; if (TrainType != TRAINTYPE.AI_PLAYERHOSTING) Trace.TraceWarning("AI Train {0} service {1} off path and removed", Number, Name); ProcessEndOfPathReached(ref returnValue, presentTime); - return (returnValue); + return returnValue; } int directionNow = ValidRoute[0][PresentPosition[0].RouteListIndex].Direction; @@ -4136,10 +4025,10 @@ public virtual bool[] ProcessEndOfPath(int presentTime, bool checkLoop = true) bool[] nextPart = UpdateRouteActions(0, checkLoop); - if (!nextPart[0]) return (returnValue); // not at end and not to attach to anything + if (!nextPart[0]) return returnValue; // Not at end and not to attach to anything - returnValue[0] = true; // end of path reached - if (nextPart[1]) // next route available + returnValue[0] = true; // End of path reached + if (nextPart[1]) // Next route available { #if DEBUG_REPORTS File.AppendAllText(@"C:\temp\printproc.txt", "Train " + @@ -4154,7 +4043,7 @@ public virtual bool[] ProcessEndOfPath(int presentTime, bool checkLoop = true) if (positionNowBack == PresentPosition[0].TCSectionIndex && directionNowBack != PresentPosition[0].TCDirection) { ReverseFormation(false); - // active subpath must be incremented in parallel in incorporated train if present + // Active subpath must be incremented in parallel in incorporated train if present if (IncorporatedTrainNo >= 0) IncrementSubpath(Simulator.TrainDictionary[IncorporatedTrainNo]); @@ -4166,7 +4055,7 @@ public virtual bool[] ProcessEndOfPath(int presentTime, bool checkLoop = true) else if (positionNow == PresentPosition[1].TCSectionIndex && directionNow != PresentPosition[1].TCDirection) { ReverseFormation(false); - // active subpath must be incremented in parallel in incorporated train if present + // Active subpath must be incremented in parallel in incorporated train if present if (IncorporatedTrainNo >= 0) IncrementSubpath(Simulator.TrainDictionary[IncorporatedTrainNo]); #if DEBUG_REPORTS @@ -4181,8 +4070,7 @@ public virtual bool[] ProcessEndOfPath(int presentTime, bool checkLoop = true) Number.ToString() + " reversed\n"); } - // check if next station was on previous subpath - if so, move to this subpath - + // Check if next station was on previous subpath - if so, move to this subpath if (StationStops.Count > 0) { StationStop thisStation = StationStops[0]; @@ -4195,7 +4083,7 @@ public virtual bool[] ProcessEndOfPath(int presentTime, bool checkLoop = true) { thisStation.SubrouteIndex = TCRoute.activeSubpath; - if (ValidRoute[0].GetRouteIndex(thisStation.TCSectionIndex, 0) < 0) // station no longer on route + if (ValidRoute[0].GetRouteIndex(thisStation.TCSectionIndex, 0) < 0) // Station no longer on route { if (thisStation.ExitSignal >= 0 && thisStation.HoldSignal && HoldingSignals.Contains(thisStation.ExitSignal)) { @@ -4206,8 +4094,7 @@ public virtual bool[] ProcessEndOfPath(int presentTime, bool checkLoop = true) } } - // reset to node control, also reset required actions - + // Reset to node control, also reset required actions SwitchToNodeControl(-1); } else @@ -4215,7 +4102,7 @@ public virtual bool[] ProcessEndOfPath(int presentTime, bool checkLoop = true) ProcessEndOfPathReached(ref returnValue, presentTime); } - return (returnValue); + return returnValue; } public virtual void ProcessEndOfPathReached(ref bool[] returnValue, int PresentTime) @@ -4231,7 +4118,7 @@ public virtual void ProcessEndOfPathReached(ref bool[] returnValue, int PresentT } var removeIt = true; var distanceThreshold = PreUpdate ? 5.0f : 2.0f; - var distanceToNextSignal = DistanceToSignal.HasValue ? DistanceToSignal.Value : 0.1f; + var distanceToNextSignal = DistanceToSignal ?? 0.1f; if (Simulator.TimetableMode) removeIt = true; else if (TrainType == TRAINTYPE.AI_PLAYERHOSTING || Simulator.OriginalPlayerTrain == this) removeIt = false; @@ -4250,7 +4137,7 @@ public virtual void ProcessEndOfPathReached(ref bool[] returnValue, int PresentT MovementState = AI_MOVEMENT_STATE.FROZEN; } } - else + else { TrackCircuitSection thisSection = signalRef.TrackCircuitList[PresentPosition[1].TCSectionIndex]; if (TCRoute.ReversalInfo[TCRoute.activeSubpath - 1].Valid && PresentPosition[1].DistanceTravelledM < distanceThreshold && PresentPosition[1].TCOffset < 25) @@ -4264,7 +4151,7 @@ public virtual void ProcessEndOfPathReached(ref bool[] returnValue, int PresentT } } } - + if (removeIt) { if (IncorporatedTrainNo >= 0 && Simulator.TrainDictionary.Count > IncorporatedTrainNo && @@ -4284,7 +4171,7 @@ public virtual bool CheckCouplePosition(Train attachTrain, out bool thisTrainFro if (MUDirection == Direction.Reverse) { - usedTraveller = new Traveller(RearTDBTraveller, Traveller.TravellerDirection.Backward); // use in direction of movement + usedTraveller = new Traveller(RearTDBTraveller, Traveller.TravellerDirection.Backward); // Use in direction of movement thisTrainFront = false; usePosition = 1; } @@ -4294,23 +4181,23 @@ public virtual bool CheckCouplePosition(Train attachTrain, out bool thisTrainFro bool withinSection = false; // Check if train is in same section as other train, either for the other trains front or rear - if (PresentPosition[usePosition].TCSectionIndex == attachTrain.PresentPosition[0].TCSectionIndex) // train in same section as front + if (PresentPosition[usePosition].TCSectionIndex == attachTrain.PresentPosition[0].TCSectionIndex) // Train in same section as front { withinSection = true; } - else if (PresentPosition[usePosition].TCSectionIndex == attachTrain.PresentPosition[1].TCSectionIndex) // train in same section as rear + else if (PresentPosition[usePosition].TCSectionIndex == attachTrain.PresentPosition[1].TCSectionIndex) // Train in same section as rear { useOtherPosition = 1; withinSection = true; } - if (!withinSection) // not yet in same section + if (!withinSection) // Not yet in same section { - return (false); + return false; } - // test directions - if (PresentPosition[usePosition].TCDirection == attachTrain.PresentPosition[useOtherPosition].TCDirection) // trains are in same direction + // Test directions + if (PresentPosition[usePosition].TCDirection == attachTrain.PresentPosition[useOtherPosition].TCDirection) // Trains are in same direction { if (usePosition == 1) { @@ -4340,25 +4227,25 @@ public virtual bool CheckCouplePosition(Train attachTrain, out bool thisTrainFro File.AppendAllText(@"C:\temp\checktrain.txt", "Check couple position : preupdate : " + PreUpdate.ToString() + "\n"); } - if (PreUpdate) return (true); // in pre-update, being in the same section is good enough + if (PreUpdate) return true; // In pre-update, being in the same section is good enough - // check distance to other train + // Check distance to other train float dist = usedTraveller.OverlapDistanceM(otherTraveller, false); if (CheckTrain) { File.AppendAllText(@"C:\temp\checktrain.txt", "Check couple position : distance : " + dist.ToString() + "\n"); } - return (dist < 0.1f); + return dist < 0.1f; } public void CoupleAI(Train attachTrain, bool thisTrainFront, bool attachTrainFront) { - // stop train + // Stop train SpeedMpS = 0; AdjustControlsThrottleOff(); physicsUpdate(0); - // check for length of remaining path + // Check for length of remaining path if (attachTrain.TrainType == Train.TRAINTYPE.STATIC && (TCRoute.activeSubpath < TCRoute.TCRouteSubpaths.Count - 1 || ValidRoute[0].Count > 5)) { CoupleAIToStatic(attachTrain, thisTrainFront, attachTrainFront); @@ -4395,7 +4282,7 @@ public void CoupleAI(Train attachTrain, bool thisTrainFront, bool attachTrainFro // Must save this because below the player locomotive passes to the other train var isActualPlayerTrain = IsActualPlayerTrain; - // attach to front of waiting train + // Attach to front of waiting train if (attachTrainFront) { attachCar = Cars[Cars.Count - 1]; @@ -4403,42 +4290,42 @@ public void CoupleAI(Train attachTrain, bool thisTrainFront, bool attachTrainFro { var car = Cars[iCar]; car.Train = attachTrain; - // car.CarID = "AI" + attachTrain.Number.ToString() + " - " + (attachTrain.Cars.Count - 1).ToString(); + // car.CarID = "AI" + attachTrain.Number.ToString() + " - " + (attachTrain.Cars.Count - 1).ToString(); attachTrain.Cars.Insert(0, car); } if (attachTrain.LeadLocomotiveIndex >= 0) attachTrain.LeadLocomotiveIndex += Cars.Count; } - // attach to rear of waiting train + // Attach to rear of waiting train else { foreach (var car in Cars) { car.Train = attachTrain; - // car.CarID = "AI" + attachTrain.Number.ToString() + " - " + (attachTrain.Cars.Count - 1).ToString(); + // car.CarID = "AI" + attachTrain.Number.ToString() + " - " + (attachTrain.Cars.Count - 1).ToString(); attachTrain.Cars.Add(car); } } - // remove cars from this train + // Remove cars from this train Cars.Clear(); attachTrain.Length += Length; attachTrain.ReinitializeEOT(); - // recalculate position of formed train - if (attachTrainFront) // coupled to front, so rear position is still valid + // Recalculate position of formed train + if (attachTrainFront) // Coupled to front, so rear position is still valid { attachTrain.CalculatePositionOfCars(); attachTrain.DistanceTravelledM += Length; } - else // coupled to rear so front position is still valid + else // Coupled to rear so front position is still valid { - attachTrain.RepositionRearTraveller(); // fix the rear traveller + attachTrain.RepositionRearTraveller(); // Fix the rear traveller attachTrain.CalculatePositionOfCars(); } - // update positions train + // Update positions train TrackNode tn = attachTrain.FrontTDBTraveller.TN; float offset = attachTrain.FrontTDBTraveller.TrackNodeOffset; int direction = (int)attachTrain.FrontTDBTraveller.Direction; @@ -4451,7 +4338,7 @@ public void CoupleAI(Train attachTrain, bool thisTrainFront, bool attachTrainFro direction = (int)attachTrain.RearTDBTraveller.Direction; attachTrain.PresentPosition[1].SetTCPosition(tn.TCCrossReference, offset, direction); - // set various items + // Set various items attachTrain.CheckFreight(); attachTrain.SetDPUnitIDs(); attachTrain.activityClearingDistanceM = attachTrain.Cars.Count < standardTrainMinCarNo ? shortClearingDistanceM : standardClearingDistanceM; @@ -4465,7 +4352,7 @@ public void CoupleAI(Train attachTrain, bool thisTrainFront, bool attachTrainFro // Why initialize brakes of a disappeared train? // InitializeBrakes(); attachTrain.physicsUpdate(0); // stop the wheels from moving etc - // remove original train + // Remove original train if (isActualPlayerTrain && this != Simulator.OriginalPlayerTrain) { // Switch to the attached train as the one where we are now will be removed @@ -4486,8 +4373,7 @@ public void CoupleAI(Train attachTrain, bool thisTrainFront, bool attachTrainFro } else { - // if there is just here a reversal point, increment subpath in order to be in accordance with attachTrain - + // If there is just here a reversal point, increment subpath in order to be in accordance with attachTrain var ppTCSectionIndex = PresentPosition[0].TCSectionIndex; this.IncorporatingTrainNo = attachTrain.Number; this.IncorporatingTrain = attachTrain; @@ -4504,16 +4390,15 @@ public void CoupleAI(Train attachTrain, bool thisTrainFront, bool attachTrainFro /// Couple AI train to static train /// /// - public void CoupleAIToStatic(Train attachTrain, bool thisTrainFront, bool attachTrainFront) { - // check on reverse formation + // Check on reverse formation if (thisTrainFront == attachTrainFront) { attachTrain.ReverseFormation(false); } // Move cars from attachTrain to train - // attach to front of this train + // Attach to front of this train var attachCar = Cars[Cars.Count - 1]; if (thisTrainFront) { @@ -4522,7 +4407,7 @@ public void CoupleAIToStatic(Train attachTrain, bool thisTrainFront, bool attach { var car = attachTrain.Cars[iCar]; car.Train = this; - // car.CarID = "AI" + Number.ToString() + " - " + (Cars.Count - 1).ToString(); + // car.CarID = "AI" + Number.ToString() + " - " + (Cars.Count - 1).ToString(); Cars.Insert(0, car); } } @@ -4531,32 +4416,32 @@ public void CoupleAIToStatic(Train attachTrain, bool thisTrainFront, bool attach foreach (var car in attachTrain.Cars) { car.Train = this; - // car.CarID = "AI" + Number.ToString() + " - " + (Cars.Count - 1).ToString(); + // car.CarID = "AI" + Number.ToString() + " - " + (Cars.Count - 1).ToString(); Cars.Add(car); } } - // remove cars from attached train + // Remove cars from attached train Length += attachTrain.Length; attachTrain.Cars.Clear(); ReinitializeEOT(); - // recalculate position of formed train - if (thisTrainFront) // coupled to front, so rear position is still valid + // Recalculate position of formed train + if (thisTrainFront) // Coupled to front, so rear position is still valid { CalculatePositionOfCars(); DistanceTravelledM += attachTrain.Length; PresentPosition[0].DistanceTravelledM = DistanceTravelledM; requiredActions.ModifyRequiredDistance(attachTrain.Length); } - else // coupled to rear so front position is still valid + else // Coupled to rear so front position is still valid { - RepositionRearTraveller(); // fix the rear traveller + RepositionRearTraveller(); // Fix the rear traveller CalculatePositionOfCars(); PresentPosition[1].DistanceTravelledM = DistanceTravelledM - Length; } - // update positions train + // Update positions train TrackNode tn = FrontTDBTraveller.TN; float offset = FrontTDBTraveller.TrackNodeOffset; int direction = (int)FrontTDBTraveller.Direction; @@ -4569,13 +4454,13 @@ public void CoupleAIToStatic(Train attachTrain, bool thisTrainFront, bool attach direction = (int)RearTDBTraveller.Direction; PresentPosition[1].SetTCPosition(tn.TCCrossReference, offset, direction); - // set various items + // Set various items CheckFreight(); SetDPUnitIDs(); activityClearingDistanceM = Cars.Count < standardTrainMinCarNo ? shortClearingDistanceM : standardClearingDistanceM; attachCar.SignalEvent(Event.Couple); - // remove attached train + // Remove attached train if (attachTrain.TrainType == TRAINTYPE.AI) ((AITrain)attachTrain).RemoveTrain(); else @@ -4585,12 +4470,11 @@ public void CoupleAIToStatic(Train attachTrain, bool thisTrainFront, bool attach Simulator.TrainDictionary.Remove(attachTrain.Number); Simulator.NameDictionary.Remove(attachTrain.Name.ToLower()); } - if (MPManager.IsMultiPlayer()) MPManager.BroadCast((new MSGCouple(this, attachTrain, false)).ToString()); + if (MPManager.IsMultiPlayer()) MPManager.BroadCast(new MSGCouple(this, attachTrain, false).ToString()); UpdateOccupancies(); AddTrackSections(); ResetActions(true); physicsUpdate(0); - } //================================================================================================// @@ -4598,10 +4482,9 @@ public void CoupleAIToStatic(Train attachTrain, bool thisTrainFront, bool attach /// Couple AI train to living train (AI or player) and leave cars to it; both remain alive in this case /// /// - public void LeaveCarsToLivingTrain(Train attachTrain, bool thisTrainFront, bool attachTrainFront) { - // find set of cars between loco and attachtrain and pass them to train to attachtrain + // Find set of cars between loco and attachtrain and pass them to train to attachtrain var passedLength = 0.0f; if (thisTrainFront) { @@ -4673,7 +4556,6 @@ public void LeaveCarsToLivingTrain(Train attachTrain, bool thisTrainFront, bool /// /// Coupling AI train steals cars to coupled AI train /// - public void StealCarsToLivingTrain(Train attachTrain, bool thisTrainFront, bool attachTrainFront) { var stealedLength = 0.0f; @@ -4684,7 +4566,7 @@ public void StealCarsToLivingTrain(Train attachTrain, bool thisTrainFront, bool var car = attachTrain.Cars[0]; if (car is MSTSLocomotive) { - // no other car to steal, leave to the attached train its loco + // No other car to steal, leave to the attached train its loco break; } else @@ -4752,43 +4634,42 @@ public void StealCarsToLivingTrain(Train attachTrain, bool thisTrainFront, bool public void TerminateCoupling(Train attachTrain, bool thisTrainFront, bool attachTrainFront, float passedLength) { - // uncouple + // Uncouple UncoupledFrom = attachTrain; attachTrain.UncoupledFrom = this; ReinitializeEOT(); attachTrain.ReinitializeEOT(); - // recalculate position of coupling train - if (thisTrainFront) // coupled to front, so rear position is still valid + // Recalculate position of coupling train + if (thisTrainFront) // Coupled to front, so rear position is still valid { CalculatePositionOfCars(); DistanceTravelledM -= passedLength; Cars[0].BrakeSystem.AngleCockAOpen = false; } - else // coupled to rear so front position is still valid + else // Coupled to rear so front position is still valid { - RepositionRearTraveller(); // fix the rear traveller + RepositionRearTraveller(); // Fix the rear traveller CalculatePositionOfCars(); Cars[Cars.Count - 1].BrakeSystem.AngleCockBOpen = false; } - // recalculate position of coupled train - if (attachTrainFront) // coupled to front, so rear position is still valid + // Recalculate position of coupled train + if (attachTrainFront) // Coupled to front, so rear position is still valid { attachTrain.CalculatePositionOfCars(); attachTrain.DistanceTravelledM += passedLength; attachTrain.Cars[0].BrakeSystem.AngleCockAOpen = false; } - else // coupled to rear so front position is still valid + else // Coupled to rear so front position is still valid { - attachTrain.RepositionRearTraveller(); // fix the rear traveller + attachTrain.RepositionRearTraveller(); // Fix the rear traveller attachTrain.CalculatePositionOfCars(); attachTrain.Cars[attachTrain.Cars.Count - 1].BrakeSystem.AngleCockBOpen = false; } - - // update positions of coupling train + // Update positions of coupling train TrackNode tn = FrontTDBTraveller.TN; float offset = FrontTDBTraveller.TrackNodeOffset; int direction = (int)FrontTDBTraveller.Direction; @@ -4802,7 +4683,7 @@ public void TerminateCoupling(Train attachTrain, bool thisTrainFront, bool attac PresentPosition[1].SetTCPosition(tn.TCCrossReference, offset, direction); - // update positions of coupled train + // Update positions of coupled train tn = attachTrain.FrontTDBTraveller.TN; offset = attachTrain.FrontTDBTraveller.TrackNodeOffset; direction = (int)attachTrain.FrontTDBTraveller.Direction; @@ -4815,14 +4696,16 @@ public void TerminateCoupling(Train attachTrain, bool thisTrainFront, bool attac direction = (int)attachTrain.RearTDBTraveller.Direction; attachTrain.PresentPosition[1].SetTCPosition(tn.TCCrossReference, offset, direction); - // set various items + + // Set various items CheckFreight(); SetDPUnitIDs(); activityClearingDistanceM = Cars.Count < standardTrainMinCarNo ? shortClearingDistanceM : standardClearingDistanceM; attachTrain.CheckFreight(); attachTrain.SetDPUnitIDs(); attachTrain.activityClearingDistanceM = attachTrain.Cars.Count < standardTrainMinCarNo ? shortClearingDistanceM : standardClearingDistanceM; - // anticipate reversal point and remove active action + + // Anticipate reversal point and remove active action TCRoute.ReversalInfo[TCRoute.activeSubpath].ReverseReversalOffset = Math.Max(PresentPosition[0].TCOffset - 10f, 0.3f); if (PresentPosition[0].TCSectionIndex != TCRoute.ReversalInfo[TCRoute.activeSubpath].ReversalSectionIndex) { @@ -4830,11 +4713,11 @@ public void TerminateCoupling(Train attachTrain, bool thisTrainFront, bool attac } if (PresentPosition[1].RouteListIndex < TCRoute.ReversalInfo[TCRoute.activeSubpath].LastSignalIndex) TCRoute.ReversalInfo[TCRoute.activeSubpath].LastSignalIndex = PresentPosition[1].RouteListIndex; - // move WP, if any, just under the loco; + // Move WP, if any, just under the loco; AuxActionsContain.MoveAuxActionAfterReversal(this); ResetActions(true); - physicsUpdate(0); // stop the wheels from moving etc + physicsUpdate(0);// Stop the wheels from moving etc } @@ -4843,8 +4726,8 @@ public void TerminateCoupling(Train attachTrain, bool thisTrainFront, bool attac /// TestUncouple /// Tests if Waiting point delay >40000 and <59999; under certain conditions this means that /// an uncoupling action happens - ///delay (in decimal notation) = 4NNSS (uncouple cars after NNth from train front (locos included), wait SS seconds) - // or 5NNSS (uncouple cars before NNth from train rear (locos included), keep rear, wait SS seconds) + /// delay (in decimal notation) = 4NNSS (uncouple cars after NNth from train front (locos included), wait SS seconds) + /// or 5NNSS (uncouple cars before NNth from train rear (locos included), keep rear, wait SS seconds) /// remember that for AI trains train front is the one of the actual moving direction, so train front changes at every reverse point /// /// @@ -4859,7 +4742,7 @@ public void TestUncouple(ref int delay) delay = delay - 10000; } carsToKeep = (delay - 40000) / 100; - delay = delay - 40000 - carsToKeep * 100; + delay = delay - 40000 - (carsToKeep * 100); if (IsActualPlayerTrain && TrainType == TRAINTYPE.AI_PLAYERDRIVEN && this != Simulator.OriginalPlayerTrain) { Simulator.ActivityRun.MsgFromNewPlayer = String.Format("Uncouple and keep coupled only {0} {1} cars", carsToKeep, keepFront ? "first" : "last"); @@ -4877,13 +4760,13 @@ public void TestUncouple(ref int delay) /// private void UncoupleSomeWagons(int carsToKeep, bool keepFront) { - // first test that carsToKeep is smaller than number of cars of train + // First test that carsToKeep is smaller than number of cars of train if (carsToKeep >= Cars.Count) { carsToKeep = Cars.Count - 1; Trace.TraceWarning("Train {0} Service {1} reduced cars to uncouple", Number, Name); } - // then test if there is at least one loco in the not-uncoupled part + // Then test if there is at least one loco in the not-uncoupled part int startCarIndex = keepFront ? 0 : Cars.Count - carsToKeep; int endCarIndex = keepFront ? carsToKeep - 1 : Cars.Count - 1; bool foundLoco = false; @@ -4897,23 +4780,19 @@ private void UncoupleSomeWagons(int carsToKeep, bool keepFront) } if (!foundLoco) { - // no loco in remaining part, abort operation + // No loco in remaining part, abort operation Trace.TraceWarning("Train {0} Service {1} Uncoupling not executed, no loco in remaining part of train", Number, Name); return; } int uncouplePoint = keepFront ? carsToKeep - 1 : Cars.Count - carsToKeep - 1; Simulator.UncoupleBehind(Cars[uncouplePoint], keepFront); - - } //================================================================================================// /// /// TestUncondAttach /// Tests if Waiting point delay =60001; under certain conditions this means that the train has to attach the nearby train - /// - /// public void TestUncondAttach(ref int delay) { if (delay != 60001) return; @@ -4933,9 +4812,7 @@ public void TestUncondAttach(ref int delay) /// /// TestPermission /// Tests if Waiting point delay =60002; a permission request to pass next signal is launched. - /// - /// public void TestPermission(ref int delay) { if (delay != 60002) return; @@ -4955,16 +4832,13 @@ public void TestPermission(ref int delay) // // Request signal permission for AI trains (triggered by WP 60002) // - public void RequestSignalPermission(TCSubpathRoute selectedRoute, int routeIndex) { - // check if signal at danger - + // Check if signal at danger TCRouteElement thisElement = selectedRoute[PresentPosition[0].RouteListIndex]; TrackCircuitSection thisSection = signalRef.TrackCircuitList[thisElement.TCSectionIndex]; - // no signal in required direction - + // No signal in required direction if (thisSection.EndSignals[thisElement.Direction] == null) return; @@ -4979,12 +4853,10 @@ public void RequestSignalPermission(TCSubpathRoute selectedRoute, int routeIndex requestedSignal.checkRouteState(false, requestedSignal.signalRoute, routedForward, false); } - //================================================================================================// /// /// Remove train /// - public override void RemoveTrain() { RemoveFromTrack(); @@ -5010,8 +4882,7 @@ public override void RemoveTrain() } } #endif - // remove train - + // Remove train AI.TrainsToRemove.Add(this); } @@ -5019,14 +4890,13 @@ public override void RemoveTrain() /// /// Suspend train because incorporated in other train /// - public virtual void SuspendTrain(Train incorporatingTrain) { RemoveFromTrack(); ClearDeadlocks(); NextSignalObject[0] = null; NextSignalObject[1] = null; - // reset AuxAction if any + // Reset AuxAction if any AuxActionsContain.ResetAuxAction(this); TrainType = TRAINTYPE.AI_INCORPORATED; LeadLocomotiveIndex = -1; @@ -5041,20 +4911,17 @@ public virtual void SuspendTrain(Train incorporatingTrain) /// /// Insert action item /// - public void CreateTrainAction(float presentSpeedMpS, float reqSpeedMpS, float distanceToTrainM, ObjectItemInfo thisItem, AIActionItem.AI_ACTION_TYPE thisAction) { - // if signal or speed limit take off clearing distance - + // If signal or speed limit take off clearing distance float activateDistanceTravelledM = PresentPosition[0].DistanceTravelledM + distanceToTrainM; if (thisItem != null) { activateDistanceTravelledM -= Simulator.TimetableMode ? clearingDistanceM : activityClearingDistanceM; } - // calculate braking distance - + // Calculate braking distance float firstPartTime = 0.0f; float firstPartRangeM = 0.0f; float secondPartTime = 0.0f; @@ -5064,51 +4931,52 @@ public virtual void SuspendTrain(Train incorporatingTrain) float triggerDistanceM = PresentPosition[0].DistanceTravelledM; // worst case + // TODO: Can we remove this? // braking distance - use 0.22 * MaxDecelMpSS as average deceleration (due to braking delay) // T = deltaV / A // R = 0.5 * Vdelta * T + Vreq * T = 0.5 * (Vnow + Vreq) * T // 0.5 * Vdelta is average speed over used time, 0.5 * Vdelta * T is related distance covered , Vreq * T is additional distance covered at minimal speed float fullPartTime = (AllowedMaxSpeedMpS - reqSpeedMpS) / (0.22f * MaxDecelMpSS); - float fullPartRangeM = ((AllowedMaxSpeedMpS + reqSpeedMpS) * 0.5f * fullPartTime); + float fullPartRangeM = (AllowedMaxSpeedMpS + reqSpeedMpS) * 0.5f * fullPartTime; - // if present speed higher, brake distance is always required (same equation) + // If present speed higher, brake distance is always required (same equation) if (presentSpeedMpS > reqSpeedMpS) { firstPartTime = (presentSpeedMpS - reqSpeedMpS) / (0.22f * MaxDecelMpSS); - firstPartRangeM = ((presentSpeedMpS + reqSpeedMpS) * 0.5f * firstPartTime); + firstPartRangeM = (presentSpeedMpS + reqSpeedMpS) * 0.5f * firstPartTime; } minReqRangeM = Math.Max(fullPartRangeM, firstPartRangeM); - // if present speed below max speed, calculate distance required to accelerate to max speed (same equation) + // If present speed below max speed, calculate distance required to accelerate to max speed (same equation) if (presentSpeedMpS < AllowedMaxSpeedMpS) { secondPartTime = (AllowedMaxSpeedMpS - presentSpeedMpS) / (0.5f * MaxAccelMpSS); secondPartRangeM = (AllowedMaxSpeedMpS + presentSpeedMpS) * 0.5f * secondPartTime; } - // if full length possible, set as trigger distance + // If full length possible, set as trigger distance if ((minReqRangeM + secondPartRangeM) < remainingRangeM) { triggerDistanceM = activateDistanceTravelledM - (fullPartRangeM + secondPartRangeM); } - // if braking from full speed still possible, set as trigger distance - // train will accelerate upto trigger point but probably not reach full speed, so there is enough braking distance available + // If braking from full speed still possible, set as trigger distance + // Train will accelerate upto trigger point but probably not reach full speed, so there is enough braking distance available else if (minReqRangeM < remainingRangeM) { triggerDistanceM = activateDistanceTravelledM - fullPartRangeM; } - // else if still possible, use minimun range based on present speed + // Else if still possible, use minimun range based on present speed else if (firstPartRangeM < remainingRangeM) { triggerDistanceM = activateDistanceTravelledM - firstPartRangeM; } - // correct trigger for approach distance but not backward beyond present position + // Correct trigger for approach distance but not backward beyond present position triggerDistanceM = Math.Max(PresentPosition[0].DistanceTravelledM, triggerDistanceM - (3.0f * signalApproachDistanceM)); - // for signal stop item : check if action allready in list, if so, remove (can be result of restore action) + // For signal stop item: check if action allready in list, if so, remove (can be result of restore action) LinkedListNode thisItemLink = requiredActions.First; bool itemFound = false; @@ -5122,7 +4990,7 @@ public virtual void SuspendTrain(Train incorporatingTrain) { if (thisActionItem.ActiveItem.ObjectDetails.thisRef == thisItem.ObjectDetails.thisRef) { - // equal item, so remove it + // Equal item, so remove it requiredActions.Remove(thisDTItem); itemFound = true; } @@ -5134,8 +5002,7 @@ public virtual void SuspendTrain(Train incorporatingTrain) } } - // create and insert action - + // Create and insert action AIActionItem newAction = new AIActionItem(thisItem, thisAction); newAction.SetParam(triggerDistanceM, reqSpeedMpS, activateDistanceTravelledM, DistanceTravelledM); requiredActions.InsertAction(newAction); @@ -5189,17 +5056,14 @@ public virtual void SuspendTrain(Train incorporatingTrain) /// /// Insert action item for end-of-route /// - public virtual void SetEndOfRouteAction() { - // remaining length first section - + // Remaining length first section TrackCircuitSection thisSection = signalRef.TrackCircuitList[PresentPosition[0].TCSectionIndex]; float lengthToGoM = thisSection.Length - PresentPosition[0].TCOffset; if (TCRoute.activeSubpath < TCRoute.TCRouteSubpaths.Count - 1) { - // go through all further sections - + // Go through all further sections for (int iElement = PresentPosition[0].RouteListIndex + 1; iElement < ValidRoute[0].Count; iElement++) { TCRouteElement thisElement = ValidRoute[0][iElement]; @@ -5208,11 +5072,9 @@ public virtual void SetEndOfRouteAction() } } else lengthToGoM = ComputeDistanceToReversalPoint(); - lengthToGoM -= 5.0f; // keep save distance from end - - // if last section does not end at signal at next section is switch, set back overlap to keep clear of switch - // only do so for last subroute to avoid falling short of reversal points + lengthToGoM -= 5.0f; // Keep save distance from end + // Only do so for last subroute to avoid falling short of reversal points TCRouteElement lastElement = ValidRoute[0][ValidRoute[0].Count - 1]; TrackCircuitSection lastSection = signalRef.TrackCircuitList[lastElement.TCSectionIndex]; @@ -5225,7 +5087,6 @@ public virtual void SetEndOfRouteAction() /// /// Reset action list /// - public void ResetActions(bool setEndOfPath, bool fromAutopilotSwitch = false) { #if DEBUG_REPORTS @@ -5268,38 +5129,38 @@ public void ResetActions(bool setEndOfPath, bool fromAutopilotSwitch = false) } } - // do not set actions for player train + // Do not set actions for player train if (TrainType == TRAINTYPE.PLAYER) { return; } - // reset signal items processed state + // Reset signal items processed state nextActionInfo = null; foreach (ObjectItemInfo thisInfo in SignalObjectItems) { thisInfo.processed = false; } - // clear any outstanding actions + // Clear any outstanding actions requiredActions.RemovePendingAIActionItems(false); - // reset auxiliary actions + // Reset auxiliary actions AuxActionsContain.SetAuxAction(this); - // set next station stop in not at station + // Set next station stop in not at station if (StationStops.Count > 0) { SetNextStationAction(fromAutopilotSwitch); } - // set end of path if required + // Set end of path if required if (setEndOfPath) { SetEndOfRouteAction(); } - // to allow re-inserting of reversal action if necessary + // To allow re-inserting of reversal action if necessary if (TCRoute.ReversalInfo[TCRoute.activeSubpath].ReversalActionInserted == true) { TCRoute.ReversalInfo[TCRoute.activeSubpath].ReversalActionInserted = false; @@ -5310,7 +5171,6 @@ public void ResetActions(bool setEndOfPath, bool fromAutopilotSwitch = false) /// /// Perform stored actions /// - public override void PerformActions(List nowActions) { foreach (var thisAction in nowActions) @@ -5349,9 +5209,7 @@ public override void PerformActions(List nowActions) } else if (thisAction is AuxActionItem) { - var presentTime = 0; - if (!PreUpdate) presentTime = Convert.ToInt32(Math.Floor(Simulator.ClockTime)); - else presentTime = Convert.ToInt32(Math.Floor(AI.clockTime)); + var presentTime = !PreUpdate ? Convert.ToInt32(Math.Floor(Simulator.ClockTime)) : Convert.ToInt32(Math.Floor(AI.clockTime)); var actionState = ((AuxActionItem)thisAction).ProcessAction(this, presentTime); if (actionState != AI_MOVEMENT_STATE.INIT_ACTION && actionState != AI_MOVEMENT_STATE.HANDLE_ACTION) MovementState = actionState; @@ -5363,7 +5221,6 @@ public override void PerformActions(List nowActions) /// /// Set pending speed limits /// - public void SetAIPendingSpeedLimit(ActivateSpeedLimit speedInfo) { if (speedInfo.MaxSpeedMpSSignal > 0) @@ -5374,20 +5231,19 @@ public void SetAIPendingSpeedLimit(ActivateSpeedLimit speedInfo) if (speedInfo.MaxSpeedMpSLimit > 0) { allowedMaxSpeedLimitMpS = Simulator.TimetableMode ? speedInfo.MaxSpeedMpSLimit : allowedAbsoluteMaxSpeedLimitMpS; - if (Simulator.TimetableMode) - AllowedMaxSpeedMpS = speedInfo.MaxSpeedMpSLimit; - else - AllowedMaxSpeedMpS = Math.Min(speedInfo.MaxSpeedMpSLimit, Math.Min(allowedMaxSpeedSignalMpS, allowedMaxTempSpeedLimitMpS)); + AllowedMaxSpeedMpS = Simulator.TimetableMode + ? speedInfo.MaxSpeedMpSLimit + : Math.Min(speedInfo.MaxSpeedMpSLimit, Math.Min(allowedMaxSpeedSignalMpS, allowedMaxTempSpeedLimitMpS)); } if (speedInfo.MaxTempSpeedMpSLimit > 0) { allowedMaxTempSpeedLimitMpS = allowedAbsoluteMaxTempSpeedLimitMpS; AllowedMaxSpeedMpS = Math.Min(speedInfo.MaxTempSpeedMpSLimit, Math.Min(allowedMaxSpeedSignalMpS, allowedMaxSpeedLimitMpS)); } - // following statement should be valid in general, as it seems there was a bug here in the original SW + // Following statement should be valid in general, as it seems there was a bug here in the original SW AllowedMaxSpeedMpS = Math.Min(AllowedMaxSpeedMpS, TrainMaxSpeedMpS); - if (MovementState == AI_MOVEMENT_STATE.RUNNING && SpeedMpS < AllowedMaxSpeedMpS - 2.0f * hysterisMpS) + if (MovementState == AI_MOVEMENT_STATE.RUNNING && SpeedMpS < AllowedMaxSpeedMpS - (2.0f * hysterisMpS)) { MovementState = AI_MOVEMENT_STATE.ACCELERATING; Alpha10 = PreUpdate & !Simulator.TimetableMode ? 2 : 10; @@ -5401,8 +5257,7 @@ public void SetAIPendingSpeedLimit(ActivateSpeedLimit speedInfo) #endif - // reset pending actions to recalculate braking distance - + // Reset pending actions to recalculate braking distance ResetActions(true); } @@ -5410,11 +5265,9 @@ public void SetAIPendingSpeedLimit(ActivateSpeedLimit speedInfo) /// /// Process pending actions /// - public void ProcessActionItem(AIActionItem thisItem) { - // normal actions - + // Normal actions bool actionValid = true; bool actionCleared = false; @@ -5466,11 +5319,10 @@ public void ProcessActionItem(AIActionItem thisItem) } } - // if signal speed, check if still set - + // If signal speed, check if still set if (thisItem.NextAction == AIActionItem.AI_ACTION_TYPE.SPEED_SIGNAL) { - if (thisItem.ActiveItem.actual_speed == AllowedMaxSpeedMpS) // no longer valid + if (thisItem.ActiveItem.actual_speed == AllowedMaxSpeedMpS) // No longer valid { actionValid = false; } @@ -5480,14 +5332,13 @@ public void ProcessActionItem(AIActionItem thisItem) } } - // if signal, check if not held for station stop (station stop comes first) - + // If signal, check if not held for station stop (station stop comes first) else if (thisItem.NextAction == AIActionItem.AI_ACTION_TYPE.SIGNAL_ASPECT_STOP) { if (thisItem.ActiveItem.signal_state == MstsSignalAspect.STOP && thisItem.ActiveItem.ObjectDetails.holdState == HoldState.StationStop) { - // check if train is approaching or standing at station and has not yet departed + // Check if train is approaching or standing at station and has not yet departed if (StationStops != null && StationStops.Count >= 1 && AtStation && StationStops[0].ExitSignal == thisItem.ActiveItem.ObjectDetails.thisRef) { actionValid = false; @@ -5523,9 +5374,7 @@ public void ProcessActionItem(AIActionItem thisItem) } } } - - // check if cleared - + // Check if cleared else if (thisItem.ActiveItem.signal_state >= MstsSignalAspect.APPROACH_1) { actionValid = false; @@ -5545,9 +5394,7 @@ public void ProcessActionItem(AIActionItem thisItem) thisItem.ActivateDistanceM.ToString() + " cleared\n"); } } - - // check if restricted - + // Dheck if restricted else if (thisItem.ActiveItem.signal_state != MstsSignalAspect.STOP) { thisItem.NextAction = AIActionItem.AI_ACTION_TYPE.SIGNAL_ASPECT_RESTRICTED; @@ -5573,7 +5420,7 @@ public void ProcessActionItem(AIActionItem thisItem) } } - // recalculate braking distance if train is running slow + // Recalculate braking distance if train is running slow if (actionValid && SpeedMpS < creepSpeedMpS) { float firstPartTime = 0.0f; @@ -5581,20 +5428,20 @@ public void ProcessActionItem(AIActionItem thisItem) float secndPartRangeM = 0.0f; float remainingRangeM = thisItem.ActivateDistanceM - PresentPosition[0].DistanceTravelledM; - if (SpeedMpS > thisItem.RequiredSpeedMpS) // if present speed higher, brake distance is always required + if (SpeedMpS > thisItem.RequiredSpeedMpS) // If present speed higher, brake distance is always required { firstPartTime = (SpeedMpS - thisItem.RequiredSpeedMpS) / (0.25f * MaxDecelMpSS); firstPartRangeM = 0.25f * MaxDecelMpSS * (firstPartTime * firstPartTime); } - if (firstPartRangeM < remainingRangeM && SpeedMpS < TrainMaxSpeedMpS) // if distance left and not at max speed - // split remaining distance based on relation between acceleration and deceleration + if (firstPartRangeM < remainingRangeM && SpeedMpS < TrainMaxSpeedMpS) // If distance left and not at max speed + // Split remaining distance based on relation between acceleration and deceleration { secndPartRangeM = (remainingRangeM - firstPartRangeM) * (2.0f * MaxDecelMpSS) / (MaxDecelMpSS + MaxAccelMpSS); } float fullRangeM = firstPartRangeM + secndPartRangeM; - if (fullRangeM < remainingRangeM && remainingRangeM > 300.0f) // if range is shorter and train not too close, reschedule + if (fullRangeM < remainingRangeM && remainingRangeM > 300.0f) // If range is shorter and train not too close, reschedule { actionValid = false; thisItem.RequiredDistance = thisItem.ActivateDistanceM - fullRangeM; @@ -5622,12 +5469,10 @@ public void ProcessActionItem(AIActionItem thisItem) FormatStrings.FormatSpeed(SpeedMpS, true) + ")\n"); } } - } } - // if signal at RESTRICTED, check if not cleared - + // If signal at RESTRICTED, check if not cleared else if (thisItem.NextAction == AIActionItem.AI_ACTION_TYPE.SIGNAL_ASPECT_RESTRICTED) { if (thisItem.ActiveItem.signal_state >= MstsSignalAspect.APPROACH_1 || @@ -5651,20 +5496,18 @@ public void ProcessActionItem(AIActionItem thisItem) } } - // get station stop, recalculate with present speed if required - + // Get station stop, recalculate with present speed if required else if (thisItem.NextAction == AIActionItem.AI_ACTION_TYPE.STATION_STOP) { float[] distancesM = CalculateDistancesToNextStation(StationStops[0], SpeedMpS, true); - if (distancesM[1] - 300.0f > DistanceTravelledM) // trigger point more than 300m away + if (distancesM[1] - 300.0f > DistanceTravelledM) // Trigger point more than 300m away { actionValid = false; thisItem.RequiredDistance = distancesM[1]; thisItem.ActivateDistanceM = distancesM[0]; requiredActions.InsertAction(thisItem); - #if DEBUG_REPORTS File.AppendAllText(@"C:\temp\printproc.txt", "StationStop rescheduled for train " + Number.ToString() + ", at " + @@ -5684,8 +5527,8 @@ public void ProcessActionItem(AIActionItem thisItem) } } else - // always copy active stop distance { + // Always copy active stop distance thisItem.ActivateDistanceM = distancesM[0]; } } @@ -5693,12 +5536,11 @@ public void ProcessActionItem(AIActionItem thisItem) EndProcessAction(actionValid, thisItem, actionCleared); } - // SPA: To be able to call it by AuxActionItems + // SPA: To be able to call it by AuxActionItems public void EndProcessAction(bool actionValid, AIActionItem thisItem, bool actionCleared) { - // if still valid - check if at station and signal is exit signal - // if so, use minimum distance of both items to ensure train stops in time for signal - + // If still valid - check if at station and signal is exit signal + // If so, use minimum distance of both items to ensure train stops in time for signal if (actionValid && nextActionInfo != null && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.STATION_STOP && thisItem.NextAction == AIActionItem.AI_ACTION_TYPE.SIGNAL_ASPECT_STOP) @@ -5742,7 +5584,7 @@ public void EndProcessAction(bool actionValid, AIActionItem thisItem, bool actio } } - // if still valid, check if this action is end of route and actual next action is station stop - if so, reject + // If still valid, check if this action is end of route and actual next action is station stop - if so, reject if (actionValid && nextActionInfo != null && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.STATION_STOP && thisItem.NextAction == AIActionItem.AI_ACTION_TYPE.END_OF_ROUTE) { @@ -5766,9 +5608,8 @@ public void EndProcessAction(bool actionValid, AIActionItem thisItem, bool actio } } - // if still valid - check if actual next action is WP and signal is WP controlled signal - // if so, use minimum distance of both items to ensure train stops in time for signal - + // If still valid - check if actual next action is WP and signal is WP controlled signal + // If so, use minimum distance of both items to ensure train stops in time for signal if (actionValid && nextActionInfo != null && nextActionInfo is AuxActionWPItem && thisItem.NextAction == AIActionItem.AI_ACTION_TYPE.SIGNAL_ASPECT_STOP) { @@ -5780,8 +5621,7 @@ public void EndProcessAction(bool actionValid, AIActionItem thisItem, bool actio } } - // if still valid - check if more severe as existing action - + // If still valid - check if more severe as existing action bool earlier = false; if (actionValid) @@ -5794,8 +5634,9 @@ public void EndProcessAction(bool actionValid, AIActionItem thisItem, bool actio { earlier = true; } - else // new requirement earlier with higher speed - check if enough braking distance remaining + else { + // New requirement earlier with higher speed - check if enough braking distance remaining float deltaTime = (thisItem.RequiredSpeedMpS - nextActionInfo.RequiredSpeedMpS) / MaxDecelMpSS; float brakingDistanceM = (thisItem.RequiredSpeedMpS * deltaTime) + (0.5f * MaxDecelMpSS * deltaTime * deltaTime); @@ -5806,8 +5647,8 @@ public void EndProcessAction(bool actionValid, AIActionItem thisItem, bool actio } } else if (thisItem.RequiredSpeedMpS < nextActionInfo.RequiredSpeedMpS) - // new requirement further but with lower speed - check if enough braking distance left { + // New requirement further but with lower speed - check if enough braking distance left float deltaTime = (nextActionInfo.RequiredSpeedMpS - thisItem.RequiredSpeedMpS) / MaxDecelMpSS; float brakingDistanceM = (nextActionInfo.RequiredSpeedMpS * deltaTime) + (0.5f * MaxDecelMpSS * deltaTime * deltaTime); @@ -5817,12 +5658,11 @@ public void EndProcessAction(bool actionValid, AIActionItem thisItem, bool actio } } - // if earlier : check if present action is station stop, new action is signal - if so, check is signal really in front of or behind station stop - + // If earlier: check if present action is station stop, new action is signal - if so, check is signal really in front of or behind station stop if (earlier && thisItem.NextAction == AIActionItem.AI_ACTION_TYPE.SIGNAL_ASPECT_STOP && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.STATION_STOP) { - float newposition = thisItem.ActivateDistanceM + 0.75f * activityClearingDistanceM; // correct with clearing distance - leave smaller gap + float newposition = thisItem.ActivateDistanceM + (0.75f * activityClearingDistanceM); // Correct with clearing distance - leave smaller gap float actposition = nextActionInfo.ActivateDistanceM; if (actposition < newposition) earlier = false; @@ -5832,7 +5672,7 @@ public void EndProcessAction(bool actionValid, AIActionItem thisItem, bool actio File.AppendAllText(@"C:\temp\checktrain.txt", "allowing minimum gap : " + newposition.ToString() + " and " + actposition.ToString() + "\n"); } - // if still earlier : check if signal really beyond start of platform + // If still earlier: check if signal really beyond start of platform if (earlier && (StationStops[0].DistanceToTrainM - thisItem.ActiveItem.distance_to_train) < StationStops[0].StopOffset) { earlier = false; @@ -5843,11 +5683,10 @@ public void EndProcessAction(bool actionValid, AIActionItem thisItem, bool actio } StationStops[0].DistanceToTrainM = thisItem.ActiveItem.distance_to_train - 1; nextActionInfo.ActivateDistanceM = thisItem.ActivateDistanceM - 1; - } + } } - // check if present action is signal and new action is station - if so, check actual position of signal in relation to stop - + // Check if present action is signal and new action is station - if so, check actual position of signal in relation to stop if (thisItem.NextAction == AIActionItem.AI_ACTION_TYPE.STATION_STOP && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.SIGNAL_ASPECT_STOP) { if (StationStops[0].DistanceToTrainM < nextActionInfo.ActiveItem.distance_to_train) @@ -5856,9 +5695,8 @@ public void EndProcessAction(bool actionValid, AIActionItem thisItem, bool actio } } - // if not earlier and station stop and present action is signal stop : check if signal is hold signal, if so set station stop - // set distance to signal if that is less than distance to platform to ensure trains stops at signal - + // If not earlier and station stop and present action is signal stop: check if signal is hold signal, if so set station stop + // Set distance to signal if that is less than distance to platform to ensure trains stops at signal if (!earlier && thisItem.NextAction == AIActionItem.AI_ACTION_TYPE.STATION_STOP && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.SIGNAL_ASPECT_STOP) { @@ -5869,18 +5707,16 @@ public void EndProcessAction(bool actionValid, AIActionItem thisItem, bool actio } } - // if not earlier and station stop and present action is end of route : favour station - + // If not earlier and station stop and present action is end of route: favour station if (!earlier && thisItem.NextAction == AIActionItem.AI_ACTION_TYPE.STATION_STOP && (nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.END_OF_ROUTE || nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.END_OF_AUTHORITY)) { - earlier = true; - nextActionInfo.ActivateDistanceM = thisItem.ActivateDistanceM + 1.0f; + earlier = true; + nextActionInfo.ActivateDistanceM = thisItem.ActivateDistanceM + 1.0f; } - // if not earlier and is a waiting point and present action is signal stop : check if signal is locking signal, if so set waiting - // set distance to signal if that is less than distance to WP to ensure trains stops at signal - + // If not earlier and is a waiting point and present action is signal stop: check if signal is locking signal, if so set waiting + // Set distance to signal if that is less than distance to WP to ensure trains stops at signal if (!earlier && thisItem is AuxActionWPItem && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.SIGNAL_ASPECT_STOP) { @@ -5895,8 +5731,7 @@ public void EndProcessAction(bool actionValid, AIActionItem thisItem, bool actio if (MovementState == AI_MOVEMENT_STATE.INIT_ACTION || MovementState == AI_MOVEMENT_STATE.HANDLE_ACTION) earlier = false; - // reject if less severe (will be rescheduled if active item is cleared) - + // Reject if less severe (will be rescheduled if active item is cleared) if (!earlier) { actionValid = false; @@ -5942,8 +5777,7 @@ public void EndProcessAction(bool actionValid, AIActionItem thisItem, bool actio } } - // if still valid, set as action, set state to braking if still running - + // If still valid, set as action, set state to braking if still running var stationCancelled = false; if (actionValid) { @@ -5960,7 +5794,7 @@ public void EndProcessAction(bool actionValid, AIActionItem thisItem, bool actio AuxActionRef actionRef = action.ActionRef; if (actionRef.IsGeneric) { - nextGenAction = thisItem; // SPA In order to manage GenericAuxAction without disturbing normal actions + nextGenAction = thisItem; // SPA: In order to manage GenericAuxAction without disturbing normal actions requiredActions.Remove(thisItem); } else @@ -5981,7 +5815,7 @@ public void EndProcessAction(bool actionValid, AIActionItem thisItem, bool actio NextStopDistanceM = thisItem.ActivateDistanceM - PresentPosition[0].DistanceTravelledM; if (Simulator.PreUpdate && !(nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.AUX_ACTION && NextStopDistanceM > minCheckDistanceM)) { - AITrainBrakePercent = 100; // because of short reaction time + AITrainBrakePercent = 100; // Because of short reaction time AITrainThrottlePercent = 0; if (CheckTrain) { @@ -5996,8 +5830,8 @@ public void EndProcessAction(bool actionValid, AIActionItem thisItem, bool actio #endif - if (MovementState != AI_MOVEMENT_STATE.STATION_STOP && - MovementState != AI_MOVEMENT_STATE.STOPPED && + if (MovementState != AI_MOVEMENT_STATE.STATION_STOP && + MovementState != AI_MOVEMENT_STATE.STOPPED && MovementState != AI_MOVEMENT_STATE.HANDLE_ACTION && MovementState != AI_MOVEMENT_STATE.FOLLOWING && MovementState != AI_MOVEMENT_STATE.TURNTABLE && @@ -6053,8 +5887,8 @@ public void EndProcessAction(bool actionValid, AIActionItem thisItem, bool actio { File.AppendAllText(@"C:\temp\checktrain.txt", "Action Cleared\n"); } - // reset actions - ensure next action is validated + // Reset actions - ensure next action is validated ResetActions(true); } else if (stationCancelled) @@ -6069,24 +5903,22 @@ public bool TrainHasPower() { if (car is MSTSLocomotive) { - return (true); + return true; } } - return (false); + return false; } //================================================================================================// // // Extra actions when alternative route is set // - public override void SetAlternativeRoute_pathBased(int startElementIndex, int altRouteIndex, SignalObject nextSignal) { base.SetAlternativeRoute_pathBased(startElementIndex, altRouteIndex, nextSignal); - // reset actions to recalculate distances - + // Reset actions to recalculate distances ResetActions(true); } @@ -6094,8 +5926,7 @@ public override void SetAlternativeRoute_locationBased(int startSectionIndex, De { base.SetAlternativeRoute_locationBased(startSectionIndex, sectionDeadlockInfo, usedPath, nextSignal); - // reset actions to recalculate distances - + // Reset actions to recalculate distances ResetActions(true); } @@ -6103,8 +5934,6 @@ public override void SetAlternativeRoute_locationBased(int startSectionIndex, De // // Find station on alternative route // - // - public override StationStop SetAlternativeStationStop(StationStop orgStop, TCSubpathRoute newRoute) { var newStop = base.SetAlternativeStationStop(orgStop, newRoute); @@ -6155,7 +5984,6 @@ public override StationStop SetAlternativeStationStop(StationStop orgStop, TCSub /// Distance to /// 11 Train Name /// - public virtual String[] AddMovementState(String[] stateString, bool metric) { String[] retString = new String[stateString.Length]; @@ -6280,7 +6108,6 @@ public virtual String[] AddMovementState(String[] stateString, bool metric) } string nameString = Name.Substring(0, Math.Min(Name.Length, 7)); - string actString = ""; if (nextActionInfo != null) @@ -6332,7 +6159,7 @@ public virtual String[] AddMovementState(String[] stateString, bool metric) retString[5] = String.Copy(abString); retString[11] = String.Copy(nameString); - return (retString); + return retString; } //================================================================================================// @@ -6421,17 +6248,16 @@ public bool SwitchToAutopilotControl() StationStops[0].ActualArrival = -(int)(new DateTime().Add(TimeSpan.FromSeconds(0.0)) - ((ActivityTaskPassengerStopAt)Simulator.ActivityRun.Current).ActArrive).Value.TotalSeconds; MovementState = AI_MOVEMENT_STATE.STATION_STOP; } - else if (this != Simulator.OriginalPlayerTrain && AtStation) - { - MovementState = AI_MOVEMENT_STATE.STATION_STOP; - } - else if (Math.Abs(SpeedMpS) <= 0.1f && ((AuxActionsContain.SpecAuxActions.Count > 0 && AuxActionsContain.SpecAuxActions[0] is AIActionWPRef && (AuxActionsContain.SpecAuxActions[0] as AIActionWPRef).keepIt != null && - (AuxActionsContain.SpecAuxActions[0] as AIActionWPRef).keepIt.currentMvmtState == AITrain.AI_MOVEMENT_STATE.HANDLE_ACTION) || (nextActionInfo is AuxActionWPItem && - MovementState == AITrain.AI_MOVEMENT_STATE.HANDLE_ACTION))) + else { - MovementState = AI_MOVEMENT_STATE.HANDLE_ACTION; + MovementState = this != Simulator.OriginalPlayerTrain && AtStation + ? AI_MOVEMENT_STATE.STATION_STOP + : Math.Abs(SpeedMpS) <= 0.1f && ((AuxActionsContain.SpecAuxActions.Count > 0 && AuxActionsContain.SpecAuxActions[0] is AIActionWPRef && (AuxActionsContain.SpecAuxActions[0] as AIActionWPRef).keepIt != null && + (AuxActionsContain.SpecAuxActions[0] as AIActionWPRef).keepIt.currentMvmtState == AITrain.AI_MOVEMENT_STATE.HANDLE_ACTION) || (nextActionInfo is AuxActionWPItem && + MovementState == AITrain.AI_MOVEMENT_STATE.HANDLE_ACTION)) + ? AI_MOVEMENT_STATE.HANDLE_ACTION + : AI_MOVEMENT_STATE.STOPPED; } - else MovementState = AI_MOVEMENT_STATE.STOPPED; success = true; return success; } @@ -6553,14 +6379,14 @@ String showActionInfo(Train.DistanceTravelledItem action) /// public override void CheckStationTask() { - // if at station + // If at station if (AtStation) { int presentTime = Convert.ToInt32(Math.Floor(Simulator.ClockTime)); int eightHundredHours = 8 * 3600; int sixteenHundredHours = 16 * 3600; - // if moving, set departed + // If moving, set departed if (Math.Abs(SpeedMpS) > 0) { if (TrainType != TRAINTYPE.AI_PLAYERHOSTING) @@ -6577,7 +6403,6 @@ public override void CheckStationTask() } else { - { int remaining; if (StationStops.Count == 0) @@ -6590,28 +6415,17 @@ public override void CheckStationTask() int correctedTime = presentTime; if (presentTime > sixteenHundredHours && StationStops[0].DepartTime < eightHundredHours) { - correctedTime = presentTime - 24 * 3600; // correct to time before midnight (negative value!) + correctedTime = presentTime - (24 * 3600); // Correct to time before midnight (negative value!) } remaining = actualDepart - correctedTime; } - // set display text color - if (remaining < 1) - { - DisplayColor = Color.LightGreen; - } - else if (remaining < 11) - { - DisplayColor = new Color(255, 255, 128); - } - else - { - DisplayColor = Color.White; - } + // Set display text color + DisplayColor = remaining < 1 ? Color.LightGreen : remaining < 11 ? new Color(255, 255, 128) : Color.White; - // clear holding signal - if (remaining < (IsActualPlayerTrain ? 120 : 2) && remaining > 0 && StationStops[0].ExitSignal >= 0) // within two minutes of departure and hold signal? + // Clear holding signal + if (remaining < (IsActualPlayerTrain ? 120 : 2) && remaining > 0 && StationStops[0].ExitSignal >= 0) // Within two minutes of departure and hold signal? { HoldingSignals.Remove(StationStops[0].ExitSignal); @@ -6623,14 +6437,14 @@ public override void CheckStationTask() StationStops[0].ExitSignal = -1; } - // check departure time + // Check departure time if (remaining <= 0) { if (!MayDepart) { float distanceToNextSignal = -1; if (NextSignalObject[0] != null) distanceToNextSignal = NextSignalObject[0].DistanceTo(FrontTDBTraveller); - // check if signal ahead is cleared - if not, do not allow depart + // Check if signal ahead is cleared - if not, do not allow depart if (NextSignalObject[0] != null && distanceToNextSignal >= 0 && distanceToNextSignal < 300 && NextSignalObject[0].this_sig_lr(MstsSignalFunction.NORMAL) == MstsSignalAspect.STOP && NextSignalObject[0].hasPermission != SignalObject.Permission.Granted) @@ -6655,14 +6469,14 @@ public override void CheckStationTask() } else { - // if stations to be checked + // If stations to be checked if (StationStops.Count > 0) { - // check if stopped at station + // Check if stopped at station if (Math.Abs(SpeedMpS) == 0.0f) { AtStation = IsAtPlatform(); - if (AtStation) + if (AtStation) { int presentTime = Convert.ToInt32(Math.Floor(Simulator.ClockTime)); StationStops[0].ActualArrival = presentTime; @@ -6671,7 +6485,7 @@ public override void CheckStationTask() } else if (ControlMode == TRAIN_CONTROL.AUTO_NODE || ControlMode == TRAIN_CONTROL.AUTO_SIGNAL) { - // check if station missed : station must be at least 250m. behind us + // Check if station missed : station must be at least 250m. behind us bool missedStation = IsMissedPlatform(250); if (missedStation) @@ -6694,18 +6508,18 @@ public void RestartWaitingTrain(RestartWaitingTrain restartWaitingTrain) int presentTime = Convert.ToInt32(Math.Floor(Simulator.ClockTime)); var roughActualDepart = presentTime + delayToRestart; if (MovementState == AITrain.AI_MOVEMENT_STATE.HANDLE_ACTION && (((nextActionInfo as AuxActionWPItem).ActionRef as AIActionWPRef).OriginalDelay == matchingWPDelay || - (AuxActionsContain.specRequiredActions.Count > 0 && ((AuxActSigDelegate)(AuxActionsContain.specRequiredActions).First.Value).currentMvmtState == AITrain.AI_MOVEMENT_STATE.HANDLE_ACTION && - (((AuxActSigDelegate)(AuxActionsContain.specRequiredActions).First.Value).ActionRef as AIActSigDelegateRef).Delay == matchingWPDelay))) + (AuxActionsContain.specRequiredActions.Count > 0 && ((AuxActSigDelegate)AuxActionsContain.specRequiredActions.First.Value).currentMvmtState == AITrain.AI_MOVEMENT_STATE.HANDLE_ACTION && + (((AuxActSigDelegate)AuxActionsContain.specRequiredActions.First.Value).ActionRef as AIActSigDelegateRef).Delay == matchingWPDelay))) { if (((nextActionInfo as AuxActionWPItem).ActionRef as AIActionWPRef).Delay >= 30000 && ((nextActionInfo as AuxActionWPItem).ActionRef as AIActionWPRef).Delay < 32400) - // absolute WP, use minutes as unit of measure { - (nextActionInfo as AuxActionWPItem).ActualDepart = (roughActualDepart / 60) * 60 + (roughActualDepart % 60 == 0 ? 0 : 60); - // compute hrs and minutes + // Absolute WP, use minutes as unit of measure + (nextActionInfo as AuxActionWPItem).ActualDepart = (roughActualDepart / 60 * 60) + (roughActualDepart % 60 == 0 ? 0 : 60); + // Compute hrs and minutes var hrs = (nextActionInfo as AuxActionWPItem).ActualDepart / 3600; - var minutes = ((nextActionInfo as AuxActionWPItem).ActualDepart - hrs * 3600) / 60; - ((nextActionInfo as AuxActionWPItem).ActionRef as AIActionWPRef).Delay = 30000 + minutes + hrs * 100; - (nextActionInfo as AuxActionWPItem).SetDelay(30000 + minutes + hrs * 100); + var minutes = ((nextActionInfo as AuxActionWPItem).ActualDepart - (hrs * 3600)) / 60; + ((nextActionInfo as AuxActionWPItem).ActionRef as AIActionWPRef).Delay = 30000 + minutes + (hrs * 100); + (nextActionInfo as AuxActionWPItem).SetDelay(30000 + minutes + (hrs * 100)); } else { @@ -6714,11 +6528,11 @@ public void RestartWaitingTrain(RestartWaitingTrain restartWaitingTrain) (nextActionInfo as AuxActionWPItem).SetDelay(delayToRestart); } if (((nextActionInfo as AuxActionWPItem).ActionRef as AIActionWPRef).LinkedAuxAction) - // also a signal is connected with this WP { + // Also a signal is connected with this WP if (AuxActionsContain.specRequiredActions.Count > 0 && AuxActionsContain.specRequiredActions.First.Value is AuxActSigDelegate) - // if should be true only for absolute WPs, where the linked aux action is started in parallel { + // If should be true only for absolute WPs, where the linked aux action is started in parallel (AuxActionsContain.specRequiredActions.First.Value as AuxActSigDelegate).ActualDepart = (nextActionInfo as AuxActionWPItem).ActualDepart; ((AuxActionsContain.specRequiredActions.First.Value as AuxActSigDelegate).ActionRef as AIActSigDelegateRef).Delay = ((nextActionInfo as AuxActionWPItem).ActionRef as AIActionWPRef).Delay; } @@ -6729,17 +6543,17 @@ public void RestartWaitingTrain(RestartWaitingTrain restartWaitingTrain) { var actualDepart = 0; var delay = 0; - // not yet at WP + // Not yet at WP if (((nextActionInfo as AuxActionWPItem).ActionRef as AIActionWPRef).Delay >= 30000 && ((nextActionInfo as AuxActionWPItem).ActionRef as AIActionWPRef).Delay < 32400) { - // compute hrs and minutes + // Compute hrs and minutes var hrs = roughActualDepart / 3600; - var minutes = (roughActualDepart - hrs * 3600) / 60; - ((nextActionInfo as AuxActionWPItem).ActionRef as AIActionWPRef).Delay = 30000 + minutes + hrs * 100; - (nextActionInfo as AuxActionWPItem).SetDelay(30000 + minutes + hrs * 100); + var minutes = (roughActualDepart - (hrs * 3600)) / 60; + ((nextActionInfo as AuxActionWPItem).ActionRef as AIActionWPRef).Delay = 30000 + minutes + (hrs * 100); + (nextActionInfo as AuxActionWPItem).SetDelay(30000 + minutes + (hrs * 100)); if (AuxActionsContain.SpecAuxActions.Count > 0 && AuxActionsContain.SpecAuxActions[0] is AIActionWPRef) - (AuxActionsContain.SpecAuxActions[0] as AIActionWPRef).Delay = 30000 + minutes + hrs * 100; - actualDepart = (roughActualDepart / 60) * 60 + (roughActualDepart % 60 == 0 ? 0 : 60); + (AuxActionsContain.SpecAuxActions[0] as AIActionWPRef).Delay = 30000 + minutes + (hrs * 100); + actualDepart = (roughActualDepart / 60 * 60) + (roughActualDepart % 60 == 0 ? 0 : 60); delay = ((nextActionInfo as AuxActionWPItem).ActionRef as AIActionWPRef).Delay; } else @@ -6750,11 +6564,11 @@ public void RestartWaitingTrain(RestartWaitingTrain restartWaitingTrain) delay = 1; } if (((nextActionInfo as AuxActionWPItem).ActionRef as AIActionWPRef).LinkedAuxAction) - // also a signal is connected with this WP { + // Also a signal is connected with this WP if (AuxActionsContain.specRequiredActions.Count > 0 && AuxActionsContain.specRequiredActions.First.Value is AuxActSigDelegate) - // if should be true only for absolute WPs, where the linked aux action is started in parallel { + // If should be true only for absolute WPs, where the linked aux action is started in parallel (AuxActionsContain.specRequiredActions.First.Value as AuxActSigDelegate).ActualDepart = actualDepart; ((AuxActionsContain.specRequiredActions.First.Value as AuxActSigDelegate).ActionRef as AIActSigDelegateRef).Delay = ((nextActionInfo as AuxActionWPItem).ActionRef as AIActionWPRef).Delay; } @@ -6813,13 +6627,9 @@ public static AILevelCrossingHornPattern CreateInstance(LevelCrossingHornPattern /// public void Save(BinaryWriter outf) { - LevelCrossingHornPattern type; - if (this is AILevelCrossingSingleHorn) - type = LevelCrossingHornPattern.Single; - else if (this is AILevelCrossingAmericanHorn) - type = LevelCrossingHornPattern.US; - else - throw new ArgumentException(); + var type = this is AILevelCrossingSingleHorn + ? LevelCrossingHornPattern.Single + : this is AILevelCrossingAmericanHorn ? LevelCrossingHornPattern.US : throw new ArgumentException(); outf.Write((int)type); } @@ -6849,7 +6659,7 @@ public override IEnumerator Execute(MSTSLocomotive locomotive, int? duratio if (!durationS.HasValue) { // Sound the horn for a pseudorandom period of seconds between 2 and 5. - durationS = (DateTime.Now.Millisecond % 10) / 3 + 2; + durationS = (DateTime.Now.Millisecond % 10 / 3) + 2; } locomotive.ManualHorn = true; @@ -6865,7 +6675,6 @@ public override IEnumerator Execute(MSTSLocomotive locomotive, int? duratio } } - /// /// Sound the long-long-short-long pattern used in the United States and Canada, and stop the bell after 30 seconds if triggered. /// @@ -6913,13 +6722,10 @@ public override IEnumerator Execute(MSTSLocomotive locomotive, int? duratio } } - //================================================================================================// /// /// AIActionItem class : class to hold info on next restrictive action /// - - public class AIActionItem : Train.DistanceTravelledItem { public float RequiredSpeedMpS; @@ -6948,9 +6754,8 @@ public enum AI_ACTION_TYPE //================================================================================================// /// - /// constructor for AIActionItem + /// Constructor for AIActionItem /// - public AIActionItem(ObjectItemInfo thisItem, AI_ACTION_TYPE thisAction) { ActiveItem = thisItem; @@ -6965,12 +6770,10 @@ public void SetParam(float requiredDistance, float requiredSpeedMpS, float activ InsertedDistanceM = insertedDistanceM; } - //================================================================================================// // // Restore // - public AIActionItem(BinaryReader inf, Signals signalRef) { RequiredDistance = inf.ReadSingle(); @@ -6991,11 +6794,11 @@ public AIActionItem(BinaryReader inf, Signals signalRef) public static ObjectItemInfo RestoreActiveItem(BinaryReader inf, Signals signalRef) { - - ObjectItemInfo thisInfo = new ObjectItemInfo(ObjectItemInfo.ObjectItemFindState.None); - - thisInfo.ObjectType = (ObjectItemInfo.ObjectItemType)inf.ReadInt32(); - thisInfo.ObjectState = (ObjectItemInfo.ObjectItemFindState)inf.ReadInt32(); + ObjectItemInfo thisInfo = new ObjectItemInfo(ObjectItemInfo.ObjectItemFindState.None) + { + ObjectType = (ObjectItemInfo.ObjectItemType)inf.ReadInt32(), + ObjectState = (ObjectItemInfo.ObjectItemFindState)inf.ReadInt32() + }; int signalIndex = inf.ReadInt32(); thisInfo.ObjectDetails = signalRef.SignalObjects[signalIndex]; @@ -7017,14 +6820,13 @@ public static ObjectItemInfo RestoreActiveItem(BinaryReader inf, Signals signalR thisInfo.signal_state = thisInfo.ObjectDetails.this_sig_lr(MstsSignalFunction.NORMAL); } - return (thisInfo); + return thisInfo; } //================================================================================================// // // Save // - public void SaveItem(BinaryWriter outf) { outf.Write(RequiredSpeedMpS); @@ -7066,7 +6868,7 @@ public static void SaveActiveItem(BinaryWriter outf, ObjectItemInfo ActiveItem) //================================================================================================// // - // Generic Handler for all derived class + // Generic Handler for all derived class // public virtual bool ValidAction(Train thisTrain) { diff --git a/Source/Orts.Simulation/Simulation/Timetables/PoolInfo.cs b/Source/Orts.Simulation/Simulation/Timetables/PoolInfo.cs index af5bea4184..7f1233d93d 100644 --- a/Source/Orts.Simulation/Simulation/Timetables/PoolInfo.cs +++ b/Source/Orts.Simulation/Simulation/Timetables/PoolInfo.cs @@ -1,4 +1,4 @@ -// COPYRIGHT 2014 by the Open Rails project. +// COPYRIGHT 2014 by the Open Rails project. // // This file is part of Open Rails. // @@ -15,8 +15,7 @@ // You should have received a copy of the GNU General Public License // along with Open Rails. If not, see . -// This code processes the Timetable definition and converts it into playable train information -// +/* This code processes the Timetable definition and converts it into playable train information */ using System; using System.Collections.Generic; @@ -44,7 +43,6 @@ public PoolInfo(Simulator simulatorref) simulator = simulatorref; } - //================================================================================================// /// /// Read pool files @@ -57,33 +55,33 @@ public PoolInfo(Simulator simulatorref) Dictionary pools = new Dictionary(); List filenames; - // get filenames to process + // Get filenames to process filenames = GetFilenames(arguments[0]); - // get file contents as strings + // Get file contents as strings Trace.Write("\n"); foreach (string filePath in filenames) { - // get contents as strings + // Get contents as strings Trace.Write("Pool File : " + filePath + "\n"); var poolInfo = new TimetableReader(filePath); - // read lines from input until 'Name' definition is found + // Read lines from input until 'Name' definition is found int lineindex = 1; while (lineindex < poolInfo.Strings.Count) { switch (poolInfo.Strings[lineindex][0].ToLower().Trim()) { - // skip comment - case "#comment" : + // Skip comment + case "#comment": lineindex++; break; - - // process name - // do not increase lineindex as that is done in called method - case "#name" : + + // Process name + // Do not increase lineindex as that is done in called method + case "#name": TimetablePool newPool = new TimetablePool(poolInfo, ref lineindex, simulator); - // store if valid pool + // Store if valid pool if (!String.IsNullOrEmpty(newPool.PoolName)) { if (pools.ContainsKey(newPool.PoolName)) @@ -96,8 +94,7 @@ public PoolInfo(Simulator simulatorref) } } break; - - default : + default: if (!String.IsNullOrEmpty(poolInfo.Strings[lineindex][0])) { Trace.TraceInformation("Invalid definition in file " + filePath + " at line " + lineindex + " : " + @@ -109,7 +106,7 @@ public PoolInfo(Simulator simulatorref) } } - return (pools); + return pools; } //================================================================================================// @@ -122,7 +119,7 @@ private List GetFilenames(string filePath) { List filenames = new List(); - // check type of timetable file - list or single + // Check type of timetable file - list or single string fileDirectory = Path.GetDirectoryName(filePath); foreach (var ORPoolFile in Directory.GetFiles(fileDirectory, "*.pool_or")) @@ -134,9 +131,8 @@ private List GetFilenames(string filePath) filenames.Add(ORPoolFile); } - return (filenames); + return filenames; } - } } diff --git a/Source/Orts.Simulation/Simulation/Timetables/ProcessTimetable.cs b/Source/Orts.Simulation/Simulation/Timetables/ProcessTimetable.cs index 3151d24f6f..14b6be1139 100644 --- a/Source/Orts.Simulation/Simulation/Timetables/ProcessTimetable.cs +++ b/Source/Orts.Simulation/Simulation/Timetables/ProcessTimetable.cs @@ -23,8 +23,11 @@ // #define DEBUG_TIMETABLE // #define DEBUG_TRACEINFO -// - +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; using Orts.Formats.Msts; using Orts.Formats.OR; using Orts.Parsers.OR; @@ -34,18 +37,13 @@ using Orts.Simulation.RollingStocks.SubSystems; using Orts.Simulation.Signalling; using ORTS.Common; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; using Event = Orts.Common.Event; namespace Orts.Simulation.Timetables { public class TimetableInfo { - private Simulator simulator; + private readonly Simulator simulator; private enum columnType { @@ -75,9 +73,9 @@ private enum rowType invalid, } - Dictionary Paths = new Dictionary(); // original path referenced by path name - List reportedPaths = new List(); // reported path fails - Dictionary TrainRouteXRef = new Dictionary(); // path name referenced from train index + Dictionary Paths = new Dictionary(); // Original path referenced by path name + readonly List reportedPaths = new List(); // Reported path fails + readonly Dictionary TrainRouteXRef = new Dictionary(); // Path name referenced from train index public bool BinaryPaths = false; @@ -110,14 +108,14 @@ public List ProcessTimetable(string[] arguments, CancellationToken canc List filenames; int indexcount = 0; - // get filenames to process + // Get filenames to process filenames = GetFilenames(arguments[0]); - // get file contents as strings + // Get file contents as strings Trace.Write("\n"); foreach (string filePath in filenames) { - // get contents as strings + // Get contents as strings Trace.Write("TT File : " + filePath + "\n"); var fileContents = new TimetableReader(filePath); @@ -125,19 +123,16 @@ public List ProcessTimetable(string[] arguments, CancellationToken canc File.AppendAllText(@"C:\temp\timetableproc.txt", "\nProcessing file : " + filePath + "\n"); #endif - // convert to train info + // Convert to train info indexcount = ConvertFileContents(fileContents, simulator.Signals, ref trainInfoList, indexcount, filePath); } - // read and pre-process routes - + // Read and pre-process routes Trace.Write(" TTROUTES:" + Paths.Count.ToString() + " "); - loadPathNoFailure = PreProcessRoutes(cancellation); - Trace.Write(" TTTRAINS:" + trainInfoList.Count.ToString() + " "); - // get startinfo for player train + // Get startinfo for player train playerTrain = GetPlayerTrain(ref trainInfoList, arguments); // pre-init player train to abstract alternative paths if set @@ -146,12 +141,12 @@ public List ProcessTimetable(string[] arguments, CancellationToken canc PreInitPlayerTrain(playerTrain); } - // reduce trainlist using player train info and parameters + // Reduce trainlist using player train info and parameters bool addPathNoLoadFailure; trainList = BuildAITrains(cancellation, trainInfoList, playerTrain, arguments, out addPathNoLoadFailure); if (!addPathNoLoadFailure) loadPathNoFailure = false; - // set references (required to process commands) + // Set references (required to process commands) foreach (Train thisTrain in trainList) { if (simulator.NameDictionary.ContainsKey(thisTrain.Name.ToLower())) @@ -165,7 +160,7 @@ public List ProcessTimetable(string[] arguments, CancellationToken canc } } - // set player train + // Set player train reqPlayerTrain = null; if (playerTrain != null) { @@ -174,13 +169,13 @@ public List ProcessTimetable(string[] arguments, CancellationToken canc addPathNoLoadFailure = playerTrain.ProcessDisposeInfo(ref trainList, null, simulator); if (!addPathNoLoadFailure) loadPathNoFailure = false; } - PlayerTrainOriginalStartTime = playerTrain.StartTime; // Saved here for use after playerTrain.StartTime gets changed. + PlayerTrainOriginalStartTime = playerTrain.StartTime; // Saved here for use after `playerTrain.StartTime` gets changed. reqPlayerTrain = InitializePlayerTrain(playerTrain, ref Paths, ref trainList); simulator.TrainDictionary.Add(reqPlayerTrain.Number, reqPlayerTrain); simulator.NameDictionary.Add(reqPlayerTrain.Name.ToLower(), reqPlayerTrain); } - // process additional commands for all extracted trains + // Process additional commands for all extracted trains reqPlayerTrain.FinalizeTimetableCommands(); reqPlayerTrain.StationStops.Sort(); @@ -189,13 +184,13 @@ public List ProcessTimetable(string[] arguments, CancellationToken canc thisTrain.FinalizeTimetableCommands(); thisTrain.StationStops.Sort(); - // finalize attach details + // Finalize attach details if (thisTrain.AttachDetails != null && thisTrain.AttachDetails.Valid) { thisTrain.AttachDetails.FinalizeAttachDetails(thisTrain, trainList, playerTrain.TTTrain); } - // finalize pickup details + // Finalize pickup details if (thisTrain.PickUpDetails != null && thisTrain.PickUpDetails.Count > 0) { foreach (PickUpInfo thisPickUp in thisTrain.PickUpDetails) @@ -205,7 +200,7 @@ public List ProcessTimetable(string[] arguments, CancellationToken canc thisTrain.PickUpDetails.Clear(); } - // finalize transfer details + // Finalize transfer details if (thisTrain.TransferStationDetails != null && thisTrain.TransferStationDetails.Count > 0) { foreach (KeyValuePair thisTransferStation in thisTrain.TransferStationDetails) @@ -228,8 +223,10 @@ public List ProcessTimetable(string[] arguments, CancellationToken canc } else { - List thisTransferList = new List(); - thisTransferList.Add(thisTransfer); + List thisTransferList = new List + { + thisTransfer + }; thisTrain.TransferTrainDetails.Add(thisTransfer.TransferTrain, thisTransferList); } } @@ -239,10 +236,10 @@ public List ProcessTimetable(string[] arguments, CancellationToken canc } } - // process activation commands for all trains + // Process activation commands for all trains FinalizeActivationCommands(ref trainList, ref reqPlayerTrain); - // set timetable identification for simulator for saves etc. + // Set timetable identification for simulator for saves etc. simulator.TimetableFileName = Path.GetFileNameWithoutExtension(arguments[0]); if (!loadPathNoFailure) @@ -250,7 +247,7 @@ public List ProcessTimetable(string[] arguments, CancellationToken canc Trace.TraceError("Load path failures"); } - // check on engine in player train + // Check on engine in player train if (simulator.PlayerLocomotive == null) { if (reqPlayerTrain.NeedAttach != null && reqPlayerTrain.NeedAttach.Count > 0) @@ -268,7 +265,7 @@ public List ProcessTimetable(string[] arguments, CancellationToken canc } trainList.Insert(0, reqPlayerTrain); - return (trainList); + return trainList; } //================================================================================================// @@ -281,7 +278,7 @@ private List GetFilenames(string filePath) { List filenames = new List(); - // check type of timetable file - list or single + // Check type of timetable file - list or single string fileExtension = Path.GetExtension(filePath); string fileDirectory = Path.GetDirectoryName(filePath); @@ -314,7 +311,7 @@ private List GetFilenames(string filePath) File.AppendAllText(@"C:\temp\timetableproc.txt", ttfile + "\n"); } #endif - return (filenames); + return filenames; } //================================================================================================// @@ -336,28 +333,27 @@ private int ConvertFileContents(TimetableReader fileContents, Signals signalRef, int firstCommentRow = -1; int firstCommentColumn = -1; - Dictionary trainHeaders = new Dictionary(); // key int = column no, value string = train header - Dictionary trainInfo = new Dictionary(); // key int = column no, value = train info class - Dictionary addTrainInfo = new Dictionary(); // key int = column no, value int = main train column - Dictionary> addTrainColumns = new Dictionary>(); // key int = main train column, value = add columns - Dictionary stationNames = new Dictionary(); // key int = row no, value string = station name + Dictionary trainHeaders = new Dictionary(); // Key int = column no, value string = train header + Dictionary trainInfo = new Dictionary(); // Key int = column no, value = train info class + Dictionary addTrainInfo = new Dictionary(); // Key int = column no, value int = main train column + Dictionary> addTrainColumns = new Dictionary>(); // Key int = main train column, value = add columns + Dictionary stationNames = new Dictionary(); // Key int = row no, value string = station name - float actSpeedConv = 1.0f; // actual set speedconversion + float actSpeedConv = 1.0f; // Actual set speedconversion rowType[] RowInfo = new rowType[fileContents.Strings.Count]; columnType[] ColInfo = new columnType[fileContents.Strings[0].Length]; - // process first row separately - + // Process first row separately ColInfo[0] = columnType.stationInfo; for (int iColumn = 1; iColumn <= fileContents.Strings[0].Length - 1; iColumn++) { string columnDef = fileContents.Strings[0][iColumn]; - // empty : continuation column if (String.IsNullOrEmpty(columnDef)) { + // Empty: continuation column switch (ColInfo[iColumn - 1]) { case columnType.stationInfo: @@ -380,24 +376,22 @@ private int ConvertFileContents(TimetableReader fileContents, Signals signalRef, break; } } - - // comment else if (String.Compare(columnDef, "#comment", true) == 0) { + // Comment ColInfo[iColumn] = columnType.comment; if (firstCommentColumn < 0) firstCommentColumn = iColumn; } - // oheck for invalid command definition else if (columnDef.Substring(0, 1).Equals("#")) { + // Check for invalid command definition Trace.TraceWarning("Invalid column definition in {0} : column {1} : {2}", filePath, iColumn, columnDef); ColInfo[iColumn] = columnType.invalid; } - - // otherwise it is a train definition else { + // Otherwise it is a train definition ColInfo[iColumn] = columnType.trainDefinition; trainHeaders.Add(iColumn, String.Copy(columnDef)); trainInfo.Add(iColumn, new TTTrainInfo(iColumn, columnDef, simulator, indexcount, this)); @@ -405,7 +399,7 @@ private int ConvertFileContents(TimetableReader fileContents, Signals signalRef, } } - // get row information + // Get row information RowInfo[0] = rowType.trainInfo; for (int iRow = 1; iRow <= fileContents.Strings.Count - 1; iRow++) @@ -420,25 +414,23 @@ private int ConvertFileContents(TimetableReader fileContents, Signals signalRef, rowDef = rowCommands[0].Trim().ToLower(); } - // emtpy : continuation if (String.IsNullOrEmpty(rowDef)) { + // Emtpy: continuation switch (RowInfo[iRow - 1]) { case rowType.stationInfo: RowInfo[iRow] = rowType.addStationInfo; break; - default: // continuation of other types not allowed, treat line as comment + default: // Continuation of other types not allowed, treat line as comment RowInfo[iRow] = rowType.comment; break; } } - - // switch on actual string - else { + // switch on actual string switch (rowDef) { case "#consist": @@ -588,7 +580,7 @@ private int ConvertFileContents(TimetableReader fileContents, Signals signalRef, bool validFile = true; - // check if all required row definitions are available + // Check if all required row definitions are available if (consistRow < 0) { Trace.TraceWarning("File : {0} - Consist definition row missing, file cannot be processed", filePath); @@ -607,15 +599,13 @@ private int ConvertFileContents(TimetableReader fileContents, Signals signalRef, validFile = false; } - if (!validFile) return (indexcount); // abandone processing - - // extract description + if (!validFile) return indexcount; // Abandon processing + // Extract description string description = (firstCommentRow >= 0 && firstCommentColumn >= 0) ? fileContents.Strings[firstCommentRow][firstCommentColumn] : Path.GetFileNameWithoutExtension(fileContents.FilePath); - // extract additional station info - + // Extract additional station info for (int iRow = 1; iRow <= fileContents.Strings.Count - 1; iRow++) { if (RowInfo[iRow] == rowType.stationInfo) @@ -632,8 +622,7 @@ private int ConvertFileContents(TimetableReader fileContents, Signals signalRef, } } - // build list of additional train columns - + // Build list of additional train columns foreach (KeyValuePair addColumn in addTrainInfo) { if (addTrainColumns.ContainsKey(addColumn.Value)) @@ -642,14 +631,15 @@ private int ConvertFileContents(TimetableReader fileContents, Signals signalRef, } else { - List addTrainColumn = new List(); - addTrainColumn.Add(addColumn.Key); + List addTrainColumn = new List + { + addColumn.Key + }; addTrainColumns.Add(addColumn.Value, addTrainColumn); } } - // build actual trains - + // Build actual trains bool allCorrectBuild = true; for (int iColumn = 1; iColumn <= ColInfo.Length - 1; iColumn++) @@ -676,7 +666,7 @@ private int ConvertFileContents(TimetableReader fileContents, Signals signalRef, Trace.TraceError("Failed to build trains"); } - // extract valid trains + // Extract valid trains foreach (KeyValuePair train in trainInfo) { if (train.Value.validTrain) @@ -685,7 +675,7 @@ private int ConvertFileContents(TimetableReader fileContents, Signals signalRef, } } - return (indexcount); + return indexcount; } //================================================================================================// @@ -746,7 +736,7 @@ private TTTrainInfo GetPlayerTrain(ref List allTrains, string[] arg throw new InvalidDataException("Player train : " + arguments[1] + " not found in timetables"); } - return (reqTrain); + return reqTrain; } //================================================================================================// @@ -763,34 +753,34 @@ private List BuildAITrains(CancellationToken cancellation, List 0) { reqTrain.ProcessCommands(simulator, reqTrain.TTTrain); } - // add AI train to output list + // Add AI train to output list trainList.Add(reqTrain.TTTrain); } } - // process dispose commands + // Process dispose commands foreach (TTTrainInfo reqTrain in allTrains) { if (reqTrain.DisposeDetails != null) @@ -799,11 +789,11 @@ private List BuildAITrains(CancellationToken cancellation, List BuildAITrains(CancellationToken cancellation, List BuildAITrains(CancellationToken cancellation, List private void PreInitPlayerTrain(TTTrainInfo reqTrain) { - // set player train idents + // Set player train idents TTTrain playerTrain = reqTrain.TTTrain; reqTrain.playerTrain = true; @@ -851,14 +841,14 @@ private void PreInitPlayerTrain(TTTrainInfo reqTrain) playerTrain.ControlMode = Train.TRAIN_CONTROL.INACTIVE; playerTrain.MovementState = AITrain.AI_MOVEMENT_STATE.AI_STATIC; - // define style of passing path + // Define style of passing path simulator.Signals.UseLocationPassingPaths = true; - // create traveller + // Create traveller AIPath usedPath = Paths[TrainRouteXRef[reqTrain.Index]]; playerTrain.RearTDBTraveller = new Traveller(simulator.TSectionDat, simulator.TDB.TrackDB.TrackNodes, usedPath); - // extract train path + // Extract train path playerTrain.SetRoutePath(usedPath, simulator.Signals); playerTrain.EndRouteAtLastSignal(); playerTrain.ValidRoute[0] = new Train.TCSubpathRoute(playerTrain.TCRoute.TCRouteSubpaths[0]); @@ -871,12 +861,12 @@ private void PreInitPlayerTrain(TTTrainInfo reqTrain) /// private TTTrain InitializePlayerTrain(TTTrainInfo reqTrain, ref Dictionary paths, ref List trainList) { - // set player train idents + // Set player train idents TTTrain playerTrain = reqTrain.TTTrain; simulator.Trains.Add(playerTrain); - // reset train for each car + // Reset train for each car int icar = 1; foreach (TrainCar car in playerTrain.Cars) @@ -886,8 +876,8 @@ private TTTrain InitializePlayerTrain(TTTrainInfo reqTrain, ref Dictionary 0) { reqTrain.ProcessCommands(simulator, reqTrain.TTTrain); } - - // set detach cross-references + // Set detach cross-references foreach (KeyValuePair> thisDetachInfo in reqTrain.TTTrain.DetachDetails) { int detachCount = 0; @@ -953,14 +942,13 @@ private TTTrain InitializePlayerTrain(TTTrainInfo reqTrain, ref Dictionary 0) { foreach (PickUpInfo thisPickUp in reqTrain.TTTrain.PickUpDetails) @@ -970,7 +958,7 @@ private TTTrain InitializePlayerTrain(TTTrainInfo reqTrain, ref Dictionary 0) { foreach (KeyValuePair thisTransferStation in reqTrain.TTTrain.TransferStationDetails) @@ -993,8 +981,10 @@ private TTTrain InitializePlayerTrain(TTTrainInfo reqTrain, ref Dictionary thisTransferList = new List(); - thisTransferList.Add(thisTransfer); + List thisTransferList = new List + { + thisTransfer + }; reqTrain.TTTrain.TransferTrainDetails.Add(thisTransfer.TransferTrain, thisTransferList); } } @@ -1002,11 +992,11 @@ private TTTrain InitializePlayerTrain(TTTrainInfo reqTrain, ref Dictionary /// Finalize activation commands /// - public void FinalizeActivationCommands(ref List trainList, ref TTTrain reqPlayerTrain) { List activatedTrains = new List(); - // build list of trains to be activated - // set original AI number for player train + // Build list of trains to be activated + // Set original AI number for player train foreach (TTTrain thisTrain in trainList) { if (thisTrain.TriggeredActivationRequired) @@ -1041,7 +1030,7 @@ public void FinalizeActivationCommands(ref List trainList, ref TTTrain activatedTrains.Add(reqPlayerTrain.OrgAINumber); } - // process all activation commands + // Process all activation commands foreach (TTTrain thisTrain in trainList) { if (thisTrain.activatedTrainTriggers != null && thisTrain.activatedTrainTriggers.Count > 0) @@ -1080,7 +1069,7 @@ public void FinalizeActivationCommands(ref List trainList, ref TTTrain } } - // process activation request for player train + // Process activation request for player train if (reqPlayerTrain.activatedTrainTriggers != null && reqPlayerTrain.activatedTrainTriggers.Count > 0) { for (int itrigger = reqPlayerTrain.activatedTrainTriggers.Count - 1; itrigger >= 0; itrigger--) @@ -1116,7 +1105,7 @@ public void FinalizeActivationCommands(ref List trainList, ref TTTrain } } - // check if any activated trains remain untriggered + // Check if any activated trains remain untriggered foreach (int inumber in activatedTrains) { TTTrain otherTrain = trainList[0].GetOtherTTTrainByNumber(inumber); @@ -1132,7 +1121,7 @@ public void FinalizeActivationCommands(ref List trainList, ref TTTrain public bool PreProcessRoutes(CancellationToken cancellation) { - // extract names + // Extract names List routeNames = new List(); foreach (KeyValuePair thisRoute in Paths) @@ -1140,22 +1129,22 @@ public bool PreProcessRoutes(CancellationToken cancellation) routeNames.Add(thisRoute.Key); } - // clear routes - will be refilled + // Clear routes - will be refilled Paths.Clear(); bool allPathsLoaded = true; - // create routes + // Create routes foreach (string thisRoute in routeNames) { - // read route + // Read route bool pathValid = true; LoadPath(thisRoute, out pathValid); if (!pathValid) allPathsLoaded = false; if (cancellation.IsCancellationRequested) - return (false); + return false; } - return (allPathsLoaded); + return allPathsLoaded; } //================================================================================================// @@ -1178,7 +1167,7 @@ public AIPath LoadPath(string pathstring, out bool validPath) if (!Paths.TryGetValue(formedpathFilefull, out var outPath)) { - // try to load binary path if required + // Try to load binary path if required bool binaryloaded = false; var formedpathFilefullBinary = simulator.Settings.GetCacheFilePath("Path", formedpathFilefull); @@ -1186,7 +1175,7 @@ public AIPath LoadPath(string pathstring, out bool validPath) { var binaryLastWriteTime = File.GetLastWriteTime(formedpathFilefullBinary); if (binaryLastWriteTime < simulator.TDB.LastWriteTime || - File.Exists(formedpathFilefull) && binaryLastWriteTime < File.GetLastWriteTime(formedpathFilefull)) + (File.Exists(formedpathFilefull) && binaryLastWriteTime < File.GetLastWriteTime(formedpathFilefull))) { File.Delete(formedpathFilefullBinary); } @@ -1264,16 +1253,16 @@ public AIPath LoadPath(string pathstring, out bool validPath) outPath.Save(outfpath); outfpath.Close(); } - // dummy catch to avoid error + // Dummy catch to avoid error catch { } } } - // report path load failure + // Report path load failure } } - return (outPath); + return outPath; } //================================================================================================// @@ -1281,7 +1270,6 @@ public AIPath LoadPath(string pathstring, out bool validPath) /// class TTTrainInfo /// contains extracted train plus additional info for identification and selection /// - private class TTTrainInfo { public TTTrain TTTrain; @@ -1305,7 +1293,6 @@ public struct consistInfo public bool reversed; } - //================================================================================================// /// /// Constructor @@ -1339,9 +1326,8 @@ public TTTrainInfo(int icolumn, string trainName, Simulator simulator, int index { TTDescription = string.Copy(description); - // set name - - // if $static, set starttime row to $static and create unique name + // Set name + // If $static, set starttime row to $static and create unique name if (Name.ToLower().Contains("$static")) { fileStrings[startRow][columnIndex] = String.Copy("$static"); @@ -1365,14 +1351,14 @@ public TTTrainInfo(int icolumn, string trainName, Simulator simulator, int index TTTrain.MovementState = AITrain.AI_MOVEMENT_STATE.AI_STATIC; TTTrain.OrgAINumber = TTTrain.Number; - // derive various directory paths + // Derive various directory paths string pathDirectory = Path.Combine(ttInfo.simulator.RoutePath, "Paths"); - // no path defined : exit + // No path defined: exit if (String.IsNullOrEmpty(fileStrings[pathRow][columnIndex])) { Trace.TraceInformation("Error for train {0} : no path defined", TTTrain.Name); - return (false); + return false; } string pathFilefull = ExtractPathString(pathDirectory, fileStrings[pathRow][columnIndex], ref TTTrain); @@ -1382,43 +1368,42 @@ public TTTrainInfo(int icolumn, string trainName, Simulator simulator, int index string consistdef = fileStrings[consistRow][columnIndex]; - // no consist defined : exit + // No consist defined: exit if (String.IsNullOrEmpty(consistdef)) { Trace.TraceInformation("Error for train {0} : no consist defined", TTTrain.Name); - return (false); + return false; } List consistdetails = ProcessConsistInfo(consistdef); string trainsetDirectory = Path.Combine(trainsDirectory, "trainset"); - // extract path + // EExtract path string pathExtension = Path.GetExtension(pathFilefull); if (String.IsNullOrEmpty(pathExtension)) pathFilefull = Path.ChangeExtension(pathFilefull, "pat"); - ttInfo.TrainRouteXRef.Add(Index, pathFilefull); // set reference to path + ttInfo.TrainRouteXRef.Add(Index, pathFilefull); // Set reference to path if (!ttInfo.Paths.ContainsKey(pathFilefull)) { - ttInfo.Paths.Add(pathFilefull, null); // insert name in dictionary, path will be loaded later + ttInfo.Paths.Add(pathFilefull, null); // Insert name in dictionary, path will be loaded later } - // build consist + // Build consist bool returnValue = true; returnValue = BuildConsist(consistdetails, trainsetDirectory, consistDirectory, ttInfo.simulator); - // return if consist could not be loaded - if (!returnValue) return (returnValue); - - // derive starttime + // Return if consist could not be loaded + if (!returnValue) return returnValue; + // Derive starttime if (validTrain) { string startString = fileStrings[startRow][columnIndex].ToLower().Trim(); ExtractStartTime(startString, consistdetails[0].consistFile, ttInfo.simulator); } - // process dispose info + // Process dispose info if (disposeRow > 0) { string disposeString = fileStrings[disposeRow][columnIndex].ToLower().Trim(); @@ -1467,8 +1452,10 @@ public TTTrainInfo(int icolumn, string trainName, Simulator simulator, int index } else { - List tempList = new List(); - tempList.Add(thisDetach); + List tempList = new List + { + thisDetach + }; TTTrain.DetachDetails.Add(-1, tempList); } break; @@ -1497,8 +1484,10 @@ public TTTrainInfo(int icolumn, string trainName, Simulator simulator, int index else { TransferInfo thisTransfer = new TransferInfo(-1, disposeCommands, TTTrain); - List newList = new List(); - newList.Add(thisTransfer); + List newList = new List + { + thisTransfer + }; if (thisTransfer.TransferTrain == -99) { @@ -1508,7 +1497,7 @@ public TTTrainInfo(int icolumn, string trainName, Simulator simulator, int index { TTTrain.TransferTrainDetails.Add(-1, newList); // set key to -1 to work out reference later } - } + } break; case "activate": @@ -1518,10 +1507,11 @@ public TTTrainInfo(int icolumn, string trainName, Simulator simulator, int index break; } - TTTrain.TriggerActivation thisTrigger = new TTTrain.TriggerActivation(); - - thisTrigger.activationType = TTTrain.TriggerActivationType.Dispose; - thisTrigger.activatedName = disposeCommands.CommandValues[0]; + TTTrain.TriggerActivation thisTrigger = new TTTrain.TriggerActivation + { + activationType = TTTrain.TriggerActivationType.Dispose, + activatedName = disposeCommands.CommandValues[0] + }; TTTrain.activatedTrainTriggers.Add(thisTrigger); break; @@ -1536,13 +1526,12 @@ public TTTrainInfo(int icolumn, string trainName, Simulator simulator, int index } } - // derive station stops and other info - + // Derive station stops and other info for (int iRow = 1; iRow <= fileStrings.Count - 1; iRow++) { switch (RowInfo[iRow]) { - case rowType.directionInfo: // no longer used, maintained for compatibility with existing timetables + case rowType.directionInfo: // No longer used, maintained for compatibility with existing timetables break; case rowType.stationInfo: @@ -1555,7 +1544,7 @@ public TTTrainInfo(int icolumn, string trainName, Simulator simulator, int index } else if (fileStrings[iRow][columnIndex].StartsWith("P")) { - // allowed in timetable but not yet implemented + // Allowed in timetable but not yet implemented } else { @@ -1591,13 +1580,13 @@ public TTTrainInfo(int icolumn, string trainName, Simulator simulator, int index } } - // set speed details based on route, config and input + // Set speed details based on route, config and input TTTrain.ProcessSpeedSettings(); if (briefingRow >= 0) TTTrain.Briefing = fileStrings[briefingRow][columnIndex].Replace("
", "\n"); - return (true); + return true; } //================================================================================================// @@ -1612,7 +1601,7 @@ public string ExtractPathString(string pathDirectory, string pathString, ref TTT { string fullstring = string.Empty; - // process strings + // Process strings string procPathString = pathString.ToLower().Trim(); List pathCommands = new List(); @@ -1627,11 +1616,11 @@ public string ExtractPathString(string pathDirectory, string pathString, ref TTT } } - // actual path is string [0] + // Actual path is string [0] fullstring = Path.Combine(pathDirectory, pathCommandString[0].Trim()); pathCommands.RemoveAt(0); - // process qualifiers + // Process qualifiers foreach (TTTrainCommands thisCommand in pathCommands) { if (!String.IsNullOrEmpty(thisCommand.CommandToken)) @@ -1660,7 +1649,7 @@ public string ExtractPathString(string pathDirectory, string pathString, ref TTT } } - return (fullstring); + return fullstring; } //================================================================================================// @@ -1685,8 +1674,7 @@ public void ExtractStartTime(string startString, string consistInfo, Simulator s bool setConsistName = false; bool activationRequired = false; - // process qualifier if set - + // Process qualifier if set List StartCommands = new List(); if (startString.Contains('$')) @@ -1700,7 +1688,7 @@ public void ExtractStartTime(string startString, string consistInfo, Simulator s } } - // first command is start time except for static + // First command is start time except for static if (!String.Equals(StartCommands[0].CommandToken, "static")) { startTimeString = StartCommands[0].CommandToken; @@ -1713,22 +1701,16 @@ public void ExtractStartTime(string startString, string consistInfo, Simulator s { switch (thisCommand.CommandToken) { - // check for create - syntax : $create [=starttime] [/ahead = train] [/pool = pool] + // Check for create - syntax : $create [=starttime] [/ahead = train] [/pool = pool] case "create": created = true; - // process starttime - if (thisCommand.CommandValues != null && thisCommand.CommandValues.Count > 0) - { - startTimeString = String.Copy(thisCommand.CommandValues[0]); - } - else - // if not set, start at 1 second (same start time as for static so /ahead will work for both create and static) - { - startTimeString = "00:00:01"; - } + // Process starttime + startTimeString = thisCommand.CommandValues != null && thisCommand.CommandValues.Count > 0 + ? String.Copy(thisCommand.CommandValues[0]) + : "00:00:01"; - // check additional qualifiers + // Check additional qualifiers if (thisCommand.CommandQualifiers != null && thisCommand.CommandQualifiers.Count > 0) { foreach (TTTrainCommands.TTTrainComQualifiers thisQualifier in thisCommand.CommandQualifiers) @@ -1749,7 +1731,7 @@ public void ExtractStartTime(string startString, string consistInfo, Simulator s } break; - // pool : created from pool - syntax : $pool = pool [/direction = backward | forward] + // Pool: created from pool - syntax: $pool = pool [/direction = backward | forward] case "pool": if (thisCommand.CommandValues == null || thisCommand.CommandValues.Count < 1) { @@ -1780,16 +1762,16 @@ public void ExtractStartTime(string startString, string consistInfo, Simulator s } break; - // check for $next : set special flag to start after midnight + // Check for $next: set special flag to start after midnight case "next": startNextNight = true; break; - // static : syntax : $static [/ahead = train] + // Static: syntax: $static [/ahead = train] case "static": createStatic = true; - // check additional qualifiers + // Check additional qualifiers if (thisCommand.CommandQualifiers != null && thisCommand.CommandQualifiers.Count > 0) { foreach (TTTrainCommands.TTTrainComQualifiers thisQualifier in thisCommand.CommandQualifiers) @@ -1822,12 +1804,12 @@ public void ExtractStartTime(string startString, string consistInfo, Simulator s } break; - // activated : set activated flag - case "activated" : + // Activated : set activated flag + case "activated": activationRequired = true; break; - // invalid command + // Invalid command default: Trace.TraceInformation("Train : " + Name + " invalid command for start value : " + thisCommand.CommandToken + "\n"); break; @@ -1852,7 +1834,7 @@ public void ExtractStartTime(string startString, string consistInfo, Simulator s TTTrain.Created = created; TTTrain.TriggeredActivationRequired = activationRequired; - // trains starting after midnight + // Trains starting after midnight if (startNextNight && TTTrain.StartTime.HasValue) { TTTrain.StartTime = TTTrain.StartTime.Value + (24 * 3600); @@ -1861,14 +1843,7 @@ public void ExtractStartTime(string startString, string consistInfo, Simulator s if (created && !String.IsNullOrEmpty(createAhead)) { - if (!createAhead.Contains(':')) - { - TTTrain.CreateAhead = createAhead + ":" + TTDescription; - } - else - { - TTTrain.CreateAhead = createAhead; - } + TTTrain.CreateAhead = !createAhead.Contains(':') ? createAhead + ":" + TTDescription : createAhead; TTTrain.CreateAhead = TTTrain.CreateAhead.ToLower(); } @@ -1913,14 +1888,7 @@ public void ExtractStartTime(string startString, string consistInfo, Simulator s if (!String.IsNullOrEmpty(createAhead)) { - if (!createAhead.Contains(':')) - { - TTTrain.CreateAhead = createAhead + ":" + TTDescription; - } - else - { - TTTrain.CreateAhead = createAhead; - } + TTTrain.CreateAhead = !createAhead.Contains(':') ? createAhead + ":" + TTDescription : createAhead; TTTrain.CreateAhead = TTTrain.CreateAhead.ToLower(); } } @@ -1930,13 +1898,12 @@ public void ExtractStartTime(string startString, string consistInfo, Simulator s validTrain = false; } - // activation is not allowed if started from pool + // Activation is not allowed if started from pool if (activationRequired && !String.IsNullOrEmpty(createFromPool)) { activationRequired = false; - Trace.TraceInformation("Trigger activation not allowed when starting from pool, trigger activation reset for train {0}", TTTrain.Name); + Trace.TraceInformation("Trigger activation not allowed when starting from pool, trigger activation reset for train {0}", TTTrain.Name); } - } //================================================================================================// @@ -1946,7 +1913,7 @@ public void ExtractStartTime(string startString, string consistInfo, Simulator s /// public void ProcessRestartDelay(string restartDelayInfo) { - // build list of commands + // Build list of commands List RestartDelayCommands = new List(); if (!String.IsNullOrEmpty(restartDelayInfo)) @@ -1961,50 +1928,49 @@ public void ProcessRestartDelay(string restartDelayInfo) } } - // process list of commands - + // Process list of commands foreach (TTTrainCommands thisCommand in RestartDelayCommands) { switch (thisCommand.CommandToken) { - // delay when new + // Delay when new case "new": TTTrain.DelayedStartSettings.newStart = ProcessRestartDelayValues(TTTrain.Name, thisCommand.CommandQualifiers, thisCommand.CommandToken); break; - // delay when restarting from signal or other path action + // Delay when restarting from signal or other path action case "path": TTTrain.DelayedStartSettings.pathRestart = ProcessRestartDelayValues(TTTrain.Name, thisCommand.CommandQualifiers, thisCommand.CommandToken); break; - // delay when restarting from station stop + // Delay when restarting from station stop case "station": TTTrain.DelayedStartSettings.stationRestart = ProcessRestartDelayValues(TTTrain.Name, thisCommand.CommandQualifiers, thisCommand.CommandToken); break; - // delay when restarting when following stopped train + // Delay when restarting when following stopped train case "follow": TTTrain.DelayedStartSettings.followRestart = ProcessRestartDelayValues(TTTrain.Name, thisCommand.CommandQualifiers, thisCommand.CommandToken); break; - // delay after attaching + // Delay after attaching case "attach": TTTrain.DelayedStartSettings.attachRestart = ProcessRestartDelayValues(TTTrain.Name, thisCommand.CommandQualifiers, thisCommand.CommandToken); break; - // delay on detaching + // Delay on detaching case "detach": TTTrain.DelayedStartSettings.detachRestart = ProcessRestartDelayValues(TTTrain.Name, thisCommand.CommandQualifiers, thisCommand.CommandToken); break; - // delay for train and moving table + // Delay for train and moving table case "movingtable": TTTrain.DelayedStartSettings.movingtableRestart = ProcessRestartDelayValues(TTTrain.Name, thisCommand.CommandQualifiers, thisCommand.CommandToken); break; - // delay when restarting at reversal + // Delay when restarting at reversal case "reverse": - // process additional reversal delay + // Process additional reversal delay for (int iIndex = thisCommand.CommandQualifiers.Count - 1; iIndex >= 0; iIndex--) { TTTrainCommands.TTTrainComQualifiers thisQual = thisCommand.CommandQualifiers[iIndex]; @@ -2045,10 +2011,10 @@ public void ProcessRestartDelay(string restartDelayInfo) /// public TTTrain.DelayedStartBase ProcessRestartDelayValues(String trainName, List commandQualifiers, string delayType) { - // preset values + // Preset values TTTrain.DelayedStartBase newDelayInfo = new TTTrain.DelayedStartBase(); - // process command qualifiers + // Process command qualifiers foreach (TTTrainCommands.TTTrainComQualifiers thisQual in commandQualifiers) { switch (thisQual.QualifierName) @@ -2083,7 +2049,7 @@ public TTTrain.DelayedStartBase ProcessRestartDelayValues(String trainName, List } } - return (newDelayInfo); + return newDelayInfo; } //================================================================================================// @@ -2094,7 +2060,7 @@ public TTTrain.DelayedStartBase ProcessRestartDelayValues(String trainName, List /// public void ProcessSpeedInfo(string speedInfo, float actSpeedConv) { - // build list of commands + // Build list of commands List SpeedCommands = new List(); if (!String.IsNullOrEmpty(speedInfo)) @@ -2229,17 +2195,21 @@ public List ProcessConsistInfo(string consistDef) if (endIndex < 0) { Trace.TraceWarning("Incomplete consist definition : \">\" character missing : {0}", consistProc); - consistInfo thisConsist = new consistInfo(); - thisConsist.consistFile = String.Copy(consistProc.Substring(1)); - thisConsist.reversed = false; + consistInfo thisConsist = new consistInfo + { + consistFile = String.Copy(consistProc.Substring(1)), + reversed = false + }; consistDetails.Add(thisConsist); consistProc = String.Empty; } else { - consistInfo thisConsist = new consistInfo(); - thisConsist.consistFile = String.Copy(consistProc.Substring(1, endIndex - 1)); - thisConsist.reversed = false; + consistInfo thisConsist = new consistInfo + { + consistFile = String.Copy(consistProc.Substring(1, endIndex - 1)), + reversed = false + }; consistDetails.Add(thisConsist); consistProc = consistProc.Substring(endIndex + 1).Trim(); } @@ -2276,8 +2246,10 @@ public List ProcessConsistInfo(string consistDef) } else if (plusIndex > 0) { - consistInfo thisConsist = new consistInfo(); - thisConsist.consistFile = String.Copy(consistProc.Substring(0, plusIndex).Trim()); + consistInfo thisConsist = new consistInfo + { + consistFile = String.Copy(consistProc.Substring(0, plusIndex).Trim()) + }; int sepIndex = thisConsist.consistFile.IndexOf('$'); if (sepIndex > 0) @@ -2294,8 +2266,10 @@ public List ProcessConsistInfo(string consistDef) } else { - consistInfo thisConsist = new consistInfo(); - thisConsist.consistFile = String.Copy(consistProc); + consistInfo thisConsist = new consistInfo + { + consistFile = String.Copy(consistProc) + }; int sepIndex = consistProc.IndexOf('$'); if (sepIndex > 0) @@ -2313,7 +2287,7 @@ public List ProcessConsistInfo(string consistDef) } } - return (consistDetails); + return consistDetails; } //================================================================================================// @@ -2345,7 +2319,7 @@ public bool BuildConsist(List consistSets, string trainsetDirectory ConsistFile conFile = null; - // try to load config file, exit if failed + // Try to load config file, exit if failed try { conFile = new ConsistFile(consistFile); @@ -2364,17 +2338,12 @@ public bool BuildConsist(List consistSets, string trainsetDirectory AddWagons(conFile, consistDetails, trainsetDirectory, simulator); - // derive speed + // Derive speed if (conFile.Train.TrainCfg.MaxVelocity != null && conFile.Train.TrainCfg.MaxVelocity.A > 0) { - if (confMaxSpeed.HasValue) - { - confMaxSpeed = Math.Min(confMaxSpeed.Value, conFile.Train.TrainCfg.MaxVelocity.A); - } - else - { - confMaxSpeed = Math.Min((float)simulator.TRK.Tr_RouteFile.SpeedLimit, conFile.Train.TrainCfg.MaxVelocity.A); - } + confMaxSpeed = confMaxSpeed.HasValue + ? Math.Min(confMaxSpeed.Value, conFile.Train.TrainCfg.MaxVelocity.A) + : Math.Min((float)simulator.TRK.Tr_RouteFile.SpeedLimit, conFile.Train.TrainCfg.MaxVelocity.A); } } @@ -2384,7 +2353,7 @@ public bool BuildConsist(List consistSets, string trainsetDirectory validTrain = false; } - // set train details + // Set train details TTTrain.CheckFreight(); TTTrain.SetDPUnitIDs(); TTTrain.ReinitializeEOT(); @@ -2436,7 +2405,7 @@ public void AddWagons(ConsistFile consistFile, consistInfo consistDetails, strin ? consistFile.Train.TrainCfg.WagonList.AsEnumerable().Reverse().ToList() : consistFile.Train.TrainCfg.WagonList; - // add wagons + // Add wagons foreach (Wagon wagon in wagonList) { string wagonFolder = Path.Combine(trainsDirectory, wagon.Folder); @@ -2448,7 +2417,7 @@ public void AddWagons(ConsistFile consistFile, consistInfo consistDetails, strin wagonFilePath = Path.ChangeExtension(wagonFilePath, ".eng"); else if (wagon.IsEOT) { - wagonFolder = simulator.BasePath + @"\trains\orts_eot\" + wagon.Folder; + wagonFolder = simulator.BasePath + @"\trains\orts_eot\" + wagon.Folder; wagonFilePath = wagonFolder + @"\" + wagon.Name + ".eot"; } @@ -2476,10 +2445,10 @@ public void AddWagons(ConsistFile consistFile, consistInfo consistDetails, strin //================================================================================================// /// /// Process station stop info cell including possible commands - /// Info may consist of : - /// one or two time values (arr / dep time or pass time) - /// commands - /// time values and commands + /// Info may consist of: + /// - one or two time values (arr / dep time or pass time) + /// - commands + /// - time values and commands /// /// Reference to station string /// Station Details class @@ -2509,9 +2478,11 @@ public StopInfo ProcessStopInfo(string stationInfo, StationInfo stationDetails) } } - StopInfo newStop = new StopInfo(stationDetails.StationName, arr_dep[0], arr_dep[1], parentInfo); - newStop.holdState = stationDetails.HoldState == StationInfo.HoldInfo.Hold ? StopInfo.SignalHoldType.Normal : StopInfo.SignalHoldType.None; - newStop.noWaitSignal = stationDetails.NoWaitSignal; + StopInfo newStop = new StopInfo(stationDetails.StationName, arr_dep[0], arr_dep[1], parentInfo) + { + holdState = stationDetails.HoldState == StationInfo.HoldInfo.Hold ? StopInfo.SignalHoldType.Normal : StopInfo.SignalHoldType.None, + noWaitSignal = stationDetails.NoWaitSignal + }; if (!String.IsNullOrEmpty(fullCommandString)) { @@ -2523,7 +2494,7 @@ public StopInfo ProcessStopInfo(string stationInfo, StationInfo stationDetails) } } - // process forced stop through station commands + // Process forced stop through station commands if (stationDetails.HoldState == StationInfo.HoldInfo.ForceHold) { if (newStop.Commands == null) @@ -2534,7 +2505,7 @@ public StopInfo ProcessStopInfo(string stationInfo, StationInfo stationDetails) newStop.Commands.Add(new TTTrainCommands("forcehold")); } - // process forced wait signal command + // Process forced wait signal command if (stationDetails.ForceWaitSignal) { if (newStop.Commands == null) @@ -2545,7 +2516,7 @@ public StopInfo ProcessStopInfo(string stationInfo, StationInfo stationDetails) newStop.Commands.Add(new TTTrainCommands("forcewait")); } - // process terminal through station commands + // Process terminal through station commands if (stationDetails.IsTerminal) { if (newStop.Commands == null) @@ -2556,7 +2527,7 @@ public StopInfo ProcessStopInfo(string stationInfo, StationInfo stationDetails) newStop.Commands.Add(new TTTrainCommands("terminal")); } - // process closeupsignal through station commands + // PProcess closeupsignal through station commands if (stationDetails.CloseupSignal) { if (newStop.Commands == null) @@ -2567,7 +2538,7 @@ public StopInfo ProcessStopInfo(string stationInfo, StationInfo stationDetails) newStop.Commands.Add(new TTTrainCommands("closeupsignal")); } - // process actual min stop time + // Process actual min stop time if (stationDetails.actMinStopTime.HasValue) { if (newStop.Commands == null) @@ -2575,10 +2546,10 @@ public StopInfo ProcessStopInfo(string stationInfo, StationInfo stationDetails) newStop.Commands = new List(); } - newStop.Commands.Add(new TTTrainCommands(String.Concat("stoptime=",stationDetails.actMinStopTime.Value.ToString().Trim()))); + newStop.Commands.Add(new TTTrainCommands(String.Concat("stoptime=", stationDetails.actMinStopTime.Value.ToString().Trim()))); } - // process restrict to signal + // Process restrict to signal if (stationDetails.RestrictPlatformToSignal) { if (newStop.Commands == null) @@ -2589,7 +2560,7 @@ public StopInfo ProcessStopInfo(string stationInfo, StationInfo stationDetails) newStop.Commands.Add(new TTTrainCommands("restrictplatformtosignal")); } - // process restrict to signal + // Process restrict to signal if (stationDetails.ExtendPlatformToSignal) { if (newStop.Commands == null) @@ -2600,7 +2571,7 @@ public StopInfo ProcessStopInfo(string stationInfo, StationInfo stationDetails) newStop.Commands.Add(new TTTrainCommands("extendplatformtosignal")); } - return (newStop); + return newStop; } //================================================================================================// @@ -2630,7 +2601,7 @@ public void ConvertStops(Simulator simulator, TTTrain actTrain, string name) Trace.TraceInformation("Station {0} not found for train {1}:{2} ", stationStop.Key, Name, TTDescription); } } - actTrain.TCRoute.StationXRef.Clear(); // info no longer required + actTrain.TCRoute.StationXRef.Clear(); // Info no longer required } //================================================================================================// @@ -2702,10 +2673,10 @@ public bool ProcessDisposeInfo(ref List trainList, TTTrainInfo playerTr TTTrain.FormCommand formtype = TTTrain.FormCommand.None; bool trainFound = false; - // set closeup if required + // Set closeup if required TTTrain.Closeup = DisposeDetails.Closeup; - // train forms other train + // Train forms other train if (DisposeDetails.FormType == TTTrain.FormCommand.TerminationFormed || DisposeDetails.FormType == TTTrain.FormCommand.TerminationTriggered) { formtype = DisposeDetails.FormType; @@ -2714,10 +2685,10 @@ public bool ProcessDisposeInfo(ref List trainList, TTTrainInfo playerTr if (DisposeDetails.FormedTrain == null) { Trace.TraceInformation("Error in dispose details for train : " + Name + " : no formed train defined"); - return (true); + return true; } - // extract name + // Extract name if (DisposeDetails.FormedTrain.Contains('=')) { otherTrainName = DisposeDetails.FormedTrain.Split('='); // extract train name @@ -2740,7 +2711,7 @@ public bool ProcessDisposeInfo(ref List trainList, TTTrainInfo playerTr otherTrainName[1] = String.Concat(otherTrainName[1], ":", timetableName[1]); } - // search train + // Search train foreach (TTTrain otherTrain in trainList) { if (String.Compare(otherTrain.Name, otherTrainName[1], true) == 0) @@ -2763,7 +2734,7 @@ public bool ProcessDisposeInfo(ref List trainList, TTTrainInfo playerTr } } - // if not found, try player train + // If not found, try player train if (!trainFound) { if (playerTrain != null && String.Compare(playerTrain.TTTrain.Name, otherTrainName[1], true) == 0) @@ -2805,13 +2776,13 @@ public bool ProcessDisposeInfo(ref List trainList, TTTrainInfo playerTr TTTrain outTrain = null; TTTrain inTrain = null; - // check if train must be stabled + // Check if train must be stabled if (DisposeDetails.Stable && (trainFound || DisposeDetails.FormStatic)) { - // save final train + // Save final train int finalForms = TTTrain.Forms; - // create outbound train (note : train is defined WITHOUT consist as it is formed of incoming train) + // Create outbound train (note: train is defined WITHOUT consist as it is formed of incoming train) outTrain = new TTTrain(simulator, TTTrain); bool addPathNoLoadFailure; @@ -2856,7 +2827,7 @@ public bool ProcessDisposeInfo(ref List trainList, TTTrainInfo playerTr TTTrain.Forms = outTrain.Number; } - // if stable to static + // If stable to static if (DisposeDetails.FormStatic) { outTrain.FormsStatic = true; @@ -2865,7 +2836,7 @@ public bool ProcessDisposeInfo(ref List trainList, TTTrainInfo playerTr { outTrain.FormsStatic = false; - // create inbound train + // Create inbound train inTrain = new TTTrain(simulator, TTTrain); AIPath inPath = parentInfo.LoadPath(DisposeDetails.StableInfo.Stable_inpath, out addPathNoLoadFailure); @@ -2884,7 +2855,7 @@ public bool ProcessDisposeInfo(ref List trainList, TTTrainInfo playerTr inTrain.ActivateTime = DisposeDetails.StableInfo.Stable_intime; inTrain.Name = String.Concat("SI_", finalForms.ToString("0000")); inTrain.FormedOf = outTrain.Number; - inTrain.FormedOfType = DisposeDetails.FormType; // set forms or triggered as defined in stable + inTrain.FormedOfType = DisposeDetails.FormType; // Set forms or triggered as defined in stable inTrain.TrainType = Train.TRAINTYPE.AI_AUTOGENERATE; inTrain.Forms = finalForms; inTrain.SetStop = DisposeDetails.SetStop; @@ -2903,13 +2874,13 @@ public bool ProcessDisposeInfo(ref List trainList, TTTrainInfo playerTr formtype = inTrain.FormedOfType; - // set back reference from final train + // Set back reference from final train formedTrain.FormedOf = inTrain.Number; formedTrain.FormedOfType = TTTrain.FormCommand.TerminationFormed; Train.TCSubpathRoute lastSubpath = inTrain.TCRoute.TCRouteSubpaths[inTrain.TCRoute.TCRouteSubpaths.Count - 1]; - if (inTrain.FormedOfType == TTTrain.FormCommand.TerminationTriggered && formedTrain.Number != 0) // no need to set consist for player train + if (inTrain.FormedOfType == TTTrain.FormCommand.TerminationTriggered && formedTrain.Number != 0) // No need to set consist for player train { bool reverseTrain = CheckFormedReverse(lastSubpath, formedTrain.TCRoute.TCRouteSubpaths[0]); BuildStabledConsist(ref inTrain, formedTrain.Cars, formedTrain.TCRoute.TCRouteSubpaths[0], reverseTrain); @@ -2917,12 +2888,12 @@ public bool ProcessDisposeInfo(ref List trainList, TTTrainInfo playerTr } } } - // if run round required, build runround + // If run round required, build runround if (formtype == TTTrain.FormCommand.TerminationFormed && trainFound && DisposeDetails.RunRound) { TTTrain usedTrain; - bool atStart = false; // indicates if run-round is to be performed before start of move or forms, or at end of move + bool atStart = false; // Indicates if run-round is to be performed before start of move or forms, or at end of move if (DisposeDetails.Stable) { @@ -2954,16 +2925,16 @@ public bool ProcessDisposeInfo(ref List trainList, TTTrainInfo playerTr if (!addPathNoLoadFailure) loadPathNoFailure = false; } - // static + // Static if (DisposeDetails.FormStatic) { TTTrain.FormsStatic = true; } - // pool + // Pool if (DisposeDetails.Pool) { - // check pool name + // Check pool name if (!simulator.PoolHolder.Pools.ContainsKey(DisposeDetails.PoolName)) { Trace.TraceInformation("Train : " + TTTrain.Name + " : reference to unkown pool in dispose command : " + DisposeDetails.PoolName + "\n"); @@ -2988,7 +2959,7 @@ public bool ProcessDisposeInfo(ref List trainList, TTTrainInfo playerTr } } } - return (loadPathNoFailure); + return loadPathNoFailure; } //================================================================================================// @@ -3055,8 +3026,10 @@ public bool BuildRunRound(ref TTTrain rrtrain, bool atStart, DisposeInfo dispose } else { - List thisDetachList = new List(); - thisDetachList.Add(detachDetails); + List thisDetachList = new List + { + detachDetails + }; rrtrain.DetachDetails.Add(-1, thisDetachList); } formedTrain.ActivateTime = rrtime.HasValue ? (rrtime.Value + 30) : 0; @@ -3071,15 +3044,17 @@ public bool BuildRunRound(ref TTTrain rrtrain, bool atStart, DisposeInfo dispose } else { - List thisDetachList = new List(); - thisDetachList.Add(detachDetails); + List thisDetachList = new List + { + detachDetails + }; rrtrain.DetachDetails.Add(-1, thisDetachList); } formedTrain.ActivateTime = 0; } } - return (loadPathNoFailure); + return loadPathNoFailure; } //================================================================================================// @@ -3093,7 +3068,7 @@ private void BuildStabledConsist(ref TTTrain stabledTrain, List cars, { int totalreverse = 0; - // check no. of reversals + // Check no. of reversals foreach (Train.TCReversalInfo reversalInfo in stabledTrain.TCRoute.ReversalInfo) { if (reversalInfo.Valid) totalreverse++; @@ -3101,8 +3076,8 @@ private void BuildStabledConsist(ref TTTrain stabledTrain, List cars, if (reverseTrain) totalreverse++; - // copy consist in same or reverse direction - if ((totalreverse % 2) == 0) // even number, so same direction + // Copy consist in same or reverse direction + if ((totalreverse % 2) == 0) // Even number, so same direction { int carId = 0; foreach (TrainCar car in cars) @@ -3136,7 +3111,7 @@ private void BuildStabledConsist(ref TTTrain stabledTrain, List cars, /// public bool CheckFormedReverse(Train.TCSubpathRoute thisTrainRoute, Train.TCSubpathRoute formedTrainRoute) { - // get matching route sections to check on direction + // Get matching route sections to check on direction int lastElementIndex = thisTrainRoute.Count - 1; Train.TCRouteElement lastElement = thisTrainRoute[lastElementIndex]; @@ -3149,7 +3124,7 @@ public bool CheckFormedReverse(Train.TCSubpathRoute thisTrainRoute, Train.TCSubp firstElementIndex = formedTrainRoute.GetRouteIndex(lastElement.TCSectionIndex, 0); } - // if no matching sections found leave train without consist + // If no matching sections found leave train without consist if (firstElementIndex < 0) { return false; @@ -3157,8 +3132,8 @@ public bool CheckFormedReverse(Train.TCSubpathRoute thisTrainRoute, Train.TCSubp Train.TCRouteElement firstElement = formedTrainRoute[firstElementIndex]; - // reverse required - return (firstElement.Direction != lastElement.Direction); + // Reverse required + return firstElement.Direction != lastElement.Direction; } } @@ -3187,8 +3162,9 @@ public enum SignalHoldType public bool arrdeppassvalid; public SignalHoldType holdState; public bool noWaitSignal; - // public int passageTime; // not yet implemented - // public bool passvalid; // not yet implemented + // TODO + // public int passageTime; // not yet implemented + // public bool passvalid; // not yet implemented public List Commands; public TimetableInfo refTTInfo; @@ -3242,7 +3218,7 @@ public StopInfo(string name, string arrTime, string depTime, TimetableInfo ttinf departureDT = new DateTime(atime.Ticks); } - arrdeppassvalid = (validArrTime || validDepTime); + arrdeppassvalid = validArrTime || validDepTime; StopName = String.Copy(name.ToLower()); } @@ -3259,10 +3235,10 @@ public bool BuildStopInfo(TTTrain actTrain, int actPlatformID, Signals signalRef { bool validStop = false; - // valid stop and not passing + // Valid stop and not passing if (arrdeppassvalid && passTime < 0) { - // check for station flags + // Check for station flags bool terminal = false; int? actMinStopTime = null; float? keepClearFront = null; @@ -3385,12 +3361,12 @@ public bool BuildStopInfo(TTTrain actTrain, int actPlatformID, Signals signalRef } break; - // train terminates at station + // Train terminates at station case "endstop": endStop = true; break; - // required minimal stop time + // Required minimal stop time case "stoptime": if (thisCommand.CommandValues != null && thisCommand.CommandValues.Count > 0) { @@ -3409,28 +3385,26 @@ public bool BuildStopInfo(TTTrain actTrain, int actPlatformID, Signals signalRef } break; - // other commands processed in station stop handling + // Other commands processed in station stop handling default: break; } } } - // create station stop info + // Create station stop info validStop = actTrain.CreateStationStop(actPlatformID, arrivalTime, departureTime, arrivalDT, departureDT, AITrain.clearingDistanceM, - AITrain.minStopDistanceM, terminal, actMinStopTime,keepClearFront, keepClearRear, forcePosition, closeupSignal, closeup, restrictPlatformToSignal, extendPlatformToSignal, endStop); - - // override holdstate using stop info - but only if exit signal is defined + AITrain.minStopDistanceM, terminal, actMinStopTime, keepClearFront, keepClearRear, forcePosition, closeupSignal, closeup, restrictPlatformToSignal, extendPlatformToSignal, endStop); + // Override holdstate using stop info - but only if exit signal is defined int exitSignal = actTrain.StationStops[actTrain.StationStops.Count - 1].ExitSignal; bool holdSignal = holdState != SignalHoldType.None && (exitSignal >= 0); actTrain.StationStops[actTrain.StationStops.Count - 1].HoldSignal = holdSignal; - // override nosignalwait using stop info - + // Override nosignalwait using stop info actTrain.StationStops[actTrain.StationStops.Count - 1].NoWaitSignal = noWaitSignal; - // process additional commands + // Process additional commands if (Commands != null && validStop) { int sectionIndex = actTrain.StationStops[actTrain.StationStops.Count - 1].TCSectionIndex; @@ -3438,14 +3412,13 @@ public bool BuildStopInfo(TTTrain actTrain, int actPlatformID, Signals signalRef foreach (TTTrainCommands thisCommand in Commands) { - actTrain.ProcessTimetableStopCommands(thisCommand, subrouteIndex, sectionIndex, (actTrain.StationStops.Count - 1), actPlatformID, refTTInfo); + actTrain.ProcessTimetableStopCommands(thisCommand, subrouteIndex, sectionIndex, actTrain.StationStops.Count - 1, actPlatformID, refTTInfo); } holdSignal = actTrain.StationStops[actTrain.StationStops.Count - 1].HoldSignal; } - // check holdsignal list - + // Check holdsignal list if (holdSignal) { if (!actTrain.HoldingSignals.Contains(exitSignal)) @@ -3462,10 +3435,10 @@ public bool BuildStopInfo(TTTrain actTrain, int actPlatformID, Signals signalRef } } - // stop used to define command only - find related section in route + // Stop used to define command only - find related section in route else if (Commands != null) { - // get platform details + // Get platform details int platformIndex; int actSubpath = 0; @@ -3475,24 +3448,21 @@ public bool BuildStopInfo(TTTrain actTrain, int actPlatformID, Signals signalRef int sectionIndex = thisPlatform.TCSectionIndex[0]; int routeIndex = actTrain.TCRoute.TCRouteSubpaths[actSubpath].GetRouteIndex(sectionIndex, 0); - // if first section not found in route, try last - + // If first section not found in route, try last if (routeIndex < 0) { sectionIndex = thisPlatform.TCSectionIndex[thisPlatform.TCSectionIndex.Count - 1]; routeIndex = actTrain.TCRoute.TCRouteSubpaths[actSubpath].GetRouteIndex(sectionIndex, 0); } - // if neither section found - try next subroute - keep trying till found or out of subroutes - + // If neither section found - try next subroute - keep trying till found or out of subroutes while (routeIndex < 0 && actSubpath < (actTrain.TCRoute.TCRouteSubpaths.Count - 1)) { actSubpath++; Train.TCSubpathRoute thisRoute = actTrain.TCRoute.TCRouteSubpaths[actSubpath]; routeIndex = thisRoute.GetRouteIndex(sectionIndex, 0); - // if first section not found in route, try last - + // If first section not found in route, try last if (routeIndex < 0) { sectionIndex = thisPlatform.TCSectionIndex[thisPlatform.TCSectionIndex.Count - 1]; @@ -3500,7 +3470,7 @@ public bool BuildStopInfo(TTTrain actTrain, int actPlatformID, Signals signalRef } } - // if section found : process stop + // If section found: process stop if (routeIndex >= 0) { validStop = true; @@ -3514,16 +3484,16 @@ public bool BuildStopInfo(TTTrain actTrain, int actPlatformID, Signals signalRef } } - // pass time only - valid condition but not yet processed + // Pass time only - valid condition but not yet processed if (!validStop && passTime >= 0) { validStop = true; } - return (validStop); - } // end buildStopInfo + return validStop; + } // End buildStopInfo - } // end class stopInfo + } // End class stopInfo //================================================================================================// //================================================================================================// @@ -3541,15 +3511,15 @@ public enum HoldInfo HoldConditional_DwellTime, } - public string StationName; // Station Name - public HoldInfo HoldState; // Hold State - public bool NoWaitSignal; // Train will run up to signal and not wait in platform - public bool ForceWaitSignal; // force to wait for signal even if not exit signal for platform - public int? actMinStopTime; // Min Dwell time for Conditional Holdstate - public bool IsTerminal; // Station is terminal - public bool CloseupSignal; // Train may close up to signal - public bool RestrictPlatformToSignal; // restrict platform end to signal position - public bool ExtendPlatformToSignal; // extend platform end to next signal position + public string StationName; // Station Name + public HoldInfo HoldState; // Hold State + public bool NoWaitSignal; // Train will run up to signal and not wait in platform + public bool ForceWaitSignal; // Force to wait for signal even if not exit signal for platform + public int? actMinStopTime; // Min Dwell time for Conditional Holdstate + public bool IsTerminal; // Station is terminal + public bool CloseupSignal; // Train may close up to signal + public bool RestrictPlatformToSignal; // Restrict platform end to signal position + public bool ExtendPlatformToSignal; // Extend platform end to next signal position //================================================================================================// /// @@ -3558,7 +3528,7 @@ public enum HoldInfo /// public StationInfo(string stationString) { - // default settings + // Default settings HoldState = HoldInfo.NoHold; NoWaitSignal = false; ForceWaitSignal = false; @@ -3568,16 +3538,16 @@ public StationInfo(string stationString) RestrictPlatformToSignal = false; ExtendPlatformToSignal = false; - // if string contains commands : split name and commands if (stationString.Contains("$")) { + // WIf string contains commands: split name and commands string[] stationDetails = stationString.Split('$'); StationName = String.Copy(stationDetails[0]).ToLower().Trim(); ProcessStationCommands(stationDetails); } else - // string contains name only { + // String contains name only StationName = String.Copy(stationString).ToLower().Trim(); } } @@ -3589,7 +3559,7 @@ public StationInfo(string stationString) /// public void ProcessStationCommands(string[] commands) { - // start at 1 as 0 is station name + // Start at 1 as 0 is station name for (int iString = 1; iString <= commands.Length - 1; iString++) { string commandFull = commands[iString]; @@ -3633,7 +3603,7 @@ public void ProcessStationCommands(string[] commands) RestrictPlatformToSignal = true; break; - // required minimal stop time + // Required minimal stop time case "stoptime": if (thisCommand.CommandValues != null && thisCommand.CommandValues.Count > 0) { @@ -3652,8 +3622,7 @@ public void ProcessStationCommands(string[] commands) } break; - - // other commands not yet implemented + // Other commands not yet implemented default: break; } @@ -3793,13 +3762,13 @@ public DisposeInfo(DisposeType typeOfDispose, TTTrainCommands trainCommands, TTT } } - // reset speed if runround is not set + // Reset speed if runround is not set if (!RunRound && DisposeSpeed != null) { DisposeSpeed = null; } break; - // end of Forms and Triggers + // End of Forms and Triggers case DisposeType.Static: List staticQualifiers = trainCommands.CommandQualifiers; @@ -3822,7 +3791,7 @@ public DisposeInfo(DisposeType typeOfDispose, TTTrainCommands trainCommands, TTT } } break; - // end of static + // End of static case DisposeType.Stable: Stable = true; @@ -3935,9 +3904,9 @@ public DisposeInfo(DisposeType typeOfDispose, TTTrainCommands trainCommands, TTT } } break; - // end of stable + // End of stable - // process pool + // Process pool case DisposeType.Pool: Pool = true; FormType = formType; @@ -3962,19 +3931,18 @@ public DisposeInfo(DisposeType typeOfDispose, TTTrainCommands trainCommands, TTT } break; + // End of pool - // end of pool - - // unknow type + // Unknow type default: Trace.TraceInformation("Train : {0} : invalid qualifier for dispose {1}\n", trainName, typeOfDispose); break; } } - }// end class DisposeInfo + } // End class DisposeInfo - } // end class TimetableInfo + } // End class TimetableInfo //================================================================================================// //================================================================================================// @@ -3999,11 +3967,10 @@ public TTTrainCommands(string CommandString) string restString = String.Empty; string commandValueString = String.Empty; - // check for qualifiers - + // Check for qualifiers if (workString.Contains('/')) { - string[] tempStrings = workString.Split('/'); // first string is token plus value, rest is qualifiers + string[] tempStrings = workString.Split('/'); // First string is token plus value, rest is qualifiers restString = String.Copy(tempStrings[0]); if (CommandQualifiers == null) CommandQualifiers = new List(); @@ -4018,7 +3985,7 @@ public TTTrainCommands(string CommandString) restString = String.Copy(workString); } - // extract command token and values + // Extract command token and values if (restString.Contains('=')) { int splitPosition = restString.IndexOf('='); @@ -4030,8 +3997,8 @@ public TTTrainCommands(string CommandString) CommandToken = String.Copy(restString.Trim()); } - // process values - // split on "+" sign (multiple values) + // Process values + // Split on "+" sign (multiple values) string[] valueStrings = null; if (String.IsNullOrEmpty(commandValueString)) @@ -4042,14 +4009,7 @@ public TTTrainCommands(string CommandString) { CommandValues = new List(); - if (commandValueString.Contains('+')) - { - valueStrings = commandValueString.Split('+'); - } - else - { - valueStrings = new string[1] { commandValueString }; - } + valueStrings = commandValueString.Contains('+') ? commandValueString.Split('+') : (new string[1] { commandValueString }); foreach (string thisValue in valueStrings) { @@ -4075,30 +4035,14 @@ public class TTTrainComQualifiers /// public TTTrainComQualifiers(string qualifier) { - string[] qualparts = null; - if (qualifier.Contains('=')) - { - qualparts = qualifier.Split('='); - } - else - { - qualparts = new string[1] { qualifier }; - } - + var qualparts = qualifier.Contains('=') ? qualifier.Split('=') : (new string[1] { qualifier }); QualifierName = String.Copy(qualparts[0].Trim()); string[] valueStrings; if (qualparts.Length > 1) { - if (qualparts[1].Contains('+')) - { - valueStrings = qualparts[1].Trim().Split('+'); - } - else - { - valueStrings = new string[1] { qualparts[1].Trim() }; - } + valueStrings = qualparts[1].Contains('+') ? qualparts[1].Trim().Split('+') : (new string[1] { qualparts[1].Trim() }); foreach (string thisValue in valueStrings) { @@ -4107,6 +4051,6 @@ public TTTrainComQualifiers(string qualifier) } } - } // end class TTTrainComQualifiers - } // end class TTTrainCommands + } // End class TTTrainComQualifiers + } // End class TTTrainCommands } diff --git a/Source/Orts.Simulation/Simulation/Timetables/TTPool.cs b/Source/Orts.Simulation/Simulation/Timetables/TTPool.cs index cffaf93d88..1ca8e3f4e1 100644 --- a/Source/Orts.Simulation/Simulation/Timetables/TTPool.cs +++ b/Source/Orts.Simulation/Simulation/Timetables/TTPool.cs @@ -18,7 +18,6 @@ // This code processes the Timetable definition and converts it into playable train information // // #define DEBUG_POOLINFO -// using System; using System.Collections.Generic; @@ -26,38 +25,38 @@ using System.IO; using System.Linq; using System.Text; +using Orts.Parsers.OR; using Orts.Simulation.AIs; using Orts.Simulation.Physics; using Orts.Simulation.RollingStocks; using Orts.Simulation.Signalling; -using Orts.Parsers.OR; using ORTS.Common; namespace Orts.Simulation.Timetables { /// - /// class Poolholder + /// Class Poolholder /// Interface class for access from Simulator /// public class Poolholder { - public Dictionary Pools; + public Dictionary Pools; /// - /// loader for timetable mode + /// Loader for timetable mode /// - public Poolholder (Simulator simulatorref, string[] arguments, CancellationToken cancellation) + public Poolholder(Simulator simulatorref, string[] arguments, CancellationToken cancellation) { - // process pools + // Process pools PoolInfo TTPool = new PoolInfo(simulatorref); Pools = TTPool.ProcessPools(arguments, cancellation); - // process turntables + // Process turntables TurntableInfo TTTurntable = new TurntableInfo(simulatorref); Dictionary TTTurntables = new Dictionary(); TTTurntables = TTTurntable.ProcessTurntables(arguments, cancellation); - // add turntables to poolholder + // Add turntables to poolholder foreach (KeyValuePair thisTTTurntable in TTTurntables) { Pools.Add(thisTTTurntable.Key, thisTTTurntable.Value); @@ -66,7 +65,7 @@ public Poolholder (Simulator simulatorref, string[] arguments, CancellationToken //================================================================================================// /// - /// loader for activity mode (dummy) + /// Loader for activity mode (dummy) /// public Poolholder() { @@ -75,7 +74,7 @@ public Poolholder() //================================================================================================// /// - /// loader for restore + /// Loader for restore /// public Poolholder(BinaryReader inf, Simulator simulatorref) { @@ -83,7 +82,7 @@ public Poolholder(BinaryReader inf, Simulator simulatorref) int nopools = inf.ReadInt32(); if (nopools > 0) - { + { Pools = new Dictionary(); for (int iPool = 0; iPool < nopools; iPool++) { @@ -115,7 +114,7 @@ public Poolholder(BinaryReader inf, Simulator simulatorref) /// Save /// /// - public void Save (BinaryWriter outf) + public void Save(BinaryWriter outf) { if (Pools == null) { @@ -144,7 +143,6 @@ public void Save (BinaryWriter outf) } } - //================================================================================================// //================================================================================================// /// /// Class TimetablePool @@ -168,29 +166,28 @@ public enum PoolExitDirectionEnum Undefined, } - public string PoolName = String.Empty; public bool ForceCreation; public struct PoolDetails { - public Train.TCSubpathRoute StoragePath; // path defined as storage location - public Traveller StoragePathTraveller; // traveller used to get path position and direction - public Traveller StoragePathReverseTraveller; // traveller used if path must be reversed - public string StorageName; // storage name - public List AccessPaths; // access paths defined for storage location - public float StorageLength; // available length - public float StorageCorrection; // length correction (e.g. due to switch overlap safety) - difference between length of sections in path and actual storage length - - public int TableExitIndex; // index in table exit list for this exit - public int TableVectorIndex; // index in VectorList of tracknode which is the table - public float TableMiddleEntry; // offset of middle of moving table when approaching table (for turntable and transfertable) - public float TableMiddleExit; // offset of middle of moving table when exiting table (for turntable and transfertable) - - public List StoredUnits; // stored no. of units - public List ClaimUnits; // units which have claimed storage but not yet in pool - public int? maxStoredUnits; // max. no of stored units for storage track - public float RemLength; // remaining storage length + public Train.TCSubpathRoute StoragePath; // Path defined as storage location + public Traveller StoragePathTraveller; // Traveller used to get path position and direction + public Traveller StoragePathReverseTraveller; // Traveller used if path must be reversed + public string StorageName; // Storage name + public List AccessPaths; // Access paths defined for storage location + public float StorageLength; // Available length + public float StorageCorrection; // Length correction (e.g. due to switch overlap safety) - difference between length of sections in path and actual storage length + + public int TableExitIndex; // Index in table exit list for this exit + public int TableVectorIndex; // Index in VectorList of tracknode which is the table + public float TableMiddleEntry; // Offset of middle of moving table when approaching table (for turntable and transfertable) + public float TableMiddleExit; // Offset of middle of moving table when exiting table (for turntable and transfertable) + + public List StoredUnits; // Stored no. of units + public List ClaimUnits; // Units which have claimed storage but not yet in pool + public int? maxStoredUnits; // Max. no of stored units for storage track + public float RemLength; // Remaining storage length } public List StoragePool = new List(); @@ -217,20 +214,20 @@ public TimetablePool(TimetableReader fileContents, ref int lineindex, Simulator ForceCreation = simulatorref.Settings.TTCreateTrainOnPoolUnderflow; - // loop through definitions + // Loop through definitions while (lineindex < fileContents.Strings.Count && !newName) { string[] inputLine = fileContents.Strings[lineindex]; - // switch through definitions + // Switch through definitions switch (inputLine[0].ToLower().Trim()) { - // comment : do not process + // Comment: do not process case "#comment": lineindex++; break; - // name : set as name + // Name: set as name case "#name": newName = firstName; if (!firstName) @@ -241,7 +238,7 @@ public TimetablePool(TimetableReader fileContents, ref int lineindex, Simulator } break; - // storage : read path, add to path list + // Storage: read path, add to path list case "#storage": if (String.IsNullOrEmpty(PoolName)) { @@ -271,7 +268,7 @@ public TimetablePool(TimetableReader fileContents, ref int lineindex, Simulator } } - // reset poolname if not valid + // Reset poolname if not valid if (!validpool) { PoolName = String.Empty; @@ -293,13 +290,14 @@ public TimetablePool(BinaryReader inf, Simulator simulatorref) { int maxStorage = 0; - PoolDetails newPool = new PoolDetails(); - newPool.StoragePath = new Train.TCSubpathRoute(inf); - newPool.StoragePathTraveller = new Traveller(simulatorref.TSectionDat, simulatorref.TDB.TrackDB.TrackNodes, inf); - newPool.StoragePathReverseTraveller = new Traveller(simulatorref.TSectionDat, simulatorref.TDB.TrackDB.TrackNodes, inf); - newPool.StorageName = inf.ReadString(); - - newPool.AccessPaths = new List(); + PoolDetails newPool = new PoolDetails + { + StoragePath = new Train.TCSubpathRoute(inf), + StoragePathTraveller = new Traveller(simulatorref.TSectionDat, simulatorref.TDB.TrackDB.TrackNodes, inf), + StoragePathReverseTraveller = new Traveller(simulatorref.TSectionDat, simulatorref.TDB.TrackDB.TrackNodes, inf), + StorageName = inf.ReadString(), + AccessPaths = new List() + }; int noAccessPaths = inf.ReadInt32(); for (int iPath = 0; iPath < noAccessPaths; iPath++) @@ -330,18 +328,11 @@ public TimetablePool(BinaryReader inf, Simulator simulatorref) newPool.TableVectorIndex = inf.ReadInt32(); newPool.TableMiddleEntry = inf.ReadSingle(); newPool.TableMiddleExit = inf.ReadSingle(); - + newPool.RemLength = inf.ReadSingle(); maxStorage = inf.ReadInt32(); - if (maxStorage <= 0) - { - newPool.maxStoredUnits = null; - } - else - { - newPool.maxStoredUnits = maxStorage; - } + newPool.maxStoredUnits = maxStorage <= 0 ? null : (int?)maxStorage; StoragePool.Add(newPool); } @@ -352,7 +343,7 @@ public TimetablePool(BinaryReader inf, Simulator simulatorref) /// Method to save pool /// /// - virtual public void Save(BinaryWriter outf) + public virtual void Save(BinaryWriter outf) { outf.Write(PoolName); outf.Write(ForceCreation); @@ -430,28 +421,28 @@ public PoolDetails ExtractStorage(TimetableReader fileContents, Simulator simula bool endOfStorage = false; validStorage = true; - // extract access paths + // Extract access paths while (lineindex < fileContents.Strings.Count && !endOfStorage) { inputLine = fileContents.Strings[lineindex]; switch (inputLine[0].ToLower().Trim()) { - // skip comment + // Skip comment case "#comment": lineindex++; break; - // exit on next name + // Exit on next name case "#name": endOfStorage = true; break; - // storage : next storage area + // Storage: next storage area case "#storage": endOfStorage = true; break; - // maxstorage : set max storage for this storage track + // Maxstorage: set max storage for this storage track case "#maxunits": try { @@ -465,7 +456,7 @@ public PoolDetails ExtractStorage(TimetableReader fileContents, Simulator simula lineindex++; break; - // access paths : process + // Access paths: process case "#access": int nextfield = 1; @@ -478,7 +469,7 @@ public PoolDetails ExtractStorage(TimetableReader fileContents, Simulator simula lineindex++; break; - // settings : check setting + // Settings: check setting case "#settings": nextfield = 1; while (nextfield < inputLine.Length) @@ -503,15 +494,15 @@ public PoolDetails ExtractStorage(TimetableReader fileContents, Simulator simula } } - // check if access paths defined + // Check if access paths defined if (reqAccess && accessPathNames.Count <= 0) { Trace.TraceInformation("Pool : " + fileContents.FilePath + " : storage : " + storagePathName + " : no access paths defined \n"); validStorage = false; - return (newPool); + return newPool; } - // process storage paths + // Process storage paths newPool.AccessPaths = new List(); newPool.StoredUnits = new List(); newPool.ClaimUnits = new List(); @@ -527,11 +518,11 @@ public PoolDetails ExtractStorage(TimetableReader fileContents, Simulator simula { Train.TCRoutePath fullRoute = new Train.TCRoutePath(newPath, -2, 1, simulatorref.Signals, -1, simulatorref.Settings); - // front traveller + // Front traveller newPool.StoragePath = new Train.TCSubpathRoute(fullRoute.TCRouteSubpaths[0]); newPool.StoragePathTraveller = new Traveller(simulatorref.TSectionDat, simulatorref.TDB.TrackDB.TrackNodes, newPath); - // rear traveller (for moving tables) + // Rear traveller (for moving tables) AIPathNode lastNode = newPath.Nodes.Last(); Traveller.TravellerDirection newDirection = newPool.StoragePathTraveller.Direction == Traveller.TravellerDirection.Forward ? Traveller.TravellerDirection.Backward : Traveller.TravellerDirection.Forward; newPool.StoragePathReverseTraveller = new Traveller(simulatorref.TSectionDat, simulatorref.TDB.TrackDB.TrackNodes, @@ -539,14 +530,14 @@ public PoolDetails ExtractStorage(TimetableReader fileContents, Simulator simula newPool.StorageName = String.Copy(storagePathName); - // if last element is end of track, remove it from path + // If last element is end of track, remove it from path int lastSectionIndex = newPool.StoragePath[newPool.StoragePath.Count - 1].TCSectionIndex; if (simulatorref.Signals.TrackCircuitList[lastSectionIndex].CircuitType == TrackCircuitSection.TrackCircuitType.EndOfTrack) { newPool.StoragePath.RemoveAt(newPool.StoragePath.Count - 1); } - // check for multiple subpaths - not allowed for storage area + // Check for multiple subpaths - not allowed for storage area if (fullRoute.TCRouteSubpaths.Count > 1) { Trace.TraceInformation("Pool : " + fileContents.FilePath + " : storage area : " + storagePathName + " : storage path may not contain multiple subpaths\n"); @@ -556,10 +547,10 @@ public PoolDetails ExtractStorage(TimetableReader fileContents, Simulator simula { Trace.TraceWarning("Pool : " + fileContents.FilePath + " : error while processing storege area path : " + storagePathName + "\n"); validStorage = false; - return (newPool); + return newPool; } - // process access paths + // Process access paths foreach (string accessPath in accessPathNames) { pathValid = true; @@ -568,7 +559,7 @@ public PoolDetails ExtractStorage(TimetableReader fileContents, Simulator simula if (pathValid) { Train.TCRoutePath fullRoute = new Train.TCRoutePath(newPath, -2, 1, simulatorref.Signals, -1, simulatorref.Settings); - // if last element is end of track, remove it from path + // If last element is end of track, remove it from path Train.TCSubpathRoute usedRoute = fullRoute.TCRouteSubpaths[0]; int lastIndex = usedRoute.Count - 1; int lastSectionIndex = usedRoute[lastIndex].TCSectionIndex; @@ -578,7 +569,7 @@ public PoolDetails ExtractStorage(TimetableReader fileContents, Simulator simula } newPool.AccessPaths.Add(new Train.TCSubpathRoute(usedRoute, 0, lastIndex)); - // check for multiple subpaths - not allowed for storage area + // Check for multiple subpaths - not allowed for storage area if (fullRoute.TCRouteSubpaths.Count > 1) { Trace.TraceInformation("Pool : " + fileContents.FilePath + " : storage area : " + accessPath + " : access path may not contain multiple subpaths\n"); @@ -591,11 +582,10 @@ public PoolDetails ExtractStorage(TimetableReader fileContents, Simulator simula } } - // verify proper access route definition - + // Verify proper access route definition if (!validStorage) { - return (newPool); + return newPool; } for (int iPath = 0; iPath < newPool.AccessPaths.Count; iPath++) @@ -615,8 +605,8 @@ public PoolDetails ExtractStorage(TimetableReader fileContents, Simulator simula } else { - // check storage path direction, reverse path if required - // path may be in wrong direction due to path conversion problems + // Check storage path direction, reverse path if required + // Path may be in wrong direction due to path conversion problems if (firstAccessDirection != newPool.StoragePath[reqElementIndex].Direction) { Train.TCSubpathRoute newRoute = new Train.TCSubpathRoute(); @@ -629,7 +619,7 @@ public PoolDetails ExtractStorage(TimetableReader fileContents, Simulator simula newPool.StoragePath = new Train.TCSubpathRoute(newRoute); } - // remove elements from access path which are part of storage path + // Remove elements from access path which are part of storage path int lastReqElement = accessPath.Count - 1; int storageRouteIndex = newPool.StoragePath.GetRouteIndex(accessPath[lastReqElement].TCSectionIndex, 0); @@ -643,10 +633,10 @@ public PoolDetails ExtractStorage(TimetableReader fileContents, Simulator simula } } - // calculate storage length + // Calculate storage length if (!validStorage) { - return (newPool); + return newPool; } float storeLength = 0; foreach (Train.TCRouteElement thisElement in newPool.StoragePath) @@ -654,10 +644,8 @@ public PoolDetails ExtractStorage(TimetableReader fileContents, Simulator simula storeLength += simulatorref.Signals.TrackCircuitList[thisElement.TCSectionIndex].Length; } - // if storage ends at switch, deduct switch safety distance - + // If storage ends at switch, deduct switch safety distance float addedLength = 0; - foreach (Train.TCRouteElement thisElement in newPool.StoragePath) { TrackCircuitSection thisSection = simulatorref.Signals.TrackCircuitList[thisElement.TCSectionIndex]; @@ -668,7 +656,7 @@ public PoolDetails ExtractStorage(TimetableReader fileContents, Simulator simula } else { - // count length only if not part of storage path itself + // Count length only if not part of storage path itself if (newPool.StoragePath.GetRouteIndex(thisSection.Index, 0) < 0) { addedLength += thisSection.Length; @@ -676,7 +664,7 @@ public PoolDetails ExtractStorage(TimetableReader fileContents, Simulator simula } } - // if switch overlap exceeds distance between end of storage and switch, deduct from storage length + // If switch overlap exceeds distance between end of storage and switch, deduct from storage length if (addedLength < 0) { storeLength += addedLength; @@ -686,95 +674,88 @@ public PoolDetails ExtractStorage(TimetableReader fileContents, Simulator simula newPool.StorageCorrection = addedLength; newPool.RemLength = storeLength; - return (newPool); + return newPool; } //================================================================================================// /// - /// TestPoolExit : test if end of route is access to required pool + /// TestPoolExit: test if end of route is access to required pool /// /// - virtual public bool TestPoolExit(TTTrain train) + public virtual bool TestPoolExit(TTTrain train) { - bool validPool = false; - // set dispose states + // Set dispose states train.FormsStatic = true; train.Closeup = true; - // find relevant access path + // Find relevant access path int lastSectionIndex = train.TCRoute.TCRouteSubpaths.Last().Last().TCSectionIndex; int lastSectionDirection = train.TCRoute.TCRouteSubpaths.Last().Last().Direction; - // use first storage path to get pool access path - + // Use first storage path to get pool access path PoolDetails thisStorage = StoragePool[0]; int reqPath = -1; int reqPathIndex = -1; - // find relevant access path + // Find relevant access path for (int iPath = 0; iPath < thisStorage.AccessPaths.Count && reqPath < 0; iPath++) { Train.TCSubpathRoute accessPath = thisStorage.AccessPaths[iPath]; reqPathIndex = accessPath.GetRouteIndex(lastSectionIndex, 0); - // path is defined outbound, so directions must be opposite + // Path is defined outbound, so directions must be opposite if (reqPathIndex >= 0 && accessPath[reqPathIndex].Direction != lastSectionDirection) { reqPath = iPath; } } - // none found + // None found if (reqPath < 0) { Trace.TraceWarning("Train : " + train.Name + " : no valid path found to access pool storage " + PoolName + "\n"); train.FormsStatic = false; train.Closeup = false; } - // path found : extend train path with access and storage paths else { + // Path found: extend train path with access and storage paths train.PoolAccessSection = lastSectionIndex; validPool = true; } - return (validPool); + return validPool; } //================================================================================================// /// - /// Create in pool : create train in pool + /// Create in pool: create train in pool /// /// - - virtual public int CreateInPool(TTTrain train, List nextTrains) + public virtual int CreateInPool(TTTrain train, List nextTrains) { int PoolStorageState = (int)TTTrain.PoolAccessState.PoolInvalid; train.TCRoute.TCRouteSubpaths[0] = PlaceInPool(train, out PoolStorageState, false); train.ValidRoute[0] = new Train.TCSubpathRoute(train.TCRoute.TCRouteSubpaths[0]); train.TCRoute.activeSubpath = 0; - // if no storage available - abondone train + // If no storage available - abondone train if (PoolStorageState < 0) { - return (PoolStorageState); + return PoolStorageState; } - // use stored traveller + // Use stored traveller train.PoolStorageIndex = PoolStorageState; train.RearTDBTraveller = new Traveller(StoragePool[train.PoolStorageIndex].StoragePathTraveller); - // if storage available check for other engines on storage track + // If storage available check for other engines on storage track if (StoragePool[train.PoolStorageIndex].StoredUnits.Count > 0) { int lastTrainNumber = StoragePool[train.PoolStorageIndex].StoredUnits[StoragePool[train.PoolStorageIndex].StoredUnits.Count - 1]; - TTTrain lastTrain = train.GetOtherTTTrainByNumber(lastTrainNumber); - if (lastTrain == null) - { - lastTrain = train.Simulator.GetAutoGenTTTrainByNumber(lastTrainNumber); - } + TTTrain lastTrain = train.GetOtherTTTrainByNumber(lastTrainNumber) ?? train.Simulator.GetAutoGenTTTrainByNumber(lastTrainNumber); if (lastTrain != null) { train.CreateAhead = String.Copy(lastTrain.Name).ToLower(); @@ -792,58 +773,56 @@ virtual public int CreateInPool(TTTrain train, List nextTrains) train.Cars[i].WorldPosition.XNAMatrix.M42 -= 1000; train.ResetInitialTrainRoute(tempRoute); - // set train route and position so proper position in pool can be calculated + // Set train route and position so proper position in pool can be calculated train.UpdateTrainPosition(); - // add unit to pool + // Add unit to pool AddUnit(train, false); - validPosition = train.PostInit(false); // post init train but do not activate + validPosition = train.PostInit(false); // Post init train but do not activate } - return (PoolStorageState); + return PoolStorageState; } //================================================================================================// /// - /// Place in pool : place train in pool + /// Place in pool: place train in pool /// /// - - virtual public Train.TCSubpathRoute PlaceInPool(TTTrain train, out int poolStorageIndex, bool checkAccessPath) + public virtual Train.TCSubpathRoute PlaceInPool(TTTrain train, out int poolStorageIndex, bool checkAccessPath) { int tempIndex; Train.TCSubpathRoute newRoute = SetPoolExit(train, out tempIndex, checkAccessPath); poolStorageIndex = tempIndex; - return (newRoute); + return newRoute; } //================================================================================================// /// - /// SetPoolExit : adjust train dispose details and path to required pool exit + /// SetPoolExit: adjust train dispose details and path to required pool exit /// Returned poolStorageState : <0 : state (enum TTTrain.PoolAccessState); >0 : poolIndex /// /// - virtual public Train.TCSubpathRoute SetPoolExit(TTTrain train, out int poolStorageState, bool checkAccessPath) + public virtual Train.TCSubpathRoute SetPoolExit(TTTrain train, out int poolStorageState, bool checkAccessPath) { - // new route + // New route Train.TCSubpathRoute newRoute = null; - poolStorageState = (int) TTTrain.PoolAccessState.PoolInvalid; + poolStorageState = (int)TTTrain.PoolAccessState.PoolInvalid; - // set dispose states + // Set dispose states train.FormsStatic = true; train.Closeup = true; - // find relevant access path + // Find relevant access path int lastSectionIndex = train.TCRoute.TCRouteSubpaths.Last().Last().TCSectionIndex; int lastSectionDirection = train.TCRoute.TCRouteSubpaths.Last().Last().Direction; - // find storage path with enough space to store train - + // Find storage path with enough space to store train poolStorageState = GetPoolExitIndex(train); - // pool overflow if (poolStorageState == (int)TTTrain.PoolAccessState.PoolOverflow) { + // Pool overflow Trace.TraceWarning("Pool : " + PoolName + " : overflow : cannot place train : " + train.Name + "\n"); if (train.CheckTrain) @@ -858,14 +837,13 @@ virtual public Train.TCSubpathRoute SetPoolExit(TTTrain train, out int poolStora } } - // train will be abandoned when reaching end of path + // Train will be abandoned when reaching end of path train.FormsStatic = false; train.Closeup = false; } - - // pool invalid else if (poolStorageState == (int)TTTrain.PoolAccessState.PoolInvalid) { + // Pool invalid Trace.TraceWarning("Pool : " + PoolName + " : no valid pool found : " + train.Name + "\n"); if (train.CheckTrain) @@ -874,17 +852,13 @@ virtual public Train.TCSubpathRoute SetPoolExit(TTTrain train, out int poolStora File.AppendAllText(@"C:\temp\checktrain.txt", "No valid pool found \n"); } - // train will be abandoned when reaching end of path + // Train will be abandoned when reaching end of path train.FormsStatic = false; train.Closeup = false; - } - - // no action if state is poolClaimed - state will resolve as train ahead is stabled in pool - - - // valid pool + } // No action if state is poolClaimed - state will resolve as train ahead is stabled in pool else if (poolStorageState >= 0) { + // valid pool PoolDetails thisStorage = StoragePool[poolStorageState]; train.PoolStorageIndex = poolStorageState; @@ -893,20 +867,20 @@ virtual public Train.TCSubpathRoute SetPoolExit(TTTrain train, out int poolStora int reqPath = -1; int reqPathIndex = -1; - // find relevant access path + // Find relevant access path for (int iPath = 0; iPath < thisStorage.AccessPaths.Count && reqPath < 0; iPath++) { Train.TCSubpathRoute accessPath = thisStorage.AccessPaths[iPath]; reqPathIndex = accessPath.GetRouteIndex(lastSectionIndex, 0); - // path is defined outbound, so directions must be opposite + // Path is defined outbound, so directions must be opposite if (reqPathIndex >= 0 && accessPath[reqPathIndex].Direction != lastSectionDirection) { reqPath = iPath; } } - // none found + // None found if (reqPath < 0) { Trace.TraceWarning("Train : " + train.Name + " : no valid path found to access pool storage " + PoolName + "\n"); @@ -914,14 +888,14 @@ virtual public Train.TCSubpathRoute SetPoolExit(TTTrain train, out int poolStora train.Closeup = false; poolStorageState = -1; } - // path found : extend train path with access and storage paths + // Path found: extend train path with access and storage paths else { Train.TCSubpathRoute accessPath = thisStorage.AccessPaths[reqPath]; newRoute = new Train.TCSubpathRoute(train.TCRoute.TCRouteSubpaths.Last()); - // add elements from access route except those allready on the path - // add in reverse order and reverse direction as path is defined outbound + // Add elements from access route except those allready on the path + // Add in reverse order and reverse direction as path is defined outbound for (int iElement = reqPathIndex; iElement >= 0; iElement--) { if (newRoute.GetRouteIndex(accessPath[iElement].TCSectionIndex, 0) < 0) @@ -931,7 +905,7 @@ virtual public Train.TCSubpathRoute SetPoolExit(TTTrain train, out int poolStora newRoute.Add(newElement); } } - // add elements from storage + // Add elements from storage for (int iElement = thisStorage.StoragePath.Count - 1; iElement >= 0; iElement--) { if (newRoute.GetRouteIndex(thisStorage.StoragePath[iElement].TCSectionIndex, 0) < 0) @@ -941,14 +915,14 @@ virtual public Train.TCSubpathRoute SetPoolExit(TTTrain train, out int poolStora newRoute.Add(newElement); } } - // set pool claim + // Set pool claim AddUnit(train, true); thisStorage.ClaimUnits.Add(train.Number); } } - // create new route from storage and access track only else { + // Create new route from storage and access track only newRoute = new Train.TCSubpathRoute(thisStorage.AccessPaths[0]); foreach (Train.TCRouteElement thisElement in thisStorage.StoragePath) @@ -962,42 +936,40 @@ virtual public Train.TCSubpathRoute SetPoolExit(TTTrain train, out int poolStora } } - return (newRoute); + return newRoute; } //================================================================================================// /// /// Base class to allow override for moving table classes /// - - virtual public float GetEndOfRouteDistance(Train.TCSubpathRoute thisRoute, Train.TCPosition frontPosition, int pathIndex, Signals signalRef) + public virtual float GetEndOfRouteDistance(Train.TCSubpathRoute thisRoute, Train.TCPosition frontPosition, int pathIndex, Signals signalRef) { - return (0); + return 0; } //================================================================================================// /// - /// GetPoolExitIndex : get pool index for train exiting to pool - /// Returned poolStorageState : <0 : state (enum TTTrain.PoolAccessState); >0 : poolIndex + /// GetPoolExitIndex: get pool index for train exiting to pool + /// Returned poolStorageState: <0: state (enum TTTrain.PoolAccessState); >0 : poolIndex /// /// public int GetPoolExitIndex(TTTrain train) { - // find storage path with enough space to store train - + // Find storage path with enough space to store train int reqPool = (int)TTTrain.PoolAccessState.PoolInvalid; for (int iPool = 0; iPool < StoragePool.Count && reqPool < 0; iPool++) { PoolDetails thisStorage = StoragePool[iPool]; - // check on max units on storage track + // Check on max units on storage track bool maxUnitsReached = false; if (thisStorage.maxStoredUnits.HasValue) { maxUnitsReached = thisStorage.StoredUnits.Count >= thisStorage.maxStoredUnits.Value; } - // train already has claimed space + // Train already has claimed space if (thisStorage.ClaimUnits.Contains(train.Number)) { reqPool = iPool; @@ -1005,7 +977,6 @@ public int GetPoolExitIndex(TTTrain train) else if (thisStorage.StoredUnits.Contains(train.Number)) { - #if DEBUG_POOLINFO var sob = new StringBuilder(); DateTime baseDT = new DateTime(); @@ -1028,8 +999,8 @@ public int GetPoolExitIndex(TTTrain train) } } - // if no valid pool found, check if any paths have a claimed train - // else state is pool overflow + // If no valid pool found, check if any paths have a claimed train + // Else state is pool overflow if (reqPool < 0) { reqPool = (int)TTTrain.PoolAccessState.PoolOverflow; @@ -1044,19 +1015,18 @@ public int GetPoolExitIndex(TTTrain train) } } - return (reqPool); + return reqPool; } //================================================================================================// /// /// Test if route leads to pool /// - public bool TestRouteLeadingToPool(Train.TCSubpathRoute testedRoute, int poolIndex, string dumpfile, string trainName) { Train.TCSubpathRoute poolStorage = StoragePool[poolIndex].StoragePath; - // check if signal route leads to pool + // Check if signal route leads to pool foreach (Train.TCRouteElement routeElement in poolStorage) { if (testedRoute.GetRouteIndex(routeElement.TCSectionIndex, 0) > 0) @@ -1067,23 +1037,23 @@ public bool TestRouteLeadingToPool(Train.TCSubpathRoute testedRoute, int poolInd sob.AppendFormat("CALL ON : Train {0} : valid - train is going into pool {1} \n", trainName, PoolName); File.AppendAllText(dumpfile, sob.ToString()); } - return (true); + return true; } } - return (false); + return false; } //================================================================================================// /// - /// AddUnit : add unit to pool, update remaining length + /// AddUnit: add unit to pool, update remaining length /// /// public void AddUnit(TTTrain train, bool claimOnly) { PoolDetails thisPool = StoragePool[train.PoolStorageIndex]; - // if train has already claimed position, remove claim + // If train has already claimed position, remove claim if (thisPool.ClaimUnits.Contains(train.Number)) { thisPool.ClaimUnits.Remove(train.Number); @@ -1092,7 +1062,7 @@ public void AddUnit(TTTrain train, bool claimOnly) else { - // add train to pool + // Add train to pool thisPool.StoredUnits.Add(train.Number); thisPool.RemLength = CalculateStorageLength(thisPool, train); @@ -1120,16 +1090,16 @@ public void AddUnit(TTTrain train, bool claimOnly) #endif } - // update altered pool + // Update altered pool StoragePool[train.PoolStorageIndex] = thisPool; - // if claim only, do not reset track section states + // If claim only, do not reset track section states if (claimOnly) { return; } - // clear track behind engine, only keep actual occupied sections + // Clear track behind engine, only keep actual occupied sections Train.TCSubpathRoute tempRoute = train.signalRef.BuildTempRoute(train, train.PresentPosition[1].TCSectionIndex, train.PresentPosition[1].TCOffset, train.PresentPosition[1].TCDirection, train.Length, true, true, false); train.OccupiedTrack.Clear(); @@ -1151,59 +1121,58 @@ public void AddUnit(TTTrain train, bool claimOnly) /// public float CalculateStorageLength(PoolDetails reqStorage, TTTrain train) { - // no trains in storage + // No trains in storage if (reqStorage.StoredUnits.Count <= 0) { - return (reqStorage.StorageLength); + return reqStorage.StorageLength; } - // calculate remaining length + // Calculate remaining length int occSectionIndex = train.PresentPosition[0].TCSectionIndex; int occSectionDirection = train.PresentPosition[0].TCDirection; int storageSectionIndex = reqStorage.StoragePath.GetRouteIndex(occSectionIndex, 0); - // if train not stopped in pool, return remaining length = 0 + // If train not stopped in pool, return remaining length = 0 if (storageSectionIndex < 0) { - return (0); + return 0; } int storageSectionDirection = reqStorage.StoragePath[storageSectionIndex].Direction; - // if directions of paths are equal, use front section, section.length - position.offset, and use front of train position + // If directions of paths are equal, use front section, section.length - position.offset, and use front of train position float remLength = 0; - // same direction : use rear of train position - // for turntable pools, path is defined in opposite direction - + // Same direction : use rear of train position + // For turntable pools, path is defined in opposite direction if (GetType() == typeof(TimetableTurntablePool)) { - // use rear of train position if (occSectionDirection == storageSectionDirection) { + // Use rear of train position occSectionIndex = train.PresentPosition[1].TCSectionIndex; TrackCircuitSection occSection = train.signalRef.TrackCircuitList[occSectionIndex]; remLength = train.PresentPosition[1].TCOffset; } else - // use front of train position { + // Use front of train position TrackCircuitSection occSection = train.signalRef.TrackCircuitList[occSectionIndex]; remLength = occSection.Length - train.PresentPosition[0].TCOffset; } } else { - // use rear of train position if (occSectionDirection == storageSectionDirection) { + // Use rear of train position occSectionIndex = train.PresentPosition[1].TCSectionIndex; TrackCircuitSection occSection = train.signalRef.TrackCircuitList[occSectionIndex]; remLength = occSection.Length - train.PresentPosition[1].TCOffset; } else - // use front of train position { + // Use front of train position TrackCircuitSection occSection = train.signalRef.TrackCircuitList[occSectionIndex]; remLength = train.PresentPosition[0].TCOffset; } @@ -1214,13 +1183,13 @@ public float CalculateStorageLength(PoolDetails reqStorage, TTTrain train) remLength += train.signalRef.TrackCircuitList[reqStorage.StoragePath[iSection].TCSectionIndex].Length; } - // position was furthest down the storage area, so take off train length + // Position was furthest down the storage area, so take off train length remLength -= train.Length; - // correct for overlap etc. - remLength += reqStorage.StorageCorrection; // storage correction is negative! + // Correct for overlap etc. + remLength += reqStorage.StorageCorrection; // Storage correction is negative! - return (remLength); + return remLength; } //================================================================================================// @@ -1229,7 +1198,7 @@ public float CalculateStorageLength(PoolDetails reqStorage, TTTrain train) ///
/// /// - virtual public TrainFromPool ExtractTrain(ref TTTrain train, int presentTime) + public virtual TrainFromPool ExtractTrain(ref TTTrain train, int presentTime) { #if DEBUG_POOLINFO var sob = new StringBuilder(); @@ -1239,7 +1208,7 @@ virtual public TrainFromPool ExtractTrain(ref TTTrain train, int presentTime) sob.AppendFormat("{0} : Pool {1} : request for train {2} ({3})", actTime.ToString("HH:mm:ss"), PoolName, train.Number, train.Name); File.AppendAllText(@"C:\temp\PoolAnal.csv", sob.ToString() + "\n"); #endif - // check if any engines available + // Check if any engines available int selectedTrainNumber = -1; int selectedStorage = -1; bool claimActive = false; @@ -1247,7 +1216,7 @@ virtual public TrainFromPool ExtractTrain(ref TTTrain train, int presentTime) for (int iStorage = 0; iStorage < StoragePool.Count; iStorage++) { PoolDetails thisStorage = StoragePool[iStorage]; - // engine has claimed access - this storage cannot be used for exit right now + // Engine has claimed access - this storage cannot be used for exit right now if (thisStorage.ClaimUnits.Count > 0) { claimActive = true; @@ -1262,7 +1231,7 @@ virtual public TrainFromPool ExtractTrain(ref TTTrain train, int presentTime) if (selectedTrainNumber < 0) { - // no train found but claim is active - create engine is delayed + // No train found but claim is active - create engine is delayed if (claimActive) { #if DEBUG_TRACEINFO @@ -1271,38 +1240,38 @@ virtual public TrainFromPool ExtractTrain(ref TTTrain train, int presentTime) #if DEBUG_POOLINFO Trace.TraceInformation("Pool {0} : train {1} : delayed through claimed access\n", PoolName, train.Name); #endif - return (TrainFromPool.Delayed); + return TrainFromPool.Delayed; } - // pool underflow : create engine from scratch + // Pool underflow: create engine from scratch DateTime baseDTA = new DateTime(); DateTime moveTimeA = baseDTA.AddSeconds(train.AI.clockTime); if (ForceCreation) { - Trace.TraceInformation("Train request : " + train.Name + " from pool " + PoolName + + Trace.TraceInformation("Train request : " + train.Name + " from pool " + PoolName + " : no engines available in pool, engine is created, at " + moveTimeA.ToString("HH:mm:ss") + "\n"); #if DEBUG_POOLINFO sob = new StringBuilder(); sob.AppendFormat("Pool {0} : train {1} ({2}) : no units available, engine force created", PoolName, train.Number, train.Name); File.AppendAllText(@"C:\temp\PoolAnal.csv", sob.ToString() + "\n"); #endif - return (TrainFromPool.ForceCreated); + return TrainFromPool.ForceCreated; } else { - Trace.TraceInformation("Train request : " + train.Name + " from pool " + PoolName + + Trace.TraceInformation("Train request : " + train.Name + " from pool " + PoolName + " : no engines available in pool, engine is not created , at " + moveTimeA.ToString("HH:mm:ss") + "\n"); #if DEBUG_POOLINFO sob = new StringBuilder(); sob.AppendFormat("Pool {0} : train {1} ({2}) : no units available, enigne not created", PoolName, train.Number, train.Name); File.AppendAllText(@"C:\temp\PoolAnal.csv", sob.ToString() + "\n"); #endif - return (TrainFromPool.NotCreated); + return TrainFromPool.NotCreated; } } - // find required access path + // Find required access path int firstSectionIndex = train.TCRoute.TCRouteSubpaths[0][0].TCSectionIndex; PoolDetails reqStorage = StoragePool[selectedStorage]; @@ -1317,27 +1286,25 @@ virtual public TrainFromPool ExtractTrain(ref TTTrain train, int presentTime) } } - // no valid path found + // No valid path found if (reqAccessPath < 0) { Trace.TraceInformation("Train request : " + train.Name + " from pool " + PoolName + " : no valid access path found \n"); - return (TrainFromPool.Failed); + return TrainFromPool.Failed; } - // if valid path found : build new path from storage area - + // If valid path found: build new path from storage area train.TCRoute.AddSectionsAtStart(reqStorage.AccessPaths[reqAccessPath], train, false); train.TCRoute.AddSectionsAtStart(reqStorage.StoragePath, train, false); - // check all sections in route for engine heading for pool - // if found, do not create engine as this may result in deadlock - + // Check all sections in route for engine heading for pool + // If found, do not create engine as this may result in deadlock bool incomingEngine = false; foreach (Train.TCRouteElement thisElement in train.TCRoute.TCRouteSubpaths[0]) { TrackCircuitSection thisSection = train.signalRef.TrackCircuitList[thisElement.TCSectionIndex]; - // check reserved + // Check reserved if (thisSection.CircuitState.TrainReserved != null) { TTTrain otherTTTrain = thisSection.CircuitState.TrainReserved.Train as TTTrain; @@ -1348,7 +1315,7 @@ virtual public TrainFromPool ExtractTrain(ref TTTrain train, int presentTime) } } - // check claimed + // Check claimed if (thisSection.CircuitState.TrainClaimed.Count > 0) { foreach (Train.TrainRouted otherTrain in thisSection.CircuitState.TrainClaimed) @@ -1363,7 +1330,7 @@ virtual public TrainFromPool ExtractTrain(ref TTTrain train, int presentTime) } if (incomingEngine) break; - // check occupied + // Check occupied List otherTrains = thisSection.CircuitState.TrainsOccupying(); foreach (Train.TrainRouted otherTrain in otherTrains) { @@ -1389,17 +1356,16 @@ virtual public TrainFromPool ExtractTrain(ref TTTrain train, int presentTime) if (incomingEngine) break; } - // if incoming engine is approach, do not create train + // If incoming engine is approach, do not create train if (incomingEngine) { #if DEBUG_TRACEINFO Trace.TraceInformation("Pool {0} : train {1} : delayed through incoming engine\n", PoolName, train.Name); #endif - return (TrainFromPool.Delayed); + return TrainFromPool.Delayed; } - // valid engine found - start train from found engine - + // Valid engine found - start train from found engine TTTrain selectedTrain = train.GetOtherTTTrainByNumber(selectedTrainNumber); if (selectedTrain == null) { @@ -1416,7 +1382,7 @@ virtual public TrainFromPool ExtractTrain(ref TTTrain train, int presentTime) sob.AppendFormat(" stored units {0} : {1} (total {2})", PoolName, reqStorage.StoredUnits.Count, totalno2); File.AppendAllText(@"C:\temp\PoolAnal.csv", sob.ToString() + "\n"); #endif - return (TrainFromPool.Delayed); + return TrainFromPool.Delayed; } TrackCircuitSection[] occupiedSections = new TrackCircuitSection[selectedTrain.OccupiedTrack.Count]; @@ -1444,29 +1410,29 @@ virtual public TrainFromPool ExtractTrain(ref TTTrain train, int presentTime) #if DEBUG_TRACEINFO Trace.TraceInformation("Pool : {0} : train {1} extracted as {2}", PoolName, selectedTrain.Name, train.Name); #endif - // set details for new train from existing train + // Set details for new train from existing train bool validFormed = train.StartFromAITrain(selectedTrain, presentTime, occupiedSections); if (validFormed) { train.InitializeSignals(true); - // start new train + // Start new train if (train.AI.Simulator.StartReference.Contains(train.Number)) { train.AI.Simulator.StartReference.Remove(train.Number); } - // existing train is player, so continue as player if (selectedTrain.TrainType == Train.TRAINTYPE.PLAYER) { + // Existing train is player, so continue as player train.AI.TrainsToRemoveFromAI.Add(train); - // set proper details for new formed train + // Set proper details for new formed train train.OrgAINumber = train.Number; train.Number = 0; train.LeadLocomotiveIndex = selectedTrain.LeadLocomotiveIndex; - for (int carid = 0; carid < train.Cars.Count; carid++ ) + for (int carid = 0; carid < train.Cars.Count; carid++) { train.Cars[carid].CarID = selectedTrain.Cars[carid].CarID; } @@ -1478,7 +1444,7 @@ virtual public TrainFromPool ExtractTrain(ref TTTrain train, int presentTime) train.ControlMode = Train.TRAIN_CONTROL.INACTIVE; train.MovementState = AITrain.AI_MOVEMENT_STATE.AI_STATIC; - // inform viewer about player train switch + // IInform viewer about player train switch train.Simulator.PlayerLocomotive = train.LeadLocomotive; train.Simulator.OnPlayerLocomotiveChanged(); @@ -1487,25 +1453,22 @@ virtual public TrainFromPool ExtractTrain(ref TTTrain train, int presentTime) train.SetupStationStopHandling(); - // clear replay commands + // Clear replay commands train.Simulator.Log.CommandList.Clear(); - // display messages - if (train.Simulator.Confirmer != null) // As Confirmer may not be created until after a restore. - train.Simulator.Confirmer.Information("Player switched to train : " + train.Name); + // Display messages + train.Simulator.Confirmer?.Information("Player switched to train : " + train.Name); } - - // new train is intended as player else if (train.TrainType == Train.TRAINTYPE.PLAYER || train.TrainType == Train.TRAINTYPE.INTENDED_PLAYER) { + // New train is intended as player train.TrainType = Train.TRAINTYPE.PLAYER; train.ControlMode = Train.TRAIN_CONTROL.INACTIVE; train.MovementState = AITrain.AI_MOVEMENT_STATE.AI_STATIC; - train.AI.TrainsToAdd.Add(train); - // set player locomotive - // first test first and last cars - if either is drivable, use it as player locomotive + // Set player locomotive + // First test first and last cars - if either is drivable, use it as player locomotive int lastIndex = train.Cars.Count - 1; if (train.Cars[0].IsDriveable) @@ -1520,7 +1483,7 @@ virtual public TrainFromPool ExtractTrain(ref TTTrain train, int presentTime) { foreach (TrainCar car in train.Cars) { - if (car.IsDriveable) // first loco is the one the player drives + if (car.IsDriveable) // First loco is the one the player drives { train.AI.Simulator.PlayerLocomotive = train.LeadLocomotive = car; break; @@ -1546,12 +1509,11 @@ virtual public TrainFromPool ExtractTrain(ref TTTrain train, int presentTime) } } } - - // normal AI train else { - // set delay - float randDelay = (float)Simulator.Random.Next((train.DelayedStartSettings.newStart.randomPartS * 10)); + // Normal AI train + // Set delay + float randDelay = Simulator.Random.Next(train.DelayedStartSettings.newStart.randomPartS * 10); train.RestdelayS = train.DelayedStartSettings.newStart.fixedPartS + (randDelay / 10f); train.DelayedStart = true; train.DelayedStartState = TTTrain.AI_START_MOVEMENT.NEW; @@ -1563,10 +1525,10 @@ virtual public TrainFromPool ExtractTrain(ref TTTrain train, int presentTime) train.MovementState = AITrain.AI_MOVEMENT_STATE.AI_STATIC; train.SetFormedOccupied(); - // update any outstanding required actions adding the added length + // Update any outstanding required actions adding the added length train.ResetActions(true); - // set forced consist name if required + // Set forced consist name if required if (!String.IsNullOrEmpty(train.ForcedConsistName)) { foreach (var car in train.Cars) @@ -1583,10 +1545,10 @@ virtual public TrainFromPool ExtractTrain(ref TTTrain train, int presentTime) #if DEBUG_POOLINFO Trace.TraceWarning("Failed to extract required train " + train.Name + " from pool " + PoolName + "\n"); #endif - return (TrainFromPool.Failed); + return TrainFromPool.Failed; } - // update pool data + // Update pool data reqStorage.StoredUnits.Remove(selectedTrainNumber); #if DEBUG_TRACEINFO @@ -1597,7 +1559,7 @@ virtual public TrainFromPool ExtractTrain(ref TTTrain train, int presentTime) } #endif - // get last train in storage + // Get last train in storage TTTrain storedTrain = null; if (reqStorage.StoredUnits.Count > 0) @@ -1629,7 +1591,7 @@ virtual public TrainFromPool ExtractTrain(ref TTTrain train, int presentTime) } StoragePool[selectedStorage] = reqStorage; - return (TrainFromPool.Formed); + return TrainFromPool.Formed; } } } diff --git a/Source/Orts.Simulation/Simulation/Timetables/TTTrain.cs b/Source/Orts.Simulation/Simulation/Timetables/TTTrain.cs index 3e249242dd..ebee454da5 100644 --- a/Source/Orts.Simulation/Simulation/Timetables/TTTrain.cs +++ b/Source/Orts.Simulation/Simulation/Timetables/TTTrain.cs @@ -49,38 +49,38 @@ namespace Orts.Simulation.Timetables { public class TTTrain : AITrain { - public float DefMaxDecelMpSSP = 1.0f; // maximum decelleration - public float DefMaxAccelMpSSP = 1.0f; // maximum accelleration - public float DefMaxDecelMpSSF = 0.8f; // maximum decelleration - public float DefMaxAccelMpSSF = 0.5f; // maximum accelleration - - public bool Closeup = false; // closeup to other train when stabling - public static float keepDistanceCloseupM = 2.5f; // stay 2.5m from end of route when closeup required (for stabling only) - public static float keepDistanceTrainAheadCloseupM = 0.5f; // stay 0.5m from train ahead when closeup required (for stabling only) - public static float keepDistanceCloseupSignalM = 7.0f; // stay 10m from signal ahead when signalcloseup required - public static float endOfRouteDistance = 150f; // Max length to remain for train to continue on route - - public int? ActivateTime; // time train is activated - public bool TriggeredActivationRequired = false; // train activation is triggered by other train - - public bool Created = false; // train is created at start - public string CreateAhead = String.Empty; // train is created ahead of other train - public string CreateInPool = String.Empty; // train is to be created in pool at start of timetable - public string CreateFromPool = String.Empty; // train is to be created from pool + public float DefMaxDecelMpSSP = 1.0f; // Maximum decelleration + public float DefMaxAccelMpSSP = 1.0f; // Maximum accelleration + public float DefMaxDecelMpSSF = 0.8f; // Maximum decelleration + public float DefMaxAccelMpSSF = 0.5f; // Maximum accelleration + + public bool Closeup = false; // Closeup to other train when stabling + public static float keepDistanceCloseupM = 2.5f; // Stay 2.5m from end of route when closeup required (for stabling only) + public static float keepDistanceTrainAheadCloseupM = 0.5f; // Stay 0.5m from train ahead when closeup required (for stabling only) + public static float keepDistanceCloseupSignalM = 7.0f; // Stay 10m from signal ahead when signalcloseup required + public static float endOfRouteDistance = 150f; // Max length to remain for train to continue on route + + public int? ActivateTime; // Time train is activated + public bool TriggeredActivationRequired = false; // Train activation is triggered by other train + + public bool Created = false; // Train is created at start + public string CreateAhead = String.Empty; // Train is created ahead of other train + public string CreateInPool = String.Empty; // Train is to be created in pool at start of timetable + public string CreateFromPool = String.Empty; // Train is to be created from pool + // Required direction on leaving pool (if applicable) public TimetablePool.PoolExitDirectionEnum CreatePoolDirection = TimetablePool.PoolExitDirectionEnum.Undefined; - // required direction on leaving pool (if applicable) - public string ForcedConsistName = String.Empty; // forced consist name for extraction from pool + public string ForcedConsistName = String.Empty; // Forced consist name for extraction from pool - public string ttanalysisreport = String.Empty; // string holding last analysis report, to avoid continouos output of same string + public string ttanalysisreport = String.Empty; // String holding last analysis report, to avoid continouos output of same string - // Timetable Commands info - public List WaitList = null; //used when in timetable mode for wait instructions - public Dictionary> WaitAnyList = null; //used when in timetable mode for waitany instructions - public bool Stable_CallOn = false; //used when in timetable mode to show stabled train is allowed to call on - public bool DriverOnlyOperation = false; //used when in timetable mode to indicate driver only operation - public bool ForceReversal = false; //used when in timetable mode to force reversal at diverging point ignoring signals + /* Timetable Commands info */ + public List WaitList = null; // Used when in timetable mode for wait instructions + public Dictionary> WaitAnyList = null; // Used when in timetable mode for waitany instructions + public bool Stable_CallOn = false; // Used when in timetable mode to show stabled train is allowed to call on + public bool DriverOnlyOperation = false; // Used when in timetable mode to indicate driver only operation + public bool ForceReversal = false; // Used when in timetable mode to force reversal at diverging point ignoring signals - public enum FormCommand //enum to indicate type of form sequence + public enum FormCommand // Enum to indicate type of form sequence { TerminationFormed, TerminationTriggered, @@ -89,104 +89,102 @@ public enum FormCommand //enum to indi None, } - public int Forms = -1; //indicates which train is to be formed out of this train on termination - public bool FormsStatic = false; //indicate if train is to remain as static - public string ExitPool = String.Empty; //set if train is to be stabled in pool - public int PoolAccessSection = -1; //set to last section index if train is to be stabled in pool, section is access section to pool + public int Forms = -1; // Indicates which train is to be formed out of this train on termination + public bool FormsStatic = false; // Indicate if train is to remain as static + public string ExitPool = String.Empty; // Set if train is to be stabled in pool + public int PoolAccessSection = -1; // Set to last section index if train is to be stabled in pool, section is access section to pool - public enum PoolAccessState // used to indicate access state to pool, combined with storage index - // values are <0, value >= 0 is returned storage index - { + public enum PoolAccessState // Used to indicate access state to pool, combined with storage index + { // Values are <0, value >= 0 is returned storage index PoolClaimed = -1, PoolOverflow = -2, PoolInvalid = -3, } - public int PoolStorageIndex = -1; // index in selected pool path (>=0) - + public int PoolStorageIndex = -1; // Index in selected pool path (>=0) + // Required exit direction from pool (if applicable) public TimetablePool.PoolExitDirectionEnum PoolExitDirection = TimetablePool.PoolExitDirectionEnum.Undefined; - // required exit direction from pool (if applicable) - public TimetableTurntableControl ActiveTurntable = null; //active turntable + public TimetableTurntableControl ActiveTurntable = null; // Active turntable - public int FormedOf = -1; //indicates out of which train this train is formed - public FormCommand FormedOfType = FormCommand.None; //indicates type of formed-of command - public int OrgAINumber = -1; //original AI number of formed player train - public bool SetStop = false; //indicates train must copy station stop from formed train - public bool FormsAtStation = false; //indicates train must form into next service at last station, route must be curtailed to that stop - public bool leadLocoAntiSlip = false; //anti slip indication for original leading engine + public int FormedOf = -1; // Indicates out of which train this train is formed + public FormCommand FormedOfType = FormCommand.None; // Indicates type of formed-of command + public int OrgAINumber = -1; // Original AI number of formed player train + public bool SetStop = false; // Indicates train must copy station stop from formed train + public bool FormsAtStation = false; // Indicates train must form into next service at last station, route must be curtailed to that stop + public bool leadLocoAntiSlip = false; // Anti slip indication for original leading engine - // detach details + /* Detach details */ public Dictionary> DetachDetails = new Dictionary>(); - // key is platform reference (use -1 for detach at start or end), list is detach commands at that location - public int[] DetachActive = new int[2] { -1, -1 }; // detach is activated - first index is key in DetachDetails, second index is index in valuelist + // Key is platform reference (use -1 for detach at start or end), list is detach commands at that location + public int[] DetachActive = new int[2] { -1, -1 }; // Detach is activated - first index is key in DetachDetails, second index is index in valuelist // 2nd index = -1 indicates invalid (first index -1 is a valid index) - public int DetachUnits = 0; // no. of units to detach - public bool DetachPosition = false; // if true detach from front - public bool DetachPending = false; // true when player detach window is displayed + public int DetachUnits = 0; // No. of units to detach + public bool DetachPosition = false; // If true detach from front + public bool DetachPending = false; // True when player detach window is displayed - // attach details - public AttachInfo AttachDetails; // attach details + /* Attach details */ + public AttachInfo AttachDetails; + // Key is platform reference or -1 for attach to static train, list are trains which are to attach public Dictionary> NeedAttach = new Dictionary>(); - // key is platform reference or -1 for attach to static train, list are trains which are to attach - // pickup details - public List PickUpDetails = new List(); // only used during train building - public List PickUpTrains = new List(); // list of train to be picked up - public List PickUpStatic = new List(); // index of locations where static consists are to be picked up - public bool PickUpStaticOnForms = false; // set if pickup of static is required when forming next train - public bool NeedPickUp = false; // indicates pickup is required + /* Pickup details */ + public List PickUpDetails = new List(); // Only used during train building + public List PickUpTrains = new List(); // List of train to be picked up + public List PickUpStatic = new List(); // Index of locations where static consists are to be picked up + public bool PickUpStaticOnForms = false; // Set if pickup of static is required when forming next train + public bool NeedPickUp = false; // Indicates pickup is required - // transfer details + /* Transfer details */ + // List of transfer to take place in station public Dictionary TransferStationDetails = new Dictionary(); - // list of transfer to take place in station + // List of transfers defined per train - if int = -1, transfer is to be performed on static train public Dictionary> TransferTrainDetails = new Dictionary>(); - // list of transfers defined per train - if int = -1, transfer is to be performed on static train - public bool NeedTransfer = false; // indicates transfer is required + public bool NeedTransfer = false; // Indicates transfer is required + // List of required station transfers, per station index public Dictionary> NeedStationTransfer = new Dictionary>(); - // list of required station transfers, per station index + // Number of required train transfers per section public Dictionary NeedTrainTransfer = new Dictionary(); - // number of required train transfers per section - // delayed restart - public bool DelayedStart = false; // start is delayed - public float RestdelayS = 0.0f; // time to wait - public AITrain.AI_START_MOVEMENT DelayedStartState; // state to start + /* Delayed restart */ + public bool DelayedStart = false; // Start is delayed + public float RestdelayS = 0.0f; // Time to wait + public AITrain.AI_START_MOVEMENT DelayedStartState; // State to start public struct DelayedStartBase { - public int fixedPartS; // fixed part for restart delay - public int randomPartS; // random part for restart delay + public int fixedPartS; // Fixed part for restart delay + public int randomPartS; // Random part for restart delay } public struct DelayedStartValues { - public DelayedStartBase newStart; // delay on new start - public DelayedStartBase pathRestart; // delay on pathing stop restart (e.g. signal, reversal, node) - public DelayedStartBase followRestart; // delay on restart when following other train - public DelayedStartBase stationRestart; // delay on restart from station stop - public DelayedStartBase attachRestart; // delay on restart after attaching - public DelayedStartBase detachRestart; // delay between stop and detaching - public DelayedStartBase movingtableRestart; // delay for movement of train and moving table - public float reverseAddedDelaySperM; // additional delay on reversal based on train length + public DelayedStartBase newStart; // Delay on new start + public DelayedStartBase pathRestart; // Delay on pathing stop restart (e.g. signal, reversal, node) + public DelayedStartBase followRestart; // Delay on restart when following other train + public DelayedStartBase stationRestart; // Delay on restart from station stop + public DelayedStartBase attachRestart; // Delay on restart after attaching + public DelayedStartBase detachRestart; // Delay between stop and detaching + public DelayedStartBase movingtableRestart; // Delay for movement of train and moving table + public float reverseAddedDelaySperM; // Additional delay on reversal based on train length } public struct SpeedValues { - public float? maxSpeedMpS; // timetable defined max speed - public float? cruiseSpeedMpS; // timetable defined cruise speed - public int? cruiseMaxDelayS; // max. delay to maintain cruise speed - public float? creepSpeedMpS; // timetable defined creep speed - public float? attachSpeedMpS; // timetable defined attach speed - public float? detachSpeedMpS; // timetable defined detach speed - public float? movingtableSpeedMpS; // timetable defined speed for moving tables - public float routeSpeedMpS; // route defined max speed - public float consistSpeedMpS; // consist defined max speed - public bool restrictedSet; // special speed has been set + public float? maxSpeedMpS; // Timetable defined max speed + public float? cruiseSpeedMpS; // Timetable defined cruise speed + public int? cruiseMaxDelayS; // Max. delay to maintain cruise speed + public float? creepSpeedMpS; // Timetable defined creep speed + public float? attachSpeedMpS; // Timetable defined attach speed + public float? detachSpeedMpS; // Timetable defined detach speed + public float? movingtableSpeedMpS; // Timetable defined speed for moving tables + public float routeSpeedMpS; // Route defined max speed + public float consistSpeedMpS; // Consist defined max speed + public bool restrictedSet; // Special speed has been set } public DelayedStartValues DelayedStartSettings = new DelayedStartValues(); public SpeedValues SpeedSettings = new SpeedValues(); - // special patch conditions + // Special patch conditions public enum LastSignalStop { None, @@ -205,10 +203,10 @@ public enum TriggerActivationType public struct TriggerActivation { - public int activatedTrain; // train to be activated - public TriggerActivationType activationType; // type of activation - public int platformId; // trigger platform ident (in case of station stop) - public string activatedName; // name of activated train (used in processing timetable only) + public int activatedTrain; // Train to be activated + public TriggerActivationType activationType; // Type of activation + public int platformId; // Trigger platform ident (in case of station stop) + public string activatedName; // Name of activated train (used in processing timetable only) } public List activatedTrainTriggers = new List(); @@ -221,19 +219,19 @@ public struct TriggerActivation public TTTrain(Simulator simulator) : base(simulator) { - // set AI reference + // Set AI reference AI = simulator.AI; - // preset accel and decel values + // Preset accel and decel values MaxAccelMpSSP = DefMaxAccelMpSSP; MaxAccelMpSSF = DefMaxAccelMpSSF; MaxDecelMpSSP = DefMaxDecelMpSSP; MaxDecelMpSSF = DefMaxDecelMpSSF; - // preset movement state + // Preset movement state MovementState = AI_MOVEMENT_STATE.AI_STATIC; - // preset restart delays + // Preset restart delays DelayedStartSettings.newStart.fixedPartS = 0; DelayedStartSettings.newStart.randomPartS = 10; DelayedStartSettings.pathRestart.fixedPartS = 1; @@ -250,7 +248,7 @@ public TTTrain(Simulator simulator) DelayedStartSettings.movingtableRestart.randomPartS = 10; DelayedStartSettings.reverseAddedDelaySperM = 0.5f; - // preset speed values + // Preset speed values SpeedSettings.maxSpeedMpS = null; SpeedSettings.cruiseSpeedMpS = null; SpeedSettings.cruiseMaxDelayS = null; @@ -268,22 +266,22 @@ public TTTrain(Simulator simulator) public TTTrain(Simulator simulator, TTTrain TTrain) : base(simulator) { - // set AI reference + // Set AI reference AI = simulator.AI; - // preset accel and decel values + // Preset accel and decel values MaxAccelMpSSP = DefMaxAccelMpSSP; MaxAccelMpSSF = DefMaxAccelMpSSF; MaxDecelMpSSP = DefMaxDecelMpSSP; MaxDecelMpSSF = DefMaxDecelMpSSF; - // preset movement state + // Preset movement state MovementState = AI_MOVEMENT_STATE.AI_STATIC; - // copy restart delays + // Copy restart delays DelayedStartSettings = TTrain.DelayedStartSettings; - // copy speed values + // Copy speed values SpeedSettings = TTrain.SpeedSettings; } @@ -310,14 +308,7 @@ public TTTrain(Simulator simulator, BinaryReader inf, AI airef) MaxDecelMpSSF = inf.ReadSingle(); int activateTimeValue = inf.ReadInt32(); - if (activateTimeValue < 0) - { - ActivateTime = null; - } - else - { - ActivateTime = activateTimeValue; - } + ActivateTime = activateTimeValue < 0 ? null : (int?)activateTimeValue; TriggeredActivationRequired = inf.ReadBoolean(); @@ -326,11 +317,13 @@ public TTTrain(Simulator simulator, BinaryReader inf, AI airef) for (int itrigger = 0; itrigger < triggerActivations; itrigger++) { - TriggerActivation newTrigger = new TriggerActivation(); - newTrigger.activatedName = inf.ReadString(); - newTrigger.activatedTrain = inf.ReadInt32(); - newTrigger.activationType = (TriggerActivationType)inf.ReadInt32(); - newTrigger.platformId = inf.ReadInt32(); + TriggerActivation newTrigger = new TriggerActivation + { + activatedName = inf.ReadString(), + activatedTrain = inf.ReadInt32(), + activationType = (TriggerActivationType)inf.ReadInt32(), + platformId = inf.ReadInt32() + }; activatedTrainTriggers.Add(newTrigger); } @@ -491,7 +484,7 @@ public TTTrain(Simulator simulator, BinaryReader inf, AI airef) } int totalNeedTrainTransfer = inf.ReadInt32(); - NeedTrainTransfer = new Dictionary(); + NeedTrainTransfer = new Dictionary(); for (int iNeedTransferList = 0; iNeedTransferList < totalNeedTrainTransfer; iNeedTransferList++) { @@ -521,83 +514,27 @@ public TTTrain(Simulator simulator, BinaryReader inf, AI airef) DelayedStartState = (AI_START_MOVEMENT)inf.ReadInt32(); RestdelayS = inf.ReadSingle(); - // preset speed values - SpeedSettings = new SpeedValues(); - - SpeedSettings.routeSpeedMpS = inf.ReadSingle(); - SpeedSettings.consistSpeedMpS = inf.ReadSingle(); - - if (inf.ReadBoolean()) - { - SpeedSettings.maxSpeedMpS = inf.ReadSingle(); - } - else - { - SpeedSettings.maxSpeedMpS = null; - } - - if (inf.ReadBoolean()) - { - SpeedSettings.cruiseSpeedMpS = inf.ReadSingle(); - } - else - { - SpeedSettings.cruiseSpeedMpS = null; - } - - if (inf.ReadBoolean()) - { - SpeedSettings.cruiseMaxDelayS = inf.ReadInt32(); - } - else - { - SpeedSettings.cruiseMaxDelayS = null; - } - - if (inf.ReadBoolean()) - { - SpeedSettings.creepSpeedMpS = inf.ReadSingle(); - } - else - { - SpeedSettings.creepSpeedMpS = null; - } - - if (inf.ReadBoolean()) - { - SpeedSettings.attachSpeedMpS = inf.ReadSingle(); - } - else - { - SpeedSettings.attachSpeedMpS = null; - } - - if (inf.ReadBoolean()) - { - SpeedSettings.detachSpeedMpS = inf.ReadSingle(); - } - else - { - SpeedSettings.detachSpeedMpS = null; - } - - if (inf.ReadBoolean()) - { - SpeedSettings.movingtableSpeedMpS = inf.ReadSingle(); - } - else - { - SpeedSettings.movingtableSpeedMpS = null; - } - - SpeedSettings.restrictedSet = inf.ReadBoolean(); + // Preset speed values + SpeedSettings = new SpeedValues + { + routeSpeedMpS = inf.ReadSingle(), + consistSpeedMpS = inf.ReadSingle(), + maxSpeedMpS = inf.ReadBoolean() ? inf.ReadSingle() : (float?)null, + cruiseSpeedMpS = inf.ReadBoolean() ? inf.ReadSingle() : (float?)null, + cruiseMaxDelayS = inf.ReadBoolean() ? inf.ReadInt32() : (int?)null, + creepSpeedMpS = inf.ReadBoolean() ? inf.ReadSingle() : (float?)null, + attachSpeedMpS = inf.ReadBoolean() ? inf.ReadSingle() : (float?)null, + detachSpeedMpS = inf.ReadBoolean() ? inf.ReadSingle() : (float?)null, + movingtableSpeedMpS = inf.ReadBoolean() ? inf.ReadSingle() : (float?)null, + restrictedSet = inf.ReadBoolean() + }; DriverOnlyOperation = inf.ReadBoolean(); ForceReversal = inf.ReadBoolean(); Briefing = inf.ReadString(); - // reset actions if train is active + // Reset actions if train is active bool activeTrain = true; if (TrainType == TRAINTYPE.AI_NOTSTARTED) activeTrain = false; @@ -619,7 +556,6 @@ public TTTrain(Simulator simulator, BinaryReader inf, AI airef) /// Save /// Override from Train class /// - public override void Save(BinaryWriter outf) { outf.Write("TT"); @@ -647,13 +583,13 @@ public override void Save(BinaryWriter outf) outf.Write(UncondAttach); outf.Write(doorCloseAdvance); outf.Write(doorOpenDelay); - // dummy for level crossing horn pattern + // Dummy for level crossing horn pattern outf.Write(-1); - // dummy for service list count + // Dummy for service list count outf.Write(-1); - //TTTrains own additional fields + // TTTrains own additional fields outf.Write(Closeup); outf.Write(Created); outf.Write(CreateAhead); @@ -716,7 +652,7 @@ public override void Save(BinaryWriter outf) outf.Write(WaitAnyList.Count); foreach (KeyValuePair> thisWInfo in WaitAnyList) { - outf.Write((int)thisWInfo.Key); + outf.Write(thisWInfo.Key); List thisWaitList = thisWInfo.Value; outf.Write(thisWaitList.Count); @@ -837,7 +773,7 @@ public override void Save(BinaryWriter outf) } outf.Write(NeedTrainTransfer.Count); - foreach (KeyValuePair thisNeedTransfer in NeedTrainTransfer) + foreach (KeyValuePair thisNeedTransfer in NeedTrainTransfer) { outf.Write(thisNeedTransfer.Key); outf.Write(thisNeedTransfer.Value); @@ -907,12 +843,10 @@ public override void Save(BinaryWriter outf) outf.Write(Briefing); } - //================================================================================================// /// /// Terminate route at last signal in train's direction /// - public void EndRouteAtLastSignal() { // no action required @@ -926,7 +860,7 @@ public void EndRouteAtLastSignal() int lastSectionIndex = -1; - // search for last signal in required direction + // Search for last signal in required direction for (int iIndex = lastSubpath.Count - 1; iIndex >= 0 && lastSectionIndex < 0; iIndex--) { TrackCircuitSection thisSection = signalRef.TrackCircuitList[lastSubpath[iIndex].TCSectionIndex]; @@ -938,13 +872,13 @@ public void EndRouteAtLastSignal() } } - // remove sections beyond last signal + // Remove sections beyond last signal for (int iIndex = lastSubpath.Count - 1; iIndex > lastSectionIndex; iIndex--) { lastSubpath.RemoveAt(iIndex); } - // reinsert subroute + // Reinsert subroute TCRoute.TCRouteSubpaths.RemoveAt(lastIndex); TCRoute.TCRouteSubpaths.Add(new TCSubpathRoute(lastSubpath)); } @@ -957,23 +891,22 @@ public void EndRouteAtLastSignal() /// /// /// - public override StationStop SetAlternativeStationStop(StationStop orgStop, TCSubpathRoute newRoute) { int altPlatformIndex = -1; - // get station platform list + // Get station platform list if (signalRef.StationXRefList.ContainsKey(orgStop.PlatformItem.Name)) { List XRefKeys = signalRef.StationXRefList[orgStop.PlatformItem.Name]; - // search through all available platforms + // Search through all available platforms for (int platformIndex = 0; platformIndex <= XRefKeys.Count - 1 && altPlatformIndex < 0; platformIndex++) { int platformXRefIndex = XRefKeys[platformIndex]; PlatformDetails altPlatform = signalRef.PlatformDetailsList[platformXRefIndex]; - // check if section is in new route + // Check if section is in new route for (int iSectionIndex = 0; iSectionIndex <= altPlatform.TCSectionIndex.Count - 1 && altPlatformIndex < 0; iSectionIndex++) { if (newRoute.GetRouteIndex(altPlatform.TCSectionIndex[iSectionIndex], 0) > 0) @@ -983,7 +916,7 @@ public override StationStop SetAlternativeStationStop(StationStop orgStop, TCSub } } - // remove holding signal if set + // Remove holding signal if set int holdSig = -1; if (orgStop.HoldSignal && orgStop.ExitSignal >= 0 && HoldingSignals.Contains(orgStop.ExitSignal)) { @@ -991,11 +924,11 @@ public override StationStop SetAlternativeStationStop(StationStop orgStop, TCSub HoldingSignals.Remove(holdSig); } - // section found in new route - set new station details using old details + // Section found in new route - set new station details using old details if (altPlatformIndex >= 0) { bool isNewPlatform = true; - // check if new found platform is actually same as original + // Check if new found platform is actually same as original foreach (int platfReference in signalRef.PlatformDetailsList[altPlatformIndex].PlatformReference) { if (platfReference == orgStop.PlatformReference) @@ -1005,21 +938,21 @@ public override StationStop SetAlternativeStationStop(StationStop orgStop, TCSub } } - // if platform found is original platform, reinstate hold signal but take no further action + // If platform found is original platform, reinstate hold signal but take no further action if (!isNewPlatform) { if (holdSig >= 0) HoldingSignals.Add(holdSig); - return (orgStop); + return orgStop; } else { - // calculate new stop + // Calculate new stop StationStop newStop = CalculateStationStop(signalRef.PlatformDetailsList[altPlatformIndex].PlatformReference[0], orgStop.ArrivalTime, orgStop.DepartTime, orgStop.arrivalDT, orgStop.departureDT, clearingDistanceM, minStopDistanceM, orgStop.Terminal, orgStop.ActualMinStopTime, orgStop.KeepClearFront, orgStop.KeepClearRear, orgStop.ForcePosition, orgStop.CloseupSignal, orgStop.Closeup, orgStop.RestrictPlatformToSignal, orgStop.ExtendPlatformToSignal, orgStop.EndStop); - // add new holding signal if required + // Add new holding signal if required if (newStop.HoldSignal && newStop.ExitSignal >= 0) { HoldingSignals.Add(newStop.ExitSignal); @@ -1064,20 +997,19 @@ public override StationStop SetAlternativeStationStop(StationStop orgStop, TCSub } } - return (newStop); + return newStop; } } } - return (null); + return null; } //================================================================================================// /// /// Post Init (override from Train) (with activate train option) - /// perform all actions required to start + /// Perform all actions required to start /// - public bool PostInit(bool activateTrain) { @@ -1098,8 +1030,7 @@ public bool PostInit(bool activateTrain) } } #endif - // if train itself forms other train, check if train is to end at station (only if other train is not autogen and this train has SetStop set) - + // If train itself forms other train, check if train is to end at station (only if other train is not autogen and this train has SetStop set) if (Forms >= 0 && SetStop) { TTTrain nextTrain = AI.StartList.GetNotStartedTTTrainByNumber(Forms, false); @@ -1114,7 +1045,7 @@ public bool PostInit(bool activateTrain) StationStops = new List(); StationStop newStop = nextTrain.StationStops[0].CreateCopy(); - int startvalue = nextTrain.ActivateTime.HasValue ? nextTrain.ActivateTime.Value : nextTrain.StartTime.Value; + int startvalue = nextTrain.ActivateTime ?? nextTrain.StartTime.Value; newStop.ArrivalTime = startvalue; newStop.DepartTime = startvalue; @@ -1124,9 +1055,9 @@ public bool PostInit(bool activateTrain) newStop.SubrouteIndex = TCRoute.TCRouteSubpaths.Count - 1; if (newStop.RouteIndex >= 0) { - StationStops.Add(newStop); // do not set stop if platform is not on route + StationStops.Add(newStop); // Do not set stop if platform is not on route - // switch stop position if train is to reverse + // Switch stop position if train is to reverse int nextTrainRouteIndex = nextTrain.TCRoute.TCRouteSubpaths[0].GetRouteIndex(lastSectionIndex, 0); if (nextTrainRouteIndex >= 0 && nextTrain.TCRoute.TCRouteSubpaths[0][nextTrainRouteIndex].Direction != lastSubpath[newStop.RouteIndex].Direction) { @@ -1138,8 +1069,9 @@ public bool PostInit(bool activateTrain) } } - if (Forms >= 0 && FormsAtStation && StationStops != null && StationStops.Count > 0) // curtail route to last station stop + if (Forms >= 0 && FormsAtStation && StationStops != null && StationStops.Count > 0) { + // Curtail route to last station stop StationStop lastStop = StationStops[StationStops.Count - 1]; TCSubpathRoute reqSubroute = TCRoute.TCRouteSubpaths[lastStop.SubrouteIndex]; for (int iRouteIndex = reqSubroute.Count - 1; iRouteIndex > lastStop.RouteIndex; iRouteIndex--) @@ -1147,16 +1079,15 @@ public bool PostInit(bool activateTrain) reqSubroute.RemoveAt(iRouteIndex); } - // if subroute is present route, create new ValidRoute + // If subroute is present route, create new ValidRoute if (lastStop.SubrouteIndex == TCRoute.activeSubpath) { ValidRoute[0] = new TCSubpathRoute(TCRoute.TCRouteSubpaths[TCRoute.activeSubpath]); } } - // on activation : if train is to join pool, set proper dispose details - // copy new route if required - + // On activation: if train is to join pool, set proper dispose details + // Copy new route if required if (activateTrain && !String.IsNullOrEmpty(ExitPool) && ActiveTurntable == null) { TimetablePool thisPool = Simulator.PoolHolder.Pools[ExitPool]; @@ -1172,51 +1103,48 @@ public bool PostInit(bool activateTrain) } } - // check deadlocks (if train has valid activate time only - otherwise it is static and won't move) - + // Check deadlocks (if train has valid activate time only - otherwise it is static and won't move) if (ActivateTime.HasValue) { CheckDeadlock(ValidRoute[0], Number); } - // set initial position and state - + // Set initial position and state bool atStation = AtStation; - bool validPosition = InitialTrainPlacement(String.IsNullOrEmpty(CreateAhead)); // Check track and if clear, set occupied + bool validPosition = InitialTrainPlacement(String.IsNullOrEmpty(CreateAhead)); // Check track and if clear, set occupied if (validPosition) { if (IsFreight) { - MaxAccelMpSS = MaxAccelMpSSF; // set freigth accel and decel + MaxAccelMpSS = MaxAccelMpSSF; // Set freight accel and decel MaxDecelMpSS = MaxAccelMpSSF; } else { - MaxAccelMpSS = MaxAccelMpSSP; // set passenger accel and decel + MaxAccelMpSS = MaxAccelMpSSP; // Set passenger accel and decel MaxDecelMpSS = MaxDecelMpSSP; if (TrainMaxSpeedMpS > 40.0f) { - MaxDecelMpSS = 1.5f * MaxDecelMpSSP; // higher decel for high speed trains + MaxDecelMpSS = 1.5f * MaxDecelMpSSP; // Higher deceleration for high speed trains } if (TrainMaxSpeedMpS > 55.0f) { - MaxDecelMpSS = 2.5f * MaxDecelMpSSP; // higher decel for very high speed trains + MaxDecelMpSS = 2.5f * MaxDecelMpSSP; // Higher deceleration for very high speed trains } } - InitializeSignals(false); // Get signal information - TCRoute.SetReversalOffset(Length); // set reversal information for first subpath - SetEndOfRouteAction(); // set action to ensure train stops at end of route - ControlMode = TRAIN_CONTROL.INACTIVE; // set control mode to INACTIVE + InitializeSignals(false); // Get signal information + TCRoute.SetReversalOffset(Length); // Set reversal information for first subpath + SetEndOfRouteAction(); // Set action to ensure train stops at end of route + ControlMode = TRAIN_CONTROL.INACTIVE; // Set control mode to INACTIVE - // active train if (activateTrain) { - MovementState = AI_MOVEMENT_STATE.INIT; // start in INIT mode to collect info - ControlMode = TRAIN_CONTROL.AUTO_NODE; // start up in NODE control + MovementState = AI_MOVEMENT_STATE.INIT; // Start in INIT mode to collect info + ControlMode = TRAIN_CONTROL.AUTO_NODE; // Start up in NODE control - // if there is an active turntable and action is not completed, start in turntable state + // If there is an active turntable and action is not completed, start in turntable state if (ActiveTurntable != null && ActiveTurntable.MovingTableState != TimetableTurntableControl.MovingTableStateEnum.Completed) { MovementState = AI_MOVEMENT_STATE.TURNTABLE; @@ -1224,16 +1152,15 @@ public bool PostInit(bool activateTrain) { if (ActiveTurntable.MovingTableState == TimetableTurntableControl.MovingTableStateEnum.WaitingMovingTableAvailability) { - if (Simulator.Confirmer != null) // As Confirmer may not be created until after a restore. - Simulator.Confirmer.Information("Wait for turntable to become available"); + Simulator.Confirmer?.Information("Wait for turntable to become available"); } } } - // recalculate station stops based on present train length + // Recalculate station stops based on present train length RecalculateStationStops(atStation); - // check if train starts at station stop + // Check if train starts at station stop if (StationStops.Count > 0 && !atStation) { atStation = CheckInitialStation(); @@ -1242,7 +1169,7 @@ public bool PostInit(bool activateTrain) { if (StationStops.Count > 0) { - SetNextStationAction(); // set station details + SetNextStationAction(); // Set station details } } } @@ -1262,10 +1189,10 @@ public bool PostInit(bool activateTrain) #endif } } - // start train as static else { - MovementState = AI_MOVEMENT_STATE.AI_STATIC; // start in STATIC mode until required activate time + // start in STATIC mode until required activate time + MovementState = AI_MOVEMENT_STATE.AI_STATIC; } } @@ -1307,10 +1234,9 @@ public bool PostInit(bool activateTrain) File.AppendAllText(@"C:\temp\checktrain.txt", " Exit to Pool : " + ExitPool + "\n"); File.AppendAllText(@"C:\temp\checktrain.txt", " From section : " + PoolAccessSection + "\n"); } - } - return (validPosition); + return validPosition; } //================================================================================================// @@ -1318,7 +1244,6 @@ public bool PostInit(bool activateTrain) /// Post Init : perform all actions required to start /// Override from Train class /// - public override bool PostInit() { #if DEBUG_CHECKTRAIN @@ -1338,8 +1263,7 @@ public override bool PostInit() } } #endif - // start ahead of train if required - + // Start ahead of train if required bool validPosition = true; if (!String.IsNullOrEmpty(CreateAhead)) @@ -1347,8 +1271,7 @@ public override bool PostInit() CalculateInitialTTTrainPosition(ref validPosition, null); } - // if not yet started, start normally - + // If not yet started, start normally if (validPosition) { validPosition = InitialTrainPlacement(true); @@ -1356,17 +1279,16 @@ public override bool PostInit() if (validPosition) { - InitializeSignals(false); // Get signal information - only if train has route // + InitializeSignals(false); // Get signal information - only if train has route if (TrainType != TRAINTYPE.STATIC) - CheckDeadlock(ValidRoute[0], Number); // Check deadlock against all other trains (not for static trains) - if (TCRoute != null) TCRoute.SetReversalOffset(Length); + CheckDeadlock(ValidRoute[0], Number); // Check deadlock against all other trains (not for static trains) + TCRoute?.SetReversalOffset(Length); } - // set train speed logging flag (valid per activity, so will be restored after save) - + // Set train speed logging flag (valid per activity, so will be restored after save) if (TrainType == TRAINTYPE.PLAYER) { - SetupStationStopHandling(); // player train must now perform own station stop handling (no activity function available) + SetupStationStopHandling(); // Player train must now perform own station stop handling (no activity function available) DatalogTrainSpeed = Simulator.Settings.DataLogTrainSpeed; DatalogTSInterval = Simulator.Settings.DataLogTSInterval; @@ -1374,7 +1296,7 @@ public override bool PostInit() DatalogTSContents = new int[Simulator.Settings.DataLogTSContents.Length]; Simulator.Settings.DataLogTSContents.CopyTo(DatalogTSContents, 0); - // if logging required, derive filename and open file + // If logging required, derive filename and open file if (DatalogTrainSpeed) { DataLogFile = Simulator.DeriveLogFile("Speed"); @@ -1388,24 +1310,21 @@ public override bool PostInit() } } - // if debug, print out all passing paths - + // If debug, print out all passing paths #if DEBUG_DEADLOCK Printout_PassingPaths(); #endif } - return (validPosition); + return validPosition; } - //================================================================================================// /// /// Calculate actual station stop details /// <\summary> - public StationStop CalculateStationStop(int platformStartID, int arrivalTime, int departTime, DateTime arrivalDT, DateTime departureDT, float clearingDistanceM, - float minStopDistance, bool terminal, int? actMinStopTime, float? keepClearFront, float? keepClearRear, bool forcePosition, bool closeupSignal, + float minStopDistance, bool terminal, int? actMinStopTime, float? keepClearFront, float? keepClearRear, bool forcePosition, bool closeupSignal, bool closeup, bool restrictPlatformToSignal, bool extendPlatformToSignal, bool endStop) { int platformIndex; @@ -1413,11 +1332,10 @@ public override bool PostInit() TCSubpathRoute thisRoute = TCRoute.TCRouteSubpaths[activeSubroute]; - // get platform details - + // Get platform details if (!signalRef.PlatformXRefList.TryGetValue(platformStartID, out platformIndex)) { - return (null); // station not found + return null; // Station not found } else { @@ -1425,24 +1343,21 @@ public override bool PostInit() int sectionIndex = thisPlatform.TCSectionIndex[0]; int routeIndex = thisRoute.GetRouteIndex(sectionIndex, 0); - // if first section not found in route, try last - + // If first section not found in route, try last if (routeIndex < 0) { sectionIndex = thisPlatform.TCSectionIndex[thisPlatform.TCSectionIndex.Count - 1]; routeIndex = thisRoute.GetRouteIndex(sectionIndex, 0); } - // if neither section found - try next subroute - keep trying till found or out of subroutes - + // If neither section found - try next subroute - keep trying till found or out of subroutes while (routeIndex < 0 && activeSubroute < (TCRoute.TCRouteSubpaths.Count - 1)) { activeSubroute++; thisRoute = TCRoute.TCRouteSubpaths[activeSubroute]; routeIndex = thisRoute.GetRouteIndex(sectionIndex, 0); - // if first section not found in route, try last - + // If first section not found in route, try last if (routeIndex < 0) { sectionIndex = thisPlatform.TCSectionIndex[thisPlatform.TCSectionIndex.Count - 1]; @@ -1450,23 +1365,20 @@ public override bool PostInit() } } - // if neither section found - platform is not on route - skip - + // If neither section found - platform is not on route - skip if (routeIndex < 0) { Trace.TraceWarning("Train {0} ({1}) : platform {2} is not on route", Name, Number.ToString(), platformStartID.ToString()); - return (null); + return null; } - // determine end stop position depending on direction - + // Determine end stop position depending on direction StationStop dummyStop = CalculateStationStopPosition(thisRoute, routeIndex, thisPlatform, activeSubroute, - keepClearFront, keepClearRear, forcePosition, closeupSignal, closeup, restrictPlatformToSignal, extendPlatformToSignal, + keepClearFront, keepClearRear, forcePosition, closeupSignal, closeup, restrictPlatformToSignal, extendPlatformToSignal, terminal, platformIndex); - // build and add station stop - + // Build and add station stop StationStop thisStation = new StationStop( platformStartID, thisPlatform, @@ -1491,12 +1403,13 @@ public override bool PostInit() restrictPlatformToSignal, extendPlatformToSignal, endStop, - StationStop.STOPTYPE.STATION_STOP); - - thisStation.arrivalDT = arrivalDT; - thisStation.departureDT = departureDT; + StationStop.STOPTYPE.STATION_STOP) + { + arrivalDT = arrivalDT, + departureDT = departureDT + }; - return (thisStation); + return thisStation; } } @@ -1514,7 +1427,7 @@ public override bool PostInit() /// /// public StationStop CalculateStationStopPosition(TCSubpathRoute thisRoute, int routeIndex, PlatformDetails thisPlatform, int activeSubroute, - float? keepClearFront, float? keepClearRear, bool forcePosition, bool closeupSignal, bool closeup, + float? keepClearFront, float? keepClearRear, bool forcePosition, bool closeupSignal, bool closeup, bool restrictPlatformToSignal, bool ExtendPlatformToSignal, bool terminal, int platformIndex) { StationStop dummyStop = new StationStop(); @@ -1535,9 +1448,9 @@ public override bool PostInit() float endOffset = thisPlatform.TCOffset[1, thisElement.Direction]; float beginOffset = thisPlatform.TCOffset[0, thisElement.Direction]; - float deltaLength = thisPlatform.Length - Length; // platform length - train length + float deltaLength = thisPlatform.Length - Length; // Platform length - train length - // get all sections which form platform + // Get all sections which form platform TCSubpathRoute platformRoute = signalRef.BuildTempRoute(this, beginSectionIndex, beginOffset, thisElement.Direction, thisPlatform.Length, true, true, false); int platformRouteIndex = platformRoute.GetRouteIndex(routeSectionIndex, 0); @@ -1553,7 +1466,7 @@ public override bool PostInit() float fullLength = thisPlatform.Length; - // path does not extend through station : adjust variables to last section + // Path does not extend through station: adjust variables to last section if (lastRouteIndex < 0) { lastRouteIndex = thisRoute.Count - 1; @@ -1562,10 +1475,10 @@ public override bool PostInit() endSectionIndex = lastRouteIndex; endSection = signalRef.TrackCircuitList[thisRoute[lastRouteIndex].TCSectionIndex]; endOffset = endSection.Length - 1.0f; - platformHasEndSignal = (endSection.EndSignals[thisRoute[lastRouteIndex].Direction] != null); + platformHasEndSignal = endSection.EndSignals[thisRoute[lastRouteIndex].Direction] != null; distanceToEndSignal = 1.0f; - float newLength = -beginOffset; // correct new length for begin offset + float newLength = -beginOffset; // Correct new length for begin offset for (int sectionRouteIndex = firstRouteIndex; sectionRouteIndex <= lastRouteIndex; sectionRouteIndex++) { TrackCircuitSection thisSection = signalRef.TrackCircuitList[thisRoute[sectionRouteIndex].TCSectionIndex]; @@ -1575,12 +1488,12 @@ public override bool PostInit() platformRoute = signalRef.BuildTempRoute(this, beginSectionIndex, beginOffset, thisElement.Direction, newLength, true, true, false); platformRouteIndex = routeIndex; - deltaLength = newLength - Length; // platform length - train length + deltaLength = newLength - Length; // Platform length - train length fullLength = newLength; } - // if required, check if there is a signal within the platform - // not possible if there is only one section + // If required, check if there is a signal within the platform + // Not possible if there is only one section else if (restrictPlatformToSignal && !platformHasEndSignal && firstRouteIndex != lastRouteIndex) { bool intermediateSignal = false; @@ -1598,7 +1511,7 @@ public override bool PostInit() } } - // if signal found, reset all end indicators + // If signal found, reset all end indicators if (intermediateSignal) { routeSectionIndex = signalRouteIndex; @@ -1626,13 +1539,13 @@ public override bool PostInit() } } - // extend platform to next signal - // only if required, platform has no signal and train does not fit into platform + // Extend platform to next signal + // Only if required, platform has no signal and train does not fit into platform else if (ExtendPlatformToSignal && !platformHasEndSignal && deltaLength < 0) { bool nextSignal = false; - // find next signal in route + // Find next signal in route for (int sectionRouteIndex = lastRouteIndex + 1; sectionRouteIndex < thisRoute.Count; sectionRouteIndex++) { TrackCircuitSection thisSection = signalRef.TrackCircuitList[thisRoute[sectionRouteIndex].TCSectionIndex]; @@ -1647,7 +1560,7 @@ public override bool PostInit() } - // if signal found, reset all end indicators + // If signal found, reset all end indicators if (nextSignal) { routeSectionIndex = signalRouteIndex; @@ -1660,8 +1573,8 @@ public override bool PostInit() endSection = signalSection; - float newLength = -beginOffset + endOffset; // correct new length for begin offset and end offset - // do not add last section as that is included through endOffset + float newLength = -beginOffset + endOffset; // Correct new length for begin offset and end offset + // Do not add last section as that is included through endOffset for (int sectionRouteIndex = firstRouteIndex; sectionRouteIndex < lastRouteIndex; sectionRouteIndex++) { TrackCircuitSection thisSection = signalRef.TrackCircuitList[thisRoute[sectionRouteIndex].TCSectionIndex]; @@ -1671,12 +1584,12 @@ public override bool PostInit() platformRoute = signalRef.BuildTempRoute(this, beginSectionIndex, beginOffset, thisElement.Direction, newLength, true, true, false); platformRouteIndex = routeIndex; - deltaLength = newLength - Length; // platform length - train length + deltaLength = newLength - Length; // Platform length - train length fullLength = newLength; } } - // calculate corrected offsets related to last section + // Calculate corrected offsets related to last section float beginOffsetCorrection = 0; float endOffsetCorrection = 0; @@ -1718,14 +1631,12 @@ public override bool PostInit() endOffset += endOffsetCorrection; } - // relate beginoffset and endoffset to section defined as platform section - - // if station is terminal, check if train is starting or terminating, and set stop position at 0.5 clearing distance from end - + // Relate `beginoffset` and `endoffset` to section defined as platform section + // If station is terminal, check if train is starting or terminating, and set stop position at 0.5 clearing distance from end float stopOffset = 0; - bool forceThroughSignal = false; // set if rear clearance is defined with force parameter + bool forceThroughSignal = false; // Set if rear clearance is defined with force parameter - // check for terminal position + // Check for terminal position if (terminal) { int startRouteIndex = firstRouteIndex < lastRouteIndex ? firstRouteIndex : lastRouteIndex; @@ -1734,38 +1645,28 @@ public override bool PostInit() bool routeNodeBeforeStart = false; bool routeNodeAfterEnd = false; - // check if any junctions in path before start + // Check if any junctions in path before start for (int iIndex = 0; iIndex < startRouteIndex && !routeNodeBeforeStart; iIndex++) { - routeNodeBeforeStart = (signalRef.TrackCircuitList[thisRoute[iIndex].TCSectionIndex].CircuitType == TrackCircuitSection.TrackCircuitType.Junction); + routeNodeBeforeStart = signalRef.TrackCircuitList[thisRoute[iIndex].TCSectionIndex].CircuitType == TrackCircuitSection.TrackCircuitType.Junction; } - // check if any junctions in path after end + // Check if any junctions in path after end for (int iIndex = lastRouteIndex + 1; iIndex < (thisRoute.Count - 1) && !routeNodeAfterEnd; iIndex++) { - routeNodeAfterEnd = (signalRef.TrackCircuitList[thisRoute[iIndex].TCSectionIndex].CircuitType == TrackCircuitSection.TrackCircuitType.Junction); + routeNodeAfterEnd = signalRef.TrackCircuitList[thisRoute[iIndex].TCSectionIndex].CircuitType == TrackCircuitSection.TrackCircuitType.Junction; } - // check if terminal is at start of route - if (firstRouteIndex == 0 || !routeNodeBeforeStart) - { - stopOffset = beginOffset + (0.5f * clearingDistanceM) + Length; - } - // if at end of route use closeup distance - else if (lastRouteIndex == thisRoute.Count - 1 || !routeNodeAfterEnd) - { - stopOffset = endOffset - keepDistanceCloseupM; - } - // if inbetween use safety distance - else - { - stopOffset = endOffset - (0.5f * clearingDistanceM); - } + // Check if terminal is at start of route + stopOffset = firstRouteIndex == 0 || !routeNodeBeforeStart + ? beginOffset + (0.5f * clearingDistanceM) + Length + : lastRouteIndex == thisRoute.Count - 1 || !routeNodeAfterEnd + ? endOffset - keepDistanceCloseupM + : endOffset - (0.5f * clearingDistanceM); } - - // if train too long : search back for platform with same name else { + // Train is too long: search back for platform with same name if (deltaLength < 0) { float actualBegin = beginOffset; @@ -1773,7 +1674,6 @@ public override bool PostInit() TrackCircuitSection thisSection = signalRef.TrackCircuitList[beginSectionIndex]; // Other platforms in same section - if (thisSection.PlatformIndex.Count > 1) { foreach (int nextIndex in thisSection.PlatformIndex) @@ -1799,7 +1699,6 @@ public override bool PostInit() int addRouteIndex = thisRoute.GetRouteIndex(otherSectionIndex, 0); float addOffset = otherPlatform.TCOffset[1, thisElement.Direction == 0 ? 1 : 0]; // offset of begin in other direction is length of available track - if (lastRouteIndex > 0) { float thisLength = @@ -1817,8 +1716,7 @@ public override bool PostInit() deltaLength = fullLength - Length; } - // search back along route - + // Search back along route if (deltaLength < 0) { float distance = fullLength + beginOffset; @@ -1837,8 +1735,8 @@ public override bool PostInit() if (String.Compare(otherPlatform.Name, thisPlatform.Name) == 0) { fullLength = otherPlatform.Length + distance; - // we miss a little bit (offset) - that's because we don't know direction of other platform - platformFound = true; // only check for one more + // We miss a little bit (offset) - that's because we don't know direction of other platform + platformFound = true; // Only check for one more } } distance += nextSection.Length; @@ -1847,51 +1745,51 @@ public override bool PostInit() deltaLength = fullLength - Length; } - // default stopposition : place train in middle of platform + // Default stop position: place train in middle of platform stopOffset = endOffset - (0.5f * deltaLength); - // check if position is not beyond end of route + // Check if position is not beyond end of route TrackCircuitSection followingSection = signalRef.TrackCircuitList[endSectionIndex]; float remLength = followingSection.Length - endOffset; - for (int iSection = lastRouteIndex + 1; iSection < thisRoute.Count; iSection++ ) + for (int iSection = lastRouteIndex + 1; iSection < thisRoute.Count; iSection++) { followingSection = signalRef.TrackCircuitList[thisRoute[iSection].TCSectionIndex]; remLength += followingSection.Length; if (followingSection.CircuitType == TrackCircuitSection.TrackCircuitType.EndOfTrack) { - remLength -= keepDistanceCloseupM; // stay clear from end of track + remLength -= keepDistanceCloseupM; // Stay clear from end of track } - if (remLength > (0.5f * deltaLength)) break; // stop check if length exceeds required overshoot + if (remLength > (0.5f * deltaLength)) break; // Stop check if length exceeds required overshoot } stopOffset = Math.Min(stopOffset, endOffset + remLength); - // keep clear at front + // Keep clear at front if (keepClearFront.HasValue) { - // if force position is set, stop train as required regardless of rear position of train + // If force position is set, stop train as required regardless of rear position of train if (forcePosition) { stopOffset = endOffset - keepClearFront.Value; } - else - // keep clear at front but ensure train is in station + else { - float frontClear = Math.Min(keepClearFront.Value, (endOffset - Length - beginOffset)); + // Keep clear at front but ensure train is in station + float frontClear = Math.Min(keepClearFront.Value, endOffset - Length - beginOffset); if (frontClear > 0) stopOffset = endOffset - frontClear; } } else if (keepClearRear.HasValue) { - // if force position is set, stop train as required regardless of front position of train - // reset hold signal state if front position is passed signal + // If force position is set, stop train as required regardless of front position of train + // Reset hold signal state if front position is passed signal if (forcePosition) { stopOffset = beginOffset + keepClearRear.Value + Length; forceThroughSignal = true; - // beyond original platform and beyond section : check for route validity (may not exceed route) + // Beyond original platform and beyond section : check for route validity (may not exceed route) if (stopOffset > endOffset && stopOffset > endSection.Length) { float addOffset = stopOffset - endOffset; @@ -1909,30 +1807,29 @@ public override bool PostInit() } else { - // check if space available between end of platform and exit signal + // Check if space available between end of platform and exit signal float endPosition = endOffset; if (platformHasEndSignal) { - endPosition = endOffset + distanceToEndSignal; // distance to signal + endPosition = endOffset + distanceToEndSignal; // Distance to signal endPosition = closeupSignal ? (endPosition - keepDistanceCloseupSignalM - 1.0f) : (endPosition - clearingDistanceM - 1.0f); // correct for clearing distance } - stopOffset = Math.Min((beginOffset + keepClearRear.Value + Length), endPosition); + stopOffset = Math.Min(beginOffset + keepClearRear.Value + Length, endPosition); + // TODO: Remove? //float rearClear = Math.Min(keepClearRear.Value, (endOffset - stopOffset)); //if (rearClear > 0) stopOffset = beginOffset + rearClear + Length; } } } - // check if stop offset beyond end signal - do not hold at signal - + // Check if stop offset beyond end signal - do not hold at signal int EndSignal = -1; bool HoldSignal = false; - // check if train is to reverse in platform - // if so, set signal at other end as hold signal - + // Check if train is to reverse in platform + // If so, set signal at other end as hold signal int useDirection = thisElement.Direction; bool inDirection = true; @@ -1947,21 +1844,20 @@ public override bool PostInit() } } - // check for end signal - + // Check for end signal if (inDirection) { if (distanceToEndSignal >= 0) { EndSignal = thisPlatform.EndSignals[useDirection]; - // stop location is in front of signal + // Stop location is in front of signal if (distanceToEndSignal > (stopOffset - endOffset)) { HoldSignal = true; - // check if stop is too close to signal - // if platform length is forced always use closeup + // Check if stop is too close to signal + // If platform length is forced always use closeup if (ExtendPlatformToSignal || restrictPlatformToSignal) { stopOffset = Math.Min(stopOffset, endOffset + distanceToEndSignal - keepDistanceCloseupSignalM - 1.0f); @@ -1976,10 +1872,10 @@ public override bool PostInit() else { stopOffset = endOffset + distanceToEndSignal - clearingDistanceM - 1.0f; - // check if train still fits in platform + // Check if train still fits in platform if ((stopOffset - beginOffset) < Length) { - float keepDistanceM = Math.Max((0.5f * clearingDistanceM), (endOffset + distanceToEndSignal) - (beginOffset + Length)); + float keepDistanceM = Math.Max(0.5f * clearingDistanceM, endOffset + distanceToEndSignal - (beginOffset + Length)); stopOffset = endOffset + distanceToEndSignal - keepDistanceM; } } @@ -1997,44 +1893,39 @@ public override bool PostInit() } } } - // reset hold signal if stop is forced beyond signal else if (forceThroughSignal) { + // Reset hold signal if stop is forced beyond signal HoldSignal = false; EndSignal = -1; } - // if most of train fits in platform then stop at signal else if ((distanceToEndSignal - clearingDistanceM + thisPlatform.Length) > (0.6 * Length)) { + // If most of train fits in platform then stop at signal HoldSignal = true; - if (closeupSignal || ExtendPlatformToSignal || restrictPlatformToSignal) - { - stopOffset = endOffset + distanceToEndSignal - keepDistanceCloseupSignalM - 1.0f; - } - else - { - stopOffset = endOffset + distanceToEndSignal - clearingDistanceM - 1.0f; - } - // set 1m earlier to give priority to station stop over signal + stopOffset = closeupSignal || ExtendPlatformToSignal || restrictPlatformToSignal + ? endOffset + distanceToEndSignal - keepDistanceCloseupSignalM - 1.0f + : endOffset + distanceToEndSignal - clearingDistanceM - 1.0f; + // Set 1m earlier to give priority to station stop over signal } - // if platform positions forced always use closeup else if (ExtendPlatformToSignal || restrictPlatformToSignal) { + // If platform positions forced always use closeup HoldSignal = true; stopOffset = endOffset + distanceToEndSignal - keepDistanceCloseupSignalM - 1.0f; - // set 1m earlier to give priority to station stop over signal + // Set 1m earlier to give priority to station stop over signal } - // train does not fit in platform - reset exit signal else { + // Train does not fit in platform - reset exit signal EndSignal = -1; } } } else - // check in reverse direction - // end of train is beyond signal { + // Check in reverse direction + // End of train is beyond signal if (thisPlatform.EndSignals[useDirection] >= 0) { if ((beginOffset - thisPlatform.DistanceToSignals[useDirection]) < (stopOffset - Length)) @@ -2046,44 +1937,44 @@ public override bool PostInit() stopOffset = beginOffset - thisPlatform.DistanceToSignals[useDirection] + Length + clearingDistanceM + 1.0f; } } - // if most of train fits in platform then stop at signal + // If most of train fits in platform then stop at signal else if ((thisPlatform.DistanceToSignals[useDirection] - clearingDistanceM + thisPlatform.Length) > (0.6 * Length)) { - // set 1m earlier to give priority to station stop over signal + // Set 1m earlier to give priority to station stop over signal stopOffset = beginOffset - thisPlatform.DistanceToSignals[useDirection] + Length + clearingDistanceM + 1.0f; - // check if stop is clear of end signal (if any) + // Check if stop is clear of end signal (if any) if (thisPlatform.EndSignals[thisElement.Direction] != -1) { if (stopOffset < (endOffset + thisPlatform.DistanceToSignals[thisElement.Direction])) { - HoldSignal = true; // if train fits between signals + HoldSignal = true; // If train fits between signals } else { - stopOffset = endOffset + thisPlatform.DistanceToSignals[thisElement.Direction] - 1.0f; // stop at end signal + stopOffset = endOffset + thisPlatform.DistanceToSignals[thisElement.Direction] - 1.0f; // Stop at end signal } } } - // train does not fit in platform - reset exit signal else { + // Train does not fit in platform - reset exit signal EndSignal = -1; } } } - // store details + // Store details TCRouteElement lastElement = thisRoute[lastRouteIndex]; dummyStop.TCSectionIndex = lastElement.TCSectionIndex; dummyStop.Direction = lastElement.Direction; dummyStop.ExitSignal = EndSignal; - dummyStop.HoldSignal = EndSignal >= 0 ? HoldSignal : false; + dummyStop.HoldSignal = EndSignal >= 0 && HoldSignal; dummyStop.StopOffset = stopOffset; dummyStop.RouteIndex = lastRouteIndex; - return (dummyStop); + return dummyStop; } /// @@ -2104,7 +1995,7 @@ public override bool PostInit() /// /// public bool CreateStationStop(int platformStartID, int arrivalTime, int departTime, DateTime arrivalDT, DateTime departureDT, float clearingDistanceM, - float minStopDistanceM, bool terminal, int? actMinStopTime, float? keepClearFront, float? keepClearRear, bool forcePosition, bool closeupSignal, + float minStopDistanceM, bool terminal, int? actMinStopTime, float? keepClearFront, float? keepClearRear, bool forcePosition, bool closeupSignal, bool closeup, bool restrictPlatformToSignal, bool extendPlatformToSignal, bool endStop) { StationStop thisStation = CalculateStationStop(platformStartID, arrivalTime, departTime, arrivalDT, departureDT, clearingDistanceM, @@ -2118,8 +2009,7 @@ public override bool PostInit() StationStops.Add(thisStation); - // if station has hold signal and this signal is the same as the exit signal for previous station, remove the exit signal from the previous station - + // If station has hold signal and this signal is the same as the exit signal for previous station, remove the exit signal from the previous station if (HoldSignal && StationStops.Count > 1) { if (EndSignal == StationStops[StationStops.Count - 2].ExitSignal && StationStops[StationStops.Count - 2].HoldSignal) @@ -2133,8 +2023,7 @@ public override bool PostInit() } } - // add signal to list of hold signals - + // Add signal to list of hold signals if (HoldSignal) { HoldingSignals.Add(EndSignal); @@ -2146,7 +2035,7 @@ public override bool PostInit() } else { - return (false); + return false; } #if DEBUG_TEST @@ -2185,7 +2074,7 @@ public override bool PostInit() } #endif - return (true); + return true; } //================================================================================================// @@ -2193,32 +2082,29 @@ public override bool PostInit() /// Check initial station /// Override from AITrain class /// <\summary> - public override bool CheckInitialStation() { bool atStation = false; - if (FormedOf > 0 && AtStation) // if train was formed and at station, train is in initial station + if (FormedOf > 0 && AtStation) // If train was formed and at station, train is in initial station { - return (true); + return true; } - // get station details - + // Get station details StationStop thisStation = StationStops[0]; if (thisStation.SubrouteIndex != TCRoute.activeSubpath) { - return (false); + return false; } if (thisStation.ActualStopType != StationStop.STOPTYPE.STATION_STOP) { - return (false); + return false; } atStation = CheckStationPosition(thisStation.PlatformItem, thisStation.Direction, thisStation.TCSectionIndex); - // At station : set state, create action item - + // At station: set state, create action item if (atStation) { thisStation.ActualArrival = -1; @@ -2238,7 +2124,7 @@ public override bool CheckInitialStation() #endif } - return (atStation); + return atStation; } /// @@ -2251,7 +2137,7 @@ public override bool CheckInitialStation() public override bool CheckStationPosition(PlatformDetails thisPlatform, int stationDirection, int stationTCSectionIndex) { bool atStation = false; - // PlatformDetails thisPlatform = thisStation.PlatformItem; + // PlatformDetails thisPlatform = thisStation.PlatformItem; // TODO: Remove? float platformBeginOffset = thisPlatform.TCOffset[0, stationDirection]; float platformEndOffset = thisPlatform.TCOffset[1, stationDirection]; @@ -2265,46 +2151,42 @@ public override bool CheckStationPosition(PlatformDetails thisPlatform, int stat thisPlatform.TCSectionIndex[0]; int beginSectionRouteIndex = ValidRoute[0].GetRouteIndex(beginSectionIndex, 0); - // check position - + // Check position float margin = 0.0f; if (Simulator.PreUpdate) - margin = 2.0f * clearingDistanceM; // allow margin in pre-update due to low update rate + margin = 2.0f * clearingDistanceM; // Allow margin in pre-update due to low update rate int stationIndex = ValidRoute[0].GetRouteIndex(stationTCSectionIndex, PresentPosition[0].RouteListIndex); - // if not found from front of train, try from rear of train (front may be beyond platform) + // If not found from front of train, try from rear of train (front may be beyond platform) if (stationIndex < 0) { stationIndex = ValidRoute[0].GetRouteIndex(stationTCSectionIndex, PresentPosition[1].RouteListIndex); } - // if rear is in platform, station is valid if (PresentPosition[1].RouteListIndex == stationIndex && PresentPosition[1].TCOffset > platformEndOffset) { + // If rear is in platform, station is valid atStation = true; } - - // if front is in platform and most of the train is as well, station is valid else if (PresentPosition[0].RouteListIndex == stationIndex && ((thisPlatform.Length - (platformBeginOffset - PresentPosition[0].TCOffset)) > (Length / 2))) { + // If front is in platform and most of the train is as well, station is valid atStation = true; } - - // if front is beyond platform and rear is not on route or before platform : train spans platform else if (PresentPosition[0].RouteListIndex > stationIndex && PresentPosition[1].RouteListIndex < stationIndex) { + // If front is beyond platform and rear is not on route or before platform: train spans platform atStation = true; } - - // if front is beyond platform and rear is in platform section but ahead of position : train spans platform else if (PresentPosition[0].RouteListIndex > stationIndex && PresentPosition[1].RouteListIndex == stationIndex && PresentPosition[1].TCOffset < platformEndOffset) { + // If front is beyond platform and rear is in platform section but ahead of position: train spans platform atStation = true; } - - return (atStation); + + return atStation; } //================================================================================================// @@ -2312,50 +2194,48 @@ public override bool CheckStationPosition(PlatformDetails thisPlatform, int stat /// Check for next station /// Override from AITrain /// <\summary> - public override void SetNextStationAction(bool fromAutopilotSwitch = false) { - // do not set action if stopped in station + // Do not set action if stopped in station if (MovementState == AI_MOVEMENT_STATE.STATION_STOP || AtStation) { return; } - // check if station in this subpath - + // Check if station in this subpath int stationIndex = 0; StationStop thisStation = StationStops[stationIndex]; - while (thisStation.SubrouteIndex < TCRoute.activeSubpath) // station was in previous subpath + while (thisStation.SubrouteIndex < TCRoute.activeSubpath) // Station was in previous subpath { StationStops.RemoveAt(0); - if (StationStops.Count == 0) // no more stations + if (StationStops.Count == 0) // No more stations { return; } thisStation = StationStops[0]; } - if (thisStation.SubrouteIndex > TCRoute.activeSubpath) // station is not in this subpath + if (thisStation.SubrouteIndex > TCRoute.activeSubpath) // Station is not in this subpath { return; } - // get distance to station, but not if just after switch to Autopilot and not during station stop + // Get distance to station, but not if just after switch to Autopilot and not during station stop bool validStop = false; while (!validStop) { float[] distancesM = CalculateDistancesToNextStation(thisStation, TrainMaxSpeedMpS, false); - if (distancesM[0] < 0f && !(MovementState == AI_MOVEMENT_STATE.STATION_STOP && distancesM[0] != -1)) // stop is not valid + if (distancesM[0] < 0f && !(MovementState == AI_MOVEMENT_STATE.STATION_STOP && distancesM[0] != -1)) // Stop is not valid { StationStops.RemoveAt(0); if (StationStops.Count == 0) { - return; // no more stations - exit + return; // No more stations - exit } thisStation = StationStops[0]; - if (thisStation.SubrouteIndex > TCRoute.activeSubpath) return; // station not in this subpath - exit + if (thisStation.SubrouteIndex > TCRoute.activeSubpath) return; // Station not in this subpath - exit } else { @@ -2436,7 +2316,7 @@ public void RecalculateStationStops(bool atStation) PlatformDetails thisPlatform = actualStation.PlatformItem; StationStop newStop = CalculateStationStopPosition(TCRoute.TCRouteSubpaths[actualStation.SubrouteIndex], actualStation.RouteIndex, actualStation.PlatformItem, - actualStation.SubrouteIndex, actualStation.KeepClearFront, actualStation.KeepClearRear, actualStation.ForcePosition, + actualStation.SubrouteIndex, actualStation.KeepClearFront, actualStation.KeepClearRear, actualStation.ForcePosition, actualStation.CloseupSignal, actualStation.Closeup, actualStation.RestrictPlatformToSignal, actualStation.ExtendPlatformToSignal, actualStation.Terminal, actualStation.PlatformReference); @@ -2454,10 +2334,9 @@ public void RecalculateStationStops(bool atStation) /// /// /// - public bool StartFromAITrain(TTTrain otherTrain, int presentTime, TrackCircuitSection[] occupiedTrack) { - // check if new train has route at present position of front of train + // Check if new train has route at present position of front of train int usedRefPosition = 0; int startPositionIndex = TCRoute.TCRouteSubpaths[0].GetRouteIndex(otherTrain.PresentPosition[0].TCSectionIndex, 0); int usedPositionIndex = startPositionIndex; @@ -2470,12 +2349,12 @@ public bool StartFromAITrain(TTTrain otherTrain, int presentTime, TrackCircuitSe usedPositionIndex = rearPositionIndex; } - // if not found - train cannot start out of other train as there is no valid route - let train start of its own + // If not found - train cannot start out of other train as there is no valid route - let train start of its own if (startPositionIndex < 0 && rearPositionIndex < 0) { FormedOf = -1; FormedOfType = FormCommand.None; - return (false); + return false; } OccupiedTrack.Clear(); @@ -2487,8 +2366,7 @@ public bool StartFromAITrain(TTTrain otherTrain, int presentTime, TrackCircuitSe int addedSections = AdjustTrainRouteOnStart(startPositionIndex, rearPositionIndex, otherTrain); usedPositionIndex += addedSections; - // copy consist information incl. max speed and type - + // Copy consist information incl. max speed and type if (FormedOfType == FormCommand.TerminationFormed) { Cars.Clear(); @@ -2505,7 +2383,7 @@ public bool StartFromAITrain(TTTrain otherTrain, int presentTime, TrackCircuitSe MassKg = otherTrain.MassKg; LeadLocomotiveIndex = otherTrain.LeadLocomotiveIndex; - // copy other train speed if not restricted for either train + // Copy other train speed if not restricted for either train if (!otherTrain.SpeedSettings.restrictedSet && !SpeedSettings.restrictedSet) { TrainMaxSpeedMpS = otherTrain.TrainMaxSpeedMpS; @@ -2517,13 +2395,12 @@ public bool StartFromAITrain(TTTrain otherTrain, int presentTime, TrackCircuitSe FrontTDBTraveller = new Traveller(otherTrain.FrontTDBTraveller); RearTDBTraveller = new Traveller(otherTrain.RearTDBTraveller); - // check if train reversal is required - + // Check if train reversal is required if (TCRoute.TCRouteSubpaths[0][usedPositionIndex].Direction != otherTrain.PresentPosition[usedRefPosition].TCDirection) { ReverseFormation(false); - // if reversal is required and units must be detached at start : reverse detached units position + // If reversal is required and units must be detached at start : reverse detached units position if (DetachDetails.ContainsKey(-1)) { List detachList = DetachDetails[-1]; @@ -2578,25 +2455,25 @@ public bool StartFromAITrain(TTTrain otherTrain, int presentTime, TrackCircuitSe InitialTrainPlacement(true); } - // set state + // Set state MovementState = AI_MOVEMENT_STATE.AI_STATIC; ControlMode = TRAIN_CONTROL.INACTIVE; int eightHundredHours = 8 * 3600; int sixteenHundredHours = 16 * 3600; - // if no activate time, set to now + 30 if (!ActivateTime.HasValue) { + // If no activate time, set to now + 30 ActivateTime = presentTime + 30; } - // if activate time < 08:00 and present time > 16:00, assume activate time is after midnight else if (ActivateTime.Value < eightHundredHours && presentTime > sixteenHundredHours) { + // If activate time < 08:00 and present time > 16:00, assume activate time is after midnight ActivateTime = ActivateTime.Value + (24 * 3600); } - return (true); + return true; } //================================================================================================// @@ -2604,13 +2481,12 @@ public bool StartFromAITrain(TTTrain otherTrain, int presentTime, TrackCircuitSe /// Update for pre-update state /// Override from AITrain class /// <\summary> - public override void AIPreUpdate(float elapsedClockSeconds) { - // calculate delta speed and speed + // Calculate delta speed and speed float distanceM = physicsPreUpdate(elapsedClockSeconds); - // force stop - no forced stop if mode is following and attach is true + // Force stop - no forced stop if mode is following and attach is true if (distanceM > NextStopDistanceM) { #if DEBUG_REPORTS @@ -2627,6 +2503,7 @@ public override void AIPreUpdate(float elapsedClockSeconds) File.AppendAllText(@"C:\temp\checktrain.txt", "Train " + Number.ToString() + " forced stop : calculated " + FormatStrings.FormatSpeed(SpeedMpS, true) + " > " + + // TODO: Remove? //FormatStrings.FormatDistance(distanceM, true) + " set to " + //"0.0 > " + FormatStrings.FormatDistance(NextStopDistanceM, true) + " at " + //FormatStrings.FormatDistance(DistanceTravelledM, true) + "\n"); @@ -2639,44 +2516,35 @@ public override void AIPreUpdate(float elapsedClockSeconds) SpeedMpS = 0; } - // set speed and position - + // Set speed and position foreach (TrainCar car in Cars) { - if (car.Flipped) - { - car.SpeedMpS = -SpeedMpS; - } - else - { - car.SpeedMpS = SpeedMpS; - } + car.SpeedMpS = car.Flipped ? -SpeedMpS : SpeedMpS; } CalculatePositionOfCars(elapsedClockSeconds, distanceM); DistanceTravelledM += distanceM; - // perform overall update - + // Perform overall update if (ControlMode == TRAIN_CONTROL.TURNTABLE) { UpdateTurntable(elapsedClockSeconds); } - else if (ValidRoute != null && MovementState != AI_MOVEMENT_STATE.AI_STATIC) // no actions required for static objects // + else if (ValidRoute != null && MovementState != AI_MOVEMENT_STATE.AI_STATIC) // No actions required for static objects { - movedBackward = CheckBackwardClearance(); // check clearance at rear // - UpdateTrainPosition(); // position update // - UpdateTrainPositionInformation(); // position linked info // - int SignalObjIndex = CheckSignalPassed(0, PresentPosition[0], PreviousPosition[0]); // check if passed signal // - UpdateSectionState(movedBackward); // update track occupation // - ObtainRequiredActions(movedBackward); // process Actions // - UpdateRouteClearanceAhead(SignalObjIndex, movedBackward, elapsedClockSeconds); // update route clearance // - UpdateSignalState(movedBackward); // update signal state // + movedBackward = CheckBackwardClearance(); // Check clearance at rear + UpdateTrainPosition(); // Position update + UpdateTrainPositionInformation(); // Pposition linked info + int SignalObjIndex = CheckSignalPassed(0, PresentPosition[0], PreviousPosition[0]); // Check if passed signal + UpdateSectionState(movedBackward); // Update track occupation + ObtainRequiredActions(movedBackward); // Process Actions + UpdateRouteClearanceAhead(SignalObjIndex, movedBackward, elapsedClockSeconds); // Update route clearance + UpdateSignalState(movedBackward); // Update signal state UpdateMinimalDelay(); - // if train ahead and approaching turntable, check if train is beyond turntable + // If train ahead and approaching turntable, check if train is beyond turntable if (ValidRoute[0].Last().MovingTableApproachPath > -1 && EndAuthorityType[0] == END_AUTHORITY.TRAIN_AHEAD) { CheckTrainBeyondTurntable(); @@ -2689,13 +2557,11 @@ public override void AIPreUpdate(float elapsedClockSeconds) /// /// Update train physics during Pre-Update /// <\summary> - public float physicsPreUpdate(float elapsedClockSeconds) { // Update train physics, position and movement // Simplified calculation for use in pre-update phase - PropagateBrakePressure(elapsedClockSeconds); float massKg = 0f; @@ -2717,24 +2583,22 @@ public float physicsPreUpdate(float elapsedClockSeconds) UpdateCarSpeeds(elapsedClockSeconds); float distanceM = LastCar.SpeedMpS * elapsedClockSeconds; - if (Math.Abs(distanceM) < 0.1f) distanceM = 0.0f; //clamp to avoid movement due to calculation noise - if (float.IsNaN(distanceM)) distanceM = 0; //avoid NaN, if so will not move + if (Math.Abs(distanceM) < 0.1f) distanceM = 0.0f; // Clamp to avoid movement due to calculation noise + if (float.IsNaN(distanceM)) distanceM = 0; // Avoid NaN, if so will not move if (TrainType == TRAINTYPE.AI && LeadLocomotiveIndex == (Cars.Count - 1) && LastCar.Flipped) distanceM = -distanceM; - return (distanceM); + return distanceM; } //================================================================================================// /// /// Update train /// - public override void Update(float elapsedClockSeconds, bool auxiliaryUpdate = true) { // Update train physics, position and movement - #if DEBUG_CHECKTRAIN if (!CheckTrain) { @@ -2760,8 +2624,7 @@ public override void Update(float elapsedClockSeconds, bool auxiliaryUpdate = tr // Check to see if wagons are attached to train WagonsAttached = GetWagonsAttachedIndication(); - //Exit here when train is static consist (no further actions required) - + // Exit here when train is static consist (no further actions required) if (GetAIMovementState() == AITrain.AI_MOVEMENT_STATE.AI_STATIC) { int presentTime = Convert.ToInt32(Math.Floor(Simulator.ClockTime)); @@ -2771,14 +2634,12 @@ public override void Update(float elapsedClockSeconds, bool auxiliaryUpdate = tr if (TrainType == TRAINTYPE.STATIC) return; - // perform overall update - - if (ControlMode == TRAIN_CONTROL.MANUAL) // manual mode + // Perform overall update + if (ControlMode == TRAIN_CONTROL.MANUAL) // Manual mode { UpdateManual(elapsedClockSeconds); } - - else if (TrainType == TRAINTYPE.PLAYER && ControlMode == TRAIN_CONTROL.TURNTABLE) // turntable mode + else if (TrainType == TRAINTYPE.PLAYER && ControlMode == TRAIN_CONTROL.TURNTABLE) // Turntable mode { string infoString = String.Copy("Do NOT move the train"); @@ -2792,20 +2653,20 @@ public override void Update(float elapsedClockSeconds, bool auxiliaryUpdate = tr } Simulator.Confirmer.Warning(infoString); - ActiveTurntable.UpdateTurntableStatePlayer(elapsedClockSeconds); // update turntable state + ActiveTurntable.UpdateTurntableStatePlayer(elapsedClockSeconds); // Update turntable state } - else if (ValidRoute[0] != null && GetAIMovementState() != AITrain.AI_MOVEMENT_STATE.AI_STATIC) // no actions required for static objects // + else if (ValidRoute[0] != null && GetAIMovementState() != AITrain.AI_MOVEMENT_STATE.AI_STATIC) // No actions required for static objects { - if (ControlMode != TRAIN_CONTROL.OUT_OF_CONTROL) movedBackward = CheckBackwardClearance(); // check clearance at rear if not out of control // - UpdateTrainPosition(); // position update // - UpdateTrainPositionInformation(); // position update // - int SignalObjIndex = CheckSignalPassed(0, PresentPosition[0], PreviousPosition[0]); // check if passed signal // - UpdateSectionState(movedBackward); // update track occupation // - ObtainRequiredActions(movedBackward); // process list of actions // + if (ControlMode != TRAIN_CONTROL.OUT_OF_CONTROL) movedBackward = CheckBackwardClearance(); // Check clearance at rear if not out of control + UpdateTrainPosition(); // Position update + UpdateTrainPositionInformation(); // Position update + int SignalObjIndex = CheckSignalPassed(0, PresentPosition[0], PreviousPosition[0]); // Check if passed signal + UpdateSectionState(movedBackward); // Update track occupation + ObtainRequiredActions(movedBackward); // Process list of actions bool stillExist = true; - if (TrainType == TRAINTYPE.PLAYER) // player train is to check own stations + if (TrainType == TRAINTYPE.PLAYER) // Player train is to check own stations { if (MovementState == AI_MOVEMENT_STATE.TURNTABLE) { @@ -2814,17 +2675,17 @@ public override void Update(float elapsedClockSeconds, bool auxiliaryUpdate = tr else { CheckStationTask(); - CheckPlayerAttachState(); // check for player attach + CheckPlayerAttachState(); // Check for player attach if (ControlMode != TRAIN_CONTROL.OUT_OF_CONTROL) { - stillExist = CheckRouteActions(elapsedClockSeconds); // check routepath (AI check at other point) // + stillExist = CheckRouteActions(elapsedClockSeconds); // Check routepath (AI check at other point) } } } if (stillExist && ControlMode != TRAIN_CONTROL.OUT_OF_CONTROL) { - UpdateRouteClearanceAhead(SignalObjIndex, movedBackward, elapsedClockSeconds); // update route clearance // + UpdateRouteClearanceAhead(SignalObjIndex, movedBackward, elapsedClockSeconds); // Update route clearance if (CheckTrain) { File.AppendAllText(@"C:\temp\checktrain.txt", "MovementState : " + MovementState.ToString() + " ; End Authority : " + EndAuthorityType[0].ToString() + "\n"); @@ -2832,10 +2693,10 @@ public override void Update(float elapsedClockSeconds, bool auxiliaryUpdate = tr if (MovementState != AI_MOVEMENT_STATE.TURNTABLE) { - UpdateSignalState(movedBackward); // update signal state but not when on turntable + UpdateSignalState(movedBackward); // Update signal state but not when on turntable } - // if train ahead and approaching turntable, check if train is beyond turntable + // If train ahead and approaching turntable, check if train is beyond turntable if (ValidRoute[0].Last().MovingTableApproachPath > -1 && EndAuthorityType[0] == END_AUTHORITY.TRAIN_AHEAD) { CheckTrainBeyondTurntable(); @@ -2843,26 +2704,23 @@ public override void Update(float elapsedClockSeconds, bool auxiliaryUpdate = tr } } - // calculate minimal delay (Timetable only) + // Calculate minimal delay (Timetable only) UpdateMinimalDelay(); - // check position of train wrt tunnels + // Check position of train wrt tunnels ProcessTunnels(); - // log train details - + // Log train details if (DatalogTrainSpeed) { LogTrainSpeed(Simulator.ClockTime); } - - } // end Update + } //================================================================================================// /// /// If approaching turntable and there is a train ahead, check if train is beyond turntable /// - public void CheckTrainBeyondTurntable() { TCRouteElement lastElement = ValidRoute[0].Last(); @@ -2880,7 +2738,7 @@ public void CheckTrainBeyondTurntable() if (lengthToGoM < DistanceToEndNodeAuthorityM[0]) { EndAuthorityType[0] = END_AUTHORITY.END_OF_PATH; - DistanceToEndNodeAuthorityM[0] = NextStopDistanceM = lengthToGoM + clearingDistanceM; // add clearing distance to avoid position lock short of turntable + DistanceToEndNodeAuthorityM[0] = NextStopDistanceM = lengthToGoM + clearingDistanceM; // Add clearing distance to avoid position lock short of turntable } } } @@ -2890,14 +2748,13 @@ public void CheckTrainBeyondTurntable() /// Calculate running delay if present time is later than next station arrival /// Override from Train class /// - public void UpdateMinimalDelay() { int presentTime = Convert.ToInt32(Math.Floor(Simulator.ClockTime)); if (TrainType == TRAINTYPE.AI) { - AITrain thisAI = this as AITrain; + AITrain thisAI = this; presentTime = Convert.ToInt32(Math.Floor(thisAI.AI.clockTime)); } @@ -2906,7 +2763,7 @@ public void UpdateMinimalDelay() if (presentTime > StationStops[0].ArrivalTime) { TimeSpan tempDelay = TimeSpan.FromSeconds((presentTime - StationStops[0].ArrivalTime) % (24 * 3600)); - //skip when delay exceeds 12 hours - that's due to passing midnight + // Skip when delay exceeds 12 hours - that's due to passing midnight if (tempDelay.TotalSeconds < (12 * 3600) && (!Delay.HasValue || tempDelay > Delay.Value)) { Delay = tempDelay; @@ -2914,17 +2771,12 @@ public void UpdateMinimalDelay() } } - // update max speed if separate cruise speed is set + // Update max speed if separate cruise speed is set if (SpeedSettings.cruiseSpeedMpS.HasValue) { - if (SpeedSettings.cruiseMaxDelayS.HasValue && Delay.HasValue && Delay.Value.TotalSeconds > SpeedSettings.cruiseMaxDelayS.Value) - { - TrainMaxSpeedMpS = SpeedSettings.maxSpeedMpS.Value; - } - else - { - TrainMaxSpeedMpS = SpeedSettings.cruiseSpeedMpS.Value; - } + TrainMaxSpeedMpS = SpeedSettings.cruiseMaxDelayS.HasValue && Delay.HasValue && Delay.Value.TotalSeconds > SpeedSettings.cruiseMaxDelayS.Value + ? SpeedSettings.maxSpeedMpS.Value + : SpeedSettings.cruiseSpeedMpS.Value; } } @@ -2944,7 +2796,6 @@ public override void TestAbsDelay(ref int delay, int correctedTime) /// Override from Train class /// /// - public override void UpdateAIStaticState(int presentTime) { #if DEBUG_CHECKTRAIN @@ -2970,7 +2821,7 @@ public override void UpdateAIStaticState(int presentTime) File.AppendAllText(@"C:\temp\checktrain.txt", "Train update AI state : " + Number + " ; type : " + TrainType + "\n"); } - // start if start time is reached + // Start if start time is reached bool reqActivate = false; if (ActivateTime.HasValue && !TriggeredActivationRequired) { @@ -2984,7 +2835,7 @@ public override void UpdateAIStaticState(int presentTime) maystart = false; } - // check if anything needs to attach or transfer + // Check if anything needs to attach or transfer if (reqActivate) { if (NeedAttach != null && NeedAttach.ContainsKey(-1)) @@ -3008,7 +2859,7 @@ public override void UpdateAIStaticState(int presentTime) } } - // check if anything needs be detached + // Check if anything needs be detached if (DetachDetails.ContainsKey(-1)) { List detachList = DetachDetails[-1]; @@ -3041,13 +2892,13 @@ public override void UpdateAIStaticState(int presentTime) if (detachList.Count <= 0) DetachDetails.Remove(-1); } - // check if other train must be activated + // Check if other train must be activated if (reqActivate) { ActivateTriggeredTrain(TriggerActivationType.Start, -1); } - // switch power + // Switch power if (reqActivate && TrainHasPower()) { if (CheckTrain) @@ -3091,8 +2942,7 @@ public override void UpdateAIStaticState(int presentTime) return; } - // switch off power for all engines until 20 secs before start - + // Switch off power for all engines until 20 secs before start if (ActivateTime.HasValue && TrainHasPower() && maystart) { if (PowerState && ActivateTime.Value < (presentTime - 20)) @@ -3107,7 +2957,7 @@ public override void UpdateAIStaticState(int presentTime) } PowerState = false; } - else if (!PowerState) // switch power on 20 secs before start + else if (!PowerState) // Switch power on 20 secs before start { foreach (var car in Cars) { @@ -3127,22 +2977,21 @@ public override void UpdateAIStaticState(int presentTime) /// Set reversal point action /// Override from AITrain class /// <\summary> - public override void SetReversalAction() { if (nextActionInfo != null && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.STATION_STOP) { - return; // station stop required - reversal not valid + return; // Station stop required - reversal not valid } - + if (nextActionInfo != null && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.REVERSAL) { - return; // other reversal still active - reversal not valid + return; // Other reversal still active - reversal not valid } if (StationStops != null && StationStops.Count > 0 && StationStops[0].SubrouteIndex == TCRoute.activeSubpath) { - return; // station stop required in this subpath - reversal not valid + return; // Station stop required in this subpath - reversal not valid } if (TCRoute.ReversalInfo[TCRoute.activeSubpath].Valid) @@ -3159,7 +3008,7 @@ public override void SetReversalAction() reqDistance = nextActionInfo != null ? Math.Min(nextActionInfo.RequiredDistance, reqDistance) : reqDistance; nextActionInfo = new AIActionItem(null, AIActionItem.AI_ACTION_TYPE.REVERSAL); - nextActionInfo.SetParam((PresentPosition[0].DistanceTravelledM - 1), 0.0f, reqDistance, PresentPosition[0].DistanceTravelledM); + nextActionInfo.SetParam(PresentPosition[0].DistanceTravelledM - 1, 0.0f, reqDistance, PresentPosition[0].DistanceTravelledM); MovementState = MovementState != AI_MOVEMENT_STATE.STOPPED ? AI_MOVEMENT_STATE.BRAKING : AI_MOVEMENT_STATE.STOPPED; } } @@ -3168,32 +3017,31 @@ public override void SetReversalAction() //================================================================================================// /// - /// change in authority state - check action + /// Change in authority state - check action /// Override from AITrain class /// <\summary> - public override void CheckRequiredAction() { - // check if train ahead + // Check if train ahead if (EndAuthorityType[0] == END_AUTHORITY.TRAIN_AHEAD) { if (MovementState != AI_MOVEMENT_STATE.STATION_STOP && MovementState != AI_MOVEMENT_STATE.STOPPED) { - MovementState = AI_MOVEMENT_STATE.FOLLOWING; // start following - CheckReadyToAttach(); // check for attach + MovementState = AI_MOVEMENT_STATE.FOLLOWING; // Start following + CheckReadyToAttach(); // Check for attach } } else if (EndAuthorityType[0] == END_AUTHORITY.RESERVED_SWITCH || EndAuthorityType[0] == END_AUTHORITY.LOOP || EndAuthorityType[0] == END_AUTHORITY.NO_PATH_RESERVED) { ResetActions(true); - NextStopDistanceM = DistanceToEndNodeAuthorityM[0] - 2.0f * junctionOverlapM; + NextStopDistanceM = DistanceToEndNodeAuthorityM[0] - (2.0f * junctionOverlapM); CreateTrainAction(SpeedMpS, 0.0f, NextStopDistanceM, null, AIActionItem.AI_ACTION_TYPE.END_OF_AUTHORITY); } - // first handle outstanding actions else if (EndAuthorityType[0] == END_AUTHORITY.END_OF_PATH && (nextActionInfo == null || nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.END_OF_ROUTE)) { + // First handle outstanding actions ResetActions(false); NextStopDistanceM = DistanceToEndNodeAuthorityM[0] - clearingDistanceM; } @@ -3204,14 +3052,13 @@ public override void CheckRequiredAction() /// Update train in stopped state /// Override from AITrain class /// <\summary> - public override AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockSeconds) { - // check if restart is delayed + // Check if restart is delayed if (DelayedStart && Simulator.Settings.TTUseRestartDelays) { RestdelayS -= elapsedClockSeconds; - if (RestdelayS <= 0) // wait time has elapsed - start moving + if (RestdelayS <= 0) // Wait time has elapsed - start moving { DelayedStart = false; RestdelayS = 0; @@ -3227,29 +3074,26 @@ public override AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockS File.AppendAllText(@"C:\temp\checktrain.txt", "Train " + Number + " : start moving \n"); } - return (MovementState); + return MovementState; } - else if (RestdelayS > 0) { - RestdelayS -= elapsedClockSeconds; // decrease pre-restart wait time while stopped + RestdelayS -= elapsedClockSeconds; // Decrease pre-restart wait time while stopped } - if (SpeedMpS > 0 || SpeedMpS < 0) // if train still running force it to stop + if (SpeedMpS > 0 || SpeedMpS < 0) // If train still running force it to stop { SpeedMpS = 0; - Update(0); // stop the wheels from moving etc + Update(0); // Stop the wheels from moving etc AITrainThrottlePercent = 0; AITrainBrakePercent = 100; } - // check if train ahead - if so, determine speed and distance - + // Check if train ahead - if so, determine speed and distance if (ControlMode == TRAIN_CONTROL.AUTO_NODE && EndAuthorityType[0] == END_AUTHORITY.TRAIN_AHEAD) { - - // check if train ahead is in same section + // Check if train ahead is in same section int sectionIndex = PresentPosition[0].TCSectionIndex; int startIndex = ValidRoute[0].GetRouteIndex(sectionIndex, 0); int endIndex = ValidRoute[0].GetRouteIndex(LastReservedSection[0], 0); @@ -3263,7 +3107,7 @@ public override AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockS addOffset = thisSection.Length - PresentPosition[0].TCOffset; } - // train not in this section, try reserved sections ahead + // Train not in this section, try reserved sections ahead for (int iIndex = startIndex + 1; iIndex <= endIndex && trainInfo.Count <= 0; iIndex++) { TrackCircuitSection nextSection = signalRef.TrackCircuitList[ValidRoute[0][iIndex].TCSectionIndex]; @@ -3274,17 +3118,17 @@ public override AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockS } } - // if train not ahead, try first section beyond last reserved + // If train not ahead, try first section beyond last reserved if (trainInfo.Count <= 0 && endIndex < ValidRoute[0].Count - 1) { TrackCircuitSection nextSection = signalRef.TrackCircuitList[ValidRoute[0][endIndex + 1].TCSectionIndex]; trainInfo = nextSection.TestTrainAhead(this, 0, ValidRoute[0][endIndex + 1].Direction); } - // if train found get distance - if (trainInfo.Count > 0) // found train + // If train found get distance + if (trainInfo.Count > 0) // Found train { - foreach (KeyValuePair trainAhead in trainInfo) // always just one + foreach (KeyValuePair trainAhead in trainInfo) // Always just one { TTTrain OtherTrain = trainAhead.Key as TTTrain; float distanceToTrain = trainAhead.Value + addOffset; @@ -3294,19 +3138,16 @@ public override AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockS DistanceToEndNodeAuthorityM[0] = distanceToTrain; } - if (Math.Abs(OtherTrain.SpeedMpS) < 0.1f && - distanceToTrain > followDistanceStatTrainM) + if (Math.Abs(OtherTrain.SpeedMpS) < 0.1f && distanceToTrain > followDistanceStatTrainM) { - // allow creeping closer + // Allow creeping closer CreateTrainAction(SpeedSettings.creepSpeedMpS.Value, 0.0f, distanceToTrain, null, AIActionItem.AI_ACTION_TYPE.TRAIN_AHEAD); DelayedStartMoving(AI_START_MOVEMENT.FOLLOW_TRAIN); } - - else if (Math.Abs(OtherTrain.SpeedMpS) > 0.1f && - distanceToTrain > keepDistanceMovingTrainM) + else if (Math.Abs(OtherTrain.SpeedMpS) > 0.1f && distanceToTrain > keepDistanceMovingTrainM) { - // train started moving + // Train started moving DelayedStartMoving(AI_START_MOVEMENT.FOLLOW_TRAIN); } else @@ -3320,7 +3161,7 @@ public override AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockS CheckReadyToAttach(); - // check attach details + // Check attach details if (AttachDetails != null && AttachDetails.Valid && AttachDetails.ReadyToAttach && AttachDetails.AttachTrain == OtherTrain.OrgAINumber) { attachToTrain = true; @@ -3328,22 +3169,21 @@ public override AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockS if (!attachToTrain) { - // check pickup details + // Check pickup details pickUpTrain = CheckPickUp(OtherTrain); - // check transfer details + // Check transfer details transferTrain = CheckTransfer(OtherTrain, ref transferStationIndex, ref transferTrainIndex); } - // if to attach to train, start moving if (attachToTrain || pickUpTrain || transferTrain) { + // If to attach to train, start moving DelayedStartMoving(AI_START_MOVEMENT.FOLLOW_TRAIN); } - - // if other train in station, check if this train to terminate in station - if so, set state as in station else if (OtherTrain.AtStation && StationStops != null && StationStops.Count == 1 && OtherTrain.StationStops[0].PlatformReference == StationStops[0].PlatformReference) { + // If other train in station, check if this train to terminate in station - if so, set state as in station MovementState = AI_MOVEMENT_STATE.STATION_STOP; if (CheckTrain) @@ -3355,19 +3195,18 @@ public override AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockS } } - // update action info + // Update action info if (nextActionInfo != null && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.TRAIN_AHEAD) { nextActionInfo.ActivateDistanceM = DistanceTravelledM + DistanceToEndNodeAuthorityM[0]; } - - // if no action, check for station stop (may not be activated due to distance travelled) else if (nextActionInfo == null && StationStops != null && StationStops.Count > 0) { + // If no action, check for station stop (may not be activated due to distance travelled) if (StationStops[0].SubrouteIndex == TCRoute.activeSubpath && - ValidRoute[0].GetRouteIndex(StationStops[0].TCSectionIndex, PresentPosition[0].RouteListIndex) <= PresentPosition[0].RouteListIndex) - // assume to be in station + ValidRoute[0].GetRouteIndex(StationStops[0].TCSectionIndex, PresentPosition[0].RouteListIndex) <= PresentPosition[0].RouteListIndex) { + // Assume to be in station MovementState = AI_MOVEMENT_STATE.STATION_STOP; if (CheckTrain) @@ -3381,23 +3220,21 @@ public override AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockS } else { - // if next action still is train ahead, reset actions + // If next action still is train ahead, reset actions if (nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.TRAIN_AHEAD) { ResetActions(true); } } - // if train not found, do nothing - state will change next update - + // If train not found, do nothing - state will change next update } - // Other node mode : check distance ahead (path may have cleared) - + // Other node mode: check distance ahead (path may have cleared) else if (ControlMode == TRAIN_CONTROL.AUTO_NODE) { if (EndAuthorityType[0] == END_AUTHORITY.RESERVED_SWITCH || EndAuthorityType[0] == END_AUTHORITY.LOOP) { - float ReqStopDistanceM = DistanceToEndNodeAuthorityM[0] - 2.0f * junctionOverlapM; + float ReqStopDistanceM = DistanceToEndNodeAuthorityM[0] - (2.0f * junctionOverlapM); if (ReqStopDistanceM > clearingDistanceM) { NextStopDistanceM = DistanceToEndNodeAuthorityM[0]; @@ -3411,32 +3248,24 @@ public override AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockS } } - // signal node : check state of signal - + // Signal node: check state of signal else if (ControlMode == TRAIN_CONTROL.AUTO_SIGNAL) { MstsSignalAspect nextAspect = MstsSignalAspect.UNKNOWN; - // there is a next item and it is the next signal - if (nextActionInfo != null && nextActionInfo.ActiveItem != null && - nextActionInfo.ActiveItem.ObjectDetails == NextSignalObject[0]) - { - nextAspect = nextActionInfo.ActiveItem.ObjectDetails.this_sig_lr(MstsSignalFunction.NORMAL); - } - else - { - nextAspect = GetNextSignalAspect(0); - } + // There is a next item and it is the next signal + nextAspect = nextActionInfo != null && nextActionInfo.ActiveItem != null && + nextActionInfo.ActiveItem.ObjectDetails == NextSignalObject[0] + ? nextActionInfo.ActiveItem.ObjectDetails.this_sig_lr(MstsSignalFunction.NORMAL) + : GetNextSignalAspect(0); - if (NextSignalObject[0] == null) // no signal ahead so switch Node control + if (NextSignalObject[0] == null) // No signal ahead so switch Node control { SwitchToNodeControl(PresentPosition[0].TCSectionIndex); NextStopDistanceM = DistanceToEndNodeAuthorityM[0]; } - - else if (nextAspect > MstsSignalAspect.STOP && - nextAspect < MstsSignalAspect.APPROACH_1) + else if (nextAspect > MstsSignalAspect.STOP && nextAspect < MstsSignalAspect.APPROACH_1) { - // check if any other signals within clearing distance + // Check if any other signals within clearing distance bool signalCleared = true; bool withinDistance = true; @@ -3445,15 +3274,15 @@ public override AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockS ObjectItemInfo nextObject = SignalObjectItems[iitem]; if (nextObject.ObjectType == ObjectItemInfo.ObjectItemType.Signal) { - if (nextObject.ObjectDetails != NextSignalObject[0]) // not signal we are waiting for + if (nextObject.ObjectDetails != NextSignalObject[0]) // Not signal we are waiting for { if (nextObject.distance_to_train > 2.0 * clearingDistanceM) { - withinDistance = false; // signal is far enough ahead + withinDistance = false; // Signal is far enough ahead } else if (nextObject.signal_state == MstsSignalAspect.STOP) { - signalCleared = false; // signal is not clear + signalCleared = false; // Signal is not clear NextSignalObject[0].ForcePropagation = true; } } @@ -3463,13 +3292,13 @@ public override AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockS if (signalCleared) { ResetActions(true); - NextStopDistanceM = 5000f; // clear to 5000m, will be updated if required + NextStopDistanceM = 5000f; // Clear to 5000m, will be updated if required DelayedStartMoving(AI_START_MOVEMENT.SIGNAL_RESTRICTED); } } else if (nextAspect >= MstsSignalAspect.APPROACH_1) { - // check if any other signals within clearing distance + // Check if any other signals within clearing distance bool signalCleared = true; bool withinDistance = true; @@ -3478,16 +3307,16 @@ public override AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockS ObjectItemInfo nextObject = SignalObjectItems[iitem]; if (nextObject.ObjectType == ObjectItemInfo.ObjectItemType.Signal) { - if (nextObject.ObjectDetails != NextSignalObject[0]) // not signal we are waiting for + if (nextObject.ObjectDetails != NextSignalObject[0]) // Not signal we are waiting for { if (nextObject.distance_to_train > 2.0 * clearingDistanceM) { - withinDistance = false; // signal is far enough ahead + withinDistance = false; // Signal is far enough ahead } else if (nextObject.signal_state == MstsSignalAspect.STOP) { - // set this signal as passed, and next signal as waiting - signalCleared = false; // signal is not clear + // Set this signal as passed, and next signal as waiting + signalCleared = false; // Signal is not clear int nextSignalIndex = NextSignalObject[0].sigfound[SignalFunction.NORMAL]; if (nextSignalIndex >= 0) { @@ -3507,28 +3336,26 @@ public override AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockS if (signalCleared) { ResetActions(true); - NextStopDistanceM = 5000f; // clear to 5000m, will be updated if required + NextStopDistanceM = 5000f; // Clear to 5000m, will be updated if required DelayedStartMoving(AI_START_MOVEMENT.SIGNAL_CLEARED); } } - else if (nextAspect == MstsSignalAspect.STOP) { - // if stop but train is well away from signal allow to close + // If stop but train is well away from signal allow to close if (DistanceToSignal.HasValue && DistanceToSignal.Value > 5 * signalApproachDistanceM) { ResetActions(true); DelayedStartMoving(AI_START_MOVEMENT.PATH_ACTION); } } - else if (nextActionInfo != null && - nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.STATION_STOP) + else if (nextActionInfo != null && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.STATION_STOP) { if (StationStops[0].SubrouteIndex == TCRoute.activeSubpath && ValidRoute[0].GetRouteIndex(StationStops[0].TCSectionIndex, PresentPosition[0].RouteListIndex) <= PresentPosition[0].RouteListIndex) - // assume to be in station { - MovementState = AI_MOVEMENT_STATE.STATION_STOP; + // Assume to be in station + MovementState = AI_MOVEMENT_STATE.STATION_STOP; if (CheckTrain) { @@ -3537,9 +3364,9 @@ public override AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockS " ; station section = " + StationStops[0].TCSectionIndex + " )\n"); } } - else - // approaching next station + else { + // Approaching next station MovementState = AI_MOVEMENT_STATE.BRAKING; if (CheckTrain) @@ -3567,28 +3394,26 @@ public override AITrain.AI_MOVEMENT_STATE UpdateStoppedState(float elapsedClockS { File.AppendAllText(@"C:\temp\checktrain.txt", "Train " + Number.ToString() + " , forced to BRAKING from invalid stop (now at " + - // FormatStrings.FormatDistance(PresentPosition[0].DistanceTravelledM, true) + ")\n"); + // FormatStrings.FormatDistance(PresentPosition[0].DistanceTravelledM, true) + ")\n"); // TODO: Remove? PresentPosition[0].DistanceTravelledM.ToString() + ")\n"); } } } - return (MovementState); + return MovementState; } //================================================================================================// /// /// Update when train on turntable /// - public override void UpdateTurntableState(float elapsedClockSeconds, int presentTime) { - - // check if delayed action is due + // Check if delayed action is due if (DelayedStart) { RestdelayS -= elapsedClockSeconds; - if (RestdelayS <= 0) // wait time has elapsed - start moving + if (RestdelayS <= 0) // Wait time has elapsed - start moving { DelayedStart = false; RestdelayS = 0; @@ -3608,11 +3433,11 @@ public override void UpdateTurntableState(float elapsedClockSeconds, int present } } - // check if turntable available, else exit turntable mode + // Check if turntable available, else exit turntable mode if (ActiveTurntable == null || ActiveTurntable.MovingTableState == TimetableTurntableControl.MovingTableStateEnum.Inactive) { - NextStopDistanceM = DistanceToEndNodeAuthorityM[0]; // set authorized distance - MovementState = AI_MOVEMENT_STATE.STOPPED; // set state to stopped to revert to normal working + NextStopDistanceM = DistanceToEndNodeAuthorityM[0]; // Set authorized distance + MovementState = AI_MOVEMENT_STATE.STOPPED; // Set state to stopped to revert to normal working if (CheckTrain) { File.AppendAllText(@"C:\temp\checktrain.txt", "TURNTABLE : exit from table, distance to go : " + NextStopDistanceM + "\n"); @@ -3631,7 +3456,6 @@ public override void UpdateTurntableState(float elapsedClockSeconds, int present /// Update for train in Station state (train is at station) /// Override for AITrain class /// <\summary> - public override void UpdateStationState(float elapsedClockSeconds, int presentTime) { StationStop thisStation = StationStops[0]; @@ -3641,8 +3465,7 @@ public override void UpdateStationState(float elapsedClockSeconds, int presentTi int sixteenHundredHours = 16 * 3600; int actualdepart = thisStation.ActualDepart; - // no arrival / departure time set : update times - + // No arrival / departure time set: update times if (thisStation.ActualStopType == StationStop.STOPTYPE.STATION_STOP) { AtStation = true; @@ -3703,10 +3526,10 @@ public override void UpdateStationState(float elapsedClockSeconds, int presentTi #endif } - // check for activation of other train + // Check for activation of other train ActivateTriggeredTrain(TriggerActivationType.StationStop, thisStation.PlatformReference); - // set reference arrival for any waiting connections + // Set reference arrival for any waiting connections if (thisStation.ConnectionsWaiting.Count > 0) { foreach (int otherTrainNumber in thisStation.ConnectionsWaiting) @@ -3729,8 +3552,7 @@ public override void UpdateStationState(float elapsedClockSeconds, int presentTi } } - // check for detach actions - + // Check for detach actions if (DetachDetails.ContainsKey(thisStation.PlatformReference)) { List detachList = DetachDetails[thisStation.PlatformReference]; @@ -3748,15 +3570,14 @@ public override void UpdateStationState(float elapsedClockSeconds, int presentTi DetachDetails.Remove(thisStation.PlatformReference); } - // check for connections - + // Check for connections if (thisStation.ConnectionsAwaited.Count > 0) { int deptime = -1; int needwait = -1; needwait = ProcessConnections(thisStation, out deptime); - // if required to wait : exit + // If required to wait: exit if (needwait >= 0) { return; @@ -3769,11 +3590,10 @@ public override void UpdateStationState(float elapsedClockSeconds, int presentTi } } - // check for attachments or transfers - + // Check for attachments or transfers if (NeedAttach.ContainsKey(thisStation.PlatformReference)) { - // waiting for train to attach : exit + // Waiting for train to attach: exit if (NeedAttach[thisStation.PlatformReference].Count > 0) { return; @@ -3782,7 +3602,7 @@ public override void UpdateStationState(float elapsedClockSeconds, int presentTi if (NeedStationTransfer.ContainsKey(thisStation.PlatformReference)) { - // waiting for transfer : exit + // Waiting for transfer: exit if (NeedStationTransfer[thisStation.PlatformReference].Count > 0) { return; @@ -3791,7 +3611,7 @@ public override void UpdateStationState(float elapsedClockSeconds, int presentTi foreach (TrackCircuitSection occSection in OccupiedTrack) { - // waiting for transfer : exit + // Waiting for transfer: exit if (NeedTrainTransfer.ContainsKey(occSection.Index)) { return; @@ -3800,18 +3620,17 @@ public override void UpdateStationState(float elapsedClockSeconds, int presentTi } - // not yet time to depart - check if signal can be released - + // Not yet time to depart - check if signal can be released int correctedTime = presentTime; - if (actualdepart > sixteenHundredHours && presentTime < eightHundredHours) // should have departed before midnight + if (actualdepart > sixteenHundredHours && presentTime < eightHundredHours) // Should have departed before midnight { correctedTime = presentTime + (24 * 3600); } - if (actualdepart < eightHundredHours && presentTime > sixteenHundredHours) // to depart after midnight + if (actualdepart < eightHundredHours && presentTime > sixteenHundredHours) // To depart after midnight { - correctedTime = presentTime - 24 * 3600; + correctedTime = presentTime - (24 * 3600); } if (actualdepart > correctedTime) @@ -3832,29 +3651,27 @@ public override void UpdateStationState(float elapsedClockSeconds, int presentTi if (nextSignal.enabledTrain != null && nextSignal.enabledTrain.Train == this) { - nextSignal.requestClearSignal(ValidRoute[0], routedForward, 0, false, null);// for AI always use direction 0 + nextSignal.requestClearSignal(ValidRoute[0], routedForward, 0, false, null); // For AI always use direction 0 } thisStation.HoldSignal = false; } return; } - // depart - - // check for activation of other train + // Depart + // Check for activation of other train ActivateTriggeredTrain(TriggerActivationType.StationDepart, thisStation.PlatformReference); - // check if to attach in this platform - + // Check if to attach in this platform bool readyToAttach = false; TTTrain trainToTransfer = null; if (AttachDetails != null) { - // check if to attach at this station + // Check if to attach at this station bool attachAtStation = AttachDetails.StationPlatformReference == StationStops[0].PlatformReference; - // check if to attach at end, train is in last station, not first in and other train is ahead + // Check if to attach at end, train is in last station, not first in and other train is ahead if (!attachAtStation && !AttachDetails.FirstIn) { if (AttachDetails.StationPlatformReference == -1 && StationStops.Count == 1) @@ -3866,7 +3683,7 @@ public override void UpdateStationState(float elapsedClockSeconds, int presentTi if (otherTrain.OrgAINumber == AttachDetails.AttachTrain) { attachAtStation = true; - AttachDetails.StationPlatformReference = StationStops[0].PlatformReference; // set attach is at this station + AttachDetails.StationPlatformReference = StationStops[0].PlatformReference; // Set attach is at this station } } } @@ -3879,12 +3696,12 @@ public override void UpdateStationState(float elapsedClockSeconds, int presentTi { trainToTransfer = GetOtherTTTrainByNumber(AttachDetails.AttachTrain); - // check if train exists + // Check if train exists if (trainToTransfer == null) - { - // if firstin, check if train is among trains to be started, or if it is an autogen train, or if it is waiting to be started + { if (AttachDetails.FirstIn) { + // If firstin, check if train is among trains to be started, or if it is an autogen train, or if it is waiting to be started trainToTransfer = Simulator.GetAutoGenTTTrainByNumber(AttachDetails.AttachTrain); if (trainToTransfer == null) @@ -3894,16 +3711,16 @@ public override void UpdateStationState(float elapsedClockSeconds, int presentTi if (trainToTransfer == null) { - foreach (TTTrain wtrain in AI.TrainsToAdd) + foreach (TTTrain wtrain in AI.TrainsToAdd.Cast()) { if (wtrain.Number == AttachDetails.AttachTrain || wtrain.OrgAINumber == AttachDetails.AttachTrain) { - return; // found train - just wait a little longer + return; // Found train - just wait a little longer } } } - // train cannot be found + // Train cannot be found if (trainToTransfer == null) { Trace.TraceInformation("Train {0} : cannot find train {1} to attach", Name, AttachDetails.AttachTrainName); @@ -3911,12 +3728,12 @@ public override void UpdateStationState(float elapsedClockSeconds, int presentTi } else { - return; // wait until train exists + return; // Wait until train exists } - } - // not first in - train not found + } else { + // Not first in - train not found Trace.TraceInformation("Train {0} : cannot find train {1} to attach", Name, AttachDetails.AttachTrainName); AttachDetails = null; } @@ -3933,20 +3750,20 @@ public override void UpdateStationState(float elapsedClockSeconds, int presentTi } else { - // exit as departure is not allowed + // Exit as departure is not allowed return; } } if (readyToAttach) { - // if setback required, reverse train + // If setback required, reverse train if (AttachDetails.SetBack) { - // remove any reserved sections + // Remove any reserved sections RemoveFromTrackNotOccupied(ValidRoute[0]); - // check if train in same section + // Check if train in same section float distanceToTrain = 0.0f; if (trainToTransfer.PresentPosition[0].TCSectionIndex == PresentPosition[1].TCSectionIndex) { @@ -3955,14 +3772,14 @@ public override void UpdateStationState(float elapsedClockSeconds, int presentTi } else { - // get section index of other train in train route + // Get section index of other train in train route int endSectionIndex = ValidRoute[0].GetRouteIndexBackward(trainToTransfer.PresentPosition[0].TCSectionIndex, PresentPosition[1].RouteListIndex); if (endSectionIndex < 0) { Trace.TraceWarning("Train {0} : attach to train {1} failed, cannot find path", Name, trainToTransfer.Name); } - // get distance to train + // Get distance to train for (int iSection = PresentPosition[0].RouteListIndex; iSection >= endSectionIndex; iSection--) { TrackCircuitSection thisSection = signalRef.TrackCircuitList[ValidRoute[0][iSection].TCSectionIndex]; @@ -3970,11 +3787,11 @@ public override void UpdateStationState(float elapsedClockSeconds, int presentTi } } - // create temp route and set as valid route + // Create temp route and set as valid route int newDirection = PresentPosition[0].TCDirection == 0 ? 1 : 0; TCSubpathRoute tempRoute = signalRef.BuildTempRoute(this, PresentPosition[0].TCSectionIndex, 0.0f, newDirection, distanceToTrain, true, true, false); - // set reverse positions + // Set reverse positions TCPosition tempPosition = new TCPosition(); PresentPosition[0].CopyTo(ref tempPosition); PresentPosition[1].CopyTo(ref PresentPosition[0]); @@ -3984,11 +3801,10 @@ public override void UpdateStationState(float elapsedClockSeconds, int presentTi PresentPosition[0].CopyTo(ref PreviousPosition[0]); PresentPosition[1].Reverse(ValidRoute[0][PresentPosition[1].RouteListIndex].Direction, tempRoute, 0.0f, signalRef); - // reverse formation + // Reverse formation ReverseFormation(false); - // get new route list indices from new route - + // Get new route list indices from new route DistanceTravelledM = 0; ValidRoute[0] = tempRoute; TCRoute.TCRouteSubpaths[TCRoute.activeSubpath] = new TCSubpathRoute(tempRoute); @@ -3998,7 +3814,7 @@ public override void UpdateStationState(float elapsedClockSeconds, int presentTi } else { - // build path to train - straight forward, set distance of 2000m (should be enough) + // Build path to train - straight forward, set distance of 2000m (should be enough) TCSubpathRoute tempRoute = signalRef.BuildTempRoute(this, PresentPosition[1].TCSectionIndex, 0.0f, PresentPosition[1].TCDirection, 2000, true, true, false); ValidRoute[0] = tempRoute; TCRoute.TCRouteSubpaths[TCRoute.activeSubpath] = new TCSubpathRoute(tempRoute); @@ -4018,34 +3834,31 @@ public override void UpdateStationState(float elapsedClockSeconds, int presentTi } } - // first, check state of signal - + // First, check state of signal if (thisStation.ExitSignal >= 0 && thisStation.HoldSignal) { HoldingSignals.Remove(thisStation.ExitSignal); var nextSignal = signalRef.SignalObjects[thisStation.ExitSignal]; - // only request signal if in signal mode (train may be in node control) + // Only request signal if in signal mode (train may be in node control) if (ControlMode == TRAIN_CONTROL.AUTO_SIGNAL) { - nextSignal.requestClearSignal(ValidRoute[0], routedForward, 0, false, null); // for AI always use direction 0 + nextSignal.requestClearSignal(ValidRoute[0], routedForward, 0, false, null); // For AI always use direction 0 } } - // check if station is end of path - + // Check if station is end of path bool[] endOfPath = ProcessEndOfPath(presentTime); - // check for exit signal - + // Check for exit signal bool exitSignalStop = false; if (thisStation.ExitSignal >= 0 && NextSignalObject[0] != null && NextSignalObject[0].thisRef == thisStation.ExitSignal) { MstsSignalAspect nextAspect = GetNextSignalAspect(0); - exitSignalStop = (nextAspect == MstsSignalAspect.STOP && !thisStation.NoWaitSignal); + exitSignalStop = nextAspect == MstsSignalAspect.STOP && !thisStation.NoWaitSignal; } - // if not end of path, check if departure allowed + // If not end of path, check if departure allowed if (!endOfPath[0] && exitSignalStop) { @@ -4053,13 +3866,13 @@ public override void UpdateStationState(float elapsedClockSeconds, int presentTi TTAnalysisUpdateStationState2(); #endif - return; // do not depart if exit signal at danger and waiting is required + return; // Do not depart if exit signal at danger and waiting is required } DateTime baseDTd = new DateTime(); DateTime depTime = baseDTd.AddSeconds(AI.clockTime); - // change state if train still exists + // Change state if train still exists if (endOfPath[1]) { if (MovementState == AI_MOVEMENT_STATE.STATION_STOP && !exitSignalStop) @@ -4067,15 +3880,15 @@ public override void UpdateStationState(float elapsedClockSeconds, int presentTi AtStation = false; thisStation.Passed = true; - MovementState = AI_MOVEMENT_STATE.STOPPED; // if state is still station_stop and ready and allowed to depart - change to stop to check action - RestdelayS = (float)DelayedStartSettings.stationRestart.fixedPartS + ((float)Simulator.Random.Next(DelayedStartSettings.stationRestart.randomPartS * 10) / 10f); + MovementState = AI_MOVEMENT_STATE.STOPPED; // If state is still station_stop and ready and allowed to depart - change to stop to check action + RestdelayS = DelayedStartSettings.stationRestart.fixedPartS + (Simulator.Random.Next(DelayedStartSettings.stationRestart.randomPartS * 10) / 10f); if (!endOfPath[0]) { - removeStation = true; // set next station if not at end of path + removeStation = true; // Set next station if not at end of path } else if (StationStops.Count > 0 && thisStation.PlatformReference == StationStops[0].PlatformReference) { - removeStation = true; // this station is still set as next station so remove + removeStation = true; // This station is still set as next station so remove } } @@ -4164,12 +3977,10 @@ public override void UpdateStationState(float elapsedClockSeconds, int presentTi /// Update for train in Braking state /// Override for AITrain class /// <\summary> - public override void UpdateBrakingState(float elapsedClockSeconds, int presentTime) { - // check if action still required - + // Check if action still required bool clearAction = false; float distanceToGoM = clearingDistanceM; @@ -4177,16 +3988,16 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi { distanceToGoM = DistanceToEndNodeAuthorityM[0]; } - - else if (nextActionInfo == null) // action has been reset - keep status quo + else if (nextActionInfo == null) { - if (ControlMode == TRAIN_CONTROL.AUTO_NODE) // node control : use control distance + // Action has been reset - keep status quo + if (ControlMode == TRAIN_CONTROL.AUTO_NODE) // Node control: use control distance { distanceToGoM = DistanceToEndNodeAuthorityM[0]; if (EndAuthorityType[0] == END_AUTHORITY.RESERVED_SWITCH) { - distanceToGoM = DistanceToEndNodeAuthorityM[0] - 2.0f * junctionOverlapM; + distanceToGoM = DistanceToEndNodeAuthorityM[0] - (2.0f * junctionOverlapM); } else if (EndAuthorityType[0] == END_AUTHORITY.END_OF_PATH || EndAuthorityType[0] == END_AUTHORITY.END_OF_AUTHORITY) { @@ -4222,8 +4033,9 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi return; } } - else // action cleared - set running or stopped + else { + // Action cleared - set running or stopped if (SpeedMpS > 0) { MovementState = AI_MOVEMENT_STATE.RUNNING; @@ -4244,12 +4056,10 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi } return; } - } - - // check if speedlimit on signal is cleared - + } else if (nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.SPEED_SIGNAL) { + // Check if speedlimit on signal is cleared if (nextActionInfo.ActiveItem.actual_speed >= AllowedMaxSpeedMpS) { clearAction = true; @@ -4271,8 +4081,9 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi nextActionInfo.ActiveItem.ObjectDetails.thisRef.ToString() + " : speed : " + FormatStrings.FormatSpeed(nextActionInfo.ActiveItem.actual_speed, true) + " >= limit : " + FormatStrings.FormatSpeed(AllowedMaxSpeedMpS, true) + " at " + - //FormatStrings.FormatDistance(nextActionInfo.ActivateDistanceM, true) + " (now at " + - //FormatStrings.FormatDistance(PresentPosition[0].DistanceTravelledM, true) + " - " + + // TODO: Remove? + //FormatStrings.FormatDistance(nextActionInfo.ActivateDistanceM, true) + " (now at " + + //FormatStrings.FormatDistance(PresentPosition[0].DistanceTravelledM, true) + " - " + nextActionInfo.ActivateDistanceM.ToString() + " (now at " + PresentPosition[0].DistanceTravelledM.ToString() + " - " + FormatStrings.FormatSpeed(SpeedMpS, true) + ")\n"); @@ -4302,13 +4113,10 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi FormatStrings.FormatSpeed(SpeedMpS, true) + ")\n"); } } - } - - // check if STOP signal cleared - + } else if (nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.SIGNAL_ASPECT_STOP) { - + // Check if STOP signal cleared if (nextActionInfo.ActiveItem.signal_state >= MstsSignalAspect.APPROACH_1) { clearAction = true; @@ -4326,8 +4134,9 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi File.AppendAllText(@"C:\temp\checktrain.txt", "Train " + Number.ToString() + " : signal " + nextActionInfo.ActiveItem.ObjectDetails.thisRef.ToString() + " at " + - //FormatStrings.FormatDistance(nextActionInfo.ActivateDistanceM, true) + " cleared (now at " + - //FormatStrings.FormatDistance(PresentPosition[0].DistanceTravelledM, true) + " - " + + // TODO: Remove? + //FormatStrings.FormatDistance(nextActionInfo.ActivateDistanceM, true) + " cleared (now at " + + //FormatStrings.FormatDistance(PresentPosition[0].DistanceTravelledM, true) + " - " + nextActionInfo.ActivateDistanceM.ToString() + " cleared (now at " + PresentPosition[0].DistanceTravelledM.ToString() + " - " + FormatStrings.FormatSpeed(SpeedMpS, true) + ")\n"); @@ -4353,8 +4162,9 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi File.AppendAllText(@"C:\temp\checktrain.txt", Number.ToString() + " : signal " + nextActionInfo.ActiveItem.ObjectDetails.thisRef.ToString() + " at " + - //FormatStrings.FormatDistance(nextActionInfo.ActivateDistanceM, true) + " cleared (now at " + - //FormatStrings.FormatDistance(PresentPosition[0].DistanceTravelledM, true) + " - " + + // TODO: Remove? + //FormatStrings.FormatDistance(nextActionInfo.ActivateDistanceM, true) + " cleared (now at " + + //FormatStrings.FormatDistance(PresentPosition[0].DistanceTravelledM, true) + " - " + nextActionInfo.ActivateDistanceM.ToString() + " cleared (now at " + PresentPosition[0].DistanceTravelledM.ToString() + " - " + FormatStrings.FormatSpeed(SpeedMpS, true) + ")\n"); @@ -4362,14 +4172,12 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi } } } - - // check if RESTRICTED signal cleared - else if (nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.SIGNAL_ASPECT_RESTRICTED) { + // Check if RESTRICTED signal cleared if ((nextActionInfo.ActiveItem.signal_state >= MstsSignalAspect.APPROACH_1) || ((nextActionInfo.ActivateDistanceM - PresentPosition[0].DistanceTravelledM) < signalApproachDistanceM) || - (nextActionInfo.ActiveItem.ObjectDetails.this_sig_noSpeedReduction(SignalFunction.NORMAL))) + nextActionInfo.ActiveItem.ObjectDetails.this_sig_noSpeedReduction(SignalFunction.NORMAL)) { clearAction = true; #if DEBUG_REPORTS @@ -4385,26 +4193,24 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi File.AppendAllText(@"C:\temp\checktrain.txt", Number.ToString() + " : signal " + nextActionInfo.ActiveItem.ObjectDetails.thisRef.ToString() + " at " + - //FormatStrings.FormatDistance(nextActionInfo.ActivateDistanceM, true) + " cleared (now at " + - //FormatStrings.FormatDistance(PresentPosition[0].DistanceTravelledM, true) + " - " + + // TODO: Remove? + //FormatStrings.FormatDistance(nextActionInfo.ActivateDistanceM, true) + " cleared (now at " + + //FormatStrings.FormatDistance(PresentPosition[0].DistanceTravelledM, true) + " - " + nextActionInfo.ActivateDistanceM.ToString() + " cleared (now at " + PresentPosition[0].DistanceTravelledM.ToString() + " - " + FormatStrings.FormatSpeed(SpeedMpS, true) + ")\n"); } } } - - // check if END_AUTHORITY extended - - else if (nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.END_OF_AUTHORITY) + else if (nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.END_OF_AUTHORITY) { + // Check if END_AUTHORITY extended nextActionInfo.ActivateDistanceM = DistanceToEndNodeAuthorityM[0] + DistanceTravelledM; if (EndAuthorityType[0] == END_AUTHORITY.MAX_DISTANCE) { clearAction = true; } } - else if (nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.SPEED_LIMIT) { if (nextActionInfo.RequiredSpeedMpS >= AllowedMaxSpeedMpS) @@ -4458,38 +4264,37 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi } } - // action cleared - reset processed info for object items to determine next action - // clear list of pending action to create new list - + // Action cleared - reset processed info for object items to determine next action + // Clear list of pending action to create new list if (clearAction) { ResetActions(true); MovementState = AI_MOVEMENT_STATE.RUNNING; Alpha10 = 10; - if (SpeedMpS < AllowedMaxSpeedMpS - 3.0f * hysterisMpS) + if (SpeedMpS < AllowedMaxSpeedMpS - (3.0f * hysterisMpS)) { AdjustControlsBrakeOff(); } + return; } - // check ideal speed - + // Check ideal speed float requiredSpeedMpS = 0; float creepDistanceM = 3.0f * signalApproachDistanceM; if (MovementState == AI_MOVEMENT_STATE.TURNTABLE) { - creepDistanceM = distanceToGoM + signalApproachDistanceM; // ensure creep distance always exceeds distance to go + creepDistanceM = distanceToGoM + signalApproachDistanceM; // Ensure creep distance always exceeds distance to go NextStopDistanceM = distanceToGoM; - // if almost in the middle, apply full brakes + // If almost in the middle, apply full brakes if (distanceToGoM < 0.25) { AdjustControlsBrakeFull(); } - // if stopped, move to next state + // If stopped, move to next state if (distanceToGoM < 1 && Math.Abs(SpeedMpS) < 0.05f) { ActiveTurntable.SetNextStageOnStopped(); @@ -4505,16 +4310,14 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi { distanceToGoM = nextActionInfo.ActiveItem.distance_to_train; } - - // check if stopped at station - + if (nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.STATION_STOP) { + // Check if stopped at station NextStopDistanceM = distanceToGoM; - // check if station has exit signal and if signal is clear - // if signal is at stop, check if stop position is sufficiently clear of signal - + // Check if station has exit signal and if signal is clear + // If signal is at stop, check if stop position is sufficiently clear of signal if (NextSignalObject[0] != null && NextSignalObject[0].this_sig_lr(MstsSignalFunction.NORMAL) == MstsSignalAspect.STOP) { float reqsignaldistance = StationStops[0].CloseupSignal ? keepDistanceCloseupSignalM : signalApproachDistanceM; @@ -4530,9 +4333,8 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi } } - // check if stopped - // train is stopped - set departure time - + // Check if stopped + // Train is stopped - set departure time if (distanceToGoM < 0.25f * keepDistanceCloseupSignalM) { if (Math.Abs(SpeedMpS) < 0.05f) @@ -4559,18 +4361,16 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi StationStops[0].PlatformItem.Name + " at " + arrTimeCT.ToString("HH:mm:ss") + "\n"); } - } - - // perform slow approach to stop + } else if (distanceToGoM > 0) { + // Perform slow approach to stop if (AITrainBrakePercent < 50) { AdjustControlsBrakeMore(MaxDecelMpSS, elapsedClockSeconds, 10); AITrainThrottlePercent = 0; } } - else { AdjustControlsBrakeMore(MaxDecelMpSS, elapsedClockSeconds, 100); @@ -4579,12 +4379,10 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi return; } - } - - // check speed reduction position reached - + } else if (nextActionInfo.RequiredSpeedMpS > 0) { + // Check speed reduction position reached if (distanceToGoM <= 0.0f) { AdjustControlsBrakeOff(); @@ -4601,27 +4399,23 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi ResetActions(true); return; } - } - - // check if approaching reversal point - + } else if (nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.REVERSAL) { + // Check if approaching reversal point if (SpeedMpS < 0.05f) MovementState = AI_MOVEMENT_STATE.STOPPED; RestdelayS = DelayedStartSettings.reverseAddedDelaySperM * Length; - } - - // check if stopped at signal - + } else if (nextActionInfo.RequiredSpeedMpS == 0) { + // Check if stopped at signal NextStopDistanceM = distanceToGoM; float stopDistanceM = signalApproachDistanceM; - // allow closeup on end of route + // Allow closeup on end of route if (nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.END_OF_ROUTE && Closeup) stopDistanceM = keepDistanceCloseupM; - // set distance for signal + // Set distance for signal else if (nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.SIGNAL_ASPECT_STOP) stopDistanceM = clearingDistanceM; if (distanceToGoM < stopDistanceM) @@ -4649,7 +4443,7 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi "Speed : " + FormatStrings.FormatSpeed(SpeedMpS, true) + "\n"); } - // if approaching signal and at 0.25 of approach distance and still moving, force stop + // If approaching signal and at 0.25 of approach distance and still moving, force stop if (distanceToGoM < (0.25 * signalApproachDistanceM) && SpeedMpS > 0 && nextActionInfo != null && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.SIGNAL_ASPECT_STOP) { @@ -4684,27 +4478,26 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi } } - // keep speed within required speed band - - // preset, also valid for reqSpeed > 0 + // Keep speed within required speed band + // Preset, also valid for reqSpeed > 0 float lowestSpeedMpS = requiredSpeedMpS; if (requiredSpeedMpS == 0) { - // station stop : use closeup distance as final stop approach + // Station stop: use closeup distance as final stop approach if (nextActionInfo != null && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.STATION_STOP) { creepDistanceM = keepDistanceCloseupSignalM; lowestSpeedMpS = SpeedSettings.creepSpeedMpS.Value; } - // signal : use 3 * signalApproachDistanceM as final stop approach to avoid signal overshoot + // Signal: use 3 * signalApproachDistanceM as final stop approach to avoid signal overshoot else if (nextActionInfo != null && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.SIGNAL_ASPECT_STOP) { creepDistanceM = 3.0f * signalApproachDistanceM; lowestSpeedMpS = distanceToGoM < creepDistanceM ? (0.5f * SpeedSettings.creepSpeedMpS.Value) : SpeedSettings.creepSpeedMpS.Value; } - // otherwise use clearingDistanceM as approach distance + // Otherwise use clearingDistanceM as approach distance else if (nextActionInfo == null && requiredSpeedMpS == 0) { creepDistanceM = clearingDistanceM; @@ -4720,33 +4513,33 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi lowestSpeedMpS = Math.Min(lowestSpeedMpS, AllowedMaxSpeedMpS); - // braking distance - use 0.25 * MaxDecelMpSS as average deceleration (due to braking delay) + // Braking distance - use 0.25 * MaxDecelMpSS as average deceleration (due to braking delay) // Videal - Vreq = a * T => T = (Videal - Vreq) / a // R = Vreq * T + 0.5 * a * T^2 => R = Vreq * (Videal - Vreq) / a + 0.5 * a * (Videal - Vreq)^2 / a^2 => // R = Vreq * Videal / a - Vreq^2 / a + Videal^2 / 2a - 2 * Vreq * Videal / 2a + Vreq^2 / 2a => R = Videal^2 / 2a - Vreq^2 /2a // so : Vreq = SQRT (2 * a * R + Vreq^2) - // remaining distance is corrected for minimal approach distance as safety margin - // for requiredSpeed > 0, take hysteris margin off ideal speed so speed settles on required speed - // for requiredSpeed == 0, use ideal speed, this allows actual speed to be a little higher - // upto creep distance : set creep speed as lowest possible speed + // Remaining distance is corrected for minimal approach distance as safety margin + // For requiredSpeed > 0, take hysteris margin off ideal speed so speed settles on required speed + // For requiredSpeed == 0, use ideal speed, this allows actual speed to be a little higher + // Upto creep distance : set creep speed as lowest possible speed float correctedDistanceToGoM = distanceToGoM - creepDistanceM; float maxPossSpeedMpS = lowestSpeedMpS; if (correctedDistanceToGoM > 0) { - maxPossSpeedMpS = (float)Math.Sqrt(0.25f * MaxDecelMpSS * 2.0f * correctedDistanceToGoM + (requiredSpeedMpS * requiredSpeedMpS)); + maxPossSpeedMpS = (float)Math.Sqrt((0.25f * MaxDecelMpSS * 2.0f * correctedDistanceToGoM) + (requiredSpeedMpS * requiredSpeedMpS)); maxPossSpeedMpS = Math.Max(lowestSpeedMpS, maxPossSpeedMpS); } - float idealSpeedMpS = requiredSpeedMpS == 0 ? Math.Min((AllowedMaxSpeedMpS - 2f * hysterisMpS), maxPossSpeedMpS) : Math.Min(AllowedMaxSpeedMpS, maxPossSpeedMpS) - (2f * hysterisMpS); + float idealSpeedMpS = requiredSpeedMpS == 0 ? Math.Min(AllowedMaxSpeedMpS - (2f * hysterisMpS), maxPossSpeedMpS) : Math.Min(AllowedMaxSpeedMpS, maxPossSpeedMpS) - (2f * hysterisMpS); float idealLowBandMpS = Math.Max(0.25f * lowestSpeedMpS, idealSpeedMpS - (3f * hysterisMpS)); float ideal3LowBandMpS = Math.Max(0.5f * lowestSpeedMpS, idealSpeedMpS - (9f * hysterisMpS)); float idealHighBandMpS = Math.Min(AllowedMaxSpeedMpS, Math.Max(lowestSpeedMpS, idealSpeedMpS) + hysterisMpS); float ideal3HighBandMpS = Math.Min(AllowedMaxSpeedMpS, Math.Max(lowestSpeedMpS, idealSpeedMpS) + (2f * hysterisMpS)); float deltaSpeedMpS = SpeedMpS - requiredSpeedMpS; - float idealDecelMpSS = Math.Max((0.5f * MaxDecelMpSS), (deltaSpeedMpS * deltaSpeedMpS / (2.0f * distanceToGoM))); + float idealDecelMpSS = Math.Max(0.5f * MaxDecelMpSS, deltaSpeedMpS * deltaSpeedMpS / (2.0f * distanceToGoM)); float lastDecelMpSS = elapsedClockSeconds > 0 ? ((SpeedMpS - LastSpeedMpS) / elapsedClockSeconds) : idealDecelMpSS; @@ -4794,9 +4587,8 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi " A&B(S): " + AITrainThrottlePercent.ToString() + " - " + AITrainBrakePercent.ToString() + "\n"); } - // keep speed withing band - - // speed exceeds allowed maximum - set brakes and clamp speed + // Keep speed withing band + // Speed exceeds allowed maximum - set brakes and clamp speed if (SpeedMpS > AllowedMaxSpeedMpS) { if (CheckTrain) @@ -4813,13 +4605,13 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi AdjustControlsBrakeMore(MaxDecelMpSS, elapsedClockSeconds, 20); } - // clamp speed + // Clamp speed AdjustControlsFixedSpeed(AllowedMaxSpeedMpS); Alpha10 = 5; } - // reached end position + // Reached end position else if (SpeedMpS > requiredSpeedMpS && distanceToGoM < 0) { if (CheckTrain) @@ -4827,7 +4619,7 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi File.AppendAllText(@"C:\temp\checktrain.txt", "Section : SpeedMpS > requiredSpeedMpS && distanceToGoM < 0 \n"); } - // if required to stop then force stop + // If required to stop then force stop if (requiredSpeedMpS == 0 && nextActionInfo != null && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.SIGNAL_ASPECT_STOP) { if (CheckTrain) @@ -4837,16 +4629,16 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi " at " + DistanceTravelledM.ToString() + ", and speed " + SpeedMpS.ToString() + "\n"); } Trace.TraceInformation("Train : {0} ({1}) forced to stop, at {2}, and speed {3} \n", Name, Number, DistanceTravelledM.ToString(), SpeedMpS.ToString()); - SpeedMpS = 0; // force to standstill + SpeedMpS = 0; // Force to standstill } - // increase brakes + // Increase brakes else { AdjustControlsBrakeMore(MaxDecelMpSS, elapsedClockSeconds, 50); } } - // speed beyond top threshold + // Speed beyond top threshold else if (SpeedMpS > ideal3HighBandMpS) { if (CheckTrain) @@ -4863,7 +4655,7 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi AdjustControlsBrakeMore(2.0f * MaxDecelMpSS, elapsedClockSeconds, 10); Alpha10 = 10; } - // if at full brake always perform application as it forces braking in case of brake failure (eg due to wheelslip) + // If at full brake always perform application as it forces braking in case of brake failure (eg due to wheelslip) else if (AITrainBrakePercent == 100) { AdjustControlsBrakeMore(2.0f * MaxDecelMpSS, elapsedClockSeconds, 50); @@ -4877,7 +4669,7 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi Alpha10 = Alpha10 > 0 ? --Alpha10 : 0; } - // speed just above ideal + // Speed just above ideal else if (SpeedMpS > idealHighBandMpS) { if (CheckTrain) @@ -4933,7 +4725,7 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi Alpha10 = Alpha10 > 0 ? --Alpha10 : 0; } - // speed just below ideal + // Speed just below ideal else if (SpeedMpS > idealLowBandMpS) { if (CheckTrain) @@ -4972,7 +4764,7 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi Alpha10 = Alpha10 > 0 ? --Alpha10 : 0; } - // speed below ideal but above lowest threshold + // Speed below ideal but above lowest threshold else if (SpeedMpS > ideal3LowBandMpS) { if (CheckTrain) @@ -5000,7 +4792,7 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi Alpha10 = Alpha10 > 0 ? --Alpha10 : 0; } - // speed below required speed + // Speed below required speed else if (SpeedMpS < requiredSpeedMpS || (requiredSpeedMpS == 0 && Math.Abs(SpeedMpS) < 0.1f)) { if (CheckTrain) @@ -5015,7 +4807,7 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi } else if (AITrainThrottlePercent > 99) { - // force setting to 100% to force acceleration + // Force setting to 100% to force acceleration AdjustControlsAccelMore(0.5f * MaxAccelMpSS, elapsedClockSeconds, 20); } Alpha10 = 5; @@ -5085,8 +4877,8 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi } } - // in preupdate : avoid problems with overshoot due to low update rate - // check if at present speed train would pass beyond end of authority + // In preupdate : avoid problems with overshoot due to low update rate + // Check if at present speed train would pass beyond end of authority if (PreUpdate) { if (requiredSpeedMpS == 0 && distanceToGoM < (10.0f * clearingDistanceM) && (elapsedClockSeconds * SpeedMpS) > (0.5f * distanceToGoM) && SpeedMpS > SpeedSettings.creepSpeedMpS) @@ -5096,7 +4888,7 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi File.AppendAllText(@"C:\temp\checktrain.txt", "Speed forced down : position " + distanceToGoM.ToString() + ", speed " + SpeedMpS.ToString() + " \n"); } - SpeedMpS = (0.5f * SpeedMpS); + SpeedMpS = 0.5f * SpeedMpS; } } @@ -5112,18 +4904,17 @@ public override void UpdateBrakingState(float elapsedClockSeconds, int presentTi /// Update in accelerating mode /// Override from AITrain class /// <\summary> - public override void UpdateAccelState(float elapsedClockSeconds) { - // check speed + // Check speed if (((SpeedMpS - LastSpeedMpS) / elapsedClockSeconds) < 0.5f * MaxAccelMpSS) { AdjustControlsAccelMore(Efficiency * 0.5f * MaxAccelMpSS, elapsedClockSeconds, 10); } - if (SpeedMpS > (AllowedMaxSpeedMpS - ((9.0f - 6.0f * Efficiency) * hysterisMpS))) + if (SpeedMpS > (AllowedMaxSpeedMpS - ((9.0f - (6.0f * Efficiency)) * hysterisMpS))) { AdjustControlsAccelLess(0.0f, elapsedClockSeconds, (int)(AITrainThrottlePercent * 0.5f)); MovementState = AI_MOVEMENT_STATE.RUNNING; @@ -5136,7 +4927,6 @@ public override void UpdateAccelState(float elapsedClockSeconds) /// Update train in following state (train ahead in same section) /// Override from AITrain class /// <\summary> - public override void UpdateFollowingState(float elapsedClockSeconds, int presentTime) { if (CheckTrain) @@ -5144,12 +4934,12 @@ public override void UpdateFollowingState(float elapsedClockSeconds, int present File.AppendAllText(@"C:\temp\checktrain.txt", "Update Train Ahead - now at : " + PresentPosition[0].TCSectionIndex.ToString() + " " + - // FormatStrings.FormatDistance(PresentPosition[0].TCOffset, true) + + // FormatStrings.FormatDistance(PresentPosition[0].TCOffset, true) + PresentPosition[0].TCOffset.ToString() + " ; speed : " + FormatStrings.FormatSpeed(SpeedMpS, true) + "\n"); } - if (ControlMode != TRAIN_CONTROL.AUTO_NODE || EndAuthorityType[0] != END_AUTHORITY.TRAIN_AHEAD) // train is gone + if (ControlMode != TRAIN_CONTROL.AUTO_NODE || EndAuthorityType[0] != END_AUTHORITY.TRAIN_AHEAD) // Train is gone { if (CheckTrain) { @@ -5160,10 +4950,10 @@ public override void UpdateFollowingState(float elapsedClockSeconds, int present } else { - // check if train is in sections ahead + // Check if train is in sections ahead Dictionary trainInfo = null; - // find other train + // Find other train int sectionIndex = ValidRoute[0][PresentPosition[0].RouteListIndex].TCSectionIndex; int startIndex = PresentPosition[0].RouteListIndex; int endSectionIndex = LastReservedSection[0]; @@ -5177,7 +4967,7 @@ public override void UpdateFollowingState(float elapsedClockSeconds, int present { addOffset = thisSection.Length - PresentPosition[0].TCOffset; - // train not in this section, try reserved sections ahead + // Train not in this section, try reserved sections ahead for (int iIndex = startIndex + 1; iIndex <= endIndex; iIndex++) { TrackCircuitSection nextSection = signalRef.TrackCircuitList[ValidRoute[0][iIndex].TCSectionIndex]; @@ -5187,17 +4977,17 @@ public override void UpdateFollowingState(float elapsedClockSeconds, int present addOffset += nextSection.Length; } } - // if train not ahead, try first section beyond last reserved + // If train not ahead, try first section beyond last reserved if (trainInfo.Count <= 0 && endIndex < ValidRoute[0].Count - 1) { TrackCircuitSection nextSection = signalRef.TrackCircuitList[ValidRoute[0][endIndex + 1].TCSectionIndex]; trainInfo = nextSection.TestTrainAhead(this, 0, ValidRoute[0][endIndex + 1].Direction); } - // if train found get distance - if (trainInfo.Count > 0) // found train + // If train found get distance + if (trainInfo.Count > 0) // Found train { - foreach (KeyValuePair trainAhead in trainInfo) // always just one + foreach (KeyValuePair trainAhead in trainInfo) // Always just one { Train OtherTrain = trainAhead.Key; float distanceToTrain = trainAhead.Value + addOffset; @@ -5206,7 +4996,7 @@ public override void UpdateFollowingState(float elapsedClockSeconds, int present } else { - // ensure train in section is aware of this train in same section if this is required + // Ensure train in section is aware of this train in same section if this is required if (PresentPosition[1].TCSectionIndex != thisSection.Index) { UpdateTrainOnEnteringSection(thisSection, trainInfo); @@ -5219,14 +5009,14 @@ public override void UpdateFollowingState(float elapsedClockSeconds, int present "Train count in section " + sectionIndex.ToString() + " = " + trainInfo.Count.ToString() + "\n"); } - // train not in this section, try reserved sections ahead + // Train not in this section, try reserved sections ahead for (int iIndex = startIndex + 1; iIndex <= endIndex && trainInfo.Count <= 0; iIndex++) { TrackCircuitSection nextSection = signalRef.TrackCircuitList[ValidRoute[0][iIndex].TCSectionIndex]; trainInfo = nextSection.TestTrainAhead(this, 0, ValidRoute[0][iIndex].Direction); } - // if train not ahead, try first section beyond last reserved + // If train not ahead, try first section beyond last reserved if (trainInfo.Count <= 0 && endIndex < ValidRoute[0].Count - 1) { TrackCircuitSection nextSection = signalRef.TrackCircuitList[ValidRoute[0][endIndex + 1].TCSectionIndex]; @@ -5237,10 +5027,10 @@ public override void UpdateFollowingState(float elapsedClockSeconds, int present } } - // train is found - if (trainInfo.Count > 0) // found train + // Train is found + if (trainInfo.Count > 0) // Found train { - foreach (KeyValuePair trainAhead in trainInfo) // always just one + foreach (KeyValuePair trainAhead in trainInfo) // Always just one { TTTrain OtherTrain = trainAhead.Key as TTTrain; float distanceToTrain = trainAhead.Value + addOffset; @@ -5250,15 +5040,15 @@ public override void UpdateFollowingState(float elapsedClockSeconds, int present File.AppendAllText(@"C:\temp\checktrain.txt", "Other train : " + OtherTrain.Number.ToString() + " at : " + OtherTrain.PresentPosition[0].TCSectionIndex.ToString() + " " + - // FormatStrings.FormatDistance(OtherTrain.PresentPosition[0].TCOffset, true) + + // FormatStrings.FormatDistance(OtherTrain.PresentPosition[0].TCOffset, true) + OtherTrain.PresentPosition[0].TCOffset.ToString() + " ; speed : " + FormatStrings.FormatSpeed(OtherTrain.SpeedMpS, true) + "\n"); File.AppendAllText(@"C:\temp\checktrain.txt", - // "DistAhd: " + FormatStrings.FormatDistance(DistanceToEndNodeAuthorityM[0], true) + "\n"); + // "DistAhd: " + FormatStrings.FormatDistance(DistanceToEndNodeAuthorityM[0], true) + "\n"); "DistAhd: " + DistanceToEndNodeAuthorityM[0].ToString() + "\n"); } - // update action info with new position + // Update action info with new position float keepDistanceTrainM = 0f; bool attachToTrain = false; @@ -5268,18 +5058,18 @@ public override void UpdateFollowingState(float elapsedClockSeconds, int present int? transferStationIndex = null; int? transferTrainIndex = null; - // check attach details + // Check attach details if (AttachDetails != null && AttachDetails.Valid && AttachDetails.ReadyToAttach && AttachDetails.AttachTrain == OtherTrain.OrgAINumber) { attachToTrain = true; } - // check pickup details + // Check pickup details if (!attachToTrain) { pickUpTrain = CheckPickUp(OtherTrain); - // check transfer details + // Check transfer details transferTrain = CheckTransfer(OtherTrain, ref transferStationIndex, ref transferTrainIndex); } @@ -5296,28 +5086,28 @@ public override void UpdateFollowingState(float elapsedClockSeconds, int present else if (!attachToTrain && !pickUpTrain && !transferTrain) { keepDistanceTrainM = (OtherTrain.IsFreight || IsFreight) ? keepDistanceStatTrainM_F : keepDistanceStatTrainM_P; - // if closeup is set for termination + // If closeup is set for termination if (Closeup) { keepDistanceTrainM = keepDistanceTrainAheadCloseupM; } - // if train has station stop and closeup set, check if approaching train in station + // If train has station stop and closeup set, check if approaching train in station if (StationStops != null && StationStops.Count > 0 && StationStops[0].Closeup) { - // other train at station and this is same station + // Other train at station and this is same station if (OtherTrain.AtStation && OtherTrain.StationStops[0].PlatformItem.Name == StationStops[0].PlatformItem.Name) { keepDistanceTrainM = keepDistanceTrainAheadCloseupM; } - // other train in station and this is same station + // Other train in station and this is same station else if (OtherTrain.PresentPosition[1].TCSectionIndex == StationStops[0].TCSectionIndex) { keepDistanceTrainM = keepDistanceTrainAheadCloseupM; } } - // if reversing on track where train is located, also allow closeup + // If reversing on track where train is located, also allow closeup if (TCRoute.activeSubpath < TCRoute.TCRouteSubpaths.Count - 1 && TCRoute.ReversalInfo[TCRoute.activeSubpath].Valid) { if (TCRoute.ReversalInfo[TCRoute.activeSubpath].ReversalSectionIndex == OtherTrain.PresentPosition[0].TCSectionIndex || @@ -5333,22 +5123,17 @@ public override void UpdateFollowingState(float elapsedClockSeconds, int present NextStopDistanceM = distanceToTrain - keepDistanceTrainM; } - // disregard action if train is to attach + // Disregard action if train is to attach else if (nextActionInfo != null && !(attachToTrain || pickUpTrain || transferTrain)) { float deltaDistance = nextActionInfo.ActivateDistanceM - DistanceTravelledM; - if (nextActionInfo.RequiredSpeedMpS > 0.0f) - { - NextStopDistanceM = distanceToTrain - keepDistanceTrainM; - } - else - { - NextStopDistanceM = Math.Min(deltaDistance, (distanceToTrain - keepDistanceTrainM)); - } + NextStopDistanceM = nextActionInfo.RequiredSpeedMpS > 0.0f + ? distanceToTrain - keepDistanceTrainM + : Math.Min(deltaDistance, distanceToTrain - keepDistanceTrainM); - if (deltaDistance < distanceToTrain) // perform to normal braking to handle action + if (deltaDistance < distanceToTrain) // Perform to normal braking to handle action { - MovementState = AI_MOVEMENT_STATE.BRAKING; // not following the train + MovementState = AI_MOVEMENT_STATE.BRAKING; // Not following the train UpdateBrakingState(elapsedClockSeconds, presentTime); return; } @@ -5373,14 +5158,14 @@ public override void UpdateFollowingState(float elapsedClockSeconds, int present if (attachToTrain) { - // check if any other train needs to be activated + // Check if any other train needs to be activated ActivateTriggeredTrain(TriggerActivationType.Dispose, -1); - TTCouple(OtherTrain, thisTrainFront, otherTrainFront); // couple this train to other train (this train is aborted) + TTCouple(OtherTrain, thisTrainFront, otherTrainFront); // Couple this train to other train (this train is aborted) } else if (pickUpTrain) { - OtherTrain.TTCouple(this, otherTrainFront, thisTrainFront); // couple other train to this train (other train is aborted) + OtherTrain.TTCouple(this, otherTrainFront, thisTrainFront); // Couple other train to this train (other train is aborted) NeedPickUp = false; } else if (transferTrain) @@ -5399,13 +5184,13 @@ public override void UpdateFollowingState(float elapsedClockSeconds, int present } } - // check distance and speed + // Check distance and speed else if (Math.Abs(OtherTrain.SpeedMpS) < 0.1f) { float brakingDistance = SpeedMpS * SpeedMpS * 0.5f * (0.5f * MaxDecelMpSS); float reqspeed = (float)Math.Sqrt(distanceToTrain * MaxDecelMpSS); - // allow creepspeed, but if to attach, allow only attach speed + // Allow creepspeed, but if to attach, allow only attach speed float maxspeed = attachToTrain || pickUpTrain || transferTrain ? Math.Max(reqspeed / 2, SpeedSettings.attachSpeedMpS.Value) : Math.Max(reqspeed / 2, SpeedSettings.creepSpeedMpS.Value); if (attachToTrain && AttachDetails.SetBack) @@ -5413,9 +5198,9 @@ public override void UpdateFollowingState(float elapsedClockSeconds, int present maxspeed = SpeedSettings.attachSpeedMpS.Value; } - maxspeed = Math.Min(maxspeed, AllowedMaxSpeedMpS); // but never beyond valid speed limit + maxspeed = Math.Min(maxspeed, AllowedMaxSpeedMpS); // But never beyond valid speed limit - // set brake or acceleration as required + // Set brake or acceleration as required if (SpeedMpS > maxspeed) { @@ -5455,7 +5240,7 @@ public override void UpdateFollowingState(float elapsedClockSeconds, int present { AdjustControlsBrakeMore(MaxDecelMpSS, elapsedClockSeconds, 50); - // if too close, force stop or slow down if coupling + // If too close, force stop or slow down if coupling if (distanceToTrain < 0.25 * keepDistanceTrainM) { foreach (TrainCar car in Cars) @@ -5481,32 +5266,25 @@ public override void UpdateFollowingState(float elapsedClockSeconds, int present { MovementState = AI_MOVEMENT_STATE.STOPPED; - // check if stopped in next station - // conditions : - // next action must be station stop - // next station must be in this subroute - // if next train is AI and that trains state is STATION_STOP, station must be ahead of present position - // else this train must be in station section + // Check if stopped in next station + // Conditions : + // Next action must be station stop + // Next station must be in this subroute + // If next train is AI and that trains state is STATION_STOP, station must be ahead of present position + // Else this train must be in station section bool otherTrainInStation = false; - TTTrain OtherAITrain = OtherTrain as TTTrain; - otherTrainInStation = (OtherAITrain.MovementState == AI_MOVEMENT_STATE.STATION_STOP || OtherAITrain.MovementState == AI_MOVEMENT_STATE.AI_STATIC); + TTTrain OtherAITrain = OtherTrain; + otherTrainInStation = OtherAITrain.MovementState == AI_MOVEMENT_STATE.STATION_STOP || OtherAITrain.MovementState == AI_MOVEMENT_STATE.AI_STATIC; - bool thisTrainInStation = (nextActionInfo != null && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.STATION_STOP); - if (thisTrainInStation) thisTrainInStation = (StationStops[0].SubrouteIndex == TCRoute.activeSubpath); + bool thisTrainInStation = nextActionInfo != null && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.STATION_STOP; + if (thisTrainInStation) thisTrainInStation = StationStops[0].SubrouteIndex == TCRoute.activeSubpath; if (thisTrainInStation) { - if (otherTrainInStation) - { - thisTrainInStation = - (ValidRoute[0].GetRouteIndex(StationStops[0].TCSectionIndex, PresentPosition[0].RouteListIndex) >= PresentPosition[0].RouteListIndex); - } - else - { - thisTrainInStation = - (ValidRoute[0].GetRouteIndex(StationStops[0].TCSectionIndex, PresentPosition[0].RouteListIndex) == PresentPosition[0].RouteListIndex); - } + thisTrainInStation = otherTrainInStation + ? ValidRoute[0].GetRouteIndex(StationStops[0].TCSectionIndex, PresentPosition[0].RouteListIndex) >= PresentPosition[0].RouteListIndex + : ValidRoute[0].GetRouteIndex(StationStops[0].TCSectionIndex, PresentPosition[0].RouteListIndex) == PresentPosition[0].RouteListIndex; } if (CheckTrain && StationStops.Count > 0) @@ -5556,20 +5334,20 @@ public override void UpdateFollowingState(float elapsedClockSeconds, int present { thisStation.ActualArrival = presentTime; - // delta time set + // Delta time set if (thisStation.DepartTime < 0) { - thisStation.ActualDepart = presentTime - thisStation.DepartTime; // depart time is negative!! + thisStation.ActualDepart = presentTime - thisStation.DepartTime; // Depart time is negative!! } - // actual time set + // Actual time set else { thisStation.ActualDepart = thisStation.DepartTime; } - // if waited behind other train, move remaining track sections to next subroute if required + // If waited behind other train, move remaining track sections to next subroute if required - // scan sections in backward order + // Scan sections in backward order TCSubpathRoute nextRoute = TCRoute.TCRouteSubpaths[TCRoute.activeSubpath + 1]; for (int iIndex = ValidRoute[0].Count - 1; iIndex > PresentPosition[0].RouteListIndex; iIndex--) @@ -5605,12 +5383,12 @@ public override void UpdateFollowingState(float elapsedClockSeconds, int present } } } - // if getting too close apply full brake + // If getting too close apply full brake else if (distanceToTrain < (2 * clearingDistanceM)) { AdjustControlsBrakeFull(); } - // check only if train is close and other train speed is below allowed speed + // Check only if train is close and other train speed is below allowed speed else if (distanceToTrain < keepDistanceTrainM - clearingDistanceM && OtherTrain.SpeedMpS < AllowedMaxSpeedMpS) { if (SpeedMpS > (OtherTrain.SpeedMpS + hysterisMpS) || @@ -5626,12 +5404,12 @@ distanceToTrain > (keepDistanceTrainM + clearingDistanceM)) AdjustControlsAccelMore(0.5f * MaxAccelMpSS, elapsedClockSeconds, 2); } } - // perform normal update + // Perform normal update else UpdateRunningState(elapsedClockSeconds); } } - // train not found - keep moving, state will change next update + // Train not found - keep moving, state will change next update } } @@ -5640,13 +5418,12 @@ distanceToTrain > (keepDistanceTrainM + clearingDistanceM)) /// Update train in running state /// Override from AITrain class /// <\summary> - public override void UpdateRunningState(float elapsedClockSeconds) { float topBand = AllowedMaxSpeedMpS - ((1.5f - Efficiency) * hysterisMpS); - float highBand = Math.Max(0.5f, AllowedMaxSpeedMpS - ((3.0f - 2.0f * Efficiency) * hysterisMpS)); - float lowBand = Math.Max(0.4f, AllowedMaxSpeedMpS - ((9.0f - 3.0f * Efficiency) * hysterisMpS)); + float highBand = Math.Max(0.5f, AllowedMaxSpeedMpS - ((3.0f - (2.0f * Efficiency)) * hysterisMpS)); + float lowBand = Math.Max(0.4f, AllowedMaxSpeedMpS - ((9.0f - (3.0f * Efficiency)) * hysterisMpS)); if (CheckTrain) { @@ -5670,13 +5447,13 @@ public override void UpdateRunningState(float elapsedClockSeconds) " A&B(S): " + AITrainThrottlePercent.ToString() + " - " + AITrainBrakePercent.ToString() + "\n"); } - // check speed + // Check speed if (SpeedMpS > AllowedMaxSpeedMpS) { if (CheckTrain) { - File.AppendAllText(@"C:\temp\checktrain.txt","Section : > AllowedMaxSpeedMps \n"); + File.AppendAllText(@"C:\temp\checktrain.txt", "Section : > AllowedMaxSpeedMps \n"); } if (AITrainThrottlePercent > 0) @@ -5813,10 +5590,9 @@ public override void UpdateRunningState(float elapsedClockSeconds) /// /// Delay Start Moving /// <\summary> - public void DelayedStartMoving(AI_START_MOVEMENT reason) { - // do not apply delayed restart while running in pre-update + // Do not apply delayed restart while running in pre-update if (Simulator.PreUpdate) { RestdelayS = 0.0f; @@ -5825,13 +5601,13 @@ public void DelayedStartMoving(AI_START_MOVEMENT reason) return; } - // note : RestDelayS may have a preset value due to previous action (e.g. reverse) + // Note : RestDelayS may have a preset value due to previous action (e.g. reverse) int randDelayPart = 0; float baseDelayPart = 0; switch (reason) { - case AI_START_MOVEMENT.END_STATION_STOP: // not used as state is processed through stop - rest delay is preset + case AI_START_MOVEMENT.END_STATION_STOP: // Not used as state is processed through stop - rest delay is preset break; case AI_START_MOVEMENT.FOLLOW_TRAIN: @@ -5860,8 +5636,8 @@ public void DelayedStartMoving(AI_START_MOVEMENT reason) break; } - float randDelay = (float)Simulator.Random.Next(randDelayPart); - RestdelayS += (baseDelayPart + (randDelay / 10f)); + float randDelay = Simulator.Random.Next(randDelayPart); + RestdelayS += baseDelayPart + (randDelay / 10f); DelayedStart = true; DelayedStartState = reason; @@ -5875,11 +5651,9 @@ public void DelayedStartMoving(AI_START_MOVEMENT reason) /// Start Moving /// Override from AITrain class /// <\summary> - public override void StartMoving(AI_START_MOVEMENT reason) { - // reset brakes, set throttle - + // Reset brakes, set throttle if (reason == AI_START_MOVEMENT.FOLLOW_TRAIN) { MovementState = AI_MOVEMENT_STATE.FOLLOWING; @@ -5888,7 +5662,7 @@ public override void StartMoving(AI_START_MOVEMENT reason) } else if (reason == AI_START_MOVEMENT.TURNTABLE) { - if (MovementState != AI_MOVEMENT_STATE.AI_STATIC) // do not restart while still in static mode) + if (MovementState != AI_MOVEMENT_STATE.AI_STATIC) // Do not restart while still in static mode) { MovementState = AI_MOVEMENT_STATE.TURNTABLE; } @@ -5903,7 +5677,7 @@ public override void StartMoving(AI_START_MOVEMENT reason) MovementState = AI_MOVEMENT_STATE.STOPPED; AITrainThrottlePercent = 0; } - else if (nextActionInfo != null) // train has valid action, so start in BRAKE mode + else if (nextActionInfo != null) // Train has valid action, so start in BRAKE mode { MovementState = AI_MOVEMENT_STATE.BRAKING; Alpha10 = 10; @@ -5929,13 +5703,11 @@ public override void StartMoving(AI_START_MOVEMENT reason) /// /// Calculate initial position /// - public TCSubpathRoute CalculateInitialTTTrainPosition(ref bool trackClear, List nextTrains) { bool sectionAvailable = true; - // calculate train length - + // Calculate train length float trainLength = 0f; for (var i = Cars.Count - 1; i >= 0; --i) @@ -5948,34 +5720,33 @@ public TCSubpathRoute CalculateInitialTTTrainPosition(ref bool trackClear, List< trainLength += car.CarLengthM; } - // default is no referenced train + // Default is no referenced train TTTrain otherTTTrain = null; - // check if to be placed ahead of other train - + // Check if to be placed ahead of other train if (!String.IsNullOrEmpty(CreateAhead)) { otherTTTrain = GetOtherTTTrainByName(CreateAhead); - // if not found - check if it is the player train + // If not found - check if it is the player train if (otherTTTrain == null) { if (Simulator.PlayerLocomotive != null && Simulator.PlayerLocomotive.Train != null && String.Equals(Simulator.PlayerLocomotive.Train.Name.ToLower(), CreateAhead)) { TTTrain playerTrain = Simulator.PlayerLocomotive.Train as TTTrain; - if (playerTrain.TrainType == TRAINTYPE.PLAYER || playerTrain.TrainType == TRAINTYPE.INTENDED_PLAYER) // train is started + if (playerTrain.TrainType == TRAINTYPE.PLAYER || playerTrain.TrainType == TRAINTYPE.INTENDED_PLAYER) // Train is started { otherTTTrain = Simulator.PlayerLocomotive.Train as TTTrain; } } } - // if other train does not yet exist, check if it is on the 'to start' list, and check start-time + // If other train does not yet exist, check if it is on the 'to start' list, and check start-time if (otherTTTrain == null) { otherTTTrain = AI.StartList.GetNotStartedTTTrainByName(CreateAhead, false); - // if other train still does not exist, check if it is on starting list + // If other train still does not exist, check if it is on starting list if (otherTTTrain == null && nextTrains != null) { foreach (TTTrain otherTT in nextTrains) @@ -5988,7 +5759,7 @@ public TCSubpathRoute CalculateInitialTTTrainPosition(ref bool trackClear, List< } } - // if really not found - set error + // If really not found - set error if (otherTTTrain == null) { Trace.TraceWarning("Creating train : " + Name + " ; cannot find train " + CreateAhead + " for initial placement, /ahead qualifier ignored\n"); @@ -6006,17 +5777,17 @@ public TCSubpathRoute CalculateInitialTTTrainPosition(ref bool trackClear, List< Trace.TraceWarning("Creating train : " + Name + " ; train refered in /ahead qualifier has later start-time, start time for this train reset\n"); StartTime = otherTTTrain.StartTime + 1; } - // train is to be started now so just wait + // Train is to be started now so just wait else { trackClear = false; - return (null); + return null; } } } } - // get starting position and route + // Get starting position and route TrackNode tn = RearTDBTraveller.TN; float offset = RearTDBTraveller.TrackNodeOffset; @@ -6026,7 +5797,7 @@ public TCSubpathRoute CalculateInitialTTTrainPosition(ref bool trackClear, List< TrackCircuitSection thisSection = signalRef.TrackCircuitList[PresentPosition[1].TCSectionIndex]; offset = PresentPosition[1].TCOffset; - // create route if train has none + // Create route if train has none if (ValidRoute[0] == null) { @@ -6034,7 +5805,7 @@ public TCSubpathRoute CalculateInitialTTTrainPosition(ref bool trackClear, List< PresentPosition[1].TCDirection, trainLength, true, true, false); } - // find sections + // Find sections float remLength = trainLength; int routeIndex = ValidRoute[0].GetRouteIndex(PresentPosition[1].TCSectionIndex, 0); @@ -6046,7 +5817,7 @@ public TCSubpathRoute CalculateInitialTTTrainPosition(ref bool trackClear, List< TCSubpathRoute tempRoute = new TCSubpathRoute(); TCRouteElement thisElement = ValidRoute[0][routeIndex]; - // check sections if not placed ahead of other train + // Check sections if not placed ahead of other train if (otherTTTrain != null) { @@ -6064,7 +5835,7 @@ public TCSubpathRoute CalculateInitialTTTrainPosition(ref bool trackClear, List< while (remLength > 0 && sectionAvailable) { tempRoute.Add(thisElement); - remLength -= (thisSection.Length - offset); + remLength -= thisSection.Length - offset; offset = 0.0f; if (remLength > 0) @@ -6098,7 +5869,7 @@ public TCSubpathRoute CalculateInitialTTTrainPosition(ref bool trackClear, List< tempRoute.Clear(); } - return (tempRoute); + return tempRoute; } //================================================================================================// @@ -6107,12 +5878,10 @@ public TCSubpathRoute CalculateInitialTTTrainPosition(ref bool trackClear, List< /// /// /// - public bool InitialTrainPlacement(bool testOccupied) { - // for initial placement, use direction 0 only - // set initial positions - + // For initial placement, use direction 0 only + // Set initial positions TrackNode tn = FrontTDBTraveller.TN; float offset = FrontTDBTraveller.TrackNodeOffset; int direction = (int)FrontTDBTraveller.Direction; @@ -6128,8 +5897,7 @@ public bool InitialTrainPlacement(bool testOccupied) PresentPosition[1].SetTCPosition(tn.TCCrossReference, offset, direction); - // create route to cover all train sections - + // Create route to cover all train sections TCSubpathRoute tempRoute = signalRef.BuildTempRoute(this, PresentPosition[1].TCSectionIndex, PresentPosition[1].TCOffset, PresentPosition[1].TCDirection, Length, true, true, false); @@ -6138,8 +5906,7 @@ public bool InitialTrainPlacement(bool testOccupied) ValidRoute[0] = new TCSubpathRoute(tempRoute); } - // get index of first section in route - + // Get index of first section in route int rearIndex = ValidRoute[0].GetRouteIndex(PresentPosition[1].TCSectionIndex, 0); if (rearIndex < 0) { @@ -6152,8 +5919,7 @@ public bool InitialTrainPlacement(bool testOccupied) PresentPosition[1].RouteListIndex = rearIndex; - // get index of front of train - + // Get index of front of train int frontIndex = ValidRoute[0].GetRouteIndex(PresentPosition[0].TCSectionIndex, 0); if (frontIndex < 0) { @@ -6163,14 +5929,12 @@ public bool InitialTrainPlacement(bool testOccupied) PresentPosition[0].RouteListIndex = frontIndex; - // check if train can be placed - // get index of section in train route // - + // Check if train can be placed + // Get index of section in train route // int routeIndex = rearIndex; List placementSections = new List(); - // check if route is available - use temp route as trains own route may not cover whole train - + // Check if route is available - use temp route as trains own route may not cover whole train offset = PresentPosition[1].TCOffset; float remLength = Length; bool sectionAvailable = true; @@ -6181,7 +5945,7 @@ public bool InitialTrainPlacement(bool testOccupied) if (thisSection.CanPlaceTrain(this, offset, remLength) || !testOccupied) { placementSections.Add(thisSection); - remLength -= (thisSection.Length - offset); + remLength -= thisSection.Length - offset; if (remLength > 0) { @@ -6206,15 +5970,13 @@ public bool InitialTrainPlacement(bool testOccupied) } } - // if not available - return - + // If not available - return if (!sectionAvailable || placementSections.Count <= 0) { - return (false); + return false; } - // set any deadlocks for sections ahead of start with end beyond start - + // Set any deadlocks for sections ahead of start with end beyond start for (int iIndex = 0; iIndex < rearIndex; iIndex++) { int rearSectionIndex = ValidRoute[0][iIndex].TCSectionIndex; @@ -6235,8 +5997,7 @@ public bool InitialTrainPlacement(bool testOccupied) } } - // set track occupied (if not done yet) - + // Set track occupied (if not done yet) List newPlacementSections = new List(); foreach (TrackCircuitSection thisSection in placementSections) { @@ -6246,27 +6007,27 @@ public bool InitialTrainPlacement(bool testOccupied) } } - // first reserve to ensure switches are all alligned properly + // First reserve to ensure switches are all alligned properly foreach (TrackCircuitSection thisSection in newPlacementSections) { thisSection.Reserve(routedForward, ValidRoute[0]); } - // next set occupied + // Next set occupied foreach (TrackCircuitSection thisSection in newPlacementSections) { if (OccupiedTrack.Contains(thisSection)) OccupiedTrack.Remove(thisSection); thisSection.SetOccupied(routedForward); } - // reset TrackOccupied to remove any 'hanging' occupations and set the sections in correct sequence + // Reset TrackOccupied to remove any 'hanging' occupations and set the sections in correct sequence OccupiedTrack.Clear(); foreach (TrackCircuitSection thisSection in placementSections) { OccupiedTrack.Add(thisSection); } - return (true); + return true; } //================================================================================================// @@ -6277,43 +6038,41 @@ public bool InitialTrainPlacement(bool testOccupied) /// /// /// - public bool GetPositionAheadOfTrain(TTTrain otherTTTrain, TCSubpathRoute trainRoute, ref TCSubpathRoute tempRoute) { bool validPlacement = false; float remainingLength = Length; - // get front position of other train + // Get front position of other train int otherTrainSectionIndex = otherTTTrain.PresentPosition[0].TCSectionIndex; int routeListIndex = trainRoute.GetRouteIndex(otherTrainSectionIndex, 0); - // front position is not in this trains route - reset clear ahead and check normal path + // Front position is not in this trains route - reset clear ahead and check normal path if (routeListIndex < 0) { Trace.TraceWarning("Train : " + Name + " : train referred to in /ahead qualifier is not in train's path, /ahead ignored\n"); CreateAhead = String.Empty; tempRoute = CalculateInitialTrainPosition(ref validPlacement); - return (validPlacement); + return validPlacement; } - // front position is in this trains route - check direction + // Front position is in this trains route - check direction TCRouteElement thisElement = trainRoute[routeListIndex]; - // not the same direction : cannot place train as front or rear is now not clear + // Not the same direction : cannot place train as front or rear is now not clear if (otherTTTrain.PresentPosition[0].TCDirection != thisElement.Direction) { Trace.TraceWarning("Train : " + Name + " : train referred to in /ahead qualifier has different direction, train can not be placed \n"); - return (false); + return false; } - // train is positioned correctly - + // Train is positioned correctly TrackCircuitSection thisSection = signalRef.TrackCircuitList[thisElement.TCSectionIndex]; float startoffset = otherTTTrain.PresentPosition[0].TCOffset + keepDistanceCloseupM; int firstSection = thisElement.TCSectionIndex; - // train starts in same section - check rest of section + // Train starts in same section - check rest of section if (startoffset <= thisSection.Length) { @@ -6326,27 +6085,27 @@ public bool GetPositionAheadOfTrain(TTTrain otherTTTrain, TCSubpathRoute trainRo Dictionary moreTrains = thisSection.TestTrainAhead(this, startoffset, thisElement.Direction); - // more trains found - check if sufficient space in between, if so, place train + // More trains found - check if sufficient space in between, if so, place train if (moreTrains.Count > 0) { KeyValuePair nextTrainInfo = moreTrains.ElementAt(0); if (nextTrainInfo.Value > Length) { - return (true); + return true; } - // more trains found - cannot place train - // do not report as warning - train may move away in time - return (false); + // More trains found - cannot place train + // Do not report as warning - train may move away in time + return false; } - // no other trains in section - determine remaining length - remainingLength -= (thisSection.Length - startoffset); + // No other trains in section - determine remaining length + remainingLength -= thisSection.Length - startoffset; validPlacement = true; } else { - startoffset = startoffset - thisSection.Length; // offset in next section + startoffset -= thisSection.Length; // Offset in next section routeListIndex++; if (routeListIndex <= trainRoute.Count - 1) @@ -6360,15 +6119,15 @@ public bool GetPositionAheadOfTrain(TTTrain otherTTTrain, TCSubpathRoute trainRo } } - // check for rest of train + // Check for rest of train float offset = startoffset; - // test rest of train in rest of route + // Test rest of train in rest of route while (remainingLength > 0 && validPlacement) { tempRoute.Add(thisElement); - remainingLength -= (thisSection.Length - offset); + remainingLength -= thisSection.Length - offset; if (remainingLength > 0) { @@ -6392,7 +6151,7 @@ public bool GetPositionAheadOfTrain(TTTrain otherTTTrain, TCSubpathRoute trainRo } } - // adjust front traveller to use found offset + // Adjust front traveller to use found offset float moved = -RearTDBTraveller.TrackNodeOffset; foreach (TCRouteElement nextElement in trainRoute) @@ -6410,7 +6169,7 @@ public bool GetPositionAheadOfTrain(TTTrain otherTTTrain, TCSubpathRoute trainRo RearTDBTraveller.Move(moved); - return (validPlacement); + return validPlacement; } //================================================================================================// @@ -6422,7 +6181,6 @@ public bool GetPositionAheadOfTrain(TTTrain otherTTTrain, TCSubpathRoute trainRo /// /// /// - public override bool CheckCouplePosition(Train attachTrain, out bool thisTrainFront, out bool otherTrainFront) { thisTrainFront = true; @@ -6433,7 +6191,7 @@ public override bool CheckCouplePosition(Train attachTrain, out bool thisTrainFr if (MUDirection == Direction.Reverse) { - usedTraveller = new Traveller(RearTDBTraveller, Traveller.TravellerDirection.Backward); // use in direction of movement + usedTraveller = new Traveller(RearTDBTraveller, Traveller.TravellerDirection.Backward); // Use in direction of movement thisTrainFront = false; usePosition = 1; } @@ -6443,23 +6201,23 @@ public override bool CheckCouplePosition(Train attachTrain, out bool thisTrainFr bool withinSection = false; // Check if train is in same section as other train, either for the other trains front or rear - if (PresentPosition[usePosition].TCSectionIndex == attachTrain.PresentPosition[0].TCSectionIndex) // train in same section as front + if (PresentPosition[usePosition].TCSectionIndex == attachTrain.PresentPosition[0].TCSectionIndex) // Train in same section as front { withinSection = true; } - else if (PresentPosition[usePosition].TCSectionIndex == attachTrain.PresentPosition[1].TCSectionIndex) // train in same section as rear + else if (PresentPosition[usePosition].TCSectionIndex == attachTrain.PresentPosition[1].TCSectionIndex) // Train in same section as rear { useOtherPosition = 1; withinSection = true; } - if (!withinSection) // not yet in same section + if (!withinSection) // Not yet in same section { - return (false); + return false; } - // test directions - if (PresentPosition[usePosition].TCDirection == attachTrain.PresentPosition[useOtherPosition].TCDirection) // trains are in same direction + // Test directions + if (PresentPosition[usePosition].TCDirection == attachTrain.PresentPosition[useOtherPosition].TCDirection) // Trains are in same direction { if (usePosition == 1) { @@ -6489,28 +6247,27 @@ public override bool CheckCouplePosition(Train attachTrain, out bool thisTrainFr File.AppendAllText(@"C:\temp\checktrain.txt", "Check couple position : preupdate : " + PreUpdate.ToString() + "\n"); } - //if (PreUpdate) return (true); // in pre-update, being in the same section is good enough + //if (PreUpdate) return (true); // In pre-update, being in the same section is good enough - // check distance to other train + // Check distance to other train float dist = usedTraveller.OverlapDistanceM(otherTraveller, false); if (CheckTrain) { File.AppendAllText(@"C:\temp\checktrain.txt", "Check couple position : distance : " + dist.ToString() + "\n"); } - return (dist < 0.1f); + return dist < 0.1f; } //================================================================================================// /// /// Update Section State - additional - /// clear waitany actions for this section + /// Clear waitany actions for this section /// Override from Train class /// - public override void UpdateSectionState_Additional(int sectionIndex) { - // clear any entries in WaitAnyList as these are now redundant + // Clear any entries in WaitAnyList as these are now redundant if (WaitAnyList != null && WaitAnyList.ContainsKey(sectionIndex)) { WaitAnyList.Remove(sectionIndex); @@ -6525,20 +6282,19 @@ public override void UpdateSectionState_Additional(int sectionIndex) /// /// Clear moving table after moving off table /// - public override void ClearMovingTable(DistanceTravelledItem action) { - // only if valid reference + // Only if valid reference if (ActiveTurntable != null) { ActiveTurntable.RemoveTrainFromTurntable(); ActiveTurntable = null; - // set action to restore original speed + // Set action to restore original speed ClearMovingTableAction clearAction = action as ClearMovingTableAction; float reqDistance = DistanceTravelledM + 1; - ActivateSpeedLimit speedLimit = new ActivateSpeedLimit((DistanceTravelledM + 1), clearAction.OriginalMaxTrainSpeedMpS, clearAction.OriginalMaxTrainSpeedMpS, clearAction.OriginalMaxTrainSpeedMpS); + ActivateSpeedLimit speedLimit = new ActivateSpeedLimit(DistanceTravelledM + 1, clearAction.OriginalMaxTrainSpeedMpS, clearAction.OriginalMaxTrainSpeedMpS, clearAction.OriginalMaxTrainSpeedMpS); requiredActions.InsertAction(speedLimit); } } @@ -6547,7 +6303,6 @@ public override void ClearMovingTable(DistanceTravelledItem action) /// /// Initialize player train /// - public void InitalizePlayerTrain() { TrainType = TRAINTYPE.PLAYER; @@ -6572,16 +6327,16 @@ public void InitalizePlayerTrain() /// public void CheckPlayerAttachState() { - // check for attach + // Check for attach if (AttachDetails != null) { CheckPlayerAttachTrain(); } - // check for pickup + // Check for pickup CheckPlayerPickUpTrain(); - // check for transfer + // Check for transfer CheckPlayerTransferTrain(); } @@ -6592,17 +6347,17 @@ public void CheckPlayerAttachState() /// public void CheckPlayerAttachTrain() { - // check for attach for player train + // Check for attach for player train if (AttachDetails.Valid && AttachDetails.ReadyToAttach) { TTTrain attachTrain = GetOtherTTTrainByNumber(AttachDetails.AttachTrain); if (attachTrain != null) { - // if in neutral, use forward position + // If in neutral, use forward position int direction = MUDirection == Direction.N ? (int)Direction.Forward : (int)MUDirection; - // check if train is in same section + // Check if train is in same section if (PresentPosition[direction].TCSectionIndex == attachTrain.PresentPosition[0].TCSectionIndex || PresentPosition[direction].TCSectionIndex == attachTrain.PresentPosition[1].TCSectionIndex) { @@ -6612,12 +6367,12 @@ public void CheckPlayerAttachTrain() if (readyToAttach) { - ProcessRouteEndTimetablePlayer(); // perform end of route actions + ProcessRouteEndTimetablePlayer(); // Perform end of route actions TTCouple(attachTrain, thisTrainFront, otherTrainFront); } } } - // check if train not yet started + // Check if train not yet started else { attachTrain = AI.StartList.GetNotStartedTTTrainByNumber(AttachDetails.AttachTrain, false); @@ -6628,14 +6383,14 @@ public void CheckPlayerAttachTrain() } } - // train cannot be found + // Train cannot be found if (attachTrain == null) { Trace.TraceWarning("Train {0} : Train {1} to attach to not found", Name, AttachDetails.AttachTrainName); AttachDetails.Valid = false; } } - // check for train to attach in static mode + // Check for train to attach in static mode else if (EndAuthorityType[0] == END_AUTHORITY.TRAIN_AHEAD && AttachDetails.StationPlatformReference < 0 && AttachDetails.Valid) { for (int iRouteSection = PresentPosition[0].RouteListIndex; iRouteSection < ValidRoute[0].Count; iRouteSection++) @@ -6680,10 +6435,10 @@ public void CheckPlayerPickUpTrain() if (NeedPickUp) { - // if in neutral, use forward position + // If in neutral, use forward position int direction = MUDirection == Direction.N ? (int)Direction.Forward : (int)MUDirection; - // check if train is in same section + // Check if train is in same section if (PresentPosition[direction].TCSectionIndex == otherTTTrain.PresentPosition[0].TCSectionIndex || PresentPosition[direction].TCSectionIndex == otherTTTrain.PresentPosition[1].TCSectionIndex) { @@ -6720,12 +6475,12 @@ public void CheckPlayerTransferTrain() int thisSectionIndex = PresentPosition[0].TCSectionIndex; TrackCircuitSection thisSection = signalRef.TrackCircuitList[thisSectionIndex]; - // check train ahead + // Check train ahead if (thisSection.CircuitState.HasOtherTrainsOccupying(routedForward)) { Dictionary trainInfo = thisSection.TestTrainAhead(this, PresentPosition[0].TCOffset, PresentPosition[0].TCDirection); - foreach (KeyValuePair thisTrain in trainInfo) // always just one + foreach (KeyValuePair thisTrain in trainInfo) // Always just one { otherTrain = thisTrain.Key as TTTrain; transferRequired = CheckTransfer(otherTrain, ref transferStationIndex, ref transferTrainIndex); @@ -6734,10 +6489,10 @@ public void CheckPlayerTransferTrain() if (transferRequired) { - // if in neutral, use forward position + // If in neutral, use forward position int direction = MUDirection == Direction.N ? (int)Direction.Forward : (int)MUDirection; - // check if train is in same section + // Check if train is in same section if (PresentPosition[direction].TCSectionIndex == otherTrain.PresentPosition[0].TCSectionIndex || PresentPosition[direction].TCSectionIndex == otherTrain.PresentPosition[1].TCSectionIndex) { @@ -6792,10 +6547,10 @@ public override bool CheckPoolAccess(int sectionIndex) TCSubpathRoute newRoute = thisPool.SetPoolExit(this, out PoolStorageState, true); - // if pool is valid, set new path + // If pool is valid, set new path if (newRoute != null) { - // reset pool access + // Reset pool access PoolAccessSection = -1; if (CheckTrain) @@ -6810,7 +6565,7 @@ public override bool CheckPoolAccess(int sectionIndex) { ValidRoute[0] = new TCSubpathRoute(newRoute); - // remove end-of-route action and recreate it as it may be altered on approach to moving table + // Remove end-of-route action and recreate it as it may be altered on approach to moving table DistanceTravelledItem removeAction = null; foreach (DistanceTravelledItem thisAction in requiredActions) { @@ -6827,13 +6582,13 @@ public override bool CheckPoolAccess(int sectionIndex) if (removeAction != null) requiredActions.Remove(removeAction); - // set new end of route action + // Set new end of route action SetEndOfRouteAction(); } validPool = true; } - // if pool is claimed, set valid pool but take no further actions + // If pool is claimed, set valid pool but take no further actions else if (PoolStorageState == (int)PoolAccessState.PoolClaimed) { if (CheckTrain) @@ -6845,7 +6600,7 @@ public override bool CheckPoolAccess(int sectionIndex) validPool = true; } - // if pool is not valid, reset pool info + // If pool is not valid, reset pool info else { if (CheckTrain) @@ -6854,13 +6609,13 @@ public override bool CheckPoolAccess(int sectionIndex) Number.ToString() + ") exits to pool " + ExitPool + "; pool overflow, pool exit removed \n"); } - // reset pool access + // Reset pool access PoolAccessSection = -1; ExitPool = String.Empty; } } - return (validPool); + return validPool; } //================================================================================================// @@ -6876,7 +6631,7 @@ public override bool CheckPoolAccess(int sectionIndex) /// public override bool TestCallOn(SignalObject thisSignal, bool allowOnNonePlatform, TCSubpathRoute thisRoute, string dumpfile) { - // always allow if set for stable working + // Always allow if set for stable working if (Stable_CallOn) { if (!String.IsNullOrEmpty(dumpfile)) @@ -6885,20 +6640,20 @@ public override bool TestCallOn(SignalObject thisSignal, bool allowOnNonePlatfor sob.AppendFormat("CALL ON : Train {0} : valid - train has Stable_CallOn set \n", Name); File.AppendAllText(dumpfile, sob.ToString()); } - return (true); + return true; } - // test for pool + // Test for pool if (PoolStorageIndex >= 0) { TimetablePool thisPool = AI.Simulator.PoolHolder.Pools[ExitPool]; if (thisPool.TestRouteLeadingToPool(thisRoute, PoolStorageIndex, dumpfile, Name)) { - return (true); + return true; } } - // loop through sections in signal route + // Loop through sections in signal route bool allclear = true; bool intoPlatform = false; bool firstTrainFound = false; @@ -6907,19 +6662,19 @@ public override bool TestCallOn(SignalObject thisSignal, bool allowOnNonePlatfor { TrackCircuitSection routeSection = signalRef.TrackCircuitList[routeElement.TCSectionIndex]; - // if train is to attach to train in section, allow callon if train is stopped + // If train is to attach to train in section, allow callon if train is stopped if (routeSection.CircuitState.HasOtherTrainsOccupying(routedForward)) { firstTrainFound = true; Dictionary trainInfo = routeSection.TestTrainAhead(this, 0, routeElement.Direction); - foreach (KeyValuePair thisTrain in trainInfo) // always just one + foreach (KeyValuePair thisTrain in trainInfo) // Always just one { TTTrain occTTTrain = thisTrain.Key as TTTrain; AITrain.AI_MOVEMENT_STATE movState = occTTTrain.ControlMode == Train.TRAIN_CONTROL.INACTIVE ? AITrain.AI_MOVEMENT_STATE.AI_STATIC : occTTTrain.MovementState; - // if train is moving - do not allow call on + // If train is moving - do not allow call on if (Math.Abs(occTTTrain.SpeedMpS) > 0.1f) { if (!String.IsNullOrEmpty(dumpfile)) @@ -6928,7 +6683,7 @@ public override bool TestCallOn(SignalObject thisSignal, bool allowOnNonePlatfor sob.AppendFormat("CALL ON : Train {0} : invalid - train {1} is moving (speed : {2} (m/s)) \n", Name, occTTTrain.Name, occTTTrain.SpeedMpS); File.AppendAllText(dumpfile, sob.ToString()); } - return (false); + return false; } bool goingToAttach = false; @@ -6947,7 +6702,7 @@ public override bool TestCallOn(SignalObject thisSignal, bool allowOnNonePlatfor sob.AppendFormat("CALL ON : Train {0} : valid - train is to attach to {1} \n", Name, occTTTrain.Name); File.AppendAllText(dumpfile, sob.ToString()); } - return (true); + return true; } else if ((occTTTrain.TrainType == TRAINTYPE.PLAYER || occTTTrain.TrainType == TRAINTYPE.INTENDED_PLAYER) && occTTTrain.AtStation) { @@ -6957,7 +6712,7 @@ public override bool TestCallOn(SignalObject thisSignal, bool allowOnNonePlatfor sob.AppendFormat("CALL ON : Train {0} : valid - train is to attach to {1} \n", Name, occTTTrain.Name); File.AppendAllText(dumpfile, sob.ToString()); } - return (true); + return true; } else { @@ -6967,11 +6722,11 @@ public override bool TestCallOn(SignalObject thisSignal, bool allowOnNonePlatfor sob.AppendFormat("CALL ON : Train {0} : invalid - train is to attach to {1} but train is moving \n", Name, occTTTrain.Name); File.AppendAllText(dumpfile, sob.ToString()); } - return (false); + return false; } } - // check if going to pick up or transfer + // Check if going to pick up or transfer int? transferStationIndex = null; int? transferTrainIndex = null; @@ -6983,7 +6738,7 @@ public override bool TestCallOn(SignalObject thisSignal, bool allowOnNonePlatfor sob.AppendFormat("CALL ON : Train {0} : valid - train is to pickup {1} \n", Name, occTTTrain.Name); File.AppendAllText(dumpfile, sob.ToString()); } - return (true); + return true; } else if (CheckTransfer(occTTTrain, ref transferStationIndex, ref transferTrainIndex)) { @@ -6993,11 +6748,11 @@ public override bool TestCallOn(SignalObject thisSignal, bool allowOnNonePlatfor sob.AppendFormat("CALL ON : Train {0} : valid - train is to transfer to {1} \n", Name, occTTTrain.Name); File.AppendAllText(dumpfile, sob.ToString()); } - return (true); + return true; } } - // check if route leads into platform + // Check if route leads into platform if (routeSection.PlatformIndex.Count > 0) { @@ -7005,10 +6760,10 @@ public override bool TestCallOn(SignalObject thisSignal, bool allowOnNonePlatfor PlatformDetails thisPlatform = signalRef.PlatformDetailsList[routeSection.PlatformIndex[0]]; - // stop is next station stop and callon is set + // Stop is next station stop and callon is set if (StationStops.Count > 0 && StationStops[0].PlatformItem.Name == thisPlatform.Name && StationStops[0].CallOnAllowed) { - // only allow if train ahead is stopped + // Only allow if train ahead is stopped foreach (KeyValuePair occTrainInfo in routeSection.CircuitState.TrainOccupy) { Train.TrainRouted occTrain = occTrainInfo.Key; @@ -7042,7 +6797,7 @@ public override bool TestCallOn(SignalObject thisSignal, bool allowOnNonePlatfor File.AppendAllText(dumpfile, sob.ToString()); } allclear = false; - break; // no need to check for other trains + break; // No need to check for other trains } } } @@ -7058,7 +6813,7 @@ public override bool TestCallOn(SignalObject thisSignal, bool allowOnNonePlatfor } } - // if first train found, check rest of route for platform + // If first train found, check rest of route for platform if (firstTrainFound && !intoPlatform) { int thisSectionRouteIndex = thisRoute.GetRouteIndex(routeSection.Index, 0); @@ -7068,7 +6823,7 @@ public override bool TestCallOn(SignalObject thisSignal, bool allowOnNonePlatfor if (routeSection.PlatformIndex.Count > 0) { PlatformDetails thisPlatform = signalRef.PlatformDetailsList[routeSection.PlatformIndex[0]]; - if (StationStops.Count > 0) // train has stops + if (StationStops.Count > 0) // Train has stops { if (String.Compare(StationStops[0].PlatformItem.Name, thisPlatform.Name) == 0) { @@ -7085,18 +6840,18 @@ public override bool TestCallOn(SignalObject thisSignal, bool allowOnNonePlatfor if (intoPlatform) { - return (allclear); + return allclear; } else { - // path does not lead into platform - return state as defined in call + // Path does not lead into platform - return state as defined in call if (!String.IsNullOrEmpty(dumpfile)) { var sob = new StringBuilder(); sob.AppendFormat("CALL ON : Train {0} : {1} - route does not lead into platform \n", Name, allowOnNonePlatform); File.AppendAllText(dumpfile, sob.ToString()); } - return (allowOnNonePlatform); + return allowOnNonePlatform; } } @@ -7106,7 +6861,7 @@ public override bool TestCallOn(SignalObject thisSignal, bool allowOnNonePlatfor /// public void CheckReadyToAttach() { - // test for attach for train ahead + // Test for attach for train ahead if (AttachDetails != null && AttachDetails.StationPlatformReference < 0 && !AttachDetails.ReadyToAttach) { for (int iRoute = PresentPosition[0].RouteListIndex; iRoute < ValidRoute[0].Count && !AttachDetails.ReadyToAttach; iRoute++) @@ -7139,16 +6894,16 @@ public bool CheckPickUp(TTTrain otherTrain) { bool pickUpTrain = false; - // if allready set, no need to check again + // If allready set, no need to check again if (NeedPickUp) { - return (true); + return true; } - // pick up is only possible if train is stopped, inactive and not reactivated at any time + // Pick up is only possible if train is stopped, inactive and not reactivated at any time if (Math.Abs(otherTrain.SpeedMpS) < 0.1f && otherTrain.ControlMode == TRAIN_CONTROL.INACTIVE && otherTrain.ActivateTime == null) { - // check train + // Check train if (PickUpTrains.Contains(otherTrain.OrgAINumber)) { pickUpTrain = true; @@ -7156,7 +6911,7 @@ public bool CheckPickUp(TTTrain otherTrain) NeedPickUp = true; } - // check platform location + // Check platform location else { foreach (TrackCircuitSection thisSection in otherTrain.OccupiedTrack) @@ -7177,24 +6932,24 @@ public bool CheckPickUp(TTTrain otherTrain) } } - // check if train is at end of path and pickup on forms is required + // Check if train is at end of path and pickup on forms is required if (!pickUpTrain && PickUpStaticOnForms) { - // train is not in last subpath so pickup cannot be valid + // Train is not in last subpath so pickup cannot be valid if (TCRoute.activeSubpath != TCRoute.TCRouteSubpaths.Count - 1) { - return (false); + return false; } - // check if we are at end of route + // Check if we are at end of route if (CheckEndOfRoutePositionTT()) { pickUpTrain = true; PickUpStaticOnForms = false; NeedPickUp = true; } - // check position other train or check remaining route + // Check position other train or check remaining route else { int otherTrainRearIndex = ValidRoute[0].GetRouteIndex(otherTrain.PresentPosition[0].TCSectionIndex, PresentPosition[0].RouteListIndex); @@ -7202,7 +6957,7 @@ public bool CheckPickUp(TTTrain otherTrain) bool validtrain = false; - // other train front or rear is in final section + // Other train front or rear is in final section if (otherTrain.PresentPosition[0].TCSectionIndex == ValidRoute[0][ValidRoute[0].Count - 1].TCSectionIndex) { validtrain = true; @@ -7211,13 +6966,13 @@ public bool CheckPickUp(TTTrain otherTrain) { validtrain = true; } - // other train front or rear is not on our route - other train stretches beyond end of route + // Other train front or rear is not on our route - other train stretches beyond end of route else if (otherTrainRearIndex < 0 || otherTrainFrontIndex < 0) { validtrain = true; } - // check if length of remaining path is less than safety clearance - // use intended route, not actual route as that may be restricted + // Check if length of remaining path is less than safety clearance + // Use intended route, not actual route as that may be restricted else { int useindex = Math.Max(otherTrainRearIndex, otherTrainFrontIndex); @@ -7234,7 +6989,7 @@ public bool CheckPickUp(TTTrain otherTrain) } } - // check if there are any other trains in remaining path + // Check if there are any other trains in remaining path if (!validtrain) { bool moretrains = false; @@ -7263,7 +7018,7 @@ public bool CheckPickUp(TTTrain otherTrain) } } - return (pickUpTrain); + return pickUpTrain; } //================================================================================================// @@ -7278,13 +7033,13 @@ public bool CheckTransfer(TTTrain otherTrain, ref int? stationTransferIndex, ref { bool transferTrain = false; - // transfer is only possible if train is stopped, either at station (station transfer) or as inactive (train transfer) + // Transfer is only possible if train is stopped, either at station (station transfer) or as inactive (train transfer) if (Math.Abs(otherTrain.SpeedMpS) > 0.1f) { - return (transferTrain); + return transferTrain; } - // train transfer + // Train transfer if (otherTrain.ControlMode == TRAIN_CONTROL.INACTIVE) { if (TransferTrainDetails.ContainsKey(otherTrain.OrgAINumber)) @@ -7292,7 +7047,7 @@ public bool CheckTransfer(TTTrain otherTrain, ref int? stationTransferIndex, ref transferTrain = true; trainTransferIndex = otherTrain.OrgAINumber; } - // static transfer required and train is static, set this train number + // Static transfer required and train is static, set this train number else if (TransferTrainDetails.ContainsKey(-99) && otherTrain.MovementState == AI_MOVEMENT_STATE.AI_STATIC && otherTrain.Forms < 0) { TransferTrainDetails.Add(otherTrain.OrgAINumber, TransferTrainDetails[-99]); @@ -7300,15 +7055,15 @@ public bool CheckTransfer(TTTrain otherTrain, ref int? stationTransferIndex, ref transferTrain = true; trainTransferIndex = otherTrain.OrgAINumber; } - - // if found, no need to look any further + + // If found, no need to look any further if (transferTrain) { - return (transferTrain); + return transferTrain; } } - // station transfer + // Station transfer if (otherTrain.AtStation) { if (otherTrain.StationStops != null && otherTrain.StationStops.Count > 0) @@ -7326,7 +7081,7 @@ public bool CheckTransfer(TTTrain otherTrain, ref int? stationTransferIndex, ref } } - // transfer at dispose - check if train in required section + // Transfer at dispose - check if train in required section if (!transferTrain) { if (TransferTrainDetails.ContainsKey(otherTrain.OrgAINumber)) @@ -7343,7 +7098,7 @@ public bool CheckTransfer(TTTrain otherTrain, ref int? stationTransferIndex, ref } } - return (transferTrain); + return transferTrain; } //================================================================================================// @@ -7355,14 +7110,13 @@ public bool CheckTransferRequired() { bool transferRequired = false; - // check if state allready set, if so return state - + // Check if state allready set, if so return state if (NeedTransfer) { - return (NeedTransfer); + return NeedTransfer; } - // check if transfer required + // Check if transfer required if ((TransferStationDetails != null && TransferStationDetails.Count > 0) || (TransferTrainDetails != null && TransferTrainDetails.Count > 0)) { bool firstTrainFound = false; @@ -7375,7 +7129,7 @@ public bool CheckTransferRequired() firstTrainFound = true; Dictionary trainInfo = thisSection.TestTrainAhead(this, 0, ValidRoute[0][iRouteIndex].Direction); - foreach (KeyValuePair thisTrain in trainInfo) // always just one + foreach (KeyValuePair thisTrain in trainInfo) // Always just one { int? transferStationIndex = 0; int? transferTrainIndex = 0; @@ -7391,7 +7145,7 @@ public bool CheckTransferRequired() } } - return (transferRequired); + return transferRequired; } //================================================================================================// @@ -7399,11 +7153,9 @@ public bool CheckTransferRequired() /// Insert action item for end-of-route /// Override from AITrain class /// <\summary> - public override void SetEndOfRouteAction() { - // check if route leads to moving table - + // Check if route leads to moving table float lengthToGoM = 0; TCRouteElement lastElement = ValidRoute[0].Last(); @@ -7412,14 +7164,12 @@ public override void SetEndOfRouteAction() TimetablePool thisPool = AI.Simulator.PoolHolder.Pools[ExitPool]; lengthToGoM = thisPool.GetEndOfRouteDistance(TCRoute.TCRouteSubpaths.Last(), PresentPosition[0], lastElement.MovingTableApproachPath, signalRef); } - - // remaining length first section + // Remaining length first section else { TrackCircuitSection thisSection = signalRef.TrackCircuitList[PresentPosition[0].TCSectionIndex]; lengthToGoM = thisSection.Length - PresentPosition[0].TCOffset; - // go through all further sections - + // Go through all further sections for (int iElement = PresentPosition[0].RouteListIndex + 1; iElement < ValidRoute[0].Count; iElement++) { TCRouteElement thisElement = ValidRoute[0][iElement]; @@ -7427,11 +7177,11 @@ public override void SetEndOfRouteAction() lengthToGoM += thisSection.Length; } - lengthToGoM -= 5.0f; // keep save distance from end + lengthToGoM -= 5.0f; // Keep save distance from end - // if last section does not end at signal or next section is switch, set back overlap to keep clear of switch - // only do so for last subroute to avoid falling short of reversal points - // only do so if last section is not a station and closeup is not set for dispose + // If last section does not end at signal or next section is switch, set back overlap to keep clear of switch + // Only do so for last subroute to avoid falling short of reversal points + // Only do so if last section is not a station and closeup is not set for dispose TrackCircuitSection lastSection = signalRef.TrackCircuitList[lastElement.TCSectionIndex]; if (lastSection.EndSignals[lastElement.Direction] == null && TCRoute.activeSubpath == (TCRoute.TCRouteSubpaths.Count - 1)) @@ -7448,18 +7198,18 @@ public override void SetEndOfRouteAction() } } - // closeup to junction if closeup is set except on last stop or when storing in pool + // Closeup to junction if closeup is set except on last stop or when storing in pool bool reqcloseup = Closeup && String.IsNullOrEmpty(ExitPool); if (nextIndex >= 0 && !lastIsStation && !reqcloseup) { if (signalRef.TrackCircuitList[nextIndex].CircuitType == TrackCircuitSection.TrackCircuitType.Junction) { float lengthCorrection = Math.Max(Convert.ToSingle(signalRef.TrackCircuitList[nextIndex].Overlap), standardOverlapM); - if (lastSection.Length - 2 * lengthCorrection < Length) // make sure train fits + if (lastSection.Length - (2 * lengthCorrection) < Length) // Make sure train fits { lengthCorrection = Math.Max(0.0f, (lastSection.Length - Length) / 2); } - lengthToGoM -= lengthCorrection; // correct for stopping position + lengthToGoM -= lengthCorrection; // Correct for stopping position } } } @@ -7497,7 +7247,7 @@ public override bool isInWaitState() } } - return (inWaitState); + return inWaitState; } //================================================================================================// @@ -7514,10 +7264,10 @@ public override bool CheckAnyWaitCondition(int index) foreach (WaitInfo reqWait in WaitAnyList[index]) { bool pathClear = CheckForRouteWait(reqWait); - return (!pathClear); + return !pathClear; } } - return (false); + return false; } //================================================================================================// @@ -7526,10 +7276,8 @@ public override bool CheckAnyWaitCondition(int index) /// Info will be fully processed after all trains have been created - this is necessary as only then is all required info available /// StationStop info may be null if command is not linked to a station (for commands issued at #note line) /// - public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrouteIndex, int sectionIndex, int stationIndex, int plattformReferenceID, TimetableInfo ttinfo) { - StationStop thisStationStop = (StationStops.Count > 0 && stationIndex >= 0) ? StationStops[stationIndex] : null; switch (thisCommand.CommandToken.Trim()) @@ -7547,26 +7295,19 @@ public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrou WaitInfo newWaitItem = new WaitInfo(); newWaitItem.WaitType = WaitInfo.WaitInfoType.Wait; - if (sectionIndex < 0) - { - newWaitItem.startSectionIndex = TCRoute.TCRouteSubpaths[subrouteIndex][0].TCSectionIndex; - } - else - { - newWaitItem.startSectionIndex = sectionIndex; - } + newWaitItem.startSectionIndex = sectionIndex < 0 ? TCRoute.TCRouteSubpaths[subrouteIndex][0].TCSectionIndex : sectionIndex; newWaitItem.startSubrouteIndex = subrouteIndex; newWaitItem.referencedTrainName = String.Copy(reqReferenceTrain); - // check if name is full name, otherwise add timetable file info from this train + // Check if name is full name, otherwise add timetable file info from this train if (!newWaitItem.referencedTrainName.Contains(':')) { int seppos = Name.IndexOf(':'); newWaitItem.referencedTrainName = String.Concat(newWaitItem.referencedTrainName, ":", Name.Substring(seppos + 1).ToLower()); } - // qualifiers : + // Qualifiers : // maxdelay (single value only) // owndelay (single value only) // notstarted (no value) @@ -7583,7 +7324,7 @@ public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrou case "maxdelay": try { - newWaitItem.maxDelayS = Convert.ToInt32(addQualifier.QualifierValues[0]) * 60; // defined in MINUTES!! + newWaitItem.maxDelayS = Convert.ToInt32(addQualifier.QualifierValues[0]) * 60; // Defined in MINUTES!! } catch { @@ -7600,7 +7341,7 @@ public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrou case "owndelay": try { - newWaitItem.ownDelayS = Convert.ToInt32(addQualifier.QualifierValues[0]) * 60; // defined in MINUTES!! + newWaitItem.ownDelayS = Convert.ToInt32(addQualifier.QualifierValues[0]) * 60; // Defined in MINUTES!! } catch { @@ -7660,26 +7401,19 @@ public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrou WaitInfo newWaitItem = new WaitInfo(); newWaitItem.WaitType = WaitInfo.WaitInfoType.Follow; - if (sectionIndex < 0) - { - newWaitItem.startSectionIndex = TCRoute.TCRouteSubpaths[subrouteIndex][0].TCSectionIndex; - } - else - { - newWaitItem.startSectionIndex = sectionIndex; - } + newWaitItem.startSectionIndex = sectionIndex < 0 ? TCRoute.TCRouteSubpaths[subrouteIndex][0].TCSectionIndex : sectionIndex; newWaitItem.startSubrouteIndex = subrouteIndex; newWaitItem.referencedTrainName = String.Copy(reqReferenceTrain); - // check if name is full name, otherwise add timetable file info from this train + // Check if name is full name, otherwise add timetable file info from this train if (!newWaitItem.referencedTrainName.Contains(':')) { int seppos = Name.IndexOf(':'); newWaitItem.referencedTrainName = String.Concat(newWaitItem.referencedTrainName, ":", Name.Substring(seppos + 1).ToLower()); } - // qualifiers : + // Qualifiers : // maxdelay (single value only) // owndelay (single value only) // notstarted (no value) @@ -7712,7 +7446,7 @@ public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrou case "owndelay": try { - newWaitItem.ownDelayS = Convert.ToInt32(addQualifier.QualifierValues[0]) * 60; // defined in MINUTES!! + newWaitItem.ownDelayS = Convert.ToInt32(addQualifier.QualifierValues[0]) * 60; // Defined in MINUTES!! } catch { @@ -7758,7 +7492,7 @@ public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrou break; case "connect": - // only valid with section index + // Only valid with section index if (sectionIndex < 0 || stationIndex < 0) { @@ -7777,14 +7511,14 @@ public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrou newWaitItem.referencedTrainName = String.Copy(reqReferenceTrain); - // check if name is full name, otherwise add timetable file info from this train + // Check if name is full name, otherwise add timetable file info from this train if (!newWaitItem.referencedTrainName.Contains(':')) { int seppos = Name.IndexOf(':'); newWaitItem.referencedTrainName = String.Concat(newWaitItem.referencedTrainName, ":", Name.Substring(seppos + 1).ToLower()); } - // qualifiers : + // Qualifiers : // maxdelay (single value only) // hold (single value only) @@ -7797,7 +7531,7 @@ public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrou case "maxdelay": try { - newWaitItem.maxDelayS = Convert.ToInt32(addQualifier.QualifierValues[0]) * 60; // defined in MINUTES!! + newWaitItem.maxDelayS = Convert.ToInt32(addQualifier.QualifierValues[0]) * 60; // Defined in MINUTES!! } catch { @@ -7808,7 +7542,7 @@ public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrou case "hold": try { - newWaitItem.holdTimeS = Convert.ToInt32(addQualifier.QualifierValues[0]) * 60; // defined in MINUTES!! + newWaitItem.holdTimeS = Convert.ToInt32(addQualifier.QualifierValues[0]) * 60; // Defined in MINUTES!! } catch { @@ -7844,7 +7578,7 @@ public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrou newWaitItem.PathDirection = WaitInfo.CheckPathDirection.Same; if (thisCommand.CommandQualifiers != null && thisCommand.CommandQualifiers.Count > 0) { - TTTrainCommands.TTTrainComQualifiers thisQualifier = thisCommand.CommandQualifiers[0]; // takes only 1 qualifier + TTTrainCommands.TTTrainComQualifiers thisQualifier = thisCommand.CommandQualifiers[0]; // Takes only 1 qualifier switch (thisQualifier.QualifierName) { case "both": @@ -7865,15 +7599,15 @@ public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrou bool loadPathNoFailure; AIPath fullpath = ttinfo.LoadPath(reqReferencePath, out loadPathNoFailure); - // create a copy of this train to process route - // copy is required as otherwise the original route would be lost + // Create a copy of this train to process route + // Copy is required as otherwise the original route would be lost - if (fullpath != null) // valid path + if (fullpath != null) // Valid path { TCRoutePath fullRoute = new TCRoutePath(fullpath, -2, 1, signalRef, -1, Simulator.Settings); newWaitItem.CheckPath = new TCSubpathRoute(fullRoute.TCRouteSubpaths[0]); - // find first overlap section with train route + // Find first overlap section with train route int overlapSection = -1; int useSubpath = 0; @@ -7891,7 +7625,7 @@ public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrou useSubpath++; } - // if overlap found : insert in waiting list + // If overlap found : insert in waiting list if (overlapSection >= 0) { if (WaitAnyList == null) @@ -7933,7 +7667,7 @@ public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrou } else { - thisStationStop.HoldSignal = thisStationStop.ExitSignal >= 0; // set holdstate only if exit signal is defined + thisStationStop.HoldSignal = thisStationStop.ExitSignal >= 0; // Set holdstate only if exit signal is defined } break; @@ -7951,12 +7685,12 @@ public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrou case "forcehold": if (thisStationStop != null) { - // use platform signal + // Use platform signal if (thisStationStop.ExitSignal >= 0) { thisStationStop.HoldSignal = true; } - // use first signal in route + // Use first signal in route else { TCSubpathRoute usedRoute = TCRoute.TCRouteSubpaths[thisStationStop.SubrouteIndex]; @@ -7995,7 +7729,7 @@ public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrou case "forcewait": if (thisStationStop != null) { - // if no platform signal, use first signal in route + // If no platform signal, use first signal in route if (thisStationStop.ExitSignal < 0) { TCSubpathRoute usedRoute = TCRoute.TCRouteSubpaths[thisStationStop.SubrouteIndex]; @@ -8061,40 +7795,40 @@ public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrou } break; - // no action for terminal (processed in create station stop) + // No action for terminal (processed in create station stop) case "terminal": break; - // no action for closeupsignal (processed in create station stop) + // No action for closeupsignal (processed in create station stop) case "closeupsignal": break; - // no action for closeupsignal (processed in create station stop) + // No action for closeupsignal (processed in create station stop) case "closeup": break; - // no action for extendplatformtosignal (processed in create station stop) + // No action for extendplatformtosignal (processed in create station stop) case "extendplatformtosignal": break; - // no action for restrictplatformtosignal (processed in create station stop) + // No action for restrictplatformtosignal (processed in create station stop) case "restrictplatformtosignal": break; - // no action for keepclear (processed in create station stop) + // No action for keepclear (processed in create station stop) case "keepclear": break; - // no action for endstop (processed in create station stop) + // No action for endstop (processed in create station stop) case "endstop": break; - // no action for stoptime (processed in create station stop) + // No action for stoptime (processed in create station stop) case "stoptime": break; case "detach": - // detach at station + // Detach at station if (thisStationStop != null) { DetachInfo thisDetach = new DetachInfo(this, thisCommand, false, true, false, thisStationStop.TCSectionIndex, thisStationStop.ArrivalTime); @@ -8110,7 +7844,7 @@ public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrou DetachDetails.Add(thisStationStop.PlatformReference, thisDetachList); } } - // detach at start + // Detach at start else { int startSection = TCRoute.TCRouteSubpaths[0][0].TCSectionIndex; @@ -8130,7 +7864,7 @@ public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrou break; case "attach": - // attach at station + // Attach at station if (plattformReferenceID >= 0) { AttachDetails = new AttachInfo(plattformReferenceID, thisCommand, this); @@ -8138,7 +7872,7 @@ public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrou break; case "pickup": - // pickup at station + // Pickup at station if (plattformReferenceID >= 0) { PickUpInfo thisPickUp = new PickUpInfo(plattformReferenceID, thisCommand, this); @@ -8162,7 +7896,7 @@ public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrou } else { - // for now, insert with train set to -1 - will be updated for proper crossreference later + // For now, insert with train set to -1 - will be updated for proper crossreference later if (TransferTrainDetails.ContainsKey(-1)) { TransferTrainDetails[-1].Add(thisTransfer); @@ -8192,7 +7926,7 @@ public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrou if (thisCommand.CommandQualifiers != null && thisCommand.CommandQualifiers.Count > 0) { - TTTrainCommands.TTTrainComQualifiers thisQualifier = thisCommand.CommandQualifiers[0]; // takes only 1 qualifier + TTTrainCommands.TTTrainComQualifiers thisQualifier = thisCommand.CommandQualifiers[0]; // Takes only 1 qualifier if (thisQualifier.QualifierName.Trim().ToLower() == "depart") { thisTrigger.activationType = TriggerActivationType.StationDepart; @@ -8219,10 +7953,9 @@ public void ProcessTimetableStopCommands(TTTrainCommands thisCommand, int subrou /// /// Finalize the command information - process referenced train details /// - public void FinalizeTimetableCommands() { - // process all wait information + // Process all wait information if (WaitList != null) { TTTrain otherTrain = null; @@ -8250,7 +7983,7 @@ public void FinalizeTimetableCommands() { ProcessWaitRequest(reqWait, otherTrain, true, true, true, ref newWaitItems); } - reqWait.WaitType = WaitInfo.WaitInfoType.Invalid; // set to invalid as item is processed + reqWait.WaitType = WaitInfo.WaitInfoType.Invalid; // Set to invalid as item is processed break; // FOLLOW command @@ -8271,7 +8004,7 @@ public void FinalizeTimetableCommands() { ProcessWaitRequest(reqWait, otherTrain, true, false, false, ref newWaitItems); } - reqWait.WaitType = WaitInfo.WaitInfoType.Invalid; // set to invalid as item is processed + reqWait.WaitType = WaitInfo.WaitInfoType.Invalid; // Set to invalid as item is processed break; // CONNECT command @@ -8293,7 +8026,7 @@ public void FinalizeTimetableCommands() { ProcessConnectRequest(reqWait, otherTrain, ref newWaitItems); } - reqWait.WaitType = WaitInfo.WaitInfoType.Invalid; // set to invalid as item is processed + reqWait.WaitType = WaitInfo.WaitInfoType.Invalid; // Set to invalid as item is processed break; default: @@ -8301,7 +8034,7 @@ public void FinalizeTimetableCommands() } } - // remove processed and invalid items + // Remove processed and invalid items for (int iWaitItem = WaitList.Count - 1; iWaitItem >= 0; iWaitItem--) { if (WaitList[iWaitItem].WaitType == WaitInfo.WaitInfoType.Invalid) @@ -8310,13 +8043,13 @@ public void FinalizeTimetableCommands() } } - // add new created items + // Add new created items foreach (WaitInfo newWait in newWaitItems) { WaitList.Add(newWait); } - // sort list - list is sorted on subpath and route index + // Sort list - list is sorted on subpath and route index WaitList.Sort(); } } @@ -8325,10 +8058,9 @@ public void FinalizeTimetableCommands() /// /// Process wait request for Timetable waits /// - public void ProcessWaitRequest(WaitInfo reqWait, TTTrain otherTrain, bool allowSameDirection, bool allowOppositeDirection, bool singleWait, ref List newWaitItems) { - // find first common section to determine train directions + // Find first common section to determine train directions int otherRouteIndex = -1; int thisSubpath = reqWait.startSubrouteIndex; int thisIndex = TCRoute.TCRouteSubpaths[thisSubpath].GetRouteIndex(reqWait.startSectionIndex, 0); @@ -8338,18 +8070,16 @@ public void ProcessWaitRequest(WaitInfo reqWait, TTTrain otherTrain, bool allowS bool allSubpathsProcessed = false; bool sameDirection = false; - bool validWait = true; // presume valid wait - - // set actual start + bool validWait = true; // Presume valid wait + // Set actual start TCRouteElement thisTrainElement = null; TCRouteElement otherTrainElement = null; int thisTrainStartSubpathIndex = reqWait.startSubrouteIndex; int thisTrainStartRouteIndex = TCRoute.TCRouteSubpaths[thisTrainStartSubpathIndex].GetRouteIndex(reqWait.startSectionIndex, 0); - // loop while no section found and further subpaths available - + // Loop while no section found and further subpaths available while (!allSubpathsProcessed) { otherRouteIndex = -1; @@ -8366,30 +8096,29 @@ public void ProcessWaitRequest(WaitInfo reqWait, TTTrain otherTrain, bool allowS else if (otherRouteIndex < 0 && thisIndex < TCRoute.TCRouteSubpaths[thisSubpath].Count - 1) { thisIndex++; - otherSubpath = 0; // reset other train subpath + otherSubpath = 0; // Reset other train subpath } else if (otherRouteIndex < 0 && thisSubpath < TCRoute.TCRouteSubpaths.Count - 1) { thisSubpath++; thisIndex = 0; - otherSubpath = 0; // reset other train subpath + otherSubpath = 0; // Reset other train subpath } else if (otherRouteIndex < 0) { validWait = false; - break; // no common section found + break; // No common section found } } - // if valid wait but wait is in next subpath, use start section of next subpath - + // If valid wait but wait is in next subpath, use start section of next subpath if (validWait && thisTrainStartSubpathIndex < thisSubpath) { thisTrainStartSubpathIndex = thisSubpath; thisTrainStartRouteIndex = 0; } - // check directions + // Check directions if (validWait) { thisTrainElement = TCRoute.TCRouteSubpaths[thisSubpath][thisIndex]; @@ -8400,59 +8129,52 @@ public void ProcessWaitRequest(WaitInfo reqWait, TTTrain otherTrain, bool allowS validWait = sameDirection ? allowSameDirection : allowOppositeDirection; } - // if original start section index is also first common index, search for first not common section + // If original start section index is also first common index, search for first not common section if (validWait && startSectionIndex == otherTrainElement.TCSectionIndex) { int notCommonSectionRouteIndex = -1; - if (sameDirection) - { - notCommonSectionRouteIndex = - FindCommonSectionEnd(TCRoute.TCRouteSubpaths[thisSubpath], thisIndex, - otherTrain.TCRoute.TCRouteSubpaths[otherSubpath], otherRouteIndex); - } - else - { - notCommonSectionRouteIndex = - FindCommonSectionEndReverse(TCRoute.TCRouteSubpaths[thisSubpath], thisIndex, + notCommonSectionRouteIndex = sameDirection + ? FindCommonSectionEnd(TCRoute.TCRouteSubpaths[thisSubpath], thisIndex, + otherTrain.TCRoute.TCRouteSubpaths[otherSubpath], otherRouteIndex) + : FindCommonSectionEndReverse(TCRoute.TCRouteSubpaths[thisSubpath], thisIndex, otherTrain.TCRoute.TCRouteSubpaths[otherSubpath], otherRouteIndex); - } - // check on found not-common section - start wait here if atstart is set, otherwise start wait at first not-common section + // Check on found not-common section - start wait here if atstart is set, otherwise start wait at first not-common section int notCommonSectionIndex = otherTrain.TCRoute.TCRouteSubpaths[otherSubpath][notCommonSectionRouteIndex].TCSectionIndex; int lastIndex = TCRoute.TCRouteSubpaths[thisTrainStartSubpathIndex].GetRouteIndex(notCommonSectionIndex, 0); - bool atStart = reqWait.atStart.HasValue ? reqWait.atStart.Value : false; + bool atStart = reqWait.atStart.HasValue && reqWait.atStart.Value; - if (lastIndex < TCRoute.TCRouteSubpaths[thisTrainStartSubpathIndex].Count - 1) // not last entry + if (lastIndex < TCRoute.TCRouteSubpaths[thisTrainStartSubpathIndex].Count - 1) // Not last entry { - // if opposite direction, use next section as start for common section search - // if same direction and atStart not set also use next section as start for common section search - // if same direction and atStart is set use first section as start for common section search as train is to wait in this section + // If opposite direction, use next section as start for common section search + // If same direction and atStart not set also use next section as start for common section search + // If same direction and atStart is set use first section as start for common section search as train is to wait in this section lastIndex++; - if (!sameDirection || !atStart) + if (!sameDirection || !atStart) { thisTrainStartRouteIndex = lastIndex; } - // valid wait, so set all subpaths processed + // Valid wait, so set all subpaths processed allSubpathsProcessed = true; } else { - // full common route but further subpath available - try next subpath + // Full common route but further subpath available - try next subpath if (otherSubpath < otherTrain.TCRoute.TCRouteSubpaths.Count - 1) { otherSubpath++; } else { - validWait = false; // full common route - no waiting point possible + validWait = false; // Full common route - no waiting point possible allSubpathsProcessed = true; } } } else - // no valid wait or common section found + // No valid wait or common section found { allSubpathsProcessed = true; } @@ -8460,26 +8182,24 @@ public void ProcessWaitRequest(WaitInfo reqWait, TTTrain otherTrain, bool allowS if (!validWait) return; - // if in same direction, start at beginning and move downward - // if in opposite direction, start at end (of found subpath!) and move upward - + // If in same direction, start at beginning and move downward + // If in opposite direction, start at end (of found subpath!) and move upward int startSubpath = sameDirection ? 0 : otherSubpath; int endSubpath = sameDirection ? otherSubpath : 0; int startIndex = sameDirection ? 0 : otherTrain.TCRoute.TCRouteSubpaths[startSubpath].Count - 1; int endIndex = sameDirection ? otherTrain.TCRoute.TCRouteSubpaths[startSubpath].Count - 1 : 0; int increment = sameDirection ? 1 : -1; - // if first section is common, first search for first non common section - + // If first section is common, first search for first non common section bool allCommonFound = false; - // loop through all possible waiting points + // Loop through all possible waiting points while (!allCommonFound) { int[,] sectionfound = FindCommonSectionStart(thisTrainStartSubpathIndex, thisTrainStartRouteIndex, otherTrain.TCRoute, startSubpath, startIndex, endSubpath, endIndex, increment); - // no common section found + // No common section found if (sectionfound[0, 0] < 0) { allCommonFound = true; @@ -8515,25 +8235,23 @@ public void ProcessWaitRequest(WaitInfo reqWait, TTTrain otherTrain, bool allowS allCommonFound = true; break; } - else if (sameDirection) - { - endSection = FindCommonSectionEnd(TCRoute.TCRouteSubpaths[newItem.activeSubrouteIndex], newItem.activeRouteIndex, - otherTrain.TCRoute.TCRouteSubpaths[newItem.waitTrainSubpathIndex], newItem.waitTrainRouteIndex); - } else { - endSection = FindCommonSectionEndReverse(TCRoute.TCRouteSubpaths[newItem.activeSubrouteIndex], newItem.activeRouteIndex, - otherTrain.TCRoute.TCRouteSubpaths[newItem.waitTrainSubpathIndex], newItem.waitTrainRouteIndex); + endSection = sameDirection + ? FindCommonSectionEnd(TCRoute.TCRouteSubpaths[newItem.activeSubrouteIndex], newItem.activeRouteIndex, + otherTrain.TCRoute.TCRouteSubpaths[newItem.waitTrainSubpathIndex], newItem.waitTrainRouteIndex) + : FindCommonSectionEndReverse(TCRoute.TCRouteSubpaths[newItem.activeSubrouteIndex], newItem.activeRouteIndex, + otherTrain.TCRoute.TCRouteSubpaths[newItem.waitTrainSubpathIndex], newItem.waitTrainRouteIndex); } - // last common section + // Last common section int lastSectionIndex = otherTrain.TCRoute.TCRouteSubpaths[newItem.waitTrainSubpathIndex][endSection].TCSectionIndex; thisTrainStartRouteIndex = TCRoute.TCRouteSubpaths[thisTrainStartSubpathIndex].GetRouteIndex(lastSectionIndex, thisTrainStartRouteIndex); if (thisTrainStartRouteIndex < TCRoute.TCRouteSubpaths[thisTrainStartSubpathIndex].Count - 1) { - thisTrainStartRouteIndex++; // first not-common section + thisTrainStartRouteIndex++; // First not-common section } - // end of subpath - shift to next subpath if available + // End of subpath - shift to next subpath if available else { if (thisTrainStartSubpathIndex < endSubpath) @@ -8572,11 +8290,10 @@ public void ProcessWaitRequest(WaitInfo reqWait, TTTrain otherTrain, bool allowS /// /// /// - public int[,] FindCommonSectionStart(int thisTrainStartSubpathIndex, int thisTrainStartRouteIndex, TCRoutePath otherTrainRoute, int startSubpath, int startIndex, int endSubpath, int endIndex, int increment) { - // preset all loop data + // Preset all loop data int thisSubpathIndex = thisTrainStartSubpathIndex; int thisRouteIndex = thisTrainStartRouteIndex; TCSubpathRoute thisRoute = TCRoute.TCRouteSubpaths[thisSubpathIndex]; @@ -8592,32 +8309,26 @@ public void ProcessWaitRequest(WaitInfo reqWait, TTTrain otherTrain, bool allowS bool otherEndOfRoute = false; bool commonSectionFound = false; - // preset result + // Preset result int[,] sectionFound = new int[2, 2] { { -1, -1 }, { -1, -1 } }; - // derive sections + // Derive sections int thisSectionIndex = thisRoute[thisRouteIndex].TCSectionIndex; int otherSectionIndex = otherRoute[otherRouteIndex].TCSectionIndex; - // convert other subpath to dictionary for quick reference - TCSubpathRoute partRoute; - if (otherRouteIndex < otherRouteEndIndex) - { - partRoute = new TCSubpathRoute(otherRoute, otherRouteIndex, otherRouteEndIndex); - } - else - { - partRoute = new TCSubpathRoute(otherRoute, otherRouteEndIndex, otherRouteIndex); - } + // Convert other subpath to dictionary for quick reference + var partRoute = otherRouteIndex < otherRouteEndIndex + ? new TCSubpathRoute(otherRoute, otherRouteIndex, otherRouteEndIndex) + : new TCSubpathRoute(otherRoute, otherRouteEndIndex, otherRouteIndex); Dictionary dictRoute = partRoute.ConvertRoute(); - // loop until common section is found or route is ended + // Loop until common section is found or route is ended while (!commonSectionFound && !otherEndOfRoute) { while (!thisEndOfRoute) { - // get section indices + // Get section indices thisSectionIndex = TCRoute.TCRouteSubpaths[thisSubpathIndex][thisRouteIndex].TCSectionIndex; if (dictRoute.ContainsKey(thisSectionIndex)) @@ -8633,7 +8344,7 @@ public void ProcessWaitRequest(WaitInfo reqWait, TTTrain otherTrain, bool allowS break; } - // move to next section for this train + // Move to next section for this train thisRouteIndex++; if (thisRouteIndex > thisRouteEndIndex) { @@ -8641,8 +8352,8 @@ public void ProcessWaitRequest(WaitInfo reqWait, TTTrain otherTrain, bool allowS } } - // move to next subpath for other train - // move to next subpath if end of subpath reached + // Move to next subpath for other train + // Move to next subpath if end of subpath reached if (increment > 0) { otherSubpathIndex++; @@ -8669,12 +8380,12 @@ public void ProcessWaitRequest(WaitInfo reqWait, TTTrain otherTrain, bool allowS } } - // reset to start for this train + // Reset to start for this train thisRouteIndex = thisTrainStartRouteIndex; thisEndOfRoute = false; } - return (sectionFound); + return sectionFound; } /// @@ -8710,7 +8421,7 @@ public int FindCommonSectionEnd(TCSubpathRoute thisRoute, int thisRouteIndex, TC } } - return (lastIndex); + return lastIndex; } /// @@ -8745,7 +8456,7 @@ public int FindCommonSectionEndReverse(TCSubpathRoute thisRoute, int thisRouteIn } } - return (lastIndex); + return lastIndex; } //================================================================================================// @@ -8760,7 +8471,7 @@ public int FindCommonSectionEndReverse(TCSubpathRoute thisRoute, int thisRouteIn /// public void ProcessConnectRequest(WaitInfo reqWait, TTTrain otherTrain, ref List newWaitItems) { - // find station reference + // Find station reference StationStop stopStation = StationStops[reqWait.stationIndex]; int otherStationStopIndex = -1; @@ -8773,7 +8484,7 @@ public void ProcessConnectRequest(WaitInfo reqWait, TTTrain otherTrain, ref List } } - if (otherStationStopIndex >= 0) // if other stop is found + if (otherStationStopIndex >= 0) // If other stop is found { WaitInfo newWait = reqWait.CreateCopy(); newWait.waitTrainNumber = otherTrain.OrgAINumber; @@ -8806,23 +8517,22 @@ public void ProcessConnectRequest(WaitInfo reqWait, TTTrain otherTrain, ref List /// public override bool CheckWaitCondition(int trackSectionIndex) { - // no waits defined + // No waits defined if (WaitList == null || WaitList.Count <= 0) { - return (false); + return false; } bool waitState = false; - // check if first wait is this section - + // Check if first wait is this section int processedWait = 0; WaitInfo firstWait = WaitList[processedWait]; - // if first wait is connect : no normal waits or follows to process + // If first wait is connect : no normal waits or follows to process if (firstWait.WaitType == WaitInfo.WaitInfoType.Connect) { - return (false); + return false; } while (firstWait.activeSubrouteIndex == TCRoute.activeSubpath && firstWait.activeSectionIndex == trackSectionIndex) @@ -8838,15 +8548,15 @@ public override bool CheckWaitCondition(int trackSectionIndex) break; } - // if not awaited, check for further waits - // wait list may have changed if first item is no longer valid + // If not awaited, check for further waits + // Wait list may have changed if first item is no longer valid if (!waitState) { if (processedWait > WaitList.Count - 1) { - break; // no more waits to check + break; // No more waits to check } - else if (firstWait == WaitList[processedWait]) // wait was maintained + else if (firstWait == WaitList[processedWait]) // Wait was maintained { processedWait++; } @@ -8857,16 +8567,16 @@ public override bool CheckWaitCondition(int trackSectionIndex) } else { - break; // no more waits to check + break; // No more waits to check } } else { - break; // no more waits to check + break; // No more waits to check } } - return (waitState); + return waitState; } //================================================================================================// @@ -8914,10 +8624,10 @@ public override bool VerifyDeadlock(List deadlockReferences) } } - // check if any possible attach trains ahead in deadlock references + // Check if any possible attach trains ahead in deadlock references if (possibleAttachTrains.Count > 0) { - // test if required train is first train ahead + // Test if required train is first train ahead int presentSectionListIndex = PresentPosition[0].RouteListIndex; for (int iSection = presentSectionListIndex + 1; iSection < ValidRoute[0].Count && !attachTrainAhead && !otherTrainAhead; iSection++) @@ -8938,7 +8648,7 @@ public override bool VerifyDeadlock(List deadlockReferences) } } - return (!attachTrainAhead); + return !attachTrainAhead; } //================================================================================================// @@ -8946,10 +8656,9 @@ public override bool VerifyDeadlock(List deadlockReferences) /// TrainGetSectionStateClearNode /// Override method from train /// - public override bool TrainGetSectionStateClearNode(int elementDirection, Train.TCSubpathRoute routePart, TrackCircuitSection thisSection) { - return (thisSection.getSectionState(routedForward, elementDirection, SignalObject.InternalBlockstate.Reserved, routePart, -1) <= SignalObject.InternalBlockstate.OccupiedSameDirection); + return thisSection.getSectionState(routedForward, elementDirection, SignalObject.InternalBlockstate.Reserved, routePart, -1) <= SignalObject.InternalBlockstate.OccupiedSameDirection; } //================================================================================================// @@ -8958,19 +8667,18 @@ public override bool TrainGetSectionStateClearNode(int elementDirection, Train.T /// /// /// - public bool CheckForSingleTrainWait(WaitInfo reqWait) { bool waitState = false; - // get other train + // Get other train TTTrain otherTrain = GetOtherTTTrainByNumber(reqWait.waitTrainNumber); - // get clock time - for AI use AI clock as simulator clock is not valid during pre-process + // Get clock time - for AI use AI clock as simulator clock is not valid during pre-process double presentTime = Simulator.ClockTime; if (TrainType == TRAINTYPE.AI) { - AITrain aitrain = this as AITrain; + AITrain aitrain = this; presentTime = aitrain.AI.clockTime; } @@ -8978,50 +8686,50 @@ public bool CheckForSingleTrainWait(WaitInfo reqWait) { if (reqWait.waittrigger.Value < Convert.ToInt32(presentTime)) { - return (waitState); // exit as wait must be retained + return waitState; // Exit as wait must be retained } } - // check if end trigger time passed + // Check if end trigger time passed if (reqWait.waitendtrigger.HasValue) { if (reqWait.waitendtrigger.Value < Convert.ToInt32(presentTime)) { - otherTrain = null; // reset other train to remove wait - reqWait.notStarted = false; // ensure wait is not triggered accidentally + otherTrain = null; // Reset other train to remove wait + reqWait.notStarted = false; // Ensure wait is not triggered accidentally } } - // check on own delay condition - bool owndelayexceeded = true; // default is no own delay + // Check on own delay condition + bool owndelayexceeded = true; // Default is no own delay if (reqWait.ownDelayS.HasValue && Delay.HasValue) { float ownDelayS = (float)Delay.Value.TotalSeconds; owndelayexceeded = ownDelayS > reqWait.ownDelayS.Value; } - // other train does exist or wait is cancelled + // Other train does exist or wait is cancelled if (otherTrain != null) { - // other train in correct subpath - // check if trigger time passed + // Other train in correct subpath + // Check if trigger time passed if (otherTrain.TCRoute.activeSubpath == reqWait.waitTrainSubpathIndex) { - // check if section on train route and if so, if end of train is beyond this section - // check only for forward path - train must have passed section in 'normal' mode + // Check if section on train route and if so, if end of train is beyond this section + // Check only for forward path - train must have passed section in 'normal' mode if (otherTrain.ValidRoute[0] != null) { int waitTrainRouteIndex = otherTrain.ValidRoute[0].GetRouteIndex(reqWait.activeSectionIndex, 0); if (waitTrainRouteIndex >= 0) { - if (otherTrain.PresentPosition[1].RouteListIndex < waitTrainRouteIndex) // train is not yet passed this section + if (otherTrain.PresentPosition[1].RouteListIndex < waitTrainRouteIndex) // Train is not yet passed this section { float? totalDelayS = null; float? ownDelayS = null; - // determine own delay + // Determine own delay if (reqWait.ownDelayS.HasValue) { if (owndelayexceeded) @@ -9041,16 +8749,16 @@ public bool CheckForSingleTrainWait(WaitInfo reqWait) } } - // determine other train delay + // Determine other train delay else { if (reqWait.maxDelayS.HasValue && otherTrain.Delay.HasValue) { totalDelayS = reqWait.maxDelayS.Value; - totalDelayS += Delay.HasValue ? (float)Delay.Value.TotalSeconds : 0f; // add own delay if set + totalDelayS += Delay.HasValue ? (float)Delay.Value.TotalSeconds : 0f; // Add own delay if set } - if (!totalDelayS.HasValue || (float)otherTrain.Delay.Value.TotalSeconds < totalDelayS) // train is not too much delayed + if (!totalDelayS.HasValue || (float)otherTrain.Delay.Value.TotalSeconds < totalDelayS) // Train is not too much delayed { waitState = true; reqWait.WaitActive = true; @@ -9061,7 +8769,7 @@ public bool CheckForSingleTrainWait(WaitInfo reqWait) } } - // if other train not in this subpath but notstarted is set, wait is valid (except when conditioned by own delay) + // If other train not in this subpath but notstarted is set, wait is valid (except when conditioned by own delay) else if (otherTrain.TCRoute.activeSubpath < reqWait.waitTrainSubpathIndex && reqWait.notStarted.HasValue && owndelayexceeded) { waitState = true; @@ -9069,7 +8777,7 @@ public bool CheckForSingleTrainWait(WaitInfo reqWait) } } - // check if waiting is also required if train not yet started + // Check if waiting is also required if train not yet started else if (reqWait.notStarted.HasValue && owndelayexceeded) { if (CheckTTTrainNotStartedByNumber(reqWait.waitTrainNumber)) @@ -9079,12 +8787,12 @@ public bool CheckForSingleTrainWait(WaitInfo reqWait) } } - if (!waitState) // wait is no longer valid + if (!waitState) // Wait is no longer valid { - WaitList.RemoveAt(0); // remove this wait + WaitList.RemoveAt(0); // Remove this wait } - return (waitState); + return waitState; } //================================================================================================// @@ -9103,7 +8811,7 @@ public bool CheckForRouteWait(WaitInfo reqWait) if (!pathClear) { reqWait.WaitActive = true; - return (pathClear); // no need to check opposite direction if allready blocked + return pathClear; // No need to check opposite direction if allready blocked } } @@ -9113,7 +8821,7 @@ public bool CheckForRouteWait(WaitInfo reqWait) } reqWait.WaitActive = !pathClear; - return (pathClear); + return pathClear; } //================================================================================================// @@ -9125,10 +8833,9 @@ public bool CheckForRouteWait(WaitInfo reqWait) /// private bool CheckRouteWait(TCSubpathRoute thisRoute, bool sameDirection) { - SignalObject.InternalBlockstate blockstate = SignalObject.InternalBlockstate.Reserved; // preset to lowest possible state // - - // loop through all sections in route list + SignalObject.InternalBlockstate blockstate = SignalObject.InternalBlockstate.Reserved; // Preset to lowest possible state + // Loop through all sections in route list TCRouteElement lastElement = null; foreach (TCRouteElement thisElement in thisRoute) @@ -9139,17 +8846,16 @@ private bool CheckRouteWait(TCSubpathRoute thisRoute, bool sameDirection) blockstate = thisSection.getSectionState(routedForward, direction, blockstate, thisRoute, -1); if (blockstate > SignalObject.InternalBlockstate.Reservable) - break; // exit on first none-available section + break; // Exit on first none-available section } - return (blockstate < SignalObject.InternalBlockstate.OccupiedSameDirection); + return blockstate < SignalObject.InternalBlockstate.OccupiedSameDirection; } //================================================================================================// /// /// Check for any active waits in indicated path /// - public override bool HasActiveWait(int startSectionIndex, int endSectionIndex) { bool returnValue = false; @@ -9159,10 +8865,10 @@ public override bool HasActiveWait(int startSectionIndex, int endSectionIndex) if (startRouteIndex < 0 || endRouteIndex < 0) { - return (returnValue); + return returnValue; } - // check for any wait in indicated route section + // Check for any wait in indicated route section for (int iRouteIndex = startRouteIndex; iRouteIndex <= endRouteIndex; iRouteIndex++) { int sectionIndex = ValidRoute[0][iRouteIndex].TCSectionIndex; @@ -9189,27 +8895,26 @@ public override bool HasActiveWait(int startSectionIndex, int endSectionIndex) } } - return (returnValue); + return returnValue; } //================================================================================================// /// /// Process end of path - /// returns : + /// Returns : /// [0] : true : end of route, false : not end of route /// [1] : true : train still exists, false : train is removed and no longer exists /// /// Override from AITrain class /// <\summary> - public override bool[] ProcessEndOfPath(int presentTime, bool checkLoop = true) { bool[] returnValue = new bool[2] { false, true }; - // if train not on route in can't be at end + // If train not on route in can't be at end if (PresentPosition[0].RouteListIndex < 0) { - return (returnValue); + return returnValue; } int directionNow = ValidRoute[0][PresentPosition[0].RouteListIndex].Direction; @@ -9219,11 +8924,11 @@ public override bool[] ProcessEndOfPath(int presentTime, bool checkLoop = true) if (!nextPart[0]) { - return (returnValue); // not at end and not to attach to anything + return returnValue; // Not at end and not to attach to anything } - returnValue[0] = true; // end of path reached - if (nextPart[1]) // next route available + returnValue[0] = true; // End of path reached + if (nextPart[1]) // Next route available { #if DEBUG_REPORTS File.AppendAllText(@"C:\temp\printproc.txt", "Train " + @@ -9260,7 +8965,7 @@ public override bool[] ProcessEndOfPath(int presentTime, bool checkLoop = true) Number.ToString() + " reversed\n"); } - // check if next station was on previous subpath - if so, move to this subpath + // Check if next station was on previous subpath - if so, move to this subpath if (StationStops.Count > 0) { @@ -9270,11 +8975,11 @@ public override bool[] ProcessEndOfPath(int presentTime, bool checkLoop = true) { StationStops.RemoveAt(0); } - // if station was in previous path, checked if passed + // If station was in previous path, checked if passed else if (thisStation.SubrouteIndex < TCRoute.activeSubpath) { int routeIndex = ValidRoute[0].GetRouteIndex(thisStation.TCSectionIndex, 0); - if (routeIndex < 0 || PresentPosition[0].RouteListIndex > routeIndex) // station no longer on route or train beyond station + if (routeIndex < 0 || PresentPosition[0].RouteListIndex > routeIndex) // Station no longer on route or train beyond station { if (thisStation.ExitSignal >= 0 && thisStation.HoldSignal && HoldingSignals.Contains(thisStation.ExitSignal)) { @@ -9282,7 +8987,7 @@ public override bool[] ProcessEndOfPath(int presentTime, bool checkLoop = true) } StationStops.RemoveAt(0); } - // if in station set correct subroute and route indices + // If in station set correct subroute and route indices else if (PresentPosition[0].RouteListIndex == routeIndex) { thisStation.SubrouteIndex = TCRoute.activeSubpath; @@ -9294,7 +8999,7 @@ public override bool[] ProcessEndOfPath(int presentTime, bool checkLoop = true) } } - // reset to node control, also reset required actions + // Reset to node control, also reset required actions SwitchToNodeControl(-1); ResetActions(true); @@ -9304,7 +9009,7 @@ public override bool[] ProcessEndOfPath(int presentTime, bool checkLoop = true) ProcessEndOfPathReached(ref returnValue, presentTime); } - return (returnValue); + return returnValue; } //================================================================================================// @@ -9316,23 +9021,22 @@ public override bool[] ProcessEndOfPath(int presentTime, bool checkLoop = true) /// public override void ProcessEndOfPathReached(ref bool[] returnValue, int presentTime) { - // check if any other train needs to be activated + // Check if any other train needs to be activated ActivateTriggeredTrain(TriggerActivationType.Dispose, -1); - // check if any outstanding moving table actions + // Check if any outstanding moving table actions List reqActions = requiredActions.GetActions(0.0f, typeof(ClearMovingTableAction)); foreach (DistanceTravelledItem thisAction in reqActions) { ClearMovingTable(thisAction); } - // check if train is to form new train - // note : if formed train == 0, formed train is player train which requires different actions - + // Check if train is to form new train + // Note: if formed train == 0, formed train is player train which requires different actions if (Forms >= 0 && DetachActive[1] == -1) { - // check if anything needs be detached - bool allowForm = true; // preset form may be activated + // Check if anything needs be detached + bool allowForm = true; // Preset form may be activated if (DetachDetails.ContainsKey(-1)) { @@ -9352,7 +9056,7 @@ public override void ProcessEndOfPathReached(ref bool[] returnValue, int present if (detachList.Count <= 0 & allowForm) DetachDetails.Remove(-1); } - // if detach was performed, form may proceed + // If detach was performed, form may proceed if (allowForm) { FormTrainFromAI(presentTime); @@ -9360,10 +9064,10 @@ public override void ProcessEndOfPathReached(ref bool[] returnValue, int present } } - // check if train is to remain as static + // Check if train is to remain as static else if (FormsStatic) { - // check if anything needs be detached + // Check if anything needs be detached if (DetachDetails.ContainsKey(-1)) { List detachList = DetachDetails[-1]; @@ -9384,10 +9088,10 @@ public override void ProcessEndOfPathReached(ref bool[] returnValue, int present MovementState = AI_MOVEMENT_STATE.AI_STATIC; ControlMode = TRAIN_CONTROL.INACTIVE; - StartTime = null; // set starttime to invalid - ActivateTime = null; // set activate to invalid + StartTime = null; // Set starttime to invalid + ActivateTime = null; // Set activate to invalid - // remove existing train from track + // Remove existing train from track TrackCircuitSection[] occupiedSections = new TrackCircuitSection[OccupiedTrack.Count]; OccupiedTrack.CopyTo(occupiedSections); RemoveFromTrack(); @@ -9398,7 +9102,7 @@ public override void ProcessEndOfPathReached(ref bool[] returnValue, int present occSection.SetOccupied(routedForward); } - // train is in pool : update pool info + // Train is in pool : update pool info if (!String.IsNullOrEmpty(ExitPool)) { TimetablePool thisPool = Simulator.PoolHolder.Pools[ExitPool]; @@ -9451,12 +9155,12 @@ public void FormTrainFromAI(int presentTime) if (Forms == 0) { - formedTrain = Simulator.Trains[0] as TTTrain; // get player train + formedTrain = Simulator.Trains[0] as TTTrain; // Get player train formedTrain.TrainType = TRAINTYPE.INTENDED_PLAYER; } else { - // get train which is to be formed + // Get train which is to be formed formedTrain = AI.StartList.GetNotStartedTTTrainByNumber(Forms, true); if (formedTrain == null) @@ -9466,17 +9170,17 @@ public void FormTrainFromAI(int presentTime) } } - // if found - start train + // If found - start train if (formedTrain != null) { - // remove existing train + // Remove existing train TrackCircuitSection[] occupiedSections = new TrackCircuitSection[OccupiedTrack.Count]; OccupiedTrack.CopyTo(occupiedSections); Forms = -1; RemoveTrain(); - // set details for new train from existing train + // Set details for new train from existing train bool validFormed = formedTrain.StartFromAITrain(this, presentTime, occupiedSections); #if DEBUG_TRACEINFO @@ -9485,7 +9189,7 @@ public void FormTrainFromAI(int presentTime) if (validFormed) { - // start new train + // Start new train if (!autogenStart) { AI.Simulator.StartReference.Remove(formedTrain.Number); @@ -9495,8 +9199,8 @@ public void FormTrainFromAI(int presentTime) { AI.TrainsToAdd.Add(formedTrain); - // set player locomotive - // first test first and last cars - if either is drivable, use it as player locomotive + // Set player locomotive + // First test first and last cars - if either is drivable, use it as player locomotive int lastIndex = formedTrain.Cars.Count - 1; if (formedTrain.Cars[0].IsDriveable) @@ -9511,7 +9215,7 @@ public void FormTrainFromAI(int presentTime) { foreach (TrainCar car in formedTrain.Cars) { - if (car.IsDriveable) // first loco is the one the player drives + if (car.IsDriveable) // First loco is the one the player drives { AI.Simulator.PlayerLocomotive = formedTrain.LeadLocomotive = car; break; @@ -9519,7 +9223,7 @@ public void FormTrainFromAI(int presentTime) } } - // only initialize brakes if previous train was not player train + // Only initialize brakes if previous train was not player train if (TrainType == TRAINTYPE.PLAYER) { formedTrain.ConnectBrakeHoses(); @@ -9568,7 +9272,7 @@ public void FormTrainFromAI(int presentTime) } else if (!autogenStart) { - // reinstate as to be started (note : train is not yet removed from reference) + // Reinstate as to be started (note : train is not yet removed from reference) AI.StartList.InsertTrain(formedTrain); } } @@ -9579,26 +9283,25 @@ public void FormTrainFromAI(int presentTime) /// Check End of Route Position /// Override class from Train, but needs additional checks before actually testing end of route /// - public override bool CheckEndOfRoutePosition() { - // check if at end of route + // Check if at end of route bool endOfRoute = CheckEndOfRoutePositionTT(); - // if so, perform further checks + // If so, perform further checks if (endOfRoute) { - // if train needs to pick up before reaching end of path, continue train + // If train needs to pick up before reaching end of path, continue train if (PickUpStaticOnForms && TCRoute.activeSubpath == (TCRoute.TCRouteSubpaths.Count - 1)) { - return (false); + return false; } - // if present or any further sections are platform section and pick up is required in platform, continue train - // if present or any further sections occupied by train which must be picked up, continue train + // If present or any further sections are platform section and pick up is required in platform, continue train + // If present or any further sections occupied by train which must be picked up, continue train for (int iRouteIndex = PresentPosition[0].RouteListIndex; iRouteIndex < ValidRoute[0].Count; iRouteIndex++) { - // check platform + // Check platform TrackCircuitSection thisSection = signalRef.TrackCircuitList[ValidRoute[0][iRouteIndex].TCSectionIndex]; foreach (int thisPlatform in thisSection.PlatformIndex) { @@ -9606,43 +9309,41 @@ public override bool CheckEndOfRoutePosition() { if (PickUpStatic.Contains(platformReference)) { - return (false); + return false; } } } - - // check occupying trains + // Check occupying trains List otherTrains = thisSection.CircuitState.TrainsOccupying(); foreach (TrainRouted otherTrain in otherTrains) { TTTrain otherTTTrain = otherTrain.Train as TTTrain; - // check for pickup + // Check for pickup if (CheckPickUp(otherTTTrain)) { - return (false); + return false; } else if (TransferTrainDetails.ContainsKey(otherTTTrain.OrgAINumber)) { - return (false); + return false; } else if (AttachDetails != null && AttachDetails.Valid && AttachDetails.AttachTrain == otherTTTrain.OrgAINumber) { - return (false); + return false; } } } } - return (endOfRoute); + return endOfRoute; } //================================================================================================// /// /// Check End of Route Position /// - public bool CheckEndOfRoutePositionTT() { if (CheckTrain) @@ -9652,14 +9353,13 @@ public bool CheckEndOfRoutePositionTT() bool endOfRoute = false; - // only allowed when stopped + // Only allowed when stopped if (Math.Abs(SpeedMpS) > 0.05f) { - return (endOfRoute); + return endOfRoute; } - // if access to pool is required and section is in present route, train can never be at end of route - + // If access to pool is required and section is in present route, train can never be at end of route if (PoolAccessSection >= 0) { int poolAccessRouteIndex = ValidRoute[0].GetRouteIndex(PoolAccessSection, 0); @@ -9669,23 +9369,23 @@ public bool CheckEndOfRoutePositionTT() { File.AppendAllText(@"C:\temp\checktrain.txt", "Pool Access required ; poolAccessRouteIndex : " + poolAccessRouteIndex + "\n"); } - return (endOfRoute); + return endOfRoute; } } - // if not stopped in station and next stop in this subpath, it cannot be end of route + // If not stopped in station and next stop in this subpath, it cannot be end of route if (!AtStation && StationStops.Count > 0 && StationStops[0].SubrouteIndex == TCRoute.activeSubpath) { - return (endOfRoute); + return endOfRoute; } - // if stopped at station and next stop in this subpath, it cannot be end of route + // If stopped at station and next stop in this subpath, it cannot be end of route if (AtStation && StationStops.Count > 1 && StationStops[1].SubrouteIndex == TCRoute.activeSubpath) { - return (endOfRoute); + return endOfRoute; } - // if stopped in last section of route and this section is exit to moving table switch to moving table mode + // If stopped in last section of route and this section is exit to moving table switch to moving table mode if (ValidRoute[0][PresentPosition[0].RouteListIndex].MovingTableApproachPath > -1) { if (AI.Simulator.PoolHolder.Pools.ContainsKey(ExitPool)) @@ -9704,12 +9404,12 @@ public bool CheckEndOfRoutePositionTT() File.AppendAllText(@"C:\temp\checktrain.txt", "TURNTABLE : Pool : " + thisTurntablePool.PoolName + " : Table state set to " + ActiveTurntable.MovingTableState.ToString() + "\n"); File.AppendAllText(@"C:\temp\checktrain.txt", "Moving table access ; Movement State : " + MovementState + "\n"); } - return (endOfRoute); + return endOfRoute; } } } - // obtain reversal section index + // Obtain reversal section index int reversalSectionIndex = -1; if (TCRoute != null && (ControlMode == TRAIN_CONTROL.AUTO_NODE || ControlMode == TRAIN_CONTROL.AUTO_SIGNAL)) { @@ -9720,21 +9420,21 @@ public bool CheckEndOfRoutePositionTT() } } - // if last entry in route is END_OF_TRACK, check against previous entry as this can never be the trains position nor a signal reference section + // If last entry in route is END_OF_TRACK, check against previous entry as this can never be the trains position nor a signal reference section int lastValidRouteIndex = ValidRoute[0].Count - 1; if (signalRef.TrackCircuitList[ValidRoute[0][lastValidRouteIndex].TCSectionIndex].CircuitType == TrackCircuitSection.TrackCircuitType.EndOfTrack) lastValidRouteIndex--; - // train authority is end of path + // Train authority is end of path if (ControlMode == TRAIN_CONTROL.AUTO_NODE && (EndAuthorityType[0] == END_AUTHORITY.END_OF_TRACK || EndAuthorityType[0] == END_AUTHORITY.END_OF_PATH || EndAuthorityType[0] == END_AUTHORITY.END_OF_AUTHORITY)) { - // front is in last route section + // Front is in last route section if (PresentPosition[0].RouteListIndex == lastValidRouteIndex) { endOfRoute = true; } - // front is within 150m. of end of route and no junctions inbetween (only very short sections ahead of train) + // Front is within 150m. of end of route and no junctions inbetween (only very short sections ahead of train) else { TrackCircuitSection thisSection = signalRef.TrackCircuitList[PresentPosition[0].TCSectionIndex]; @@ -9755,25 +9455,24 @@ public bool CheckEndOfRoutePositionTT() } } - - // other checks unrelated to state + // Other checks unrelated to state if (!endOfRoute) { - // if train is in station and endstop is set + // If train is in station and endstop is set if (AtStation) { endOfRoute = StationStops[0].EndStop; } } - // if end of train on last section in route - end of route reached + // If end of train on last section in route - end of route reached if (!endOfRoute) { if (PresentPosition[1].RouteListIndex == lastValidRouteIndex) { endOfRoute = true; } - // if length of last section is less than train length, check if front position is on last section + // If length of last section is less than train length, check if front position is on last section else { TrackCircuitSection lastSection = signalRef.TrackCircuitList[ValidRoute[0][lastValidRouteIndex].TCSectionIndex]; @@ -9784,7 +9483,7 @@ public bool CheckEndOfRoutePositionTT() } } - // if in last station and station is on end of route + // If in last station and station is on end of route if (!endOfRoute) { if (MovementState == AI_MOVEMENT_STATE.STATION_STOP && StationStops.Count == 1) @@ -9792,7 +9491,7 @@ public bool CheckEndOfRoutePositionTT() StationStop presentStation = StationStops[0]; int stationRouteIndex = -1; - // check all platform sections + // Check all platform sections foreach (int sectionIndex in presentStation.PlatformItem.TCSectionIndex) { stationRouteIndex = ValidRoute[0].GetRouteIndex(sectionIndex, PresentPosition[1].RouteListIndex); @@ -9807,7 +9506,7 @@ public bool CheckEndOfRoutePositionTT() endOfRoute = true; } - // test length of track beyond station + // Test length of track beyond station else { float remainLength = 0; @@ -9825,8 +9524,8 @@ public bool CheckEndOfRoutePositionTT() } } - // if waiting for next signal and section in front of signal is last in route - end of route reached - // if stopped at station and NoWaitSignal is set, train cannot be waiting for a signal + // If waiting for next signal and section in front of signal is last in route - end of route reached + // If stopped at station and NoWaitSignal is set, train cannot be waiting for a signal if (!endOfRoute && !(AtStation && StationStops[0].NoWaitSignal)) { if (NextSignalObject[0] != null && PresentPosition[0].TCSectionIndex == NextSignalObject[0].TCReference && @@ -9841,8 +9540,8 @@ public bool CheckEndOfRoutePositionTT() } } - // if waiting for next signal and section beyond signal is last in route and there is no valid reversal index - end of route reached - // if stopped at station and NoWaitSignal is set, train cannot be waiting for a signal + // If waiting for next signal and section beyond signal is last in route and there is no valid reversal index - end of route reached + // If stopped at station and NoWaitSignal is set, train cannot be waiting for a signal if (!endOfRoute && !(AtStation && StationStops[0].NoWaitSignal)) { if (NextSignalObject[0] != null && PresentPosition[0].TCSectionIndex == NextSignalObject[0].TCReference && @@ -9852,12 +9551,12 @@ public bool CheckEndOfRoutePositionTT() } } - // if remaining section length is less than safety distance + // If remaining section length is less than safety distance if (!endOfRoute) { TrackCircuitSection thisSection = signalRef.TrackCircuitList[ValidRoute[0][PresentPosition[0].RouteListIndex].TCSectionIndex]; int direction = ValidRoute[0][PresentPosition[0].RouteListIndex].Direction; - float remLength = (thisSection.Length - PresentPosition[0].TCOffset); + float remLength = thisSection.Length - PresentPosition[0].TCOffset; for (int Index = PresentPosition[0].RouteListIndex + 1; Index <= lastValidRouteIndex && (remLength < 2 * standardOverlapM); Index++) { @@ -9870,7 +9569,7 @@ public bool CheckEndOfRoutePositionTT() } } - // if next action is end of route and remaining distance is less than safety distance and no junction ahead of rear of train + // If next action is end of route and remaining distance is less than safety distance and no junction ahead of rear of train if (!endOfRoute) { bool junctionFound = false; @@ -9890,26 +9589,19 @@ public bool CheckEndOfRoutePositionTT() } } - // if rear of train is beyond reversal section + // If rear of train is beyond reversal section if (!endOfRoute) { if (reversalSectionIndex >= 0 && PresentPosition[1].RouteListIndex >= reversalSectionIndex) { - // if there is a station ahead, this is not end of route - if (MovementState != AI_MOVEMENT_STATE.STATION_STOP && StationStops != null && StationStops.Count > 0 && - StationStops[0].SubrouteIndex == TCRoute.activeSubpath) - { - endOfRoute = false; - } - else - { - endOfRoute = true; - } + // If there is a station ahead, this is not end of route + endOfRoute = MovementState == AI_MOVEMENT_STATE.STATION_STOP || StationStops == null || StationStops.Count <= 0 || + StationStops[0].SubrouteIndex != TCRoute.activeSubpath; } } - // if remaining length less then train length and no junctions to end of route - end of route reached - // if no junctions or signals to end of route - end of route reached + // If remaining length less then train length and no junctions to end of route - end of route reached + // If no junctions or signals to end of route - end of route reached if (!endOfRoute) { bool intermediateJunction = false; @@ -9918,15 +9610,15 @@ public bool CheckEndOfRoutePositionTT() float distanceToNextJunction = -1f; float distanceToNextSignal = -1f; - if (PresentPosition[1].RouteListIndex >= 0) // end of train is on route + if (PresentPosition[1].RouteListIndex >= 0) // End of train is on route { TrackCircuitSection thisSection = signalRef.TrackCircuitList[ValidRoute[0][PresentPosition[1].RouteListIndex].TCSectionIndex]; int direction = ValidRoute[0][PresentPosition[1].RouteListIndex].Direction; - length = (thisSection.Length - PresentPosition[1].TCOffset); - if (thisSection.EndSignals[direction] != null) // check for signal only in direction of train (other signal is behind train) + length = thisSection.Length - PresentPosition[1].TCOffset; + if (thisSection.EndSignals[direction] != null) // Check for signal only in direction of train (other signal is behind train) { intermediateSignal = true; - distanceToNextSignal = length; // distance is total length + distanceToNextSignal = length; // Distance is total length } if (thisSection.CircuitType == TrackCircuitSection.TrackCircuitType.Junction || thisSection.CircuitType == TrackCircuitSection.TrackCircuitType.Crossover) @@ -9952,14 +9644,15 @@ public bool CheckEndOfRoutePositionTT() intermediateSignal = true; distanceToNextSignal = distanceToNextSignal < 0 ? length : distanceToNextSignal; } - if (thisSection.EndSignals[direction == 1 ? 0 : 1] != null) // check in other direction + if (thisSection.EndSignals[direction == 1 ? 0 : 1] != null) // Check in other direction { intermediateSignal = true; - distanceToNextSignal = distanceToNextSignal < 0 ? length - thisSection.Length : distanceToNextSignal; // signal is at start of section + distanceToNextSignal = distanceToNextSignal < 0 ? length - thisSection.Length : distanceToNextSignal; // Signal is at start of section } } - // check if intermediate junction or signal is valid : only so if there is enough distance (from the front of the train) left for train to pass that junction - // however, do accept signal or junction if train is still in first section + + // Check if intermediate junction or signal is valid : only so if there is enough distance (from the front of the train) left for train to pass that junction + // However, do accept signal or junction if train is still in first section float frontlength = length; if (intermediateJunction) { @@ -9971,7 +9664,7 @@ public bool CheckEndOfRoutePositionTT() if ((frontlength - distanceToNextSignal) < Length && PresentPosition[0].RouteListIndex > 0) intermediateSignal = false; } } - else if (PresentPosition[0].RouteListIndex >= 0) // else use front position - check for further signals or junctions only + else if (PresentPosition[0].RouteListIndex >= 0) // Else use front position - check for further signals or junctions only { for (int iIndex = PresentPosition[0].RouteListIndex; iIndex >= 0 && iIndex <= lastValidRouteIndex; iIndex++) { @@ -9991,15 +9684,13 @@ public bool CheckEndOfRoutePositionTT() } } - // check overall position - - if (!intermediateJunction && !intermediateSignal && (StationStops == null || StationStops.Count < 1)) // no more junctions and no more signal and no more stations - reverse subpath + // Check overall position + if (!intermediateJunction && !intermediateSignal && (StationStops == null || StationStops.Count < 1)) // No more junctions and no more signal and no more stations - reverse subpath { endOfRoute = true; } - // check if there is a train ahead, and that train is stopped at the end of our route - if so, we can't go any further - + // Check if there is a train ahead, and that train is stopped at the end of our route - if so, we can't go any further if (!endOfRoute) { TrackCircuitSection thisSection = signalRef.TrackCircuitList[PresentPosition[0].TCSectionIndex]; @@ -10010,7 +9701,7 @@ public bool CheckEndOfRoutePositionTT() foreach (KeyValuePair trainAhead in trainInfo) { TTTrain otherTrain = trainAhead.Key as TTTrain; - if (Math.Abs(otherTrain.SpeedMpS) < 0.1f) // other train must be stopped + if (Math.Abs(otherTrain.SpeedMpS) < 0.1f) // Other train must be stopped { if (otherTrain.PresentPosition[0].TCSectionIndex == ValidRoute[0][lastValidRouteIndex].TCSectionIndex) { @@ -10026,12 +9717,11 @@ public bool CheckEndOfRoutePositionTT() } } - // return state - - // never return end of route if train has not moved + // Return state + // Never return end of route if train has not moved if (endOfRoute && DistanceTravelledM < 0.1) endOfRoute = false; - return (endOfRoute); + return endOfRoute; } //================================================================================================// @@ -10039,13 +9729,12 @@ public bool CheckEndOfRoutePositionTT() /// Remove train /// Override from Train class /// <\summary> - public override void RemoveTrain() { RemoveFromTrack(); ClearDeadlocks(); - // if train was to form another train, ensure this other train is started by removing the formed link + // If train was to form another train, ensure this other train is started by removing the formed link if (Forms >= 0) { TTTrain formedTrain = AI.StartList.GetNotStartedTTTrainByNumber(Forms, true); @@ -10076,8 +9765,7 @@ public override void RemoveTrain() } } #endif - // remove train - + // Remove train AI.TrainsToRemove.Add(this); } @@ -10087,7 +9775,6 @@ public override void RemoveTrain() /// Used to build movement state information in dispatcher HUD info /// Override from AITrain class /// <\summary> - public override String[] AddMovementState(String[] stateString, bool metric) { String[] retString = new String[stateString.Length]; @@ -10106,7 +9793,7 @@ public override String[] AddMovementState(String[] stateString, bool metric) movString = "STP "; break; case AI_MOVEMENT_STATE.STATION_STOP: - break; // set below + break; // Set below case AI_MOVEMENT_STATE.BRAKING: movString = "BRK "; break; @@ -10127,7 +9814,7 @@ public override String[] AddMovementState(String[] stateString, bool metric) string abString = AITrainThrottlePercent.ToString("000"); abString = String.Concat(abString, "&", AITrainBrakePercent.ToString("000")); - // if station stop : show departure time + // If station stop: show departure time if (MovementState == AI_MOVEMENT_STATE.STATION_STOP) { DateTime baseDT = new DateTime(); @@ -10219,7 +9906,7 @@ public override String[] AddMovementState(String[] stateString, bool metric) retString[5] = String.Copy(abString); retString[11] = String.Copy(nameString); - return (retString); + return retString; } //================================================================================================// @@ -10227,12 +9914,11 @@ public override String[] AddMovementState(String[] stateString, bool metric) /// Add reversal info to TrackMonitorInfo /// Override from Train class /// - public override void AddTrainReversalInfo(TCReversalInfo thisReversal, ref TrainInfo thisInfo) { if (!thisReversal.Valid) return; - int reversalSection = TCRoute.TCRouteSubpaths[TCRoute.activeSubpath][(TCRoute.TCRouteSubpaths[TCRoute.activeSubpath].Count) - 1].TCSectionIndex; + int reversalSection = TCRoute.TCRouteSubpaths[TCRoute.activeSubpath][TCRoute.TCRouteSubpaths[TCRoute.activeSubpath].Count - 1].TCSectionIndex; if (thisReversal.LastDivergeIndex >= 0) { reversalSection = thisReversal.SignalUsed ? thisReversal.SignalSectorIndex : thisReversal.DivergeSectorIndex; @@ -10264,15 +9950,14 @@ public override bool CheckRouteActions(float elapsedClockSeconds) if (PresentPosition[0].RouteListIndex >= 0) directionNow = ValidRoute[0][PresentPosition[0].RouteListIndex].Direction; - // check if at station + // Check if at station CheckStationTask(); - if (DetachPending) return (true); // do not check for further actions if player train detach is pending + if (DetachPending) return true; // Do not check for further actions if player train detach is pending bool[] nextRoute = UpdateRouteActions(elapsedClockSeconds); - if (!nextRoute[0]) return (true); // not at end of route - - // check if train reversed + if (!nextRoute[0]) return true; // Not at end of route + // Check if train reversed if (nextRoute[1]) { if (positionNow == PresentPosition[0].TCSectionIndex && directionNow != PresentPosition[0].TCDirection) @@ -10284,8 +9969,7 @@ public override bool CheckRouteActions(float elapsedClockSeconds) ReverseFormation(true); } - // check if next station was on previous subpath - if so, move to this subpath - + // Check if next station was on previous subpath - if so, move to this subpath if (StationStops.Count > 0) { StationStop thisStation = StationStops[0]; @@ -10295,32 +9979,29 @@ public override bool CheckRouteActions(float elapsedClockSeconds) } } } - - //process train end for player if stopped + // Process train end for player if stopped else { if (Math.Abs(SpeedMpS) < 0.05f) { SpeedMpS = 0.0f; - return (ProcessRouteEndTimetablePlayer()); + return ProcessRouteEndTimetablePlayer(); } } - // return train still exists - - return (true); + // Return train still exists + return true; } //================================================================================================// /// - /// compute boarding time for timetable mode - /// also check validity of depart time value + /// Compute boarding time for timetable mode + /// Also check validity of depart time value /// Override from Train class /// <\summary> - public override bool ComputeTrainBoardingTime(StationStop thisStop, ref int stopTime) { - // use minimun station dwell time + // Use minimun station dwell time if (stopTime <= 0 && thisStop.ActualMinStopTime.HasValue) { stopTime = thisStop.ActualMinStopTime.Value; @@ -10334,19 +10015,18 @@ public override bool ComputeTrainBoardingTime(StationStop thisStop, ref int stop stopTime = (int)thisStop.PlatformItem.MinWaitingTime; } - return (true); + return true; } //================================================================================================// /// - /// setup station stop handling for player train + /// Setup station stop handling for player train /// - public void SetupStationStopHandling() { - CheckStations = true; // set station stops to be handled by train - - // check if initial at station + CheckStations = true; // Set station stops to be handled by train + + // Check if initial at station if (StationStops.Count > 0) { int frontIndex = PresentPosition[0].RouteListIndex; @@ -10385,18 +10065,18 @@ public void SetupStationStopHandling() /// public override void CheckStationTask() { - // if at station + // If at station if (AtStation) { - // check for activation of other train + // Check for activation of other train ActivateTriggeredTrain(TriggerActivationType.StationStop, StationStops[0].PlatformReference); - // get time + // Get time int presentTime = Convert.ToInt32(Math.Floor(Simulator.ClockTime)); int eightHundredHours = 8 * 3600; int sixteenHundredHours = 16 * 3600; - // if moving, set departed + // If moving, set departed if (Math.Abs(SpeedMpS) > 1.0f) { StationStops[0].ActualDepart = presentTime; @@ -10406,16 +10086,16 @@ public override void CheckStationTask() DisplayMessage = ""; Delay = TimeSpan.FromSeconds((presentTime - StationStops[0].DepartTime) % (24 * 3600)); - // check for activation of other train + // Check for activation of other train ActivateTriggeredTrain(TriggerActivationType.StationDepart, StationStops[0].PlatformReference); - // remove stop + // Remove stop PreviousStop = StationStops[0].CreateCopy(); StationStops.RemoveAt(0); } else { - // check for detach + // Check for detach if (DetachDetails.ContainsKey(StationStops[0].PlatformReference)) { List detachList = DetachDetails[StationStops[0].PlatformReference]; @@ -10438,11 +10118,11 @@ public override void CheckStationTask() } } - // check for connection + // Check for connection int helddepart = -1; int needwait = -1; - // keep trying to set connections as train may be created during stop + // Keep trying to set connections as train may be created during stop if (StationStops[0].ConnectionsWaiting.Count > 0) { foreach (int otherTrainNumber in StationStops[0].ConnectionsWaiting) @@ -10462,13 +10142,13 @@ public override void CheckStationTask() } } - // check if waiting for connection + // Check if waiting for connection if (StationStops[0].ConnectionsAwaited.Count > 0) { needwait = ProcessConnections(StationStops[0], out helddepart); } - // check for attachments + // Check for attachments int waitAttach = -1; if (NeedAttach.ContainsKey(StationStops[0].PlatformReference)) @@ -10490,7 +10170,7 @@ public override void CheckStationTask() } } - // check if attaching + // Check if attaching int waitArrivalAttach = -1; bool readyToAttach = false; bool attaching = false; @@ -10504,7 +10184,7 @@ public override void CheckStationTask() waitArrivalAttach = AttachDetails.AttachTrain; if (attachTrain.MovementState == AI_MOVEMENT_STATE.STATION_STOP && attachTrain.StationStops[0].PlatformReference == StationStops[0].PlatformReference) { - // attach not already taking place + // Attach not already taking place if (AttachDetails.ReadyToAttach) { attaching = true; @@ -10517,7 +10197,7 @@ public override void CheckStationTask() } } - // set message + // Set message int remaining = 999; if (needwait >= 0) @@ -10571,13 +10251,13 @@ public override void CheckStationTask() { string attachPositionInfo = String.Empty; - // if setback required, reverse train + // If setback required, reverse train if (AttachDetails.SetBack) { - // remove any reserved sections + // Remove any reserved sections RemoveFromTrackNotOccupied(ValidRoute[0]); - // check if train in same section + // Check if train in same section float distanceToTrain = 0.0f; if (attachTrain.PresentPosition[0].TCSectionIndex == PresentPosition[1].TCSectionIndex) { @@ -10586,14 +10266,14 @@ public override void CheckStationTask() } else { - // get section index of other train in train route + // Get section index of other train in train route int endSectionIndex = ValidRoute[0].GetRouteIndexBackward(attachTrain.PresentPosition[0].TCSectionIndex, PresentPosition[1].RouteListIndex); if (endSectionIndex < 0) { Trace.TraceWarning("Train {0} : attach to train {1} failed, cannot find path", Name, attachTrain.Name); } - // get distance to train + // Get distance to train for (int iSection = PresentPosition[0].RouteListIndex; iSection >= endSectionIndex; iSection--) { TrackCircuitSection thisSection = signalRef.TrackCircuitList[ValidRoute[0][iSection].TCSectionIndex]; @@ -10601,11 +10281,11 @@ public override void CheckStationTask() } } - // create temp route and set as valid route + // Create temp route and set as valid route int newDirection = PresentPosition[0].TCDirection == 0 ? 1 : 0; TCSubpathRoute tempRoute = signalRef.BuildTempRoute(this, PresentPosition[0].TCSectionIndex, 0.0f, newDirection, distanceToTrain, true, true, false); - // set reverse positions + // Set reverse positions TCPosition tempPosition = new TCPosition(); PresentPosition[0].CopyTo(ref tempPosition); PresentPosition[1].CopyTo(ref PresentPosition[0]); @@ -10615,11 +10295,11 @@ public override void CheckStationTask() PresentPosition[0].CopyTo(ref PreviousPosition[0]); PresentPosition[1].Reverse(ValidRoute[0][PresentPosition[1].RouteListIndex].Direction, tempRoute, 0.0f, signalRef); - // reverse formation + // Reverse formation ReverseFormation(true); attachPositionInfo = Simulator.Catalog.GetString(", backward"); - // get new route list indices from new route + // Get new route list indices from new route DistanceTravelledM = 0; ValidRoute[0] = tempRoute; @@ -10629,7 +10309,7 @@ public override void CheckStationTask() } else { - // build path to train - straight forward, set distance of 2000m (should be enough) + // Build path to train - straight forward, set distance of 2000m (should be enough) TCSubpathRoute tempRoute = signalRef.BuildTempRoute(this, PresentPosition[1].TCSectionIndex, 0.0f, PresentPosition[1].TCDirection, 2000, true, true, false); ValidRoute[0] = tempRoute; attachPositionInfo = Simulator.Catalog.GetString(", forward"); @@ -10666,27 +10346,16 @@ public override void CheckStationTask() int correctedTime = presentTime; if (presentTime > sixteenHundredHours && StationStops[0].DepartTime < eightHundredHours) { - correctedTime = presentTime - 24 * 3600; // correct to time before midnight (negative value!) + correctedTime = presentTime - (24 * 3600); // Correct to time before midnight (negative value!) } remaining = actualDepart - correctedTime; - // set display text color - if (remaining < 1) - { - DisplayColor = Color.LightGreen; - } - else if (remaining < 11) - { - DisplayColor = new Color(255, 255, 128); - } - else - { - DisplayColor = Color.White; - } + // Set display text color + DisplayColor = remaining < 1 ? Color.LightGreen : remaining < 11 ? new Color(255, 255, 128) : Color.White; - // clear holding signal - if (remaining < 120 && StationStops[0].ExitSignal >= 0 && HoldingSignals.Contains(StationStops[0].ExitSignal)) // within two minutes of departure and hold signal? + // Clear holding signal + if (remaining < 120 && StationStops[0].ExitSignal >= 0 && HoldingSignals.Contains(StationStops[0].ExitSignal)) // Within two minutes of departure and hold signal? { HoldingSignals.Remove(StationStops[0].ExitSignal); @@ -10697,10 +10366,10 @@ public override void CheckStationTask() } } - // check departure time + // Check departure time if (remaining <= 0) { - // if at end of route allow depart without playing departure sound + // If at end of route allow depart without playing departure sound if (CheckEndOfRoutePositionTT()) { MayDepart = true; @@ -10708,7 +10377,7 @@ public override void CheckStationTask() } else if (!MayDepart) { - // check if signal ahead is cleared - if not, and signal is station exit signal, do not allow depart + // Check if signal ahead is cleared - if not, and signal is station exit signal, do not allow depart if (NextSignalObject[0] != null && NextSignalObject[0].this_sig_lr(MstsSignalFunction.NORMAL) == MstsSignalAspect.STOP && NextSignalObject[0].hasPermission != SignalObject.Permission.Granted && !StationStops[0].NoWaitSignal && NextSignalObject[0].thisRef == StationStops[0].ExitSignal) @@ -10720,7 +10389,7 @@ public override void CheckStationTask() MayDepart = true; if (!StationStops[0].EndStop) { - if (!DriverOnlyOperation) Simulator.SoundNotify = Event.PermissionToDepart; // sound departure if not doo + if (!DriverOnlyOperation) Simulator.SoundNotify = Event.PermissionToDepart; // Sound departure if not doo DisplayMessage = Simulator.Catalog.GetString("Passenger boarding completed. You may depart now."); } } @@ -10736,28 +10405,28 @@ public override void CheckStationTask() } else { - // if stations to be checked + // If stations to be checked if (StationStops.Count > 0) { - // check if stopped at station + // Check if stopped at station if (Math.Abs(SpeedMpS) < 0.05f) { - // build list of occupied section + // Build list of occupied section int frontIndex = PresentPosition[0].RouteListIndex; int rearIndex = PresentPosition[1].RouteListIndex; List occupiedSections = new List(); - // check valid positions - if (frontIndex < 0 && rearIndex < 0) // not on route so cannot be in station + // Check valid positions + if (frontIndex < 0 && rearIndex < 0) // Not on route so cannot be in station { - return; // no further actions possible + return; // No further actions possible } - // correct position if either end is off route + // Correct position if either end is off route if (frontIndex < 0) frontIndex = rearIndex; if (rearIndex < 0) rearIndex = frontIndex; - // set start and stop in correct order + // Set start and stop in correct order int startIndex = frontIndex < rearIndex ? frontIndex : rearIndex; int stopIndex = frontIndex < rearIndex ? rearIndex : frontIndex; @@ -10766,7 +10435,7 @@ public override void CheckStationTask() occupiedSections.Add(ValidRoute[0][iIndex].TCSectionIndex); } - // check if any platform section is in list of occupied sections - if so, we're in the station + // Check if any platform section is in list of occupied sections - if so, we're in the station foreach (int sectionIndex in StationStops[0].PlatformItem.TCSectionIndex) { if (occupiedSections.Contains(sectionIndex)) @@ -10807,13 +10476,13 @@ public override void CheckStationTask() } else { - MovementState = AI_MOVEMENT_STATE.RUNNING; // reset movement state (must not remain set at STATION_STOP) + MovementState = AI_MOVEMENT_STATE.RUNNING; // Reset movement state (must not remain set at STATION_STOP) if (nextActionInfo != null && nextActionInfo.NextAction == AIActionItem.AI_ACTION_TYPE.STATION_STOP) { - nextActionInfo = null; // clear next action if still referring to station stop + nextActionInfo = null; // Clear next action if still referring to station stop } - // check if station missed : station must be at least 500m. behind us + // Check if station missed : station must be at least 500m. behind us bool missedStation = false; int stationRouteIndex = ValidRoute[0].GetRouteIndex(StationStops[0].TCSectionIndex, 0); @@ -10835,8 +10504,7 @@ public override void CheckStationTask() PreviousStop = StationStops[0].CreateCopy(); StationStops.RemoveAt(0); - if (Simulator.Confirmer != null) // As Confirmer may not be created until after a restore. - Simulator.Confirmer.Information("Missed station stop : " + PreviousStop.PlatformItem.Name); + Simulator.Confirmer?.Information("Missed station stop : " + PreviousStop.PlatformItem.Name); } } @@ -10849,16 +10517,15 @@ public override void CheckStationTask() /// Special actions in timetable mode when waiting for signal to clear /// Override from Train class to allow call from common methods /// <\summary> - public override void ActionsForSignalStop(ref bool claimAllowed) { - // cannot claim if in station and noclaim is set + // Cannot claim if in station and noclaim is set if (AtStation) { if (StationStops[0].NoClaimAllowed) claimAllowed = false; } - // test for attach for train ahead + // Test for attach for train ahead if (AttachDetails != null && AttachDetails.StationPlatformReference < 0 && !AttachDetails.ReadyToAttach) { for (int iIndex = PresentPosition[0].RouteListIndex; iIndex < ValidRoute[0].Count; iIndex++) @@ -10892,12 +10559,11 @@ public override void ActionsForSignalStop(ref bool claimAllowed) /// Switch to Node control /// Override from Train class /// <\summary> - public override void SwitchToNodeControl(int thisSectionIndex) { base.SwitchToNodeControl(thisSectionIndex); - // check if train is to attach in sections ahead (otherwise done at signal) + // Check if train is to attach in sections ahead (otherwise done at signal) if (TrainType != TRAINTYPE.PLAYER) { CheckReadyToAttach(); @@ -10909,7 +10575,6 @@ public override void SwitchToNodeControl(int thisSectionIndex) /// Clear station from list, clear exit signal if required /// Override from Train class /// <\summary> - public override void ClearStation(uint id1, uint id2, bool removeStation) { int foundStation = -1; @@ -10924,7 +10589,7 @@ public override void ClearStation(uint id1, uint id2, bool removeStation) foundStation = iStation; } - if (thisStation.SubrouteIndex > TCRoute.activeSubpath) break; // stop looking if station is in next subpath + if (thisStation.SubrouteIndex > TCRoute.activeSubpath) break; // Stop looking if station is in next subpath } if (foundStation >= 0) @@ -10965,32 +10630,25 @@ public int ProcessConnections(StationStop thisStop, out int deptime) foreach (KeyValuePair connectionInfo in thisStop.ConnectionsAwaited) { - // check if train arrival time set + // Check if train arrival time set int otherTrainNumber = connectionInfo.Key; WaitInfo reqWait = thisStop.ConnectionDetails[otherTrainNumber]; if (connectionInfo.Value >= 0) { removeKeys.Add(connectionInfo.Key); - int reqHoldTime = (reqWait.holdTimeS.HasValue) ? reqWait.holdTimeS.Value : 0; + int reqHoldTime = reqWait.holdTimeS.HasValue ? reqWait.holdTimeS.Value : 0; int allowedDepart = (connectionInfo.Value + reqHoldTime) % (24 * 3600); - if (helddepart.HasValue) - { - helddepart = CompareTimes.LatestTime(helddepart.Value, allowedDepart); - } - else - { - helddepart = allowedDepart; - } + helddepart = helddepart.HasValue ? CompareTimes.LatestTime(helddepart.Value, allowedDepart) : allowedDepart; } else - // check if train exists and if so, check its delay + // Check if train exists and if so, check its delay { TTTrain otherTrain = GetOtherTTTrainByNumber(otherTrainNumber); if (otherTrain != null) { - // get station index for other train + // Get station index for other train StationStop reqStop = null; foreach (StationStop nextStop in otherTrain.StationStops) @@ -11002,50 +10660,50 @@ public int ProcessConnections(StationStop thisStop, out int deptime) } } - // check if train is not passed the station + // Check if train is not passed the station if (reqStop != null) { if (otherTrain.Delay.HasValue && reqWait.maxDelayS.HasValue) { if (otherTrain.Delay.Value.TotalSeconds <= reqWait.maxDelayS.Value) { - needwait = otherTrainNumber; // train is within allowed time - wait required - break; // no need to check other trains + needwait = otherTrainNumber; // Train is within allowed time - wait required + break; // No need to check other trains } else if (Delay.HasValue && (thisStop.ActualDepart > reqStop.ArrivalTime + otherTrain.Delay.Value.TotalSeconds)) { - needwait = otherTrainNumber; // train expected to arrive before our departure - wait + needwait = otherTrainNumber; // Train expected to arrive before our departure - wait break; } else { - removeKeys.Add(connectionInfo.Key); // train is excessively late - remove connection + removeKeys.Add(connectionInfo.Key); // Train is excessively late - remove connection } } else { needwait = otherTrainNumber; - break; // no need to check other trains + break; // No need to check other trains } } } } } - // remove processed keys + // Remove processed keys foreach (int key in removeKeys) { thisStop.ConnectionsAwaited.Remove(key); } - // set departure time + // Set departure time deptime = -1; if (helddepart.HasValue) { deptime = helddepart.Value; } - return (needwait); + return needwait; } //================================================================================================// @@ -11062,16 +10720,16 @@ public bool ProcessRouteEndTimetablePlayer() int nextTrainNumber = -1; bool stillExist = true; - // check if needs to attach - if so, keep alive + // Check if needs to attach - if so, keep alive if (AttachDetails != null && AttachDetails.Valid) { - return (true); + return true; } - // check if final station not yet processed and any detach actions required - bool allowForm = DetachActive[1] == -1; // preset if form is allowed to proceed - may not proceed if detach action is still active + // Check if final station not yet processed and any detach actions required + bool allowForm = DetachActive[1] == -1; // Preset if form is allowed to proceed - may not proceed if detach action is still active - // check if detach action active + // Check if detach action active if (DetachActive[1] == -1) { if (StationStops != null && StationStops.Count > 0) @@ -11095,7 +10753,7 @@ public bool ProcessRouteEndTimetablePlayer() if (allowForm) DetachDetails.Remove(StationStops[0].PlatformReference); } - // check if anything needs be detached at formed + // Check if anything needs be detached at formed if (DetachDetails.ContainsKey(-1)) { List detachList = DetachDetails[-1]; @@ -11115,24 +10773,24 @@ public bool ProcessRouteEndTimetablePlayer() } } - // check if train is still player train + // Check if train is still player train if (TrainType != TRAINTYPE.PLAYER) { FormTrainFromAI(presentTime); stillExist = false; } - // if player train, only form new train if allowed - may be blocked by detach if detach is performed through player detach window + // If player train, only form new train if allowed - may be blocked by detach if detach is performed through player detach window else if (allowForm) { - // train is terminated and does not form next train - set to static + // Train is terminated and does not form next train - set to static if (Forms < 0) { ControlMode = TRAIN_CONTROL.INACTIVE; ActivateTime = null; StartTime = null; - // train is stored in pool + // Train is stored in pool if (!String.IsNullOrEmpty(ExitPool)) { TimetablePool thisPool = Simulator.PoolHolder.Pools[ExitPool]; @@ -11140,16 +10798,16 @@ public bool ProcessRouteEndTimetablePlayer() } MovementState = AI_MOVEMENT_STATE.AI_STATIC; - return (true); + return true; } - // form next train + // Form next train TTTrain nextPlayerTrain = null; List newTrains = new List(); bool autogenStart = false; - // get train which is to be formed + // Get train which is to be formed TTTrain formedTrain = Simulator.AI.StartList.GetNotStartedTTTrainByNumber(Forms, true); if (formedTrain == null) @@ -11158,16 +10816,16 @@ public bool ProcessRouteEndTimetablePlayer() autogenStart = true; } - // if found - start train + // If found - start train if (formedTrain != null) { - // remove existing train + // Remove existing train Forms = -1; - // remove all existing deadlock path references + // Remove all existing deadlock path references signalRef.RemoveDeadlockPathReferences(0); - // set details for new train from existing train + // Set details for new train from existing train TrackCircuitSection[] occupiedSections = new TrackCircuitSection[OccupiedTrack.Count]; OccupiedTrack.CopyTo(occupiedSections); bool validFormed = formedTrain.StartFromAITrain(this, presentTime, occupiedSections); @@ -11178,7 +10836,7 @@ public bool ProcessRouteEndTimetablePlayer() if (validFormed) { - // start new train + // Start new train if (!autogenStart) { Simulator.StartReference.Remove(formedTrain.Number); @@ -11196,27 +10854,27 @@ public bool ProcessRouteEndTimetablePlayer() } else if (!autogenStart) { - // reinstate as to be started (note : train is not yet removed from reference) + // Reinstate as to be started (note : train is not yet removed from reference) Simulator.AI.StartList.InsertTrain(formedTrain); } } - // set proper player train references + // Set proper player train references if (nextTrainNumber > 0) { - // clear this train - prepare for removal + // Clear this train - prepare for removal RemoveFromTrack(); ClearDeadlocks(); Simulator.Trains.Remove(this); - Number = OrgAINumber; // reset number + Number = OrgAINumber; // Reset number stillExist = false; AI.TrainsToRemove.Add(this); - // remove formed train from AI list + // Remove formed train from AI list AI.TrainsToRemoveFromAI.Add(formedTrain); - // set proper details for new formed train + // Set proper details for new formed train formedTrain.OrgAINumber = nextTrainNumber; formedTrain.Number = 0; AI.TrainsToAdd.Add(formedTrain); @@ -11228,7 +10886,7 @@ public bool ProcessRouteEndTimetablePlayer() formedTrain.ControlMode = TRAIN_CONTROL.INACTIVE; formedTrain.MovementState = AI_MOVEMENT_STATE.AI_STATIC; - // copy train control details + // Copy train control details formedTrain.MUDirection = MUDirection; formedTrain.MUThrottlePercent = MUThrottlePercent; formedTrain.MUGearboxGearIndex = MUGearboxGearIndex; @@ -11244,13 +10902,13 @@ public bool ProcessRouteEndTimetablePlayer() formedTrain.InitializeBrakes(); } - // reallocate deadlock path references for new train + // Reallocate deadlock path references for new train signalRef.ReallocateDeadlockPathReferences(nextTrainNumber, 0); bool foundPlayerLocomotive = false; TrainCar newPlayerLocomotive = null; - // search for player locomotive + // Search for player locomotive for (int icar = 0; icar < formedTrain.Cars.Count; icar++) { var car = formedTrain.Cars[icar]; @@ -11276,11 +10934,11 @@ public bool ProcessRouteEndTimetablePlayer() Simulator.OnPlayerLocomotiveChanged(); } - // notify viewer of change in selected train + // Notify viewer of change in selected train Simulator.OnPlayerTrainChanged(this, formedTrain); Simulator.PlayerLocomotive.Train = formedTrain; - // set up station handling for new train + // Set up station handling for new train formedTrain.SetupStationStopHandling(); if (AtStation && formedTrain.AtStation && StationStops[0].PlatformReference == formedTrain.StationStops[0].PlatformReference) @@ -11292,35 +10950,33 @@ public bool ProcessRouteEndTimetablePlayer() formedTrain.StationStops[0].CalculateDepartTime(presentTime, this); } - // clear replay commands + // Clear replay commands Simulator.Log.CommandList.Clear(); - // display messages - if (Simulator.Confirmer != null) // As Confirmer may not be created until after a restore. - Simulator.Confirmer.Information("Player switched to train : " + formedTrain.Name); + // Display messages + Simulator.Confirmer?.Information("Player switched to train : " + formedTrain.Name); } } - return (stillExist); + return stillExist; } //================================================================================================// /// /// Process speed settings defined in timetable /// - public void ProcessSpeedSettings() { SpeedSettings.consistSpeedMpS = SpeedSettings.consistSpeedMpS == 0 ? SpeedSettings.routeSpeedMpS : Math.Min(SpeedSettings.consistSpeedMpS, SpeedSettings.routeSpeedMpS); - // correct cruise speed if value is incorrect + // Correct cruise speed if value is incorrect if (SpeedSettings.maxSpeedMpS.HasValue && SpeedSettings.cruiseSpeedMpS.HasValue && SpeedSettings.maxSpeedMpS < SpeedSettings.cruiseSpeedMpS) { SpeedSettings.cruiseSpeedMpS = SpeedSettings.maxSpeedMpS; } - // take max of maxspeed and consist speed, or set maxspeed + // Take max of maxspeed and consist speed, or set maxspeed if (SpeedSettings.maxSpeedMpS.HasValue) { SpeedSettings.maxSpeedMpS = Math.Min(SpeedSettings.maxSpeedMpS.Value, SpeedSettings.consistSpeedMpS); @@ -11331,13 +10987,13 @@ public void ProcessSpeedSettings() SpeedSettings.maxSpeedMpS = SpeedSettings.consistSpeedMpS; } - // take max of cruisespeed and consist speed + // Take max of cruisespeed and consist speed if (SpeedSettings.cruiseSpeedMpS.HasValue) { SpeedSettings.cruiseSpeedMpS = Math.Min(SpeedSettings.cruiseSpeedMpS.Value, SpeedSettings.consistSpeedMpS); } - // set creep, attach and detach speed if not defined + // Set creep, attach and detach speed if not defined if (!SpeedSettings.creepSpeedMpS.HasValue) { SpeedSettings.creepSpeedMpS = TTTrain.creepSpeedMpS; @@ -11382,7 +11038,7 @@ public int GetUnitsToDetach(DetachInfo.DetachUnitsInfo detachUnits, int numberOf bool checktender = false; bool checkengine = false; - // check first unit + // Check first unit thisCar = Cars[0]; if (thisCar.WagonType == TrainCar.WagonTypes.Engine) { @@ -11450,7 +11106,7 @@ public int GetUnitsToDetach(DetachInfo.DetachUnitsInfo detachUnits, int numberOf checkengine = false; frontpos = false; - // check first unit + // Check first unit thisCar = Cars[Cars.Count - 1]; if (thisCar.WagonType == TrainCar.WagonTypes.Engine) { @@ -11518,7 +11174,7 @@ public int GetUnitsToDetach(DetachInfo.DetachUnitsInfo detachUnits, int numberOf case DetachInfo.DetachUnitsInfo.nonPower: int frontunits = 0; - // power is at front + // Power is at front if (Cars[0].WagonType == TrainCar.WagonTypes.Engine || Cars[0].WagonType == TrainCar.WagonTypes.Tender) { frontpos = false; @@ -11536,7 +11192,7 @@ public int GetUnitsToDetach(DetachInfo.DetachUnitsInfo detachUnits, int numberOf } iunits = Cars.Count - frontunits; } - // power is at rear + // Power is at rear else { frontpos = true; @@ -11558,8 +11214,8 @@ public int GetUnitsToDetach(DetachInfo.DetachUnitsInfo detachUnits, int numberOf case DetachInfo.DetachUnitsInfo.consists: bool inConsist = false; - - // check if front must be detached + + // Check if front must be detached if (detachConsist.Contains(Cars[0].OrgConsist)) { inConsist = true; @@ -11613,7 +11269,7 @@ public int GetUnitsToDetach(DetachInfo.DetachUnitsInfo detachUnits, int numberOf break; } - return (iunits); + return iunits; } //================================================================================================// @@ -11625,7 +11281,7 @@ public int GetUnitsToDetach(DetachInfo.DetachUnitsInfo detachUnits, int numberOf /// public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainFront) { - // stop train + // Stop train SpeedMpS = 0; foreach (var car in Cars) { @@ -11635,7 +11291,7 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF if (TrainType != TRAINTYPE.PLAYER) AdjustControlsThrottleOff(); physicsUpdate(0); - // stop attach train + // Stop attach train attachTrain.SpeedMpS = 0; foreach (var car in attachTrain.Cars) { @@ -11645,13 +11301,13 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF if (attachTrain.TrainType != TRAINTYPE.PLAYER) attachTrain.AdjustControlsThrottleOff(); attachTrain.physicsUpdate(0); - // set message for checktrain + // Set message for checktrain if (attachTrain.CheckTrain || CheckTrain) { File.AppendAllText(@"C:\temp\checktrain.txt", "Attaching : " + Number + " ; to : " + attachTrain.Number + " ; at front : " + attachTrainFront.ToString() + "\n"); } - // check on reverse formation + // Check on reverse formation if (thisTrainFront == attachTrainFront) { ReverseFormation(TrainType == TRAINTYPE.PLAYER); @@ -11669,7 +11325,7 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF playerLocomotiveIndex = attachTrain.LeadLocomotiveIndex; } - // attach to front of waiting train + // Attach to front of waiting train if (attachTrainFront) { attachCar = Cars[Cars.Count - 1]; @@ -11681,7 +11337,7 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF if (attachTrain.TrainType == TRAINTYPE.PLAYER) playerLocomotiveIndex++; } } - // attach to rear of waiting train + // Attach to rear of waiting train else { if (TrainType == TRAINTYPE.PLAYER) playerLocomotiveIndex += attachTrain.Cars.Count; @@ -11692,7 +11348,7 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF } } - // renumber cars + // Renumber cars int carId = 0; foreach (var car in attachTrain.Cars) { @@ -11700,27 +11356,27 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF carId++; } - // remove cars from this train + // Remove cars from this train Cars.Clear(); attachTrain.Length += Length; float distanceTravelledCorrection = 0; attachTrain.ReinitializeEOT(); - // recalculate position of formed train - if (attachTrainFront) // coupled to front, so rear position is still valid + // Recalculate position of formed train + if (attachTrainFront) // Coupled to front, so rear position is still valid { attachTrain.CalculatePositionOfCars(); attachTrain.DistanceTravelledM += Length; distanceTravelledCorrection = Length; } - else // coupled to rear so front position is still valid + else // Coupled to rear so front position is still valid { - attachTrain.RepositionRearTraveller(); // fix the rear traveller + attachTrain.RepositionRearTraveller(); // Fix the rear traveller attachTrain.CalculatePositionOfCars(); } - // update positions train + // Update positions train TrackNode tn = attachTrain.FrontTDBTraveller.TN; float offset = attachTrain.FrontTDBTraveller.TrackNodeOffset; int direction = (int)attachTrain.FrontTDBTraveller.Direction; @@ -11734,7 +11390,7 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF attachTrain.PresentPosition[1].SetTCPosition(tn.TCCrossReference, offset, direction); - // set new track sections occupied + // Set new track sections occupied TCSubpathRoute tempRoute = signalRef.BuildTempRoute(attachTrain, attachTrain.PresentPosition[1].TCSectionIndex, attachTrain.PresentPosition[1].TCOffset, attachTrain.PresentPosition[1].TCDirection, attachTrain.Length, true, true, false); @@ -11748,19 +11404,19 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF } } - // first reserve to ensure all switches are properly alligned + // First reserve to ensure all switches are properly alligned foreach (TrackCircuitSection newSection in newOccupiedSections) { newSection.Reserve(attachTrain.routedForward, tempRoute); } - // next set occupied + // Next set occupied foreach (TrackCircuitSection newSection in newOccupiedSections) { newSection.SetOccupied(attachTrain.routedForward); } - // reset OccupiedTrack to ensure it is set in correct sequence + // Reset OccupiedTrack to ensure it is set in correct sequence attachTrain.OccupiedTrack.Clear(); foreach (TCRouteElement thisElement in tempRoute) { @@ -11768,20 +11424,20 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF attachTrain.OccupiedTrack.Add(thisSection); } - // set various items + // Set various items attachTrain.CheckFreight(); attachTrain.SetDPUnitIDs(); attachCar.SignalEvent(Event.Couple); attachTrain.ProcessSpeedSettings(); - // adjust set actions for updated distance travelled value + // Adjust set actions for updated distance travelled value if (distanceTravelledCorrection > 0) { attachTrain.requiredActions.ModifyRequiredDistance(distanceTravelledCorrection); } - // if not static, reassess signals if coupled at front (no need to reassess signals if coupled to rear) - // also, reset movement state if not player train + // If not static, reassess signals if coupled at front (no need to reassess signals if coupled to rear) + // Also, reset movement state if not player train if (attachTrain.MovementState != AI_MOVEMENT_STATE.AI_STATIC) { if (attachTrainFront) @@ -11799,7 +11455,7 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF } attachTrain.ResetActions(true, false); - // check if stopped in station - either this train or the attach train + // Check if stopped in station - either this train or the attach train if (AtStation && attachTrain.StationStops.Count > 0) { if (StationStops[0].PlatformReference == attachTrain.StationStops[0].PlatformReference) @@ -11819,8 +11475,8 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF { if (attachTrain.StationStops[0].SubrouteIndex == attachTrain.TCRoute.activeSubpath && attachTrain.ValidRoute[0].GetRouteIndex(attachTrain.StationStops[0].TCSectionIndex, attachTrain.PresentPosition[0].RouteListIndex) <= attachTrain.PresentPosition[0].RouteListIndex) - // assume to be in station - // also set state of present train to station stop + // Assume to be in station + // Also set state of present train to station stop { MovementState = attachTrain.MovementState = AI_MOVEMENT_STATE.STATION_STOP; attachTrain.AtStation = true; @@ -11840,8 +11496,8 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF attachTrain.DistanceTravelledM = 0; } - // check for needattach in attached train - // if stopped at station use platform reference + // Check for needattach in attached train + // If stopped at station use platform reference bool needAttachFound = false; if (AtStation) @@ -11861,7 +11517,7 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF } } } - // else search through all entries + // Else search through all entries if (!needAttachFound && attachTrain.NeedAttach != null && attachTrain.NeedAttach.Count > 0) { @@ -11892,10 +11548,10 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF } #endif - // if train is player or intended player and train has no player engine, determine new loco lead index + // If train is player or intended player and train has no player engine, determine new loco lead index if (attachTrain.TrainType == Train.TRAINTYPE.PLAYER || attachTrain.TrainType == Train.TRAINTYPE.INTENDED_PLAYER) { - if (Simulator.Confirmer != null) Simulator.Confirmer.Information("Train " + Name + " has attached"); + Simulator.Confirmer?.Information("Train " + Name + " has attached"); Trace.TraceInformation("Train " + Name + " has attached to player train"); if (attachTrain.LeadLocomotive == null) @@ -11904,9 +11560,9 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF { attachTrain.LeadLocomotive = attachTrain.Simulator.PlayerLocomotive = attachTrain.Cars[0]; } - else if (attachTrain.Cars[(attachTrain.Cars.Count - 1)].IsDriveable) + else if (attachTrain.Cars[attachTrain.Cars.Count - 1].IsDriveable) { - attachTrain.LeadLocomotive = attachTrain.Simulator.PlayerLocomotive = attachTrain.Cars[(attachTrain.Cars.Count - 1)]; + attachTrain.LeadLocomotive = attachTrain.Simulator.PlayerLocomotive = attachTrain.Cars[attachTrain.Cars.Count - 1]; } else { @@ -11921,21 +11577,21 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF } else { - // reassign leadlocomotive to reset index + // Reassign leadlocomotive to reset index attachTrain.LeadLocomotive = attachTrain.Simulator.PlayerLocomotive = attachTrain.Cars[playerLocomotiveIndex]; attachTrain.LeadLocomotiveIndex = playerLocomotiveIndex; } - // if not in preupdate there must be an engine + // If not in preupdate there must be an engine if (AI.Simulator.PlayerLocomotive == null && !Simulator.PreUpdate) { throw new InvalidDataException("Can't find player locomotive in " + attachTrain.Name); } } - // if attaching train is player : switch trains and set new engine index + // If attaching train is player : switch trains and set new engine index else if (TrainType == TRAINTYPE.PLAYER) { - // prepare to remove old train + // Prepare to remove old train Number = OrgAINumber; attachTrain.OrgAINumber = attachTrain.Number; attachTrain.Number = 0; @@ -11943,11 +11599,11 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF RemoveTrain(); Simulator.Trains.Remove(this); - // reassign leadlocomotive to reset index + // Reassign leadlocomotive to reset index attachTrain.LeadLocomotiveIndex = playerLocomotiveIndex; attachTrain.LeadLocomotive = attachTrain.Simulator.PlayerLocomotive = attachTrain.Cars[playerLocomotiveIndex]; - // correctly insert new player train + // Correctly insert new player train attachTrain.AI.TrainsToRemoveFromAI.Add(attachTrain); attachTrain.Simulator.Trains.Remove(attachTrain); attachTrain.AI.TrainsToAdd.Add(attachTrain); @@ -11957,13 +11613,13 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF attachTrain.SetFormedOccupied(); attachTrain.TrainType = Train.TRAINTYPE.PLAYER; - // if present movement state is active state, copy to new train + // If present movement state is active state, copy to new train if (MovementState != AI_MOVEMENT_STATE.AI_STATIC) { attachTrain.MovementState = MovementState; } - // inform viewer about player train switch + // Inform viewer about player train switch attachTrain.Simulator.OnPlayerTrainChanged(this, attachTrain); attachTrain.Simulator.PlayerLocomotive.Train = attachTrain; @@ -11976,7 +11632,7 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF } } - // set anti-slip for all engines in AI train + // Set anti-slip for all engines in AI train else { foreach (TrainCar car in attachTrain.Cars) @@ -11989,13 +11645,13 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF } } - // remove original train + // Remove original train RemoveTrain(); - // stop the wheels from moving etc + // Stop the wheels from moving etc attachTrain.physicsUpdate(0); - // initialize brakes on resulting train except when both trains are player trains + // Initialize brakes on resulting train except when both trains are player trains if (attachTrain.TrainType == TRAINTYPE.PLAYER) { attachTrain.ConnectBrakeHoses(); @@ -12005,7 +11661,7 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF attachTrain.InitializeBrakes(); } - // update route positions if required + // Update route positions if required int trainRearPositionIndex = attachTrain.ValidRoute[0].GetRouteIndex(tempRoute.First().TCSectionIndex, 0); int trainFrontPositionIndex = attachTrain.ValidRoute[0].GetRouteIndex(tempRoute.Last().TCSectionIndex, 0); @@ -12014,13 +11670,13 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF attachTrain.AdjustTrainRouteOnStart(trainRearPositionIndex, trainFrontPositionIndex, this); } - // recalculate station stop positions + // Recalculate station stop positions attachTrain.RecalculateStationStops(); - // if normal stop, set restart delay + // If normal stop, set restart delay if (!AtStation && !attachTrain.AtStation) { - float randDelay = (float)Simulator.Random.Next((DelayedStartSettings.attachRestart.randomPartS * 10)); + float randDelay = Simulator.Random.Next(DelayedStartSettings.attachRestart.randomPartS * 10); RestdelayS = DelayedStartSettings.attachRestart.fixedPartS + (randDelay / 10f); DelayedStart = true; DelayedStartState = AI_START_MOVEMENT.PATH_ACTION; @@ -12039,62 +11695,60 @@ public void TTCouple(TTTrain attachTrain, bool thisTrainFront, bool attachTrainF /// public int TTUncoupleBehind(TTTrain newTrain, bool reverseTrain, int leadLocomotiveIndex, bool newIsPlayer) { - // if front portion : move req units to new train and remove from old train - // remove from rear to front otherwise they cannot be deleted - + // If front portion: move req units to new train and remove from old train + // Remove from rear to front otherwise they cannot be deleted int newLeadLocomotiveIndex = leadLocomotiveIndex; bool leadLocomotiveInNewTrain = false; var detachCar = Cars[DetachUnits]; - // detach from front + // Detach from front if (DetachPosition) { detachCar = Cars[DetachUnits]; - newTrain.Cars.Clear(); // remove any cars on new train + newTrain.Cars.Clear(); // Remove any cars on new train for (int iCar = 0; iCar <= DetachUnits - 1; iCar++) { - var car = Cars[0]; // each car is removed so always detach first car!!! + var car = Cars[0]; // Each car is removed so always detach first car!!! Cars.Remove(car); Length = -car.CarLengthM; - newTrain.Cars.Add(car); // place in rear + newTrain.Cars.Add(car); // Place in rear car.Train = newTrain; car.CarID = String.Concat(newTrain.Number.ToString("0000"), "_", (newTrain.Cars.Count - 1).ToString("0000")); newTrain.Length += car.CarLengthM; - leadLocomotiveInNewTrain = leadLocomotiveInNewTrain || iCar == LeadLocomotiveIndex; // if detached car is leadlocomotive, the locomotive is in the new train + leadLocomotiveInNewTrain = leadLocomotiveInNewTrain || iCar == LeadLocomotiveIndex; // If detached car is leadlocomotive, the locomotive is in the new train } - // if lead locomotive is beyond detach unit, update index + // If lead locomotive is beyond detach unit, update index if (leadLocomotiveIndex >= DetachUnits) { newLeadLocomotiveIndex = leadLocomotiveIndex - DetachUnits; } - // if new train is player but engine is not in new train, reset Simulator.Playerlocomotive + // If new train is player but engine is not in new train, reset Simulator.Playerlocomotive else if (newIsPlayer && !leadLocomotiveInNewTrain) { Simulator.PlayerLocomotive = null; } - } - // detach from rear + // Detach from rear else { int detachUnitsFromFront = Cars.Count - DetachUnits; detachCar = Cars[Cars.Count - DetachUnits]; int totalCars = Cars.Count; - newTrain.Cars.Clear(); // remove any cars on new train + newTrain.Cars.Clear(); // Remove any cars on new train for (int iCar = 0; iCar <= DetachUnits - 1; iCar++) { - var car = Cars[totalCars - 1 - iCar]; // total cars is original length which keeps value despite cars are removed + var car = Cars[totalCars - 1 - iCar]; // Total cars is original length which keeps value despite cars are removed Cars.Remove(car); Length -= car.CarLengthM; - newTrain.Cars.Insert(0, car); // place in front + newTrain.Cars.Insert(0, car); // Place in front car.Train = newTrain; car.CarID = String.Concat(newTrain.Number.ToString("0000"), "_", (DetachUnits - newTrain.Cars.Count).ToString("0000")); newTrain.Length += car.CarLengthM; leadLocomotiveInNewTrain = leadLocomotiveInNewTrain || (totalCars - 1 - iCar) == LeadLocomotiveIndex; } - // if lead locomotive is beyond detach unit, update index + // If lead locomotive is beyond detach unit, update index if (leadLocomotiveIndex >= detachUnitsFromFront) { newLeadLocomotiveIndex = leadLocomotiveIndex - detachUnitsFromFront; @@ -12103,13 +11757,12 @@ public int TTUncoupleBehind(TTTrain newTrain, bool reverseTrain, int leadLocomot { Simulator.PlayerLocomotive = null; } - } ReinitializeEOT(); newTrain.ReinitializeEOT(); - // and fix up the travellers + // And fix up the travellers if (DetachPosition) { CalculatePositionOfCars(); @@ -12120,7 +11773,7 @@ public int TTUncoupleBehind(TTTrain newTrain, bool reverseTrain, int leadLocomot { newTrain.RearTDBTraveller = new Traveller(RearTDBTraveller); newTrain.CalculatePositionOfCars(); - RepositionRearTraveller(); // fix the rear traveller + RepositionRearTraveller(); // Fix the rear traveller } LastCar.CouplerSlackM = 0; @@ -12130,7 +11783,7 @@ public int TTUncoupleBehind(TTTrain newTrain, bool reverseTrain, int leadLocomot newTrain.AITrainBrakePercent = AITrainBrakePercent; newTrain.AITrainDirectionForward = true; - // disconnect brake hose and close angle cocks + // Disconnect brake hose and close angle cocks if (DetachPosition) { Cars[0].BrakeSystem.FrontBrakeHoseConnected = false; @@ -12144,7 +11797,7 @@ public int TTUncoupleBehind(TTTrain newTrain, bool reverseTrain, int leadLocomot Cars[Cars.Count - 1].BrakeSystem.AngleCockBOpen = false; } - // reverse new train if required + // Reverse new train if required if (reverseTrain) { newTrain.ReverseFormation(false); @@ -12154,22 +11807,22 @@ public int TTUncoupleBehind(TTTrain newTrain, bool reverseTrain, int leadLocomot } } - // check freight for both trains + // Check freight for both trains CheckFreight(); SetDPUnitIDs(); newTrain.CheckFreight(); newTrain.SetDPUnitIDs(); - // check speed values for both trains + // Check speed values for both trains ProcessSpeedSettings(); newTrain.ProcessSpeedSettings(); - // set states - newTrain.MovementState = AITrain.AI_MOVEMENT_STATE.AI_STATIC; // start of as AI static - newTrain.StartTime = null; // time will be set later + // Set states + newTrain.MovementState = AITrain.AI_MOVEMENT_STATE.AI_STATIC; // Start of as AI static + newTrain.StartTime = null; // Time will be set later - // set delay - float randDelay = (float)Simulator.Random.Next((DelayedStartSettings.detachRestart.randomPartS * 10)); + // Set delay + float randDelay = Simulator.Random.Next(DelayedStartSettings.detachRestart.randomPartS * 10); RestdelayS = DelayedStartSettings.detachRestart.fixedPartS + (randDelay / 10f); DelayedStart = true; DelayedStartState = AI_START_MOVEMENT.NEW; @@ -12181,10 +11834,10 @@ public int TTUncoupleBehind(TTTrain newTrain, bool reverseTrain, int leadLocomot newTrain.AI.TrainsToAdd.Add(newTrain); } - // signal event + // Signal event detachCar.SignalEvent(Event.Uncouple); - // update positions train + // Update positions train TrackNode tn = FrontTDBTraveller.TN; float offset = FrontTDBTraveller.TrackNodeOffset; int direction = (int)FrontTDBTraveller.Direction; @@ -12205,17 +11858,17 @@ public int TTUncoupleBehind(TTTrain newTrain, bool reverseTrain, int leadLocomot PresentPosition[1].SetTCPosition(tn.TCCrossReference, offset, direction); PresentPosition[1].RouteListIndex = ValidRoute[0].GetRouteIndex(PresentPosition[1].TCSectionIndex, 0); - // get new track sections occupied + // Get new track sections occupied Train.TCSubpathRoute tempRouteTrain = Simulator.Signals.BuildTempRoute(this, PresentPosition[1].TCSectionIndex, PresentPosition[1].TCOffset, PresentPosition[1].TCDirection, Length, false, true, false); - // if detached from front, clear train from track and all further sections - // set train occupied for new sections + // If detached from front, clear train from track and all further sections + // Set train occupied for new sections if (DetachPosition) { RemoveFromTrack(); - // first reserve all sections to ensure switched are alligned, next set occupied + // First reserve all sections to ensure switched are alligned, next set occupied for (int iIndex = 0; iIndex < tempRouteTrain.Count; iIndex++) { TrackCircuitSection thisSection = Simulator.Signals.TrackCircuitList[tempRouteTrain[iIndex].TCSectionIndex]; @@ -12227,17 +11880,17 @@ public int TTUncoupleBehind(TTTrain newTrain, bool reverseTrain, int leadLocomot thisSection.SetOccupied(routedForward); } - if (ControlMode == TRAIN_CONTROL.AUTO_SIGNAL) ControlMode = TRAIN_CONTROL.AUTO_NODE; // set to node control as detached portion is in front - NextSignalObject[0] = null; // reset signal object (signal is not directly in front) + if (ControlMode == TRAIN_CONTROL.AUTO_SIGNAL) ControlMode = TRAIN_CONTROL.AUTO_NODE; // Set to node control as detached portion is in front + NextSignalObject[0] = null; // Reset signal object (signal is not directly in front) } - // remove train from track which it no longer occupies and clear actions for those sections + // Remove train from track which it no longer occupies and clear actions for those sections else { RemoveFromTrackNotOccupied(tempRouteTrain); } - // update positions new train + // Update positions new train tn = newTrain.FrontTDBTraveller.TN; offset = newTrain.FrontTDBTraveller.TrackNodeOffset; direction = (int)newTrain.FrontTDBTraveller.Direction; @@ -12256,7 +11909,7 @@ public int TTUncoupleBehind(TTTrain newTrain, bool reverseTrain, int leadLocomot newTrain.PresentPosition[1].RouteListIndex = newTrain.ValidRoute[0].GetRouteIndex(newTrain.PresentPosition[1].TCSectionIndex, 0); newTrain.PresentPosition[1].CopyTo(ref newTrain.PreviousPosition[1]); - // check if train is on valid path + // Check if train is on valid path if (newTrain.PresentPosition[0].RouteListIndex < 0 && newTrain.PresentPosition[1].RouteListIndex < 0) { Trace.TraceInformation("Train : {0} ({1}) : detached from {2} ({3}) : is not on valid path\n", newTrain.Name, newTrain.Number, Name, Number); @@ -12265,15 +11918,15 @@ public int TTUncoupleBehind(TTTrain newTrain, bool reverseTrain, int leadLocomot } else { - // ensure new trains route extends fully underneath train + // Ensure new trains route extends fully underneath train AdjustTrainRouteOnStart(newTrain.PresentPosition[0].RouteListIndex, newTrain.PresentPosition[1].RouteListIndex, this); } - // build temp route for new train + // Build temp route for new train Train.TCSubpathRoute tempRouteNewTrain = Simulator.Signals.BuildTempRoute(newTrain, newTrain.PresentPosition[1].TCSectionIndex, newTrain.PresentPosition[1].TCOffset, newTrain.PresentPosition[1].TCDirection, newTrain.Length, false, true, false); - // if train has no valid route, create from occupied sections + // If train has no valid route, create from occupied sections if (newTrain.ValidRoute[0] == null) { newTrain.ValidRoute[0] = new Train.TCSubpathRoute(tempRouteNewTrain); @@ -12284,34 +11937,34 @@ public int TTUncoupleBehind(TTTrain newTrain, bool reverseTrain, int leadLocomot newTrain.PresentPosition[1].CopyTo(ref newTrain.PreviousPosition[1]); } - // set track section reserved - first reserve to ensure correct alignment of switches + // Set track section reserved - first reserve to ensure correct alignment of switches for (int iIndex = 0; iIndex < tempRouteNewTrain.Count; iIndex++) { TrackCircuitSection thisSection = Simulator.Signals.TrackCircuitList[tempRouteNewTrain[iIndex].TCSectionIndex]; thisSection.Reserve(newTrain.routedForward, tempRouteNewTrain); } - // set track section occupied + // Set track section occupied for (int iIndex = 0; iIndex < tempRouteNewTrain.Count; iIndex++) { TrackCircuitSection thisSection = Simulator.Signals.TrackCircuitList[tempRouteNewTrain[iIndex].TCSectionIndex]; thisSection.SetOccupied(newTrain.routedForward); } - // update station stop offsets for continuing train + // Update station stop offsets for continuing train RecalculateStationStops(); - // if normal stop, set restart delay + // If normal stop, set restart delay if (MovementState == AI_MOVEMENT_STATE.STOPPED) { - randDelay = (float)Simulator.Random.Next((DelayedStartSettings.detachRestart.randomPartS * 10)); + randDelay = Simulator.Random.Next(DelayedStartSettings.detachRestart.randomPartS * 10); RestdelayS = DelayedStartSettings.detachRestart.fixedPartS + (randDelay / 10f); DelayedStart = true; DelayedStartState = AI_START_MOVEMENT.PATH_ACTION; } - // return new lead locomotive position - return (newLeadLocomotiveIndex); + // Return new lead locomotive position + return newLeadLocomotiveIndex; } //================================================================================================// @@ -12373,7 +12026,7 @@ public int AdjustTrainRouteOnStart(int trainRearPositionIndex, int trainFrontPos TrackCircuitSection[] occupiedSections = new TrackCircuitSection[OccupiedTrack.Count]; OccupiedTrack.CopyTo(occupiedSections); - // check if train is occupying end of route (happens when attaching) or front of route (happens when forming) + // Check if train is occupying end of route (happens when attaching) or front of route (happens when forming) bool addFront = false; int firstSectionIndex = ValidRoute[0][0].TCSectionIndex; @@ -12386,10 +12039,10 @@ public int AdjustTrainRouteOnStart(int trainRearPositionIndex, int trainFrontPos } } - // if start position not on route, add sections to route to cover + // If start position not on route, add sections to route to cover if (trainRearPositionIndex < 0) { - // add to front + // Add to front if (addFront) { //ensure first section in route is occupied, otherwise do not add sections @@ -12398,10 +12051,10 @@ public int AdjustTrainRouteOnStart(int trainRearPositionIndex, int trainFrontPos for (int iSection = occupiedSections.Length - 1; iSection >= 0 && !firstoccupied; iSection--) { TrackCircuitSection thisSection = occupiedSections[iSection]; - firstoccupied = (thisSection.Index == firstIndex); + firstoccupied = thisSection.Index == firstIndex; } - // create route for occupied sections if position is available + // Create route for occupied sections if position is available TCSubpathRoute tempRoute = null; if (PresentPosition[1].TCSectionIndex >= 0) @@ -12410,7 +12063,7 @@ public int AdjustTrainRouteOnStart(int trainRearPositionIndex, int trainFrontPos PresentPosition[1].TCDirection, Length, true, true, false); } - // add if first section is occupied + // Add if first section is occupied for (int iSection = occupiedSections.Length - 1; iSection >= 0 && firstoccupied; iSection--) { TrackCircuitSection thisSection = occupiedSections[iSection]; @@ -12420,13 +12073,13 @@ public int AdjustTrainRouteOnStart(int trainRearPositionIndex, int trainFrontPos { TCRouteElement newElement = null; - // try to use element from old route + // Try to use element from old route int otherTrainRouteIndex = oldTrain.ValidRoute[0].GetRouteIndex(thisSection.Index, 0); if (otherTrainRouteIndex >= 0) { newElement = new TCRouteElement(oldTrain.ValidRoute[0][otherTrainRouteIndex]); } - // if failed and temp route available, try to use from temp route + // If failed and temp route available, try to use from temp route else if (tempRoute != null) { otherTrainRouteIndex = tempRoute.GetRouteIndex(thisSection.Index, 0); @@ -12448,7 +12101,7 @@ public int AdjustTrainRouteOnStart(int trainRearPositionIndex, int trainFrontPos } } } - // add to rear + // Add to rear else { //ensure last section in route is occupied, otherwise do not add sections @@ -12457,10 +12110,10 @@ public int AdjustTrainRouteOnStart(int trainRearPositionIndex, int trainFrontPos for (int iSection = occupiedSections.Length - 1; iSection >= 0 && !lastoccupied; iSection--) { TrackCircuitSection thisSection = occupiedSections[iSection]; - lastoccupied = (thisSection.Index == lastIndex); + lastoccupied = thisSection.Index == lastIndex; } - // create route for occupied sections if position is available + // Create route for occupied sections if position is available TCSubpathRoute tempRoute = null; if (PresentPosition[1].TCSectionIndex >= 0) { @@ -12468,7 +12121,7 @@ public int AdjustTrainRouteOnStart(int trainRearPositionIndex, int trainFrontPos PresentPosition[1].TCDirection, Length, true, true, false); } - // add if last section is occupied + // Add if last section is occupied for (int iSection = 0; iSection < occupiedSections.Length && lastoccupied; iSection++) { TrackCircuitSection thisSection = occupiedSections[iSection]; @@ -12477,13 +12130,13 @@ public int AdjustTrainRouteOnStart(int trainRearPositionIndex, int trainFrontPos { TCRouteElement newElement = null; - // first try to add from old route + // First try to add from old route int otherTrainRouteIndex = oldTrain.ValidRoute[0].GetRouteIndex(thisSection.Index, 0); if (otherTrainRouteIndex >= 0) { newElement = new TCRouteElement(oldTrain.ValidRoute[0][otherTrainRouteIndex]); } - // if failed try from temp route if available + // If failed try from temp route if available else if (tempRoute != null) { otherTrainRouteIndex = tempRoute.GetRouteIndex(thisSection.Index, 0); @@ -12508,7 +12161,7 @@ public int AdjustTrainRouteOnStart(int trainRearPositionIndex, int trainFrontPos ValidRoute[0] = new TCSubpathRoute(TCRoute.TCRouteSubpaths[TCRoute.activeSubpath]); - // update section index references in TCroute data + // Update section index references in TCroute data if (TCRoute.ReversalInfo[0].Valid) { TCRoute.ReversalInfo[0].FirstDivergeIndex += addedSections; @@ -12517,7 +12170,7 @@ public int AdjustTrainRouteOnStart(int trainRearPositionIndex, int trainFrontPos TCRoute.ReversalInfo[0].LastSignalIndex += addedSections; } - // update station stop indices + // Update station stop indices if (StationStops != null) { foreach (StationStop thisStation in StationStops) @@ -12530,7 +12183,7 @@ public int AdjustTrainRouteOnStart(int trainRearPositionIndex, int trainFrontPos } } - // if end position not on route, add sections to route to cover + // If end position not on route, add sections to route to cover else if (trainFrontPositionIndex < 0) { if (addFront) @@ -12541,7 +12194,7 @@ public int AdjustTrainRouteOnStart(int trainRearPositionIndex, int trainFrontPos for (int iSection = occupiedSections.Length - 1; iSection >= 0 && !firstoccupied; iSection--) { TrackCircuitSection thisSection = occupiedSections[iSection]; - firstoccupied = (thisSection.Index == firstIndex); + firstoccupied = thisSection.Index == firstIndex; } for (int iSection = occupiedSections.Length - 1; iSection >= 0 && firstoccupied; iSection--) @@ -12565,7 +12218,7 @@ public int AdjustTrainRouteOnStart(int trainRearPositionIndex, int trainFrontPos for (int iSection = occupiedSections.Length - 1; iSection >= 0 && !lastoccupied; iSection--) { TrackCircuitSection thisSection = occupiedSections[iSection]; - lastoccupied = (thisSection.Index == lastIndex); + lastoccupied = thisSection.Index == lastIndex; } for (int iSection = 0; iSection < occupiedSections.Length && lastoccupied; iSection++) @@ -12585,7 +12238,7 @@ public int AdjustTrainRouteOnStart(int trainRearPositionIndex, int trainFrontPos trainFrontPositionIndex = 0; ValidRoute[0] = new TCSubpathRoute(TCRoute.TCRouteSubpaths[TCRoute.activeSubpath]); - // update section index references in TCroute data + // Update section index references in TCroute data if (TCRoute.ReversalInfo[TCRoute.activeSubpath].Valid) { TCRoute.ReversalInfo[TCRoute.activeSubpath].FirstDivergeIndex += addedSections; @@ -12593,7 +12246,7 @@ public int AdjustTrainRouteOnStart(int trainRearPositionIndex, int trainFrontPos TCRoute.ReversalInfo[TCRoute.activeSubpath].LastDivergeIndex += addedSections; TCRoute.ReversalInfo[TCRoute.activeSubpath].LastSignalIndex += addedSections; } - // update station stop indices + // Update station stop indices if (StationStops != null) { foreach (StationStop thisStation in StationStops) @@ -12605,7 +12258,7 @@ public int AdjustTrainRouteOnStart(int trainRearPositionIndex, int trainFrontPos } } } - return (addedSections); + return addedSections; } //================================================================================================// @@ -12636,7 +12289,7 @@ public int CreateStaticTrainRef(TTTrain train, ref List trainlist, stri trainlist.Add(formedTrain); - return (formedTrain.Number); + return formedTrain.Number; } //================================================================================================// @@ -12668,26 +12321,21 @@ public int CreateStaticTrain(TTTrain train, ref List trainList, string } formedTrain.AITrainDirectionForward = true; - if (String.IsNullOrEmpty(reqName)) - { - formedTrain.Name = String.Concat("D_", train.Number.ToString("0000"), "_", formedTrain.Number.ToString("00")); - } - else - { - formedTrain.Name = String.Copy(reqName); - } + formedTrain.Name = String.IsNullOrEmpty(reqName) + ? String.Concat("D_", train.Number.ToString("0000"), "_", formedTrain.Number.ToString("00")) + : String.Copy(reqName); formedTrain.FormedOf = train.Number; formedTrain.FormedOfType = TTTrain.FormCommand.Detached; formedTrain.TrainType = Train.TRAINTYPE.AI_AUTOGENERATE; formedTrain.MovementState = AITrain.AI_MOVEMENT_STATE.AI_STATIC; - // set starttime to 1 sec, and set activate time to null (train is never activated) + // Set starttime to 1 sec, and set activate time to null (train is never activated) formedTrain.StartTime = 1; formedTrain.ActivateTime = null; formedTrain.AI = train.AI; trainList.Add(formedTrain); - return(formedTrain.Number); + return formedTrain.Number; } //================================================================================================// @@ -12695,12 +12343,11 @@ public int CreateStaticTrain(TTTrain train, ref List trainList, string /// Get other train from number /// Use Simulator.Trains to get other train /// - public TTTrain GetOtherTTTrainByNumber(int reqNumber) { TTTrain returnTrain = Simulator.Trains.GetTrainByNumber(reqNumber) as TTTrain; - // if not found, try if player train has required number as original number + // If not found, try if player train has required number as original number if (returnTrain == null) { TTTrain playerTrain = Simulator.Trains.GetTrainByNumber(0) as TTTrain; @@ -12710,7 +12357,7 @@ public TTTrain GetOtherTTTrainByNumber(int reqNumber) } } - return (returnTrain); + return returnTrain; } //================================================================================================// @@ -12718,10 +12365,9 @@ public TTTrain GetOtherTTTrainByNumber(int reqNumber) /// Get other train from name /// Use Simulator.Trains to get other train /// - public TTTrain GetOtherTTTrainByName(string reqName) { - return (Simulator.Trains.GetTrainByName(reqName) as TTTrain); + return Simulator.Trains.GetTrainByName(reqName) as TTTrain; } //================================================================================================// @@ -12729,21 +12375,21 @@ public TTTrain GetOtherTTTrainByName(string reqName) /// Check if other train is yet to be started /// Use Simulator.Trains to get other train /// - public bool CheckTTTrainNotStartedByNumber(int reqNumber) { bool notStarted = false; - // check if on startlist + + // Check if on startlist if (Simulator.Trains.CheckTrainNotStartedByNumber(reqNumber)) { notStarted = true; } - // check if on autogen list + // Check if on autogen list else if (Simulator.AutoGenDictionary.ContainsKey(reqNumber)) { notStarted = true; } - // check if in process of being started + // Check if in process of being started else foreach (TTTrain thisTrain in AI.TrainsToAdd) { if (thisTrain.Number == reqNumber) @@ -12753,14 +12399,13 @@ public bool CheckTTTrainNotStartedByNumber(int reqNumber) } } - return (notStarted); + return notStarted; } //================================================================================================// /// - /// TTAnalys methods : dump methods for Timetable Analysis + /// TTAnalys methods: dump methods for Timetable Analysis /// - public void TTAnalysisUpdateStationState1(int presentTime, StationStop thisStation) { @@ -12828,7 +12473,7 @@ public void TTAnalysisUpdateStationState2() DateTime baseDT = new DateTime(); DateTime stopTime = baseDT.AddSeconds(AI.clockTime); - // output string only if different from last output + // Output string only if different from last output if (waitforstring.ToString() != ttanalysisreport) { @@ -13013,40 +12658,40 @@ public enum CheckPathDirection } // General info - public WaitInfoType WaitType; // type of wait instruction - public bool WaitActive; // wait state is active + public WaitInfoType WaitType; // Type of wait instruction + public bool WaitActive; // Wait state is active - // preprocessed info - info is removed after processing - public int startSectionIndex; // section from which command is valid (-1 if valid from start) - public int startSubrouteIndex; // subpath index from which command is valid - public string referencedTrainName; // referenced train name (for Wait, Follow or Connect) + // Preprocessed info - info is removed after processing + public int startSectionIndex; // Section from which command is valid (-1 if valid from start) + public int startSubrouteIndex; // Subpath index from which command is valid + public string referencedTrainName; // Referenced train name (for Wait, Follow or Connect) - // processed info - public int activeSectionIndex; // index of TrackCircuitSection where wait must be activated - public int activeSubrouteIndex; // subpath in which this wait is valid - public int activeRouteIndex; // index of section in active subpath + // Processed info + public int activeSectionIndex; // Index of TrackCircuitSection where wait must be activated + public int activeSubrouteIndex; // Subpath in which this wait is valid + public int activeRouteIndex; // Index of section in active subpath - // common for Wait, Follow and Connect - public int waitTrainNumber; // number of train for which to wait - public int? maxDelayS = null; // max. delay for waiting (in seconds) - public int? ownDelayS = null; // min. own delay for waiting to be active (in seconds) - public bool? notStarted = null; // also wait if not yet started - public bool? atStart = null; // wait at start of wait section, otherwise wait at first not-common section - public int? waittrigger = null; // time at which wait is triggered - public int? waitendtrigger = null; // time at which wait is cancelled + // Common for Wait, Follow and Connect + public int waitTrainNumber; // Number of train for which to wait + public int? maxDelayS = null; // Max. delay for waiting (in seconds) + public int? ownDelayS = null; // Min. own delay for waiting to be active (in seconds) + public bool? notStarted = null; // Also wait if not yet started + public bool? atStart = null; // Wait at start of wait section, otherwise wait at first not-common section + public int? waittrigger = null; // Time at which wait is triggered + public int? waitendtrigger = null; // Time at which wait is cancelled - // wait types Wait and Follow : - public int waitTrainSubpathIndex; // subpath index for train - set to -1 if wait is always active - public int waitTrainRouteIndex; // index of section in active subpath + // Wait types Wait and Follow : + public int waitTrainSubpathIndex; // Subpath index for train - set to -1 if wait is always active + public int waitTrainRouteIndex; // Index of section in active subpath - // wait types Connect : - public int stationIndex; // index in this train station stop list - public int? holdTimeS; // required hold time (in seconds) + // Wait types Connect : + public int stationIndex; // Index in this train station stop list + public int? holdTimeS; // Required hold time (in seconds) - // wait types WaitInfo (no post-processing required) : - public Train.TCSubpathRoute CheckPath = null; // required path to check in case of WaitAny + // Wait types WaitInfo (no post-processing required) : + public Train.TCSubpathRoute CheckPath = null; // Required path to check in case of WaitAny - public CheckPathDirection PathDirection = CheckPathDirection.Same; // required path direction + public CheckPathDirection PathDirection = CheckPathDirection.Same; // Required path direction //================================================================================================// /// @@ -13072,78 +12717,29 @@ public WaitInfo(BinaryReader inf) waitTrainNumber = inf.ReadInt32(); int mdelayValue = inf.ReadInt32(); - if (mdelayValue < 0) - { - maxDelayS = null; - } - else - { - maxDelayS = mdelayValue; - } + maxDelayS = mdelayValue < 0 ? null : (int?)mdelayValue; int odelayValue = inf.ReadInt32(); - if (odelayValue < 0) - { - ownDelayS = null; - } - else - { - ownDelayS = odelayValue; - } + ownDelayS = odelayValue < 0 ? null : (int?)odelayValue; int notStartedValue = inf.ReadInt32(); - if (notStartedValue > 0) - { - notStarted = inf.ReadBoolean(); - } - else - { - notStarted = null; - } + notStarted = notStartedValue > 0 ? inf.ReadBoolean() : (bool?)null; int atStartValue = inf.ReadInt32(); - if (atStartValue > 0) - { - atStart = inf.ReadBoolean(); - } - else - { - atStart = null; - } + atStart = atStartValue > 0 ? inf.ReadBoolean() : (bool?)null; int triggervalue = inf.ReadInt32(); - if (triggervalue > 0) - { - waittrigger = triggervalue; - } - else - { - waittrigger = null; - } + waittrigger = triggervalue > 0 ? triggervalue : (int?)null; int endtriggervalue = inf.ReadInt32(); - if (endtriggervalue > 0) - { - waitendtrigger = endtriggervalue; - } - else - { - waitendtrigger = null; - } + waitendtrigger = endtriggervalue > 0 ? endtriggervalue : (int?)null; waitTrainSubpathIndex = inf.ReadInt32(); waitTrainRouteIndex = inf.ReadInt32(); stationIndex = inf.ReadInt32(); int holdTimevalue = inf.ReadInt32(); - if (holdTimevalue < 0) - { - holdTimeS = null; - } - else - { - holdTimeS = holdTimevalue; - } + holdTimeS = holdTimevalue < 0 ? null : (int?)holdTimevalue; int validCheckPath = inf.ReadInt32(); @@ -13261,26 +12857,21 @@ public void Save(BinaryWriter outf) // // Compare To (to allow sort) // - public int CompareTo(WaitInfo otherItem) { - // all connects are moved to the end of the queue + // All connects are moved to the end of the queue if (this.WaitType == WaitInfoType.Connect) { - if (otherItem.WaitType != WaitInfoType.Connect) - return (1); - return (0); + return otherItem.WaitType != WaitInfoType.Connect ? 1 : 0; } if (otherItem.WaitType == WaitInfoType.Connect) - return (-1); + return -1; if (this.activeSubrouteIndex < otherItem.activeSubrouteIndex) - return (-1); - if (this.activeSubrouteIndex == otherItem.activeSubrouteIndex && this.activeRouteIndex < otherItem.activeRouteIndex) - return (-1); - if (this.activeSubrouteIndex == otherItem.activeSubrouteIndex && this.activeRouteIndex == otherItem.activeRouteIndex) - return (0); - return (1); + return -1; + return this.activeSubrouteIndex == otherItem.activeSubrouteIndex && this.activeRouteIndex < otherItem.activeRouteIndex + ? -1 + : this.activeSubrouteIndex == otherItem.activeSubrouteIndex && this.activeRouteIndex == otherItem.activeRouteIndex ? 0 : 1; } //================================================================================================// @@ -13290,7 +12881,7 @@ public int CompareTo(WaitInfo otherItem) /// public WaitInfo CreateCopy() { - return ((WaitInfo)this.MemberwiseClone()); + return (WaitInfo)this.MemberwiseClone(); } } @@ -13328,9 +12919,9 @@ public enum DetachUnitsInfo public DetachUnitsInfo DetachUnits; public List DetachConsists; public int NumberOfUnits; - public int DetachFormedTrain; // used for auto formed detaches - public String DetachFormedTrainName = String.Empty; // used for station and startup detaches - public bool DetachFormedStatic; // used for station and startup detaches + public int DetachFormedTrain; // Used for auto formed detaches + public String DetachFormedTrainName = String.Empty; // Used for station and startup detaches + public bool DetachFormedStatic; // Used for station and startup detaches public bool? ReverseDetachedTrain; public bool PlayerAutoDetach; public int? DetachTime; @@ -13347,7 +12938,7 @@ public enum DetachUnitsInfo /// /// /// - public DetachInfo(bool atStart, bool atEnd, bool atStation, int sectionIndex, bool leadingPower, bool allLeadingPower, bool trailingPower, bool allTrailingPower, + public DetachInfo(bool atStart, bool atEnd, bool atStation, int sectionIndex, bool leadingPower, bool allLeadingPower, bool trailingPower, bool allTrailingPower, bool onlyPower, bool nonPower, int units, int? time, int formedTrain, bool reverseTrain) { if (atStart) @@ -13446,7 +13037,7 @@ public DetachInfo(TTTrain thisTrain, TTTrainCommands commandInfo, bool atActivat { switch (Qualifier.QualifierName.Trim().ToLower()) { - // detach info qualifiers + // Detach info qualifiers case "power": DetachUnits = DetachUnitsInfo.onlyPower; portionDefined = true; @@ -13493,14 +13084,7 @@ public DetachInfo(TTTrain thisTrain, TTTrainCommands commandInfo, bool atActivat if (unitvalid) { - if (nounits > 0) - { - DetachUnits = DetachUnitsInfo.unitsAtFront; - } - else - { - DetachUnits = DetachUnitsInfo.unitsAtEnd; - } + DetachUnits = nounits > 0 ? DetachUnitsInfo.unitsAtFront : DetachUnitsInfo.unitsAtEnd; NumberOfUnits = Math.Abs(nounits); portionDefined = true; } @@ -13518,7 +13102,7 @@ public DetachInfo(TTTrain thisTrain, TTTrainCommands commandInfo, bool atActivat portionDefined = true; break; - // form qualifier + // Form qualifier case "forms": if (Qualifier.QualifierValues == null || Qualifier.QualifierValues.Count <= 0) { @@ -13538,7 +13122,7 @@ public DetachInfo(TTTrain thisTrain, TTTrainCommands commandInfo, bool atActivat } break; - // static qualifier + // Static qualifier case "static": if (Qualifier.QualifierValues != null && Qualifier.QualifierValues.Count > 0) { @@ -13554,7 +13138,7 @@ public DetachInfo(TTTrain thisTrain, TTTrainCommands commandInfo, bool atActivat formedTrainDefined = true; break; - // manual or auto detach for player train (note : not yet implemented) + // Manual or auto detach for player train (note : not yet implemented) case "manual": PlayerAutoDetach = false; break; @@ -13563,14 +13147,14 @@ public DetachInfo(TTTrain thisTrain, TTTrainCommands commandInfo, bool atActivat PlayerAutoDetach = true; break; - // default : invalid qualifier + // Default : invalid qualifier default: Trace.TraceWarning("Train {0} : invalid qualifier for detach command : {1}", thisTrain.Name, Qualifier.QualifierName.Trim()); break; } } - // set detach time to arrival time or activate time + // Set detach time to arrival time or activate time DetachTime = detachTime.HasValue ? detachTime.Value : 0; if (!portionDefined) @@ -13601,14 +13185,7 @@ public DetachInfo(BinaryReader inf) DetachUnits = (DetachUnitsInfo)inf.ReadInt32(); NumberOfUnits = inf.ReadInt32(); int detachTimeValue = inf.ReadInt32(); - if (detachTimeValue < 0) - { - DetachTime = null; - } - else - { - DetachTime = detachTimeValue; - } + DetachTime = detachTimeValue < 0 ? null : (int?)detachTimeValue; DetachFormedTrain = inf.ReadInt32(); DetachFormedTrainName = inf.ReadString(); @@ -13696,18 +13273,13 @@ public bool PerformDetach(TTTrain train, bool allowPlayerSelect) int iunits = 0; bool frontpos = true; - // if position of power not defined, set position according to present position of power + // If position of power not defined, set position according to present position of power if (DetachUnits == DetachUnitsInfo.onlyPower) { DetachUnits = DetachUnitsInfo.allLeadingPower; - if (train.Cars[0].WagonType == TrainCar.WagonTypes.Engine || train.Cars[0].WagonType == TrainCar.WagonTypes.Tender) - { - DetachUnits = DetachUnitsInfo.allLeadingPower; - } - else - { - DetachUnits = DetachUnitsInfo.allTrailingPower; - } + DetachUnits = train.Cars[0].WagonType == TrainCar.WagonTypes.Engine || train.Cars[0].WagonType == TrainCar.WagonTypes.Tender + ? DetachUnitsInfo.allLeadingPower + : DetachUnitsInfo.allTrailingPower; } iunits = train.GetUnitsToDetach(this.DetachUnits, this.NumberOfUnits, this.DetachConsists, ref frontpos); @@ -13717,18 +13289,10 @@ public bool PerformDetach(TTTrain train, bool allowPlayerSelect) File.AppendAllText(@"C:\temp\checktrain.txt", "Detaching from : " + train.Number + " ; units : " + iunits + " ; from front position : " + frontpos.ToString() + "\n"); } - // check if anything to detach and anything left on train - - TTTrain newTrain = null; - if (DetachFormedTrain == 0) - { - newTrain = train.Simulator.PlayerLocomotive.Train as TTTrain; - } - else - { - newTrain = train.AI.Simulator.GetAutoGenTTTrainByNumber(DetachFormedTrain); - } - + // Check if anything to detach and anything left on train + var newTrain = DetachFormedTrain == 0 + ? train.Simulator.PlayerLocomotive.Train as TTTrain + : train.AI.Simulator.GetAutoGenTTTrainByNumber(DetachFormedTrain); if (newTrain == null) { Trace.TraceInformation("Train {0} : detach to train {1} : cannot find new train \n", train.Name, DetachFormedTrainName); @@ -13757,10 +13321,10 @@ public bool PerformDetach(TTTrain train, bool allowPlayerSelect) { if (newTrain == null) { - // create dummy train - train will be removed but timetable can continue + // Create dummy train - train will be removed but timetable can continue newTrain = new TTTrain(train.AI.Simulator, train); - newTrain.AI = train.AI; // set AT as Simulator.AI does not exist in prerun mode - newTrain.ValidRoute[0] = train.signalRef.BuildTempRoute(newTrain, train.PresentPosition[0].TCSectionIndex, + newTrain.AI = train.AI; // Set AT as Simulator.AI does not exist in prerun mode + newTrain.ValidRoute[0] = train.signalRef.BuildTempRoute(newTrain, train.PresentPosition[0].TCSectionIndex, train.PresentPosition[0].TCOffset, train.PresentPosition[0].TCDirection, train.Length, true, true, false); train.PresentPosition[0].CopyTo(ref newTrain.PresentPosition[0]); train.PresentPosition[1].CopyTo(ref newTrain.PresentPosition[1]); @@ -13771,7 +13335,7 @@ public bool PerformDetach(TTTrain train, bool allowPlayerSelect) } else { - // if new train has no route, create from present position + // If new train has no route, create from present position if (newTrain.TCRoute == null) { Train.TCSubpathRoute newTrainPath = new Train.TCSubpathRoute(train.ValidRoute[0], train.PresentPosition[1].RouteListIndex, train.PresentPosition[0].RouteListIndex); @@ -13779,31 +13343,30 @@ public bool PerformDetach(TTTrain train, bool allowPlayerSelect) newTrain.ValidRoute[0] = new Train.TCSubpathRoute(newTrain.TCRoute.TCRouteSubpaths[0]); } - // handle player train + // Handle player train if (train.TrainType == Train.TRAINTYPE.PLAYER) { bool detachablePower = CheckDetachedDriveablePower(train); bool keepPower = CheckKeepDriveablePower(train); - // if both portions contain detachable power, display window - // quit method as detaching is handled through window button activation + // If both portions contain detachable power, display window + // Quit method as detaching is handled through window button activation if (detachablePower && keepPower && allowPlayerSelect) { - // reinsert newtrain as autogen train otherwise it cannot be found + // Reinsert newtrain as autogen train otherwise it cannot be found train.AI.AutoGenTrains.Add(newTrain); train.Simulator.AutoGenDictionary.Add(newTrain.Number, newTrain); - // show window, set detach action is pending + // Show window, set detach action is pending train.Simulator.OnRequestTTDetachWindow(); train.DetachPending = true; - return (false); + return false; } - // detachable portion has no power, so detach immediately - + // Detachable portion has no power, so detach immediately bool playerEngineInRemainingPortion = CheckPlayerPowerPortion(train); - // player engine is in remaining portion + // Player engine is in remaining portion if (playerEngineInRemainingPortion) { if (!ReverseDetachedTrain.HasValue) @@ -13815,13 +13378,13 @@ public bool PerformDetach(TTTrain train, bool allowPlayerSelect) train.Simulator.Confirmer.Information(train.DetachUnits.ToString() + " units detached as train : " + newTrain.Name); train.DetachActive[1] = -1; - // set proper details for new train + // Set proper details for new train newTrain.SetFormedOccupied(); newTrain.ControlMode = Train.TRAIN_CONTROL.INACTIVE; newTrain.MovementState = AITrain.AI_MOVEMENT_STATE.AI_STATIC; newTrain.SetupStationStopHandling(); } - // keep portion has no power, so detach immediately and switch to new train + // Keep portion has no power, so detach immediately and switch to new train else { if (!ReverseDetachedTrain.HasValue) @@ -13833,7 +13396,7 @@ public bool PerformDetach(TTTrain train, bool allowPlayerSelect) Trace.TraceInformation("Detach : " + train.DetachUnits.ToString() + " units detached as train : " + newTrain.Name + "\n"); train.DetachActive[1] = -1; - // set proper details for existing train + // Set proper details for existing train train.Number = train.OrgAINumber; train.TrainType = Train.TRAINTYPE.AI; train.LeadLocomotiveIndex = -1; @@ -13841,10 +13404,10 @@ public bool PerformDetach(TTTrain train, bool allowPlayerSelect) train.AI.TrainsToRemoveFromAI.Add(train); train.AI.TrainsToAdd.Add(train); - // set proper details for new train + // Set proper details for new train newTrain.AI.TrainsToRemoveFromAI.Add(newTrain); - // set proper details for new formed train + // Set proper details for new formed train newTrain.OrgAINumber = newTrain.Number; newTrain.Number = 0; newTrain.LeadLocomotiveIndex = newLocoIndex; @@ -13857,24 +13420,23 @@ public bool PerformDetach(TTTrain train, bool allowPlayerSelect) newTrain.ControlMode = Train.TRAIN_CONTROL.INACTIVE; newTrain.MovementState = AITrain.AI_MOVEMENT_STATE.AI_STATIC; - // inform viewer about player train switch + // Inform viewer about player train switch train.Simulator.OnPlayerTrainChanged(train, newTrain); train.Simulator.PlayerLocomotive.Train = newTrain; newTrain.SetupStationStopHandling(); - // clear replay commands + // Clear replay commands train.Simulator.Log.CommandList.Clear(); - // display messages - if (train.Simulator.Confirmer != null) // As Confirmer may not be created until after a restore. - train.Simulator.Confirmer.Information("Player switched to train : " + newTrain.Name); + // Display messages + train.Simulator.Confirmer?.Information("Player switched to train : " + newTrain.Name); } } else { - // handle AI train + // Handle AI train if (train.AI.Simulator.AutoGenDictionary != null && train.AI.Simulator.AutoGenDictionary.ContainsKey(newTrain.Number)) train.AI.Simulator.AutoGenDictionary.Remove(newTrain.Number); @@ -13896,7 +13458,7 @@ public bool PerformDetach(TTTrain train, bool allowPlayerSelect) } - // if train is player or intended player, determine new loco lead index + // If train is player or intended player, determine new loco lead index if (train.TrainType == Train.TRAINTYPE.PLAYER || train.TrainType == Train.TRAINTYPE.INTENDED_PLAYER) { if (train.LeadLocomotiveIndex >= 0) @@ -13951,7 +13513,7 @@ public bool PerformDetach(TTTrain train, bool allowPlayerSelect) } } - return(true); + return true; } //================================================================================================// @@ -13964,22 +13526,16 @@ public bool PerformDetach(TTTrain train, bool allowPlayerSelect) public void DetachPlayerTrain(TTTrain train, int newTrainNumber) { // Determine no. of units to detach - int iunits = 0; bool frontpos = true; - // if position of power not defined, set position according to present position of power + // If position of power not defined, set position according to present position of power if (DetachUnits == DetachUnitsInfo.onlyPower) { DetachUnits = DetachUnitsInfo.allLeadingPower; - if (train.Cars[0].WagonType == TrainCar.WagonTypes.Engine || train.Cars[0].WagonType == TrainCar.WagonTypes.Tender) - { - DetachUnits = DetachUnitsInfo.allLeadingPower; - } - else - { - DetachUnits = DetachUnitsInfo.allTrailingPower; - } + DetachUnits = train.Cars[0].WagonType == TrainCar.WagonTypes.Engine || train.Cars[0].WagonType == TrainCar.WagonTypes.Tender + ? DetachUnitsInfo.allLeadingPower + : DetachUnitsInfo.allTrailingPower; } iunits = train.GetUnitsToDetach(this.DetachUnits, this.NumberOfUnits, this.DetachConsists, ref frontpos); @@ -13989,16 +13545,11 @@ public void DetachPlayerTrain(TTTrain train, int newTrainNumber) File.AppendAllText(@"C:\temp\checktrain.txt", "Detaching from : " + train.Number + " ; units : " + iunits + " ; from front position : " + frontpos.ToString() + "\n"); } - // check if anything to detach and anything left on train - + // Check if anything to detach and anything left on train train.DetachUnits = iunits; train.DetachPosition = frontpos; - TTTrain newTrain = train.AI.Simulator.GetAutoGenTTTrainByNumber(newTrainNumber); - if (newTrain == null) - { - newTrain = train.AI.StartList.GetNotStartedTTTrainByNumber(newTrainNumber, true); - } + TTTrain newTrain = train.AI.Simulator.GetAutoGenTTTrainByNumber(newTrainNumber) ?? train.AI.StartList.GetNotStartedTTTrainByNumber(newTrainNumber, true); bool playerEngineInRemainingPortion = CheckPlayerPowerPortion(train); ReverseDetachedTrain = GetDetachReversalInfo(train, newTrain); @@ -14008,16 +13559,16 @@ public void DetachPlayerTrain(TTTrain train, int newTrainNumber) Trace.TraceInformation(train.DetachUnits.ToString() + " units detached as train : " + newTrain.Name); train.DetachActive[1] = -1; - // player engine is in remaining portion + // Player engine is in remaining portion if (playerEngineInRemainingPortion) { train.LeadLocomotiveIndex = newLocoIndex; } - // player engine is in detached portion, so switch trains + // Player engine is in detached portion, so switch trains else { - // set proper details for existing train + // Set proper details for existing train train.Number = train.OrgAINumber; train.TrainType = Train.TRAINTYPE.AI; train.MovementState = train.AtStation ? AITrain.AI_MOVEMENT_STATE.STATION_STOP : AITrain.AI_MOVEMENT_STATE.STOPPED; @@ -14027,7 +13578,7 @@ public void DetachPlayerTrain(TTTrain train, int newTrainNumber) train.AI.TrainsToAdd.Add(train); train.MUDirection = Direction.Forward; - // set proper details for new formed train + // Set proper details for new formed train newTrain.AI.TrainsToRemoveFromAI.Add(newTrain); newTrain.OrgAINumber = newTrain.Number; @@ -14042,22 +13593,21 @@ public void DetachPlayerTrain(TTTrain train, int newTrainNumber) newTrain.SetFormedOccupied(); - // inform viewer about player train switch + // Inform viewer about player train switch train.Simulator.OnPlayerTrainChanged(train, newTrain); train.Simulator.PlayerLocomotive.Train = newTrain; newTrain.SetupStationStopHandling(); - // clear replay commands + // Clear replay commands train.Simulator.Log.CommandList.Clear(); - // display messages - if (train.Simulator.Confirmer != null) // As Confirmer may not be created until after a restore. - train.Simulator.Confirmer.Information("Player switched to train : " + newTrain.Name); + // Display messages + train.Simulator.Confirmer?.Information("Player switched to train : " + newTrain.Name); Trace.TraceInformation("Player switched to train : " + newTrain.Name); } - train.DetachPending = false; // detach completed + train.DetachPending = false; // Detach completed } //================================================================================================// @@ -14092,7 +13642,7 @@ public void SetDetachXRef(TTTrain dettrain, List trainList, TTTrain pla } } - // if not found, try player train + // If not found, try player train if (!trainFound) { if (playerTrain != null && String.Compare(playerTrain.Name, DetachFormedTrainName, true) == 0) @@ -14110,7 +13660,7 @@ public void SetDetachXRef(TTTrain dettrain, List trainList, TTTrain pla } } - // issue warning if train not found + // Issue warning if train not found if (!trainFound) { Trace.TraceWarning("Train : {0} : detach details : detached train {1} not found", @@ -14128,7 +13678,7 @@ public bool CheckDetachedDriveablePower(TTTrain train) { bool portionHasDriveablePower = false; - // detach at front + // Detach at front if (train.DetachPosition) { for (int iCar = 0; iCar < train.DetachUnits && !portionHasDriveablePower; iCar++) @@ -14137,7 +13687,7 @@ public bool CheckDetachedDriveablePower(TTTrain train) if (thisCar.IsDriveable) portionHasDriveablePower = true; } } - // detach at rear + // Detach at rear else { for (int iCar = 0; iCar < train.DetachUnits && !portionHasDriveablePower; iCar++) @@ -14147,7 +13697,7 @@ public bool CheckDetachedDriveablePower(TTTrain train) if (thisCar.IsDriveable) portionHasDriveablePower = true; } } - return (portionHasDriveablePower); + return portionHasDriveablePower; } //================================================================================================// @@ -14160,7 +13710,7 @@ public bool CheckKeepDriveablePower(TTTrain train) { bool portionHasDriveablePower = false; - // detach at front - so check rear portion + // Detach at front - so check rear portion if (train.DetachPosition) { for (int iCar = 0; iCar < (train.Cars.Count - train.DetachUnits) && !portionHasDriveablePower; iCar++) @@ -14170,7 +13720,7 @@ public bool CheckKeepDriveablePower(TTTrain train) if (thisCar.IsDriveable) portionHasDriveablePower = true; } } - // detach at rear - so check front portion + // Detach at rear - so check front portion else { for (int iCar = 0; iCar < (train.Cars.Count - train.DetachUnits) && !portionHasDriveablePower; iCar++) @@ -14179,7 +13729,7 @@ public bool CheckKeepDriveablePower(TTTrain train) if (thisCar.IsDriveable) portionHasDriveablePower = true; } } - return (portionHasDriveablePower); + return portionHasDriveablePower; } //================================================================================================// @@ -14192,7 +13742,7 @@ public bool CheckPlayerPowerPortion(TTTrain train) { bool PlayerInRemainingPortion = false; - // detach at front - so check rear portion + // Detach at front - so check rear portion if (train.DetachPosition) { for (int iCar = 0; iCar < (train.Cars.Count - train.DetachUnits) && !PlayerInRemainingPortion; iCar++) @@ -14204,7 +13754,7 @@ public bool CheckPlayerPowerPortion(TTTrain train) } } } - // detach at rear - so check front portion + // Detach at rear - so check front portion else { for (int iCar = 0; iCar < (train.Cars.Count - train.DetachUnits) && !PlayerInRemainingPortion; iCar++) @@ -14215,7 +13765,7 @@ public bool CheckPlayerPowerPortion(TTTrain train) } } } - return (PlayerInRemainingPortion); + return PlayerInRemainingPortion; } //================================================================================================// @@ -14229,7 +13779,7 @@ public bool GetDetachReversalInfo(TTTrain thisTrain, TTTrain detachedTrain) { bool reversed = false; - // if detached at front, use front position + // If detached at front, use front position if (thisTrain.DetachPosition) { int frontSectionIndex = thisTrain.PresentPosition[0].TCSectionIndex; @@ -14241,7 +13791,7 @@ public bool GetDetachReversalInfo(TTTrain thisTrain, TTTrain detachedTrain) if (otherTrainIndex >= 0) { int otherTrainDirection = otherPath[otherTrainIndex].Direction; - reversed = (thisDirection != otherTrainDirection); + reversed = thisDirection != otherTrainDirection; } } else @@ -14255,11 +13805,11 @@ public bool GetDetachReversalInfo(TTTrain thisTrain, TTTrain detachedTrain) if (otherTrainIndex >= 0) { int otherTrainDirection = otherPath[otherTrainIndex].Direction; - reversed = (thisDirection != otherTrainDirection); + reversed = thisDirection != otherTrainDirection; } } - return (reversed); + return reversed; } } @@ -14270,15 +13820,15 @@ public bool GetDetachReversalInfo(TTTrain thisTrain, TTTrain detachedTrain) /// public class AttachInfo { - public int AttachTrain; // train number to which to attach - public string AttachTrainName = String.Empty; // train name to which to attach + public int AttachTrain; // Train number to which to attach + public string AttachTrainName = String.Empty; // Train name to which to attach - public int StationPlatformReference; // station platform reference - set to -1 if attaching to static train in dispose command - public bool FirstIn; // this train arrives first - public bool SetBack; // reverse in order to attach - public bool Valid; // attach info is valid + public int StationPlatformReference; // Station platform reference - set to -1 if attaching to static train in dispose command + public bool FirstIn; // This train arrives first + public bool SetBack; // Reverse in order to attach + public bool Valid; // Attach info is valid - public bool ReadyToAttach; // trains are ready to attach + public bool ReadyToAttach; // Trains are ready to attach //================================================================================================// /// @@ -14346,7 +13896,7 @@ public AttachInfo(int stationPlatformReference, TTTrainCommands thisCommand, TTT } - // straight forward attach in station without first in and no set back : set no need to store (attach can be set directly) + // Straight forward attach in station without first in and no set back : set no need to store (attach can be set directly) if (!FirstIn && !SetBack && StationPlatformReference >= 0) { ReadyToAttach = true; @@ -14419,7 +13969,7 @@ public void FinalizeAttachDetails(TTTrain thisTrain, List trainList, TT { if (Valid) { - // set Xref to train to which to attach + // Set Xref to train to which to attach SetAttachXRef(thisTrain, trainList, playerTrain); } } @@ -14447,7 +13997,7 @@ public void SetAttachXRef(TTTrain dettrain, List trainList, TTTrain pla } } - // if not found, try player train + // If not found, try player train if (!trainFound) { if (playerTrain != null && String.Compare(playerTrain.Name, AttachTrainName, true) == 0) @@ -14458,14 +14008,14 @@ public void SetAttachXRef(TTTrain dettrain, List trainList, TTTrain pla } } - // issue warning if train not found + // Issue warning if train not found if (!trainFound) { Trace.TraceWarning("Train : {0} : attach details : train {1} to attach to is not found", dettrain.Name, AttachTrainName); } - // search for station stop if set + // Search for station stop if set else if (StationPlatformReference >= 0) { int stationIndex = -1; @@ -14484,10 +14034,10 @@ public void SetAttachXRef(TTTrain dettrain, List trainList, TTTrain pla } } - // if train is found, set need attach information + // If train is found, set need attach information if (trainFound) { - // set need attach + // Set need attach if (attachedTrain.NeedAttach.ContainsKey(StationPlatformReference)) { List needAttachList = attachedTrain.NeedAttach[StationPlatformReference]; @@ -14495,13 +14045,15 @@ public void SetAttachXRef(TTTrain dettrain, List trainList, TTTrain pla } else { - List needAttachList = new List(); - needAttachList.Add(dettrain.OrgAINumber); + List needAttachList = new List + { + dettrain.OrgAINumber + }; attachedTrain.NeedAttach.Add(StationPlatformReference, needAttachList); } } else - // if not found, set attach to invalid (nothing to attach to) + // If not found, set attach to invalid (nothing to attach to) { Valid = false; Trace.TraceWarning("Train {0} : attach command to attach to train {1} : command invalid", dettrain.Name, AttachTrainName); @@ -14516,12 +14068,12 @@ public void SetAttachXRef(TTTrain dettrain, List trainList, TTTrain pla /// public class PickUpInfo { - public int PickUpTrain; // train number to which to attach - public string PickUpTrainName = String.Empty; // train name to which to attach - public bool PickUpStatic = false; // pickup unnamed static consist + public int PickUpTrain; // Train number to which to attach + public string PickUpTrainName = String.Empty; // Train name to which to attach + public bool PickUpStatic = false; // Pickup unnamed static consist - public int StationPlatformReference; // station platform reference - set to -1 if attaching to static train in dispose command - public bool Valid; // attach info is valid + public int StationPlatformReference; // Station platform reference - set to -1 if attaching to static train in dispose command + public bool Valid; // Attach info is valid //================================================================================================// /// @@ -14550,12 +14102,12 @@ public PickUpInfo(int stationPlatformReference, TTTrainCommands thisCommand, TTT { switch (thisCommand.CommandQualifiers[0].QualifierName) { - case "static" : + case "static": PickUpStatic = true; StationPlatformReference = stationPlatformReference; break; - default : + default: Trace.TraceInformation("Train : {0} : unknown pickup qualifier : {1}", thisTrain.Name, thisCommand.CommandQualifiers[0].QualifierName); break; } @@ -14608,10 +14160,10 @@ public void Save(BinaryWriter outf) /// public void FinalizePickUpDetails(TTTrain thisTrain, List trainList, TTTrain playerTrain) { - // set Xref to train to which to attach + // Set Xref to train to which to attach SetPickUpXRef(thisTrain, trainList, playerTrain); - // sort out information per train or per location + // Sort out information per train or per location foreach (PickUpInfo thisPickUp in thisTrain.PickUpDetails) { thisTrain.PickUpStaticOnForms = false; @@ -14675,7 +14227,7 @@ public void SetPickUpXRef(TTTrain dettrain, List trainList, TTTrain pla } } - // if not found, try player train + // If not found, try player train if (!trainFound) { if (playerTrain != null && String.Compare(playerTrain.Name, PickUpTrainName, true) == 0) @@ -14686,7 +14238,7 @@ public void SetPickUpXRef(TTTrain dettrain, List trainList, TTTrain pla } } - // issue warning if train not found + // Issue warning if train not found if (!trainFound) { Trace.TraceWarning("Train : {0} : pickup details : train {1} to pick up is not found", @@ -14713,14 +14265,14 @@ public enum TransferType Leave, } - public TransferType TypeOfTransfer; // type of transfer - public DetachInfo.DetachUnitsInfo TransferUnitsInfo; // type of unit definition - public int TransferUnitCount; // no. of units (if defined as units) - public List TransferConsist = null; // consists to transfer (if defined as consist) + public TransferType TypeOfTransfer; // Type of transfer + public DetachInfo.DetachUnitsInfo TransferUnitsInfo; // Type of unit definition + public int TransferUnitCount; // No. of units (if defined as units) + public List TransferConsist = null; // Consists to transfer (if defined as consist) public int TransferTrain; // Number of other train public string TransferTrainName = String.Empty; // Name of other train - public int StationPlatformReference; // platform reference of transfer location - public bool Valid; // transfer is valid + public int StationPlatformReference; // Platform reference of transfer location + public bool Valid; // Transfer is valid //================================================================================================// /// @@ -14735,10 +14287,10 @@ public TransferInfo(int stationPlatformReference, TTTrainCommands thisCommand, T bool typeDefined = false; bool portionDefined = false; - // set station platform reference + // Set station platform reference StationPlatformReference = stationPlatformReference; - // set transfer train name + // Set transfer train name if (thisCommand.CommandValues != null && thisCommand.CommandValues.Count > 0) { TransferTrainName = String.Copy(thisCommand.CommandValues[0]); @@ -14752,13 +14304,13 @@ public TransferInfo(int stationPlatformReference, TTTrainCommands thisCommand, T { switch (thisCommand.CommandQualifiers[0].QualifierName) { - // static is allowed, will be inserted with key -99 - case "static" : + // Static is allowed, will be inserted with key -99 + case "static": TransferTrain = -99; break; - // other qualifiers processed below - default : + // Other qualifiers processed below + default: break; } } @@ -14768,7 +14320,7 @@ public TransferInfo(int stationPlatformReference, TTTrainCommands thisCommand, T trainDefined = false; } - // transfer unit type + // Transfer unit type if (thisCommand.CommandQualifiers == null || thisCommand.CommandQualifiers.Count <= 0) { Trace.TraceInformation("Train {0} : transfer command : missing transfer type", thisTrain.Name); @@ -14779,7 +14331,7 @@ public TransferInfo(int stationPlatformReference, TTTrainCommands thisCommand, T { switch (Qualifier.QualifierName.Trim().ToLower()) { - // transfer type qualifiers + // Transfer type qualifiers case "give": TypeOfTransfer = TransferType.Give; typeDefined = true; @@ -14800,7 +14352,7 @@ public TransferInfo(int stationPlatformReference, TTTrainCommands thisCommand, T typeDefined = true; break; - // transfer info qualifiers + // Transfer info qualifiers case "onepower": TransferUnitsInfo = DetachInfo.DetachUnitsInfo.leadingPower; portionDefined = true; @@ -14856,7 +14408,7 @@ public TransferInfo(int stationPlatformReference, TTTrainCommands thisCommand, T portionDefined = true; break; - // static is allready processed, so skip + // Static is allready processed, so skip case "static": break; @@ -14891,7 +14443,7 @@ public TransferInfo(int stationPlatformReference, TTTrainCommands thisCommand, T /// public TransferInfo(BinaryReader inf) { - TypeOfTransfer = (TransferType) inf.ReadInt32(); + TypeOfTransfer = (TransferType)inf.ReadInt32(); TransferUnitsInfo = (DetachInfo.DetachUnitsInfo)inf.ReadInt32(); TransferUnitCount = inf.ReadInt32(); @@ -14960,7 +14512,7 @@ public void PerformTransfer(TTTrain otherTrain, bool otherTrainFront, TTTrain th bool GiveTrainFront = false; bool TakeTrainFront = false; - // stop train + // Stop train thisTrain.SpeedMpS = 0; foreach (var car in thisTrain.Cars) { @@ -14970,7 +14522,7 @@ public void PerformTransfer(TTTrain otherTrain, bool otherTrainFront, TTTrain th if (thisTrain.TrainType != Train.TRAINTYPE.PLAYER) thisTrain.AdjustControlsThrottleOff(); thisTrain.physicsUpdate(0); - // sort out what to detach + // Sort out what to detach int iunits = 0; bool frontpos = true; DetachInfo.DetachUnitsInfo thisInfo; @@ -15020,7 +14572,7 @@ public void PerformTransfer(TTTrain otherTrain, bool otherTrainFront, TTTrain th TransferUnitsInfo = DetachInfo.DetachUnitsInfo.unitsAtEnd; break; - // other definitions : no change + // Other definitions: no change default: break; } @@ -15173,29 +14725,29 @@ public void PerformTransfer(TTTrain otherTrain, bool otherTrainFront, TTTrain th } else { - // create temp train which will hold transfered units + // Create temp train which will hold transfered units List tempList = new List(); string tempName = String.Concat("T_", thisTrain.OrgAINumber.ToString("0000")); int formedTrainNo = thisTrain.CreateStaticTrain(thisTrain, ref tempList, tempName, thisTrain.PresentPosition[0].TCSectionIndex); TTTrain tempTrain = tempList[0]; - // add new train (stored in tempList) to AutoGenTrains + // Add new train (stored in tempList) to AutoGenTrains thisTrain.AI.AutoGenTrains.Add(tempList[0]); thisTrain.Simulator.AutoGenDictionary.Add(formedTrainNo, tempList[0]); - // if detached at rear set negative no of units + // If detached at rear set negative no of units if (!frontpos) iunits = -iunits; - // create detach command + // Create detach command DetachInfo thisDetach = new DetachInfo(true, false, false, -1, false, false, false, false, false, false, iunits, null, formedTrainNo, false); - // perform detach on giving train + // Perform detach on giving train thisDetach.PerformDetach(GivingTrain, false); - // attach temp train to taking train + // Attach temp train to taking train tempTrain.TTCouple(TakingTrain, GiveTrainFront, TakeTrainFront); - // remove train from need transfer list + // Remove train from need transfer list if (StationPlatformReference >= 0) { if (otherTrain.NeedStationTransfer.ContainsKey(StationPlatformReference)) @@ -15203,7 +14755,7 @@ public void PerformTransfer(TTTrain otherTrain, bool otherTrainFront, TTTrain th List needTransferList = otherTrain.NeedStationTransfer[StationPlatformReference]; needTransferList.Remove(thisTrain.Number); - // remove list if empty + // Remove list if empty if (tempList.Count < 1) { otherTrain.NeedStationTransfer.Remove(StationPlatformReference); @@ -15212,7 +14764,7 @@ public void PerformTransfer(TTTrain otherTrain, bool otherTrainFront, TTTrain th } else if (TransferTrain == otherTrain.OrgAINumber) { - // get last section as reference to transfer position + // Get last section as reference to transfer position int lastSectionIndex = thisTrain.TCRoute.TCRouteSubpaths.Last().Last().TCSectionIndex; if (otherTrain.NeedTrainTransfer.ContainsKey(lastSectionIndex)) { @@ -15228,10 +14780,10 @@ public void PerformTransfer(TTTrain otherTrain, bool otherTrainFront, TTTrain th } } - // if transfer was part of dispose command, curtail train route so train is positioned at end of route + // If transfer was part of dispose command, curtail train route so train is positioned at end of route if (StationPlatformReference < 0) { - // get furthest index + // Get furthest index int firstSectionIndex = thisTrain.OccupiedTrack[0].Index; int lastSectionIndex = thisTrain.OccupiedTrack.Last().Index; int lastRouteIndex = Math.Max(thisTrain.ValidRoute[0].GetRouteIndex(firstSectionIndex, 0), thisTrain.ValidRoute[0].GetRouteIndex(lastSectionIndex, 0)); @@ -15266,7 +14818,7 @@ public void SetTransferXRef(TTTrain dettrain, List trainList, TTTrain p } } - // if not found, try player train + // If not found, try player train if (!trainFound) { if (playerTrain != null && String.Compare(playerTrain.Name, TransferTrainName, true) == 0) @@ -15275,9 +14827,9 @@ public void SetTransferXRef(TTTrain dettrain, List trainList, TTTrain p transferTrain = playerTrain; trainFound = true; } - } + } - // issue warning if train not found + // Issue warning if train not found if (!trainFound) { Trace.TraceWarning("Train : {0} : transfer details : train {1} is not found", @@ -15286,7 +14838,7 @@ public void SetTransferXRef(TTTrain dettrain, List trainList, TTTrain p Trace.TraceWarning("Train {0} : transfer command with train {1} : command invalid", dettrain.Name, TransferTrainName); } else - // set need to transfer + // Set need to transfer { if (stationTransfer) { @@ -15296,14 +14848,16 @@ public void SetTransferXRef(TTTrain dettrain, List trainList, TTTrain p } else { - List tempList = new List(); - tempList.Add(dettrain.OrgAINumber); + List tempList = new List + { + dettrain.OrgAINumber + }; transferTrain.NeedStationTransfer.Add(StationPlatformReference, tempList); } } else { - // get last section if train - assume this to be the transfer section + // Get last section if train - assume this to be the transfer section int lastSectionIndex = dettrain.TCRoute.TCRouteSubpaths.Last().Last().TCSectionIndex; if (transferTrain.NeedTrainTransfer.ContainsKey(lastSectionIndex)) { diff --git a/Source/Orts.Simulation/Simulation/Timetables/TurntableInfo.cs b/Source/Orts.Simulation/Simulation/Timetables/TurntableInfo.cs index 43aa77f4a5..9afb0d5493 100644 --- a/Source/Orts.Simulation/Simulation/Timetables/TurntableInfo.cs +++ b/Source/Orts.Simulation/Simulation/Timetables/TurntableInfo.cs @@ -16,7 +16,6 @@ // along with Open Rails. If not, see . // This code processes the Timetable definition and converts it into playable train information -// using System; using System.Collections.Generic; @@ -32,7 +31,6 @@ namespace Orts.Simulation.Timetables /// public class TurntableInfo : PoolInfo { - //================================================================================================// /// /// Constructor @@ -42,7 +40,6 @@ public TurntableInfo(Simulator simulatorref) : base(simulatorref) { } - //================================================================================================// /// /// Read pool files @@ -55,33 +52,33 @@ public TurntableInfo(Simulator simulatorref) : base(simulatorref) Dictionary turntables = new Dictionary(); List filenames; - // get filenames to process + // Get filenames to process filenames = GetTurntableFilenames(arguments[0]); - // get file contents as strings + // Get file contents as strings Trace.Write("\n"); foreach (string filePath in filenames) { - // get contents as strings + // Get contents as strings Trace.Write("Turntable File : " + filePath + "\n"); var turntableInfo = new TimetableReader(filePath); - // read lines from input until 'Name' definition is found + // Read lines from input until 'Name' definition is found int lineindex = 1; while (lineindex < turntableInfo.Strings.Count) { switch (turntableInfo.Strings[lineindex][0].ToLower().Trim()) { - // skip comment + // Skip comment case "#comment": lineindex++; break; - // process name - // do not increase lineindex as that is done in called method + // Process name + // Do not increase lineindex as that is done in called method case "#name": TimetableTurntablePool newTurntable = new TimetableTurntablePool(turntableInfo, ref lineindex, simulator); - // store if valid pool + // Store if valid pool if (!String.IsNullOrEmpty(newTurntable.PoolName)) { if (turntables.ContainsKey(newTurntable.PoolName)) @@ -107,7 +104,7 @@ public TurntableInfo(Simulator simulatorref) : base(simulatorref) } } - return (turntables); + return turntables; } @@ -121,7 +118,7 @@ private List GetTurntableFilenames(string filePath) { List filenames = new List(); - // check type of timetable file - list or single + // Check type of timetable file - list or single string fileDirectory = Path.GetDirectoryName(filePath); foreach (var ORTurntableFile in Directory.GetFiles(fileDirectory, "*.turntable_or")) @@ -133,7 +130,7 @@ private List GetTurntableFilenames(string filePath) filenames.Add(ORTunrtableFile); } - return (filenames); + return filenames; } } } diff --git a/Source/Orts.Simulation/Simulation/Weather.cs b/Source/Orts.Simulation/Simulation/Weather.cs index 543a232977..2d6fff3cbe 100644 --- a/Source/Orts.Simulation/Simulation/Weather.cs +++ b/Source/Orts.Simulation/Simulation/Weather.cs @@ -44,9 +44,6 @@ public class Weather // Fog/visibility distance. Ranges from 10m (can't see anything), 5km (medium), 20km (clear) to 100km (clear arctic). public float FogDistance; - - // Daylight offset (-12h to +12h) - public int DaylightOffset = 0; // Precipitation liquidity; =1 for rain, =0 for snow; intermediate values possible with dynamic weather; public float PrecipitationLiquidity; diff --git a/Source/RunActivity/Program.cs b/Source/RunActivity/Program.cs index 0781e0b889..89d13a81b3 100644 --- a/Source/RunActivity/Program.cs +++ b/Source/RunActivity/Program.cs @@ -20,7 +20,6 @@ using System.Linq; using System.Reflection; using System.Runtime.InteropServices; -using System.Windows.Forms; using Orts.Common; using Orts.Simulation; using Orts.Viewer3D; @@ -42,7 +41,6 @@ static class Program public static Simulator Simulator; public static Viewer Viewer; public static DispatchViewer DebugViewer; - public static MapViewer DebugViewerBeta; public static SoundDebugForm SoundDebugForm; public static ORTraceListener ORTraceListener; public static string logFileName = ""; // contains path to file @@ -62,9 +60,6 @@ static void Main(string[] args) path = Path.Combine(path, (Environment.Is64BitProcess) ? "X64" : "X86"); NativeMethods.SetDllDirectory(path); - Application.EnableVisualStyles(); - Application.SetCompatibleTextRenderingDefault(false); - var game = new Game(settings); game.PushState(new GameStateRunActivity(args)); game.Run(); diff --git a/Source/RunActivity/Viewer3D/Debugging/DebugViewerForm.Designer.cs b/Source/RunActivity/Viewer3D/Debugging/DebugViewerForm.Designer.cs index 1ce3a0ff36..4d19ee119c 100644 --- a/Source/RunActivity/Viewer3D/Debugging/DebugViewerForm.Designer.cs +++ b/Source/RunActivity/Viewer3D/Debugging/DebugViewerForm.Designer.cs @@ -159,7 +159,7 @@ private void InitializeComponent() this.resLabel.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.resLabel.Location = new System.Drawing.Point(887, 35); this.resLabel.Name = "resLabel"; - this.resLabel.Size = new System.Drawing.Size(18, 16); + this.resLabel.Size = new System.Drawing.Size(19, 16); this.resLabel.TabIndex = 8; this.resLabel.Text = "m"; // @@ -477,7 +477,7 @@ private void InitializeComponent() this.lblSimulationTimeText.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblSimulationTimeText.Location = new System.Drawing.Point(5, 34); this.lblSimulationTimeText.Name = "lblSimulationTimeText"; - this.lblSimulationTimeText.Size = new System.Drawing.Size(103, 16); + this.lblSimulationTimeText.Size = new System.Drawing.Size(104, 16); this.lblSimulationTimeText.TabIndex = 36; this.lblSimulationTimeText.Text = "Simulation Time"; this.lblSimulationTimeText.Visible = false; @@ -488,7 +488,7 @@ private void InitializeComponent() this.lblSimulationTime.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblSimulationTime.Location = new System.Drawing.Point(115, 34); this.lblSimulationTime.Name = "lblSimulationTime"; - this.lblSimulationTime.Size = new System.Drawing.Size(100, 16); + this.lblSimulationTime.Size = new System.Drawing.Size(101, 16); this.lblSimulationTime.TabIndex = 37; this.lblSimulationTime.Text = "SimulationTime"; this.lblSimulationTime.Visible = false; @@ -677,7 +677,7 @@ private void InitializeComponent() // lblInstruction1 // this.lblInstruction1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); - this.lblInstruction1.Location = new System.Drawing.Point(8, 717); + this.lblInstruction1.Location = new System.Drawing.Point(8, 672); this.lblInstruction1.Name = "lblInstruction1"; this.lblInstruction1.Padding = new System.Windows.Forms.Padding(3); this.lblInstruction1.Size = new System.Drawing.Size(327, 22); @@ -749,7 +749,7 @@ private void InitializeComponent() // lblInstruction2 // this.lblInstruction2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); - this.lblInstruction2.Location = new System.Drawing.Point(8, 738); + this.lblInstruction2.Location = new System.Drawing.Point(8, 693); this.lblInstruction2.Name = "lblInstruction2"; this.lblInstruction2.Padding = new System.Windows.Forms.Padding(3); this.lblInstruction2.Size = new System.Drawing.Size(327, 21); @@ -760,7 +760,7 @@ private void InitializeComponent() // lblInstruction3 // this.lblInstruction3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); - this.lblInstruction3.Location = new System.Drawing.Point(8, 759); + this.lblInstruction3.Location = new System.Drawing.Point(8, 714); this.lblInstruction3.Name = "lblInstruction3"; this.lblInstruction3.Padding = new System.Windows.Forms.Padding(3); this.lblInstruction3.Size = new System.Drawing.Size(327, 21); @@ -771,7 +771,7 @@ private void InitializeComponent() // lblInstruction4 // this.lblInstruction4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); - this.lblInstruction4.Location = new System.Drawing.Point(8, 780); + this.lblInstruction4.Location = new System.Drawing.Point(8, 735); this.lblInstruction4.Name = "lblInstruction4"; this.lblInstruction4.Padding = new System.Windows.Forms.Padding(3); this.lblInstruction4.Size = new System.Drawing.Size(327, 21); @@ -799,7 +799,7 @@ private void InitializeComponent() this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScroll = true; - this.ClientSize = new System.Drawing.Size(923, 749); + this.ClientSize = new System.Drawing.Size(923, 768); this.Controls.Add(this.cbShowPlatforms); this.Controls.Add(this.lblInstruction4); this.Controls.Add(this.lblInstruction3); diff --git a/Source/RunActivity/Viewer3D/Debugging/DebugViewerForm.cs b/Source/RunActivity/Viewer3D/Debugging/DebugViewerForm.cs index b1110fc075..8b295226c2 100644 --- a/Source/RunActivity/Viewer3D/Debugging/DebugViewerForm.cs +++ b/Source/RunActivity/Viewer3D/Debugging/DebugViewerForm.cs @@ -2138,9 +2138,6 @@ private void ClipDrag(int diffX, int diffY) #endregion } - - /* NOTE: Commented out to avoid duplication in namespace; copied to `DebugViewerBetaForm.cs` */ - /* #region SignalWidget /// /// Defines a signal being drawn in a 2D view. @@ -2451,5 +2448,5 @@ static public double DistanceSqr(dVector v1, dVector v2) return Math.Pow((v1.TileX - v2.TileX) * 2048 + v1.X - v2.X, 2) + Math.Pow((v1.TileZ - v2.TileZ) * 2048 + v1.Z - v2.Z, 2); } - }*/ + } } diff --git a/Source/RunActivity/Viewer3D/Map/MapDataProvider.cs b/Source/RunActivity/Viewer3D/Map/MapDataProvider.cs deleted file mode 100644 index 19997dbe99..0000000000 --- a/Source/RunActivity/Viewer3D/Map/MapDataProvider.cs +++ /dev/null @@ -1,308 +0,0 @@ -// COPYRIGHT 2023 by the Open Rails project. -// -// This file is part of Open Rails. -// -// Open Rails is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Open Rails is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Open Rails. If not, see . - -using System; -using System.Diagnostics; -using System.Drawing; -using Microsoft.Xna.Framework; -using Orts.Formats.Msts; -using Orts.MultiPlayer; -using Orts.Simulation.Physics; -using Orts.Simulation.Signalling; -using Orts.Viewer3D.Debugging; - -namespace Orts.Viewer3D.Map -{ - public class MapDataProvider - { - public MapViewer F { get; set; } // Shortest possible abbreviation so code is easier to read - - public MapDataProvider(MapViewer form) - { - F = form; - } - - public void SetControls() - { - UpdateControlVisibility(); - } - - private void UpdateControlVisibility() - { - var isMultiPlayer = MPManager.IsMultiPlayer(); - - if (isMultiPlayer) - { - F.playersPanel.Visible = true; - } - - if (isMultiPlayer && MPManager.IsServer()) - { - F.playerRolePanel.Visible = true; - F.messagesPanel.Visible = true; - F.multiplayerSettingsPanel.Visible = true; - //F.playersPanel.Visible = true; - } - } - - public void PopulateItemLists() - { - foreach (var item in F.simulator.TDB.TrackDB.TrItemTable) - { - switch (item.ItemType) - { - case TrItem.trItemType.trSIGNAL: - if (item is SignalItem si) - { - if (si.SigObj >= 0 && si.SigObj < F.simulator.Signals.SignalObjects.Length) - { - var s = F.simulator.Signals.SignalObjects[si.SigObj]; - if (s != null && s.Type == SignalObjectType.Signal && s.isSignalNormal()) - F.signals.Add(new SignalWidget(si, s)); - } - } - break; - - case TrItem.trItemType.trSIDING: - // Sidings have 2 ends but are not always listed in pairs in the *.tdb file - // Neither are their names unique (e.g. Bernina Bahn). - // Find whether this siding is a new one or the other end of an old one. - // If other end, then find the right-hand one as the location for a single label. - // Note: Find() within a foreach() loop is O(n^2) but is only done at start. - var oldSidingIndex = F.sidings.FindIndex(r => r.LinkId == item.TrItemId && r.Name == item.ItemName); - if (oldSidingIndex < 0) - { - var newSiding = new SidingWidget(item as SidingItem); - F.sidings.Add(newSiding); - } - else - { - var oldSiding = F.sidings[oldSidingIndex]; - var oldLocation = oldSiding.Location; - var newLocation = new PointF((item.TileX * 2048) + item.X, (item.TileZ * 2048) + item.Z); - - // Because these are structs, not classes, compiler won't let you overwrite them. - // Instead create a single item which replaces the 2 platform items. - var replacement = new SidingWidget(item as SidingItem) - { - Location = GetMidPoint(oldLocation, newLocation) - }; - - // Replace the old siding item with the replacement - F.sidings.RemoveAt(oldSidingIndex); - F.sidings.Add(replacement); - } - break; - - case TrItem.trItemType.trPLATFORM: - // Platforms have 2 ends but are not always listed in pairs in the *.tdb file - // Neither are their names unique (e.g. Bernina Bahn). - // Find whether this platform is a new one or the other end of an old one. - // If other end, then find the right-hand one as the location for a single label. - var oldPlatformIndex = F.platforms.FindIndex(r => r.LinkId == item.TrItemId && r.Name == item.ItemName); - if (oldPlatformIndex < 0) - { - var newPlatform = new PlatformWidget(item as PlatformItem) - { - Extent1 = new PointF((item.TileX * 2048) + item.X, (item.TileZ * 2048) + item.Z) - }; - F.platforms.Add(newPlatform); - } - else - { - var oldPlatform = F.platforms[oldPlatformIndex]; - var oldLocation = oldPlatform.Location; - var newLocation = new PointF((item.TileX * 2048) + item.X, (item.TileZ * 2048) + item.Z); - - // Because these are structs, not classes, compiler won't let you overwrite them. - // Instead create a single item which replaces the 2 platform items. - var replacement = new PlatformWidget(item as PlatformItem) - { - Extent1 = oldLocation - , - Extent2 = newLocation - // Give it the right-hand location - , - Location = GetRightHandPoint(oldLocation, newLocation) - }; - - // Replace the old platform item with the replacement - F.platforms.RemoveAt(oldPlatformIndex); - F.platforms.Add(replacement); - } - break; - - default: - break; - } - } - - foreach (var p in F.platforms) - if (p.Extent1.IsEmpty || p.Extent2.IsEmpty) - Trace.TraceWarning("Platform '{0}' is incomplete as the two ends do not match. It will not show in full in the Timetable Tab of the Map Window", p.Name); - } - - /// - /// Returns the mid-point between two locations - /// - /// - /// - /// - /// - private PointF GetMidPoint(PointF location1, PointF location2) - { - return new PointF() - { - X = (location1.X + location2.X) / 2 - , - Y = (location1.Y + location2.Y) / 2 - }; - } - - private PointF GetRightHandPoint(PointF location1, PointF location2) - { - return location1.X > location2.X ? location1 : location2; - } - - public void ShowSimulationTime() - { - var ct = TimeSpan.FromSeconds(Program.Simulator.ClockTime); - F.timeLabel.Text = $"{ct:hh}:{ct:mm}:{ct:ss}"; - } - - /// - /// In case of missing X,Y values, just draw a blob at the non-zero end. - /// - public void FixForBadData(float width, ref PointF scaledA, ref PointF scaledB, PointF Extent1, PointF Extent2) - { - if (Extent1.X == 0 || Extent1.Y == 0) - { - scaledA.X = scaledB.X + width; - scaledA.Y = scaledB.Y + width; - } - else if (Extent2.X == 0 || Extent2.Y == 0) - { - scaledB.X = scaledA.X + width; - scaledB.Y = scaledA.Y + width; - } - } - - public bool IsActiveTrain(Simulation.AIs.AITrain t) - { - return t != null -&& (t.MovementState != Simulation.AIs.AITrain.AI_MOVEMENT_STATE.AI_STATIC - && !(t.TrainType == Train.TRAINTYPE.AI_INCORPORATED && !t.IncorporatingTrain.IsPathless) - - || t.TrainType == Train.TRAINTYPE.PLAYER); - } - - /* - * # section is claimed by a train which is waiting for a signal. - * & section is occupied by more than one train. - * deadlock info (always linked to a switch node): - * · * possible deadlock location - start of a single track section shared with a train running in opposite direction. - * · ^ active deadlock - train from opposite direction is occupying or has reserved at least part of the common - * single track section. Train will be stopped at this location – generally at the last signal ahead of this node. - * · ~ active deadlock at that location for other train - can be significant as this other train can block this - * train’s path. - */ - private static readonly char[] DeadlockIndicators = "#&*^~".ToCharArray(); - - public static bool ContainsDeadlockIndicators(string text) - { - return text.IndexOfAny(DeadlockIndicators) >= 0; - } - - // The canvas is split into equally pitched rows. - // Each row has an array of 4 slots with StartX, EndX positions and a count of how many slots have been filled. - // Arrays are used instead of lists to avoid delays for memory management. - public void CleanTextCells() - { - if (F.alignedTextY == null || F.alignedTextY.Length != F.mapCanvas.Height / DispatchViewer.spacing) //first time to put text, or the text height has changed - { - F.alignedTextY = new Vector2[F.mapCanvas.Height / DispatchViewer.spacing][]; - F.alignedTextNum = new int[F.mapCanvas.Height / DispatchViewer.spacing]; - for (var i = 0; i < F.mapCanvas.Height / DispatchViewer.spacing; i++) - F.alignedTextY[i] = new Vector2[5]; //each line has at most 5 slots - } - for (var i = 0; i < F.mapCanvas.Height / DispatchViewer.spacing; i++) - F.alignedTextNum[i] = 0; - } - - // Returns a vertical position for the text that doesn't clash or returns -1 - // If the preferred space for text is occupied, then the slot above (-ve Y) is tested, then 2 sltos above, then 1 below. - public float GetUnusedYLocation(float startX, float wantY, string name) - { - const float noFreeSlotFound = -1f; - - var desiredPositionY = (int)(wantY / DispatchViewer.spacing); // The positionY of the ideal row for the text. - var endX = startX + (name.Length * F.trainFont.Size); - //out of drawing area - if (endX < 0) - return noFreeSlotFound; - - var positionY = desiredPositionY; - while (positionY >= 0 && positionY < F.alignedTextY.Length) - { - //if the line contains no text yet, put it there - if (F.alignedTextNum[positionY] == 0) - return SaveLabelLocation(startX, endX, positionY); - - var conflict = false; - - //check if it intersects with any labels already in this row - for (var col = 0; col < F.alignedTextNum[positionY]; col++) - { - var v = F.alignedTextY[positionY][col]; - //check conflict with a text, v.X is the start of the text, v.Y is the end of the text - if (endX >= v.X && startX <= v.Y) - { - conflict = true; - break; - } - } - - if (conflict) - { - positionY--; // Try a different row: -1, -2, +2, +1 - - if (positionY - desiredPositionY <= -2) // Cannot move up (-ve Y), so try to move it down (+ve Y) - positionY = desiredPositionY + 2; // Try +2 then +1 - - if (positionY == desiredPositionY) // Back to original position again - return noFreeSlotFound; - } - else - { - // Check that row has an unused column in its fixed size array - return F.alignedTextNum[positionY] >= F.alignedTextY[positionY].Length ? noFreeSlotFound : SaveLabelLocation(startX, endX, positionY); - } - } - return noFreeSlotFound; - } - - private float SaveLabelLocation(float startX, float endX, int positionY) - { - // add start and end location for the new label - F.alignedTextY[positionY][F.alignedTextNum[positionY]] = new Vector2 { X = startX, Y = endX }; - - F.alignedTextNum[positionY]++; - - return positionY * DispatchViewer.spacing; - } - } -} diff --git a/Source/RunActivity/Viewer3D/Map/MapForm.Designer.cs b/Source/RunActivity/Viewer3D/Map/MapForm.Designer.cs deleted file mode 100644 index 09e6111dd6..0000000000 --- a/Source/RunActivity/Viewer3D/Map/MapForm.Designer.cs +++ /dev/null @@ -1,1076 +0,0 @@ -namespace Orts.Viewer3D.Debugging -{ - partial class MapViewer - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.components = new System.ComponentModel.Container(); - System.Windows.Forms.ListViewItem listViewItem1 = new System.Windows.Forms.ListViewItem(new string[] { - "Player1 (you)"}, -1, System.Drawing.Color.Empty, System.Drawing.Color.Empty, new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)))); - System.Windows.Forms.ListViewItem listViewItem2 = new System.Windows.Forms.ListViewItem("Player2"); - System.Windows.Forms.ListViewItem listViewItem3 = new System.Windows.Forms.ListViewItem("Player3"); - System.Windows.Forms.ListViewItem listViewItem4 = new System.Windows.Forms.ListViewItem("..."); - this.playerRolePanel = new System.Windows.Forms.Panel(); - this.playerRoleLink = new System.Windows.Forms.LinkLabel(); - this.playerRoleExplanation = new System.Windows.Forms.Label(); - this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); - this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); - this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel(); - this.messagesPanel = new System.Windows.Forms.Panel(); - this.messages = new System.Windows.Forms.ListBox(); - this.button2 = new System.Windows.Forms.Button(); - this.button1 = new System.Windows.Forms.Button(); - this.textBox1 = new System.Windows.Forms.TextBox(); - this.label2 = new System.Windows.Forms.Label(); - this.canvasPanel = new System.Windows.Forms.Panel(); - this.timeLabel = new System.Windows.Forms.Label(); - this.mapCustomizationButton = new System.Windows.Forms.Button(); - this.mapCustomizationPanel = new System.Windows.Forms.Panel(); - this.showAllTrainsRadio = new System.Windows.Forms.RadioButton(); - this.showActiveTrainsRadio = new System.Windows.Forms.RadioButton(); - this.showTrainStateCheckbox = new System.Windows.Forms.CheckBox(); - this.showTrainLabelsCheckbox = new System.Windows.Forms.CheckBox(); - this.showSignalStateCheckbox = new System.Windows.Forms.CheckBox(); - this.showSignalsCheckbox = new System.Windows.Forms.CheckBox(); - this.showSwitchesCheckbox = new System.Windows.Forms.CheckBox(); - this.showSidingLabelsCheckbox = new System.Windows.Forms.CheckBox(); - this.showPlatformLabelsCheckbox = new System.Windows.Forms.CheckBox(); - this.showPlatformsCheckbox = new System.Windows.Forms.CheckBox(); - this.label1 = new System.Windows.Forms.Label(); - this.rotateThemesButton = new System.Windows.Forms.Button(); - this.showTimeCheckbox = new System.Windows.Forms.CheckBox(); - this.useAntiAliasingCheckbox = new System.Windows.Forms.CheckBox(); - this.mapCanvas = new System.Windows.Forms.PictureBox(); - this.tableLayoutPanel4 = new System.Windows.Forms.TableLayoutPanel(); - this.panel1 = new System.Windows.Forms.Panel(); - this.multiplayerSettingsPanel = new System.Windows.Forms.Panel(); - this.groupBox2 = new System.Windows.Forms.GroupBox(); - this.penaltyCheckbox = new System.Windows.Forms.CheckBox(); - this.checkBox5 = new System.Windows.Forms.CheckBox(); - this.allowJoiningCheckbox = new System.Windows.Forms.CheckBox(); - this.mapSettingsPanel = new System.Windows.Forms.Panel(); - this.groupBox1 = new System.Windows.Forms.GroupBox(); - this.button5 = new System.Windows.Forms.Button(); - this.centerOnMyTrainButton = new System.Windows.Forms.Button(); - this.seeTrainInGameButton = new System.Windows.Forms.Button(); - this.label3 = new System.Windows.Forms.Label(); - this.mapResolutionUpDown = new System.Windows.Forms.NumericUpDown(); - this.allowThrowingSwitchesCheckbox = new System.Windows.Forms.CheckBox(); - this.allowChangingSignalsCheckbox = new System.Windows.Forms.CheckBox(); - this.drawPathCheckbox = new System.Windows.Forms.CheckBox(); - this.playersPanel = new System.Windows.Forms.Panel(); - this.groupBox3 = new System.Windows.Forms.GroupBox(); - this.playersView = new System.Windows.Forms.ListView(); - this.messageActionsMenu = new System.Windows.Forms.ContextMenuStrip(this.components); - this.messageSelectedPlayerMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.replyToSelectedPlayerMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.playerActionsMenu = new System.Windows.Forms.ContextMenuStrip(this.components); - this.makeThisPlayerAnAssistantToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.jumpToThisPlayerInGameToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.followToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.kickFromMultiplayerSessionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.setSwitchMenu = new System.Windows.Forms.ContextMenuStrip(this.components); - this.setSwitchToToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.mainRouteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.sideRouteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.setSignalMenu = new System.Windows.Forms.ContextMenuStrip(this.components); - this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); - this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem(); - this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripMenuItem(); - this.approachToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.proceedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); - this.allowCallOnToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.playerRolePanel.SuspendLayout(); - this.tableLayoutPanel1.SuspendLayout(); - this.tableLayoutPanel2.SuspendLayout(); - this.tableLayoutPanel3.SuspendLayout(); - this.messagesPanel.SuspendLayout(); - this.canvasPanel.SuspendLayout(); - this.mapCustomizationPanel.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)(this.mapCanvas)).BeginInit(); - this.tableLayoutPanel4.SuspendLayout(); - this.multiplayerSettingsPanel.SuspendLayout(); - this.groupBox2.SuspendLayout(); - this.mapSettingsPanel.SuspendLayout(); - this.groupBox1.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)(this.mapResolutionUpDown)).BeginInit(); - this.playersPanel.SuspendLayout(); - this.groupBox3.SuspendLayout(); - this.messageActionsMenu.SuspendLayout(); - this.playerActionsMenu.SuspendLayout(); - this.setSwitchMenu.SuspendLayout(); - this.setSignalMenu.SuspendLayout(); - this.SuspendLayout(); - // - // playerRolePanel - // - this.playerRolePanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.playerRolePanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(214)))), ((int)(((byte)(234)))), ((int)(((byte)(248))))); - this.playerRolePanel.Controls.Add(this.playerRoleLink); - this.playerRolePanel.Controls.Add(this.playerRoleExplanation); - this.playerRolePanel.Location = new System.Drawing.Point(0, 0); - this.playerRolePanel.Margin = new System.Windows.Forms.Padding(0); - this.playerRolePanel.Name = "playerRolePanel"; - this.playerRolePanel.Size = new System.Drawing.Size(784, 30); - this.playerRolePanel.TabIndex = 0; - this.playerRolePanel.Visible = false; - // - // playerRoleLink - // - this.playerRoleLink.ActiveLinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(27)))), ((int)(((byte)(79)))), ((int)(((byte)(114))))); - this.playerRoleLink.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); - this.playerRoleLink.AutoSize = true; - this.playerRoleLink.LinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(116)))), ((int)(((byte)(166))))); - this.playerRoleLink.Location = new System.Drawing.Point(717, 9); - this.playerRoleLink.Name = "playerRoleLink"; - this.playerRoleLink.Size = new System.Drawing.Size(60, 13); - this.playerRoleLink.TabIndex = 1; - this.playerRoleLink.TabStop = true; - this.playerRoleLink.Text = "Learn more"; - this.playerRoleLink.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.playerRoleLink_LinkClicked); - // - // playerRoleExplanation - // - this.playerRoleExplanation.AutoSize = true; - this.playerRoleExplanation.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); - this.playerRoleExplanation.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(116)))), ((int)(((byte)(166))))); - this.playerRoleExplanation.Location = new System.Drawing.Point(12, 9); - this.playerRoleExplanation.Name = "playerRoleExplanation"; - this.playerRoleExplanation.Size = new System.Drawing.Size(284, 13); - this.playerRoleExplanation.TabIndex = 0; - this.playerRoleExplanation.Text = "You are the dispatcher in this multiplayer session"; - // - // tableLayoutPanel1 - // - this.tableLayoutPanel1.ColumnCount = 1; - this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); - this.tableLayoutPanel1.Controls.Add(this.playerRolePanel, 0, 0); - this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel2, 0, 1); - this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; - this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); - this.tableLayoutPanel1.Margin = new System.Windows.Forms.Padding(0); - this.tableLayoutPanel1.Name = "tableLayoutPanel1"; - this.tableLayoutPanel1.RowCount = 1; - this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); - this.tableLayoutPanel1.Size = new System.Drawing.Size(784, 561); - this.tableLayoutPanel1.TabIndex = 3; - // - // tableLayoutPanel2 - // - this.tableLayoutPanel2.ColumnCount = 2; - this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); - this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 200F)); - this.tableLayoutPanel2.Controls.Add(this.tableLayoutPanel3, 0, 0); - this.tableLayoutPanel2.Controls.Add(this.tableLayoutPanel4, 1, 0); - this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill; - this.tableLayoutPanel2.Location = new System.Drawing.Point(0, 30); - this.tableLayoutPanel2.Margin = new System.Windows.Forms.Padding(0); - this.tableLayoutPanel2.Name = "tableLayoutPanel2"; - this.tableLayoutPanel2.RowCount = 1; - this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); - this.tableLayoutPanel2.Size = new System.Drawing.Size(784, 531); - this.tableLayoutPanel2.TabIndex = 0; - // - // tableLayoutPanel3 - // - this.tableLayoutPanel3.ColumnCount = 1; - this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); - this.tableLayoutPanel3.Controls.Add(this.messagesPanel, 0, 0); - this.tableLayoutPanel3.Controls.Add(this.canvasPanel, 0, 1); - this.tableLayoutPanel3.Dock = System.Windows.Forms.DockStyle.Fill; - this.tableLayoutPanel3.Location = new System.Drawing.Point(0, 0); - this.tableLayoutPanel3.Margin = new System.Windows.Forms.Padding(0); - this.tableLayoutPanel3.Name = "tableLayoutPanel3"; - this.tableLayoutPanel3.RowCount = 2; - this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); - this.tableLayoutPanel3.Size = new System.Drawing.Size(584, 531); - this.tableLayoutPanel3.TabIndex = 0; - // - // messagesPanel - // - this.messagesPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.messagesPanel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; - this.messagesPanel.Controls.Add(this.messages); - this.messagesPanel.Controls.Add(this.button2); - this.messagesPanel.Controls.Add(this.button1); - this.messagesPanel.Controls.Add(this.textBox1); - this.messagesPanel.Controls.Add(this.label2); - this.messagesPanel.Location = new System.Drawing.Point(0, 0); - this.messagesPanel.Margin = new System.Windows.Forms.Padding(0); - this.messagesPanel.Name = "messagesPanel"; - this.messagesPanel.Padding = new System.Windows.Forms.Padding(10); - this.messagesPanel.Size = new System.Drawing.Size(584, 163); - this.messagesPanel.TabIndex = 0; - this.messagesPanel.Visible = false; - // - // messages - // - this.messages.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.messages.Enabled = false; - this.messages.FormattingEnabled = true; - this.messages.IntegralHeight = false; - this.messages.Location = new System.Drawing.Point(16, 26); - this.messages.Name = "messages"; - this.messages.Size = new System.Drawing.Size(554, 97); - this.messages.TabIndex = 5; - // - // button2 - // - this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); - this.button2.Enabled = false; - this.button2.Location = new System.Drawing.Point(421, 128); - this.button2.Margin = new System.Windows.Forms.Padding(0); - this.button2.Name = "button2"; - this.button2.Size = new System.Drawing.Size(126, 23); - this.button2.TabIndex = 4; - this.button2.Text = "Message all players"; - this.button2.UseVisualStyleBackColor = true; - // - // button1 - // - this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); - this.button1.AutoSize = true; - this.button1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; - this.button1.Enabled = false; - this.button1.Location = new System.Drawing.Point(547, 128); - this.button1.Margin = new System.Windows.Forms.Padding(0); - this.button1.Name = "button1"; - this.button1.Size = new System.Drawing.Size(23, 23); - this.button1.TabIndex = 3; - this.button1.Text = ">"; - this.button1.UseVisualStyleBackColor = true; - // - // textBox1 - // - this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.textBox1.Enabled = false; - this.textBox1.Location = new System.Drawing.Point(16, 130); - this.textBox1.Name = "textBox1"; - this.textBox1.Size = new System.Drawing.Size(402, 20); - this.textBox1.TabIndex = 2; - // - // label2 - // - this.label2.AutoSize = true; - this.label2.Location = new System.Drawing.Point(13, 10); - this.label2.Name = "label2"; - this.label2.Size = new System.Drawing.Size(58, 13); - this.label2.TabIndex = 0; - this.label2.Text = "Messages:"; - // - // canvasPanel - // - this.canvasPanel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; - this.canvasPanel.Controls.Add(this.timeLabel); - this.canvasPanel.Controls.Add(this.mapCustomizationButton); - this.canvasPanel.Controls.Add(this.mapCustomizationPanel); - this.canvasPanel.Controls.Add(this.mapCanvas); - this.canvasPanel.Dock = System.Windows.Forms.DockStyle.Fill; - this.canvasPanel.Location = new System.Drawing.Point(0, 163); - this.canvasPanel.Margin = new System.Windows.Forms.Padding(0); - this.canvasPanel.Name = "canvasPanel"; - this.canvasPanel.Padding = new System.Windows.Forms.Padding(13); - this.canvasPanel.Size = new System.Drawing.Size(584, 368); - this.canvasPanel.TabIndex = 1; - // - // timeLabel - // - this.timeLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); - this.timeLabel.AutoSize = true; - this.timeLabel.BackColor = System.Drawing.Color.Transparent; - this.timeLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); - this.timeLabel.Location = new System.Drawing.Point(25, 333); - this.timeLabel.Name = "timeLabel"; - this.timeLabel.Size = new System.Drawing.Size(92, 13); - this.timeLabel.TabIndex = 1; - this.timeLabel.Text = "Simulation time"; - // - // mapCustomizationButton - // - this.mapCustomizationButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.mapCustomizationButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; - this.mapCustomizationButton.FlatAppearance.BorderSize = 0; - this.mapCustomizationButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat; - this.mapCustomizationButton.Location = new System.Drawing.Point(443, 324); - this.mapCustomizationButton.Name = "mapCustomizationButton"; - this.mapCustomizationButton.Size = new System.Drawing.Size(120, 23); - this.mapCustomizationButton.TabIndex = 0; - this.mapCustomizationButton.Tag = "mapCustomization"; - this.mapCustomizationButton.Text = "Map customization"; - this.mapCustomizationButton.UseVisualStyleBackColor = true; - this.mapCustomizationButton.Click += new System.EventHandler(this.mapCustomizationButton_Click); - // - // mapCustomizationPanel - // - this.mapCustomizationPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.mapCustomizationPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; - this.mapCustomizationPanel.Controls.Add(this.showAllTrainsRadio); - this.mapCustomizationPanel.Controls.Add(this.showActiveTrainsRadio); - this.mapCustomizationPanel.Controls.Add(this.showTrainStateCheckbox); - this.mapCustomizationPanel.Controls.Add(this.showTrainLabelsCheckbox); - this.mapCustomizationPanel.Controls.Add(this.showSignalStateCheckbox); - this.mapCustomizationPanel.Controls.Add(this.showSignalsCheckbox); - this.mapCustomizationPanel.Controls.Add(this.showSwitchesCheckbox); - this.mapCustomizationPanel.Controls.Add(this.showSidingLabelsCheckbox); - this.mapCustomizationPanel.Controls.Add(this.showPlatformLabelsCheckbox); - this.mapCustomizationPanel.Controls.Add(this.showPlatformsCheckbox); - this.mapCustomizationPanel.Controls.Add(this.label1); - this.mapCustomizationPanel.Controls.Add(this.rotateThemesButton); - this.mapCustomizationPanel.Controls.Add(this.showTimeCheckbox); - this.mapCustomizationPanel.Controls.Add(this.useAntiAliasingCheckbox); - this.mapCustomizationPanel.Location = new System.Drawing.Point(373, 3); - this.mapCustomizationPanel.Name = "mapCustomizationPanel"; - this.mapCustomizationPanel.Size = new System.Drawing.Size(190, 315); - this.mapCustomizationPanel.TabIndex = 0; - this.mapCustomizationPanel.Visible = false; - // - // showAllTrainsRadio - // - this.showAllTrainsRadio.AutoSize = true; - this.showAllTrainsRadio.Location = new System.Drawing.Point(10, 279); - this.showAllTrainsRadio.Name = "showAllTrainsRadio"; - this.showAllTrainsRadio.Size = new System.Drawing.Size(64, 17); - this.showAllTrainsRadio.TabIndex = 19; - this.showAllTrainsRadio.Text = "All trains"; - this.showAllTrainsRadio.UseVisualStyleBackColor = true; - // - // showActiveTrainsRadio - // - this.showActiveTrainsRadio.AutoSize = true; - this.showActiveTrainsRadio.Checked = true; - this.showActiveTrainsRadio.Location = new System.Drawing.Point(10, 260); - this.showActiveTrainsRadio.Name = "showActiveTrainsRadio"; - this.showActiveTrainsRadio.Size = new System.Drawing.Size(106, 17); - this.showActiveTrainsRadio.TabIndex = 18; - this.showActiveTrainsRadio.TabStop = true; - this.showActiveTrainsRadio.Text = "Only active trains"; - this.showActiveTrainsRadio.UseVisualStyleBackColor = true; - // - // showTrainStateCheckbox - // - this.showTrainStateCheckbox.AutoSize = true; - this.showTrainStateCheckbox.Location = new System.Drawing.Point(28, 241); - this.showTrainStateCheckbox.Name = "showTrainStateCheckbox"; - this.showTrainStateCheckbox.Size = new System.Drawing.Size(76, 17); - this.showTrainStateCheckbox.TabIndex = 17; - this.showTrainStateCheckbox.Text = "Train state"; - this.showTrainStateCheckbox.UseVisualStyleBackColor = true; - // - // showTrainLabelsCheckbox - // - this.showTrainLabelsCheckbox.AutoSize = true; - this.showTrainLabelsCheckbox.Location = new System.Drawing.Point(10, 222); - this.showTrainLabelsCheckbox.Name = "showTrainLabelsCheckbox"; - this.showTrainLabelsCheckbox.Size = new System.Drawing.Size(80, 17); - this.showTrainLabelsCheckbox.TabIndex = 16; - this.showTrainLabelsCheckbox.Text = "Train labels"; - this.showTrainLabelsCheckbox.UseVisualStyleBackColor = true; - // - // showSignalStateCheckbox - // - this.showSignalStateCheckbox.AutoSize = true; - this.showSignalStateCheckbox.Location = new System.Drawing.Point(28, 203); - this.showSignalStateCheckbox.Name = "showSignalStateCheckbox"; - this.showSignalStateCheckbox.Size = new System.Drawing.Size(81, 17); - this.showSignalStateCheckbox.TabIndex = 15; - this.showSignalStateCheckbox.Text = "Signal state"; - this.showSignalStateCheckbox.UseVisualStyleBackColor = true; - // - // showSignalsCheckbox - // - this.showSignalsCheckbox.AutoSize = true; - this.showSignalsCheckbox.Location = new System.Drawing.Point(10, 184); - this.showSignalsCheckbox.Name = "showSignalsCheckbox"; - this.showSignalsCheckbox.Size = new System.Drawing.Size(60, 17); - this.showSignalsCheckbox.TabIndex = 14; - this.showSignalsCheckbox.Text = "Signals"; - this.showSignalsCheckbox.UseVisualStyleBackColor = true; - // - // showSwitchesCheckbox - // - this.showSwitchesCheckbox.AutoSize = true; - this.showSwitchesCheckbox.Location = new System.Drawing.Point(10, 165); - this.showSwitchesCheckbox.Name = "showSwitchesCheckbox"; - this.showSwitchesCheckbox.Size = new System.Drawing.Size(69, 17); - this.showSwitchesCheckbox.TabIndex = 13; - this.showSwitchesCheckbox.Text = "Switches"; - this.showSwitchesCheckbox.UseVisualStyleBackColor = true; - // - // showSidingLabelsCheckbox - // - this.showSidingLabelsCheckbox.AutoSize = true; - this.showSidingLabelsCheckbox.Location = new System.Drawing.Point(10, 146); - this.showSidingLabelsCheckbox.Name = "showSidingLabelsCheckbox"; - this.showSidingLabelsCheckbox.Size = new System.Drawing.Size(85, 17); - this.showSidingLabelsCheckbox.TabIndex = 12; - this.showSidingLabelsCheckbox.Text = "Siding labels"; - this.showSidingLabelsCheckbox.UseVisualStyleBackColor = true; - // - // showPlatformLabelsCheckbox - // - this.showPlatformLabelsCheckbox.AutoSize = true; - this.showPlatformLabelsCheckbox.Location = new System.Drawing.Point(10, 127); - this.showPlatformLabelsCheckbox.Name = "showPlatformLabelsCheckbox"; - this.showPlatformLabelsCheckbox.Size = new System.Drawing.Size(94, 17); - this.showPlatformLabelsCheckbox.TabIndex = 11; - this.showPlatformLabelsCheckbox.Text = "Platform labels"; - this.showPlatformLabelsCheckbox.UseVisualStyleBackColor = true; - // - // showPlatformsCheckbox - // - this.showPlatformsCheckbox.AutoSize = true; - this.showPlatformsCheckbox.Location = new System.Drawing.Point(10, 108); - this.showPlatformsCheckbox.Name = "showPlatformsCheckbox"; - this.showPlatformsCheckbox.Size = new System.Drawing.Size(69, 17); - this.showPlatformsCheckbox.TabIndex = 10; - this.showPlatformsCheckbox.Text = "Platforms"; - this.showPlatformsCheckbox.UseVisualStyleBackColor = true; - // - // label1 - // - this.label1.AutoSize = true; - this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); - this.label1.Location = new System.Drawing.Point(7, 91); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(81, 13); - this.label1.TabIndex = 9; - this.label1.Text = "Map features"; - // - // rotateThemesButton - // - this.rotateThemesButton.AutoSize = true; - this.rotateThemesButton.Location = new System.Drawing.Point(10, 52); - this.rotateThemesButton.Name = "rotateThemesButton"; - this.rotateThemesButton.Size = new System.Drawing.Size(167, 23); - this.rotateThemesButton.TabIndex = 8; - this.rotateThemesButton.Text = "Rotate between themes"; - this.rotateThemesButton.UseVisualStyleBackColor = true; - this.rotateThemesButton.Click += new System.EventHandler(this.rotateThemesButton_Click); - // - // showTimeCheckbox - // - this.showTimeCheckbox.AutoSize = true; - this.showTimeCheckbox.Checked = true; - this.showTimeCheckbox.CheckState = System.Windows.Forms.CheckState.Checked; - this.showTimeCheckbox.Location = new System.Drawing.Point(10, 29); - this.showTimeCheckbox.Name = "showTimeCheckbox"; - this.showTimeCheckbox.Size = new System.Drawing.Size(124, 17); - this.showTimeCheckbox.TabIndex = 1; - this.showTimeCheckbox.Text = "Show simulation time"; - this.showTimeCheckbox.UseVisualStyleBackColor = true; - // - // useAntiAliasingCheckbox - // - this.useAntiAliasingCheckbox.AutoSize = true; - this.useAntiAliasingCheckbox.Location = new System.Drawing.Point(10, 10); - this.useAntiAliasingCheckbox.Name = "useAntiAliasingCheckbox"; - this.useAntiAliasingCheckbox.Size = new System.Drawing.Size(103, 17); - this.useAntiAliasingCheckbox.TabIndex = 0; - this.useAntiAliasingCheckbox.Text = "Use anti-aliasing"; - this.useAntiAliasingCheckbox.UseVisualStyleBackColor = true; - // - // mapCanvas - // - this.mapCanvas.Dock = System.Windows.Forms.DockStyle.Fill; - this.mapCanvas.Location = new System.Drawing.Point(13, 13); - this.mapCanvas.Margin = new System.Windows.Forms.Padding(0); - this.mapCanvas.Name = "mapCanvas"; - this.mapCanvas.Size = new System.Drawing.Size(558, 342); - this.mapCanvas.TabIndex = 0; - this.mapCanvas.TabStop = false; - this.mapCanvas.MouseDown += new System.Windows.Forms.MouseEventHandler(this.mapCanvas_MouseDown); - this.mapCanvas.MouseMove += new System.Windows.Forms.MouseEventHandler(this.mapCanvas_MouseMove); - this.mapCanvas.MouseUp += new System.Windows.Forms.MouseEventHandler(this.mapCanvas_MouseUp); - // - // tableLayoutPanel4 - // - this.tableLayoutPanel4.ColumnCount = 1; - this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); - this.tableLayoutPanel4.Controls.Add(this.panel1, 0, 0); - this.tableLayoutPanel4.Controls.Add(this.multiplayerSettingsPanel, 0, 1); - this.tableLayoutPanel4.Controls.Add(this.mapSettingsPanel, 0, 2); - this.tableLayoutPanel4.Controls.Add(this.playersPanel, 0, 3); - this.tableLayoutPanel4.Dock = System.Windows.Forms.DockStyle.Fill; - this.tableLayoutPanel4.Location = new System.Drawing.Point(584, 0); - this.tableLayoutPanel4.Margin = new System.Windows.Forms.Padding(0); - this.tableLayoutPanel4.Name = "tableLayoutPanel4"; - this.tableLayoutPanel4.RowCount = 4; - this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); - this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle()); - this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); - this.tableLayoutPanel4.Size = new System.Drawing.Size(200, 531); - this.tableLayoutPanel4.TabIndex = 1; - // - // panel1 - // - this.panel1.Location = new System.Drawing.Point(3, 3); - this.panel1.Name = "panel1"; - this.panel1.Size = new System.Drawing.Size(194, 14); - this.panel1.TabIndex = 3; - // - // multiplayerSettingsPanel - // - this.multiplayerSettingsPanel.AutoSize = true; - this.multiplayerSettingsPanel.Controls.Add(this.groupBox2); - this.multiplayerSettingsPanel.Location = new System.Drawing.Point(0, 20); - this.multiplayerSettingsPanel.Margin = new System.Windows.Forms.Padding(0); - this.multiplayerSettingsPanel.Name = "multiplayerSettingsPanel"; - this.multiplayerSettingsPanel.Padding = new System.Windows.Forms.Padding(10, 0, 10, 0); - this.multiplayerSettingsPanel.Size = new System.Drawing.Size(200, 83); - this.multiplayerSettingsPanel.TabIndex = 1; - this.multiplayerSettingsPanel.Visible = false; - // - // groupBox2 - // - this.groupBox2.Controls.Add(this.penaltyCheckbox); - this.groupBox2.Controls.Add(this.checkBox5); - this.groupBox2.Controls.Add(this.allowJoiningCheckbox); - this.groupBox2.Location = new System.Drawing.Point(10, 0); - this.groupBox2.Name = "groupBox2"; - this.groupBox2.Size = new System.Drawing.Size(180, 80); - this.groupBox2.TabIndex = 0; - this.groupBox2.TabStop = false; - this.groupBox2.Text = "Multiplayer settings"; - // - // penaltyCheckbox - // - this.penaltyCheckbox.AutoSize = true; - this.penaltyCheckbox.Checked = true; - this.penaltyCheckbox.CheckState = System.Windows.Forms.CheckState.Checked; - this.penaltyCheckbox.Location = new System.Drawing.Point(7, 57); - this.penaltyCheckbox.Name = "penaltyCheckbox"; - this.penaltyCheckbox.Size = new System.Drawing.Size(163, 17); - this.penaltyCheckbox.TabIndex = 2; - this.penaltyCheckbox.Text = "Penalty for speeding && SPAD"; - this.penaltyCheckbox.UseVisualStyleBackColor = true; - this.penaltyCheckbox.CheckedChanged += new System.EventHandler(this.penaltyCheckbox_CheckedChanged); - // - // checkBox5 - // - this.checkBox5.AutoSize = true; - this.checkBox5.Enabled = false; - this.checkBox5.Location = new System.Drawing.Point(7, 38); - this.checkBox5.Name = "checkBox5"; - this.checkBox5.Size = new System.Drawing.Size(99, 17); - this.checkBox5.TabIndex = 1; - this.checkBox5.Text = "Prefer green (?)"; - this.checkBox5.UseVisualStyleBackColor = true; - // - // allowJoiningCheckbox - // - this.allowJoiningCheckbox.AutoSize = true; - this.allowJoiningCheckbox.Checked = true; - this.allowJoiningCheckbox.CheckState = System.Windows.Forms.CheckState.Checked; - this.allowJoiningCheckbox.Location = new System.Drawing.Point(7, 19); - this.allowJoiningCheckbox.Name = "allowJoiningCheckbox"; - this.allowJoiningCheckbox.Size = new System.Drawing.Size(141, 17); - this.allowJoiningCheckbox.TabIndex = 0; - this.allowJoiningCheckbox.Text = "Allow new players to join"; - this.allowJoiningCheckbox.UseVisualStyleBackColor = true; - this.allowJoiningCheckbox.CheckedChanged += new System.EventHandler(this.allowJoiningCheckbox_CheckedChanged); - // - // mapSettingsPanel - // - this.mapSettingsPanel.AutoSize = true; - this.mapSettingsPanel.Controls.Add(this.groupBox1); - this.mapSettingsPanel.Location = new System.Drawing.Point(0, 103); - this.mapSettingsPanel.Margin = new System.Windows.Forms.Padding(0); - this.mapSettingsPanel.Name = "mapSettingsPanel"; - this.mapSettingsPanel.Padding = new System.Windows.Forms.Padding(10, 0, 10, 0); - this.mapSettingsPanel.Size = new System.Drawing.Size(200, 191); - this.mapSettingsPanel.TabIndex = 0; - // - // groupBox1 - // - this.groupBox1.Controls.Add(this.button5); - this.groupBox1.Controls.Add(this.centerOnMyTrainButton); - this.groupBox1.Controls.Add(this.seeTrainInGameButton); - this.groupBox1.Controls.Add(this.label3); - this.groupBox1.Controls.Add(this.mapResolutionUpDown); - this.groupBox1.Controls.Add(this.allowThrowingSwitchesCheckbox); - this.groupBox1.Controls.Add(this.allowChangingSignalsCheckbox); - this.groupBox1.Controls.Add(this.drawPathCheckbox); - this.groupBox1.Location = new System.Drawing.Point(10, 3); - this.groupBox1.Name = "groupBox1"; - this.groupBox1.Size = new System.Drawing.Size(180, 185); - this.groupBox1.TabIndex = 0; - this.groupBox1.TabStop = false; - this.groupBox1.Text = "Map settings and controls"; - // - // button5 - // - this.button5.AutoSize = true; - this.button5.Enabled = false; - this.button5.Location = new System.Drawing.Point(7, 156); - this.button5.Name = "button5"; - this.button5.Size = new System.Drawing.Size(167, 23); - this.button5.TabIndex = 7; - this.button5.Text = "Follow my train on the map"; - this.button5.UseVisualStyleBackColor = true; - // - // centerOnMyTrainButton - // - this.centerOnMyTrainButton.AutoSize = true; - this.centerOnMyTrainButton.Location = new System.Drawing.Point(7, 127); - this.centerOnMyTrainButton.Name = "centerOnMyTrainButton"; - this.centerOnMyTrainButton.Size = new System.Drawing.Size(167, 23); - this.centerOnMyTrainButton.TabIndex = 6; - this.centerOnMyTrainButton.Text = "Jump to my train on the map"; - this.centerOnMyTrainButton.UseVisualStyleBackColor = true; - this.centerOnMyTrainButton.Click += new System.EventHandler(this.centerOnMyTrainButton_Click); - // - // seeTrainInGameButton - // - this.seeTrainInGameButton.AutoSize = true; - this.seeTrainInGameButton.Enabled = false; - this.seeTrainInGameButton.Location = new System.Drawing.Point(7, 98); - this.seeTrainInGameButton.Name = "seeTrainInGameButton"; - this.seeTrainInGameButton.Size = new System.Drawing.Size(167, 23); - this.seeTrainInGameButton.TabIndex = 5; - this.seeTrainInGameButton.Text = "Jump to my train in game"; - this.seeTrainInGameButton.UseVisualStyleBackColor = true; - this.seeTrainInGameButton.Click += new System.EventHandler(this.seeTrainInGameButton_Click); - // - // label3 - // - this.label3.AutoSize = true; - this.label3.Location = new System.Drawing.Point(4, 78); - this.label3.Name = "label3"; - this.label3.Size = new System.Drawing.Size(96, 13); - this.label3.TabIndex = 4; - this.label3.Text = "Map resolution (m):"; - // - // mapResolutionUpDown - // - this.mapResolutionUpDown.Increment = new decimal(new int[] { - 50, - 0, - 0, - 0}); - this.mapResolutionUpDown.Location = new System.Drawing.Point(102, 75); - this.mapResolutionUpDown.Margin = new System.Windows.Forms.Padding(0); - this.mapResolutionUpDown.Maximum = new decimal(new int[] { - 200000, - 0, - 0, - 0}); - this.mapResolutionUpDown.Minimum = new decimal(new int[] { - 80, - 0, - 0, - 0}); - this.mapResolutionUpDown.Name = "mapResolutionUpDown"; - this.mapResolutionUpDown.Size = new System.Drawing.Size(72, 20); - this.mapResolutionUpDown.TabIndex = 3; - this.mapResolutionUpDown.ThousandsSeparator = true; - this.mapResolutionUpDown.Value = new decimal(new int[] { - 5000, - 0, - 0, - 0}); - this.mapResolutionUpDown.ValueChanged += new System.EventHandler(this.mapResolutionUpDown_ValueChanged); - // - // allowThrowingSwitchesCheckbox - // - this.allowThrowingSwitchesCheckbox.AutoSize = true; - this.allowThrowingSwitchesCheckbox.Checked = true; - this.allowThrowingSwitchesCheckbox.CheckState = System.Windows.Forms.CheckState.Checked; - this.allowThrowingSwitchesCheckbox.Location = new System.Drawing.Point(7, 57); - this.allowThrowingSwitchesCheckbox.Name = "allowThrowingSwitchesCheckbox"; - this.allowThrowingSwitchesCheckbox.Size = new System.Drawing.Size(138, 17); - this.allowThrowingSwitchesCheckbox.TabIndex = 2; - this.allowThrowingSwitchesCheckbox.Text = "Allow throwing switches"; - this.allowThrowingSwitchesCheckbox.UseVisualStyleBackColor = true; - // - // allowChangingSignalsCheckbox - // - this.allowChangingSignalsCheckbox.AutoSize = true; - this.allowChangingSignalsCheckbox.Checked = true; - this.allowChangingSignalsCheckbox.CheckState = System.Windows.Forms.CheckState.Checked; - this.allowChangingSignalsCheckbox.Location = new System.Drawing.Point(7, 38); - this.allowChangingSignalsCheckbox.Name = "allowChangingSignalsCheckbox"; - this.allowChangingSignalsCheckbox.Size = new System.Drawing.Size(133, 17); - this.allowChangingSignalsCheckbox.TabIndex = 1; - this.allowChangingSignalsCheckbox.Text = "Allow changing signals"; - this.allowChangingSignalsCheckbox.UseVisualStyleBackColor = true; - // - // drawPathCheckbox - // - this.drawPathCheckbox.AutoSize = true; - this.drawPathCheckbox.Checked = true; - this.drawPathCheckbox.CheckState = System.Windows.Forms.CheckState.Checked; - this.drawPathCheckbox.Location = new System.Drawing.Point(7, 19); - this.drawPathCheckbox.Name = "drawPathCheckbox"; - this.drawPathCheckbox.Size = new System.Drawing.Size(135, 17); - this.drawPathCheckbox.TabIndex = 0; - this.drawPathCheckbox.Text = "Draw next path section"; - this.drawPathCheckbox.UseVisualStyleBackColor = true; - this.drawPathCheckbox.CheckedChanged += new System.EventHandler(this.drawPathCheckbox_CheckedChanged); - // - // playersPanel - // - this.playersPanel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; - this.playersPanel.Controls.Add(this.groupBox3); - this.playersPanel.Dock = System.Windows.Forms.DockStyle.Fill; - this.playersPanel.Location = new System.Drawing.Point(0, 294); - this.playersPanel.Margin = new System.Windows.Forms.Padding(0); - this.playersPanel.Name = "playersPanel"; - this.playersPanel.Padding = new System.Windows.Forms.Padding(10, 0, 10, 10); - this.playersPanel.Size = new System.Drawing.Size(200, 237); - this.playersPanel.TabIndex = 2; - this.playersPanel.Visible = false; - // - // groupBox3 - // - this.groupBox3.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; - this.groupBox3.Controls.Add(this.playersView); - this.groupBox3.Dock = System.Windows.Forms.DockStyle.Fill; - this.groupBox3.Location = new System.Drawing.Point(10, 0); - this.groupBox3.Name = "groupBox3"; - this.groupBox3.Size = new System.Drawing.Size(180, 227); - this.groupBox3.TabIndex = 0; - this.groupBox3.TabStop = false; - this.groupBox3.Text = "Players"; - // - // playersView - // - this.playersView.Activation = System.Windows.Forms.ItemActivation.OneClick; - this.playersView.Alignment = System.Windows.Forms.ListViewAlignment.Left; - this.playersView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.playersView.HideSelection = false; - this.playersView.HoverSelection = true; - this.playersView.Items.AddRange(new System.Windows.Forms.ListViewItem[] { - listViewItem1, - listViewItem2, - listViewItem3, - listViewItem4}); - this.playersView.Location = new System.Drawing.Point(7, 19); - this.playersView.MultiSelect = false; - this.playersView.Name = "playersView"; - this.playersView.Size = new System.Drawing.Size(167, 202); - this.playersView.TabIndex = 1; - this.playersView.UseCompatibleStateImageBehavior = false; - this.playersView.View = System.Windows.Forms.View.List; - this.playersView.MouseClick += new System.Windows.Forms.MouseEventHandler(this.playersView_MouseClick); - // - // messageActionsMenu - // - this.messageActionsMenu.Enabled = false; - this.messageActionsMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.messageSelectedPlayerMenuItem, - this.replyToSelectedPlayerMenuItem}); - this.messageActionsMenu.Name = "contextMenuStrip2"; - this.messageActionsMenu.ShowImageMargin = false; - this.messageActionsMenu.Size = new System.Drawing.Size(197, 48); - // - // messageSelectedPlayerMenuItem - // - this.messageSelectedPlayerMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; - this.messageSelectedPlayerMenuItem.Enabled = false; - this.messageSelectedPlayerMenuItem.Name = "messageSelectedPlayerMenuItem"; - this.messageSelectedPlayerMenuItem.Size = new System.Drawing.Size(196, 22); - this.messageSelectedPlayerMenuItem.Text = "Message the selected player"; - // - // replyToSelectedPlayerMenuItem - // - this.replyToSelectedPlayerMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; - this.replyToSelectedPlayerMenuItem.Enabled = false; - this.replyToSelectedPlayerMenuItem.Name = "replyToSelectedPlayerMenuItem"; - this.replyToSelectedPlayerMenuItem.Size = new System.Drawing.Size(196, 22); - this.replyToSelectedPlayerMenuItem.Text = "Reply to the selected player"; - // - // playerActionsMenu - // - this.playerActionsMenu.Enabled = false; - this.playerActionsMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.makeThisPlayerAnAssistantToolStripMenuItem, - this.jumpToThisPlayerInGameToolStripMenuItem, - this.followToolStripMenuItem, - this.kickFromMultiplayerSessionToolStripMenuItem}); - this.playerActionsMenu.Name = "contextMenuStrip3"; - this.playerActionsMenu.Size = new System.Drawing.Size(230, 92); - // - // makeThisPlayerAnAssistantToolStripMenuItem - // - this.makeThisPlayerAnAssistantToolStripMenuItem.Enabled = false; - this.makeThisPlayerAnAssistantToolStripMenuItem.Name = "makeThisPlayerAnAssistantToolStripMenuItem"; - this.makeThisPlayerAnAssistantToolStripMenuItem.Size = new System.Drawing.Size(229, 22); - this.makeThisPlayerAnAssistantToolStripMenuItem.Text = "Make this player an assistant"; - // - // jumpToThisPlayerInGameToolStripMenuItem - // - this.jumpToThisPlayerInGameToolStripMenuItem.Enabled = false; - this.jumpToThisPlayerInGameToolStripMenuItem.Name = "jumpToThisPlayerInGameToolStripMenuItem"; - this.jumpToThisPlayerInGameToolStripMenuItem.Size = new System.Drawing.Size(229, 22); - this.jumpToThisPlayerInGameToolStripMenuItem.Text = "Jump to this player in game"; - // - // followToolStripMenuItem - // - this.followToolStripMenuItem.Enabled = false; - this.followToolStripMenuItem.Name = "followToolStripMenuItem"; - this.followToolStripMenuItem.Size = new System.Drawing.Size(229, 22); - this.followToolStripMenuItem.Text = "Follow on the map"; - // - // kickFromMultiplayerSessionToolStripMenuItem - // - this.kickFromMultiplayerSessionToolStripMenuItem.Enabled = false; - this.kickFromMultiplayerSessionToolStripMenuItem.Name = "kickFromMultiplayerSessionToolStripMenuItem"; - this.kickFromMultiplayerSessionToolStripMenuItem.Size = new System.Drawing.Size(229, 22); - this.kickFromMultiplayerSessionToolStripMenuItem.Text = "Kick from multiplayer session"; - // - // setSwitchMenu - // - this.setSwitchMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.setSwitchToToolStripMenuItem, - this.mainRouteToolStripMenuItem, - this.sideRouteToolStripMenuItem}); - this.setSwitchMenu.Name = "contextMenuStrip1"; - this.setSwitchMenu.Size = new System.Drawing.Size(157, 70); - this.setSwitchMenu.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.setSwitchMenu_ItemClicked); - // - // setSwitchToToolStripMenuItem - // - this.setSwitchToToolStripMenuItem.Enabled = false; - this.setSwitchToToolStripMenuItem.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Bold); - this.setSwitchToToolStripMenuItem.Name = "setSwitchToToolStripMenuItem"; - this.setSwitchToToolStripMenuItem.Size = new System.Drawing.Size(156, 22); - this.setSwitchToToolStripMenuItem.Text = "Set switch to..."; - // - // mainRouteToolStripMenuItem - // - this.mainRouteToolStripMenuItem.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(93)))), ((int)(((byte)(64)))), ((int)(((byte)(55))))); - this.mainRouteToolStripMenuItem.ForeColor = System.Drawing.Color.White; - this.mainRouteToolStripMenuItem.Name = "mainRouteToolStripMenuItem"; - this.mainRouteToolStripMenuItem.Size = new System.Drawing.Size(156, 22); - this.mainRouteToolStripMenuItem.Tag = "mainRoute"; - this.mainRouteToolStripMenuItem.Text = "Main route"; - // - // sideRouteToolStripMenuItem - // - this.sideRouteToolStripMenuItem.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(161)))), ((int)(((byte)(136)))), ((int)(((byte)(127))))); - this.sideRouteToolStripMenuItem.Name = "sideRouteToolStripMenuItem"; - this.sideRouteToolStripMenuItem.Size = new System.Drawing.Size(156, 22); - this.sideRouteToolStripMenuItem.Tag = "sideRoute"; - this.sideRouteToolStripMenuItem.Text = "Side route"; - // - // setSignalMenu - // - this.setSignalMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.toolStripMenuItem1, - this.toolStripMenuItem2, - this.toolStripMenuItem3, - this.approachToolStripMenuItem, - this.proceedToolStripMenuItem, - this.toolStripSeparator1, - this.allowCallOnToolStripMenuItem}); - this.setSignalMenu.Name = "contextMenuStrip1"; - this.setSignalMenu.Size = new System.Drawing.Size(191, 142); - this.setSignalMenu.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.setSignalMenu_ItemClicked); - // - // toolStripMenuItem1 - // - this.toolStripMenuItem1.Enabled = false; - this.toolStripMenuItem1.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Bold); - this.toolStripMenuItem1.Name = "toolStripMenuItem1"; - this.toolStripMenuItem1.Size = new System.Drawing.Size(190, 22); - this.toolStripMenuItem1.Text = "Set signal aspect to..."; - // - // toolStripMenuItem2 - // - this.toolStripMenuItem2.Name = "toolStripMenuItem2"; - this.toolStripMenuItem2.Size = new System.Drawing.Size(190, 22); - this.toolStripMenuItem2.Tag = "system"; - this.toolStripMenuItem2.Text = "System controlled"; - // - // toolStripMenuItem3 - // - this.toolStripMenuItem3.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(203)))), ((int)(((byte)(67)))), ((int)(((byte)(53))))); - this.toolStripMenuItem3.ForeColor = System.Drawing.Color.White; - this.toolStripMenuItem3.Name = "toolStripMenuItem3"; - this.toolStripMenuItem3.Size = new System.Drawing.Size(190, 22); - this.toolStripMenuItem3.Tag = "stop"; - this.toolStripMenuItem3.Text = "Stop"; - // - // approachToolStripMenuItem - // - this.approachToolStripMenuItem.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(241)))), ((int)(((byte)(196)))), ((int)(((byte)(15))))); - this.approachToolStripMenuItem.Name = "approachToolStripMenuItem"; - this.approachToolStripMenuItem.Size = new System.Drawing.Size(190, 22); - this.approachToolStripMenuItem.Tag = "approach"; - this.approachToolStripMenuItem.Text = "Approach"; - // - // proceedToolStripMenuItem - // - this.proceedToolStripMenuItem.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(34)))), ((int)(((byte)(153)))), ((int)(((byte)(84))))); - this.proceedToolStripMenuItem.ForeColor = System.Drawing.Color.White; - this.proceedToolStripMenuItem.Name = "proceedToolStripMenuItem"; - this.proceedToolStripMenuItem.Size = new System.Drawing.Size(190, 22); - this.proceedToolStripMenuItem.Tag = "proceed"; - this.proceedToolStripMenuItem.Text = "Proceed"; - // - // toolStripSeparator1 - // - this.toolStripSeparator1.Name = "toolStripSeparator1"; - this.toolStripSeparator1.Size = new System.Drawing.Size(187, 6); - // - // allowCallOnToolStripMenuItem - // - this.allowCallOnToolStripMenuItem.Enabled = false; - this.allowCallOnToolStripMenuItem.Name = "allowCallOnToolStripMenuItem"; - this.allowCallOnToolStripMenuItem.Size = new System.Drawing.Size(190, 22); - this.allowCallOnToolStripMenuItem.Tag = "callOn"; - this.allowCallOnToolStripMenuItem.Text = "Allow call on"; - // - // DispatchViewerBeta - // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(784, 561); - this.Controls.Add(this.tableLayoutPanel1); - this.MinimumSize = new System.Drawing.Size(600, 400); - this.Name = "DispatchViewerBeta"; - this.Text = "Map window"; - this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.DispatchViewerBeta_FormClosing); - this.Resize += new System.EventHandler(this.DispatchViewerBeta_Resize); - this.playerRolePanel.ResumeLayout(false); - this.playerRolePanel.PerformLayout(); - this.tableLayoutPanel1.ResumeLayout(false); - this.tableLayoutPanel2.ResumeLayout(false); - this.tableLayoutPanel3.ResumeLayout(false); - this.messagesPanel.ResumeLayout(false); - this.messagesPanel.PerformLayout(); - this.canvasPanel.ResumeLayout(false); - this.canvasPanel.PerformLayout(); - this.mapCustomizationPanel.ResumeLayout(false); - this.mapCustomizationPanel.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)(this.mapCanvas)).EndInit(); - this.tableLayoutPanel4.ResumeLayout(false); - this.tableLayoutPanel4.PerformLayout(); - this.multiplayerSettingsPanel.ResumeLayout(false); - this.groupBox2.ResumeLayout(false); - this.groupBox2.PerformLayout(); - this.mapSettingsPanel.ResumeLayout(false); - this.groupBox1.ResumeLayout(false); - this.groupBox1.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)(this.mapResolutionUpDown)).EndInit(); - this.playersPanel.ResumeLayout(false); - this.groupBox3.ResumeLayout(false); - this.messageActionsMenu.ResumeLayout(false); - this.playerActionsMenu.ResumeLayout(false); - this.setSwitchMenu.ResumeLayout(false); - this.setSignalMenu.ResumeLayout(false); - this.ResumeLayout(false); - - } - - #endregion - - public System.Windows.Forms.Panel playerRolePanel; - private System.Windows.Forms.Label playerRoleExplanation; - private System.Windows.Forms.LinkLabel playerRoleLink; - private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; - private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; - private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3; - public System.Windows.Forms.Panel messagesPanel; - private System.Windows.Forms.Label label2; - private System.Windows.Forms.Button button2; - private System.Windows.Forms.Button button1; - private System.Windows.Forms.TextBox textBox1; - private System.Windows.Forms.ContextMenuStrip messageActionsMenu; - private System.Windows.Forms.ToolStripMenuItem messageSelectedPlayerMenuItem; - private System.Windows.Forms.ToolStripMenuItem replyToSelectedPlayerMenuItem; - private System.Windows.Forms.TableLayoutPanel tableLayoutPanel4; - private System.Windows.Forms.Panel mapSettingsPanel; - private System.Windows.Forms.GroupBox groupBox1; - private System.Windows.Forms.CheckBox allowThrowingSwitchesCheckbox; - private System.Windows.Forms.CheckBox allowChangingSignalsCheckbox; - private System.Windows.Forms.CheckBox drawPathCheckbox; - public System.Windows.Forms.Panel multiplayerSettingsPanel; - private System.Windows.Forms.GroupBox groupBox2; - private System.Windows.Forms.CheckBox penaltyCheckbox; - private System.Windows.Forms.CheckBox checkBox5; - private System.Windows.Forms.CheckBox allowJoiningCheckbox; - private System.Windows.Forms.NumericUpDown mapResolutionUpDown; - private System.Windows.Forms.Label label3; - private System.Windows.Forms.Button button5; - private System.Windows.Forms.Button centerOnMyTrainButton; - private System.Windows.Forms.Button seeTrainInGameButton; - public System.Windows.Forms.Panel playersPanel; - private System.Windows.Forms.GroupBox groupBox3; - private System.Windows.Forms.ListView playersView; - private System.Windows.Forms.ContextMenuStrip playerActionsMenu; - private System.Windows.Forms.ToolStripMenuItem makeThisPlayerAnAssistantToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem followToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem jumpToThisPlayerInGameToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem kickFromMultiplayerSessionToolStripMenuItem; - private System.Windows.Forms.Panel canvasPanel; - public System.Windows.Forms.PictureBox mapCanvas; - private System.Windows.Forms.Button mapCustomizationButton; - private System.Windows.Forms.Panel mapCustomizationPanel; - private System.Windows.Forms.CheckBox useAntiAliasingCheckbox; - private System.Windows.Forms.ListBox messages; - private System.Windows.Forms.Panel panel1; - private System.Windows.Forms.CheckBox showTimeCheckbox; - private System.Windows.Forms.Button rotateThemesButton; - public System.Windows.Forms.Label timeLabel; - private System.Windows.Forms.CheckBox showSignalsCheckbox; - private System.Windows.Forms.CheckBox showSwitchesCheckbox; - private System.Windows.Forms.CheckBox showSidingLabelsCheckbox; - private System.Windows.Forms.CheckBox showPlatformLabelsCheckbox; - private System.Windows.Forms.CheckBox showPlatformsCheckbox; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.CheckBox showSignalStateCheckbox; - private System.Windows.Forms.RadioButton showActiveTrainsRadio; - private System.Windows.Forms.CheckBox showTrainStateCheckbox; - private System.Windows.Forms.CheckBox showTrainLabelsCheckbox; - private System.Windows.Forms.RadioButton showAllTrainsRadio; - private System.Windows.Forms.ContextMenuStrip setSwitchMenu; - private System.Windows.Forms.ToolStripMenuItem setSwitchToToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem mainRouteToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem sideRouteToolStripMenuItem; - private System.Windows.Forms.ContextMenuStrip setSignalMenu; - private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem1; - private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem2; - private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem3; - private System.Windows.Forms.ToolStripMenuItem approachToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem proceedToolStripMenuItem; - private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; - private System.Windows.Forms.ToolStripMenuItem allowCallOnToolStripMenuItem; - } -} - diff --git a/Source/RunActivity/Viewer3D/Map/MapForm.cs b/Source/RunActivity/Viewer3D/Map/MapForm.cs deleted file mode 100644 index 2d5223f8dc..0000000000 --- a/Source/RunActivity/Viewer3D/Map/MapForm.cs +++ /dev/null @@ -1,2027 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Drawing; -using System.Linq; -using System.Windows.Forms; -using Microsoft.Xna.Framework; -using Orts.Formats.Msts; -using Orts.MultiPlayer; -using Orts.Simulation; -using Orts.Simulation.AIs; -using Orts.Simulation.Physics; -using Orts.Simulation.RollingStocks; -using Orts.Simulation.Signalling; -using Orts.Simulation.Timetables; -using Orts.Viewer3D.Map; -using Orts.Viewer3D.Popups; -using ORTS.Common; -using Color = System.Drawing.Color; - -namespace Orts.Viewer3D.Debugging -{ - public partial class MapViewer : Form - { - #region Variables - /// - /// Reference to the main simulator object. - /// - public readonly Simulator simulator; - private readonly MapDataProvider MapDataProvider; - private readonly MapThemeProvider MapThemeProvider; - private string ThemeName = "light"; - private ThemeStyle Theme; - /// - /// Used to periodically check if we should shift the view when the - /// user is holding down a "shift view" button. - /// - private readonly Timer UITimer; - public Viewer Viewer; - - /// - /// True when the user is dragging the route view - /// - public bool Dragging; - private WorldPosition worldPos; - public float xScale = 1; // pixels / metre - public float yScale = 1; // pixels / metre - - public List switchItemsDrawn; - public List signalItemsDrawn; - public SwitchWidget switchPickedItem; - public SignalWidget signalPickedItem; - public bool switchPickedItemHandled; - public double switchPickedTime; - public bool signalPickedItemHandled; - public double signalPickedTime; - public bool DrawPath = true; //draw train path - readonly TrackNode[] nodes; - - public List selectedTrainList; - /// - /// contains the last position of the mouse - /// - private System.Drawing.Point LastCursorPosition = new System.Drawing.Point(); - - public Pen redPen = new Pen(Color.FromArgb(244, 67, 54)); - public Pen greenPen = new Pen(Color.FromArgb(76, 175, 80)); - public Pen orangePen = new Pen(Color.FromArgb(255, 235, 59)); - public Pen trainPen = new Pen(Color.DarkGreen); - public Pen pathPen = new Pen(Color.FromArgb(52, 152, 219)); - public Pen grayPen = new Pen(Color.Gray); - public Pen PlatformPen = new Pen(Color.Blue); - public Pen TrackPen = new Pen(Color.FromArgb(46, 64, 83)); - public Pen ZoomTargetPen = new Pen(Color.FromArgb(46, 64, 83)); - - public Font trainFont = new Font("Segoe UI Semibold", 10, FontStyle.Bold); - public Font sidingFont = new Font("Segoe UI Semibold", 10, FontStyle.Regular); - public Font PlatformFont = new Font("Segoe UI Semibold", 10, FontStyle.Regular); - public Font SignalFont = new Font("Segoe UI Semibold", 10, FontStyle.Regular); - private readonly SolidBrush trainBrush = new SolidBrush(Color.Red); - public SolidBrush sidingBrush = new SolidBrush(Color.Blue); - public SolidBrush PlatformBrush = new SolidBrush(Color.DarkBlue); - public SolidBrush SignalBrush = new SolidBrush(Color.DarkRed); - public SolidBrush InactiveTrainBrush = new SolidBrush(Color.DarkRed); - private Color MapCanvasColor = Color.White; - - // the train selected by leftclicking the mouse - public Train PickedTrain; - /// - /// Defines the area to view, in meters. The left edge is meters from the leftmost extent of the route. - /// - public RectangleF ViewWindow; - - // Extents of the route in meters measured from the World origin - public float minX = float.MaxValue; - public float minY = float.MaxValue; - public float maxX = float.MinValue; - public float maxY = float.MinValue; - - public int RedrawCount; - private double lastUpdateTime; - - private bool MapCustomizationVisible = false; - #endregion - - public MapViewer(Simulator simulator, Viewer viewer) - { - InitializeComponent(); - - if (simulator == null) - throw new ArgumentNullException("simulator", "Simulator object cannot be null."); - - this.simulator = simulator; - Viewer = viewer; - MapDataProvider = new MapDataProvider(this); - MapThemeProvider = new MapThemeProvider(); - nodes = simulator.TDB.TrackDB.TrackNodes; - - InitializeForm(); - - ViewWindow = new RectangleF(0, 0, 5000f, 5000f); - mapResolutionUpDown.Accelerations.Add(new NumericUpDownAcceleration(1, 100)); - /*boxSetSignal.Items.Add("System Controlled"); - boxSetSignal.Items.Add("Stop"); - boxSetSignal.Items.Add("Approach"); - boxSetSignal.Items.Add("Proceed"); - chkAllowUserSwitch.Checked = false;*/ - selectedTrainList = new List(); - - InitializeData(); - InitializeImage(); - - // Initialise the timer used to handle user input - UITimer = new Timer(); - UITimer.Interval = 100; - UITimer.Tick += new EventHandler(UITimer_Tick); - UITimer.Start(); - } - - void InitializeForm() - { - MapDataProvider.SetControls(); - MapThemeProvider.InitializeThemes(); - Theme = MapThemeProvider.GetTheme(ThemeName); - - float[] dashPattern = { 4, 2 }; - ZoomTargetPen.DashPattern = dashPattern; - pathPen.DashPattern = dashPattern; - } - - #region initData - private void InitializeData() - { - /*if (!loaded) - { - // do this only once - loaded = true; - //trackSections.DataSource = new List(simulator.InterlockingSystem.Tracks.Values).ToArray(); - Localizer.Localize(this, Viewer.Catalog); - }*/ - - switchItemsDrawn = new List(); - signalItemsDrawn = new List(); - switches = new List(); - for (int i = 0; i < nodes.Length; i++) - { - TrackNode currNode = nodes[i]; - - if (currNode != null) - { - if (currNode.TrEndNode) - { - //buffers.Add(new PointF(currNode.UiD.TileX * 2048 + currNode.UiD.X, currNode.UiD.TileZ * 2048 + currNode.UiD.Z)); - } - else if (currNode.TrVectorNode != null) - { - - if (currNode.TrVectorNode.TrVectorSections.Length > 1) - { - AddSegments(segments, currNode, currNode.TrVectorNode.TrVectorSections, ref minX, ref minY, ref maxX, ref maxY, simulator); - } - else - { - TrVectorSection s = currNode.TrVectorNode.TrVectorSections[0]; - - foreach (TrPin pin in currNode.TrPins) - { - - TrackNode connectedNode = nodes[pin.Link]; - - dVector A = new dVector(s.TileX, s.X, s.TileZ, +s.Z); - dVector B = new dVector(connectedNode.UiD.TileX, connectedNode.UiD.X, connectedNode.UiD.TileZ, connectedNode.UiD.Z); - segments.Add(new LineSegment(A, B, /*s.InterlockingTrack.IsOccupied*/ false, null)); - } - } - } - else if (currNode.TrJunctionNode != null) - { - foreach (TrPin pin in currNode.TrPins) - { - var vectorSections = nodes[pin.Link]?.TrVectorNode?.TrVectorSections; - if (vectorSections == null || vectorSections.Length < 1) - continue; - TrVectorSection item = pin.Direction == 1 ? vectorSections.First() : vectorSections.Last(); - dVector A = new dVector(currNode.UiD.TileX, currNode.UiD.X, currNode.UiD.TileZ, +currNode.UiD.Z); - dVector B = new dVector(item.TileX, +item.X, item.TileZ, +item.Z); - var x = dVector.DistanceSqr(A, B); - if (x < 0.1) continue; - segments.Add(new LineSegment(B, A, /*s.InterlockingTrack.IsOccupied*/ false, item)); - } - switches.Add(new SwitchWidget(currNode)); - } - } - } - - var maxsize = maxX - minX > maxY - minY ? maxX - minX : maxY - minY; - // Take up to next 500 - maxsize = (int)((maxsize / 100) + 1) * 500; - mapResolutionUpDown.Maximum = (decimal)maxsize; - Inited = true; - - if (simulator.TDB == null || simulator.TDB.TrackDB == null || simulator.TDB.TrackDB.TrItemTable == null) - return; - - MapDataProvider.PopulateItemLists(); - } - - bool Inited; - public List segments = new List(); - public List switches; - public List signals = new List(); - public List sidings = new List(); - public List platforms = new List(); - - /// - /// Initialises the picturebox and the image it contains. - /// - public void InitializeImage() - { - // When minimizing the window, `mapCanvas.Width` gets reported as 0 - // This crashes `System.Drawing.dll`, hence the check below - if (mapCanvas.Width <= 0 || mapCanvas.Height <= 0) return; - - mapCanvas.Image?.Dispose(); - mapCanvas.Image = new Bitmap(mapCanvas.Width, mapCanvas.Height); - } - #endregion - - #region playersList - readonly List PlayersList = new List(); - - public void AddPlayer(string name) - { - PlayersList.Add(name); - } - - // TODO: Colour code players based on their roles - // TODO: FUNCTION NOT WORKING CORRECTLY - public void CheckPlayers() - { - if (!MPManager.IsMultiPlayer() || MPManager.OnlineTrains == null || MPManager.OnlineTrains.Players == null) return; - var players = MPManager.OnlineTrains.Players; - var username = MPManager.GetUserName(); - players = players.Concat(MPManager.Instance().lostPlayer).ToDictionary(x => x.Key, x => x.Value); - - bool PlayersListChanged = false; - - // Add myself - if (!PlayersList.Contains(username)) - { - AddPlayer(username); - PlayersListChanged = true; - } - - foreach (var p in players) - { - if (PlayersList.Contains(p.Key)) continue; - AddPlayer(p.Key); - PlayersListChanged = true; - } - - // Remove players from `PlayersList` if they are no longer on the server - foreach (var p in PlayersList.ToList()) // https://stackoverflow.com/a/604843/ - { - if (players.ContainsKey(p) || p == username) continue; - PlayersList.Remove(p); - PlayersListChanged = true; - } - - // If `PlayersList` hasn't changed since we've last checked, we should not clear/update - // `playersView` to avoid flickering - if (!PlayersListChanged) return; - - playersView.Items.Clear(); - Console.Beep(); - foreach (var p in PlayersList) - { - if (p == username) - playersView.Items.Add(p); - - if (MPManager.Instance().aiderList.Contains(p)) - { - playersView.Items.Add(p + " (Helper)"); - } - else if (MPManager.Instance().lostPlayer.ContainsKey(p)) - { - playersView.Items.Add(p + " (Disconnected)"); - } - else - { - playersView.Items.Add(p); - } - } - } - #endregion - - #region Draw - public bool firstShow = true; - public bool followTrain; - public float subX, subY; - public float oldWidth; - public float oldHeight; - - /// - /// Regenerates the 2D view. At the moment, examines the track network - /// each time the view is drawn. Later, the traversal and drawing can be separated. - /// - public void GenerateView(bool dragging = false) - { - if (!Inited) return; - - timeLabel.Visible = showTimeCheckbox.Checked; - if (showTimeCheckbox.Checked) - MapDataProvider.ShowSimulationTime(); - - if (mapCanvas.Image == null || firstShow) InitializeImage(); - - if (firstShow || followTrain) - { - //see who should I look at: - //if the player is selected in the avatar list, show the player, otherwise, show the one with the lowest index - WorldPosition pos = Program.Simulator.PlayerLocomotive == null ? Program.Simulator.Trains.First().Cars.First().WorldPosition : Program.Simulator.PlayerLocomotive.WorldPosition; - if (playersView.SelectedIndices.Count > 0 && !playersView.SelectedIndices.Contains(0)) - { - int i = playersView.SelectedIndices.Cast().Min(); - string name = (playersView.Items[i].Text ?? "").Split(' ').First().Trim(); - if (MPManager.OnlineTrains.Players.TryGetValue(name, out OnlinePlayer player)) - pos = player?.Train?.Cars?.FirstOrDefault()?.WorldPosition; - else if (MPManager.Instance().lostPlayer.TryGetValue(name, out OnlinePlayer lost)) - pos = lost?.Train?.Cars?.FirstOrDefault()?.WorldPosition; - } - if (pos == null) - pos = PickedTrain?.Cars?.FirstOrDefault()?.WorldPosition; - if (pos != null) - { - var ploc = new PointF((pos.TileX * 2048) + pos.Location.X, (pos.TileZ * 2048) + pos.Location.Z); - ViewWindow.X = ploc.X - minX - (ViewWindow.Width / 2); ViewWindow.Y = ploc.Y - minY - (ViewWindow.Width / 2); - firstShow = false; - } - } - - CheckPlayers(); - - using (Graphics g = Graphics.FromImage(mapCanvas.Image)) - { - // Optional anti-aliasing - if (useAntiAliasingCheckbox.Checked == true) - g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; - - subX = minX + ViewWindow.X; subY = minY + ViewWindow.Y; - g.Clear(MapCanvasColor); - - xScale = mapCanvas.Width / ViewWindow.Width; - yScale = mapCanvas.Height / ViewWindow.Height; - xScale = yScale = Math.Max(xScale, yScale); // Make X and Y scales the same to maintain correct angles - - // Set the default pen to represent 1 meter - var scale = (float)Math.Round(xScale); // Round to nearest pixels/meter - var penWidth = (int)MathHelper.Clamp(scale, 1, 4); // Keep 1 <= width <= 4 pixels - - PointF[] points = new PointF[3]; - Pen p = grayPen; - - // TODO: Refactor - p.Width = MathHelper.Clamp(xScale, 1, 3); - greenPen.Width = orangePen.Width = redPen.Width = p.Width; pathPen.Width = 2 * p.Width; - trainPen.Width = p.Width * 6; - - grayPen.Width = greenPen.Width = orangePen.Width = redPen.Width = penWidth; - pathPen.Width = penWidth * 2; - - var forwardDist = 100 / xScale; if (forwardDist < 5) forwardDist = 5; - - /*PointF scaledA = new PointF(0, 0); - PointF scaledB = new PointF(0, 0); - PointF scaledC = new PointF(0, 0);*/ - - // Draw platforms first because track is drawn over the thicker platform line - DrawPlatforms(g, penWidth); - - PointF scaledA, scaledB; - DrawTrack(g, p, out scaledA, out scaledB); - - if (Dragging == false) - { - // Draw trains and path - DrawTrains(g, scaledA, scaledB); - - // Keep widgetWidth <= 15 pixels - var widgetWidth = Math.Min(penWidth * 6, 15); - - // Draw signals on top of path so they are easier to see. - signalItemsDrawn.Clear(); - ShowSignals(g, scaledB, widgetWidth); - - // Draw switches - switchItemsDrawn.Clear(); - ShowSwitches(g, widgetWidth); - - // Draw labels for sidings and platforms last so they go on top for readability - MapDataProvider.CleanTextCells(); // Empty the listing of labels ready for adding labels again - ShowPlatformLabels(g); // Platforms take priority over sidings and signal states - ShowSidingLabels(g); - } - - DrawZoomTarget(g); - } - - mapCanvas.Invalidate(); // Triggers a re-paint - } - - private void DrawPlatforms(Graphics g, int penWidth) - { - if (!showPlatformsCheckbox.Checked) - return; - - // Platforms can be obtrusive, so draw in solid blue only when zoomed in and fade them as we zoom out - switch (penWidth) - { - case 1: - PlatformPen.Color = Color.FromArgb(174, 214, 241); break; - case 2: - PlatformPen.Color = Color.FromArgb(93, 173, 226); break; - default: - PlatformPen.Color = Color.FromArgb(46, 134, 193); break; - } - - var width = grayPen.Width * 3; - PlatformPen.Width = width; - foreach (var p in platforms) - { - var scaledA = new PointF((p.Extent1.X - subX) * xScale, mapCanvas.Height - ((p.Extent1.Y - subY) * yScale)); - var scaledB = new PointF((p.Extent2.X - subX) * xScale, mapCanvas.Height - ((p.Extent2.Y - subY) * yScale)); - - MapDataProvider.FixForBadData(width, ref scaledA, ref scaledB, p.Extent1, p.Extent2); - g.DrawLine(PlatformPen, scaledA, scaledB); - } - } - - private void DrawTrack(Graphics g, Pen p, out PointF scaledA, out PointF scaledB) - { - - PointF[] points = new PointF[3]; - scaledA = new PointF(0, 0); - scaledB = new PointF(0, 0); - PointF scaledC = new PointF(0, 0); - foreach (var line in segments) - { - scaledA.X = ((line.A.TileX * 2048) - subX + (float)line.A.X) * xScale; - scaledA.Y = mapCanvas.Height - (((line.A.TileZ * 2048) - subY + (float)line.A.Z) * yScale); - scaledB.X = ((line.B.TileX * 2048) - subX + (float)line.B.X) * xScale; - scaledB.Y = mapCanvas.Height - (((line.B.TileZ * 2048) - subY + (float)line.B.Z) * yScale); - - if ((scaledA.X < 0 && scaledB.X < 0) - || (scaledA.Y < 0 && scaledB.Y < 0)) - continue; - - if (line.isCurved == true) - { - scaledC.X = ((float)line.C.X - subX) * xScale; scaledC.Y = mapCanvas.Height - (((float)line.C.Z - subY) * yScale); - points[0] = scaledA; points[1] = scaledC; points[2] = scaledB; - g.DrawCurve(TrackPen, points); - } - else g.DrawLine(TrackPen, scaledA, scaledB); - } - } - - private void DrawTrains(Graphics g, PointF scaledA, PointF scaledB) - { - var margin = 30 * xScale; // Margins to determine if we want to draw a train - var margin2 = 5000 * xScale; - - // Variable for drawing train path - var mDist = 5000f; var pDist = 50; // Segment length when drawing path - - selectedTrainList.Clear(); - - /*if (simulator.TimetableMode) - { - // Add the player's train... - if (simulator.PlayerLocomotive.Train is AITrain) - selectedTrainList.Add(simulator.PlayerLocomotive.Train as AITrain); - - // ...then all the AI trains, including static consists. - foreach (AITrain train in simulator.AI.AITrains) - selectedTrainList.Add(train); - } - else - {*/ - foreach (var train in simulator.Trains) - selectedTrainList.Add(train); - /*}*/ - - foreach (var train in selectedTrainList) - { - string trainName; - WorldPosition worldPos; - TrainCar locoCar = null; - if (train.LeadLocomotive != null) - { - trainName = train.GetTrainName(train.LeadLocomotive.CarID); - locoCar = train.LeadLocomotive; - } - else if (train.Cars != null && train.Cars.Count > 0) - { - trainName = train.GetTrainName(train.Cars[0].CarID); - if (train.TrainType == Train.TRAINTYPE.AI || train.TrainType == Train.TRAINTYPE.STATIC) - trainName = train.Number.ToString() + ":" + train.Name; - - locoCar = train.Cars.Where(r => r is MSTSLocomotive).FirstOrDefault(); - - // Skip trains with no loco - if (locoCar == null) - locoCar = train.Cars[0]; - } - else - continue; - - // Draw the path, then each car of the train, then maybe the name - var loc = train.FrontTDBTraveller.WorldLocation; - float x = ((loc.TileX * 2048) + loc.Location.X - subX) * xScale; - float y = mapCanvas.Height - (((loc.TileZ * 2048) + loc.Location.Z - subY) * yScale); - - // If train out of view then skip it. - if (x < -margin2 || y < -margin2) - continue; - - DrawTrainPath(train, subX, subY, pathPen, g, scaledA, scaledB, pDist, mDist); - - // If zoomed out, so train occupies less than 2 * minTrainPx pixels, then - // draw the train as 2 squares of combined length minTrainPx. - const int minTrainPx = 24; - - // pen | train | Values for a good presentation - // 1 10 - // 2 12 - // 3 14 - // 4 16 - trainPen.Width = grayPen.Width * 6; - - var minTrainLengthM = minTrainPx / xScale; // Calculate length equivalent to a set number of pixels - bool drawEveryCar = IsDrawEveryCar(train, minTrainLengthM); - - foreach (var car in train.Cars) - DrawCar(g, train, car, locoCar, margin, minTrainPx, drawEveryCar); - - worldPos = locoCar.WorldPosition; - var scaledTrain = new PointF - { - X = ((worldPos.TileX * 2048) - subX + worldPos.Location.X) * xScale, - Y = -25 + mapCanvas.Height - (((worldPos.TileZ * 2048) - subY + worldPos.Location.Z) * yScale) - }; - if (showTrainLabelsCheckbox.Checked) - DrawTrainLabels(g, train, trainName, scaledTrain); - } - } - - private void DrawCar(Graphics g, Train train, TrainCar car, TrainCar locoCar, float margin, int minTrainPx, bool drawEveryCar) - { - if (drawEveryCar == false) - // Skip the intermediate cars - if (car != train.Cars.First() && car != train.Cars.Last()) - return; - - var t = new Traveller(train.RearTDBTraveller); - var worldPos = car.WorldPosition; - var dist = t.DistanceTo(worldPos.WorldLocation.TileX, worldPos.WorldLocation.TileZ, worldPos.WorldLocation.Location.X, worldPos.WorldLocation.Location.Y, worldPos.WorldLocation.Location.Z); - if (dist > -1) - { - var scaledTrain = new PointF(); - float x; - float y; - if (drawEveryCar) - { - t.Move(dist + (car.CarLengthM / 2)); // Move along from centre of car to front of car - x = ((t.TileX * 2048) + t.Location.X - subX) * xScale; - y = mapCanvas.Height - (((t.TileZ * 2048) + t.Location.Z - subY) * yScale); - - // If car out of view then skip it. - if (x < -margin || y < -margin) - return; - - t.Move(-car.CarLengthM + (2 / xScale)); // Move from front of car to rear less 1 pixel to create a visible gap // TODO: investigate `(1 / xScale)` ==> `(2 / xScale)` car gap consequences - scaledTrain.X = x; scaledTrain.Y = y; - } - else // Draw the train as 2 boxes of fixed size - { - trainPen.Width = minTrainPx / 2; - if (car == train.Cars.First()) - { - // Draw first half a train back from the front of the first car as abox - t.Move(dist + (car.CarLengthM / 2)); - x = ((t.TileX * 2048) + t.Location.X - subX) * xScale; - y = mapCanvas.Height - (((t.TileZ * 2048) + t.Location.Z - subY) * yScale); - - // If car out of view then skip it. - if (x < -margin || y < -margin) - return; - - t.Move(-(minTrainPx - 2) / xScale / 2); // Move from front of car to rear less 1 pixel to create a visible gap - } - else // car == t.Cars.Last() - { - // Draw half a train back from the rear of the first box - worldPos = train.Cars.First().WorldPosition; - dist = t.DistanceTo(worldPos.WorldLocation.TileX, worldPos.WorldLocation.TileZ, worldPos.WorldLocation.Location.X, worldPos.WorldLocation.Location.Y, worldPos.WorldLocation.Location.Z); - t.Move(dist + (train.Cars.First().CarLengthM / 2) - (minTrainPx / xScale / 2)); - x = ((t.TileX * 2048) + t.Location.X - subX) * xScale; - y = mapCanvas.Height - (((t.TileZ * 2048) + t.Location.Z - subY) * yScale); - if (x < -margin || y < -margin) - return; - t.Move(-minTrainPx / xScale / 2); - } - scaledTrain.X = x; scaledTrain.Y = y; - } - x = ((t.TileX * 2048) + t.Location.X - subX) * xScale; - y = mapCanvas.Height - (((t.TileZ * 2048) + t.Location.Z - subY) * yScale); - - // If car out of view then skip it. - if (x < -margin || y < -margin) - return; - - SetTrainColor(train, locoCar, car); - g.DrawLine(trainPen, new PointF(x, y), scaledTrain); - } - } - - private void SetTrainColor(Train t, TrainCar locoCar, TrainCar car) - { - // Draw train in green with locos in brown - // HSL values - // Saturation: 100/100 - // Hue: if loco then H=50/360 else H=120/360 - // Lightness: if active then L=40/100 else L=30/100 - // RGB values - // active loco: RGB 204,170,0 - // inactive loco: RGB 153,128,0 - // active car: RGB 0,204,0 - // inactive car: RGB 0,153,0 - trainPen.Color = MapDataProvider.IsActiveTrain(t as AITrain) - ? car is MSTSLocomotive - ? (car == locoCar) ? Color.FromArgb(204, 170, 0) : Color.FromArgb(153, 128, 0) - : Color.FromArgb(0, 204, 0) - : car is MSTSLocomotive ? Color.FromArgb(153, 128, 0) : Color.FromArgb(0, 153, 0); - - if (t.TrainType == Train.TRAINTYPE.STATIC || (t.TrainType == Train.TRAINTYPE.AI && t.GetAIMovementState() == AITrain.AI_MOVEMENT_STATE.AI_STATIC)) - { - trainPen.Color = car is MSTSLocomotive ? Color.FromArgb(19, 185, 160) : Color.FromArgb(83, 237, 214); - } - - // Draw player train with loco in red - if (t.TrainType == Train.TRAINTYPE.PLAYER && car == locoCar) - trainPen.Color = Color.Red; - } - - private void DrawTrainLabels(Graphics g, Train t, string trainName, PointF scaledTrain) - { - /*WorldPosition worldPos = firstCar.WorldPosition; - scaledTrain.X = ((worldPos.TileX * 2048) - subX + worldPos.Location.X) * xScale; - scaledTrain.Y = -25 + mapCanvas.Height - (((worldPos.TileZ * 2048) - subY + worldPos.Location.Z) * yScale);*/ - if (showActiveTrainsRadio.Checked) - { - if (t is AITrain && MapDataProvider.IsActiveTrain(t as AITrain)) - ShowTrainNameAndState(g, scaledTrain, t, trainName); - } - else - { - ShowTrainNameAndState(g, scaledTrain, t, trainName); - } - } - - private void ShowTrainNameAndState(Graphics g, PointF scaledItem, Train t, string trainName) - { - if (simulator.TimetableMode) - { - if (t is TTTrain tTTrain) - { - // Remove name of timetable, e.g.: ":SCE" - var lastPos = trainName.LastIndexOf(":"); - var shortName = (lastPos > 0) ? trainName.Substring(0, lastPos) : trainName; - - if (MapDataProvider.IsActiveTrain(tTTrain)) - { - if (showTrainStateCheckbox.Checked) - { - // 4:AI mode, 6:Mode, 7:Auth, 9:Signal, 12:Path - var status = tTTrain.GetStatus(Viewer.MilepostUnitsMetric); - - // Add in fields 4 and 7 - status = tTTrain.AddMovementState(status, Viewer.MilepostUnitsMetric); - - var statuses = $"{status[4]} {status[6]} {status[7]} {status[9]}"; - - // Add path if it contains any deadlock information - if (MapDataProvider.ContainsDeadlockIndicators(status[12])) - statuses += status[12]; - - g.DrawString($"{shortName} {statuses}", trainFont, trainBrush, scaledItem); - } - else - g.DrawString(shortName, trainFont, trainBrush, scaledItem); - } - else - g.DrawString(shortName, trainFont, InactiveTrainBrush, scaledItem); - } - } - else - g.DrawString(trainName, trainFont, trainBrush, scaledItem); - } - - private void ShowSwitches(Graphics g, float width) - { - if (!showSwitchesCheckbox.Checked) - return; - - for (var i = 0; i < switches.Count; i++) - { - SwitchWidget sw = switches[i]; - - var x = (sw.Location.X - subX) * xScale; - var y = mapCanvas.Height - ((sw.Location.Y - subY) * yScale); - if (x < 0 || y < 0) - continue; - - var scaledItem = new PointF() { X = x, Y = y }; - - if (sw.Item.TrJunctionNode.SelectedRoute == sw.main) - g.FillEllipse(new SolidBrush(Color.FromArgb(93, 64, 55)), DispatchViewer.GetRect(scaledItem, width)); - else - g.FillEllipse(new SolidBrush(Color.FromArgb(161, 136, 127)), DispatchViewer.GetRect(scaledItem, width)); - - sw.Location2D.X = scaledItem.X; sw.Location2D.Y = scaledItem.Y; - switchItemsDrawn.Add(sw); - } - } - - private void ShowSignals(Graphics g, PointF scaledB, float width) - { - if (!showSignalsCheckbox.Checked) - return; - - foreach (var s in signals) - { - if (float.IsNaN(s.Location.X) || float.IsNaN(s.Location.Y)) - continue; - var x = (s.Location.X - subX) * xScale; - var y = mapCanvas.Height - ((s.Location.Y - subY) * yScale); - if (x < 0 || y < 0) - continue; - - var scaledItem = new PointF() { X = x, Y = y }; - s.Location2D.X = scaledItem.X; s.Location2D.Y = scaledItem.Y; - if (s.Signal.isSignalNormal()) - { - var color = new SolidBrush(Color.FromArgb(76, 175, 80)); - var pen = greenPen; - if (s.IsProceed == 0) - { - } - else if (s.IsProceed == 1) - { - color = new SolidBrush(Color.FromArgb(255, 235, 59)); - pen = orangePen; - } - else - { - color = new SolidBrush(Color.FromArgb(244, 67, 54)); - pen = redPen; - } - g.FillEllipse(color, DispatchViewer.GetRect(scaledItem, width)); - signalItemsDrawn.Add(s); - if (s.hasDir) - { - scaledB.X = (s.Dir.X - subX) * xScale; scaledB.Y = mapCanvas.Height - ((s.Dir.Y - subY) * yScale); - g.DrawLine(pen, scaledItem, scaledB); - } - ShowSignalState(g, scaledItem, s); - } - } - } - - private void ShowSignalState(Graphics g, PointF scaledItem, SignalWidget sw) - { - if (!showSignalStateCheckbox.Checked) - return; - - var item = sw.Item as SignalItem; - var trainNumber = sw.Signal?.enabledTrain?.Train?.Number; - var trainString = (trainNumber == null) ? "" : $" train: {trainNumber}"; - var offset = 0; - var position = scaledItem; - foreach (var signalHead in sw.Signal.SignalHeads) - { - offset++; - position.X += offset * 10; - position.Y += offset * 15; - var text = $" {item?.SigObj} {signalHead.SignalTypeName} {signalHead.state} {trainString}"; - scaledItem.Y = MapDataProvider.GetUnusedYLocation(scaledItem.X, mapCanvas.Height - ((sw.Location.Y - subY) * yScale), text); - if (scaledItem.Y >= 0f) // -1 indicates no free slot to draw label - g.DrawString(text, SignalFont, SignalBrush, scaledItem); - } - - } - - private void ShowSidingLabels(Graphics g) - { - if (!showSidingLabelsCheckbox.Checked) - return; - - foreach (var s in sidings) - { - var scaledItem = new PointF(); - - scaledItem.X = (s.Location.X - subX) * xScale; - scaledItem.Y = MapDataProvider.GetUnusedYLocation(scaledItem.X, mapCanvas.Height - ((s.Location.Y - subY) * yScale), s.Name); - if (scaledItem.Y >= 0f) // -1 indicates no free slot to draw label - g.DrawString(s.Name, sidingFont, sidingBrush, scaledItem); - } - } - - private void ShowPlatformLabels(Graphics g) - { - var platformMarginPxX = 5; - - if (!showPlatformLabelsCheckbox.Checked) - return; - - foreach (var p in platforms) - { - var scaledItem = new PointF(); - scaledItem.X = ((p.Location.X - subX) * xScale) + platformMarginPxX; - var yPixels = mapCanvas.Height - ((p.Location.Y - subY) * yScale); - - // If track is close to horizontal, then start label search 1 row down to minimise overwriting platform line. - if (p.Extent1.X != p.Extent2.X - && Math.Abs((p.Extent1.Y - p.Extent2.Y) / (p.Extent1.X - p.Extent2.X)) < 0.1) - yPixels += DispatchViewer.spacing; - - scaledItem.Y = MapDataProvider.GetUnusedYLocation(scaledItem.X, mapCanvas.Height - ((p.Location.Y - subY) * yScale), p.Name); - if (scaledItem.Y >= 0f) // -1 indicates no free slot to draw label - g.DrawString(p.Name, PlatformFont, PlatformBrush, scaledItem); - } - } - - /// - /// If the train is long enough then draw every car else just draw it as one or two blocks - /// - /// - /// - /// - private bool IsDrawEveryCar(Train train, float minTrainLengthM) - { - float trainLengthM = 0f; - foreach (var car in train.Cars) - { - trainLengthM += car.CarLengthM; - if (trainLengthM > minTrainLengthM) - { - return true; - } - } - return false; - } - - /// - /// Indicates the location around which the image is zoomed. - /// If user drags an item of interest into this target box and zooms in, the item will remain in view. - /// - /// - private void DrawZoomTarget(Graphics g) - { - if (!Dragging) - return; - - const int size = 24; - var top = (mapCanvas.Height / 2) - (size / 2); - var left = (mapCanvas.Width / 2) - (size / 2); - g.DrawRectangle(ZoomTargetPen, left, top, size, size); - - } - - public Vector2[][] alignedTextY; - public int[] alignedTextNum; - public const int spacing = 12; - - const float SignalErrorDistance = 100; - const float SignalWarningDistance = 500; - const float DisplayDistance = 1000; - const float DisplaySegmentLength = 10; - const float MaximumSectionDistance = 10000; - - readonly Dictionary Cache = new Dictionary(); - SignallingDebugWindow.TrackSectionCacheEntry GetCacheEntry(Traveller position) - { - SignallingDebugWindow.TrackSectionCacheEntry rv; - if (Cache.TryGetValue(position.TrackNodeIndex, out rv) && (rv.Direction == position.Direction)) - return rv; - Cache[position.TrackNodeIndex] = rv = new SignallingDebugWindow.TrackSectionCacheEntry() - { - Direction = position.Direction, - Length = 0, - Objects = new List(), - }; - var nodeIndex = position.TrackNodeIndex; - var trackNode = new Traveller(position); - while (true) - { - rv.Length += MaximumSectionDistance - trackNode.MoveInSection(MaximumSectionDistance); - if (!trackNode.NextSection()) - break; - if (trackNode.IsEnd) - rv.Objects.Add(new SignallingDebugWindow.TrackSectionEndOfLine() { Distance = rv.Length }); - else if (trackNode.IsJunction) - rv.Objects.Add(new SignallingDebugWindow.TrackSectionSwitch() { Distance = rv.Length, TrackNode = trackNode.TN, NodeIndex = nodeIndex }); - else - rv.Objects.Add(new SignallingDebugWindow.TrackSectionObject() { Distance = rv.Length }); // Always have an object at the end. - if (trackNode.TrackNodeIndex != nodeIndex) - break; - } - trackNode = new Traveller(position); - - rv.Objects = rv.Objects.OrderBy(tso => tso.Distance).ToList(); - return rv; - } - - //draw the train path if it is within the window - public void DrawTrainPath(Train train, float subX, float subY, Pen pathPen, Graphics g, PointF scaledA, PointF scaledB, float stepDist, float MaximumSectionDistance) - { - if (DrawPath != true) return; - bool ok = false; - if (train == Program.Simulator.PlayerLocomotive.Train) ok = true; - if (MPManager.IsMultiPlayer()) - { - if (MPManager.OnlineTrains.findTrain(train)) - ok = true; - } - if (train.FirstCar != null & train.FirstCar.CarID.Contains("AI")) // AI train - ok = true; - if (Math.Abs(train.SpeedMpS) > 0.001) - ok = true; - - if (ok == false) return; - - var DisplayDistance = MaximumSectionDistance; - var position = train.MUDirection != Direction.Reverse ? new Traveller(train.FrontTDBTraveller) : new Traveller(train.RearTDBTraveller, Traveller.TravellerDirection.Backward); - var caches = new List(); - // Work backwards until we end up on a different track section. - var cacheNode = new Traveller(position); - cacheNode.ReverseDirection(); - var initialNodeOffsetCount = 0; - while (cacheNode.TrackNodeIndex == position.TrackNodeIndex && cacheNode.NextSection()) - initialNodeOffsetCount++; - // Now do it again, but don't go the last track section (because it is from a different track node). - cacheNode = new Traveller(position); - cacheNode.ReverseDirection(); - for (var i = 1; i < initialNodeOffsetCount; i++) - cacheNode.NextSection(); - // Push the location right up to the end of the section. - cacheNode.MoveInSection(MaximumSectionDistance); - // Now back facing the right way, calculate the distance to the train location. - cacheNode.ReverseDirection(); - var initialNodeOffset = cacheNode.DistanceTo(position.TileX, position.TileZ, position.X, position.Y, position.Z); - // Go and collect all the cache entries for the visible range of vector nodes (straights, curves). - var totalDistance = 0f; - while (!cacheNode.IsEnd && totalDistance - initialNodeOffset < DisplayDistance) - { - if (cacheNode.IsTrack) - { - var cache = GetCacheEntry(cacheNode); - cache.Age = 0; - caches.Add(cache); - totalDistance += cache.Length; - } - var nodeIndex = cacheNode.TrackNodeIndex; - while (cacheNode.TrackNodeIndex == nodeIndex && cacheNode.NextSection()) ; - } - - var switchErrorDistance = initialNodeOffset + DisplayDistance + SignalWarningDistance; - var signalErrorDistance = initialNodeOffset + DisplayDistance + SignalWarningDistance; - var currentDistance = 0f; - foreach (var cache in caches) - { - foreach (var obj in cache.Objects) - { - var objDistance = currentDistance + obj.Distance; - if (objDistance < initialNodeOffset) - continue; - - if (obj is SignallingDebugWindow.TrackSectionSwitch switchObj) - { - for (var pin = switchObj.TrackNode.Inpins; pin < switchObj.TrackNode.Inpins + switchObj.TrackNode.Outpins; pin++) - { - if (switchObj.TrackNode.TrPins[pin].Link == switchObj.NodeIndex) - { - if (pin - switchObj.TrackNode.Inpins != switchObj.TrackNode.TrJunctionNode.SelectedRoute) - switchErrorDistance = objDistance; - break; - } - } - if (switchErrorDistance < DisplayDistance) - break; - } - - } - if (switchErrorDistance < DisplayDistance || signalErrorDistance < DisplayDistance) - break; - currentDistance += cache.Length; - } - - var currentPosition = new Traveller(position); - currentPosition.Move(-initialNodeOffset); - currentDistance = 0; - - foreach (var cache in caches) - { - var lastObjDistance = 0f; - foreach (var obj in cache.Objects) - { - var objDistance = currentDistance + obj.Distance; - - for (var step = lastObjDistance; step < obj.Distance; step += DisplaySegmentLength) - { - var stepDistance = currentDistance + step; - var stepLength = DisplaySegmentLength > obj.Distance - step ? obj.Distance - step : DisplaySegmentLength; - var previousLocation = currentPosition.WorldLocation; - currentPosition.Move(stepLength); - if (stepDistance + stepLength >= initialNodeOffset && stepDistance <= initialNodeOffset + DisplayDistance) - { - var currentLocation = currentPosition.WorldLocation; - scaledA.X = (float)(((previousLocation.TileX * WorldLocation.TileSize) + previousLocation.Location.X - subX) * xScale); - scaledA.Y = (float)(mapCanvas.Height - (((previousLocation.TileZ * WorldLocation.TileSize) + previousLocation.Location.Z - subY) * yScale)); - scaledB.X = (float)(((currentLocation.TileX * WorldLocation.TileSize) + currentLocation.Location.X - subX) * xScale); - scaledB.Y = (float)(mapCanvas.Height - (((currentPosition.TileZ * WorldLocation.TileSize) + currentPosition.Location.Z - subY) * yScale)); g.DrawLine(pathPen, scaledA, scaledB); - } - } - lastObjDistance = obj.Distance; - - if (objDistance >= switchErrorDistance) - break; - } - currentDistance += cache.Length; - if (currentDistance >= switchErrorDistance) - break; - - } - - currentPosition = new Traveller(position); - currentPosition.Move(-initialNodeOffset); - currentDistance = 0; - foreach (var cache in caches) - { - var lastObjDistance = 0f; - foreach (var obj in cache.Objects) - { - currentPosition.Move(obj.Distance - lastObjDistance); - lastObjDistance = obj.Distance; - - var objDistance = currentDistance + obj.Distance; - if (objDistance < initialNodeOffset || objDistance > initialNodeOffset + DisplayDistance) - continue; - - if (obj is SignallingDebugWindow.TrackSectionSwitch switchObj) - { - for (var pin = switchObj.TrackNode.Inpins; pin < switchObj.TrackNode.Inpins + switchObj.TrackNode.Outpins; pin++) - { - if (switchObj.TrackNode.TrPins[pin].Link == switchObj.NodeIndex && pin - switchObj.TrackNode.Inpins != switchObj.TrackNode.TrJunctionNode.SelectedRoute) - { - foreach (var sw in switchItemsDrawn) - { - if (sw.Item.TrJunctionNode == switchObj.TrackNode.TrJunctionNode) - { - var r = 6 * greenPen.Width; - g.DrawLine(pathPen, new PointF(sw.Location2D.X - r, sw.Location2D.Y - r), new PointF(sw.Location2D.X + r, sw.Location2D.Y + r)); - g.DrawLine(pathPen, new PointF(sw.Location2D.X - r, sw.Location2D.Y + r), new PointF(sw.Location2D.X + r, sw.Location2D.Y - r)); - break; - } - } - } - } - } - - if (objDistance >= switchErrorDistance) - break; - } - currentDistance += cache.Length; - if (currentDistance >= switchErrorDistance) - break; - } - // Clean up any cache entries who haven't been using for 30 seconds. - var oldCaches = Cache.Where(kvp => kvp.Value.Age > 30 * 4).ToArray(); - foreach (var oldCache in oldCaches) - Cache.Remove(oldCache.Key); - - } - #endregion - - #region themes - private void ApplyThemeRecursively(System.Windows.Forms.Control parent) - { - foreach (System.Windows.Forms.Control c in parent.Controls) - { - if (c is Button button && c?.Tag?.ToString() != "mapCustomization") - { - Button b = button; - b.BackColor = Theme.BackColor; - b.ForeColor = Theme.ForeColor; - b.FlatStyle = Theme.FlatStyle; - } - else if (c is GroupBox || c is Panel) - { - c.BackColor = Theme.PanelBackColor; - c.ForeColor = Theme.ForeColor; - } - else - { - c.BackColor = Theme.PanelBackColor; - c.ForeColor = Theme.ForeColor; - } - - ApplyThemeRecursively(c); - } - } - #endregion - - /// - /// Generates a rectangle representing a dot being drawn. - /// - /// Center point of the dot, in pixels. - /// Size of the dot's diameter, in pixels - /// - public static RectangleF GetRect(PointF p, float size) - { - return new RectangleF(p.X - (size / 2f), p.Y - (size / 2f), size, size); - } - - /// - /// Generates line segments from an array of TrVectorSection. Also computes - /// the bounds of the entire route being drawn. - /// - /// - /// - /// - /// - /// - /// - /// - private static void AddSegments(List segments, TrackNode node, TrVectorSection[] items, ref float minX, ref float minY, ref float maxX, ref float maxY, Simulator simulator) - { - - bool occupied = false; - - double tempX1, tempX2, tempZ1, tempZ2; - - for (int i = 0; i < items.Length - 1; i++) - { - dVector A = new dVector(items[i].TileX, items[i].X, items[i].TileZ, items[i].Z); - dVector B = new dVector(items[i + 1].TileX, items[i + 1].X, items[i + 1].TileZ, items[i + 1].Z); - - tempX1 = (A.TileX * 2048) + A.X; tempX2 = (B.TileX * 2048) + B.X; - tempZ1 = (A.TileZ * 2048) + A.Z; tempZ2 = (B.TileZ * 2048) + B.Z; - CalcBounds(ref maxX, tempX1, true); - CalcBounds(ref maxY, tempZ1, true); - CalcBounds(ref maxX, tempX2, true); - CalcBounds(ref maxY, tempZ2, true); - - CalcBounds(ref minX, tempX1, false); - CalcBounds(ref minY, tempZ1, false); - CalcBounds(ref minX, tempX2, false); - CalcBounds(ref minY, tempZ2, false); - - segments.Add(new LineSegment(A, B, occupied, items[i])); - } - } - - /// - /// Given a value representing a limit, evaluate if the given value exceeds the current limit. - /// If so, expand the limit. - /// - /// The current limit. - /// The value to compare the limit to. - /// True when comparison is greater-than. False if less-than. - private static void CalcBounds(ref float limit, double v, bool gt) - { - float value = (float)v; - if (gt) - { - if (value > limit) - { - limit = value; - } - } - else - { - if (value < limit) - { - limit = value; - } - } - } - - void UITimer_Tick(object sender, EventArgs e) - { - if (Viewer.DebugViewerBetaEnabled == false) // Ctrl+9 sets this true to initialise the window and make it visible - { - Visible = false; - return; - } - Visible = true; - - if (Program.Simulator.GameTime - lastUpdateTime < 1) - return; - - lastUpdateTime = Program.Simulator.GameTime; - - GenerateView(); - } - - private void allowJoiningCheckbox_CheckedChanged(object sender, EventArgs e) - { - MPManager.Instance().AllowNewPlayer = allowJoiningCheckbox.Checked; - } - - private void drawPathCheckbox_CheckedChanged(object sender, EventArgs e) - { - DrawPath = drawPathCheckbox.Checked; - } - - private void mapResolutionUpDown_ValueChanged(object sender, EventArgs e) - { - // Center point of the map viewport before the change in resolution - PointF center = new PointF(ViewWindow.X + (ViewWindow.Width / 2f), ViewWindow.Y + (ViewWindow.Height / 2f)); - - float newSizeH = (float)mapResolutionUpDown.Value; - float verticalByHorizontal = ViewWindow.Height / ViewWindow.Width; - float newSizeV = newSizeH * verticalByHorizontal; - - ViewWindow = new RectangleF(center.X - (newSizeH / 2f), center.Y - (newSizeV / 2f), newSizeH, newSizeV); - - GenerateView(); - } - - private float ScrollSpeedX - { - get - { - return ViewWindow.Width * 0.10f; - } - } - - private float ScrollSpeedY - { - get - { - return ViewWindow.Width * 0.10f; - } - } - - protected override void OnMouseWheel(MouseEventArgs e) - { - decimal tempValue = mapResolutionUpDown.Value; - if (e.Delta < 0) tempValue /= 0.95m; - else if (e.Delta > 0) tempValue *= 0.95m; - else return; - - if (tempValue < mapResolutionUpDown.Minimum) tempValue = mapResolutionUpDown.Minimum; - if (tempValue > mapResolutionUpDown.Maximum) tempValue = mapResolutionUpDown.Maximum; - mapResolutionUpDown.Value = tempValue; - } - - private bool Zooming; - private bool LeftClick; - private bool RightClick; - - private void mapCanvas_MouseDown(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtons.Left) LeftClick = true; - if (e.Button == MouseButtons.Right) RightClick = true; - - if (LeftClick == true && RightClick == false) - { - if (Dragging == false) - { - Dragging = true; - Cursor.Current = Cursors.NoMove2D; - } - } - else if (LeftClick == true && RightClick == true) - { - if (Zooming == false) Zooming = true; - } - LastCursorPosition.X = e.X; - LastCursorPosition.Y = e.Y; - MPManager.Instance().ComposingText = false; - /*lblInstruction1.Visible = true; - lblInstruction2.Visible = true; - lblInstruction3.Visible = true; - lblInstruction4.Visible = true;*/ - } - - private void mapCanvas_MouseUp(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtons.Left) LeftClick = false; - if (e.Button == MouseButtons.Right) RightClick = false; - - if (LeftClick == false) - { - Dragging = false; - Zooming = false; - } - - if ((ModifierKeys & Keys.Shift) == Keys.Shift) - { - CanvasMoveAndZoomInOut(e.X, e.Y, 1200); - } - else if ((ModifierKeys & Keys.Alt) == Keys.Alt) - { - CanvasMoveAndZoomInOut(e.X, e.Y, 30000); - } - else if ((ModifierKeys & Keys.Control) == Keys.Control) - { - CanvasMoveAndZoomInOut(e.X, e.Y, mapResolutionUpDown.Maximum); - } - else if (LeftClick == false) - { - if (LastCursorPosition.X == e.X && LastCursorPosition.Y == e.Y) - { - var range = 5 * (int)xScale; if (range > 10) range = 10; - var temp = findItemFromMouse(e.X, e.Y, range); - if (temp != null) - { - if (temp is SwitchWidget widget) - { - switchPickedItem = widget; - signalPickedItem = null; - HandlePickedSwitch(); - } - if (temp is SignalWidget widget1) - { - signalPickedItem = widget1; - switchPickedItem = null; - HandlePickedSignal(); - } - } - else - { - switchPickedItem = null; - signalPickedItem = null; - UnHandleItemPick(); - PickedTrain = null; - } - } - - } - /*lblInstruction1.Visible = false; - lblInstruction2.Visible = false; - lblInstruction3.Visible = false; - lblInstruction4.Visible = false;*/ - } - - private void UnHandleItemPick() - { - setSignalMenu.Visible = false; - setSwitchMenu.Visible = false; - } - - private void HandlePickedSignal() - { - if (MPManager.IsClient() && !MPManager.Instance().AmAider) // normal client not server or aider - return; - setSwitchMenu.Visible = false; - if (signalPickedItem == null) return; - - allowCallOnToolStripMenuItem.Enabled = false; - if (signalPickedItem.Signal.enabledTrain != null && signalPickedItem.Signal.CallOnEnabled && !signalPickedItem.Signal.CallOnManuallyAllowed) - allowCallOnToolStripMenuItem.Enabled = true; - - setSignalMenu.Show(Cursor.Position); - setSignalMenu.Enabled = true; - setSignalMenu.Focus(); - setSignalMenu.Visible = true; - return; - } - - private void HandlePickedSwitch() - { - if (MPManager.IsClient() && !MPManager.Instance().AmAider) - return;//normal client not server - - setSignalMenu.Visible = false; - if (switchPickedItem == null) return; - setSwitchMenu.Show(Cursor.Position); - setSwitchMenu.Enabled = true; - setSwitchMenu.Focus(); - setSwitchMenu.Visible = true; - return; - } - - private void setSignalMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e) - { - if (signalPickedItem == null) - { - UnHandleItemPick(); - return; - } - - var signal = signalPickedItem.Signal; - var type = e.ClickedItem.Tag.ToString(); - - string[] signalAspects = { "system", "stop", "approach", "proceed" }; - int numericSignalAspect = Array.IndexOf(signalAspects, "stop"); - - if (MPManager.Instance().AmAider) - { - MPManager.Notify(new MSGSignalChange(signal, numericSignalAspect).ToString()); - UnHandleItemPick(); - return; - } - - switch (type) - { - case "system": - signal.ClearHoldSignalDispatcher(); - break; - - case "stop": - signal.RequestHoldSignalDispatcher(true); - break; - - case "approach": - signal.RequestApproachAspect(); - break; - - case "proceed": - signal.RequestLeastRestrictiveAspect(); - break; - - case "callOn": - signal.SetManualCallOn(true); - break; - } - - UnHandleItemPick(); - } - - private void setSwitchMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e) - { - if (switchPickedItem == null) - { - UnHandleItemPick(); return; - } - var sw = switchPickedItem.Item.TrJunctionNode; - var type = e.ClickedItem.Tag.ToString(); - - // Aider can send message to the server for a switch - if (MPManager.IsMultiPlayer() && MPManager.Instance().AmAider) - { - var nextSwitchTrack = sw; - var Selected = 0; - switch (type) - { - case "mainRoute": - Selected = (int)switchPickedItem.main; - break; - case "sideRoute": - Selected = 1 - (int)switchPickedItem.main; - break; - } - // Aider selects and throws the switch, but need to confirm by the dispatcher - MPManager.Notify(new MSGSwitch(MPManager.GetUserName(), - nextSwitchTrack.TN.UiD.WorldTileX, nextSwitchTrack.TN.UiD.WorldTileZ, nextSwitchTrack.TN.UiD.WorldId, Selected, true).ToString()); - Program.Simulator.Confirmer.Information(Viewer.Catalog.GetString("Switching Request Sent to the Server")); - - } - else // Server throws the switch immediately - { - switch (type) - { - case "mainRoute": - Program.Simulator.Signals.RequestSetSwitch(sw.TN, (int)switchPickedItem.main); - //sw.SelectedRoute = (int)switchPickedItem.main; - break; - case "sideRoute": - Program.Simulator.Signals.RequestSetSwitch(sw.TN, 1 - (int)switchPickedItem.main); - //sw.SelectedRoute = 1 - (int)switchPickedItem.main; - break; - } - } - UnHandleItemPick(); - } - - private ItemWidget findItemFromMouse(int x, int y, int range) - { - if (range < 5) range = 5; - double closest = float.NaN; - ItemWidget closestItem = null; - if (allowThrowingSwitchesCheckbox.Checked == true) - { - foreach (var item in switchItemsDrawn) - { - //if out of range, continue - if (item.Location2D.X < x - range || item.Location2D.X > x + range - || item.Location2D.Y < y - range || item.Location2D.Y > y + range) - continue; - - if (closestItem != null) - { - var dist = Math.Pow(item.Location2D.X - closestItem.Location2D.X, 2) + Math.Pow(item.Location2D.Y - closestItem.Location2D.Y, 2); - if (dist < closest) - { - closest = dist; closestItem = item; - } - } - else closestItem = item; - } - if (closestItem != null) - { - switchPickedTime = simulator.GameTime; - return closestItem; - } - } - if (allowChangingSignalsCheckbox.Checked == true) - { - foreach (var item in signalItemsDrawn) - { - //if out of range, continue - if (item.Location2D.X < x - range || item.Location2D.X > x + range - || item.Location2D.Y < y - range || item.Location2D.Y > y + range) - continue; - - if (closestItem != null) - { - var dist = Math.Pow(item.Location2D.X - closestItem.Location2D.X, 2) + Math.Pow(item.Location2D.Y - closestItem.Location2D.Y, 2); - if (dist < closest) - { - closest = dist; closestItem = item; - } - } - else closestItem = item; - } - if (closestItem != null) - { - switchPickedTime = simulator.GameTime; - return closestItem; - } - } - - //now check for trains (first car only) - TrainCar firstCar; - PickedTrain = null; float tX, tY; - closest = 100f; - - foreach (var t in Program.Simulator.Trains) - { - firstCar = null; - if (t.LeadLocomotive != null) - { - worldPos = t.LeadLocomotive.WorldPosition; - firstCar = t.LeadLocomotive; - } - else if (t.Cars != null && t.Cars.Count > 0) - { - worldPos = t.Cars[0].WorldPosition; - firstCar = t.Cars[0]; - - } - else - continue; - - worldPos = firstCar.WorldPosition; - tX = ((worldPos.TileX * 2048) - subX + worldPos.Location.X) * xScale; - tY = mapCanvas.Height - (((worldPos.TileZ * 2048) - subY + worldPos.Location.Z) * yScale); - float xSpeedCorr = Math.Abs(t.SpeedMpS) * xScale * 1.5f; - float ySpeedCorr = Math.Abs(t.SpeedMpS) * yScale * 1.5f; - - if (tX < x - range - xSpeedCorr || tX > x + range + xSpeedCorr || tY < y - range - ySpeedCorr || tY > y + range + ySpeedCorr) - continue; - if (PickedTrain == null) - PickedTrain = t; - } - //if a train is picked, will clear the avatar list selection - if (PickedTrain != null) - { - //AvatarView.SelectedItems.Clear(); - return new TrainWidget(PickedTrain); - } - return null; - } - - private void mapCanvas_MouseMove(object sender, MouseEventArgs e) - { - if (Dragging && !Zooming) - { - int diffX = LastCursorPosition.X - e.X; - int diffY = LastCursorPosition.Y - e.Y; - - ViewWindow.Offset(diffX * ScrollSpeedX / 10, -diffY * ScrollSpeedY / 10); - GenerateView(); - } - else if (Zooming) - { - decimal tempValue = mapResolutionUpDown.Value; - if (LastCursorPosition.Y - e.Y < 0) tempValue /= 0.95m; - else if (LastCursorPosition.Y - e.Y > 0) tempValue *= 0.95m; - - if (tempValue < mapResolutionUpDown.Minimum) tempValue = mapResolutionUpDown.Minimum; - if (tempValue > mapResolutionUpDown.Maximum) tempValue = mapResolutionUpDown.Maximum; - mapResolutionUpDown.Value = tempValue; - GenerateView(); - } - LastCursorPosition.X = e.X; - LastCursorPosition.Y = e.Y; - } - - private void CanvasMoveAndZoomInOut(int x, int y, decimal scale) - { - int diffX = x - (mapCanvas.Width / 2); - int diffY = y - (mapCanvas.Height / 2); - ViewWindow.Offset(diffX / xScale, -diffY / yScale); - if (scale < mapResolutionUpDown.Minimum) scale = mapResolutionUpDown.Minimum; - if (scale > mapResolutionUpDown.Maximum) scale = mapResolutionUpDown.Maximum; - mapResolutionUpDown.Value = scale; - GenerateView(); - } - - private void playerRoleLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) - { - Process.Start("https://open-rails.readthedocs.io/en/latest/multiplayer.html#in-game-controls"); - } - - private void mapCustomizationButton_Click(object sender, EventArgs e) - { - MapCustomizationVisible = !MapCustomizationVisible; - mapCustomizationPanel.Visible = MapCustomizationVisible; - - if (MapCustomizationVisible == true) - { - mapCustomizationButton.BackColor = Color.FromArgb(214, 234, 248); - mapCustomizationButton.ForeColor = Color.FromArgb(40, 116, 166); - } - else - { - mapCustomizationButton.BackColor = SystemColors.Control; - mapCustomizationButton.ForeColor = SystemColors.ControlText; - } - } - - private void playersView_MouseClick(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtons.Right) - { - var focusedItem = playersView.FocusedItem; - if (focusedItem != null && focusedItem.Bounds.Contains(e.Location)) - { - playerActionsMenu.Show(Cursor.Position); - } - } - } - - public bool ClickedTrain; - private void seeTrainInGameButton_Click(object sender, EventArgs e) - { - ClickedTrain = PickedTrain != null; - } - - private void centerOnMyTrainButton_Click(object sender, EventArgs e) - { - followTrain = false; - firstShow = true; - GenerateView(); - } - - private void penaltyCheckbox_CheckedChanged(object sender, EventArgs e) - { - MPManager.Instance().CheckSpad = penaltyCheckbox.Checked; - if (penaltyCheckbox.Checked == false) { MPManager.BroadCast(new MSGMessage("All", "OverSpeedOK", "OK to go overspeed and pass stop light").ToString()); } - else { MPManager.BroadCast(new MSGMessage("All", "NoOverSpeed", "Penalty for overspeed and passing stop light").ToString()); } - } - - private void DispatchViewerBeta_Resize(object sender, EventArgs e) - { - InitializeImage(); - } - - private void rotateThemesButton_Click(object sender, EventArgs e) - { - // Cycles through the array of available themes - string[] themes = MapThemeProvider.GetThemes(); - int i = Array.IndexOf(themes, ThemeName); - ThemeName = i >= 0 && i < themes.Length - 1 ? themes[i + 1] : themes[0]; - - Theme = MapThemeProvider.GetTheme(ThemeName); - - ApplyThemeRecursively(this); - MapCanvasColor = Theme.MapCanvasColor; - TrackPen.Color = Theme.TrackColor; - InitializeImage(); - } - - private void DispatchViewerBeta_FormClosing(object sender, FormClosingEventArgs e) - { - // Prevent the window from closing; instead, hide it - e.Cancel = true; - Viewer.DebugViewerBetaEnabled = false; - } - } - - #region SignalWidget - /// - /// Defines a signal being drawn in a 2D view. - /// - public class SignalWidget : ItemWidget - { - public TrItem Item; - /// - /// The underlying signal object as referenced by the TrItem. - /// - public SignalObject Signal; - - public PointF Dir; - public bool hasDir; - /// - /// For now, returns true if any of the signal heads shows any "clear" aspect. - /// This obviously needs some refinement. - /// - public int IsProceed - { - get - { - int returnValue = 2; - - foreach (var head in Signal.SignalHeads.Where(x => x.Function == SignalFunction.NORMAL)) - { - if (head.state == MstsSignalAspect.CLEAR_1 - || head.state == MstsSignalAspect.CLEAR_2) - { - returnValue = 0; - } - if (head.state == MstsSignalAspect.APPROACH_1 - || head.state == MstsSignalAspect.APPROACH_2 - || head.state == MstsSignalAspect.APPROACH_3) - { - returnValue = 1; - } - } - - return returnValue; - } - } - - /// - /// - /// - /// - /// - public SignalWidget(SignalItem item, SignalObject signal) - { - Item = item; - Signal = signal; - hasDir = false; - Location.X = (item.TileX * 2048) + item.X; - Location.Y = (item.TileZ * 2048) + item.Z; - var node = Program.Simulator.TDB.TrackDB.TrackNodes?[signal.trackNode]; - Vector2 v2; - if (node?.TrVectorNode != null) - { - var ts = node.TrVectorNode.TrVectorSections?.FirstOrDefault(); - if (ts == null) - return; - v2 = new Vector2((ts.TileX * 2048) + ts.X, (ts.TileZ * 2048) + ts.Z); - } - else if (node?.TrJunctionNode != null) - { - var ts = node?.UiD; - if (ts == null) - return; - v2 = new Vector2((ts.TileX * 2048) + ts.X, (ts.TileZ * 2048) + ts.Z); - } - else - { - return; - } - var v1 = new Vector2(Location.X, Location.Y); - var v3 = v1 - v2; - v3.Normalize(); - void copyTo(Vector2 input, ref PointF output) - { - output.X = input.X; - output.Y = input.Y; - } - copyTo(v1 - Vector2.Multiply(v3, signal.direction == 0 ? 12f : -12f), ref Dir); - //shift signal along the dir for 2m, so signals will not be overlapped - copyTo(v1 - Vector2.Multiply(v3, signal.direction == 0 ? 1.5f : -1.5f), ref Location); - hasDir = true; - } - } - #endregion - - #region SwitchWidget - /// - /// Defines a signal being drawn in a 2D view. - /// - public class SwitchWidget : ItemWidget - { - public TrackNode Item; - public uint main; - - /// - /// - /// - /// - /// - public SwitchWidget(TrackNode item) - { - Item = item; - var TS = Program.Simulator.TSectionDat.TrackShapes.Get(item.TrJunctionNode.ShapeIndex); // TSECTION.DAT tells us which is the main route - - main = TS != null ? TS.MainRoute : 0; - - Location.X = (Item.UiD.TileX * 2048) + Item.UiD.X; Location.Y = (Item.UiD.TileZ * 2048) + Item.UiD.Z; - } - } - - #endregion - - #region BufferWidget - public class BufferWidget : ItemWidget - { - public TrackNode Item; - - /// - /// - /// - /// - /// - public BufferWidget(TrackNode item) - { - Item = item; - - Location.X = (Item.UiD.TileX * 2048) + Item.UiD.X; Location.Y = (Item.UiD.TileZ * 2048) + Item.UiD.Z; - } - } - #endregion - - #region ItemWidget - public class ItemWidget - { - public PointF Location; - public PointF Location2D; - - /// - /// - /// - /// - public ItemWidget() - { - - Location = new PointF(float.NegativeInfinity, float.NegativeInfinity); - Location2D = new PointF(float.NegativeInfinity, float.NegativeInfinity); - } - } - #endregion - - #region TrainWidget - public class TrainWidget : ItemWidget - { - public Train Train; - - /// - /// - /// - /// - public TrainWidget(Train t) - { - Train = t; - } - } - #endregion - - #region LineSegment - /// - /// Defines a geometric line segment. - /// - public class LineSegment - { - public dVector A; - public dVector B; - public dVector C; - //public float radius; - public bool isCurved; - - public float angle1, angle2; - - public LineSegment(dVector A, dVector B, bool Occupied, TrVectorSection Section) - { - this.A = A; - this.B = B; - - isCurved = false; - if (Section == null) return; - //MySection = Section; - uint k = Section.SectionIndex; - TrackSection ts = Program.Simulator.TSectionDat.TrackSections.Get(k); - if (ts != null) - { - if (ts.SectionCurve != null) - { - float diff = (float)(ts.SectionCurve.Radius * (1 - Math.Cos(ts.SectionCurve.Angle * 3.14f / 360))); - if (diff < 3) return; //not need to worry, curve too small - //curve = ts.SectionCurve; - Vector3 v = new Vector3((float)(((B.TileX - A.TileX) * 2048) + B.X - A.X), 0, (float)(((B.TileZ - A.TileZ) * 2048) + B.Z - A.Z)); - isCurved = true; - Vector3 v2 = Vector3.Cross(Vector3.Up, v); v2.Normalize(); - v /= 2; v.X += (A.TileX * 2048) + (float)A.X; v.Z += (A.TileZ * 2048) + (float)A.Z; - v = ts.SectionCurve.Angle > 0 ? (v2 * -diff) + v : (v2 * diff) + v; - C = new dVector(0, v.X, 0, v.Z); - } - } - } - } - #endregion - - #region SidingWidget - - /// - /// Defines a siding name being drawn in a 2D view. - /// - public struct SidingWidget - { - public uint Id; - public PointF Location; - public string Name; - public uint LinkId; - - /// - /// The underlying track item. - /// - public SidingItem Item; - - /// - /// - /// - /// - /// - public SidingWidget(SidingItem item) - { - Id = item.TrItemId; - LinkId = item.LinkedSidingId; - Item = item; - Name = item.ItemName; - Location = new PointF((item.TileX * 2048) + item.X, (item.TileZ * 2048) + item.Z); - } - } - #endregion - - public struct PlatformWidget - { - public uint Id; - public PointF Location; - public string Name; - public PointF Extent1; - public PointF Extent2; - public uint LinkId; - public string Station; - - /// - /// The underlying track item. - /// - public PlatformItem Item; - - /// - /// - /// - /// - /// - public PlatformWidget(PlatformItem item) - { - Id = item.TrItemId; - LinkId = item.LinkedPlatformItemId; - Item = item; - Name = item.ItemName; - Station = item.Station; - Location = new PointF((item.TileX * 2048) + item.X, (item.TileZ * 2048) + item.Z); - Extent1 = default; - Extent2 = default; - } - } - - public class dVector - { - public int TileX, TileZ; - public double X, Z; - - public dVector(int tilex1, double x1, int tilez1, double z1) - { - TileX = tilex1; - TileZ = tilez1; - X = x1; - Z = z1; - } - - public static double DistanceSqr(dVector v1, dVector v2) - { - return Math.Pow(((v1.TileX - v2.TileX) * 2048) + v1.X - v2.X, 2) - + Math.Pow(((v1.TileZ - v2.TileZ) * 2048) + v1.Z - v2.Z, 2); - } - } -} diff --git a/Source/RunActivity/Viewer3D/Map/MapForm.resx b/Source/RunActivity/Viewer3D/Map/MapForm.resx deleted file mode 100644 index 0b1b1d3cce..0000000000 --- a/Source/RunActivity/Viewer3D/Map/MapForm.resx +++ /dev/null @@ -1,135 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 19, 16 - - - 174, 16 - - - 331, 16 - - - 486, 16 - - - 110 - - \ No newline at end of file diff --git a/Source/RunActivity/Viewer3D/Map/MapThemeProvider.cs b/Source/RunActivity/Viewer3D/Map/MapThemeProvider.cs deleted file mode 100644 index 77c4b8602b..0000000000 --- a/Source/RunActivity/Viewer3D/Map/MapThemeProvider.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System.Collections.Generic; -using System.Drawing; -using System.Linq; -using System.Windows.Forms; - -namespace Orts.Viewer3D.Map -{ - public class MapThemeProvider - { - public void InitializeThemes() - { - var LightTheme = new ThemeStyle - { - BackColor = Color.Transparent, - ForeColor = SystemColors.ControlText, - PanelBackColor = SystemColors.Control, - FlatStyle = FlatStyle.Standard, - MapCanvasColor = Color.White, - TrackColor = Color.FromArgb(46, 64, 83), - }; - - var DarkTheme = new ThemeStyle - { - BackColor = Color.FromArgb(44, 62, 80), - ForeColor = Color.FromArgb(247, 249, 249), - PanelBackColor = Color.FromArgb(28, 40, 51), - FlatStyle = FlatStyle.Flat, - MapCanvasColor = Color.FromArgb(44, 62, 80), - TrackColor = Color.FromArgb(234, 236, 238), - }; - - // Reference for "solarized" themes: https://github.com/altercation/solarized?tab=readme-ov-file#the-values - var LightSolarizedTheme = new ThemeStyle - { - BackColor = Color.FromArgb(253, 246, 227), - ForeColor = Color.FromArgb(101, 123, 131), - PanelBackColor = Color.FromArgb(238, 232, 213), - FlatStyle = FlatStyle.Flat, - MapCanvasColor = Color.FromArgb(253, 246, 227), - TrackColor = Color.FromArgb(88, 110, 117), - }; - - var DarkSolarizedTheme = new ThemeStyle - { - BackColor = Color.FromArgb(0, 43, 54), - ForeColor = Color.FromArgb(131, 148, 150), - PanelBackColor = Color.FromArgb(28, 40, 51), - FlatStyle = FlatStyle.Flat, - MapCanvasColor = Color.FromArgb(0, 43, 54), - TrackColor = Color.FromArgb(147, 161, 161), - }; - - Themes.Add("light", LightTheme); - Themes.Add("light-solarized", LightSolarizedTheme); - Themes.Add("dark-solarized", DarkSolarizedTheme); - Themes.Add("dark", DarkTheme); - } - - private readonly Dictionary Themes = new Dictionary(); - - public ThemeStyle GetTheme(string themeName) - { - if (Themes.TryGetValue(themeName, out var theme)) - { - return theme; - } - - // Handle the case when the theme doesn't exist - return null; - } - - public string[] GetThemes() - { - return Themes.Keys.ToArray(); - } - } - - public class ThemeStyle - { - public Color BackColor; - public Color ForeColor; - public Color PanelBackColor; - public FlatStyle FlatStyle; - public Color MapCanvasColor; - public Color TrackColor; - } -} - - diff --git a/Source/RunActivity/Viewer3D/Processes/GameStateViewer3D.cs b/Source/RunActivity/Viewer3D/Processes/GameStateViewer3D.cs index dbe07a6515..f9f773c752 100644 --- a/Source/RunActivity/Viewer3D/Processes/GameStateViewer3D.cs +++ b/Source/RunActivity/Viewer3D/Processes/GameStateViewer3D.cs @@ -56,10 +56,6 @@ internal override void BeginRender(RenderFrame frame) Program.DebugViewer.Hide(); Viewer.DebugViewerEnabled = false; - Program.DebugViewerBeta = new MapViewer(Viewer.Simulator, Viewer); - Program.DebugViewerBeta.Hide(); - Viewer.DebugViewerBetaEnabled = false; - Program.SoundDebugForm = new SoundDebugForm(Viewer); Program.SoundDebugForm.Hide(); Viewer.SoundDebugFormEnabled = false; diff --git a/Source/RunActivity/Viewer3D/Processes/RenderProcess.cs b/Source/RunActivity/Viewer3D/Processes/RenderProcess.cs index 288c64578b..29d6c16d23 100644 --- a/Source/RunActivity/Viewer3D/Processes/RenderProcess.cs +++ b/Source/RunActivity/Viewer3D/Processes/RenderProcess.cs @@ -261,12 +261,7 @@ internal void Update(GameTime gameTime) if (IsMouseVisible != Game.IsMouseVisible) Game.IsMouseVisible = IsMouseVisible; - // Restrict `ActualCursor` to the main window so that it won't affect other popup - // windows, such as the Dispatch window. This prevents cursor flickering. - if (GameForm.Focused == true) - { - GameForm.Cursor = ActualCursor; - } + Cursor.Current = ActualCursor; if (ToggleFullScreenRequested) { diff --git a/Source/RunActivity/Viewer3D/SkyInterpolation.cs b/Source/RunActivity/Viewer3D/SkyInterpolation.cs index a247eb27c3..7bbf187a23 100644 --- a/Source/RunActivity/Viewer3D/SkyInterpolation.cs +++ b/Source/RunActivity/Viewer3D/SkyInterpolation.cs @@ -29,7 +29,7 @@ public class SkyInterpolation public int Step1; public int Step2; - static float DaylightOffsetS => (float)Program.Simulator.Weather.DaylightOffset * 60 * 60; + static float DaylightOffsetS => (Program.DebugViewer == null) ? 0f : (float)Program.DebugViewer.DaylightOffsetHrs * 60 * 60; public void SetSunAndMoonDirection(ref Vector3 solarDirection, ref Vector3 lunarDirection, Vector3[] solarPosArray, Vector3[] lunarPosArray, double clockTime) { diff --git a/Source/RunActivity/Viewer3D/Viewer.cs b/Source/RunActivity/Viewer3D/Viewer.cs index 98ff10d350..e45b7610d7 100644 --- a/Source/RunActivity/Viewer3D/Viewer.cs +++ b/Source/RunActivity/Viewer3D/Viewer.cs @@ -192,7 +192,6 @@ void CameraActivate() public Vector3 FarPoint { get; private set; } public bool DebugViewerEnabled { get; set; } - public bool DebugViewerBetaEnabled { get; set; } public bool SoundDebugFormEnabled { get; set; } public TRPFile TRP; // Track profile file @@ -1171,7 +1170,6 @@ void HandleUserInput(ElapsedTime elapsedTime) if (UserInput.IsPressed(UserCommand.GameResetOutOfControlMode)) new ResetOutOfControlModeCommand(Log); if (UserInput.IsPressed(UserCommand.GameMultiPlayerDispatcher)) { DebugViewerEnabled = !DebugViewerEnabled; return; } - if (UserInput.IsPressed(UserCommand.GameMultiPlayerDispatcherBeta)) { DebugViewerBetaEnabled = !DebugViewerBetaEnabled; return; } if (UserInput.IsPressed(UserCommand.DebugSoundForm)) { SoundDebugFormEnabled = !SoundDebugFormEnabled; return; } if (UserInput.IsPressed(UserCommand.CameraJumpSeeSwitch)) @@ -1308,10 +1306,9 @@ void HandleUserInput(ElapsedTime elapsedTime) //} //in the dispatcher window, when one clicks a train and "See in Game", will jump to see that train - if ((Program.DebugViewer != null && Program.DebugViewer.ClickedTrain == true) || (Program.DebugViewerBeta != null && Program.DebugViewerBeta.ClickedTrain == true)) + if (Program.DebugViewer != null && Program.DebugViewer.ClickedTrain == true) { Program.DebugViewer.ClickedTrain = false; - Program.DebugViewerBeta.ClickedTrain = false; if (SelectedTrain != Program.DebugViewer.PickedTrain) { SelectedTrain = Program.DebugViewer.PickedTrain; diff --git a/Source/RunActivity/Viewer3D/Weather.cs b/Source/RunActivity/Viewer3D/Weather.cs index 5d15c11bb8..33a3f26cc3 100644 --- a/Source/RunActivity/Viewer3D/Weather.cs +++ b/Source/RunActivity/Viewer3D/Weather.cs @@ -17,7 +17,7 @@ // This file is the responsibility of the 3D & Environment Team. -// debug compiler flag for test output for automatic weather +// Debug compiler flag for test output for automatic weather //#define DEBUG_AUTOWEATHER using System; @@ -46,10 +46,10 @@ public class WeatherControl public readonly List SnowSound; public readonly List WeatherSounds = new List(); - public bool weatherChangeOn = false; + public bool weatherChangeOn; public DynamicWeather dynamicWeather; public bool RandomizedWeather; - public bool DesertZone; // we are in a desert zone, so no randomized weather change... + public bool DesertZone; // We are in a desert zone, so no randomized weather change... private readonly float[,] DesertZones = { { 30, 45, -120, -105 } }; // minlat, maxlat, minlong, maxlong // Variables used for wind calculations @@ -58,7 +58,7 @@ public class WeatherControl public float Time; readonly float[] WindChangeMpSS = { 40, 5 }; // Flurry, steady const float WindSpeedMaxMpS = 4.5f; - float WindUpdateTimer = 0.0f; + float WindUpdateTimer; readonly float WindGustUpdateTimeS = 1.0f; bool InitialWind = true; float BaseWindDirectionRad; @@ -76,15 +76,15 @@ public WeatherControl(Viewer viewer) Program.Simulator.BasePath + @"\SOUND", }; - ClearSound = new List() { + ClearSound = new List { new SoundSource(viewer, Events.Source.MSTSInGame, ORTSPaths.GetFileFromFolders(pathArray, "clear_in.sms"), false), new SoundSource(viewer, Events.Source.MSTSInGame, ORTSPaths.GetFileFromFolders(pathArray, "clear_ex.sms"), false), }; - RainSound = new List() { + RainSound = new List { new SoundSource(viewer, Events.Source.MSTSInGame, ORTSPaths.GetFileFromFolders(pathArray, "rain_in.sms"), false), new SoundSource(viewer, Events.Source.MSTSInGame, ORTSPaths.GetFileFromFolders(pathArray, "rain_ex.sms"), false), }; - SnowSound = new List() { + SnowSound = new List { new SoundSource(viewer, Events.Source.MSTSInGame, ORTSPaths.GetFileFromFolders(pathArray, "snow_in.sms"), false), new SoundSource(viewer, Events.Source.MSTSInGame, ORTSPaths.GetFileFromFolders(pathArray, "snow_ex.sms"), false), }; @@ -96,7 +96,7 @@ public WeatherControl(Viewer viewer) SetInitialWeatherParameters(); UpdateWeatherParameters(); - // add here randomized weather + // Add here randomized weather if (Viewer.Settings.ActWeatherRandomizationLevel > 0 && Viewer.Simulator.ActivityRun != null && !Viewer.Simulator.ActivityRun.WeatherChangesPresent) { RandomizedWeather = RandomizeInitialWeather(); @@ -109,7 +109,6 @@ public WeatherControl(Viewer viewer) dynamicWeather.stableWeatherTimer = ((4.0f - Viewer.Settings.ActWeatherRandomizationLevel) * 600) + Viewer.Random.Next(300) - 150; weatherChangeOn = true; } - } Viewer.Simulator.WeatherChanged += (object sender, EventArgs e) => @@ -121,7 +120,7 @@ public WeatherControl(Viewer viewer) public virtual void SaveWeatherParameters(BinaryWriter outf) { - outf.Write(0); // set fixed weather + outf.Write(0); // Set fixed weather outf.Write(Weather.FogDistance); outf.Write(Weather.OvercastFactor); outf.Write(Weather.PricipitationIntensityPPSPM2); @@ -138,7 +137,7 @@ public virtual void RestoreWeatherParameters(BinaryReader inf) { int weathercontroltype = inf.ReadInt32(); - // restoring wrong type of weather - abort + // Restoring wrong type of weather - abort if (weathercontroltype != 0) { Trace.TraceError(Simulator.Catalog.GetString("Restoring wrong weather type : trying to restore dynamic weather but save contains user controlled weather")); @@ -163,9 +162,10 @@ public void SetInitialWeatherParameters() // These values are defaults only; subsequent changes to the weather via debugging only change the components (weather, overcastFactor and fogDistance) individually. switch (Viewer.Simulator.WeatherType) { - case Orts.Formats.Msts.WeatherType.Clear: Weather.OvercastFactor = 0.05f; Weather.FogDistance = 20000; break; - case Orts.Formats.Msts.WeatherType.Rain: Weather.OvercastFactor = 0.7f; Weather.FogDistance = 1000; break; - case Orts.Formats.Msts.WeatherType.Snow: Weather.OvercastFactor = 0.6f; Weather.FogDistance = 500; break; + case WeatherType.Clear: Weather.OvercastFactor = 0.05f; Weather.FogDistance = 20000; break; + case WeatherType.Rain: Weather.OvercastFactor = 0.7f; Weather.FogDistance = 1000; break; + case WeatherType.Snow: Weather.OvercastFactor = 0.6f; Weather.FogDistance = 500; break; + default: break; } } @@ -174,11 +174,11 @@ public void UpdateWeatherParameters() Viewer.SoundProcess.RemoveSoundSources(this); switch (Viewer.Simulator.WeatherType) { - case Orts.Formats.Msts.WeatherType.Clear: Weather.PrecipitationLiquidity = 1; Weather.PricipitationIntensityPPSPM2 = 0; Viewer.SoundProcess.AddSoundSources(this, ClearSound); break; - case Orts.Formats.Msts.WeatherType.Rain: Weather.PrecipitationLiquidity = 1; Weather.PricipitationIntensityPPSPM2 = 0.010f; Viewer.SoundProcess.AddSoundSources(this, RainSound); break; - case Orts.Formats.Msts.WeatherType.Snow: Weather.PrecipitationLiquidity = 0; Weather.PricipitationIntensityPPSPM2 = 0.0050f; Viewer.SoundProcess.AddSoundSources(this, SnowSound); break; + case WeatherType.Clear: Weather.PrecipitationLiquidity = 1; Weather.PricipitationIntensityPPSPM2 = 0; Viewer.SoundProcess.AddSoundSources(this, ClearSound); break; + case WeatherType.Rain: Weather.PrecipitationLiquidity = 1; Weather.PricipitationIntensityPPSPM2 = 0.010f; Viewer.SoundProcess.AddSoundSources(this, RainSound); break; + case WeatherType.Snow: Weather.PrecipitationLiquidity = 0; Weather.PricipitationIntensityPPSPM2 = 0.0050f; Viewer.SoundProcess.AddSoundSources(this, SnowSound); break; + default: break; } - } void UpdateSoundSources() @@ -186,9 +186,10 @@ void UpdateSoundSources() Viewer.SoundProcess.RemoveSoundSources(this); switch (Viewer.Simulator.WeatherType) { - case Orts.Formats.Msts.WeatherType.Clear: Viewer.SoundProcess.AddSoundSources(this, ClearSound); break; - case Orts.Formats.Msts.WeatherType.Rain: Viewer.SoundProcess.AddSoundSources(this, RainSound); break; - case Orts.Formats.Msts.WeatherType.Snow: Viewer.SoundProcess.AddSoundSources(this, SnowSound); break; + case WeatherType.Clear: Viewer.SoundProcess.AddSoundSources(this, ClearSound); break; + case WeatherType.Rain: Viewer.SoundProcess.AddSoundSources(this, RainSound); break; + case WeatherType.Snow: Viewer.SoundProcess.AddSoundSources(this, SnowSound); break; + default: break; } } @@ -252,7 +253,6 @@ private void UpdateWind(ElapsedTime elapsedTime) calculatedWindDirection = BaseWindDirectionRad - (WindDirectionVariationRad * (float)Viewer.Random.NextDouble()); Weather.CalculatedWindDirection = calculatedWindDirection; - } } @@ -264,7 +264,7 @@ private bool RandomizeInitialWeather() var randValue = Viewer.Random.Next(170); var intermValue = randValue >= 50 ? (float)(randValue - 50f) : randValue; Weather.OvercastFactor = intermValue >= 20 ? (float)(intermValue - 20f) / 100f : (float)intermValue / 100f; // give more probability to less overcast - Viewer.Simulator.WeatherType = Orts.Formats.Msts.WeatherType.Clear; + Viewer.Simulator.WeatherType = WeatherType.Clear; // Then check if we are in precipitation zone if (Weather.OvercastFactor > 0.5) { @@ -274,22 +274,22 @@ private bool RandomizeInitialWeather() Weather.PricipitationIntensityPPSPM2 = (float)(randValue - 40f) / 1000f; if (Viewer.Simulator.Season == SeasonType.Winter) { - Viewer.Simulator.WeatherType = Orts.Formats.Msts.WeatherType.Snow; + Viewer.Simulator.WeatherType = WeatherType.Snow; Weather.PrecipitationLiquidity = 0; } else { - Viewer.Simulator.WeatherType = Orts.Formats.Msts.WeatherType.Rain; + Viewer.Simulator.WeatherType = WeatherType.Rain; Weather.PrecipitationLiquidity = 1; } } else Weather.PricipitationIntensityPPSPM2 = 0; } else Weather.PricipitationIntensityPPSPM2 = 0; - // and now define visibility + // And now define visibility randValue = Viewer.Random.Next(2000); if (Weather.PricipitationIntensityPPSPM2 > 0 || Weather.OvercastFactor > 0.7f) - // use first digit to define power of ten and the other three to define the multiplying number + // Use first digit to define power of ten and the other three to define the multiplying number Weather.FogDistance = Math.Max(100, (float)Math.Pow(10, randValue / 1000 + 2) * (float)(((randValue % 1000) + 1) / 100f)); else Weather.FogDistance = Math.Max(500, (float)Math.Pow(10, (randValue / 1000) + 3) * (float)(((randValue % 1000) + 1) / 100f)); @@ -359,7 +359,6 @@ public virtual void Update(ElapsedTime elapsedTime) manager.fogDistance = -1; } } - else if (!MPManager.IsClient()) { // The user is able to change the weather for debugging. This will cycle through clear, rain and snow. @@ -367,17 +366,17 @@ public virtual void Update(ElapsedTime elapsedTime) { switch (Viewer.Simulator.WeatherType) { - case Orts.Formats.Msts.WeatherType.Clear: - Viewer.Simulator.WeatherType = Orts.Formats.Msts.WeatherType.Rain; + case WeatherType.Clear: + Viewer.Simulator.WeatherType = WeatherType.Rain; break; - case Orts.Formats.Msts.WeatherType.Rain: - Viewer.Simulator.WeatherType = Orts.Formats.Msts.WeatherType.Snow; + case WeatherType.Rain: + Viewer.Simulator.WeatherType = WeatherType.Snow; break; - case Orts.Formats.Msts.WeatherType.Snow: - Viewer.Simulator.WeatherType = Orts.Formats.Msts.WeatherType.Clear; + case WeatherType.Snow: + Viewer.Simulator.WeatherType = WeatherType.Clear; break; } - // block dynamic weather change after a manual weather change operation + // Block dynamic weather change after a manual weather change operation weatherChangeOn = false; dynamicWeather?.ResetWeatherTargets(); UpdateWeatherParameters(); @@ -454,7 +453,6 @@ public virtual void Update(ElapsedTime elapsedTime) Viewer.Simulator.WeatherType = WeatherType.Rain; Viewer.SoundProcess.RemoveSoundSources(this); Viewer.SoundProcess.AddSoundSources(this, RainSound); - } } if (UserInput.IsDown(UserCommand.DebugPrecipitationLiquidityDecrease)) @@ -486,23 +484,10 @@ public virtual void Update(ElapsedTime elapsedTime) weatherChangeOn = false; } - // Daylight offset is useful for debugging night running timetables; it ranges from -12h to +12h - string FormatDaylightOffsetHour(int h) => h <= 0 ? h.ToString() : $"+{h}"; - if (UserInput.IsPressed(UserCommand.DebugDaylightOffsetIncrease) && Weather.DaylightOffset < 12) - { - Weather.DaylightOffset += 1; - Viewer.Simulator.Confirmer.Message(ConfirmLevel.None, Simulator.Catalog.GetStringFmt("Increased daylight offset to {0} h", FormatDaylightOffsetHour(Weather.DaylightOffset))); - } - if (UserInput.IsPressed(UserCommand.DebugDaylightOffsetDecrease) && Weather.DaylightOffset > -12) - { - Weather.DaylightOffset -= 1; - Viewer.Simulator.Confirmer.Message(ConfirmLevel.None, Simulator.Catalog.GetStringFmt("Decreased daylight offset to {0} h", FormatDaylightOffsetHour(Weather.DaylightOffset))); - } - UpdateWind(elapsedTime); } - if (!MPManager.IsMultiPlayer()) + if (!Orts.MultiPlayer.MPManager.IsMultiPlayer()) { // Shift the clock forwards or backwards at 1h-per-second. if (UserInput.IsDown(UserCommand.DebugClockForwards)) Viewer.Simulator.ClockTime += elapsedTime.RealSeconds * 3600; @@ -524,7 +509,7 @@ public virtual void Update(ElapsedTime elapsedTime) (Program.Simulator.ActivityRun.triggeredEventWrapper.ParsedObject.ORTSWeatherChange != null || Program.Simulator.ActivityRun.triggeredEventWrapper.ParsedObject.Outcomes.ORTSWeatherChange != null)) // Start a weather change sequence in activity mode { - // if not yet weather changes, create the instance + // If not yet weather changes, create the instance if (dynamicWeather == null) { dynamicWeather = new DynamicWeather(); @@ -534,15 +519,15 @@ public virtual void Update(ElapsedTime elapsedTime) Program.Simulator.ActivityRun.triggeredEventWrapper = null; } if (weatherChangeOn) - // manage the weather change sequence + // Manage the weather change sequence { dynamicWeather.WeatherChange_Update(elapsedTime, this); } - if (RandomizedWeather && !weatherChangeOn) // time to prepare a new weather change + if (RandomizedWeather && !weatherChangeOn) // Time to prepare a new weather change dynamicWeather.WeatherChange_NextRandomization(elapsedTime, this); if (Weather.PricipitationIntensityPPSPM2 == 0 && Viewer.Simulator.WeatherType != WeatherType.Clear) { - Viewer.Simulator.WeatherType = Orts.Formats.Msts.WeatherType.Clear; + Viewer.Simulator.WeatherType = WeatherType.Clear; UpdateWeatherParameters(); } else if (Weather.PricipitationIntensityPPSPM2 > 0 && Viewer.Simulator.WeatherType == WeatherType.Clear) @@ -555,16 +540,16 @@ public virtual void Update(ElapsedTime elapsedTime) public class DynamicWeather { public const float RainSnowLiquidityThreshold = 0.3f; - public float overcastChangeRate = 0; - public float overcastTimer = 0; - public float fogChangeRate = 0; - public float fogTimer = 0; - public float stableWeatherTimer = 0; - public float precipitationIntensityChangeRate = 0; - public float precipitationIntensityTimer = 0; + public float overcastChangeRate; + public float overcastTimer; + public float fogChangeRate; + public float fogTimer; + public float stableWeatherTimer; + public float precipitationIntensityChangeRate; + public float precipitationIntensityTimer; public float precipitationIntensityDelayTimer = -1; - public float precipitationLiquidityChangeRate = 0; - public float precipitationLiquidityTimer = 0; + public float precipitationLiquidityChangeRate; + public float precipitationLiquidityTimer; public float ORTSOvercast = -1; public int ORTSOvercastTransitionTimeS = -1; public float ORTSFog = -1; @@ -573,7 +558,7 @@ public class DynamicWeather public int ORTSPrecipitationIntensityTransitionTimeS = -1; public float ORTSPrecipitationLiquidity = -1; public int ORTSPrecipitationLiquidityTransitionTimeS = -1; - public bool fogDistanceIncreasing = false; + public bool fogDistanceIncreasing; public DynamicWeather() { } @@ -738,7 +723,7 @@ public void WeatherChange_Update(ElapsedTime elapsedTime, WeatherControl weather if (precipitationIntensityDelayTimer <= 0) { precipitationIntensityDelayTimer = -1; // OK, now rain/snow can start - precipitationIntensityTimer = overcastTimer; // going in parallel now + precipitationIntensityTimer = overcastTimer; // Going in parallel now } } if (ORTSPrecipitationLiquidity >= 0) @@ -780,10 +765,10 @@ public void WeatherChange_Update(ElapsedTime elapsedTime, WeatherControl weather public void WeatherChange_NextRandomization(ElapsedTime elapsedTime, WeatherControl weatherControl) // start next randomization { - // define how much time transition will last + // Define how much time transition will last var weatherChangeTimer = ((4 - weatherControl.Viewer.Settings.ActWeatherRandomizationLevel) * 600) + Viewer.Random.Next((4 - weatherControl.Viewer.Settings.ActWeatherRandomizationLevel) * 600); - // begin with overcast + // Begin with overcast var randValue = Viewer.Random.Next(170); var intermValue = randValue >= 50 ? (float)(randValue - 50f) : randValue; ORTSOvercast = intermValue >= 20 ? (float)(intermValue - 20f) / 100f : (float)intermValue / 100f; // give more probability to less overcast @@ -803,12 +788,12 @@ public void WeatherChange_Update(ElapsedTime elapsedTime, WeatherControl weather if (weatherControl.Weather.PricipitationIntensityPPSPM2 > 0 && ORTSPrecipitationIntensity == -1) { ORTSPrecipitationIntensity = 0; - // must return to zero before overcast < 0.5 + // Must return to zero before overcast < 0.5 ORTSPrecipitationIntensityTransitionTimeS = (int)((0.5 - weatherControl.Weather.OvercastFactor) / overcastChangeRate); } if (weatherControl.Weather.PricipitationIntensityPPSPM2 == 0 && ORTSPrecipitationIntensity > 0 && weatherControl.Weather.OvercastFactor < 0.5) { - // we will have precipitation now, but it must start after overcast is over 0.5 + // We will have precipitation now, but it must start after overcast is over 0.5 precipitationIntensityDelayTimer = (0.5f - weatherControl.Weather.OvercastFactor) / overcastChangeRate; } @@ -823,10 +808,10 @@ public void WeatherChange_Update(ElapsedTime elapsedTime, WeatherControl weather - weatherControl.Weather.PricipitationIntensityPPSPM2) / ORTSPrecipitationIntensityTransitionTimeS : 0; } - // and now define visibility + // And now define visibility randValue = Viewer.Random.Next(2000); if (ORTSPrecipitationIntensity > 0 || ORTSOvercast > 0.7f) - // use first digit to define power of ten and the other three to define the multiplying number + // Use first digit to define power of ten and the other three to define the multiplying number ORTSFog = Math.Max(100, (float)Math.Pow(10, randValue / 1000 + 2) * (float)(((randValue % 1000) + 1) / 100f)); else ORTSFog = Math.Max(500, (float)Math.Pow(10, (randValue / 1000) + 3) * (float)(((randValue % 1000) + 1) / 100f)); @@ -850,7 +835,7 @@ public void WeatherChange_Update(ElapsedTime elapsedTime, WeatherControl weather public class AutomaticWeather : WeatherControl { - // Variables used for auto weather control + /* Variables used for auto weather control */ // settings readonly List weatherDetails = new List(); @@ -878,7 +863,7 @@ public class AutomaticWeather : WeatherControl public float AWPrecipitationEndRate; // rate of change at end of spell // fog - public float AWActualVisibility; // actual fog visibility + public float AWActualVisibility; // actual fog visibility public float AWFogChangeRateMpS; // required rate of change for fog public float AWFogLiftTime; // start time of fog lifting to be clear at required time @@ -898,7 +883,7 @@ public class AutomaticWeather : WeatherControl public AutomaticWeather(Viewer viewer, string weatherFile, double realTime) : base(viewer) { - // read weather details from file + // Read weather details from file var WeatherFile = new WeatherFile(weatherFile); weatherDetails = WeatherFile.Changes; @@ -911,17 +896,17 @@ public AutomaticWeather(Viewer viewer, string weatherFile, double realTime) CheckWeatherDetails(); } - // set initial weather parameters + // Set initial weather parameters SetInitialWeatherParameters(realTime); } - // dummy constructor for restore + // Dummy constructor for restore public AutomaticWeather(Viewer viewer) : base(viewer) { } - // check weather details, set auto variables + // Check weather details, set auto variables void CheckWeatherDetails() { float prevTime = 0; @@ -930,7 +915,7 @@ void CheckWeatherDetails() { TimeSpan acttime = new TimeSpan((long)(weatherSet.Time * 10000000)); - // check if time is in sequence + // Check if time is in sequence if (weatherSet.Time < prevTime) { Trace.TraceInformation("Invalid time value : time out of sequence : {0}", acttime.ToString()); @@ -938,7 +923,7 @@ void CheckWeatherDetails() } prevTime = weatherSet.Time; - // check settings + // Check settings if (weatherSet is WeatherSettingOvercast) { WeatherSettingOvercast thisOvercast = weatherSet as WeatherSettingOvercast; @@ -947,18 +932,17 @@ void CheckWeatherDetails() CheckValue(ref thisOvercast.OvercastRateOfChange, true, 0, 1, acttime, "Overcast Rate of Change"); CheckValue(ref thisOvercast.OvercastVisibilityM, false, 1000, 60000, acttime, "Overcast Visibility"); } - else if (weatherSet is WeatherSettingPrecipitation) { WeatherSettingPrecipitation thisPrecipitation = weatherSet as WeatherSettingPrecipitation; - // clear spell + // Clear spell CheckValue(ref thisPrecipitation.Overcast, true, 0, 100, acttime, "Overcast"); CheckValue(ref thisPrecipitation.OvercastVariation, true, 0, 100, acttime, "Overcast Variation"); CheckValue(ref thisPrecipitation.OvercastRateOfChange, true, 0, 1, acttime, "Overcast Rate of Change"); CheckValue(ref thisPrecipitation.OvercastVisibilityM, false, 1000, 60000, acttime, "Overcast Visibility"); - // precipitation + // Precipitation CheckValue(ref thisPrecipitation.PrecipitationDensity, true, 0, 1, acttime, "Precipitation Density"); CheckValue(ref thisPrecipitation.PrecipitationVariation, true, 0, 1, acttime, "Precipitation Variation"); CheckValue(ref thisPrecipitation.PrecipitationRateOfChange, true, 0, 1, acttime, "Precipitation Rate Of Change"); @@ -967,16 +951,15 @@ void CheckWeatherDetails() CheckValue(ref thisPrecipitation.PrecipitationVisibilityAtMinDensityM, false, 100, thisPrecipitation.OvercastVisibilityM, acttime, "Precipitation Visibility At Min Density"); CheckValue(ref thisPrecipitation.PrecipitationVisibilityAtMaxDensityM, false, 100, thisPrecipitation.PrecipitationVisibilityAtMinDensityM, acttime, "Precipitation Visibility At Max Density"); - // build up + // Build up CheckValue(ref thisPrecipitation.OvercastPrecipitationStart, true, thisPrecipitation.Overcast, 100, acttime, "Overcast Precipitation Start"); CheckValue(ref thisPrecipitation.OvercastBuildUp, true, 0, 1, acttime, "Overcast Build Up"); CheckValue(ref thisPrecipitation.PrecipitationStartPhaseS, false, 30, 240, acttime, "Precipitation Start Phase"); - // dispersion + // Dispersion CheckValue(ref thisPrecipitation.OvercastDispersion, true, 0, 1, acttime, "Overcast Dispersion"); CheckValue(ref thisPrecipitation.PrecipitationEndPhaseS, false, 30, 360, acttime, "Precipitation End Phase"); } - else if (weatherSet is WeatherSettingFog) { WeatherSettingFog thisFog = weatherSet as WeatherSettingFog; @@ -988,10 +971,10 @@ void CheckWeatherDetails() } } - // check value, set random value if allowed and value not set + // Check value, set random value if allowed and value not set void CheckValue(ref float setValue, bool randomize, float minValue, float maxValue, TimeSpan acttime, string description) { - // overcast + // Overcast if (setValue < 0 && randomize) { setValue = Viewer.Random.Next((int)maxValue * 100) / 100; // ensure there is a value if range is 0 - 1 @@ -1008,12 +991,12 @@ void CheckValue(ref float setValue, bool randomize, float minValue, float maxVal } } - // set initial weather parameters + // Set initial weather parameters void SetInitialWeatherParameters(double realTime) { Time = (float)realTime; - // find last valid weather change + // Find last valid weather change AWActiveIndex = 0; var passedTime = false; @@ -1029,7 +1012,7 @@ void SetInitialWeatherParameters(double realTime) } } - // get last weather + // Get last weather #if DEBUG_AUTOWEATHER Trace.TraceInformation("Initial active weather : {0}", AWActiveIndex); #endif @@ -1038,14 +1021,14 @@ void SetInitialWeatherParameters(double realTime) AWNextChangeTime = AWActiveIndex < (weatherDetails.Count - 1) ? weatherDetails[AWActiveIndex + 1].Time : (24 * 3600); int nextIndex = AWActiveIndex < (weatherDetails.Count - 1) ? AWActiveIndex + 1 : -1; - // fog + // Fog if (lastWeather is WeatherSettingFog) { WeatherSettingFog lastWeatherFog = lastWeather as WeatherSettingFog; float actualLiftingTime = (0.9f * lastWeatherFog.FogLiftTimeS) + ((float)Viewer.Random.Next(10) / 100 * lastWeatherFog.FogLiftTimeS); // defined time +- 10% AWFogLiftTime = AWNextChangeTime - actualLiftingTime; - // check if fog is allready lifting + // Check if fog is allready lifting if ((float)realTime > AWFogLiftTime && nextIndex > 1) { float reqVisibility = GetWeatherVisibility(weatherDetails[nextIndex]); @@ -1059,14 +1042,14 @@ void SetInitialWeatherParameters(double realTime) } } - // precipitation + // Precipitation else if (lastWeather is WeatherSettingPrecipitation) { WeatherSettingPrecipitation lastWeatherPrecipitation = lastWeather as WeatherSettingPrecipitation; StartPrecipitation(lastWeatherPrecipitation, (float)realTime, true); } - // cloudcover + // Cloudcover else if (lastWeather is WeatherSettingOvercast) { WeatherSettingOvercast lastWeatherOvercast = lastWeather as WeatherSettingOvercast; @@ -1077,10 +1060,9 @@ void SetInitialWeatherParameters(double realTime) #if DEBUG_AUTOWEATHER Trace.TraceInformation("Visibility : {0}", Weather.FogDistance); #endif - } - // set system weather parameters + // Set system weather parameters Viewer.SoundProcess.RemoveSoundSources(this); Viewer.Simulator.WeatherType = AWPrecipitationActiveType; @@ -1125,11 +1107,10 @@ void SetInitialWeatherParameters(double realTime) #endif } - [CallOnThread("Updater")] public override void Update(ElapsedTime elapsedTime) { - // not client and weather auto mode + // Not client and weather auto mode Time += elapsedTime.ClockSeconds; var fogActive = false; @@ -1140,45 +1121,45 @@ public override void Update(ElapsedTime elapsedTime) int nextIndex = AWActiveIndex < (weatherDetails.Count - 1) ? AWActiveIndex + 1 : -1; fogActive = false; - // check for fog + // Check for fog if (lastWeather is WeatherSettingFog) { WeatherSettingFog lastWeatherFog = lastWeather as WeatherSettingFog; CalculateFog(lastWeatherFog, nextIndex); fogActive = true; - // if fog has lifted, change to next sequence + // If fog has lifted, change to next sequence if (Time > (AWNextChangeTime - lastWeatherFog.FogLiftTimeS) && AWActualVisibility >= 19999 && AWActiveIndex < (weatherDetails.Count - 1)) { fogActive = false; - AWNextChangeTime = Time - 1; // force change to next weather + AWNextChangeTime = Time - 1; // Force change to next weather } } - // check for precipitation + // Check for precipitation else if (lastWeather is WeatherSettingPrecipitation) { WeatherSettingPrecipitation lastWeatherPrecipitation = lastWeather as WeatherSettingPrecipitation; - // precipitation not active + // Precipitation not active if (AWPrecipitationActiveType == WeatherType.Clear) { - // if beyond start of next spell start precipitation + // If beyond start of next spell start precipitation if (Time > AWPrecipitationNextSpell) { - // if cloud has build up + // If cloud has build up if (AWOvercastCloudcover >= (lastWeatherPrecipitation.OvercastPrecipitationStart / 100)) { StartPrecipitationSpell(lastWeatherPrecipitation, AWNextChangeTime); CalculatePrecipitation(lastWeatherPrecipitation, elapsedTime); } - // build up cloud + // Build up cloud else { AWOvercastCloudcover = CalculateOvercast(lastWeatherPrecipitation.OvercastPrecipitationStart, 0, lastWeatherPrecipitation.OvercastBuildUp, elapsedTime); } } - // set overcast and visibility + // Set overcast and visibility else { AWOvercastCloudcover = CalculateOvercast(lastWeatherPrecipitation.Overcast, lastWeatherPrecipitation.OvercastVariation, lastWeatherPrecipitation.OvercastRateOfChange, elapsedTime); @@ -1192,8 +1173,8 @@ public override void Update(ElapsedTime elapsedTime) } } } - // active precipitation - // if beyond end of spell : decrease densitity, if density below minimum threshold stop precipitation + // Active precipitation + // If beyond end of spell: decrease densitity, if density below minimum threshold stop precipitation else if (Time > AWPrecipitationEndSpell) { StopPrecipitationSpell(lastWeatherPrecipitation, elapsedTime); @@ -1208,13 +1189,13 @@ public override void Update(ElapsedTime elapsedTime) #endif } } - // active precipitation : set density and related visibility + // Active precipitation: set density and related visibility else { CalculatePrecipitation(lastWeatherPrecipitation, elapsedTime); } } - // clear + // Clear else if (lastWeather is WeatherSettingOvercast) { WeatherSettingOvercast lastWeatherOvercast = lastWeather as WeatherSettingOvercast; @@ -1229,7 +1210,7 @@ public override void Update(ElapsedTime elapsedTime) } } - // set weather parameters + // Set weather parameters Viewer.SoundProcess.RemoveSoundSources(this); Viewer.Simulator.WeatherType = AWPrecipitationActiveType; @@ -1259,21 +1240,21 @@ public override void Update(ElapsedTime elapsedTime) break; } - // check for change in required weather - // time to change but no change after midnight and further weather available + // Check for change in required weather + // Time to change but no change after midnight and further weather available if (Time < 24 * 3600 && Time > AWNextChangeTime && AWActiveIndex < (weatherDetails.Count - 1)) { - // if precipitation still active or fog not lifted, postpone change by one minute + // If precipitation still active or fog not lifted, postpone change by one minute if (AWPrecipitationActiveType != WeatherType.Clear || fogActive) { AWNextChangeTime += 60; } else { - // set final values of last weather + // Set final values of last weather lastWeather.GenOvercast = Weather.OvercastFactor; lastWeather.GenVisibility = AWLastVisibility = Weather.FogDistance; - //lastWeater.AWGenWind = ?? + //lastWeater.AWGenWind = ?? // TODO AWActiveIndex++; AWNextChangeTime = AWActiveIndex < (weatherDetails.Count - 2) ? weatherDetails[AWActiveIndex + 1].Time : 24 * 3600; @@ -1297,7 +1278,7 @@ public override void Update(ElapsedTime elapsedTime) float GetWeatherVisibility(WeatherSetting weatherDetail) { - float nextVisibility = Weather.FogDistance; // present visibility + float nextVisibility = Weather.FogDistance; // Present visibility if (weatherDetail is WeatherSettingFog) { WeatherSettingFog weatherFog = weatherDetail as WeatherSettingFog; @@ -1318,12 +1299,12 @@ float GetWeatherVisibility(WeatherSetting weatherDetail) void StartFog(WeatherSettingFog lastWeatherFog, float startTime, int activeIndex) { - // fog fully set or fog at start of day + // Fog fully set or fog at start of day if (startTime > (lastWeatherFog.Time + lastWeatherFog.FogSetTimeS) || activeIndex == 0) { AWActualVisibility = lastWeatherFog.FogVisibilityM; } - // fog still setting + // Fog still setting else { float remainingFactor = (startTime - lastWeatherFog.Time + lastWeatherFog.FogSetTimeS) / lastWeatherFog.FogSetTimeS; @@ -1351,14 +1332,14 @@ void StartPrecipitation(WeatherSettingPrecipitation lastWeatherPrecipitation, fl { AWPrecipitationRequiredType = lastWeatherPrecipitation.PrecipitationType; - // determine actual duration of precipitation + // Determine actual duration of precipitation float maxDuration = AWNextChangeTime - weatherDetails[AWActiveIndex].Time; AWPrecipitationTotalDuration = (float)maxDuration * (lastWeatherPrecipitation.PrecipitationProbability / 100f); // nominal value AWPrecipitationTotalDuration = (0.9f + ((float)Viewer.Random.Next(20) / 20)) * AWPrecipitationTotalDuration; // randomized value, +- 10% AWPrecipitationTotalDuration = Math.Min(AWPrecipitationTotalDuration, maxDuration); // but never exceeding maximum duration AWPrecipitationNextSpell = lastWeatherPrecipitation.Time; // set start of spell to start of weather change - // determine spread : no. of periods with precipitation (no. of showers) + // Determine spread: no. of periods with precipitation (no. of showers) if (lastWeatherPrecipitation.PrecipitationSpread == 1) { AWPrecipitationTotalSpread = 1; @@ -1366,22 +1347,21 @@ void StartPrecipitation(WeatherSettingPrecipitation lastWeatherPrecipitation, fl else { AWPrecipitationTotalSpread = Math.Max(1, (int)((0.9f + ((float)Viewer.Random.Next(20) / 20)) * lastWeatherPrecipitation.PrecipitationSpread)); - if ((AWPrecipitationTotalDuration / AWPrecipitationTotalSpread) < 900) // length of spell at least 15 mins + if ((AWPrecipitationTotalDuration / AWPrecipitationTotalSpread) < 900) // Length of spell at least 15 mins { AWPrecipitationTotalSpread = (int)(AWPrecipitationTotalDuration / 900); } } - - // determine actual precipitation state - only if immediate start allowed + // Determine actual precipitation state - only if immediate start allowed bool precipitationActive = allowImmediateStart && Viewer.Random.Next(100) >= lastWeatherPrecipitation.PrecipitationProbability; #if DEBUG_AUTOWEATHER Trace.TraceInformation("Precipitation active on start : {0}", precipitationActive.ToString()); #endif - // determine total remaining time as well as remaining periods, based on start/end time and present time - // this is independent from actual precipitation state + // Determine total remaining time as well as remaining periods, based on start/end time and present time + // This is independent from actual precipitation state if (AWPrecipitationTotalSpread > 1) { @@ -1389,10 +1369,10 @@ void StartPrecipitation(WeatherSettingPrecipitation lastWeatherPrecipitation, fl AWPrecipitationTotalSpread = (int)(((float)((AWNextChangeTime - startTime) / (AWNextChangeTime - weatherDetails[AWActiveIndex].Time))) * AWPrecipitationTotalSpread); } - // set actual details + // Set actual details if (precipitationActive) { - // precipitation active : set actual details, calculate end of present spell + // Precipitation active: set actual details, calculate end of present spell int precvariation = (int)(lastWeatherPrecipitation.PrecipitationVariation * 100); float baseDensitiy = PrecipitationViewer.MaxIntensityPPSPM2 * lastWeatherPrecipitation.PrecipitationDensity; AWPrecipitationActualPPSPM2 = MathHelper.Clamp((1.0f + ((float)Viewer.Random.Next(-precvariation, precvariation) / 100)) * baseDensitiy, @@ -1400,14 +1380,14 @@ void StartPrecipitation(WeatherSettingPrecipitation lastWeatherPrecipitation, fl AWPrecipitationRequiredPPSPM2 = MathHelper.Clamp((1.0f + ((float)Viewer.Random.Next(-precvariation, precvariation) / 100)) * baseDensitiy, PrecipitationViewer.MinIntensityPPSPM2, PrecipitationViewer.MaxIntensityPPSPM2); - // rate of change is max. difference over random timespan between 1 and 10 mins. - // startphase + // Rate of change is max. difference over random timespan between 1 and 10 mins. + // Startphase float startrate = (1.75f * lastWeatherPrecipitation.PrecipitationRateOfChange) + (0.5F * Viewer.Random.Next((int)(lastWeatherPrecipitation.PrecipitationRateOfChange * 100)) / 100f); float spellStartPhase = Math.Min(60f + (300f * startrate), 600); AWPrecipitationStartRate = (AWPrecipitationRequiredPPSPM2 - AWPrecipitationActualPPSPM2) / spellStartPhase; - // endphase + // Endphase float endrate = (1.75f * lastWeatherPrecipitation.PrecipitationRateOfChange) + (0.5F * Viewer.Random.Next((int)(lastWeatherPrecipitation.PrecipitationRateOfChange * 100)) / 100f); float spellEndPhase = Math.Min(60f + (300f * endrate), 600); @@ -1416,12 +1396,12 @@ void StartPrecipitation(WeatherSettingPrecipitation lastWeatherPrecipitation, fl float actduration = (0.5f + ((float)Viewer.Random.Next(100) / 100)) * avduration; float spellEndTime = Math.Min(startTime + actduration, AWNextChangeTime); AWPrecipitationEndSpell = Math.Max(startTime, spellEndTime - spellEndPhase); - // for end rate, use minimum precipitation + // For end rate, use minimum precipitation AWPrecipitationEndRate = (AWPrecipitationActualPPSPM2 - PrecipitationViewer.MinIntensityPPSPM2) / spellEndPhase; AWPrecipitationTotalDuration -= actduration; AWPrecipitationTotalSpread -= 1; - // calculate length of clear period and start of next spell + // Calculate length of clear period and start of next spell if (AWPrecipitationTotalDuration > 0 && AWPrecipitationTotalSpread > 0) { float avclearspell = (AWNextChangeTime - startTime - AWPrecipitationTotalDuration) / AWPrecipitationTotalSpread; @@ -1429,18 +1409,18 @@ void StartPrecipitation(WeatherSettingPrecipitation lastWeatherPrecipitation, fl } else { - AWPrecipitationNextSpell = AWNextChangeTime + 1; // set beyond next weather such that it never occurs + AWPrecipitationNextSpell = AWNextChangeTime + 1; // Set beyond next weather such that it never occurs } // set active values AWPrecipitationActiveType = lastWeatherPrecipitation.PrecipitationType; - AWOvercastCloudcover = lastWeatherPrecipitation.OvercastPrecipitationStart / 100; // fixed cloudcover during precipitation + AWOvercastCloudcover = lastWeatherPrecipitation.OvercastPrecipitationStart / 100; // Fixed cloudcover during precipitation AWActualVisibility = lastWeatherPrecipitation.PrecipitationVisibilityAtMinDensityM + (float)(Math.Sqrt(AWPrecipitationActualPPSPM2 / PrecipitationViewer.MaxIntensityPPSPM2) * (lastWeatherPrecipitation.PrecipitationVisibilityAtMaxDensityM - lastWeatherPrecipitation.PrecipitationVisibilityAtMinDensityM)); - AWLastVisibility = lastWeatherPrecipitation.PrecipitationVisibilityAtMinDensityM; // fix last visibility to visibility at minimum density + AWLastVisibility = lastWeatherPrecipitation.PrecipitationVisibilityAtMinDensityM; // Fix last visibility to visibility at minimum density } else - // if presently not active, set start of next spell + // If presently not active, set start of next spell { if (AWPrecipitationTotalSpread < 1) { @@ -1477,16 +1457,16 @@ void StartPrecipitationSpell(WeatherSettingPrecipitation lastWeatherPrecipitatio PrecipitationViewer.MinIntensityPPSPM2, PrecipitationViewer.MaxIntensityPPSPM2); AWLastVisibility = Weather.FogDistance; - // rate of change at start is max. difference over defined time span +- 10%, scaled between 1/2 and 4 mins + // Rate of change at start is max. difference over defined time span +- 10%, scaled between 1/2 and 4 mins float startphase = MathHelper.Clamp(lastWeatherPrecipitation.PrecipitationStartPhaseS * (0.9f + (Viewer.Random.Next(100) / 1000)), 30, 240); AWPrecipitationStartRate = (AWPrecipitationRequiredPPSPM2 - AWPrecipitationActualPPSPM2) / startphase; AWPrecipitationRateOfChangePPSPM2PS = AWPrecipitationStartRate; - // rate of change at end is max. difference over defined time span +- 10%, scaled between 1/2 and 6 mins + // Rate of change at end is max. difference over defined time span +- 10%, scaled between 1/2 and 6 mins float endphase = MathHelper.Clamp(lastWeatherPrecipitation.PrecipitationEndPhaseS * (0.9f + (Viewer.Random.Next(100) / 1000)), 30, 360); AWPrecipitationEndRate = (AWPrecipitationRequiredPPSPM2 - AWPrecipitationActualPPSPM2) / endphase; - // calculate end of spell and start of next spell + // Calculate end of spell and start of next spell if (AWPrecipitationTotalSpread > 1) { float avduration = AWPrecipitationTotalDuration / AWPrecipitationTotalSpread; @@ -1498,7 +1478,7 @@ void StartPrecipitationSpell(WeatherSettingPrecipitation lastWeatherPrecipitatio AWPrecipitationTotalSpread -= 1; int clearSpell = (int)((nextWeatherTime - spellEndTime - AWPrecipitationTotalDuration) / AWPrecipitationTotalSpread); - AWPrecipitationNextSpell = spellEndTime + 60f; // always a minute between spells + AWPrecipitationNextSpell = spellEndTime + 60f; // Always a minute between spells AWPrecipitationNextSpell = clearSpell > 0 ? AWPrecipitationNextSpell + Viewer.Random.Next(clearSpell) : AWPrecipitationNextSpell; } else @@ -1511,7 +1491,6 @@ void StartPrecipitationSpell(WeatherSettingPrecipitation lastWeatherPrecipitatio (AWPrecipitationEndSpell - Time), startphase, endphase, AWPrecipitationRequiredPPSPM2, PrecipitationViewer.MaxIntensityPPSPM2, AWPrecipitationRateOfChangePPSPM2PS, AWPrecipitationStartRate, AWPrecipitationEndRate); #endif - } void CalculatePrecipitation(WeatherSettingPrecipitation lastWeatherPrecipitation, ElapsedTime elapsedTime) @@ -1538,7 +1517,7 @@ void CalculatePrecipitation(WeatherSettingPrecipitation lastWeatherPrecipitation AWLastVisibility = lastWeatherPrecipitation.PrecipitationVisibilityAtMinDensityM; // reach required density, so from now on visibility is determined by density } - // calculate visibility - use last visibility which is either visibility at start of precipitation (at start of spell) or visibility at minimum density (after reaching required density) + // Calculate visibility: use last visibility which is either visibility at start of precipitation (at start of spell) or visibility at minimum density (after reaching required density) float reqVisibility = lastWeatherPrecipitation.PrecipitationVisibilityAtMinDensityM + ((float)Math.Sqrt(AWPrecipitationRequiredPPSPM2 / PrecipitationViewer.MaxIntensityPPSPM2) * (lastWeatherPrecipitation.PrecipitationVisibilityAtMaxDensityM - lastWeatherPrecipitation.PrecipitationVisibilityAtMinDensityM)); AWActualVisibility = AWLastVisibility + (float)(Math.Sqrt(AWPrecipitationActualPPSPM2 / AWPrecipitationRequiredPPSPM2) * @@ -1579,10 +1558,10 @@ float CalculateOvercast(float requiredOvercast, float overcastVariation, float o public override void SaveWeatherParameters(BinaryWriter outf) { - // set indication to automatic weather + // Set indication to automatic weather outf.Write(1); - // save input details + // Save input details foreach (WeatherSetting autoweather in weatherDetails) { if (autoweather is WeatherSettingFog) @@ -1634,7 +1613,7 @@ public override void RestoreWeatherParameters(BinaryReader inf) { int weathercontroltype = inf.ReadInt32(); - // restoring wrong type of weather - abort + // Restoring wrong type of weather - abort if (weathercontroltype != 1) { Trace.TraceError(Simulator.Catalog.GetString("Restoring wrong weather type : trying to restore user controlled weather but save contains dynamic weather")); @@ -1668,7 +1647,7 @@ public override void RestoreWeatherParameters(BinaryReader inf) } else { - // error - nothing to report it here + // Error - nothing to report it here endread = true; } @@ -1706,6 +1685,5 @@ public override void RestoreWeatherParameters(BinaryReader inf) Time = (float)Viewer.Simulator.ClockTime; } - } }