public FastEngine(string windowName, int width, int height, int fps) { // disabling HiDPI support var options = new ToolkitOptions { EnableHighResolution = false }; OpenTK.Toolkit.Init(options); window = new GameWindow(width, height, OpenTK.Graphics.GraphicsMode.Default, windowName); // call it AFTER GameWindow initialization to avoid problems with Windows.Forms this.Initialize(windowName, width, height, fps); // create a new texture texture = GL.GenTexture(); // use the texure (as a 2d one) GL.BindTexture(TextureTarget.Texture2D, texture); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); this.textureRect = new Rectangle(0, 0, width, height); GL.Enable(EnableCap.Texture2D); window.Resize += this.Game_Resize; window.RenderFrame += this.Game_RenderFrame; // initialize OpenAL context (No ! do it lazily) // audioContext = new AudioContext (); }
public bool NeedPresentThread => FrameFactory.getcurrentfunc == null && Xwt.Toolkit.CurrentEngine.Type != ToolkitType.Wpf;//only mac and wpf have auto present for gtk public FrameFactory(Func <IntPtr> getcurrentfunc) { try { var options = new ToolkitOptions() { EnableHighResolution = true }; options.Backend = PlatformBackend.PreferNative; this.toolkit = global::OpenTK.Toolkit.Init(options); if (getcurrentfunc != null) { FrameFactory._getcurrentfunc = getcurrentfunc; FrameFactory.getcurrentfunc = new GraphicsContext.GetCurrentContextDelegate(() => new ContextHandle(getcurrentfunc())); typeof(GraphicsContext).SetFieldValuePrivateStatic("GetCurrentContext", FrameFactory.getcurrentfunc); } } catch (Exception e) { // Log.LogException(e); throw; } }
public GL46SwapChain(SwapChainInfo swapChainInfo) { var options = new ToolkitOptions(); options.Backend = PlatformBackend.PreferNative; Toolkit.Init(options); _windowInfo = Utilities.CreateWindowsWindowInfo(swapChainInfo.WindowHandle); var graphicsContextFlags = GraphicsContextFlags.ForwardCompatible; #if DEBUG graphicsContextFlags |= GraphicsContextFlags.Debug; #endif _nativeContext = new GraphicsContext(GraphicsMode.Default, _windowInfo, null, 4, 6, graphicsContextFlags); _nativeContext.LoadAll(); TurnOnDebugging(); _nativeContext.MakeCurrent(_windowInfo); _nativeContext.SwapInterval = swapChainInfo.VSync ? 1 : 0; OpenTK.Graphics.OpenGL4.GL.Enable(EnableCap.CullFace); OpenTK.Graphics.OpenGL4.GL.CullFace(CullFaceMode.Back); OpenTK.Graphics.OpenGL4.GL.FrontFace(FrontFaceDirection.Ccw); OpenTK.Graphics.OpenGL4.GL.Enable(EnableCap.DepthTest); OpenTK.Graphics.OpenGL4.GL.DepthFunc(DepthFunction.Less); }
protected DesktopGameHost(string gameName = @"", bool bindIPCPort = false, ToolkitOptions toolkitOptions = default) : base(gameName, toolkitOptions) { //todo: yeah. Architecture.SetIncludePath(); if (bindIPCPort) { ipcProvider = new TcpIpcProvider(); IsPrimaryInstance = ipcProvider.Bind(); if (IsPrimaryInstance) { ipcProvider.MessageReceived += OnMessageReceived; ipcThread = new Thread(() => ipcProvider.StartAsync().Wait()) { Name = "IPC", IsBackground = true }; ipcThread.Start(); } } Logger.Storage = Storage.GetStorageForDirectory("logs"); }
public static void Main(string[] args) { ToolkitOptions options = new ToolkitOptions(); options.Backend = PlatformBackend.Default; Toolkit.Init(options); // need to enable depth / stencil buffers for composite path to work properly // e.g. Popup window with rounded rectangle + arrow. int aa = GetMaxAntiAliasingAvailable(2); GraphicsMode gm = new GraphicsMode(32, 16, 8, aa); Console.WriteLine("Start Demo"); using (GameWindow window = new DemoWindow(1000, 600, gm)) { try { //Screen screen = new Screen (window, Vector2.Zero, "Screen"); //Console.WriteLine ("Running Screen = " + screen.ToString ()); window.Run(30f, 0f); } catch (Exception e) { Console.WriteLine(e.Message); } } }
protected DesktopGameHost(string gameName = @"", bool bindIPCPort = false, ToolkitOptions toolkitOptions = default, bool portableInstallation = false, bool useOsuTK = false) : base(gameName, toolkitOptions) { this.bindIPCPort = bindIPCPort; IsPortableInstallation = portableInstallation; UseOsuTK = useOsuTK; }
public static void InitRenderer() { ToolkitOptions Options = new ToolkitOptions(); Options.Backend = PlatformBackend.PreferNative; Toolkit.Init(Options); }
internal LinuxGameHost(string gameName, bool bindIPC = false, ToolkitOptions toolkitOptions = default) : base(gameName, bindIPC, toolkitOptions) { Window = new LinuxGameWindow(); // required for the time being to address libbass_fx.so load failures (see https://github.com/ppy/osu/issues/2852) Library.Load("libbass.so", Library.LoadFlags.RTLD_LAZY | Library.LoadFlags.RTLD_GLOBAL); }
public OpenTKPlugins() { var options = new ToolkitOptions(); options.Backend = PlatformBackend.PreferNative; Toolkit.Init(options); _gameWindow = new GameCreatorOpenTKGameWindow(); Graphics = new OpenTKGraphicsPlugin(_gameWindow); Audio = new OpenTKAudioPlugin(); Input = new OpenTKInputPlugin(_gameWindow); Timer = new OpenTKTimerPlugin(_gameWindow); }
static void Main(string[] args) { ToolkitOptions Options = new ToolkitOptions() { Backend = PlatformBackend.PreferNative, EnableHighResolution = true }; using (Toolkit.Init(Options)) using (OpenGLExampleBaseWindow MainWindow = new OpenGLExampleBaseWindow()) { MainWindow.Run(); } }
internal WindowsGameHost(string gameName, bool bindIPC = false, ToolkitOptions toolkitOptions = default) : base(gameName, bindIPC, toolkitOptions) { // OnActivate / OnDeactivate may not fire, so the initial activity state may be unknown here. // In order to be certain we have the correct activity state we are querying the Windows API here. timePeriod = new TimePeriod(1) { Active = true }; Window = new WindowsGameWindow(); }
/// <summary> /// The entry point. /// </summary> public static void Main() { // Bind any unhandled exceptions in the main thread so that they are logged. AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; // Set correct working directory for compatibility with double-clicking Directory.SetCurrentDirectory(DirectoryHelpers.GetLocalDir()); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Environment.SetEnvironmentVariable("GSETTINGS_SCHEMA_DIR", "share\\glib-2.0\\schemas\\"); } log4net.Config.XmlConfigurator.Configure(); Log.Info("----------------"); Log.Info("Initializing Everlook..."); Log.Info("Initializing OpenTK..."); // OpenGL var toolkitOptions = new ToolkitOptions { Backend = PlatformBackend.PreferNative, EnableHighResolution = true }; using (Toolkit.Init(toolkitOptions)) { Log.Info($"OpenTK initialized using the {GetOpenTKBackend()} backend."); Log.Info("Initializing GTK..."); // Bind any unhandled exceptions in the GTK UI so that they are logged. ExceptionManager.UnhandledException += OnGLibUnhandledException; Log.Info("Registering treeview types with the native backend..."); GType nodeType = (GType)typeof(SerializedNode); GType.Register(nodeType, typeof(SerializedNode)); GType referenceType = (GType)typeof(FileReference); GType.Register(referenceType, typeof(FileReference)); // GTK IconManager.LoadEmbeddedIcons(); Application.Init(); MainWindow win = MainWindow.Create(); win.Show(); Application.Run(); } }
private static frmStudioMain InitializeMainForm() { var mainForm = new frmStudioMain(); mainForm.FormClosed += MainForm_FormClosed; MainFormManager.Start(mainForm); MainFormManager.ProcesArguments(Environment.GetCommandLineArgs()); var toolkitOptions = new ToolkitOptions(); toolkitOptions.Backend = PlatformBackend.PreferNative; Toolkit.Init(toolkitOptions); return(mainForm); }
internal MacOSGameHost(string gameName, bool bindIPC = false, ToolkitOptions toolkitOptions = default) : base(gameName, bindIPC, toolkitOptions) { Window = new MacOSGameWindow(); Window.WindowStateChanged += (sender, e) => { if (Window.WindowState != WindowState.Minimized) { OnActivated(); } else { OnDeactivated(); } }; }
internal LinuxGameHost(string gameName, bool bindIPC = false, ToolkitOptions toolkitOptions = default) : base(gameName, bindIPC, toolkitOptions) { Window = new LinuxGameWindow(); Window.WindowStateChanged += (sender, e) => { if (Window.WindowState != WindowState.Minimized) { OnActivated(); } else { OnDeactivated(); } }; // required for the time being to address libbass_fx.so load failures (see https://github.com/ppy/osu/issues/2852) Library.Load("libbass.so", Library.LoadFlags.RTLD_LAZY | Library.LoadFlags.RTLD_GLOBAL); }
public static Toolkit InitOpenTK() { // Prevent OpenTK from using SDL2 when it's available. The toolkit // tries to initialize that first, by default, not caring that it // doesn't support GLControl. Stepping through the code showed that // OpenTK.Configuration.RunningOnSdl2 was true. A simple search then // revealed the answer: https://github.com/opentk/opentk/issues/266 var options = new ToolkitOptions() { Backend = PlatformBackend.PreferNative }; // An important point is that when embedding OpenTK in a GUI toolkit // like Eto, not only must this method be called, but it must be the // very first thing done by your application. Attempting to use it // later can cause issues that are hard to trace, e.g. the program // crashing when first adding a menu with text to a MenuBar. return(Toolkit.Init(options)); }
static void Main(string[] args) { DebugSetup(); Console.WriteLine(Settings.Caption); Toolkit T = null; Renderer R = null; Indented("Renderer", () => { ToolkitOptions TO = new ToolkitOptions(); TO.Backend = PlatformBackend.PreferNative; TO.EnableHighResolution = true; T = Toolkit.Init(TO); GraphicsMode GMode = new GraphicsMode(GraphicsMode.Default.ColorFormat, 24, 8, 0, 0, 2, false); R = new Renderer(GMode, 800, 600); }); Indented("OpenGL", () => { Msg(string.Format("[{0}] Venor[{1}] GLSL[{2}] Renderer[{3}]", GL.GetString(StringName.Version), GL.GetString(StringName.Vendor), GL.GetString(StringName.ShadingLanguageVersion), GL.GetString(StringName.Renderer))); }); Indented("Extensions", () => { Msg(GL.GetString(StringName.Extensions).Split(' ')); }); Indented("Run", () => { SWatch.Start(); R.Run(); }); Indented("Disposal", () => { R.Dispose(); T.Dispose(); }); Environment.Exit(0); }
internal static void InitOpenTK() { if (openTKInitialized) { return; } openTKInitialized = true; Assembly execAssembly = Assembly.GetEntryAssembly() ?? typeof(DualityApp).Assembly; string execAssemblyDir = PathOp.GetFullPath(PathOp.GetDirectoryName(execAssembly.Location)); bool inEditor = DualityApp.ExecEnvironment == DualityApp.ExecutionEnvironment.Editor; bool isWindows = Environment.OSVersion.Platform == PlatformID.Win32NT || Environment.OSVersion.Platform == PlatformID.Win32S || Environment.OSVersion.Platform == PlatformID.Win32Windows || Environment.OSVersion.Platform == PlatformID.WinCE; bool genericFolderSDL = isWindows && !FileOp.Exists("SDL2.dll") && !FileOp.Exists(PathOp.Combine(execAssemblyDir, "SDL2.dll")); ToolkitOptions options = new ToolkitOptions { // Prefer the native backend in the editor, because it supports GLControl. SDL doesn't. // Also, never use SDL if it isn't in the local game folder, because it might be in PATH on some machines. Backend = (inEditor || genericFolderSDL) ? PlatformBackend.PreferNative : PlatformBackend.Default, // Disable High Resolution support in the editor, because it's not DPI-Aware EnableHighResolution = !inEditor }; Logs.Core.Write("Initializing OpenTK..."); Logs.Core.PushIndent(); Logs.Core.Write( "Platform Backend: {0}" + Environment.NewLine + "EnableHighResolution: {1}", options.Backend, options.EnableHighResolution); Toolkit.Init(options); Logs.Core.PopIndent(); }
private static frmStudioMain InitializeMainForm(string[] fileNames = null) { var mainForm = new frmStudioMain(); mainForm.FormClosed += MainForm_FormClosed; MainFormManager.Start(mainForm); if (fileNames != null && fileNames.Count() > 0) { MainFormManager.ProcesArguments(fileNames); } else { MainFormManager.ProcesArguments(Environment.GetCommandLineArgs()); } var toolkitOptions = new ToolkitOptions(); toolkitOptions.Backend = PlatformBackend.PreferNative; Toolkit.Init(toolkitOptions); return(mainForm); }
protected override void InitPlugin() { base.InitPlugin(); mainThread = Thread.CurrentThread; // Initialize OpenTK { bool inEditor = DualityApp.ExecEnvironment == DualityApp.ExecutionEnvironment.Editor; ToolkitOptions options = new ToolkitOptions { // Prefer the native backend in the editor, because it supports GLControl. SDL doesn't. Backend = inEditor ? PlatformBackend.PreferNative : PlatformBackend.Default, // Disable High Resolution support in the editor, because it's not DPI-Aware EnableHighResolution = !inEditor }; Toolkit.Init(options); } // Register global / non-windowbound input devices GlobalGamepadInputSource.UpdateAvailableDecives(DualityApp.Gamepads); GlobalJoystickInputSource.UpdateAvailableDecives(DualityApp.Joysticks); }
public static DesktopGameHost GetSuitableHost(string gameName, bool bindIPC = false, bool portableInstallation = false) { var toolkitOptions = new ToolkitOptions { EnableHighResolution = true, Backend = RuntimeInfo.OS == RuntimeInfo.Platform.Linux ? PlatformBackend.Default : PlatformBackend.PreferNative }; switch (RuntimeInfo.OS) { case RuntimeInfo.Platform.MacOsx: return(new MacOSGameHost(gameName, bindIPC, toolkitOptions, portableInstallation)); case RuntimeInfo.Platform.Linux: return(new LinuxGameHost(gameName, bindIPC, toolkitOptions, portableInstallation)); case RuntimeInfo.Platform.Windows: return(new WindowsGameHost(gameName, bindIPC, toolkitOptions, portableInstallation)); default: throw new InvalidOperationException($"Could not find a suitable host for the selected operating system ({Enum.GetName(typeof(RuntimeInfo.Platform), RuntimeInfo.OS)})."); } }
internal WindowsGameHost(string gameName, bool bindIPC = false, ToolkitOptions toolkitOptions = default, bool portableInstallation = false, bool useOsuTK = false) : base(gameName, bindIPC, toolkitOptions, portableInstallation, useOsuTK) { }
public void SetUp() { _options = new ToolkitOptions(); }
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); } } }
internal MacOSGameHost(string gameName, bool bindIPC = false, ToolkitOptions toolkitOptions = default, bool portableInstallation = false, bool useSdl = false) : base(gameName, bindIPC, toolkitOptions, portableInstallation, useSdl) { }
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); } } }
internal static void Main(string[] args) { CurrentlyRunOnMono = Type.GetType("Mono.Runtime") != null; CurrentHost = new Host(); // file system FileSystem = FileSystem.FromCommandLineArgs(args); FileSystem.CreateFileSystem(); Renderer = new NewRenderer(); CurrentRoute = new CurrentRoute(Renderer); Options.LoadOptions(); if (Renderer.Screen.Width == 0 || Renderer.Screen.Height == 0) { Renderer.Screen.Width = 960; Renderer.Screen.Height = 600; } 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; } } } var options = new ToolkitOptions(); options.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); currentGameWindow.Visible = true; currentGameWindow.TargetUpdateFrequency = 0; currentGameWindow.TargetRenderFrequency = 0; currentGameWindow.Title = "Object Viewer"; currentGameWindow.Run(); // quit Renderer.TextureManager.UnloadAllTextures(); }
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(); }
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(); }
static void LaunchExample(string type) { try { if (File.Exists("debug.log")) { File.Delete("debug.log"); } if (File.Exists("trace.log")) { File.Delete("trace.log"); } } catch (Exception e) { Trace.WriteLine(String.Format("Could not access debug.log", e.ToString())); } ToolkitOptions options = ToolkitOptions.Default; if (type.Contains("GLControl") || type.Contains("Form")) { // SDL does not currently support embedding in foreign windows // such as GLControl. We need to use a native OpenTK.Platform // backend in that case. This hack is specific to the example-browser // architecture - you do not need to do anything like this in your // own code (it will just work). options = new ToolkitOptions { Backend = PlatformBackend.PreferNative }; } using (TextWriterTraceListener dbg = new TextWriterTraceListener("debug.log")) using (Toolkit.Init(options)) { Trace.Listeners.Add(dbg); try { var example = Type.GetType(type); if (example != null) { example.InvokeMember("Main", BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, null, null); } } catch (Exception e) { Trace.WriteLine(String.Format("Exception occured in example {0}: {1}", type, e.ToString())); } Trace.Listeners.Remove(dbg); dbg.Flush(); dbg.Close(); } }
internal MacOSGameHost(string gameName, bool bindIPC = false, ToolkitOptions toolkitOptions = default) : base(gameName, bindIPC, toolkitOptions) { Window = new MacOSGameWindow(); }