FromCommandLineArgs() static private method

Creates the file system information from the command line arguments. If no configuration file is specified in the command line arguments, the default lookup location is used. If no configuration file is found, default values are used.
static private FromCommandLineArgs ( string args ) : FileSystem
args string The command line arguments.
return FileSystem
Beispiel #1
0
        private static void Main(string[] args)
        {
            Interface.CurrentOptions.UseSound = true;
            Interface.CurrentOptions.ObjectOptimizationBasicThreshold = 1000;
            Interface.CurrentOptions.ObjectOptimizationFullThreshold  = 250;
            // file system
            FileSystem = FileSystem.FromCommandLineArgs(args);
            FileSystem.CreateFileSystem();
            SetPackageLookupDirectories();
            //Unload
            TextureManager.UnuseAllTextures();
//			SoundManager.Deinitialize();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
Beispiel #2
0
 private static void Main(string[] args)
 {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     // --- determine the running environment ---
     CurrentlyRunningOnMono    = Type.GetType("Mono.Runtime") != null;
     CurrentlyRunningOnWindows = Environment.OSVersion.Platform == PlatformID.Win32S | Environment.OSVersion.Platform == PlatformID.Win32Windows | Environment.OSVersion.Platform == PlatformID.Win32NT;
     CurrentHost = new Host();
     try {
         FileSystem = FileSystem.FromCommandLineArgs(args);
         FileSystem.CreateFileSystem();
     } catch (Exception ex) {
         MessageBox.Show("The file system configuration could not be accessed or is invalid due to the following reason:\n\n" + ex.Message, "openBVE", MessageBoxButtons.OK, MessageBoxIcon.Hand);
         return;
     }
     // --- set up packages ---
     SetPackageLookupDirectories();
     // --- load options and controls ---
     Interface.LoadOptions();
     Interface.LoadControls(null, out Interface.CurrentControls);
     {
         string folder = Program.FileSystem.GetDataFolder("Controls");
         string file   = OpenBveApi.Path.CombineFile(folder, "Default keyboard assignment.controls");
         Interface.Control[] controls;
         Interface.LoadControls(file, out controls);
         Interface.AddControls(ref Interface.CurrentControls, controls);
     }
     // --- load language ---
     {
         string folder = Program.FileSystem.GetDataFolder("Languages");
         string file   = OpenBveApi.Path.CombineFile(folder, Interface.CurrentOptions.LanguageCode + ".cfg");
         if (!System.IO.File.Exists(file))
         {
             file = OpenBveApi.Path.CombineFile(folder, "en-US.cfg");
         }
         Interface.LoadLanguage(file);
     }
     // --- check the command-line arguments for route and train ---
     formMain.MainDialogResult result = new formMain.MainDialogResult();
     for (int i = 0; i < args.Length; i++)
     {
         if (args[i].StartsWith("/route=", StringComparison.OrdinalIgnoreCase))
         {
             result.RouteFile     = args[i].Substring(7);
             result.RouteEncoding = System.Text.Encoding.UTF8;
             for (int j = 0; j < Interface.CurrentOptions.RouteEncodings.Length; j++)
             {
                 if (string.Compare(Interface.CurrentOptions.RouteEncodings[j].Value, result.RouteFile, StringComparison.InvariantCultureIgnoreCase) == 0)
                 {
                     result.RouteEncoding = System.Text.Encoding.GetEncoding(Interface.CurrentOptions.RouteEncodings[j].Codepage);
                     break;
                 }
             }
         }
         else if (args[i].StartsWith("/train=", StringComparison.OrdinalIgnoreCase))
         {
             result.TrainFolder   = args[i].Substring(7);
             result.TrainEncoding = System.Text.Encoding.UTF8;
             for (int j = 0; j < Interface.CurrentOptions.TrainEncodings.Length; j++)
             {
                 if (string.Compare(Interface.CurrentOptions.TrainEncodings[j].Value, result.TrainFolder, StringComparison.InvariantCultureIgnoreCase) == 0)
                 {
                     result.TrainEncoding = System.Text.Encoding.GetEncoding(Interface.CurrentOptions.TrainEncodings[j].Codepage);
                     break;
                 }
             }
         }
     }
     // --- check whether route and train exist ---
     if (result.RouteFile != null)
     {
         if (!System.IO.File.Exists(result.RouteFile))
         {
             result.RouteFile = null;
         }
     }
     if (result.TrainFolder != null)
     {
         if (!System.IO.Directory.Exists(result.TrainFolder))
         {
             result.TrainFolder = null;
         }
     }
     // --- if a route was provided but no train, try to use the route default ---
     if (result.RouteFile != null & result.TrainFolder == null)
     {
         bool isRW = string.Equals(System.IO.Path.GetExtension(result.RouteFile), ".rw", StringComparison.OrdinalIgnoreCase);
         CsvRwRouteParser.ParseRoute(result.RouteFile, isRW, result.RouteEncoding, null, null, null, true);
         if (Game.TrainName != null && Game.TrainName.Length != 0)
         {
             string folder = System.IO.Path.GetDirectoryName(result.RouteFile);
             while (true)
             {
                 string trainFolder = OpenBveApi.Path.CombineDirectory(folder, "Train");
                 if (System.IO.Directory.Exists(trainFolder))
                 {
                     folder = OpenBveApi.Path.CombineDirectory(trainFolder, Game.TrainName);
                     if (System.IO.Directory.Exists(folder))
                     {
                         string file = OpenBveApi.Path.CombineFile(folder, "train.dat");
                         if (System.IO.File.Exists(file))
                         {
                             result.TrainFolder   = folder;
                             result.TrainEncoding = System.Text.Encoding.UTF8;
                             for (int j = 0; j < Interface.CurrentOptions.TrainEncodings.Length; j++)
                             {
                                 if (string.Compare(Interface.CurrentOptions.TrainEncodings[j].Value, result.TrainFolder, StringComparison.InvariantCultureIgnoreCase) == 0)
                                 {
                                     result.TrainEncoding = System.Text.Encoding.GetEncoding(Interface.CurrentOptions.TrainEncodings[j].Codepage);
                                     break;
                                 }
                             }
                         }
                     }
                     break;
                 }
                 else
                 {
                     System.IO.DirectoryInfo info = System.IO.Directory.GetParent(folder);
                     if (info != null)
                     {
                         folder = info.FullName;
                     }
                     else
                     {
                         break;
                     }
                 }
             }
         }
         Game.Reset(false);
     }
     // --- show the main menu if necessary ---
     if (result.RouteFile == null | result.TrainFolder == null)
     {
         // begin HACK //
         if (!Joysticks.Initialize())
         {
             MessageBox.Show("SDL failed to initialize the joystick subsystem.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
             return;
         }
         // end HACK //
         result = formMain.ShowMainDialog(result);
     }
     else
     {
         result.Start = true;
     }
     // --- start the actual program ---
     if (result.Start)
     {
         if (Initialize())
         {
                                 #if !DEBUG
             try {
                                         #endif
             MainLoop.StartLoopEx(result);
                                         #if !DEBUG
         }
         catch (Exception ex) {
             bool found = false;
             for (int i = 0; i < TrainManager.Trains.Length; i++)
             {
                 if (TrainManager.Trains[i] != null && TrainManager.Trains[i].Plugin != null)
                 {
                     if (TrainManager.Trains[i].Plugin.LastException != null)
                     {
                         MessageBox.Show("The train plugin " + TrainManager.Trains[i].Plugin.PluginTitle + " caused a runtime exception: " + TrainManager.Trains[i].Plugin.LastException.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                         found = true;
                         break;
                     }
                 }
             }
             if (!found)
             {
                 MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
             }
         }
                                 #endif
         }
         Deinitialize();
     }
     // --- restart the program if necessary ---
     if (RestartArguments != null)
     {
         string arguments;
         if (FileSystem.RestartArguments.Length != 0 & RestartArguments.Length != 0)
         {
             arguments = FileSystem.RestartArguments + " " + RestartArguments;
         }
         else
         {
             arguments = FileSystem.RestartArguments + RestartArguments;
         }
         try {
             System.Diagnostics.Process.Start(FileSystem.RestartProcess, arguments);
         } catch (Exception ex) {
             MessageBox.Show(ex.Message + "\n\nProcess = " + FileSystem.RestartProcess + "\nArguments = " + arguments, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
 }
Beispiel #3
0
        internal static void Main(string[] args)
        {
            CurrentlyRunOnMono = Type.GetType("Mono.Runtime") != null;
            CurrentHost        = new Host();

            // file system
            FileSystem = FileSystem.FromCommandLineArgs(args);
            FileSystem.CreateFileSystem();
            Plugins.LoadPlugins();
            // command line arguments
            SkipArgs = new bool[args.Length];
            if (args.Length != 0)
            {
                string File = System.IO.Path.Combine(Application.StartupPath, "RouteViewer.exe");
                if (System.IO.File.Exists(File))
                {
                    int Skips = 0;
                    System.Text.StringBuilder NewArgs = new System.Text.StringBuilder();
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (args[i] != null && System.IO.File.Exists(args[i]))
                        {
                            if (System.IO.Path.GetExtension(args[i]).Equals(".csv", StringComparison.OrdinalIgnoreCase))
                            {
                                string Text = System.IO.File.ReadAllText(args[i], System.Text.Encoding.UTF8);
                                if (Text.Length != -1 &&
                                    Text.IndexOf("CreateMeshBuilder", StringComparison.OrdinalIgnoreCase) == -1)
                                {
                                    if (NewArgs.Length != 0)
                                    {
                                        NewArgs.Append(" ");
                                    }

                                    NewArgs.Append("\"" + args[i] + "\"");
                                    SkipArgs[i] = true;
                                    Skips++;
                                }
                            }
                        }
                        else
                        {
                            SkipArgs[i] = true;
                            Skips++;
                        }
                    }
                    if (NewArgs.Length != 0)
                    {
                        System.Diagnostics.Process.Start(File, NewArgs.ToString());
                    }
                    if (Skips == args.Length)
                    {
                        return;
                    }
                }
            }
            Options.LoadOptions();
            Interface.CurrentOptions.ObjectOptimizationBasicThreshold = 1000;
            Interface.CurrentOptions.ObjectOptimizationFullThreshold  = 250;
            Interface.CurrentOptions.AntialiasingLevel         = 16;
            Interface.CurrentOptions.AnisotropicFilteringLevel = 16;
            // initialize camera

            currentGraphicsMode       = new GraphicsMode(new ColorFormat(8, 8, 8, 8), 24, 8, Interface.CurrentOptions.AntialiasingLevel);
            currentGameWindow         = new ObjectViewer(Renderer.ScreenWidth, Renderer.ScreenHeight, currentGraphicsMode, "Object Viewer", GameWindowFlags.Default);
            currentGameWindow.Visible = true;
            currentGameWindow.TargetUpdateFrequency = 0;
            currentGameWindow.TargetRenderFrequency = 0;
            currentGameWindow.Title = "Object Viewer";
            currentGameWindow.Run();
            // quit
            Textures.UnloadAllTextures();
        }
Beispiel #4
0
        private static void Main(string[] args)
        {
            // Add handler for UI thread exceptions
            Application.ThreadException += (CrashHandler.UIThreadException);

            // Force all WinForms errors to go through handler
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            // This handler is for catching non-UI thread exceptions
            AppDomain.CurrentDomain.UnhandledException += (CrashHandler.CurrentDomain_UnhandledException);


            //Determine the current CPU architecture-
            //ARM will generally only support OpenGL-ES
            PortableExecutableKinds peKind;

            typeof(object).Module.GetPEKind(out peKind, out CurrentCPUArchitecture);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //--- determine the running environment ---
            //I wonder if disabling this hack will stop the craashing on Linux....
            CurrentlyRunningOnMono = Type.GetType("Mono.Runtime") != null;
            //Doesn't appear to, but Mono have fixed the button appearance bug
            CurrentlyRunningOnWindows = Environment.OSVersion.Platform == PlatformID.Win32S | Environment.OSVersion.Platform == PlatformID.Win32Windows | Environment.OSVersion.Platform == PlatformID.Win32NT;
            Joysticks   = new JoystickManager();
            CurrentHost = new Host();
            try {
                FileSystem = FileSystem.FromCommandLineArgs(args);
                FileSystem.CreateFileSystem();
            } catch (Exception ex) {
                MessageBox.Show(Translations.GetInterfaceString("errors_filesystem_invalid") + Environment.NewLine + Environment.NewLine + ex.Message, Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }

            Renderer     = new NewRenderer();
            Sounds       = new Sounds();
            CurrentRoute = new CurrentRoute(Renderer);

            //Platform specific startup checks
            if (CurrentlyRunningOnMono && !CurrentlyRunningOnWindows)
            {
                // --- Check if we're running as root, and prompt not to ---
                if (getuid() == 0)
                {
                    MessageBox.Show(
                        "You are currently running as the root user." + System.Environment.NewLine +
                        "This is a bad idea, please dont!", Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }

                if (File.Exists(@"/System/Library/CoreServices/SystemVersion.plist"))
                {
                    //Mono's platform detection doesn't reliably differentiate between OS-X and Unix
                    CurrentlyRunningOnMacOS = true;
                }
            }
            else
            {
                if (!System.IO.File.Exists(System.IO.Path.Combine(Environment.SystemDirectory, "OpenAL32.dll")))
                {
                    MessageBox.Show(
                        "OpenAL was not found on your system, and will now be installed." + System.Environment.NewLine + System.Environment.NewLine +
                        "Please follow the install prompts.", Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);

                    ProcessStartInfo info = new ProcessStartInfo(Path.Combine(FileSystem.DataFolder, "Dependencies\\Win32\\oalinst.exe"));
                    info.UseShellExecute = true;
                    if (Environment.OSVersion.Version.Major >= 6)
                    {
                        info.Verb = "runas";
                    }
                    try
                    {
                        Process p = Process.Start(info);
                        if (p != null)
                        {
                            p.WaitForExit();
                        }
                        else
                        {
                            //For unknown reasons, the process failed to trigger, but did not raise an exception itself
                            //Throw one
                            throw new Win32Exception();
                        }
                    }
                    catch (Win32Exception)
                    {
                        MessageBox.Show(
                            "An error occured during OpenAL installation....", Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                }
            }


            // --- load options and controls ---
            Interface.LoadOptions();
            //Switch between SDL2 and native backends; use native backend by default
            var options = new ToolkitOptions();

            if (Interface.CurrentOptions.PreferNativeBackend)
            {
                options.Backend = PlatformBackend.PreferNative;
            }
            Toolkit.Init(options);
            // --- load language ---
            string folder = Program.FileSystem.GetDataFolder("Languages");

            Translations.LoadLanguageFiles(folder);

            folder = Program.FileSystem.GetDataFolder("Cursors");
            Cursors.LoadCursorImages(folder);

            Interface.LoadControls(null, out Interface.CurrentControls);
            folder = Program.FileSystem.GetDataFolder("Controls");
            string file = OpenBveApi.Path.CombineFile(folder, "Default keyboard assignment.controls");

            Interface.Control[] controls;
            Interface.LoadControls(file, out controls);
            Interface.AddControls(ref Interface.CurrentControls, controls);

            InputDevicePlugin.LoadPlugins(Program.FileSystem);

            // --- check the command-line arguments for route and train ---
            formMain.MainDialogResult result = new formMain.MainDialogResult();
            CommandLine.ParseArguments(args, ref result);
            // --- check whether route and train exist ---
            if (result.RouteFile != null)
            {
                if (!System.IO.File.Exists(result.RouteFile))
                {
                    result.RouteFile = null;
                }
            }
            if (result.TrainFolder != null)
            {
                if (!System.IO.Directory.Exists(result.TrainFolder))
                {
                    result.TrainFolder = null;
                }
            }
            // --- if a route was provided but no train, try to use the route default ---
            if (result.RouteFile != null & result.TrainFolder == null)
            {
                if (!Plugins.LoadPlugins())
                {
                    throw new Exception("Unable to load the required plugins- Please reinstall OpenBVE");
                }
                Game.Reset(false);
                bool loaded = false;
                for (int i = 0; i < Program.CurrentHost.Plugins.Length; i++)
                {
                    if (Program.CurrentHost.Plugins[i].Route != null && Program.CurrentHost.Plugins[i].Route.CanLoadRoute(result.RouteFile))
                    {
                        object Route = (object)Program.CurrentRoute;                         //must cast to allow us to use the ref keyword.
                        Program.CurrentHost.Plugins[i].Route.LoadRoute(result.RouteFile, result.RouteEncoding, null, null, null, true, ref Route);
                        Program.CurrentRoute = (CurrentRoute)Route;
                        Program.Renderer.Lighting.OptionAmbientColor  = CurrentRoute.Atmosphere.AmbientLightColor;
                        Program.Renderer.Lighting.OptionDiffuseColor  = CurrentRoute.Atmosphere.DiffuseLightColor;
                        Program.Renderer.Lighting.OptionLightPosition = CurrentRoute.Atmosphere.LightPosition;
                        loaded = true;
                        break;
                    }
                }
                Plugins.UnloadPlugins();
                if (!loaded)
                {
                    throw new Exception("No plugins capable of loading routefile " + result.RouteFile + " were found.");
                }
                if (!string.IsNullOrEmpty(Interface.CurrentOptions.TrainName))
                {
                    folder = System.IO.Path.GetDirectoryName(result.RouteFile);
                    while (true)
                    {
                        string trainFolder = OpenBveApi.Path.CombineDirectory(folder, "Train");
                        if (System.IO.Directory.Exists(trainFolder))
                        {
                            try
                            {
                                folder = OpenBveApi.Path.CombineDirectory(trainFolder, Interface.CurrentOptions.TrainName);
                            }
                            catch (Exception ex)
                            {
                                if (ex is ArgumentException)
                                {
                                    break;
                                }
                            }
                            if (System.IO.Directory.Exists(folder))
                            {
                                file = OpenBveApi.Path.CombineFile(folder, "train.dat");
                                if (System.IO.File.Exists(file))
                                {
                                    result.TrainFolder   = folder;
                                    result.TrainEncoding = System.Text.Encoding.UTF8;
                                    for (int j = 0; j < Interface.CurrentOptions.TrainEncodings.Length; j++)
                                    {
                                        if (string.Compare(Interface.CurrentOptions.TrainEncodings[j].Value, result.TrainFolder, StringComparison.InvariantCultureIgnoreCase) == 0)
                                        {
                                            result.TrainEncoding = System.Text.Encoding.GetEncoding(Interface.CurrentOptions.TrainEncodings[j].Codepage);
                                            break;
                                        }
                                    }
                                }
                            }
                            break;
                        }
                        if (folder == null)
                        {
                            continue;
                        }
                        System.IO.DirectoryInfo info = System.IO.Directory.GetParent(folder);
                        if (info != null)
                        {
                            folder = info.FullName;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                Game.Reset(false);
            }
            // --- show the main menu if necessary ---
            if (result.RouteFile == null | result.TrainFolder == null)
            {
                Joysticks.RefreshJoysticks();

                // end HACK //
                result = formMain.ShowMainDialog(result);
            }
            else
            {
                result.Start = true;
                //Apply translations
                Translations.SetInGameLanguage(Translations.CurrentLanguageCode);
            }
            // --- start the actual program ---
            if (result.Start)
            {
                if (Initialize())
                {
                                        #if !DEBUG
                    try {
                                                #endif
                    MainLoop.StartLoopEx(result);
                                                #if !DEBUG
                }
                catch (Exception ex) {
                    bool found = false;
                    for (int i = 0; i < TrainManager.Trains.Length; i++)
                    {
                        if (TrainManager.Trains[i] != null && TrainManager.Trains[i].Plugin != null)
                        {
                            if (TrainManager.Trains[i].Plugin.LastException != null)
                            {
                                CrashHandler.LoadingCrash(ex.Message, true);
                                MessageBox.Show("The train plugin " + TrainManager.Trains[i].Plugin.PluginTitle + " caused a runtime exception: " + TrainManager.Trains[i].Plugin.LastException.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                                found            = true;
                                RestartArguments = "";
                                break;
                            }
                        }
                    }
                    if (!found)
                    {
                        if (ex is System.DllNotFoundException)
                        {
                            Interface.AddMessage(MessageType.Critical, false, "The required system library " + ex.Message + " was not found on the system.");
                            switch (ex.Message)
                            {
                            case "libopenal.so.1":
                                MessageBox.Show("openAL was not found on this system. \n Please install libopenal1 via your distribtion's package management system.", Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                                break;

                            default:
                                MessageBox.Show("The required system library " + ex.Message + " was not found on this system.", Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                                break;
                            }
                        }
                        else
                        {
                            Interface.AddMessage(MessageType.Critical, false, "The route and train loader encountered the following critical error: " + ex.Message);
                            CrashHandler.LoadingCrash(ex + Environment.StackTrace, false);
                        }
                        RestartArguments = "";
                    }
                }
#endif
                }
                Deinitialize();
            }
            // --- restart the program if necessary ---
            if (RestartArguments != null)
            {
                string arguments;
                if (FileSystem.RestartArguments.Length != 0 & RestartArguments.Length != 0)
                {
                    arguments = FileSystem.RestartArguments + " " + RestartArguments;
                }
                else
                {
                    arguments = FileSystem.RestartArguments + RestartArguments;
                }
                try {
                    System.Diagnostics.Process.Start(System.IO.File.Exists(FileSystem.RestartProcess) ? FileSystem.RestartProcess : Application.ExecutablePath, arguments);
                } catch (Exception ex) {
                    MessageBox.Show(ex.Message + "\n\nProcess = " + FileSystem.RestartProcess + "\nArguments = " + arguments, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Beispiel #5
0
        internal static void Main(string[] args)
        {
            CurrentHost = new Host();
            // file system
            FileSystem = FileSystem.FromCommandLineArgs(args, CurrentHost);
            FileSystem.CreateFileSystem();
            Renderer     = new NewRenderer();
            CurrentRoute = new CurrentRoute(Renderer);
            Renderer.CameraTrackFollower = new TrackFollower(CurrentHost);
            Options.LoadOptions();
            if (Renderer.Screen.Width == 0 || Renderer.Screen.Height == 0)
            {
                Renderer.Screen.Width  = 960;
                Renderer.Screen.Height = 600;
            }
            Plugins.LoadPlugins();
            // command line arguments
            List <string> filesToLoad = new List <string>();

            if (args.Length != 0)
            {
                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i] != null)
                    {
                        if (System.IO.File.Exists(args[i]))
                        {
                            for (int j = 0; j < CurrentHost.Plugins.Length; j++)
                            {
                                if (CurrentHost.Plugins[j].Route != null && CurrentHost.Plugins[j].Route.CanLoadRoute(args[i]))
                                {
                                    string File = System.IO.Path.Combine(Application.StartupPath, "RouteViewer.exe");
                                    if (System.IO.File.Exists(File))
                                    {
                                        System.Diagnostics.Process.Start(File, args[i]);
                                    }
                                    continue;
                                }

                                if (CurrentHost.Plugins[j].Object != null && CurrentHost.Plugins[j].Object.CanLoadObject(args[i]))
                                {
                                    filesToLoad.Add(args[i]);
                                }
                            }
                        }
                        else if (args[i].ToLowerInvariant() == "/enablehacks")
                        {
                            //Deliberately undocumented option for debugging use
                            Interface.CurrentOptions.EnableBveTsHacks = true;
                            for (int j = 0; j < CurrentHost.Plugins.Length; j++)
                            {
                                if (CurrentHost.Plugins[j].Object != null)
                                {
                                    CompatabilityHacks enabledHacks = new CompatabilityHacks
                                    {
                                        BveTsHacks        = true,
                                        CylinderHack      = false,
                                        BlackTransparency = true
                                    };
                                    CurrentHost.Plugins[j].Object.SetCompatibilityHacks(enabledHacks);
                                }
                            }
                        }
                    }
                }

                if (filesToLoad.Count != 0)
                {
                    Files = filesToLoad.ToArray();
                }
            }

            var options = new ToolkitOptions
            {
                Backend = PlatformBackend.PreferX11
            };

            Toolkit.Init(options);
            Interface.CurrentOptions.ObjectOptimizationBasicThreshold = 1000;
            Interface.CurrentOptions.ObjectOptimizationFullThreshold  = 250;
            Interface.CurrentOptions.AntiAliasingLevel         = 16;
            Interface.CurrentOptions.AnisotropicFilteringLevel = 16;
            // initialize camera

            currentGraphicsMode = new GraphicsMode(new ColorFormat(8, 8, 8, 8), 24, 8, Interface.CurrentOptions.AntiAliasingLevel);
            currentGameWindow   = new ObjectViewer(Renderer.Screen.Width, Renderer.Screen.Height, currentGraphicsMode, "Object Viewer", GameWindowFlags.Default)
            {
                Visible = true,
                TargetUpdateFrequency = 0,
                TargetRenderFrequency = 0,
                Title = "Object Viewer"
            };
            currentGameWindow.Run();
            // quit
            Renderer.TextureManager.UnloadAllTextures();
        }
Beispiel #6
0
        internal static void Main(string[] args)
        {
            CurrentHost          = new Host();
            commandLineArguments = args;
            // platform and mono
            CurrentlyRunOnMono = Type.GetType("Mono.Runtime") != null;
            // file system
            FileSystem = FileSystem.FromCommandLineArgs(args);
            FileSystem.CreateFileSystem();
            Renderer     = new NewRenderer();
            CurrentRoute = new CurrentRoute(Renderer);
            Sounds       = new Sounds();

            // command line arguments
            SkipArgs = new bool[args.Length];
            if (args.Length != 0)
            {
                string File = System.IO.Path.Combine(Application.StartupPath, "ObjectViewer.exe");
                if (System.IO.File.Exists(File))
                {
                    int Skips = 0;
                    System.Text.StringBuilder NewArgs = new System.Text.StringBuilder();
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (args[i] != null && System.IO.File.Exists(args[i]))
                        {
                            if (System.IO.Path.GetExtension(args[i]).Equals(".csv", StringComparison.OrdinalIgnoreCase))
                            {
                                string Text = System.IO.File.ReadAllText(args[i], System.Text.Encoding.UTF8);
                                if (Text.Length == 0 || Text.IndexOf("CreateMeshBuilder", StringComparison.OrdinalIgnoreCase) >= 0)
                                {
                                    if (NewArgs.Length != 0)
                                    {
                                        NewArgs.Append(" ");
                                    }
                                    NewArgs.Append("\"" + args[i] + "\"");
                                    SkipArgs[i] = true;
                                    Skips++;
                                }
                            }
                        }
                        else
                        {
                            SkipArgs[i] = true;
                            Skips++;
                        }
                    }
                    if (NewArgs.Length != 0)
                    {
                        System.Diagnostics.Process.Start(File, NewArgs.ToString());
                    }
                    if (Skips == args.Length)
                    {
                        return;
                    }
                }
            }
            Options.LoadOptions();
            var options = new ToolkitOptions();

            Plugins.LoadPlugins();
            options.Backend = PlatformBackend.PreferX11;
            Toolkit.Init(options);
            string folder = Program.FileSystem.GetDataFolder("Languages");

            Translations.LoadLanguageFiles(folder);
            Interface.CurrentOptions.ObjectOptimizationBasicThreshold = 1000;
            Interface.CurrentOptions.ObjectOptimizationFullThreshold  = 250;
            // application
            currentGraphicsMode = new GraphicsMode(new ColorFormat(8, 8, 8, 8), 24, 8, Interface.CurrentOptions.AntiAliasingLevel);
            if (Renderer.Screen.Width == 0 || Renderer.Screen.Height == 0)
            {
                //Duff values saved, so reset to something sensible else we crash
                Renderer.Screen.Width  = 1024;
                Renderer.Screen.Height = 768;
            }
            Renderer.CameraTrackFollower            = new TrackFollower(Program.CurrentHost);
            currentGameWindow                       = new RouteViewer(Renderer.Screen.Width, Renderer.Screen.Height, currentGraphicsMode, "Route Viewer", GameWindowFlags.Default);
            currentGameWindow.Visible               = true;
            currentGameWindow.TargetUpdateFrequency = 0;
            currentGameWindow.TargetRenderFrequency = 0;
            currentGameWindow.Title                 = "Route Viewer";
            processCommandLineArgs                  = true;
            currentGameWindow.Run();
            //Unload
            Sounds.Deinitialize();
        }
Beispiel #7
0
        private static void Main(string[] args)
        {
#if !DEBUG
            // Add handler for UI thread exceptions
            Application.ThreadException += new ThreadExceptionEventHandler(CrashHandler.UIThreadException);

            // Force all WinForms errors to go through handler
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            // This handler is for catching non-UI thread exceptions
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CrashHandler.CurrentDomain_UnhandledException);
#endif

            //Determine the current CPU architecture-
            //ARM will generally only support OpenGL-ES
            PortableExecutableKinds peKind;
            typeof(object).Module.GetPEKind(out peKind, out CurrentCPUArchitecture);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //--- determine the running environment ---
            //I wonder if disabling this hack will stop the craashing on Linux....
            CurrentlyRunningOnMono = Type.GetType("Mono.Runtime") != null;
            //Doesn't appear to, but Mono have fixed the button appearance bug
            CurrentlyRunningOnWindows = Environment.OSVersion.Platform == PlatformID.Win32S | Environment.OSVersion.Platform == PlatformID.Win32Windows | Environment.OSVersion.Platform == PlatformID.Win32NT;
            Joysticks   = new JoystickManager();
            CurrentHost = new Host();
            try {
                FileSystem = FileSystem.FromCommandLineArgs(args);
                FileSystem.CreateFileSystem();
            } catch (Exception ex) {
                MessageBox.Show(Interface.GetInterfaceString("errors_filesystem_invalid") + Environment.NewLine + Environment.NewLine + ex.Message, Interface.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }

            //Platform specific startup checks
            if (CurrentlyRunningOnMono && !CurrentlyRunningOnWindows)
            {
                // --- Check if we're running as root, and prompt not to ---
                if (getuid() == 0)
                {
                    MessageBox.Show(
                        "You are currently running as the root user." + System.Environment.NewLine +
                        "This is a bad idea, please dont!", Interface.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
            }
            else
            {
                if (!System.IO.File.Exists(System.IO.Path.Combine(Environment.SystemDirectory, "OpenAL32.dll")))
                {
                    MessageBox.Show(
                        "OpenAL was not found on your system, and will now be installed." + System.Environment.NewLine + System.Environment.NewLine +
                        "Please follow the install prompts.", Interface.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);

                    ProcessStartInfo info = new ProcessStartInfo(System.IO.Path.Combine(FileSystem.DataFolder, "Dependencies\\Win32\\oalinst.exe"));
                    info.UseShellExecute = true;
                    if (Environment.OSVersion.Version.Major >= 6)
                    {
                        info.Verb = "runas";
                    }
                    try
                    {
                        System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
                        p.WaitForExit();
                    }
                    catch (Win32Exception)
                    {
                        MessageBox.Show(
                            "An error occured during OpenAL installation....", Interface.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                }
            }


            // --- load options and controls ---
            Interface.LoadOptions();
            //Switch between SDL2 and native backends; use native backend by default
            var options = new ToolkitOptions();
            if (Interface.CurrentOptions.PreferNativeBackend)
            {
                options.Backend = PlatformBackend.PreferNative;
            }
            Toolkit.Init(options);
            // --- load language ---
            {
                string folder = Program.FileSystem.GetDataFolder("Languages");
                try
                {
                    string[] LanguageFiles = Directory.GetFiles(folder, "*.cfg");
                    foreach (var File in LanguageFiles)
                    {
                        Interface.AddLanguage(File);
                    }
                }
                catch
                {
                    MessageBox.Show(@"An error occured whilst attempting to load the default language files.");
                    //Environment.Exit(0);
                }
            }
            Interface.LoadControls(null, out Interface.CurrentControls);
            {
                string folder = Program.FileSystem.GetDataFolder("Controls");
                string file   = OpenBveApi.Path.CombineFile(folder, "Default keyboard assignment.controls");
                Interface.Control[] controls;
                Interface.LoadControls(file, out controls);
                Interface.AddControls(ref Interface.CurrentControls, controls);
            }

            // --- check the command-line arguments for route and train ---
            formMain.MainDialogResult result = new formMain.MainDialogResult();
            CommandLine.ParseArguments(args, ref result);
            // --- check whether route and train exist ---
            if (result.RouteFile != null)
            {
                if (!System.IO.File.Exists(result.RouteFile))
                {
                    result.RouteFile = null;
                }
            }
            if (result.TrainFolder != null)
            {
                if (!System.IO.Directory.Exists(result.TrainFolder))
                {
                    result.TrainFolder = null;
                }
            }
            // --- if a route was provided but no train, try to use the route default ---
            if (result.RouteFile != null & result.TrainFolder == null)
            {
                bool isRW = string.Equals(System.IO.Path.GetExtension(result.RouteFile), ".rw", StringComparison.OrdinalIgnoreCase);
                CsvRwRouteParser.ParseRoute(result.RouteFile, isRW, result.RouteEncoding, null, null, null, true);
                if (!string.IsNullOrEmpty(Game.TrainName))
                {
                    string folder = System.IO.Path.GetDirectoryName(result.RouteFile);
                    while (true)
                    {
                        string trainFolder = OpenBveApi.Path.CombineDirectory(folder, "Train");
                        if (System.IO.Directory.Exists(trainFolder))
                        {
                            folder = OpenBveApi.Path.CombineDirectory(trainFolder, Game.TrainName);
                            if (System.IO.Directory.Exists(folder))
                            {
                                string file = OpenBveApi.Path.CombineFile(folder, "train.dat");
                                if (System.IO.File.Exists(file))
                                {
                                    result.TrainFolder   = folder;
                                    result.TrainEncoding = System.Text.Encoding.UTF8;
                                    for (int j = 0; j < Interface.CurrentOptions.TrainEncodings.Length; j++)
                                    {
                                        if (string.Compare(Interface.CurrentOptions.TrainEncodings[j].Value, result.TrainFolder, StringComparison.InvariantCultureIgnoreCase) == 0)
                                        {
                                            result.TrainEncoding = System.Text.Encoding.GetEncoding(Interface.CurrentOptions.TrainEncodings[j].Codepage);
                                            break;
                                        }
                                    }
                                }
                            }
                            break;
                        }
                        if (folder == null)
                        {
                            continue;
                        }
                        System.IO.DirectoryInfo info = System.IO.Directory.GetParent(folder);
                        if (info != null)
                        {
                            folder = info.FullName;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                Game.Reset(false);
            }
            // --- show the main menu if necessary ---
            if (result.RouteFile == null | result.TrainFolder == null)
            {
                Joysticks.RefreshJoysticks();

                // end HACK //
                result = formMain.ShowMainDialog(result);
            }
            else
            {
                result.Start = true;
                //Apply translations
                Interface.SetInGameLanguage(Interface.CurrentLanguageCode);
            }
            // --- start the actual program ---
            if (result.Start)
            {
                if (Initialize())
                {
                                        #if !DEBUG
                    try {
                                                #endif
                    MainLoop.StartLoopEx(result);
                                                #if !DEBUG
                }
                catch (Exception ex) {
                    bool found = false;
                    //Thread.Sleep(20);
                    for (int i = 0; i < TrainManager.Trains.Length; i++)
                    {
                        if (TrainManager.Trains[i] != null && TrainManager.Trains[i].Plugin != null)
                        {
                            if (TrainManager.Trains[i].Plugin.LastException != null)
                            {
                                CrashHandler.LoadingCrash(ex.Message, true);
                                MessageBox.Show("The train plugin " + TrainManager.Trains[i].Plugin.PluginTitle + " caused a runtime exception: " + TrainManager.Trains[i].Plugin.LastException.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                                found            = true;
                                RestartArguments = "";
                                break;
                            }
                        }
                    }
                    if (!found)
                    {
                        MessageBox.Show("The route and train loader encountered the following critical error: " + Environment.NewLine + ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        CrashHandler.LoadingCrash(ex.ToString(), false);
                        RestartArguments = "";
                    }
                }
#endif
                }
                Deinitialize();
            }
            // --- restart the program if necessary ---
            if (RestartArguments != null)
            {
                string arguments;
                if (FileSystem.RestartArguments.Length != 0 & RestartArguments.Length != 0)
                {
                    arguments = FileSystem.RestartArguments + " " + RestartArguments;
                }
                else
                {
                    arguments = FileSystem.RestartArguments + RestartArguments;
                }
                try {
                    System.Diagnostics.Process.Start(System.IO.File.Exists(FileSystem.RestartProcess) ? FileSystem.RestartProcess : Application.ExecutablePath, arguments);
                } catch (Exception ex) {
                    MessageBox.Show(ex.Message + "\n\nProcess = " + FileSystem.RestartProcess + "\nArguments = " + arguments, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Beispiel #8
0
        internal static void Main(string[] args)
        {
            Interface.CurrentOptions.UseSound = true;
            Interface.CurrentOptions.ObjectOptimizationBasicThreshold = 1000;
            Interface.CurrentOptions.ObjectOptimizationFullThreshold  = 250;
            // platform and mono
            int p = (int)Environment.OSVersion.Platform;

            if (p == 4 | p == 128)
            {
                // general Unix
                CurrentPlatform = Platform.Linux;
            }
            else if (p == 6)
            {
                // Mac
                CurrentPlatform = Platform.Mac;
            }
            else
            {
                // non-Unix
                CurrentPlatform = Platform.Windows;
            }
            CurrentlyRunOnMono = Type.GetType("Mono.Runtime") != null;
            // file system
            FileSystem = FileSystem.FromCommandLineArgs(args);
            FileSystem.CreateFileSystem();
            SetPackageLookupDirectories();
            // command line arguments
            bool[] SkipArgs = new bool[args.Length];
            if (args.Length != 0)
            {
                string File = System.IO.Path.Combine(Application.StartupPath, "ObjectViewer.exe");
                if (System.IO.File.Exists(File))
                {
                    int Skips = 0;
                    System.Text.StringBuilder NewArgs = new System.Text.StringBuilder();
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (System.IO.File.Exists(args[i]))
                        {
                            if (System.IO.Path.GetExtension(args[i]).Equals(".csv", StringComparison.OrdinalIgnoreCase))
                            {
                                string Text = System.IO.File.ReadAllText(args[i], System.Text.Encoding.UTF8);
                                if (Text.Length == 0 || Text.IndexOf("CreateMeshBuilder", StringComparison.OrdinalIgnoreCase) >= 0)
                                {
                                    if (NewArgs.Length != 0)
                                    {
                                        NewArgs.Append(" ");
                                    }
                                    NewArgs.Append("\"" + args[i] + "\"");
                                    SkipArgs[i] = true;
                                    Skips++;
                                }
                            }
                        }
                        else
                        {
                            SkipArgs[i] = true;
                            Skips++;
                        }
                    }
                    if (NewArgs.Length != 0)
                    {
                        System.Diagnostics.Process.Start(File, NewArgs.ToString());
                    }
                    if (Skips == args.Length)
                    {
                        return;
                    }
                }
            }
            // application
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO) != 0)
            {
                MessageBox.Show("SDL failed to initialize the video subsystem.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }
            // initialize sdl window
            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_DOUBLEBUFFER, 1);
            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_DEPTH_SIZE, 16);
            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_RED_SIZE, 8);
            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_GREEN_SIZE, 8);
            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_BLUE_SIZE, 8);
            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_ALPHA_SIZE, 8);
            SDL.SDL_ShowCursor(1);

            // initialize camera
            ResetCamera();
            World.BackgroundImageDistance = 600.0;
            World.ForwardViewingDistance  = 600.0;
            World.BackwardViewingDistance = 0.0;
            World.ExtraViewingDistance    = 50.0;
            // create window
            Renderer.ScreenWidth  = 960;
            Renderer.ScreenHeight = 600;
            //int Bits = 32;
            //IntPtr video = Sdl.SDL_SetVideoMode(Renderer.ScreenWidth, Renderer.ScreenHeight, Bits, Sdl.SDL_OPENGL | Sdl.SDL_DOUBLEBUF);
            Window = SDL.SDL_CreateWindow(Application.ProductName,
                                          SDL.SDL_WINDOWPOS_UNDEFINED, SDL.SDL_WINDOWPOS_UNDEFINED,
                                          Renderer.ScreenWidth, Renderer.ScreenHeight,
                                          SDL.SDL_WindowFlags.SDL_WINDOW_OPENGL | SDL.SDL_WindowFlags.SDL_WINDOW_RESIZABLE);
            if (Window == IntPtr.Zero)
            {
                MessageBox.Show("SDL failed to create the window.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }
            // icon
            string iconFile = OpenBveApi.Path.CombineFile(Program.FileSystem.GetDataFolder(), "icon.png");

            if (System.IO.File.Exists(iconFile))
            {
                iconBmp  = new Bitmap(iconFile);                // load file
                iconData = iconBmp.LockBits(new Rectangle(0, 0, iconBmp.Width, iconBmp.Height),
                                            System.Drawing.Imaging.ImageLockMode.ReadOnly,
                                            System.Drawing.Imaging.PixelFormat.Format32bppArgb);            // lock data
                iconSurface = SDL.SDL_CreateRGBSurfaceFrom(iconData.Scan0, iconBmp.Width, iconBmp.Height, 32, iconData.Stride,
                                                           0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); // upload to sdl
                SDL.SDL_SetWindowIcon(Window, iconSurface);                                                 // use icon
            }
            GLContext = SDL.SDL_GL_CreateContext(Window);
            tkContext = new GraphicsContext(new ContextHandle(GLContext),
                                            SDL.SDL_GL_GetProcAddress,
                                            SDLGetCurrentContext);
            // anisotropic filtering
            string[] extensions = GL.GetString(StringName.Extensions).Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            Interface.CurrentOptions.AnisotropicFilteringMaximum = 0;
            for (int i = 0; i < extensions.Length; i++)
            {
                if (extensions[i] == "GL_EXT_texture_filter_anisotropic")
                {
                    float n;
                    GL.GetFloat((GetPName)ExtTextureFilterAnisotropic.MaxTextureMaxAnisotropyExt, out n);
                    Interface.CurrentOptions.AnisotropicFilteringMaximum = (int)Math.Round((double)n);
                    break;
                }
            }
            if (Interface.CurrentOptions.AnisotropicFilteringMaximum <= 0)
            {
                Interface.CurrentOptions.AnisotropicFilteringMaximum = 0;
                Interface.CurrentOptions.AnisotropicFilteringLevel   = 0;
                Interface.CurrentOptions.Interpolation = TextureManager.InterpolationMode.AnisotropicFiltering;
            }
            else
            {
                Interface.CurrentOptions.AnisotropicFilteringLevel = Interface.CurrentOptions.AnisotropicFilteringMaximum;
                Interface.CurrentOptions.Interpolation             = TextureManager.InterpolationMode.TrilinearMipmapped;
            }
            Interface.CurrentOptions.TransparencyMode = Renderer.TransparencyMode.Sharp;
            // module initialization
            Renderer.Initialize();
            Renderer.InitializeLighting();
            SoundManager.Initialize();
            GL.ClearColor(0.75f, 0.75f, 0.75f, 1.0f);
            SwapBuffers();
            Fonts.Initialize();
            UpdateViewport();
            // loop
            bool processCommandLineArgs = true;

            timer = new System.Diagnostics.Stopwatch();
            timer.Start();
            while (!Quit)
            {
                ProcessEvents();
                int    a           = (int)timer.ElapsedMilliseconds;
                double TimeElapsed = 0.001 * (double)(a - LastTicks);
                if (CpuReducedMode)
                {
                    System.Threading.Thread.Sleep(250);
                }
                else
                {
                    System.Threading.Thread.Sleep(1);
                    if (ReducedModeEnteringTime == 0)
                    {
                        ReducedModeEnteringTime = a + 2500;
                    }
                    if (World.CameraAlignmentDirection.Position.X != 0.0 | World.CameraAlignmentDirection.Position.Y != 0.0 | World.CameraAlignmentDirection.Position.Z != 0.0 | World.CameraAlignmentDirection.Pitch != 0.0 | World.CameraAlignmentDirection.Yaw != 0.0 | World.CameraAlignmentDirection.Roll != 0.0 | World.CameraAlignmentDirection.TrackPosition != 0.0 | World.CameraAlignmentDirection.Zoom != 0.0)
                    {
                        ReducedModeEnteringTime = a + 2500;
                    }
                    else if (a > ReducedModeEnteringTime & CpuAutomaticMode)
                    {
                        ReducedModeEnteringTime = 0;
                        CpuReducedMode          = true;
                    }
                }
                DateTime d = DateTime.Now;
                Game.SecondsSinceMidnight = (double)(3600 * d.Hour + 60 * d.Minute + d.Second) + 0.001 * (double)d.Millisecond;
                ObjectManager.UpdateAnimatedWorldObjects(TimeElapsed, false);
                World.UpdateAbsoluteCamera(TimeElapsed);
                ObjectManager.UpdateVisibility(World.CameraTrackFollower.TrackPosition + World.CameraCurrentAlignment.Position.Z);
                TextureManager.Update(TimeElapsed);
                SoundManager.Update(TimeElapsed);
                Renderer.RenderScene(TimeElapsed);
                SwapBuffers();
                LastTicks = a;
                // command line arguments
                if (processCommandLineArgs)
                {
                    processCommandLineArgs = false;
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (!SkipArgs[i] && System.IO.File.Exists(args[i]))
                        {
                            CurrentlyLoading = true;
                            Renderer.RenderScene(0.0);
                            SwapBuffers();
                            CurrentRoute = args[i];
                            LoadRoute();
                            CurrentlyLoading = false;
                            UpdateCaption();
                            break;
                        }
                    }
                }
            }
            // quit
            TextureManager.UnuseAllTextures();
            SoundManager.Deinitialize();
            if (iconSurface != IntPtr.Zero)
            {
                SDL.SDL_FreeSurface(iconSurface);                 // free surface
            }
            if (iconBmp != null && iconData != null)
            {
                iconBmp.UnlockBits(iconData);                 // free pixels
                iconBmp.Dispose();
            }
            SDL.SDL_GL_DeleteContext(GLContext);
            SDL.SDL_DestroyWindow(Window);
            SDL.SDL_Quit();
        }
        private static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            // platform and mono
            int p = (int)Environment.OSVersion.Platform;

            if (p == 4 | p == 128)
            {
                // general Unix
                CurrentPlatform = Platform.Linux;
            }
            else if (p == 6)
            {
                // Mac
                CurrentPlatform = Platform.Mac;
            }
            else
            {
                // non-Unix
                CurrentPlatform = Platform.Windows;
            }
            CurrentlyRunOnMono = Type.GetType("Mono.Runtime") != null;
            // file system
            try
            {
                FileSystem = FileSystem.FromCommandLineArgs(args);
            }
            catch (Exception ex)
            {
                MessageBox.Show("The file system configuration could not be accessed or is invalid due to the following reason:\n\n" + ex.Message, "openBVE", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }
            FileSystem.CreateFileSystem();
            // start
#if DEBUG
            Start(args);
#else
            try
            {
                Start(args);
            }
            catch (Exception ex)
            {
                bool shown = false;
                for (int i = 0; i < TrainManager.Trains.Length; i++)
                {
                    if (TrainManager.Trains[i] != null && TrainManager.Trains[i].Plugin != null)
                    {
                        if (TrainManager.Trains[i].Plugin.LastException != null)
                        {
                            string text = GetExceptionText(TrainManager.Trains[i].Plugin.LastException, 5);
                            MessageBox.Show("The train plugin " + TrainManager.Trains[i].Plugin.PluginTitle + " caused the following exception:\n\n" + text, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            shown = false;
                        }
                    }
                }
                if (!shown)
                {
                    string text = GetExceptionText(ex, 5);
                    MessageBox.Show(text, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
#endif
            // deinitialize
            if (SdlWindowCreated & Interface.CurrentOptions.FullscreenMode)
            {
                Sdl.SDL_SetVideoMode(Interface.CurrentOptions.WindowWidth, Interface.CurrentOptions.WindowHeight, 32, Sdl.SDL_OPENGL | Sdl.SDL_DOUBLEBUF);
            }
            Renderer.Deinitialize();
            TextureManager.UnuseAllTextures();
            Asynchronous.Deinitialize();
            for (int i = 0; i < TrainManager.Trains.Length; i++)
            {
                if (TrainManager.Trains[i] != null && TrainManager.Trains[i].Plugin != null)
                {
                    PluginManager.UnloadPlugin(TrainManager.Trains[i]);
                }
            }
            SoundManager.Deinitialize();
            // close sdl
            for (int i = 0; i < Interface.CurrentJoysticks.Length; i++)
            {
                Sdl.SDL_JoystickClose(Interface.CurrentJoysticks[i].SdlHandle);
                Interface.CurrentJoysticks[i].SdlHandle = IntPtr.Zero;
            }
            Sdl.SDL_Quit();
            // restart
            if (RestartProcessArguments != null)
            {
                string arguments;
                if (FileSystem.RestartArguments.Length != 0 & RestartProcessArguments.Length != 0)
                {
                    arguments = FileSystem.RestartArguments + " " + RestartProcessArguments;
                }
                else
                {
                    arguments = FileSystem.RestartArguments + RestartProcessArguments;
                }
                try
                {
                    System.Diagnostics.Process.Start(FileSystem.RestartProcess, arguments);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + "\n\nProcess = " + FileSystem.RestartProcess + "\nArguments = " + arguments, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Beispiel #10
0
        internal static void Main(string[] args)
        {
            CurrentHost = new Host();

            commandLineArguments = args;
            Options.LoadOptions();
            Interface.CurrentOptions.UseSound = true;
            Interface.CurrentOptions.ObjectOptimizationBasicThreshold = 1000;
            Interface.CurrentOptions.ObjectOptimizationFullThreshold  = 250;
            // platform and mono
            int p = (int)Environment.OSVersion.Platform;

            if (p == 4 | p == 128)
            {
                // general Unix
                CurrentPlatform = Platform.Linux;
            }
            else if (p == 6)
            {
                // Mac
                CurrentPlatform = Platform.Mac;
            }
            else
            {
                // non-Unix
                CurrentPlatform = Platform.Windows;
            }
            CurrentlyRunOnMono = Type.GetType("Mono.Runtime") != null;
            // file system
            FileSystem = FileSystem.FromCommandLineArgs(args);
            FileSystem.CreateFileSystem();
            Plugins.LoadPlugins();
            // command line arguments
            SkipArgs = new bool[args.Length];
            if (args.Length != 0)
            {
                string File = System.IO.Path.Combine(Application.StartupPath, "ObjectViewer.exe");
                if (System.IO.File.Exists(File))
                {
                    int Skips = 0;
                    System.Text.StringBuilder NewArgs = new System.Text.StringBuilder();
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (args[i] != null && System.IO.File.Exists(args[i]))
                        {
                            if (System.IO.Path.GetExtension(args[i]).Equals(".csv", StringComparison.OrdinalIgnoreCase))
                            {
                                string Text = System.IO.File.ReadAllText(args[i], System.Text.Encoding.UTF8);
                                if (Text.Length == 0 || Text.IndexOf("CreateMeshBuilder", StringComparison.OrdinalIgnoreCase) >= 0)
                                {
                                    if (NewArgs.Length != 0)
                                    {
                                        NewArgs.Append(" ");
                                    }
                                    NewArgs.Append("\"" + args[i] + "\"");
                                    SkipArgs[i] = true;
                                    Skips++;
                                }
                            }
                        }
                        else
                        {
                            SkipArgs[i] = true;
                            Skips++;
                        }
                    }
                    if (NewArgs.Length != 0)
                    {
                        System.Diagnostics.Process.Start(File, NewArgs.ToString());
                    }
                    if (Skips == args.Length)
                    {
                        return;
                    }
                }
            }
            // application

            currentGraphicsMode       = new GraphicsMode(new ColorFormat(8, 8, 8, 8), 24, 8, Interface.CurrentOptions.AntialiasingLevel);
            currentGameWindow         = new RouteViewer(Renderer.ScreenWidth, Renderer.ScreenHeight, currentGraphicsMode, "Route Viewer", GameWindowFlags.Default);
            currentGameWindow.Visible = true;
            currentGameWindow.TargetUpdateFrequency = 0;
            currentGameWindow.TargetRenderFrequency = 0;
            currentGameWindow.Title = "Route Viewer";
            processCommandLineArgs  = true;
            currentGameWindow.Run();
            //Unload
            TextureManager.UnuseAllTextures();
            Sounds.Deinitialize();
        }
Beispiel #11
0
        internal static void Main(string[] args)
        {
            CurrentHost = new Host();
            // file system
            FileSystem = FileSystem.FromCommandLineArgs(args, CurrentHost);
            FileSystem.CreateFileSystem();
            Renderer     = new NewRenderer();
            CurrentRoute = new CurrentRoute(Renderer);
            Sounds       = new Sounds();

            Options.LoadOptions();
            Plugins.LoadPlugins();
            // command line arguments
            StringBuilder objectsToLoad = new StringBuilder();

            if (args.Length != 0)
            {
                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i] != null)
                    {
                        if (System.IO.File.Exists(args[i]))
                        {
                            for (int j = 0; j < CurrentHost.Plugins.Length; j++)
                            {
                                if (CurrentHost.Plugins[j].Object != null && CurrentHost.Plugins[j].Object.CanLoadObject(args[i]))
                                {
                                    objectsToLoad.Append(args[i] + " ");
                                    continue;
                                }

                                if (CurrentHost.Plugins[j].Route != null && CurrentHost.Plugins[j].Route.CanLoadRoute(args[i]))
                                {
                                    if (string.IsNullOrEmpty(CurrentRouteFile))
                                    {
                                        CurrentRouteFile       = args[i];
                                        processCommandLineArgs = true;
                                    }
                                }
                            }
                        }
                        else if (args[i].ToLowerInvariant() == "/enablehacks")
                        {
                            //Deliberately undocumented option for debugging use
                            Interface.CurrentOptions.EnableBveTsHacks = true;
                            for (int j = 0; j < CurrentHost.Plugins.Length; j++)
                            {
                                if (CurrentHost.Plugins[j].Object != null)
                                {
                                    CompatabilityHacks enabledHacks = new CompatabilityHacks
                                    {
                                        BveTsHacks        = true,
                                        CylinderHack      = false,
                                        BlackTransparency = true
                                    };
                                    CurrentHost.Plugins[j].Object.SetCompatibilityHacks(enabledHacks);
                                }
                            }
                        }
                    }
                }
            }

            if (objectsToLoad.Length != 0)
            {
                string File = System.IO.Path.Combine(Application.StartupPath, "ObjectViewer.exe");
                if (System.IO.File.Exists(File))
                {
                    System.Diagnostics.Process.Start(File, objectsToLoad.ToString());
                    if (string.IsNullOrEmpty(CurrentRouteFile))
                    {
                        //We only supplied objects, so launch Object Viewer instead
                        Environment.Exit(0);
                    }
                }
            }

            var options = new ToolkitOptions();

            Plugins.LoadPlugins();
            options.Backend = PlatformBackend.PreferX11;
            Toolkit.Init(options);
            string folder = Program.FileSystem.GetDataFolder("Languages");

            Translations.LoadLanguageFiles(folder);
            Interface.CurrentOptions.ObjectOptimizationBasicThreshold = 1000;
            Interface.CurrentOptions.ObjectOptimizationFullThreshold  = 250;
            // application
            currentGraphicsMode = new GraphicsMode(new ColorFormat(8, 8, 8, 8), 24, 8, Interface.CurrentOptions.AntiAliasingLevel);
            if (Renderer.Screen.Width == 0 || Renderer.Screen.Height == 0)
            {
                //Duff values saved, so reset to something sensible else we crash
                Renderer.Screen.Width  = 1024;
                Renderer.Screen.Height = 768;
            }
            Renderer.CameraTrackFollower            = new TrackFollower(Program.CurrentHost);
            currentGameWindow                       = new RouteViewer(Renderer.Screen.Width, Renderer.Screen.Height, currentGraphicsMode, "Route Viewer", GameWindowFlags.Default);
            currentGameWindow.Visible               = true;
            currentGameWindow.TargetUpdateFrequency = 0;
            currentGameWindow.TargetRenderFrequency = 0;
            currentGameWindow.Title                 = "Route Viewer";
            processCommandLineArgs                  = true;
            currentGameWindow.Run();
            //Unload
            Sounds.Deinitialize();
        }
Beispiel #12
0
        internal static void Main(string[] args)
        {
            // platform and mono
            int p = (int)Environment.OSVersion.Platform;

            if (p == 4 | p == 128)
            {
                // general Unix
                CurrentPlatform = Platform.Linux;
            }
            else if (p == 6)
            {
                // Mac
                CurrentPlatform = Platform.Mac;
            }
            else
            {
                // non-Unix
                CurrentPlatform = Platform.Windows;
            }
            CurrentlyRunOnMono = Type.GetType("Mono.Runtime") != null;
            // file system
            FileSystem = FileSystem.FromCommandLineArgs(args);
            FileSystem.CreateFileSystem();
            SetPackageLookupDirectories();
            // command line arguments
            bool[] SkipArgs = new bool[args.Length];
            if (args.Length != 0)
            {
                string File = System.IO.Path.Combine(Application.StartupPath, "RouteViewer.exe");
                if (System.IO.File.Exists(File))
                {
                    int Skips = 0;
                    System.Text.StringBuilder NewArgs = new System.Text.StringBuilder();
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (System.IO.File.Exists(args[i]))
                        {
                            if (System.IO.Path.GetExtension(args[i]).Equals(".csv", StringComparison.OrdinalIgnoreCase))
                            {
                                string Text = System.IO.File.ReadAllText(args[i], System.Text.Encoding.UTF8);
                                if (Text.Length != -1 && Text.IndexOf("CreateMeshBuilder", StringComparison.OrdinalIgnoreCase) == -1)
                                {
                                    if (NewArgs.Length != 0)
                                    {
                                        NewArgs.Append(" ");
                                    }
                                    NewArgs.Append("\"" + args[i] + "\"");
                                    SkipArgs[i] = true;
                                    Skips++;
                                }
                            }
                        }
                        else
                        {
                            SkipArgs[i] = true;
                            Skips++;
                        }
                    }
                    if (NewArgs.Length != 0)
                    {
                        System.Diagnostics.Process.Start(File, NewArgs.ToString());
                    }
                    if (Skips == args.Length)
                    {
                        return;
                    }
                }
            }
            // application
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO) != 0)
            {
                MessageBox.Show("SDL failed to initialize the video subsystem.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }
            Interface.CurrentOptions.ObjectOptimizationBasicThreshold = 1000;
            Interface.CurrentOptions.ObjectOptimizationFullThreshold  = 250;
            // initialize sdl window
            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_DOUBLEBUFFER, 1);
            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_DEPTH_SIZE, 16);
            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_RED_SIZE, 8);
            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_GREEN_SIZE, 8);
            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_BLUE_SIZE, 8);
            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_ALPHA_SIZE, 8);
            SDL.SDL_ShowCursor(1);
            // initialize camera
            ResetCamera();
            // create window
            Renderer.ScreenWidth  = 960;
            Renderer.ScreenHeight = 600;
            // int Bits = 32;
            //Sdl.SDL_SetVideoMode(Renderer.ScreenWidth, Renderer.ScreenHeight, Bits, Sdl.SDL_OPENGL | Sdl.SDL_DOUBLEBUF);
            SDLWindow = SDL.SDL_CreateWindow(Application.ProductName,
                                             SDL.SDL_WINDOWPOS_UNDEFINED, SDL.SDL_WINDOWPOS_UNDEFINED,
                                             Renderer.ScreenWidth, Renderer.ScreenHeight,
                                             SDL.SDL_WindowFlags.SDL_WINDOW_OPENGL | SDL.SDL_WindowFlags.SDL_WINDOW_RESIZABLE);
            if (SDLWindow != IntPtr.Zero)
            {
                // create window
                string File = OpenBveApi.Path.CombineFile(Program.FileSystem.GetDataFolder(), "icon.png");
                if (System.IO.File.Exists(File))
                {
                    // set up icon
                    iconBmp  = new Bitmap(File);                    // load file
                    iconData = iconBmp.LockBits(new Rectangle(0, 0, iconBmp.Width, iconBmp.Height),
                                                System.Drawing.Imaging.ImageLockMode.ReadOnly,
                                                System.Drawing.Imaging.PixelFormat.Format32bppArgb);            // lock data
                    iconSurface = SDL.SDL_CreateRGBSurfaceFrom(iconData.Scan0, iconBmp.Width, iconBmp.Height, 32, iconData.Stride,
                                                               0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); // upload to sdl
                    SDL.SDL_SetWindowIcon(SDLWindow, iconSurface);                                              // use icon
                    // free is on the end of the program

                    /*
                     * IntPtr bitmap = SDL.SDL_LoadBMP(File);
                     * if (bitmap != IntPtr.Zero) {
                     *      SDL.SDL_Surface Surface = (SDL.SDL_Surface)System.Runtime.InteropServices.Marshal.PtrToStructure(bitmap, typeof(SDL.SDL_Surface));
                     *      uint ColorKey = SDL.SDL_MapRGB(Surface.format, 0, 0, 255);
                     *      SDL.SDL_SetColorKey(bitmap, 1, ColorKey);
                     *      SDL.SDL_SetWindowIcon(SDLWindow,bitmap);
                     * }
                     */
                }
                GLContext = SDL.SDL_GL_CreateContext(SDLWindow);
                tkContext = new GraphicsContext(new ContextHandle(GLContext),
                                                SDL.SDL_GL_GetProcAddress,
                                                () => new ContextHandle(SDL.SDL_GL_GetCurrentContext()));
                // anisotropic filtering
                string[] extensions = GL.GetString(StringName.Extensions).Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                Interface.CurrentOptions.AnisotropicFilteringMaximum = 0;
                for (int i = 0; i < extensions.Length; i++)
                {
                    if (extensions[i] == "GL_EXT_texture_filter_anisotropic")
                    {
                        float n;
                        GL.GetFloat((GetPName)ExtTextureFilterAnisotropic.MaxTextureMaxAnisotropyExt, out n);
                        Interface.CurrentOptions.AnisotropicFilteringMaximum = (int)Math.Round((double)n);
                        break;
                    }
                }
                if (Interface.CurrentOptions.AnisotropicFilteringMaximum <= 0)
                {
                    Interface.CurrentOptions.AnisotropicFilteringMaximum = 0;
                    Interface.CurrentOptions.AnisotropicFilteringLevel   = 0;
                    Interface.CurrentOptions.Interpolation = TextureManager.InterpolationMode.AnisotropicFiltering;
                }
                else
                {
                    Interface.CurrentOptions.AnisotropicFilteringLevel = Interface.CurrentOptions.AnisotropicFilteringMaximum;
                    Interface.CurrentOptions.Interpolation             = TextureManager.InterpolationMode.TrilinearMipmapped;
                }
                // module initialization
                Renderer.Initialize();
                Renderer.InitializeLighting();
                SDL.SDL_GL_SwapWindow(SDLWindow);
                Fonts.Initialize();
                UpdateViewport();
                // command line arguments
                for (int i = 0; i < args.Length; i++)
                {
                    if (!SkipArgs[i] && System.IO.File.Exists(args[i]))
                    {
                        try {
                            ObjectManager.UnifiedObject o = ObjectManager.LoadObject(args[i], System.Text.Encoding.UTF8, ObjectManager.ObjectLoadMode.Normal, false, false, false);
                            ObjectManager.CreateObject(o, new World.Vector3D(0.0, 0.0, 0.0), new World.Transformation(0.0, 0.0, 0.0), new World.Transformation(0.0, 0.0, 0.0), true, 0.0, 0.0, 25.0, 0.0);
                        } catch (Exception ex) {
                            Interface.AddMessage(Interface.MessageType.Critical, false, "Unhandled error (" + ex.Message + ") encountered while processing the file " + args[i] + ".");
                        }
                        Array.Resize <string>(ref Files, Files.Length + 1);
                        Files[Files.Length - 1] = args[i];
                    }
                }
                ObjectManager.InitializeVisibility();
                ObjectManager.FinishCreatingObjects();
                ObjectManager.UpdateVisibility(0.0, true);
                ObjectManager.UpdateAnimatedWorldObjects(0.01, true);
                UpdateCaption();
                Stopwatch timer = new Stopwatch();
                timer.Start();
                LastTicks = timer.ElapsedMilliseconds;
                // loop
                while (!Quit)
                {
                    long   ticks       = timer.ElapsedMilliseconds;
                    double timeElapsed = 0.001 * (double)(ticks - LastTicks);
                    if (timeElapsed < 0.0001)
                    {
                        timeElapsed = 0.0001;
                    }
                    LastTicks = ticks;
                    DateTime time = DateTime.Now;
                    Game.SecondsSinceMidnight = (double)(3600 * time.Hour + 60 * time.Minute + time.Second) + 0.001 * (double)time.Millisecond;
                    ObjectManager.UpdateAnimatedWorldObjects(timeElapsed, false);
                    ProcessEvents();
                    if (ReducedMode)
                    {
                        System.Threading.Thread.Sleep(125);
                    }
                    else
                    {
                        System.Threading.Thread.Sleep(1);
                    }
                    bool updatelight = false;
                    bool keep        = false;
                    // rotate x
                    if (RotateX == 0)
                    {
                        double d = (1.0 + Math.Abs(RotateXSpeed)) * timeElapsed;
                        if (RotateXSpeed >= -d & RotateXSpeed <= d)
                        {
                            RotateXSpeed = 0.0;
                        }
                        else
                        {
                            RotateXSpeed -= (double)Math.Sign(RotateXSpeed) * d;
                        }
                    }
                    else
                    {
                        double d = (1.0 + 1.0 - 1.0 / (1.0 + RotateXSpeed * RotateXSpeed)) * timeElapsed;
                        double m = 1.0;
                        RotateXSpeed += (double)RotateX * d;
                        if (RotateXSpeed < -m)
                        {
                            RotateXSpeed = -m;
                        }
                        else if (RotateXSpeed > m)
                        {
                            RotateXSpeed = m;
                        }
                    }
                    if (RotateXSpeed != 0.0)
                    {
                        double cosa = Math.Cos(RotateXSpeed * timeElapsed);
                        double sina = Math.Sin(RotateXSpeed * timeElapsed);
                        World.Rotate(ref World.AbsoluteCameraDirection.X, ref World.AbsoluteCameraDirection.Y, ref World.AbsoluteCameraDirection.Z, 0.0, 1.0, 0.0, cosa, sina);
                        World.Rotate(ref World.AbsoluteCameraUp.X, ref World.AbsoluteCameraUp.Y, ref World.AbsoluteCameraUp.Z, 0.0, 1.0, 0.0, cosa, sina);
                        World.Rotate(ref World.AbsoluteCameraSide.X, ref World.AbsoluteCameraSide.Y, ref World.AbsoluteCameraSide.Z, 0.0, 1.0, 0.0, cosa, sina);
                        keep = true;
                    }
                    // rotate y
                    if (RotateY == 0)
                    {
                        double d = (1.0 + Math.Abs(RotateYSpeed)) * timeElapsed;
                        if (RotateYSpeed >= -d & RotateYSpeed <= d)
                        {
                            RotateYSpeed = 0.0;
                        }
                        else
                        {
                            RotateYSpeed -= (double)Math.Sign(RotateYSpeed) * d;
                        }
                    }
                    else
                    {
                        double d = (1.0 + 1.0 - 1.0 / (1.0 + RotateYSpeed * RotateYSpeed)) * timeElapsed;
                        double m = 1.0;
                        RotateYSpeed += (double)RotateY * d;
                        if (RotateYSpeed < -m)
                        {
                            RotateYSpeed = -m;
                        }
                        else if (RotateYSpeed > m)
                        {
                            RotateYSpeed = m;
                        }
                    }
                    if (RotateYSpeed != 0.0)
                    {
                        double cosa = Math.Cos(RotateYSpeed * timeElapsed);
                        double sina = Math.Sin(RotateYSpeed * timeElapsed);
                        World.Rotate(ref World.AbsoluteCameraDirection.X, ref World.AbsoluteCameraDirection.Y, ref World.AbsoluteCameraDirection.Z, World.AbsoluteCameraSide.X, World.AbsoluteCameraSide.Y, World.AbsoluteCameraSide.Z, cosa, sina);
                        World.Rotate(ref World.AbsoluteCameraUp.X, ref World.AbsoluteCameraUp.Y, ref World.AbsoluteCameraUp.Z, World.AbsoluteCameraSide.X, World.AbsoluteCameraSide.Y, World.AbsoluteCameraSide.Z, cosa, sina);
                        keep = true;
                    }
                    // move x
                    if (MoveX == 0)
                    {
                        double d = (2.5 + Math.Abs(MoveXSpeed)) * timeElapsed;
                        if (MoveXSpeed >= -d & MoveXSpeed <= d)
                        {
                            MoveXSpeed = 0.0;
                        }
                        else
                        {
                            MoveXSpeed -= (double)Math.Sign(MoveXSpeed) * d;
                        }
                    }
                    else
                    {
                        double d = (5.0 + 10.0 - 10.0 / (1.0 + MoveXSpeed * MoveXSpeed)) * timeElapsed;
                        double m = 25.0;
                        MoveXSpeed += (double)MoveX * d;
                        if (MoveXSpeed < -m)
                        {
                            MoveXSpeed = -m;
                        }
                        else if (MoveXSpeed > m)
                        {
                            MoveXSpeed = m;
                        }
                    }
                    if (MoveXSpeed != 0.0)
                    {
                        World.AbsoluteCameraPosition.X += MoveXSpeed * timeElapsed * World.AbsoluteCameraSide.X;
                        World.AbsoluteCameraPosition.Y += MoveXSpeed * timeElapsed * World.AbsoluteCameraSide.Y;
                        World.AbsoluteCameraPosition.Z += MoveXSpeed * timeElapsed * World.AbsoluteCameraSide.Z;
                        keep = true;
                    }
                    // move y
                    if (MoveY == 0)
                    {
                        double d = (2.5 + Math.Abs(MoveYSpeed)) * timeElapsed;
                        if (MoveYSpeed >= -d & MoveYSpeed <= d)
                        {
                            MoveYSpeed = 0.0;
                        }
                        else
                        {
                            MoveYSpeed -= (double)Math.Sign(MoveYSpeed) * d;
                        }
                    }
                    else
                    {
                        double d = (5.0 + 10.0 - 10.0 / (1.0 + MoveYSpeed * MoveYSpeed)) * timeElapsed;
                        double m = 25.0;
                        MoveYSpeed += (double)MoveY * d;
                        if (MoveYSpeed < -m)
                        {
                            MoveYSpeed = -m;
                        }
                        else if (MoveYSpeed > m)
                        {
                            MoveYSpeed = m;
                        }
                    }
                    if (MoveYSpeed != 0.0)
                    {
                        World.AbsoluteCameraPosition.X += MoveYSpeed * timeElapsed * World.AbsoluteCameraUp.X;
                        World.AbsoluteCameraPosition.Y += MoveYSpeed * timeElapsed * World.AbsoluteCameraUp.Y;
                        World.AbsoluteCameraPosition.Z += MoveYSpeed * timeElapsed * World.AbsoluteCameraUp.Z;
                        keep = true;
                    }
                    // move z
                    if (MoveZ == 0)
                    {
                        double d = (2.5 + Math.Abs(MoveZSpeed)) * timeElapsed;
                        if (MoveZSpeed >= -d & MoveZSpeed <= d)
                        {
                            MoveZSpeed = 0.0;
                        }
                        else
                        {
                            MoveZSpeed -= (double)Math.Sign(MoveZSpeed) * d;
                        }
                    }
                    else
                    {
                        double d = (5.0 + 10.0 - 10.0 / (1.0 + MoveZSpeed * MoveZSpeed)) * timeElapsed;
                        double m = 25.0;
                        MoveZSpeed += (double)MoveZ * d;
                        if (MoveZSpeed < -m)
                        {
                            MoveZSpeed = -m;
                        }
                        else if (MoveZSpeed > m)
                        {
                            MoveZSpeed = m;
                        }
                    }
                    if (MoveZSpeed != 0.0)
                    {
                        World.AbsoluteCameraPosition.X += MoveZSpeed * timeElapsed * World.AbsoluteCameraDirection.X;
                        World.AbsoluteCameraPosition.Y += MoveZSpeed * timeElapsed * World.AbsoluteCameraDirection.Y;
                        World.AbsoluteCameraPosition.Z += MoveZSpeed * timeElapsed * World.AbsoluteCameraDirection.Z;
                        keep = true;
                    }
                    // lighting
                    if (LightingRelative == -1)
                    {
                        LightingRelative = (double)LightingTarget;
                        updatelight      = true;
                    }
                    if (LightingTarget == 0)
                    {
                        if (LightingRelative != 0.0)
                        {
                            LightingRelative -= 0.5 * timeElapsed;
                            if (LightingRelative < 0.0)
                            {
                                LightingRelative = 0.0;
                            }
                            updatelight = true;
                            keep        = true;
                        }
                    }
                    else
                    {
                        if (LightingRelative != 1.0)
                        {
                            LightingRelative += 0.5 * timeElapsed;
                            if (LightingRelative > 1.0)
                            {
                                LightingRelative = 1.0;
                            }
                            updatelight = true;
                            keep        = true;
                        }
                    }
                    // continue
                    if (ReducedMode)
                    {
                        ReducedModeEnteringTime = (int)(ticks + 3000);
                    }
                    else
                    {
                        if (keep)
                        {
                            ReducedModeEnteringTime = (int)(ticks + 3000);
                        }
                        else if (ticks > ReducedModeEnteringTime)
                        {
                            ReducedMode = true;
                            World.AbsoluteCameraSide.Y = 0.0;
                            World.Normalize(ref World.AbsoluteCameraSide.X, ref World.AbsoluteCameraSide.Y, ref World.AbsoluteCameraSide.Z);
                            World.Normalize(ref World.AbsoluteCameraDirection.X, ref World.AbsoluteCameraDirection.Y, ref World.AbsoluteCameraDirection.Z);
                            World.AbsoluteCameraUp = World.Cross(World.AbsoluteCameraDirection, World.AbsoluteCameraSide);
                        }
                    }
                    if (updatelight)
                    {
                        Renderer.OptionAmbientColor.R = (byte)Math.Round(32.0 + 128.0 * LightingRelative * (2.0 - LightingRelative));
                        Renderer.OptionAmbientColor.G = (byte)Math.Round(32.0 + 128.0 * 0.5 * (LightingRelative + LightingRelative * (2.0 - LightingRelative)));
                        Renderer.OptionAmbientColor.B = (byte)Math.Round(32.0 + 128.0 * LightingRelative);
                        Renderer.OptionDiffuseColor.R = (byte)Math.Round(32.0 + 128.0 * LightingRelative);
                        Renderer.OptionDiffuseColor.G = (byte)Math.Round(32.0 + 128.0 * LightingRelative);
                        Renderer.OptionDiffuseColor.B = (byte)Math.Round(32.0 + 128.0 * Math.Sqrt(LightingRelative));
                        Renderer.InitializeLighting();
                    }
                    Renderer.RenderScene();
                    SDL.SDL_GL_SwapWindow(SDLWindow);
                }
                // quit
                TextureManager.UnuseAllTextures();
                if (iconSurface != IntPtr.Zero)
                {
                    SDL.SDL_FreeSurface(iconSurface);                     // free surface
                }
                if (iconBmp != null && iconData != null)
                {
                    iconBmp.UnlockBits(iconData);                     // free pixels
                    iconBmp.Dispose();
                }
                SDL.SDL_GL_DeleteContext(GLContext);
                SDL.SDL_DestroyWindow(SDLWindow);
                SDL.SDL_Quit();
            }
            else
            {
                MessageBox.Show("SDL failed to create the window.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }
Beispiel #13
0
        private static void Main(string[] args)
        {
            // --- load options and controls ---
            try
            {
                FileSystem = FileSystem.FromCommandLineArgs(args, CurrentHost);
                FileSystem.CreateFileSystem();
                Interface.LoadOptions();
            }
            catch
            {
                // ignored
            }
            //Switch between SDL2 and native backends; use native backend by default
            var options = new ToolkitOptions();

            if (Interface.CurrentOptions.PreferNativeBackend)
            {
                options.Backend = PlatformBackend.PreferNative;
            }
            Toolkit.Init(options);

            // Add handler for UI thread exceptions
            Application.ThreadException += (CrashHandler.UIThreadException);

            // Force all WinForms errors to go through handler
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            // This handler is for catching non-UI thread exceptions
            AppDomain.CurrentDomain.UnhandledException += (CrashHandler.CurrentDomain_UnhandledException);


            //Determine the current CPU architecture-
            //ARM will generally only support OpenGL-ES
            PortableExecutableKinds peKind;

            typeof(object).Module.GetPEKind(out peKind, out CurrentCPUArchitecture);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            CurrentHost = new Host();
            if (IntPtr.Size == 4)
            {
                Joysticks = new JoystickManager32();
            }
            else
            {
                Joysticks = new JoystickManager64();
            }
            try {
                FileSystem = FileSystem.FromCommandLineArgs(args, CurrentHost);
                FileSystem.CreateFileSystem();
            } catch (Exception ex) {
                MessageBox.Show(Translations.GetInterfaceString("errors_filesystem_invalid") + Environment.NewLine + Environment.NewLine + ex.Message, Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }

            Renderer     = new NewRenderer(CurrentHost, Interface.CurrentOptions, FileSystem);
            Sounds       = new Sounds();
            CurrentRoute = new CurrentRoute(CurrentHost, Renderer);

            //Platform specific startup checks
            // --- Check if we're running as root, and prompt not to ---
            if (CurrentHost.Platform == HostPlatform.GNULinux && (getuid() == 0 || geteuid() == 0))
            {
                MessageBox.Show(
                    "You are currently running as the root user, or via the sudo command." + System.Environment.NewLine +
                    "This is a bad idea, please dont!", Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }



            TrainManager = new TrainManager(CurrentHost, Renderer, Interface.CurrentOptions, FileSystem);

            // --- load language ---
            string folder = Program.FileSystem.GetDataFolder("Languages");

            Translations.LoadLanguageFiles(folder);

            folder = Program.FileSystem.GetDataFolder("Cursors");
            Cursors.LoadCursorImages(folder);

            Interface.LoadControls(null, out Interface.CurrentControls);
            folder = Program.FileSystem.GetDataFolder("Controls");
            string file = OpenBveApi.Path.CombineFile(folder, "Default keyboard assignment.controls");

            Control[] controls;
            Interface.LoadControls(file, out controls);
            Interface.AddControls(ref Interface.CurrentControls, controls);

            InputDevicePlugin.LoadPlugins(Program.FileSystem);

            // --- check the command-line arguments for route and train ---
            formMain.MainDialogResult result = new formMain.MainDialogResult();
            CommandLine.ParseArguments(args, ref result);
            // --- check whether route and train exist ---
            if (result.RouteFile != null)
            {
                if (!System.IO.File.Exists(result.RouteFile))
                {
                    result.RouteFile = null;
                }
            }
            if (result.TrainFolder != null)
            {
                if (!System.IO.Directory.Exists(result.TrainFolder))
                {
                    result.TrainFolder = null;
                }
            }
            // --- if a route was provided but no train, try to use the route default ---
            if (result.RouteFile != null & result.TrainFolder == null)
            {
                string error;
                if (!CurrentHost.LoadPlugins(FileSystem, Interface.CurrentOptions, out error, TrainManager, Renderer))
                {
                    MessageBox.Show(error, @"OpenBVE", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    throw new Exception("Unable to load the required plugins- Please reinstall OpenBVE");
                }
                Game.Reset(false);
                bool loaded = false;
                for (int i = 0; i < Program.CurrentHost.Plugins.Length; i++)
                {
                    if (Program.CurrentHost.Plugins[i].Route != null && Program.CurrentHost.Plugins[i].Route.CanLoadRoute(result.RouteFile))
                    {
                        object Route = (object)Program.CurrentRoute;                         //must cast to allow us to use the ref keyword.
                        Program.CurrentHost.Plugins[i].Route.LoadRoute(result.RouteFile, result.RouteEncoding, null, null, null, true, ref Route);
                        Program.CurrentRoute = (CurrentRoute)Route;
                        Program.Renderer.Lighting.OptionAmbientColor  = CurrentRoute.Atmosphere.AmbientLightColor;
                        Program.Renderer.Lighting.OptionDiffuseColor  = CurrentRoute.Atmosphere.DiffuseLightColor;
                        Program.Renderer.Lighting.OptionLightPosition = CurrentRoute.Atmosphere.LightPosition;
                        loaded = true;
                        break;
                    }
                }

                if (!CurrentHost.UnloadPlugins(out error))
                {
                    MessageBox.Show(error, @"OpenBVE", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                if (!loaded)
                {
                    throw new Exception("No plugins capable of loading routefile " + result.RouteFile + " were found.");
                }
                if (!string.IsNullOrEmpty(Interface.CurrentOptions.TrainName))
                {
                    folder = System.IO.Path.GetDirectoryName(result.RouteFile);
                    while (true)
                    {
                        string trainFolder = OpenBveApi.Path.CombineDirectory(folder, "Train");
                        if (System.IO.Directory.Exists(trainFolder))
                        {
                            try
                            {
                                folder = OpenBveApi.Path.CombineDirectory(trainFolder, Interface.CurrentOptions.TrainName);
                            }
                            catch (Exception ex)
                            {
                                if (ex is ArgumentException)
                                {
                                    break;
                                }
                            }
                            if (System.IO.Directory.Exists(folder))
                            {
                                file = OpenBveApi.Path.CombineFile(folder, "train.dat");
                                if (System.IO.File.Exists(file))
                                {
                                    result.TrainFolder   = folder;
                                    result.TrainEncoding = System.Text.Encoding.UTF8;
                                    for (int j = 0; j < Interface.CurrentOptions.TrainEncodings.Length; j++)
                                    {
                                        if (string.Compare(Interface.CurrentOptions.TrainEncodings[j].Value, result.TrainFolder, StringComparison.InvariantCultureIgnoreCase) == 0)
                                        {
                                            result.TrainEncoding = System.Text.Encoding.GetEncoding(Interface.CurrentOptions.TrainEncodings[j].Codepage);
                                            break;
                                        }
                                    }
                                }
                            }
                            break;
                        }
                        if (folder == null)
                        {
                            continue;
                        }
                        System.IO.DirectoryInfo info = System.IO.Directory.GetParent(folder);
                        if (info != null)
                        {
                            folder = info.FullName;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                Game.Reset(false);
            }

            // --- show the main menu if necessary ---
            if (result.RouteFile == null | result.TrainFolder == null)
            {
                Joysticks.RefreshJoysticks();

                if (CurrentHost.Platform == HostPlatform.AppleOSX && IntPtr.Size != 4)
                {
                    //WinForms are not supported on 64-bit Apple, so show the experimental GL menu
                    result.ExperimentalGLMenu = true;
                }
                else
                {
                    if (!result.ExperimentalGLMenu)
                    {
                        result = formMain.ShowMainDialog(result);
                    }
                }
            }
            else
            {
                result.Start = true;
                //Apply translations
                Translations.SetInGameLanguage(Translations.CurrentLanguageCode);
            }

            if (result.ExperimentalGLMenu)
            {
                result.Start       = true;
                result.RouteFile   = null;
                result.TrainFolder = null;
            }

            // --- start the actual program ---
            if (result.Start)
            {
                if (Initialize())
                {
                                        #if !DEBUG
                    try {
                                                #endif
                    MainLoop.StartLoopEx(result);
                                                #if !DEBUG
                }
                catch (Exception ex) {
                    bool found = false;
                    for (int i = 0; i < TrainManager.Trains.Length; i++)
                    {
                        if (TrainManager.Trains[i] != null && TrainManager.Trains[i].Plugin != null)
                        {
                            if (TrainManager.Trains[i].Plugin.LastException != null)
                            {
                                CrashHandler.LoadingCrash(ex.Message, true);
                                MessageBox.Show("The train plugin " + TrainManager.Trains[i].Plugin.PluginTitle + " caused a runtime exception: " + TrainManager.Trains[i].Plugin.LastException.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                                found            = true;
                                RestartArguments = "";
                                break;
                            }
                        }
                    }
                    if (!found)
                    {
                        if (ex is System.DllNotFoundException)
                        {
                            Interface.AddMessage(MessageType.Critical, false, "The required system library " + ex.Message + " was not found on the system.");
                            switch (ex.Message)
                            {
                            case "libopenal.so.1":
                                MessageBox.Show("openAL was not found on this system. \n Please install libopenal1 via your distribtion's package management system.", Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                                break;

                            default:
                                MessageBox.Show("The required system library " + ex.Message + " was not found on this system.", Translations.GetInterfaceString("program_title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
                                break;
                            }
                        }
                        else
                        {
                            Interface.AddMessage(MessageType.Critical, false, "The route and train loader encountered the following critical error: " + ex.Message);
                            CrashHandler.LoadingCrash(ex + Environment.StackTrace, false);
                        }
                        RestartArguments = "";
                    }
                }
#endif
                }
                Deinitialize();
            }
            // --- restart the program if necessary ---
            if (RestartArguments != null)
            {
                string arguments;
                if (FileSystem.RestartArguments.Length != 0 & RestartArguments.Length != 0)
                {
                    arguments = FileSystem.RestartArguments + " " + RestartArguments;
                }
                else
                {
                    arguments = FileSystem.RestartArguments + RestartArguments;
                }
                try {
                    System.Diagnostics.Process.Start(System.IO.File.Exists(FileSystem.RestartProcess) ? FileSystem.RestartProcess : Application.ExecutablePath, arguments);
                } catch (Exception ex) {
                    MessageBox.Show(ex.Message + "\n\nProcess = " + FileSystem.RestartProcess + "\nArguments = " + arguments, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Beispiel #14
0
        internal static void Main(string[] args)
        {
            Interface.CurrentOptions.UseSound = true;
            Interface.CurrentOptions.ObjectOptimizationBasicThreshold = 1000;
            Interface.CurrentOptions.ObjectOptimizationFullThreshold  = 250;
            // platform and mono
            int p = (int)Environment.OSVersion.Platform;

            if (p == 4 | p == 128)
            {
                /// general Unix
                CurrentPlatform = Platform.Linux;
            }
            else if (p == 6)
            {
                /// Mac
                CurrentPlatform = Platform.Mac;
            }
            else
            {
                /// non-Unix
                CurrentPlatform = Platform.Windows;
            }
            CurrentlyRunOnMono = Type.GetType("Mono.Runtime") != null;
            // file system
            FileSystem = FileSystem.FromCommandLineArgs(args);
            FileSystem.CreateFileSystem();
            SetPackageLookupDirectories();
            // command line arguments
            bool[] SkipArgs = new bool[args.Length];
            if (args.Length != 0)
            {
                string File = System.IO.Path.Combine(Application.StartupPath, "ObjectViewer.exe");
                if (System.IO.File.Exists(File))
                {
                    int Skips = 0;
                    System.Text.StringBuilder NewArgs = new System.Text.StringBuilder();
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (System.IO.File.Exists(args[i]))
                        {
                            if (System.IO.Path.GetExtension(args[i]).Equals(".csv", StringComparison.OrdinalIgnoreCase))
                            {
                                string Text = System.IO.File.ReadAllText(args[i], System.Text.Encoding.UTF8);
                                if (Text.Length == 0 || Text.IndexOf("CreateMeshBuilder", StringComparison.OrdinalIgnoreCase) >= 0)
                                {
                                    if (NewArgs.Length != 0)
                                    {
                                        NewArgs.Append(" ");
                                    }
                                    NewArgs.Append("\"" + args[i] + "\"");
                                    SkipArgs[i] = true;
                                    Skips++;
                                }
                            }
                        }
                        else
                        {
                            SkipArgs[i] = true;
                            Skips++;
                        }
                    }
                    if (NewArgs.Length != 0)
                    {
                        System.Diagnostics.Process.Start(File, NewArgs.ToString());
                    }
                    if (Skips == args.Length)
                    {
                        return;
                    }
                }
            }
            // application
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            if (Sdl.SDL_Init(Sdl.SDL_INIT_VIDEO) != 0)
            {
                MessageBox.Show("SDL failed to initialize the video subsystem.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }
            // initialize sdl window
            Sdl.SDL_GL_SetAttribute(Sdl.SDL_GL_DOUBLEBUFFER, 1);
            Sdl.SDL_GL_SetAttribute(Sdl.SDL_GL_DEPTH_SIZE, 16);
            Sdl.SDL_GL_SetAttribute(Sdl.SDL_GL_RED_SIZE, 8);
            Sdl.SDL_GL_SetAttribute(Sdl.SDL_GL_GREEN_SIZE, 8);
            Sdl.SDL_GL_SetAttribute(Sdl.SDL_GL_BLUE_SIZE, 8);
            Sdl.SDL_GL_SetAttribute(Sdl.SDL_GL_ALPHA_SIZE, 8);
            Sdl.SDL_ShowCursor(Sdl.SDL_ENABLE);
            // icon
            if (Program.CurrentPlatform == Platform.Windows)
            {
                string File = OpenBveApi.Path.CombineFile(Program.FileSystem.GetDataFolder(), "icon.bmp");
                if (System.IO.File.Exists(File))
                {
                    IntPtr Bitmap = Sdl.SDL_LoadBMP(File);
                    if (Bitmap != null)
                    {
                        Sdl.SDL_Surface Surface  = (Sdl.SDL_Surface)System.Runtime.InteropServices.Marshal.PtrToStructure(Bitmap, typeof(Sdl.SDL_Surface));
                        int             ColorKey = Sdl.SDL_MapRGB(Surface.format, 0, 0, 255);
                        Sdl.SDL_SetColorKey(Bitmap, Sdl.SDL_SRCCOLORKEY, ColorKey);
                        Sdl.SDL_WM_SetIcon(Bitmap, null);
                    }
                }
            }
            // initialize camera
            ResetCamera();
            World.BackgroundImageDistance = 600.0;
            World.ForwardViewingDistance  = 600.0;
            World.BackwardViewingDistance = 0.0;
            World.ExtraViewingDistance    = 50.0;
            // create window
            Renderer.ScreenWidth  = 960;
            Renderer.ScreenHeight = 600;
            int    Bits  = 32;
            IntPtr video = Sdl.SDL_SetVideoMode(Renderer.ScreenWidth, Renderer.ScreenHeight, Bits, Sdl.SDL_OPENGL | Sdl.SDL_DOUBLEBUF);

            if (video != IntPtr.Zero)
            {
                // create window
                Sdl.SDL_WM_SetCaption(Application.ProductName, null);
                // anisotropic filtering
                string[] Extensions = Gl.glGetString(Gl.GL_EXTENSIONS).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                Interface.CurrentOptions.AnisotropicFilteringMaximum = 0;
                for (int i = 0; i < Extensions.Length; i++)
                {
                    if (string.Compare(Extensions[i], "GL_EXT_texture_filter_anisotropic", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        float n; Gl.glGetFloatv(Gl.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, out n);
                        Interface.CurrentOptions.AnisotropicFilteringMaximum = (int)Math.Round((double)n);
                        break;
                    }
                }
                if (Interface.CurrentOptions.AnisotropicFilteringMaximum <= 0)
                {
                    Interface.CurrentOptions.AnisotropicFilteringMaximum = 0;
                    Interface.CurrentOptions.AnisotropicFilteringLevel   = 0;
                    Interface.CurrentOptions.Interpolation = TextureManager.InterpolationMode.AnisotropicFiltering;
                }
                else
                {
                    Interface.CurrentOptions.AnisotropicFilteringLevel = Interface.CurrentOptions.AnisotropicFilteringMaximum;
                    Interface.CurrentOptions.Interpolation             = TextureManager.InterpolationMode.TrilinearMipmapped;
                }
                Interface.CurrentOptions.TransparencyMode = Renderer.TransparencyMode.Sharp;
                // module initialization
                Renderer.Initialize();
                Renderer.InitializeLighting();
                SoundManager.Initialize();
                Gl.glClearColor(0.75f, 0.75f, 0.75f, 1.0f);
                Sdl.SDL_GL_SwapBuffers();
                Fonts.Initialize();
                UpdateViewport();
                // loop
                bool processCommandLineArgs = true;
                while (!Quit)
                {
                    ProcessEvents();
                    int    a           = Sdl.SDL_GetTicks();
                    double TimeElapsed = 0.001 * (double)(a - LastTicks);
                    if (CpuReducedMode)
                    {
                        System.Threading.Thread.Sleep(250);
                    }
                    else
                    {
                        System.Threading.Thread.Sleep(1);
                        if (ReducedModeEnteringTime == 0)
                        {
                            ReducedModeEnteringTime = a + 2500;
                        }
                        if (World.CameraAlignmentDirection.Position.X != 0.0 | World.CameraAlignmentDirection.Position.Y != 0.0 | World.CameraAlignmentDirection.Position.Z != 0.0 | World.CameraAlignmentDirection.Pitch != 0.0 | World.CameraAlignmentDirection.Yaw != 0.0 | World.CameraAlignmentDirection.Roll != 0.0 | World.CameraAlignmentDirection.TrackPosition != 0.0 | World.CameraAlignmentDirection.Zoom != 0.0)
                        {
                            ReducedModeEnteringTime = a + 2500;
                        }
                        else if (a > ReducedModeEnteringTime & CpuAutomaticMode)
                        {
                            ReducedModeEnteringTime = 0;
                            CpuReducedMode          = true;
                        }
                    }
                    DateTime d = DateTime.Now;
                    Game.SecondsSinceMidnight = (double)(3600 * d.Hour + 60 * d.Minute + d.Second) + 0.001 * (double)d.Millisecond;
                    ObjectManager.UpdateAnimatedWorldObjects(TimeElapsed, false);
                    World.UpdateAbsoluteCamera(TimeElapsed);
                    ObjectManager.UpdateVisibility(World.CameraTrackFollower.TrackPosition + World.CameraCurrentAlignment.Position.Z);
                    TextureManager.Update(TimeElapsed);
                    SoundManager.Update(TimeElapsed);
                    Renderer.RenderScene(TimeElapsed);
                    Sdl.SDL_GL_SwapBuffers();
                    LastTicks = a;
                    // command line arguments
                    if (processCommandLineArgs)
                    {
                        processCommandLineArgs = false;
                        for (int i = 0; i < args.Length; i++)
                        {
                            if (!SkipArgs[i] && System.IO.File.Exists(args[i]))
                            {
                                CurrentlyLoading = true;
                                Renderer.RenderScene(0.0);
                                Sdl.SDL_GL_SwapBuffers();
                                CurrentRoute = args[i];
                                LoadRoute();
                                CurrentlyLoading = false;
                                UpdateCaption();
                                break;
                            }
                        }
                    }
                }
                // quit
                TextureManager.UnuseAllTextures();
                SoundManager.Deinitialize();
                Sdl.SDL_Quit();
            }
            else
            {
                MessageBox.Show("SDL failed to create the window.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }