/
Viewer.cs
1926 lines (1742 loc) · 95.4 KB
/
Viewer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// COPYRIGHT 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 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 <http://www.gnu.org/licenses/>.
// This file is the responsibility of the 3D & Environment Team.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Threading;
using System.Windows.Forms;
using GNU.Gettext;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Orts.Common;
using Orts.Formats.Msts;
using Orts.MultiPlayer;
using Orts.Simulation;
using Orts.Simulation.AIs;
using Orts.Simulation.Physics;
using Orts.Simulation.RollingStocks;
using Orts.Viewer3D.Popups;
using Orts.Viewer3D.Processes;
using Orts.Viewer3D.RollingStock;
using ORTS.Common;
using ORTS.Common.Input;
using ORTS.Scripting.Api;
using ORTS.Settings;
using Event = Orts.Common.Event;
namespace Orts.Viewer3D
{
public class Viewer
{
public static GettextResourceManager Catalog { get; private set; }
public static Random Random { get; private set; }
// User setups.
public UserSettings Settings { get; private set; }
private readonly SavingProperty<bool> Use3DCabProperty;
// Multi-threaded processes
public LoaderProcess LoaderProcess { get; private set; }
public UpdaterProcess UpdaterProcess { get; private set; }
public RenderProcess RenderProcess { get; private set; }
public SoundProcess SoundProcess { get; private set; }
// Access to the XNA Game class
public GraphicsDevice GraphicsDevice { get; private set; }
public string ContentPath { get; private set; }
public SharedTextureManager TextureManager { get; private set; }
public SharedMaterialManager MaterialManager { get; private set; }
public SharedShapeManager ShapeManager { get; private set; }
public SignalTypeDataManager SignalTypeDataManager { get; private set; }
public Point DisplaySize { get { return RenderProcess.DisplaySize; } }
// Components
public Orts.Viewer3D.Processes.Game Game { get; private set; }
public Simulator Simulator { get; private set; }
public World World { get; private set; }
private SoundSource ViewerSounds { get; set; }
/// <summary>
/// Monotonically increasing time value (in seconds) for the game/viewer. Starts at 0 and only ever increases, at real-time.
/// </summary>
public double RealTime { get; private set; }
InfoDisplay InfoDisplay;
public WindowManager WindowManager { get; private set; }
public MessagesWindow MessagesWindow { get; private set; } // Game message window (special, always visible)
public NoticeWindow NoticeWindow { get; private set; } // Game notices window (special)
public PauseWindow PauseWindow { get; private set; } // Game paused window (special)
public ActivityWindow ActivityWindow { get; private set; } // Activity notices window
public QuitWindow QuitWindow { get; private set; } // Escape window
public HelpWindow HelpWindow { get; private set; } // F1 window
public TrackMonitorWindow TrackMonitorWindow { get; private set; } // F4 window
public HUDWindow HUDWindow { get; private set; } // F5 hud
public TrainDrivingWindow TrainDrivingWindow { get; private set; } // F5 train driving window
public MultiPlayerWindow MultiPlayerWindow { get; private set; } // Shift+9 MultiPlayer data windowed
public OSDLocations OSDLocations { get; private set; } // F6 platforms/sidings OSD
public OSDCars OSDCars { get; private set; } // F7 cars OSD
public SwitchWindow SwitchWindow { get; private set; } // F8 window
public TrainOperationsWindow TrainOperationsWindow { get; private set; } // F9 window
public CarOperationsWindow CarOperationsWindow { get; private set; } // F9 sub-window for car operations
public TrainDpuWindow TrainDpuWindow { get; private set; } // Shift + F9 train distributed power window
public NextStationWindow NextStationWindow { get; private set; } // F10 window
public CompassWindow CompassWindow { get; private set; } // 0 window
public TracksDebugWindow TracksDebugWindow { get; private set; } // Control-Alt-F6
public SignallingDebugWindow SignallingDebugWindow { get; private set; } // Control-Alt-F11 window
public ComposeMessage ComposeMessageWindow { get; private set; } // ??? window
public TrainListWindow TrainListWindow { get; private set; } // for switching driven train
public TTDetachWindow TTDetachWindow { get; private set; } // for detaching player train in timetable mode
// Route Information
public TileManager Tiles { get; private set; }
public TileManager LoTiles { get; private set; }
public EnvironmentFile ENVFile { get; private set; }
public SignalConfigurationFile SIGCFG { get; private set; }
public TrackTypesFile TrackTypes { get; private set; }
public SpeedpostDatFile SpeedpostDatFile;
public bool MilepostUnitsMetric { get; private set; }
// Cameras
public Camera Camera { get; set; } // Current camera
public Camera AbovegroundCamera { get; private set; } // Previous camera for when automatically switching to cab.
/// <summary>
/// Camera #1, 2D cab. Swaps with <see cref="ThreeDimCabCamera"/> with Alt+1.
/// </summary>
private readonly CabCamera CabCamera;
/// <summary>
/// Camera #1, 3D cab. Swaps with <see cref="CabCamera"/> with Alt+1.
/// </summary>
private readonly ThreeDimCabCamera ThreeDimCabCamera;
public HeadOutCamera HeadOutForwardCamera { get; private set; } // Camera 1+Up
public HeadOutCamera HeadOutBackCamera { get; private set; } // Camera 2+Down
public TrackingCamera FrontCamera { get; private set; } // Camera 2
public TrackingCamera BackCamera { get; private set; } // Camera 3
public TracksideCamera TracksideCamera { get; private set; } // Camera 4
public SpecialTracksideCamera SpecialTracksideCamera { get; private set; } // Camera 4 for special points (platforms and level crossings)
public PassengerCamera PassengerCamera { get; private set; } // Camera 5
public BrakemanCamera BrakemanCamera { get; private set; } // Camera 6
public List<FreeRoamCamera> FreeRoamCameraList = new List<FreeRoamCamera>();
public FreeRoamCamera FreeRoamCamera { get { return FreeRoamCameraList[0]; } } // Camera 8
/// <summary>
/// Activate the 2D or 3D cab camera depending on the current player preference.
/// </summary>
public void ActivateCabCamera()
{
if (Settings.Use3DCab && ThreeDimCabCamera.IsAvailable)
ThreeDimCabCamera.Activate();
else
CabCamera.Activate();
}
/// <summary>
/// Toggle the 2D/3D cab preference and, if already in the cab camera, switch modes.
/// </summary>
public void ToggleCabCameraView()
{
Use3DCabProperty.Value = !Use3DCabProperty.Value;
if (Camera == CabCamera || Camera == ThreeDimCabCamera)
ActivateCabCamera();
}
List<Camera> WellKnownCameras; // Providing Camera save functionality by GeorgeS
public TrainCarViewer PlayerLocomotiveViewer { get; private set; } // we are controlling this loco, or null if we aren't controlling any
MouseState originalMouseState; // Current mouse coordinates.
// This is the train we are controlling
public TrainCar PlayerLocomotive { get { return Simulator.PlayerLocomotive; } set { Simulator.PlayerLocomotive = value; } }
public Train PlayerTrain { get { if (PlayerLocomotive == null) return null; else return PlayerLocomotive.Train; } }
// This is the train we are viewing
public Train SelectedTrain { get; private set; }
void CameraActivate()
{
if (Camera == null || !Camera.IsAvailable) //passenger camera may jump to a train without passenger view
FrontCamera.Activate();
else
Camera.Activate();
}
bool ForceMouseVisible;
double MouseVisibleTillRealTime;
public Cursor ActualCursor = Cursors.Default;
public static Viewport DefaultViewport;
ICabViewMouseControlRenderer MouseChangingControl;
ICabViewMouseControlRenderer MousePickedControl;
ICabViewMouseControlRenderer OldMousePickedControl;
public bool SaveScreenshot { get; set; }
public bool SaveActivityThumbnail { get; private set; }
public string SaveActivityFileStem { get; private set; }
public Vector3 NearPoint { get; private set; }
public Vector3 FarPoint { get; private set; }
public bool DebugViewerEnabled { get; set; }
public bool SoundDebugFormEnabled { get; set; }
public TRPFile TRP; // Track profile file
enum VisibilityState
{
Visible,
Hidden,
ScreenshotPending,
};
VisibilityState Visibility = VisibilityState.Visible;
// MSTS cab views are images with aspect ratio 4:3.
// OR can use cab views with other aspect ratios where these are available.
// On screen with other aspect ratios (e.g. 16:9), three approaches are possible:
// 1) stretch the width to fit the screen. This gives flattened controls, most noticeable with round dials.
// 2) clip the image losing a slice off top and bottom.
// 3) letterbox the image by drawing black bars in the unfilled spaces.
// Setting.Cab2DStretch controls the amount of stretch and clip. 0 is entirely clipped and 100 is entirely stretched.
// No difference is seen on screens with 4:3 aspect ratio.
// This adjustment assumes that the cab view is 4:3. Where the cab view matches the aspect ratio of the screen, use an adjustment of 100.
public int CabHeightPixels { get; private set; }
public int CabWidthPixels { get; private set; }
public int CabYOffsetPixels { get; set; } // Note: Always -ve. Without it, the cab view is fixed to the top of the screen. -ve values pull it up the screen.
public int CabXOffsetPixels { get; set; }
public int CabExceedsDisplay; // difference between cabview texture vertical resolution and display vertical resolution
public int CabExceedsDisplayHorizontally; // difference between cabview texture horizontal resolution and display vertical resolution
public int CabYLetterboxPixels { get; set; } // offset the cab when drawing it if it is smaller than the display; both coordinates should always be >= 0
public int CabXLetterboxPixels { get; set; }
public float CabTextureInverseRatio = 0.75f; // default of inverse of cab texture ratio
public CommandLog Log { get { return Simulator.Log; } }
public bool DontLoadNightTextures; // Checkbox set and time of day allows not to load textures
public bool DontLoadDayTextures; // Checkbox set and time of day allows not to load textures
public bool NightTexturesNotLoaded; // At least one night texture hasn't been loaded
public bool DayTexturesNotLoaded; // At least one day texture hasn't been loaded
public long LoadMemoryThreshold; // Above this threshold loader doesn't bulk load day or night textures
public bool tryLoadingNightTextures = false;
public bool tryLoadingDayTextures = false;
public int poscounter = 1; // counter for print position info
public Camera SuspendedCamera { get; private set; }
UserInputRailDriver RailDriver;
public static double DbfEvalAutoPilotTimeS = 0;//Debrief eval
public static double DbfEvalIniAutoPilotTimeS = 0;//Debrief eval
public bool DbfEvalAutoPilot = false;//DebriefEval
/// <summary>
/// Finds time of last entry to set ReplayEndsAt and provide the Replay started message.
/// </summary>
void InitReplay()
{
if (Simulator.ReplayCommandList != null)
{
// Get time of last entry
int lastEntry = Simulator.ReplayCommandList.Count - 1;
if (lastEntry >= 0)
{
double lastTime = Simulator.ReplayCommandList[lastEntry].Time;
Log.ReplayEndsAt = lastTime;
double duration = lastTime - Simulator.ClockTime;
MessagesWindow.AddMessage(String.Format("Replay started: ending at {0} after {1}",
FormatStrings.FormatApproximateTime(lastTime),
FormatStrings.FormatTime(duration)),
3.0);
}
}
}
/// <summary>
/// Initializes a new instances of the <see cref="Viewer3D"/> class based on the specified <paramref name="simulator"/> and <paramref name="game"/>.
/// </summary>
/// <param name="simulator">The <see cref="Simulator"/> with which the viewer runs.</param>
/// <param name="game">The <see cref="Game"/> with which the viewer runs.</param>
[CallOnThread("Loader")]
public Viewer(Simulator simulator, Orts.Viewer3D.Processes.Game game)
{
Catalog = new GettextResourceManager("RunActivity");
Random = new Random();
Simulator = simulator;
Game = game;
Settings = simulator.Settings;
Use3DCabProperty = Settings.GetSavingProperty<bool>("Use3DCab");
RenderProcess = game.RenderProcess;
UpdaterProcess = game.UpdaterProcess;
LoaderProcess = game.LoaderProcess;
SoundProcess = game.SoundProcess;
WellKnownCameras = new List<Camera>();
WellKnownCameras.Add(CabCamera = new CabCamera(this));
WellKnownCameras.Add(FrontCamera = new TrackingCamera(this, TrackingCamera.AttachedTo.Front));
WellKnownCameras.Add(BackCamera = new TrackingCamera(this, TrackingCamera.AttachedTo.Rear));
WellKnownCameras.Add(PassengerCamera = new PassengerCamera(this));
WellKnownCameras.Add(BrakemanCamera = new BrakemanCamera(this));
WellKnownCameras.Add(HeadOutForwardCamera = new HeadOutCamera(this, HeadOutCamera.HeadDirection.Forward));
WellKnownCameras.Add(HeadOutBackCamera = new HeadOutCamera(this, HeadOutCamera.HeadDirection.Backward));
WellKnownCameras.Add(TracksideCamera = new TracksideCamera(this));
WellKnownCameras.Add(SpecialTracksideCamera = new SpecialTracksideCamera(this));
WellKnownCameras.Add(new FreeRoamCamera(this, FrontCamera)); // Any existing camera will suffice to satisfy .Save() and .Restore()
WellKnownCameras.Add(ThreeDimCabCamera = new ThreeDimCabCamera(this));
string ORfilepath = System.IO.Path.Combine(Simulator.RoutePath, "OpenRails");
ContentPath = Game.ContentPath;
Trace.Write(" ENV");
ENVFile = new EnvironmentFile(Simulator.RoutePath + @"\ENVFILES\" + Simulator.TRK.Tr_RouteFile.Environment.ENVFileName(Simulator.Season, Simulator.WeatherType));
Trace.Write(" SIGCFG");
if (File.Exists(ORfilepath + @"\sigcfg.dat"))
{
Trace.Write(" SIGCFG_OR");
SIGCFG = new SignalConfigurationFile(ORfilepath + @"\sigcfg.dat", true);
}
else
{
Trace.Write(" SIGCFG");
SIGCFG = new SignalConfigurationFile(Simulator.RoutePath + @"\sigcfg.dat", false);
}
Trace.Write(" TTYPE");
TrackTypes = new TrackTypesFile(Simulator.RoutePath + @"\TTYPE.DAT");
Tiles = new TileManager(Simulator.RoutePath + @"\TILES\", false);
LoTiles = new TileManager(Simulator.RoutePath + @"\LO_TILES\", true);
MilepostUnitsMetric = Simulator.TRK.Tr_RouteFile.MilepostUnitsMetric;
RailDriver = new UserInputRailDriver(Simulator.BasePath);
Simulator.AllowedSpeedRaised += (object sender, EventArgs e) =>
{
var train = sender as Train;
if (!TrackMonitorWindow.Visible && Simulator.Confirmer != null && train != null)
{
var message = Catalog.GetStringFmt("Allowed speed raised to {0}", FormatStrings.FormatSpeedDisplay(train.AllowedMaxSpeedMpS, MilepostUnitsMetric));
Simulator.Confirmer.Message(ConfirmLevel.Information, message);
}
};
Simulator.PlayerLocomotiveChanged += PlayerLocomotiveChanged;
Simulator.PlayerTrainChanged += PlayerTrainChanged;
Simulator.RequestTTDetachWindow += RequestTTDetachWindow;
// The speedpost.dat file is needed only to derive the shape names for the temporary speed restriction zones,
// so it is opened only in activity mode
if (Simulator.ActivityRun != null && Simulator.Activity.Tr_Activity.Tr_Activity_File.ActivityRestrictedSpeedZones != null)
{
var speedpostDatFile = Simulator.RoutePath + @"\speedpost.dat";
if (File.Exists(speedpostDatFile))
{
Trace.Write(" SPEEDPOST");
SpeedpostDatFile = new SpeedpostDatFile(Simulator.RoutePath + @"\speedpost.dat", Simulator.RoutePath + @"\shapes\");
}
}
Initialize();
}
[CallOnThread("Updater")]
public void Save(BinaryWriter outf, string fileStem)
{
outf.Write(Simulator.Trains.IndexOf(PlayerTrain));
outf.Write(PlayerTrain.Cars.IndexOf(PlayerLocomotive));
outf.Write(Simulator.Trains.IndexOf(SelectedTrain));
WindowManager.Save(outf);
outf.Write(WellKnownCameras.IndexOf(Camera));
foreach (var camera in WellKnownCameras)
camera.Save(outf);
Camera.Save(outf);
outf.Write(CabYOffsetPixels);
outf.Write(CabXOffsetPixels);
// Set these so RenderFrame can use them when its thread gets control.
SaveActivityFileStem = fileStem;
SaveActivityThumbnail = true;
outf.Write(NightTexturesNotLoaded);
outf.Write(DayTexturesNotLoaded);
World.WeatherControl.SaveWeatherParameters(outf);
}
[CallOnThread("Render")]
public void Restore(BinaryReader inf)
{
Train playerTrain = Simulator.Trains[inf.ReadInt32()];
PlayerLocomotive = playerTrain.Cars[inf.ReadInt32()];
var selected = inf.ReadInt32();
if (selected >= 0 && selected < Simulator.Trains.Count)
{
SelectedTrain = Simulator.Trains[selected];
}
else if (selected < 0)
{
SelectedTrain = Simulator.Trains[0];
}
WindowManager.Restore(inf);
var cameraToRestore = inf.ReadInt32();
foreach (var camera in WellKnownCameras)
camera.Restore(inf);
if (cameraToRestore == -1)
new FreeRoamCamera(this, Camera).Activate();
else
WellKnownCameras[cameraToRestore].Activate();
Camera.Restore(inf);
CabYOffsetPixels = inf.ReadInt32();
CabXOffsetPixels = inf.ReadInt32();
NightTexturesNotLoaded = inf.ReadBoolean();
DayTexturesNotLoaded = inf.ReadBoolean();
LoadMemoryThreshold = (long)HUDWindow.GetVirtualAddressLimit() - 512 * 1024 * 1024;
tryLoadingNightTextures = true;
tryLoadingDayTextures = true;
World.WeatherControl.RestoreWeatherParameters(inf);
}
/// <summary>
/// Called once after the graphics device is ready
/// to load any static graphics content, background
/// processes haven't started yet.
/// </summary>
[CallOnThread("Loader")]
internal void Initialize()
{
GraphicsDevice = RenderProcess.GraphicsDevice;
UpdateAdapterInformation(GraphicsDevice.Adapter);
DefaultViewport = GraphicsDevice.Viewport;
if (PlayerLocomotive == null) PlayerLocomotive = Simulator.InitialPlayerLocomotive();
SelectedTrain = PlayerTrain;
PlayerTrain.InitializePlayerTrainData();
if (PlayerTrain.TrainType == Train.TRAINTYPE.AI_PLAYERHOSTING)
{
Simulator.Trains[0].LeadLocomotive = null;
Simulator.Trains[0].LeadLocomotiveIndex = -1;
}
InitializeAutomaticTrackSounds();
TextureManager = new SharedTextureManager(this, GraphicsDevice);
AdjustCabHeight(DisplaySize.X, DisplaySize.Y); // needs TextureManager
MaterialManager = new SharedMaterialManager(this);
ShapeManager = new SharedShapeManager(this);
SignalTypeDataManager = new SignalTypeDataManager(this);
WindowManager = new WindowManager(this);
MessagesWindow = new MessagesWindow(WindowManager);
NoticeWindow = new NoticeWindow(WindowManager);
PauseWindow = new PauseWindow(WindowManager);
ActivityWindow = new ActivityWindow(WindowManager);
QuitWindow = new QuitWindow(WindowManager);
HelpWindow = new HelpWindow(WindowManager);
TrackMonitorWindow = new TrackMonitorWindow(WindowManager);
HUDWindow = new HUDWindow(WindowManager);
TrainDrivingWindow = new TrainDrivingWindow(WindowManager);
OSDLocations = new OSDLocations(WindowManager);
OSDCars = new OSDCars(WindowManager);
SwitchWindow = new SwitchWindow(WindowManager);
TrainOperationsWindow = new TrainOperationsWindow(WindowManager);
MultiPlayerWindow = new MultiPlayerWindow(WindowManager);
CarOperationsWindow = new CarOperationsWindow(WindowManager);
TrainDpuWindow = new TrainDpuWindow(WindowManager);
NextStationWindow = new NextStationWindow(WindowManager);
CompassWindow = new CompassWindow(WindowManager);
TracksDebugWindow = new TracksDebugWindow(WindowManager);
SignallingDebugWindow = new SignallingDebugWindow(WindowManager);
ComposeMessageWindow = new ComposeMessage(WindowManager);
TrainListWindow = new TrainListWindow(WindowManager);
TTDetachWindow = new TTDetachWindow(WindowManager);
WindowManager.Initialize();
InfoDisplay = new InfoDisplay(this);
World = new World(this, Simulator.ClockTime);
ViewerSounds = new SoundSource(this, soundSource => new[]
{
new SoundStream(soundSource, soundStream => new[]
{
new ORTSDiscreteTrigger(soundStream, Event.TakeScreenshot, ORTSSoundCommand.Precompiled(Path.Combine(ContentPath, "TakeScreenshot.wav"), soundStream)),
}),
});
SoundProcess.AddSoundSource(this, ViewerSounds);
Simulator.Confirmer.PlayErrorSound += (s, e) =>
{
if (World.GameSounds != null)
World.GameSounds.HandleEvent(Event.ControlError);
};
Simulator.Confirmer.DisplayMessage += (s, e) => MessagesWindow.AddMessage(e.Key, e.Text, e.Duration);
if (CabCamera.IsAvailable || ThreeDimCabCamera.IsAvailable)
ActivateCabCamera();
else
CameraActivate();
// Prepare the world to be loaded and then load it from the correct thread for debugging/tracing purposes.
// This ensures that a) we have all the required objects loaded when the 3D view first appears and b) that
// all loading is performed on a single thread that we can handle in debugging and tracing.
World.LoadPrep();
if (Simulator.Settings.ConditionalLoadOfDayOrNightTextures) // We need to compute sun height only in this case
{
MaterialManager.LoadPrep();
LoadMemoryThreshold = (long)HUDWindow.GetVirtualAddressLimit() - 512 * 1024 * 1024;
}
Load();
// MUST be after loading is done! (Or we try and load shapes on the main thread.)
PlayerLocomotiveViewer = World.Trains.GetViewer(PlayerLocomotive);
SetCommandReceivers();
InitReplay();
}
/// <summary>
/// Each Command needs to know its Receiver so it can call a method of the Receiver to action the command.
/// The Receiver is a static property as all commands of the same class share the same Receiver
/// and it needs to be set before the command is used.
/// </summary>
public void SetCommandReceivers()
{
ReverserCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
NotchedThrottleCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
ContinuousThrottleCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
TrainBrakeCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
EngineBrakeCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
BrakemanBrakeCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
DynamicBrakeCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
InitializeBrakesCommand.Receiver = PlayerLocomotive.Train;
ResetOutOfControlModeCommand.Receiver = PlayerLocomotive.Train;
EmergencyPushButtonCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
HandbrakeCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
BailOffCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
QuickReleaseCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
BrakeOverchargeCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
RetainersCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
BrakeHoseConnectCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
ToggleWaterScoopCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
if (PlayerLocomotive is MSTSSteamLocomotive)
{
ContinuousReverserCommand.Receiver = (MSTSSteamLocomotive)PlayerLocomotive;
ContinuousInjectorCommand.Receiver = (MSTSSteamLocomotive)PlayerLocomotive;
ContinuousSmallEjectorCommand.Receiver = (MSTSSteamLocomotive)PlayerLocomotive;
ContinuousLargeEjectorCommand.Receiver = (MSTSSteamLocomotive)PlayerLocomotive;
ToggleInjectorCommand.Receiver = (MSTSSteamLocomotive)PlayerLocomotive;
ToggleBlowdownValveCommand.Receiver = (MSTSSteamLocomotive)PlayerLocomotive;
ContinuousBlowerCommand.Receiver = (MSTSSteamLocomotive)PlayerLocomotive;
ContinuousDamperCommand.Receiver = (MSTSSteamLocomotive)PlayerLocomotive;
ContinuousFiringRateCommand.Receiver = (MSTSSteamLocomotive)PlayerLocomotive;
ToggleManualFiringCommand.Receiver = (MSTSSteamLocomotive)PlayerLocomotive;
ToggleCylinderCocksCommand.Receiver = (MSTSSteamLocomotive)PlayerLocomotive;
ToggleCylinderCompoundCommand.Receiver = (MSTSSteamLocomotive)PlayerLocomotive;
FireShovelfullCommand.Receiver = (MSTSSteamLocomotive)PlayerLocomotive;
AIFireOnCommand.Receiver = (MSTSSteamLocomotive)PlayerLocomotive;
AIFireOffCommand.Receiver = (MSTSSteamLocomotive)PlayerLocomotive;
AIFireResetCommand.Receiver = (MSTSSteamLocomotive)PlayerLocomotive;
}
PantographCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
if (PlayerLocomotive is MSTSElectricLocomotive)
{
CircuitBreakerClosingOrderCommand.Receiver = (PlayerLocomotive as MSTSLocomotive).LocomotivePowerSupply;
CircuitBreakerClosingOrderButtonCommand.Receiver = (PlayerLocomotive as MSTSLocomotive).LocomotivePowerSupply;
CircuitBreakerOpeningOrderButtonCommand.Receiver = (PlayerLocomotive as MSTSLocomotive).LocomotivePowerSupply;
CircuitBreakerClosingAuthorizationCommand.Receiver = (PlayerLocomotive as MSTSLocomotive).LocomotivePowerSupply;
}
if (PlayerLocomotive is MSTSDieselLocomotive)
{
TractionCutOffRelayClosingOrderCommand.Receiver = (PlayerLocomotive as MSTSLocomotive).LocomotivePowerSupply;
TractionCutOffRelayClosingOrderButtonCommand.Receiver = (PlayerLocomotive as MSTSLocomotive).LocomotivePowerSupply;
TractionCutOffRelayOpeningOrderButtonCommand.Receiver = (PlayerLocomotive as MSTSLocomotive).LocomotivePowerSupply;
TractionCutOffRelayClosingAuthorizationCommand.Receiver = (PlayerLocomotive as MSTSLocomotive).LocomotivePowerSupply;
TogglePlayerEngineCommand.Receiver = (MSTSDieselLocomotive)PlayerLocomotive;
VacuumExhausterCommand.Receiver = (MSTSDieselLocomotive)PlayerLocomotive;
}
ImmediateRefillCommand.Receiver = (MSTSLocomotiveViewer)PlayerLocomotiveViewer;
RefillCommand.Receiver = (MSTSLocomotiveViewer)PlayerLocomotiveViewer;
ToggleOdometerCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
ResetOdometerCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
ToggleOdometerDirectionCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
SanderCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
AlerterCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
HornCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
BellCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
ToggleCabLightCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
WipersCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
HeadlightCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
ChangeCabCommand.Receiver = this;
ToggleDoorsLeftCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
ToggleDoorsRightCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
ToggleMirrorsCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
CabRadioCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
ToggleSwitchAheadCommand.Receiver = this;
ToggleSwitchBehindCommand.Receiver = this;
ToggleAnySwitchCommand.Receiver = this;
UncoupleCommand.Receiver = this;
SaveScreenshotCommand.Receiver = this;
ActivityCommand.Receiver = ActivityWindow; // and therefore shared by all sub-classes
UseCameraCommand.Receiver = this;
MoveCameraCommand.Receiver = this;
ToggleHelpersEngineCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
BatterySwitchCommand.Receiver = (PlayerLocomotive as MSTSLocomotive).LocomotivePowerSupply;
BatterySwitchCloseButtonCommand.Receiver = (PlayerLocomotive as MSTSLocomotive).LocomotivePowerSupply;
BatterySwitchOpenButtonCommand.Receiver = (PlayerLocomotive as MSTSLocomotive).LocomotivePowerSupply;
ToggleMasterKeyCommand.Receiver = (PlayerLocomotive as MSTSLocomotive).LocomotivePowerSupply;
ServiceRetentionButtonCommand.Receiver = (PlayerLocomotive as MSTSLocomotive).LocomotivePowerSupply;
ServiceRetentionCancellationButtonCommand.Receiver = (PlayerLocomotive as MSTSLocomotive).LocomotivePowerSupply;
ElectricTrainSupplyCommand.Receiver = (PlayerLocomotive as MSTSLocomotive).LocomotivePowerSupply;
TCSButtonCommand.Receiver = (PlayerLocomotive as MSTSLocomotive).TrainControlSystem;
TCSSwitchCommand.Receiver = (PlayerLocomotive as MSTSLocomotive).TrainControlSystem;
ToggleGenericItem1Command.Receiver = (MSTSLocomotive)PlayerLocomotive;
ToggleGenericItem2Command.Receiver = (MSTSLocomotive)PlayerLocomotive;
//Distributed power
DPMoveToFrontCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
DPMoveToBackCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
DPTractionCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
DPIdleCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
DPDynamicBrakeCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
DPMoreCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
DPLessCommand.Receiver = (MSTSLocomotive)PlayerLocomotive;
}
public void ChangeToPreviousFreeRoamCamera()
{
if (Camera == FreeRoamCamera)
{
// If 8 is the current camera, rotate the list and then activate a different camera.
RotateFreeRoamCameraList();
FreeRoamCamera.Activate();
}
else
{
FreeRoamCamera.Activate();
RotateFreeRoamCameraList();
}
}
void RotateFreeRoamCameraList()
{
// Rotate list moving 1 to 0 etc. (by adding 0 to end, then removing 0)
FreeRoamCameraList.Add(FreeRoamCamera);
FreeRoamCameraList.RemoveAt(0);
}
public void InitializeAutomaticTrackSounds()
{
SharedSMSFileManager.AutoTrackSound = false;
SharedSMSFileManager.SwitchSMSNumber = Simulator.TRK.Tr_RouteFile.SwitchSMSNumber;
if (SharedSMSFileManager.SwitchSMSNumber < -1 || SharedSMSFileManager.SwitchSMSNumber >= TrackTypes.Count)
{
SharedSMSFileManager.SwitchSMSNumber = -1;
Trace.TraceInformation("Switch SMS Number out of range");
}
if (SharedSMSFileManager.SwitchSMSNumber != -1) SharedSMSFileManager.AutoTrackSound = true;
SharedSMSFileManager.CurveSMSNumber = Simulator.TRK.Tr_RouteFile.CurveSMSNumber;
if (SharedSMSFileManager.CurveSMSNumber < -1 || SharedSMSFileManager.CurveSMSNumber >= TrackTypes.Count)
{
SharedSMSFileManager.CurveSMSNumber = -1;
Trace.TraceInformation("Curve SMS Number out of range");
}
if (SharedSMSFileManager.CurveSMSNumber != -1) SharedSMSFileManager.AutoTrackSound = true;
SharedSMSFileManager.CurveSwitchSMSNumber = Simulator.TRK.Tr_RouteFile.CurveSwitchSMSNumber;
if (SharedSMSFileManager.CurveSwitchSMSNumber < -1 || SharedSMSFileManager.CurveSwitchSMSNumber >= TrackTypes.Count)
{
SharedSMSFileManager.CurveSwitchSMSNumber = SharedSMSFileManager.CurveSMSNumber;
Trace.TraceInformation("CurveSwitch SMS Number out of range, replaced with curve SMS number");
}
if (SharedSMSFileManager.CurveSwitchSMSNumber != -1) SharedSMSFileManager.AutoTrackSound = true;
}
public void ChangeSelectedTrain(Train selectedTrain)
{
SelectedTrain = selectedTrain;
}
public void AdjustCabHeight(int windowWidth, int windowHeight)
{
CabTextureInverseRatio = 0.75f; // start setting it to default
// MSTS cab views are designed for 4:3 aspect ratio. This is the default. However a check is done with the actual
// cabview texture. If this has a different aspect ratio, that one is considered
// For wider screens (e.g. 16:9), the height of the cab view before adjustment exceeds the height of the display.
// The user can decide how much of this excess to keep. Setting of 0 keeps all the excess and 100 keeps none.
// <CSComment> If the aspect ratio of the viewing window is greater than the aspect ratio of the cabview texture file
// it is either possible to stretch the cabview texture file or to leave the proportions unaltered and to vertically pan
// the screen
if (CabCamera.IsAvailable)
{
var i = ((PlayerLocomotive as MSTSLocomotive).UsingRearCab) ? 1 : 0;
var cabTextureFileName = (PlayerLocomotive as MSTSLocomotive).CabViewList[i].CVFFile.TwoDViews[0];
var cabTextureInverseRatio = ComputeCabTextureInverseRatio(cabTextureFileName);
if (cabTextureInverseRatio != -1) CabTextureInverseRatio = cabTextureInverseRatio;
}
int unstretchedCabHeightPixels = (int)(CabTextureInverseRatio * windowWidth);
int unstretchedCabWidthPixels = (int)(windowHeight / CabTextureInverseRatio);
float windowInverseRatio = (float)windowHeight / windowWidth;
if (Settings.Letterbox2DCab)
{
CabWidthPixels = Math.Min((int)Math.Round(windowHeight / CabTextureInverseRatio), windowWidth);
CabHeightPixels = Math.Min((int)Math.Round(windowWidth * CabTextureInverseRatio), windowHeight);
CabXLetterboxPixels = (windowWidth - CabWidthPixels) / 2;
CabYLetterboxPixels = (windowHeight - CabHeightPixels) / 2;
CabExceedsDisplay = CabExceedsDisplayHorizontally = CabXOffsetPixels = CabYOffsetPixels = 0;
}
else
{
if (windowInverseRatio == CabTextureInverseRatio)
{
// nice, window aspect ratio and cabview aspect ratio are identical
CabExceedsDisplay = 0;
CabExceedsDisplayHorizontally = 0;
}
else if (windowInverseRatio < CabTextureInverseRatio)
{
// screen is wide-screen, so can choose between vertical scroll or horizontal stretch
CabExceedsDisplay = (int)((unstretchedCabHeightPixels - windowHeight) * ((100 - Settings.Cab2DStretch) / 100f));
CabExceedsDisplayHorizontally = 0;
}
else
{
// must scroll horizontally
CabExceedsDisplay = 0;
CabExceedsDisplayHorizontally = unstretchedCabWidthPixels - windowWidth;
}
CabHeightPixels = windowHeight + CabExceedsDisplay;
CabYOffsetPixels = -CabExceedsDisplay / 2; // Initial value is halfway. User can adjust with arrow keys.
CabWidthPixels = windowWidth + CabExceedsDisplayHorizontally;
CabXOffsetPixels = CabExceedsDisplayHorizontally / 2;
CabXLetterboxPixels = CabYLetterboxPixels = 0;
}
if (CabCamera.IsAvailable) CabCamera.Initialize();
}
public float ComputeCabTextureInverseRatio(string cabTextureFileName)
{
float cabTextureInverseRatio = -1;
bool _isNightTexture;
var cabTexture = CABTextureManager.GetTexture(cabTextureFileName, false, false, out _isNightTexture, false);
if (cabTexture != SharedMaterialManager.MissingTexture)
{
cabTextureInverseRatio = (float)cabTexture.Height / cabTexture.Width;
// if square cab texture files with dimension of at least 1024 pixels are used, they are considered as stretched 4 : 3 ones
if (cabTextureInverseRatio == 1 && cabTexture.Width >= 1024) cabTextureInverseRatio = 0.75f;
}
return cabTextureInverseRatio;
}
string adapterDescription;
public string AdapterDescription { get { return adapterDescription; } }
uint adapterMemory;
public uint AdapterMemory { get { return adapterMemory; } }
[CallOnThread("Updater")]
internal void UpdateAdapterInformation(GraphicsAdapter graphicsAdapter)
{
adapterDescription = graphicsAdapter.Description;
try
{
// Note that we might find multiple adapters with the same
// description; however, the chance of such adapters not having
// the same amount of video memory is very slim.
foreach (ManagementObject videoController in new ManagementClass("Win32_VideoController").GetInstances())
if (((string)videoController["Description"] == adapterDescription) && (videoController["AdapterRAM"] != null))
adapterMemory = (uint)videoController["AdapterRAM"];
}
catch (ManagementException error)
{
Trace.WriteLine(error);
}
catch (UnauthorizedAccessException error)
{
Trace.WriteLine(error);
}
}
[CallOnThread("Loader")]
public void Load()
{
World.Load();
WindowManager.Load();
}
[CallOnThread("Updater")]
public void Update(RenderFrame frame, float elapsedRealTime)
{
RealTime += elapsedRealTime;
var elapsedTime = new ElapsedTime(Simulator.GetElapsedClockSeconds(elapsedRealTime), elapsedRealTime);
if (ComposeMessageWindow.Visible == true)
{
UserInput.Handled();
ComposeMessageWindow.AppendMessage(UserInput.GetPressedKeys(), UserInput.GetPreviousPressedKeys());
}
HandleUserInput(elapsedTime);
UserInput.Handled();
// We need to do it also here, because passing from manual to auto a ReverseFormation may be needed
if (Camera is TrackingCamera && Camera.AttachedCar != null && Camera.AttachedCar.Train != null && Camera.AttachedCar.Train.FormationReversed)
{
Camera.AttachedCar.Train.FormationReversed = false;
(Camera as TrackingCamera).SwapCameras();
}
Simulator.Update(elapsedTime.ClockSeconds);
if (PlayerLocomotive.Train.BrakingTime == -2) // We just had a wagon with stuck brakes
{
LoadDefectCarSound(PlayerLocomotive.Train.Cars[-(int)PlayerLocomotive.Train.ContinuousBrakingTime], "BrakesStuck.sms");
}
if (MPManager.IsMultiPlayer())
{
MPManager.Instance().PreUpdate();
//get key strokes and determine if some messages should be sent
MultiPlayerViewer.HandleUserInput();
MPManager.Instance().Update(Simulator.GameTime);
}
RailDriver.Update(PlayerLocomotive);
// This has to be done also for stopped trains
var cars = World.Trains.Cars;
foreach (var car in cars)
car.Value.UpdateSoundPosition();
if (Simulator.ReplayCommandList != null)
{
Log.Update(Simulator.ReplayCommandList);
if (Log.PauseState == ReplayPauseState.Due)
{
if (Simulator.Settings.ReplayPauseBeforeEnd)
{
// Reveal Quit Menu
QuitWindow.Visible = Simulator.Paused = !QuitWindow.Visible;
Log.PauseState = ReplayPauseState.During;
}
else
{
Log.PauseState = ReplayPauseState.Done;
}
}
}
if (Log.ReplayComplete)
{
MessagesWindow.AddMessage("Replay complete", 2);
Log.ReplayComplete = false;
}
World.Update(elapsedTime);
if (frame.IsScreenChanged)
Camera.ScreenChanged();
// Check if you need to swap camera
if (Camera is TrackingCamera && Camera.AttachedCar != null && Camera.AttachedCar.Train != null && Camera.AttachedCar.Train.FormationReversed)
{
Camera.AttachedCar.Train.FormationReversed = false;
(Camera as TrackingCamera).SwapCameras();
}
// Update camera first...
Camera.Update(elapsedTime);
// No above camera means we're allowed to auto-switch to cab view.
if ((AbovegroundCamera == null) && Camera.IsUnderground)
{
AbovegroundCamera = Camera;
bool ViewingPlayer = true;
if (Camera.AttachedCar != null) ViewingPlayer = Camera.AttachedCar.Train == Simulator.PlayerLocomotive.Train;
if ((Simulator.PlayerLocomotive.HasFront3DCab || Simulator.PlayerLocomotive.HasRear3DCab && ViewingPlayer) && !(Camera is CabCamera))
{
ThreeDimCabCamera.Activate();
}
else if ((Simulator.PlayerLocomotive.HasFrontCab || Simulator.PlayerLocomotive.HasRearCab) && ViewingPlayer)
{
CabCamera.Activate();
}
else
{
Simulator.Confirmer.Warning(Viewer.Catalog.GetString("Cab view not available"));
}
}
else if (AbovegroundCamera != null
&& Camera.AttachedCar != null
&& Camera.AttachedCar.Train == Simulator.PlayerLocomotive.Train)
{
// The AbovegroundCamera.Update() has been creating an odd sound issue when the locomotive is in the tunnel.
// Allowing the update to take place when only in cab view solved the issue.
if (Camera == CabCamera || Camera == ThreeDimCabCamera)
AbovegroundCamera.Update(elapsedTime);
if (!AbovegroundCamera.IsUnderground)
{
// But only if the user hasn't selected another camera!
if (Camera == CabCamera || Camera == ThreeDimCabCamera)
AbovegroundCamera.Activate();
AbovegroundCamera = null;
}
}
Simulator.ActiveMovingTable = FindActiveMovingTable();
frame.PrepareFrame(this);
Camera.PrepareFrame(frame, elapsedTime);
frame.PrepareFrame(elapsedTime);
World.PrepareFrame(frame, elapsedTime);
InfoDisplay.PrepareFrame(frame, elapsedTime);
// TODO: This is not correct. The ActivityWindow's PrepareFrame is already called by the WindowManager!
if (Simulator.ActivityRun != null) ActivityWindow.PrepareFrame(elapsedTime, true);
WindowManager.PrepareFrame(frame, elapsedTime);
}
private void LoadDefectCarSound(TrainCar car, string filename)
{
var smsFilePath = Simulator.BasePath + @"\sound\" + filename;
if (!File.Exists(smsFilePath))
{
Trace.TraceWarning("Cannot find defect car sound file {0}", filename);
return;
}
try
{
SoundProcess.AddSoundSource(this, new SoundSource(this, car as MSTSWagon, smsFilePath));
}
catch (Exception error)
{
Trace.WriteLine(new FileLoadException(smsFilePath, error));
}
}
[CallOnThread("Updater")]
void HandleUserInput(ElapsedTime elapsedTime)
{
var train = Program.Viewer.PlayerLocomotive.Train;//DebriefEval
if (UserInput.IsMouseLeftButtonDown || (Camera is ThreeDimCabCamera && RenderProcess.IsMouseVisible))
{
Vector3 nearsource = new Vector3((float)UserInput.MouseX, (float)UserInput.MouseY, 0f);
Vector3 farsource = new Vector3((float)UserInput.MouseX, (float)UserInput.MouseY, 1f);
Matrix world = Matrix.CreateTranslation(0, 0, 0);
NearPoint = DefaultViewport.Unproject(nearsource, Camera.XnaProjection, Camera.XnaView, world);
FarPoint = DefaultViewport.Unproject(farsource, Camera.XnaProjection, Camera.XnaView, world);
}
if (UserInput.IsPressed(UserCommand.CameraReset))
Camera.Reset();
Camera.HandleUserInput(elapsedTime);
if (PlayerLocomotiveViewer != null)
PlayerLocomotiveViewer.HandleUserInput(elapsedTime);
InfoDisplay.HandleUserInput(elapsedTime);
WindowManager.HandleUserInput(elapsedTime);
// Check for game control keys
if (MPManager.IsMultiPlayer() && UserInput.IsPressed(UserCommand.GameMultiPlayerTexting))
{
if (ComposeMessageWindow == null) ComposeMessageWindow = new ComposeMessage(WindowManager);
ComposeMessageWindow.InitMessage();
}
if ((MPManager.IsMultiPlayer() || (Settings.MultiplayerClient && MPManager.Simulator.Confirmer != null)) && UserInput.IsPressed(UserCommand.DisplayMultiPlayerWindow)){ MultiPlayerWindow.Visible = !MultiPlayerWindow.Visible; }
if (!MPManager.IsMultiPlayer() && UserInput.IsPressed(UserCommand.GamePauseMenu)) { QuitWindow.Visible = Simulator.Paused = !QuitWindow.Visible; }
if (MPManager.IsMultiPlayer() && UserInput.IsPressed(UserCommand.GamePauseMenu)) { if (Simulator.Confirmer != null) Simulator.Confirmer.Information(Viewer.Catalog.GetString("In MP, use Alt-F4 to quit directly")); }
if (UserInput.IsPressed(UserCommand.GameFullscreen)) { RenderProcess.ToggleFullScreen(); }
if (!MPManager.IsMultiPlayer() && UserInput.IsPressed(UserCommand.GamePause)) Simulator.Paused = !Simulator.Paused;
if (!MPManager.IsMultiPlayer() && UserInput.IsPressed(UserCommand.DebugSpeedUp))
{
Simulator.GameSpeed *= 1.5f;
Simulator.Confirmer.ConfirmWithPerCent(CabControl.SimulationSpeed, CabSetting.Increase, Simulator.GameSpeed * 100);
}
if (!MPManager.IsMultiPlayer() && UserInput.IsPressed(UserCommand.DebugSpeedDown))
{
Simulator.GameSpeed /= 1.5f;
Simulator.Confirmer.ConfirmWithPerCent(CabControl.SimulationSpeed, CabSetting.Decrease, Simulator.GameSpeed * 100);
}
if (UserInput.IsPressed(UserCommand.DebugSpeedReset))
{
Simulator.GameSpeed = 1;
Simulator.Confirmer.ConfirmWithPerCent(CabControl.SimulationSpeed, CabSetting.Off, Simulator.GameSpeed * 100);
}
if (UserInput.IsPressed(UserCommand.GameSave)) { GameStateRunActivity.Save(); }
if (UserInput.IsPressed(UserCommand.DisplayHelpWindow)) if (UserInput.IsDown(UserCommand.DisplayNextWindowTab)) HelpWindow.TabAction(); else HelpWindow.Visible = !HelpWindow.Visible;
if (UserInput.IsPressed(UserCommand.DisplayTrackMonitorWindow)) if (UserInput.IsDown(UserCommand.DisplayNextWindowTab)) TrackMonitorWindow.TabAction(); else TrackMonitorWindow.Visible = !TrackMonitorWindow.Visible;
if (UserInput.IsPressed(UserCommand.DisplayTrainDrivingWindow)) if (UserInput.IsDown(UserCommand.DisplayNextWindowTab)) TrainDrivingWindow.TabAction(); else TrainDrivingWindow.Visible = !TrainDrivingWindow.Visible;
if (UserInput.IsPressed(UserCommand.DisplayHUD)) if (UserInput.IsDown(UserCommand.DisplayNextWindowTab)) HUDWindow.TabAction(); else HUDWindow.Visible = !HUDWindow.Visible;
if (UserInput.IsPressed(UserCommand.DisplayStationLabels))
{
if (UserInput.IsDown(UserCommand.DisplayNextWindowTab)) OSDLocations.TabAction(); else OSDLocations.Visible = !OSDLocations.Visible;
if (OSDLocations.Visible)
{
switch (OSDLocations.CurrentDisplayState)
{