forked from stride3d/stride
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
452 lines (409 loc) · 19 KB
/
Copy pathProgram.cs
File metadata and controls
452 lines (409 loc) · 19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using Stride.Assets;
using Stride.Assets.Presentation;
using Stride.Core.Assets;
using Stride.Core.Assets.Editor;
using Stride.Core.Assets.Editor.Components.TemplateDescriptions.ViewModels;
using Stride.Core.Assets.Editor.Components.TemplateDescriptions.Views;
using Stride.Core.Assets.Editor.Services;
using Stride.Core.Assets.Editor.Settings;
using Stride.Core.Assets.Editor.ViewModel;
using Stride.Core.Diagnostics;
using Stride.Core.Extensions;
using Stride.Core.IO;
using Stride.Core.MostRecentlyUsedFiles;
using Stride.Core.Presentation.Interop;
using Stride.Core.Presentation.Services;
using Stride.Core.Presentation.View;
using Stride.Core.Presentation.ViewModels;
using Stride.Core.Presentation.Windows;
using Stride.Core.Translation;
using Stride.Core.Translation.Providers;
using Stride.Editor.Build;
using Stride.Editor.Preview;
using Stride.GameStudio.Helpers;
using Stride.GameStudio.Plugin;
using Stride.GameStudio.Services;
using Stride.GameStudio.View;
using Stride.GameStudio.ViewModels;
using Stride.Graphics;
using EditorSettings = Stride.Core.Assets.Editor.Settings.EditorSettings;
using MessageBox = System.Windows.MessageBox;
using MessageBoxButton = System.Windows.MessageBoxButton;
using MessageBoxImage = System.Windows.MessageBoxImage;
using MessageBoxResult = System.Windows.MessageBoxResult;
namespace Stride.GameStudio;
public static class Program
{
private static App app;
private static IntPtr windowHandle;
private static bool terminating;
private static Dispatcher mainDispatcher;
private static RenderDocManager renderDocManager;
private static readonly ConcurrentQueue<string> LogRingbuffer = new();
private static bool enableThumbnailServices = true;
private static bool resetGraphicsApiPreference;
// Startup checkpoints; shared file with the AutoTesting runner.
private static readonly string DiagLogPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "gs-diag.log");
private static void DiagLog(string message)
{
try { System.IO.File.AppendAllText(DiagLogPath, $"{DateTime.UtcNow:HH:mm:ss.fff} [tid={Thread.CurrentThread.ManagedThreadId}] GS: {message}\n"); }
catch { /* best-effort */ }
}
[STAThread]
public static void Main()
{
// Surface a recorded --graphics-api startup error and exit.
if (GraphicsApiSelector.StartupError is { } graphicsApiError)
{
MessageBox.Show(graphicsApiError, "Stride", MessageBoxButton.OK, MessageBoxImage.Error);
Environment.Exit(1);
}
// The persisted graphics API preference isn't staged in this build: offer to fall back
// and reset the setting, so the user isn't stuck in a fail-at-launch loop.
if (GraphicsApiHostResolver.UnavailablePreference is { } unavailableApi)
{
var fallback = GraphicsApiHostResolver.FallbackApi;
var choice = MessageBox.Show(
$"Graphics API '{unavailableApi}' (from Game Studio settings) is not available in this build.\n\nContinue with '{fallback}' and reset the setting to Default?",
"Stride", MessageBoxButton.YesNo, MessageBoxImage.Warning);
if (choice != MessageBoxResult.Yes)
Environment.Exit(1);
GraphicsApiHostResolver.UseFallback();
resetGraphicsApiPreference = true;
}
Run(Environment.GetCommandLineArgs().Skip(1).ToList());
}
/// <summary>
/// Editor entry point body. <paramref name="appHosted"/> fires after
/// <c>InitializeComponent</c> and before <c>app.Run</c>, giving the AutoTesting runner
/// access to the WPF Application + dispatcher.
/// </summary>
public static void Run(IList<string> args, Action<Application, Dispatcher>? appHosted = null)
{
DiagLog($"Run entered. args=[{string.Join(", ", args)}]");
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
EditorPath.EditorTitle = StrideGameStudio.EditorName;
if (IntPtr.Size == 4)
{
MessageBox.Show("Stride GameStudio requires a 64bit OS to run.", "Stride", MessageBoxButton.OK, MessageBoxImage.Error);
Environment.Exit(1);
}
// We use MRU of the current version only when we're trying to reload last session.
var mru = new MostRecentlyUsedFileCollection(InternalSettings.LoadProfileCopy, InternalSettings.MostRecentlyUsedSessions, InternalSettings.WriteFile);
mru.LoadFromSettings();
EditorSettings.Initialize();
if (resetGraphicsApiPreference)
{
EditorSettings.GraphicsApi.SetValue(EditorSettings.GraphicsApiDefault);
EditorSettings.Save();
}
Thread.CurrentThread.Name = "Main thread";
try
{
var startupSessionPath = StrideEditorSettings.StartupSession.GetValue();
var lastSessionPath = EditorSettings.ReloadLastSession.GetValue() ? mru.MostRecentlyUsedFiles.FirstOrDefault() : null;
var initialSessionPath = !UPath.IsNullOrEmpty(startupSessionPath) ? startupSessionPath : lastSessionPath?.FilePath;
// Handle arguments
for (var i = 0; i < args.Count; i++)
{
if (args[i] == "/LauncherWindowHandle")
{
windowHandle = new IntPtr(long.Parse(args[++i]));
}
else if (args[i] == "/NewProject")
{
initialSessionPath = null;
}
else if (args[i] == "/DebugEditorGraphics")
{
StrideConfig.GraphicsDebugMode = true;
}
else if (args[i] == "--graphics-api")
{
// Consumed at startup by GraphicsApiSelector; skip the following value here.
i++;
}
else if (args[i] == "/DisableThumbnails")
{
enableThumbnailServices = false;
}
else if (args[i] == "/DisablePreview")
{
GameStudioPreviewService.DisablePreview = true;
}
#if STRIDE_GRAPHICS_API_DIRECT3D12
else if (args[i] == "/PixGpuCapturer")
{
WinPixNative.LoadPixGpuCapturer();
}
#endif
else if (args[i] == "/RenderDoc")
{
// TODO: RenderDoc is not working here (when not in debug)
GameStudioPreviewService.DisablePreview = true;
renderDocManager = new RenderDocManager();
renderDocManager.Initialize();
}
else if (args[i] == "/RecordEffects")
{
GameStudioBuilderService.GlobalEffectLogPath = args[++i];
}
else
{
initialSessionPath = args[i];
}
}
RuntimeHelpers.RunModuleConstructor(typeof(Asset).Module.ModuleHandle);
//listen to logger for crash report
GlobalLogger.GlobalMessageLogged += GlobalLoggerOnGlobalMessageLogged;
// Route GlobalLogger output to VS Debug pane (no-op in Release).
// Warning+ only — Info/Verbose volume slows the debugger noticeably during
// asset compile / NuGet restore.
GlobalLogger.GlobalMessageLogged += new DebugLogListener { MinimumLevel = LogMessageType.Warning };
mainDispatcher = Dispatcher.CurrentDispatcher;
mainDispatcher.InvokeAsync(() =>
{
// Surface startup failures that escape Startup before its first await, instead of
// leaving the dispatcher pumping with no window.
try
{
Startup(initialSessionPath);
}
catch (Exception ex)
{
HandleException(ex, 0);
}
});
using (new WindowManager(mainDispatcher))
{
app = new App { ShutdownMode = ShutdownMode.OnExplicitShutdown };
app.DispatcherUnhandledException += (sender, eventArgs) =>
{
eventArgs.Handled = true;
HandleException(eventArgs.Exception, 0);
};
app.InitializeComponent();
appHosted?.Invoke(app, mainDispatcher);
DiagLog("calling app.Run");
app.Run();
DiagLog("app.Run returned");
}
renderDocManager?.RemoveHooks();
}
catch (Exception e)
{
HandleException(e, 0);
}
}
private static void GlobalLoggerOnGlobalMessageLogged(ILogMessage logMessage)
{
if (logMessage.Type <= LogMessageType.Warning) return;
LogRingbuffer.Enqueue(logMessage.ToString());
while (LogRingbuffer.Count > 5)
{
LogRingbuffer.TryDequeue(out var msg);
}
}
private sealed record CrashReportArgs(int Location, Exception Exception, string[] Log, string ThreadName);
private static void CrashReport(object data)
{
var args = (CrashReportArgs)data;
//Stop the game studio rendering thread
mainDispatcher?.InvokeAsync(() => Thread.CurrentThread.Join());
CrashReportHelper.SendReport(args.Exception.FormatFull(), args.Location, args.Log, args.ThreadName);
//Make sure we stop now.. more exceptions might come but we just grab the first one
Environment.Exit(0);
}
private static void HandleException(Exception exception, int location)
{
if (exception == null) return;
//prevent multiple crash reports
if (terminating) return;
terminating = true;
// In case assembly resolve was not done yet, disable it altogether
NuGetAssemblyResolver.DisableAssemblyResolve();
var englishCulture = new CultureInfo("en-US");
var crashLogThread = new Thread(CrashReport) { CurrentUICulture = englishCulture, CurrentCulture = englishCulture };
crashLogThread.SetApartmentState(ApartmentState.STA);
crashLogThread.Start(new CrashReportArgs(location, exception, LogRingbuffer.ToArray(), Thread.CurrentThread.Name));
crashLogThread.Join();
}
[SecurityCritical]
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (e.IsTerminating)
{
HandleException(e.ExceptionObject as Exception, 1);
}
}
private static async void Startup(UFile initialSessionPath)
{
try
{
InitializeLanguageSettings();
var serviceProvider = InitializeServiceProvider();
try
{
PackageSessionPublicHelper.FindAndSetMSBuildVersion();
}
catch (Exception e)
{
var message = "Could not find a compatible version of MSBuild.\r\n\r\n" +
"Check that you have a valid installation with the required workloads, or go to [www.visualstudio.com/downloads](https://www.visualstudio.com/downloads) to install a new one.\r\n" +
$"Also make sure you have the latest [.NET {PackageSessionPublicHelper.NetMajorVersion} SDK](https://dotnet.microsoft.com/) \r\n\r\n" +
e;
await serviceProvider.Get<IDialogService>().MessageBoxAsync(message, Core.Presentation.Services.MessageBoxButton.OK, Core.Presentation.Services.MessageBoxImage.Error);
app.Shutdown();
return;
}
// We use a MRU that contains the older version projects to display in the editor
var mru = new MostRecentlyUsedFileCollection(InternalSettings.LoadProfileCopy, InternalSettings.MostRecentlyUsedSessions, InternalSettings.WriteFile);
mru.LoadFromSettings();
var editor = new GameStudioViewModel(serviceProvider, mru);
AssetsPlugin.RegisterPlugin(typeof(StrideDefaultAssetsPlugin));
var strideEditorPlugin = (StrideEditorPlugin)AssetsPlugin.RegisterPlugin(typeof(StrideEditorPlugin));
strideEditorPlugin.EnableThumbnailService = enableThumbnailServices;
// Attempt to load the startup session, if available
if (!UPath.IsNullOrEmpty(initialSessionPath))
{
var sessionLoaded = await editor.OpenInitialSession(initialSessionPath);
if (sessionLoaded == true)
{
var mainWindow = new GameStudioWindow(editor);
Application.Current.MainWindow = mainWindow;
WindowManager.ShowMainWindow(mainWindow);
return;
}
}
// No session successfully loaded, open the new/open project window
bool? completed;
// The user might cancel after chosing a template to instantiate, in this case we'll reopen the window
var startupWindow = new ProjectSelectionWindow
{
WindowStartupLocation = WindowStartupLocation.CenterScreen,
ShowInTaskbar = true,
};
var viewModel = new NewOrOpenSessionTemplateCollectionViewModel(serviceProvider, startupWindow);
startupWindow.Templates = viewModel;
startupWindow.ShowDialog();
// The user selected a template to instantiate
if (startupWindow.NewSessionParameters != null)
{
// Clean existing entry in the MRU data
var directory = startupWindow.NewSessionParameters.OutputDirectory;
var name = startupWindow.NewSessionParameters.OutputName;
var mruData = new MRUAdditionalDataCollection(InternalSettings.LoadProfileCopy, GameStudioInternalSettings.MostRecentlyUsedSessionsData, InternalSettings.WriteFile);
mruData.RemoveFile(UFile.Combine(UDirectory.Combine(directory, name), new UFile(name + SessionViewModel.SolutionExtension)));
completed = await editor.NewSession(startupWindow.NewSessionParameters);
}
// The user selected a path to open
else if (startupWindow.ExistingSessionPath != null)
{
completed = await editor.OpenSession(startupWindow.ExistingSessionPath);
}
// The user cancelled from the new/open project window, so exit the application
else
{
completed = true;
}
if (completed != true)
{
var windowsClosed = new List<Task>();
foreach (var window in Application.Current.Windows.Cast<Window>().Where(x => x.IsLoaded))
{
var tcs = new TaskCompletionSource<int>();
window.Unloaded += (s, e) => tcs.SetResult(0);
windowsClosed.Add(tcs.Task);
}
await Task.WhenAll(windowsClosed);
// When a project has been partially loaded, it might already have initialized some plugin that could conflict with
// the next attempt to start something. Better start the application again.
var commandLine = string.Join(" ", Environment.GetCommandLineArgs().Skip(1).Select(x => $"\"{x}\""));
var process = new Process { StartInfo = new ProcessStartInfo(typeof(Program).Assembly.Location, commandLine) };
process.Start();
app.Shutdown();
return;
}
if (editor.Session != null)
{
// If a session was correctly loaded, show the main window
var mainWindow = new GameStudioWindow(editor);
Application.Current.MainWindow = mainWindow;
WindowManager.ShowMainWindow(mainWindow);
}
else
{
// Otherwise, exit.
app.Shutdown();
}
}
catch (Exception ex)
{
// Don't shut down silently — report the failure so the user sees what went wrong.
HandleException(ex, 0);
}
}
private static void RestartApplication()
{
var args = Environment.GetCommandLineArgs();
var startInfo = new ProcessStartInfo(Assembly.GetEntryAssembly().Location)
{
Arguments = string.Join(" ", args.Skip(1)),
WorkingDirectory = Environment.CurrentDirectory,
};
Process.Start(startInfo);
Environment.Exit(0);
}
private static IViewModelServiceProvider InitializeServiceProvider()
{
// TODO: this should be done elsewhere
var dispatcherService = new DispatcherService(Dispatcher.CurrentDispatcher);
var dialogService = new StrideDialogService(dispatcherService, StrideGameStudio.EditorName);
var pluginService = new PluginService();
var services = new List<object>{ new DispatcherService(Dispatcher.CurrentDispatcher), dialogService, pluginService };
if (renderDocManager != null)
services.Add(renderDocManager);
var serviceProvider = new ViewModelServiceProvider(services);
return serviceProvider;
}
private static void InitializeLanguageSettings()
{
TranslationManager.Instance.RegisterProvider(new GettextTranslationProvider());
TranslationManager.Instance.CurrentLanguage = EditorSettings.Language.GetValue() switch
{
SupportedLanguage.MachineDefault => CultureInfo.InstalledUICulture,
SupportedLanguage.English => new CultureInfo("en-US"),
SupportedLanguage.French => new CultureInfo("fr-FR"),
SupportedLanguage.Japanese => new CultureInfo("ja-JP"),
SupportedLanguage.Russian => new CultureInfo("ru-RU"),
SupportedLanguage.German => new CultureInfo("de-DE"),
SupportedLanguage.Spanish => new CultureInfo("es-ES"),
SupportedLanguage.ChineseSimplified => new CultureInfo("zh-Hans"),
SupportedLanguage.Italian => new CultureInfo("it-IT"),
SupportedLanguage.Korean => new CultureInfo("ko-KR"),
_ => throw new ArgumentException("Invalid language option"),
};
}
internal static void NotifyGameStudioStarted()
{
if (windowHandle != IntPtr.Zero)
{
NativeHelper.SendMessage(windowHandle, NativeHelper.WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
}
}