forked from ToadsworthLP/desktoptale
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDesktoptale.cs
443 lines (366 loc) · 16.7 KB
/
Desktoptale.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using CommandLine;
using Desktoptale.Characters;
using Desktoptale.Messages;
using Desktoptale.Messaging;
using Desktoptale.Registry;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Color = Microsoft.Xna.Framework.Color;
namespace Desktoptale
{
public class Desktoptale : Game
{
public static string ApplicationPath { get; private set; }
public static string CustomCharacterPath { get; private set; }
private Settings settings;
private IRegistry<CharacterType, string> characterRegistry { get; }
private GraphicsDeviceManager graphics;
private SpriteBatch spriteBatch;
private InputManager inputManager;
private PresetManager presetManager;
private MonitorManager monitorManager;
private WindowTracker windowTracker;
private PartyManager partyManager;
private ContextMenu contextMenu;
private InteractionManager interactionManager;
private Physics physics;
private GlobalSettingsManager globalSettingsManager;
private DistractionManager distractionManager;
private ISet<ICharacter> characters;
private const int WINDOW_STATE_UPDATE_INTERVAL = 20;
private int windowStateUpdateCounter = 0;
private bool firstFrame = true;
private WindowInfo containingWindow;
private Point defaultCharacterStartPosition;
private Random rng = new Random();
private bool globalPause = false;
private readonly Color clearColor = new Color(0f, 0f, 0f, 0f);
private const string globalSettingsFilePath = "GlobalSettings.yaml";
private ConcurrentQueue<Action> UpdateTaskQueue;
public Desktoptale(Settings settings)
{
ApplicationPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
CustomCharacterPath = Path.Combine(ApplicationPath, "Content/Custom/");
this.settings = settings;
graphics = new GraphicsDeviceManager(this)
{
HardwareModeSwitch = false,
IsFullScreen = false,
GraphicsProfile = GraphicsProfile.HiDef
};
Window.Title = ProgramInfo.NAME;
Content.RootDirectory = "Content";
IsMouseVisible = true;
characterRegistry = new CharacterRegistry();
monitorManager = new MonitorManager();
windowTracker = new WindowTracker(monitorManager);
IsFixedTimeStep = true;
TargetElapsedTime = TimeSpan.FromSeconds(1d/60d);
UpdateTaskQueue = new ConcurrentQueue<Action>();
}
protected override void Initialize()
{
base.Initialize();
MessageBus.Subscribe<OtherInstanceStartedMessage>(OnOtherInstanceStartedMessage);
MessageBus.Subscribe<AddCharacterMessage>(OnAddCharacterMessage);
MessageBus.Subscribe<RemoveCharacterMessage>(OnRemoveCharacterMessage);
MessageBus.Subscribe<CharacterChangeRequestedMessage>(OnCharacterChangeRequestedMessage);
MessageBus.Subscribe<DisplaySettingsChangedMessage>(OnDisplaySettingsChangedMessage);
MessageBus.Subscribe<AddCharacterRequestedMessage>(OnAddCharacterRequestedMessage);
MessageBus.Subscribe<GlobalPauseMessage>(OnGlobalPauseMessage);
inputManager = new InputManager(monitorManager);
presetManager = new PresetManager(characterRegistry, partyManager);
physics = new Physics(inputManager);
spriteBatch = new SpriteBatch(GraphicsDevice);
interactionManager = new InteractionManager(monitorManager, Window, inputManager);
partyManager = new PartyManager();
characters = new HashSet<ICharacter>();
defaultCharacterStartPosition = monitorManager.ToMonoGameCoordinates(Window.ClientBounds.Center.ToVector2()).ToPoint();
UpdateWindow();
AddCharacterFromSettings(settings);
globalSettingsManager = new GlobalSettingsManager(globalSettingsFilePath);
if (!globalSettingsManager.DoesGlobalSettingsFileExist())
{
DisplayWelcomeMessage();
globalSettingsManager.GlobalSettings = new GlobalSettings();
globalSettingsManager.SaveGlobalSettings();
}
else
{
globalSettingsManager.LoadGlobalSettings();
}
distractionManager = new DistractionManager(Content, Window, windowTracker);
distractionManager.Initialize();
contextMenu = new ContextMenu(inputManager, characterRegistry, globalSettingsManager.GlobalSettings, partyManager);
globalSettingsManager.SendMessages();
}
private void OnGlobalPauseMessage(GlobalPauseMessage message)
{
globalPause = message.Paused;
if (message.Paused)
{
WindowsUtils.MakeClickthrough(Window);
}
else
{
WindowsUtils.MakeTopmostWindow(Window);
}
}
private void OnOtherInstanceStartedMessage(OtherInstanceStartedMessage message)
{
Settings settings = new Settings();
if (message.Args != null && message.Args.Length > 0)
{
Parser parser = new Parser(config =>
{
config.AutoHelp = false;
config.AutoVersion = false;
});
parser.ParseArguments<Settings>(message.Args)
.WithParsed<Settings>((s) =>
{
settings = s;
});
}
UpdateTaskQueue.Enqueue(() => AddCharacterFromSettings(settings));
}
private void AddCharacterFromSettings(Settings sourceSettings)
{
// Preset loading
CharacterProperties characterProperties = presetManager.LoadPreset(sourceSettings.Preset);
if (characterProperties != null && characterProperties.Position.X < 0 && characterProperties.Position.Y < 0)
characterProperties.Position = defaultCharacterStartPosition.ToVector2();
// If no preset had been loaded, create a character according to the CLI settings
if (characterProperties == null)
{
CharacterType initialCharacter = CharacterRegistry.FRISK;
if (!string.IsNullOrWhiteSpace(sourceSettings.Character))
{
try
{
initialCharacter = characterRegistry.Get(sourceSettings.Character);
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine($"Failed to add character: Invalid character registry key: {sourceSettings.Character}");
WindowsUtils.ShowMessageBox($"Could not find character: {sourceSettings.Character}\nIf this character is a custom character, please make sure that it is installed properly.", ProgramInfo.NAME, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
WindowInfo stayInsideWindow = null;
if (!string.IsNullOrWhiteSpace(sourceSettings.Window))
{
WindowInfo target = WindowsUtils.GetWindowByName(sourceSettings.Window);
if (target != null)
{
stayInsideWindow = target;
}
else
{
Console.WriteLine($"Failed to attach to window: Window or process {sourceSettings.Window} could not be found.");
}
}
Party party = null;
if (!string.IsNullOrWhiteSpace(settings.Party))
{
party = partyManager.GetOrCreateParty(settings.Party);
}
characterProperties = new CharacterProperties(
initialCharacter,
defaultCharacterStartPosition.ToVector2(),
new Vector2(sourceSettings.Scale),
sourceSettings.IdleRoaming,
sourceSettings.UnfocusedInput,
stayInsideWindow,
party
);
}
MessageBus.Send(new AddCharacterMessage() { Properties = characterProperties });
}
protected override void LoadContent()
{
ExternalCharacterFactory externalCharacterFactory = new ExternalCharacterFactory(CustomCharacterPath, graphics.GraphicsDevice);
externalCharacterFactory.AddAllToRegistry(characterRegistry);
if(settings.PrintRegistryKeys) PrintRegistryKeys();
}
protected override void UnloadContent()
{
Content.Unload();
}
protected override void Update(GameTime gameTime)
{
if (globalPause) return;
if (firstFrame)
{
WindowsUtils.PrepareWindow(Window);
WindowsUtils.MakeTopmostWindow(Window);
UpdateWindow();
firstFrame = false;
}
while (!UpdateTaskQueue.IsEmpty)
{
Action action = null;
UpdateTaskQueue.TryDequeue(out action);
action?.Invoke();
}
inputManager.Update();
windowTracker.Update();
foreach (var gameObject in characters)
{
gameObject.Update(gameTime);
}
physics.Update();
if (physics.HasColliderUnderCursorChanged)
{
if (physics.PhysicsObjectUnderCursor == null)
{
WindowsUtils.MakeClickthrough(Window);
}
else
{
WindowsUtils.MakeClickable(Window);
}
}
if (windowStateUpdateCounter >= WINDOW_STATE_UPDATE_INTERVAL)
{
WindowsUtils.MakeTopmostWindow(Window);
windowStateUpdateCounter = 0;
}
windowStateUpdateCounter++;
distractionManager.Update(gameTime);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(clearColor);
spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, samplerState: SamplerState.PointClamp);
foreach (var gameObject in characters)
{
gameObject.Draw(gameTime, spriteBatch);
}
distractionManager.Draw(gameTime, spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
private void UpdateWindow()
{
Rectangle boundingRect = monitorManager.BoundingRectangle;
graphics.PreferredBackBufferWidth = boundingRect.Width;
graphics.PreferredBackBufferHeight = boundingRect.Height;
graphics.ApplyChanges();
Window.Position = boundingRect.Location;
}
private void OnDisplaySettingsChangedMessage(DisplaySettingsChangedMessage message)
{
UpdateWindow();
}
private void OnAddCharacterMessage(AddCharacterMessage message)
{
Character character;
try
{
character = message.Properties.Type.FactoryFunction
.Invoke(new CharacterCreationContext(message.Properties, spriteBatch, inputManager, monitorManager, windowTracker));
character.LoadContent(Content);
}
catch (Exception e)
{
Console.WriteLine($"Failed to add character: {e.Message}");
WindowsUtils.ShowMessageBox($"Failed to add character: {e.Message}", ProgramInfo.NAME, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
character.Initialize();
characters.Add(character);
physics.AddCollider(character);
MessageBus.Send(new FocusCharacterMessage() {Character = character });
}
private void OnRemoveCharacterMessage(RemoveCharacterMessage message)
{
physics.RemoveCollider(message.Target);
characters.Remove(message.Target);
message.Target.Dispose();
if (characters.Count == 0)
{
Exit();
}
}
private void OnAddCharacterRequestedMessage(AddCharacterRequestedMessage message)
{
CharacterProperties characterProperties = new CharacterProperties(
message.Character,
message.Target.Properties.Position + new Vector2((float)((rng.NextDouble() - 0.5d) * message.Target.HitBox.Width), (message.Target.HitBox.Height / 2f)),
message.Target.Properties.Scale,
message.Target.Properties.IdleRoamingEnabled,
message.Target.Properties.UnfocusedInputEnabled,
message.Target.TrackedWindow?.Window,
message.Target.Properties.Party
);
Character newCharacter;
try
{
newCharacter = message.Character.FactoryFunction
.Invoke(new CharacterCreationContext(characterProperties, spriteBatch, inputManager, monitorManager, windowTracker));
newCharacter.LoadContent(Content);
}
catch (Exception e)
{
Console.WriteLine($"Failed to switch character: {e.Message}");
WindowsUtils.ShowMessageBox($"Failed to switch character: {e.Message}", ProgramInfo.NAME, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
newCharacter.Properties.Type = message.Character;
newCharacter.Initialize();
characters.Add(newCharacter);
physics.AddCollider(newCharacter);
MessageBus.Send(new FocusCharacterMessage() {Character = newCharacter });
}
private void OnCharacterChangeRequestedMessage(CharacterChangeRequestedMessage message)
{
ICharacter oldCharacter = message.Target;
Character newCharacter;
try
{
newCharacter = message.Character.FactoryFunction
.Invoke(new CharacterCreationContext(new CharacterProperties(oldCharacter.Properties), spriteBatch, inputManager, monitorManager, windowTracker));
newCharacter.LoadContent(Content);
}
catch (Exception e)
{
Console.WriteLine($"Failed to switch character: {e.Message}");
WindowsUtils.ShowMessageBox($"Failed to switch character: {e.Message}", ProgramInfo.NAME, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
physics.RemoveCollider(oldCharacter);
characters.Remove(oldCharacter);
oldCharacter.Dispose();
newCharacter.Properties.Type = message.Character;
newCharacter.Initialize();
characters.Add(newCharacter);
physics.AddCollider(newCharacter);
MessageBus.Send(new CharacterChangeSuccessMessage { Character = message.Character });
MessageBus.Send(new FocusCharacterMessage() {Character = newCharacter });
}
private void PrintRegistryKeys()
{
Console.WriteLine("Currently registered characters:");
foreach (string key in characterRegistry.GetAllIds())
{
Console.WriteLine(key);
}
}
private void DisplayWelcomeMessage()
{
DialogResult result = WindowsUtils.ShowMessageBox(ProgramInfo.WELCOME_MESSAGE, ProgramInfo.NAME,
MessageBoxButtons.YesNo, MessageBoxIcon.None);
if (result == DialogResult.Yes)
{
MessageBus.Send(new SetPresetFileAssociationRequestedMessage());
}
}
}
}