This repository has been archived by the owner on Jan 4, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 98
/
DesktopRunner.cs
executable file
·1992 lines (1597 loc) · 74.9 KB
/
DesktopRunner.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) Jesse Freeman, Pixel Vision 8. All rights reserved.
//
// Licensed under the Microsoft Public License (MS-PL) except for a few
// portions of the code. See LICENSE file in the project root for full
// license information. Third-party libraries used by Pixel Vision 8 are
// under their own licenses. Please refer to those libraries for details
// on the license they use.
//
// Contributors
// --------------------------------------------------------
// This is the official list of Pixel Vision 8 contributors:
//
// Jesse Freeman - @JesseFreeman
// Christina-Antoinette Neofotistou @CastPixel
// Christer Kaitila - @McFunkypants
// Pedro Medeiros - @saint11
// Shawn Rakowski - @shwany
// Drake Williams - drakewill+pv8@gmail.com
//
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using MoonSharp.Interpreter;
using MoonSharp.VsCodeDebugger;
using MoonSharp.VsCodeDebugger.DebuggerLogic;
using PixelVision8.Engine;
using PixelVision8.Engine.Chips;
using PixelVision8.Engine.Services;
using PixelVision8.Runner.Data;
using PixelVision8.Runner.Editors;
using PixelVision8.Runner.Services;
using PixelVision8.Runner.Utils;
using PixelVision8.Runner.Workspace;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Buttons = PixelVision8.Engine.Chips.Buttons;
namespace PixelVision8.Runner
{
public enum ErrorCode
{
Exception,
LoadError,
NoAutoRun
}
// Runner modes
public enum RunnerMode
{
Playing,
Booting,
Loading,
Error
}
/// <summary>
/// This is the main type for your game.
/// </summary>
public class DesktopRunner : GameRunner
{
public readonly Dictionary<ActionKeys, Keys> actionKeys = new Dictionary<ActionKeys, Keys>
{
// TODO need to add the other action keys here so they are mapped in the bios
{ActionKeys.BackKey, Keys.Escape},
{ActionKeys.ScreenShotKey, Keys.D2},
{ActionKeys.RecordKey, Keys.D3},
{ActionKeys.RestartKey, Keys.D4}
};
private GameEditor _editor;
public bool autoRunEnabled = true;
public bool backKeyEnabled = true;
public BiosService bios;
protected WorkspacePath biosPath = WorkspacePath.Root.AppendDirectory("App").AppendFile("bios.json");
protected IControllerChip controllerChip;
protected string documentsPath;
protected bool ejectingDisk;
public string[] GameFiles;
protected GifExporter gifEncoder;
public List<KeyValuePair<string, Dictionary<string, string>>> loadHistory =
new List<KeyValuePair<string, Dictionary<string, string>>>();
public bool LuaMode = true;
protected LuaService luaService;
protected bool mountingDisk;
protected Dictionary<string, string> nextMetaData;
protected RunnerMode nextMode;
protected string nextPathToLoad;
protected string rootPath;
protected bool screenShotActive;
protected float screenshotDelay = 200f;
private ScreenshotService screenshotService;
protected float screenshotTime;
protected bool shutdown;
public string systemName;
public string SystemVersion;
protected string tmpPath;
public WorkspaceService workspaceService;
protected WorkspaceServicePlus workspaceServicePlus;
public LoadService loadService;
public IServiceLocator ServiceManager { get; }
protected RunnerMode mode;
protected bool displayProgress;
private string bootDisk;
protected override bool RunnerActive
{
get
{
if (_autoShutdown && mode != RunnerMode.Loading) return IsActive;
return true;
}
}
// Default path to where PV8 workspaces will go
public DesktopRunner(string rootPath, string bootDisk = null)
{
// Fix a bug related to parsing numbers in Europe, among other things
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;
ServiceManager = new ServiceManager();
this.rootPath = rootPath;
server = new MoonSharpVsCodeDebugServer(1985);
server.Start();
if (bootDisk != null && bootDisk.EndsWith(".pv8") ? File.Exists(bootDisk) : Directory.Exists(bootDisk))
{
this.bootDisk = bootDisk;
}
}
protected MoonSharpVsCodeDebugServer server;
private bool attachScript = true;
public string SessionId { get; protected set; }
protected WorkspacePath userBiosPath => WorkspacePath.Parse("/Storage/user-bios.json");
public string LocalStorage
{
get
{
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
// TODO replace with something better
DisplayWarning("Local Storage Located at " + localAppData);
return localAppData;
}
}
public override List<string> DefaultChips
{
get
{
var chips = new List<string>
{
typeof(ColorChip).FullName,
typeof(SpriteChip).FullName,
typeof(TilemapChip).FullName,
typeof(FontChip).FullName,
typeof(ControllerChip).FullName,
typeof(DisplayChip).FullName,
typeof(SfxrSoundChip).FullName,
typeof(MusicChip).FullName
};
// Return the list of chips
return chips;
}
}
protected string Documents => Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
public GameDataExportService ExportService { get; protected set; }
public bool Recording { get; set; }
protected string DefaultWindowTitle =>
bios.ReadBiosData(BiosSettings.SystemName.ToString(), "Pixel Vision 8 Runner") + " " +
bios.ReadBiosData(BiosSettings.SystemVersion.ToString(), "0.0.0");
public GameEditor Editor
{
get
{
if (_editor == null) _editor = new GameEditor(this, ServiceManager);
return _editor;
}
}
public void CreateLoadService()
{
loadService = new LoadService(new WorkspaceFileLoadHelper(workspaceService));
Script.DefaultOptions.ScriptLoader = new ScriptLoaderUtil(workspaceService);
}
public override void ConfigureDisplayTarget()
{
// Get the virtual monitor resolution
var tmpRes = bios.ReadBiosData(BiosSettings.Resolution.ToString(), "512x480")
.Split('x').Select(int.Parse)
.ToArray();
if (DisplayTarget == null) DisplayTarget = new DisplayTarget(_graphics, tmpRes[0], tmpRes[1]);
Fullscreen(Convert.ToBoolean(
bios.ReadBiosData(BiosSettings.FullScreen.ToString(), "False")));
StretchScreen(
Convert.ToBoolean(
bios.ReadBiosData(BiosSettings.StretchScreen.ToString(), "False")));
CropScreen(Convert.ToBoolean(
bios.ReadBiosData(BiosSettings.CropScreen.ToString(), "True")));
Scale(Convert.ToInt32(bios.ReadBiosData(BiosSettings.Scale.ToString(), "1")));
if (((DisplayTarget)DisplayTarget).HasShader() == false)
{
// Configure CRT shader
var shaderPath = WorkspacePath.Parse(bios.ReadBiosData(CRTSettings.CRTEffectPath.ToString(),
"/App/Effects/crt-lottes-mg.ogl.mgfxo"));
if (workspaceService.Exists(shaderPath))
((DisplayTarget)DisplayTarget).shaderPath = workspaceService.OpenFile(shaderPath, FileAccess.Read);
}
DisplayTarget.ResetResolution(tmpRes[0], tmpRes[1]);
// Configure the shader from the bios
Brightness(Convert.ToSingle(bios.ReadBiosData(CRTSettings.Brightness.ToString(), "100")) / 100F);
Sharpness(Convert.ToSingle(bios.ReadBiosData(CRTSettings.Sharpness.ToString(), "-6")));
}
// public enum InputMap
// {
// Player1UpKey,
// Player1DownKey,
// Player1RightKey,
// Player1LeftKey,
// Player1SelectKey,
// Player1StartKey,
// Player1AKey,
// Player1BKey,
// Player1UpButton,
// Player1DownButton,
// Player1RightButton,
// Player1LeftButton,
// Player1SelectButton,
// Player1StartButton,
// Player1AButton,
// Player1BButton,
// Player2UpKey,
// Player2DownKey,
// Player2RightKey,
// Player2LeftKey,
// Player2SelectKey,
// Player2StartKey,
// Player2AKey,
// Player2BKey,
// Player2UpButton,
// Player2DownButton,
// Player2RightButton,
// Player2LeftButton,
// Player2SelectButton,
// Player2StartButton,
// Player2AButton,
// Player2BButton
// }
public readonly Dictionary<string, int> defaultKeys = new Dictionary<string, int>
{
{"Player1UpKey", (int) Keys.Up},
{"Player1DownKey", (int) Keys.Down},
{"Player1RightKey", (int) Keys.Right},
{"Player1LeftKey", (int) Keys.Left},
{"Player1SelectKey", (int) Keys.A},
{"Player1StartKey", (int) Keys.S},
{"Player1AKey", (int) Keys.X},
{"Player1BKey", (int) Keys.C},
{"Player1UpButton", (int) Buttons.Up},
{"Player1DownButton", (int) Buttons.Down},
{"Player1RightButton", (int) Buttons.Right},
{"Player1LeftButton", (int) Buttons.Left},
{"Player1SelectButton", (int) Buttons.Select},
{"Player1StartButton", (int) Buttons.Start},
{"Player1AButton", (int) Buttons.A},
{"Player1BButton", (int) Buttons.B},
{"Player2UpKey", (int) Keys.I},
{"Player2DownKey", (int) Keys.K},
{"Player2RightKey", (int) Keys.L},
{"Player2LeftKey", (int) Keys.J},
{"Player2SelectKey", (int) Keys.OemSemicolon},
{"Player2StartKey", (int) Keys.OemComma},
{"Player2AKey", (int) Keys.Enter},
{"Player2BKey", (int) Keys.RightShift},
{"Player2UpButton", (int) Buttons.Up},
{"Player2DownButton", (int) Buttons.Down},
{"Player2RightButton", (int) Buttons.Right},
{"Player2LeftButton", (int) Buttons.Left},
{"Player2SelectButton", (int) Buttons.Select},
{"Player2StartButton", (int) Buttons.Start},
{"Player2AButton", (int) Buttons.A},
{"Player2BButton", (int) Buttons.B}
};
protected void ConfigureKeyboard()
{
var targetEngine = _tmpEngine as PixelVisionEngine;
// Pass input mapping
foreach (var keyMap in defaultKeys)
{
var rawValue = Convert.ToInt32(bios.ReadBiosData(keyMap.Key, keyMap.Value.ToString(), true));
var keyValue = rawValue;
targetEngine.SetMetadata(keyMap.Key, keyValue.ToString());
}
// base.ConfigureKeyboard();
var player1KeyboardMap = new Dictionary<Buttons, Keys>
{
{Buttons.Up, (Keys) Enum.Parse(typeof(Keys), targetEngine.GetMetadata(InputMap.Player1UpKey.ToString()))},
{
Buttons.Left,
(Keys) Enum.Parse(typeof(Keys), targetEngine.GetMetadata(InputMap.Player1LeftKey.ToString()))
},
{
Buttons.Right,
(Keys) Enum.Parse(typeof(Keys), targetEngine.GetMetadata(InputMap.Player1RightKey.ToString()))
},
{
Buttons.Down,
(Keys) Enum.Parse(typeof(Keys), targetEngine.GetMetadata(InputMap.Player1DownKey.ToString()))
},
{
Buttons.Select,
(Keys) Enum.Parse(typeof(Keys), targetEngine.GetMetadata(InputMap.Player1SelectKey.ToString()))
},
{
Buttons.Start,
(Keys) Enum.Parse(typeof(Keys), targetEngine.GetMetadata(InputMap.Player1StartKey.ToString()))
},
{Buttons.A, (Keys) Enum.Parse(typeof(Keys), targetEngine.GetMetadata(InputMap.Player1AKey.ToString()))},
{Buttons.B, (Keys) Enum.Parse(typeof(Keys), targetEngine.GetMetadata(InputMap.Player1BKey.ToString()))}
};
// var player2 = getPlayer(1);
// player2.GamePadIndex = KEYBOARD_INDEX;
var player2KeyboardMap = new Dictionary<Buttons, Keys>
{
{Buttons.Up, (Keys) Enum.Parse(typeof(Keys), targetEngine.GetMetadata(InputMap.Player2UpKey.ToString()))},
{
Buttons.Left,
(Keys) Enum.Parse(typeof(Keys), targetEngine.GetMetadata(InputMap.Player2LeftKey.ToString()))
},
{
Buttons.Right,
(Keys) Enum.Parse(typeof(Keys), targetEngine.GetMetadata(InputMap.Player2RightKey.ToString()))
},
{
Buttons.Down,
(Keys) Enum.Parse(typeof(Keys), targetEngine.GetMetadata(InputMap.Player2DownKey.ToString()))
},
{
Buttons.Select,
(Keys) Enum.Parse(typeof(Keys), targetEngine.GetMetadata(InputMap.Player2SelectKey.ToString()))
},
{
Buttons.Start,
(Keys) Enum.Parse(typeof(Keys), targetEngine.GetMetadata(InputMap.Player2StartKey.ToString()))
},
{Buttons.A, (Keys) Enum.Parse(typeof(Keys), targetEngine.GetMetadata(InputMap.Player2AKey.ToString()))},
{Buttons.B, (Keys) Enum.Parse(typeof(Keys), targetEngine.GetMetadata(InputMap.Player2BKey.ToString()))}
};
_tmpEngine.ControllerChip.RegisterKeyInput(player1KeyboardMap, player2KeyboardMap);
}
public override void ActivateEngine(IEngine engine)
{
// At this point this game is fully configured so all chips are accessible for extra configuring
if (mode == RunnerMode.Loading)
((LuaGameChip)engine.GameChip).LuaScript.Globals["DebuggerAttached"] =
new Func<bool>(AwaitDebuggerAttach);
// Save a reference to the controller chip so we can listen for special key events
controllerChip = engine.ControllerChip;
// Activate the game
BaseActivateEngine(engine);
}
private bool AwaitDebuggerAttach()
{
var connected = server.Connected;
if (connected == false && attachScript)
{
var tempQualifier = (LuaGameChip)_tmpEngine.GameChip;
// Kick off the first game script file
tempQualifier.LoadScript(tempQualifier.DefaultScriptPath);
var scriptPath = workspaceService.GetPhysicalPath(WorkspacePath.Parse(ActiveEngine.Name + "code.lua"));
server.AttachToScript(tempQualifier.LuaScript, scriptPath);
attachScript = false;
}
UpdateTitle();
return connected;
}
protected void OnTextInput(object sender, TextInputEventArgs e)
{
// Pass this to the input chip
controllerChip.SetInputText(e.Character, e.Key);
}
public virtual void BaseActivateEngine(IEngine engine)
{
if (engine == null) return;
// Make the loaded engine active
ActiveEngine = engine;
if (ActiveEngine?.GameChip is LuaGameChip)
{
var tempQualifier = (LuaGameChip)ActiveEngine.GameChip;
tempQualifier.LoadScript(tempQualifier.DefaultScriptPath);
}
ActiveEngine.ResetGame();
// After loading the game, we are ready to run it.
ActiveEngine.RunGame();
// Reset the game's resolution
ResetResolution();
// Make sure that the first frame is cleared with the default color
ActiveEngine.GameChip.Clear();
// No ned to call the base method since the logic is copied here
}
protected override void ConfigureRunner()
{
// Save the session ID
SessionId = DateTime.Now.ToString("yyyyMMddHHmmssffff");
SystemVersion = bios.ReadBiosData(BiosSettings.SystemVersion.ToString(), "0.0.0", true);
systemName = bios.ReadBiosData("SystemName", "PixelVision8", true);
base.ConfigureRunner();
CreateLoadService();
// TODO This may be a string
Volume(MathHelper.Clamp(
Convert.ToInt32(bios.ReadBiosData(BiosSettings.Volume.ToString(), "40", true)),
0, 100));
Mute(Convert.ToBoolean(bios.ReadBiosData(BiosSettings.Mute.ToString(), "False", true)));
Window.Title =
bios.ReadBiosData(BiosSettings.SystemName.ToString(), "Pixel Vision 8 Runner", true);
// Capture text input from the window
Window.TextInput += OnTextInput;
screenshotService = new ScreenshotService(workspaceServicePlus);
ExportService = new GameDataExportService(); //TODO Need to create a new AudioClipAdaptor
_autoShutdown = bios.ReadBiosData("AutoShutdown", "True") == "True";
RefreshActionKeys();
UpdateTitle();
}
public void RefreshActionKeys()
{
var actions = Enum.GetValues(typeof(ActionKeys)).Cast<ActionKeys>();
foreach (var action in actions)
actionKeys[action] =
(Keys)Convert.ToInt32(bios.ReadBiosData(action.ToString(), ((int)actionKeys[action]).ToString(),
true));
}
protected void CreateWorkspaceService()
{
// workspaceService = new WorkspaceService(new KeyValuePair<WorkspacePath, IFileSystem>(
// WorkspacePath.Root.AppendDirectory("App"),
// new PhysicalFileSystem(rootPath)));
//
// ServiceManager.AddService(typeof(WorkspaceService).FullName, workspaceService);
// TODO use partial class to add in support for workspace APIs needed by tools
workspaceServicePlus = new WorkspaceServicePlus(
new KeyValuePair<WorkspacePath, IFileSystem>(
WorkspacePath.Root.AppendDirectory("App"),
new PhysicalFileSystem(rootPath)
)
);
// Pass the new service back to the base class
workspaceService = workspaceServicePlus;
ServiceManager.AddService(typeof(WorkspaceService).FullName, workspaceService);
}
/// <summary>
/// This is called when the runner first starts up.
/// </summary>
protected override void Initialize()
{
// Create the workspace starting at the App's directory
CreateWorkspaceService();
// Test if a bios file exists
if (workspaceService.Exists(biosPath))
{
// Read the bios text
var biosText = workspaceService.ReadTextFromFile(biosPath);
//
bios = new BiosService();
try
{
bios.ParseBiosText(biosText);
}
catch
{
// DisplayBootErrorScreen("Error parsing system bios.");
}
ConfigureWorkspace();
// Configure the runner
ConfigureRunner();
// Load the game
LoadDefaultGame();
// Reset the filter based from bios after everything loads up
EnableCRT(Convert.ToBoolean(bios.ReadBiosData(CRTSettings.CRT.ToString(), "False")));
}
}
protected virtual void ConfigureWorkspace()
{
// Call the base ConfigureWorkspace method to configure the workspace correctly
var mounts = new Dictionary<WorkspacePath, IFileSystem>();
// Create the base directory in the documents and local storage folder
// Get the base directory from the bios or use Pixel Vision 8 as the default name
var baseDir = bios.ReadBiosData("BaseDir", "PixelVision8");
tmpPath = Path.Combine(LocalStorage, baseDir, "Tmp");
// Create an array of required directories
var requiredDirectories = new Dictionary<string, string>
{
{"Storage", Path.Combine(LocalStorage, baseDir)},
{"Tmp", tmpPath}
};
// Loop through the list of directories, make sure they exist and create them
foreach (var directory in requiredDirectories)
{
if (!Directory.Exists(directory.Value)) Directory.CreateDirectory(directory.Value);
// Add directories as mount points
mounts.Add(WorkspacePath.Root.AppendDirectory(directory.Key), new PhysicalFileSystem(directory.Value));
}
// Mount the filesystem
workspaceService.MountFileSystems(mounts);
var userBios = workspaceService.ReadTextFromFile(userBiosPath);
bios.ParseBiosText(userBios);
workspaceService.SetupLogFile(WorkspacePath.Parse(bios.ReadBiosData("LogFilePath", "/Tmp/Log.txt")));
// Everything below is custom to PV8
// Define PV8 disk extensions from the bios
workspaceServicePlus.archiveExtensions =
bios.ReadBiosData("ArchiveExtensions", "zip,pv8,pvt,pvs,pva,pvr", true).Split(',')
.ToList();
// Define the valid file extensions from the bios
workspaceServicePlus.fileExtensions =
bios.ReadBiosData("FileExtensions", "png,lua,json,txt,wav,cs", true).Split(',')
.ToList();
// Define the files required to make a game valid from the bios
workspaceServicePlus.requiredFiles =
bios.ReadBiosData("RequiredFiles", "data.json,info.json", true).Split(',')
.ToList();
// Include any library files in the OS mount point
workspaceServicePlus.osLibPath = WorkspacePath.Root.AppendDirectory("PixelVisionOS")
.AppendDirectory(bios.ReadBiosData("LibsDir", "Libs", true));
var createWorkspace = bios.ReadBiosData("CreateWorkspace", "True");
if (createWorkspace == "True")
{
// Look for the workspace name
var workspaceName = bios.ReadBiosData("WorkspaceDir", "Workspace", true);
// Set the TotalDisks disks
workspaceServicePlus.MaxDisks = int.Parse(bios.ReadBiosData("MaxDisks", "2", true));
// Create the real system path to the documents folder
documentsPath = Path.Combine(Documents, baseDir);
if (Directory.Exists(documentsPath) == false) Directory.CreateDirectory(documentsPath);
// Create a new physical file system mount
workspaceServicePlus.AddMount(new KeyValuePair<WorkspacePath, IFileSystem>(
WorkspacePath.Root.AppendDirectory("User"),
new PhysicalFileSystem(documentsPath)));
// Mount the workspace drive
workspaceServicePlus.MountWorkspace(workspaceName);
}
workspaceServicePlus.RebuildWorkspace();
}
public void EjectDisk(string path)
{
ejectingDisk = true;
workspaceServicePlus.EjectDisk(WorkspacePath.Parse(path));
UpdateDiskInBios();
AutoLoadDefaultGame();
ejectingDisk = false;
}
public void EnableAutoRun(bool value)
{
autoRunEnabled = value;
}
public void EnableBackKey(bool value)
{
backKeyEnabled = value;
}
/// <summary>
/// This quits the current tool and returns to the default tool which should be the workspace explorer.
/// </summary>
/// <param name="metaData">
/// An optional argument to supply additional metadata back to the tool that is loaded when
/// quitting.
/// </param>
/// <param name="tool">
/// An optional argument that allows you to supply a string name for a built-in tool to load instead of
/// the default workspace explorer.
/// </param>
public void QuitCurrentTool(Dictionary<string, string> metaData, string tool = null)
{
// When quitting, we should modify the history by removing the current game and if a new game is provided, add that to the history
if (tool != null)
// TODO need to remove the previous game from the history
Load(tool, RunnerMode.Loading, metaData);
else
Back(metaData);
}
protected override void Update(GameTime gameTime)
{
// while (Sdl.PollEvent(out ev) == 1)
// {
if (ActiveEngine == null || shutdown) return;
// TODO make sure this order is correct or maybe it can be cleaned up
if (screenShotActive)
{
screenshotTime += _timeDelta;
if (screenshotTime > screenshotDelay)
{
screenShotActive = false;
screenshotTime = 0;
}
UpdateTitle();
}
if (controllerChip.GetKeyDown(Keys.LeftControl) ||
controllerChip.GetKeyDown(Keys.LeftControl))
{
if (controllerChip.GetKeyUp(actionKeys[ActionKeys.ScreenShotKey]))
{
// Only take a screenshot when one isn't being saved
if (!screenShotActive)
screenShotActive = screenshotService.TakeScreenshot(ActiveEngine);
}
else if (controllerChip.GetKeyUp(actionKeys[ActionKeys.RecordKey]))
{
if (Recording)
StopRecording();
else
StartRecording();
}
else if (controllerChip.GetKeyUp(actionKeys[ActionKeys.RestartKey]))
{
if (controllerChip.GetKeyDown(Keys.LeftShift) || controllerChip.GetKeyDown(Keys.RightShift))
AutoLoadDefaultGame();
else
ResetGame();
}
}
else if (controllerChip.GetKeyUp(Keys.Escape) && backKeyEnabled)
{
Back();
}
// Capture Script errors
try
{
base.Update(gameTime);
}
catch (Exception e)
{
DisplayError(ErrorCode.Exception,
new Dictionary<string, string>
{{"@{error}", e is ScriptRuntimeException error ? error.DecoratedMessage : e.Message + e.StackTrace.Split("\r\n")[0]}},
e);
}
}
protected override void Draw(GameTime gameTime)
{
try
{
// If we are taking a screenshot, clear with white and don't draw the runner.
if (screenShotActive)
{
// TODO need to figure out why this is not displaying white when a screen shot happens
_graphics.GraphicsDevice.Clear(Color.White);
}
else
{
base.Draw(gameTime);
if (Recording) gifEncoder.AddFrame(_timeDelta / 1000f);
}
workspaceServicePlus.SaveLog();
}
catch (Exception e)
{
DisplayError(ErrorCode.Exception,
new Dictionary<string, string>
{{"@{error}", e is ScriptRuntimeException error ? error.DecoratedMessage : e.Message}}, e);
}
}
// Custom method to use instaed of the default BootDone
public void BootDone(bool safeMode = false)
{
// Only call BootDone when the runner is booting.
if (mode != RunnerMode.Booting) return;
// Test to see if we are in save mode before loading the bios
if (safeMode)
{
// Clear the current bios
bios.Clear();
// Read the bios text
var biosText = workspaceService.ReadTextFromFile(biosPath);
// Reparse the bios text
bios.ParseBiosText(biosText);
// Reset all the default values from the bios
ConfigureDisplayTarget();
}
// We only activate this if there is not bios setting to disable it
if (bios.ReadBiosData("FileDiskMounting", "True", true) != "False")
{
// Setup Drag and drop support
// Window.FileDropped += (o, e) => OnFileDropped(o, e);
// Window.FileDropped += (o, e) => OnFileDropped(o, e);
// Disable auto run when loading up the default disks
autoRunEnabled = false;
for (var i = 0; i < workspaceServicePlus.MaxDisks; i++)
{
var diskPath = bios.ReadBiosData("Disk" + i, "none", true);
if (diskPath != "none" && diskPath != "")
// manually mount each disk since we are not going to load from them
workspaceServicePlus.MountDisk(diskPath);
}
}
if (bootDisk == null)
{
AutoLoadDefaultGame();
}
else
{
// Force runner to auto run disk
autoRunEnabled = true;
// Mount the disk
MountDisk(bootDisk);
}
}
protected string GetErrorMessage(ErrorCode code)
{
return bios.ReadBiosData(code.ToString(), "Error code " + (int)code);
}
protected virtual void LoadError(Dictionary<string, string> metaData)
{
var tool = bios.ReadBiosData("ErrorTool", "/PixelVisionOS/Tools/ErrorTool/");
workspaceService.UpdateLog(metaData["errorMessage"], LogType.Error,
metaData.ContainsKey("exceptionMessage") ? metaData["exceptionMessage"] : null);
Load(tool, RunnerMode.Error, metaData);
}
public virtual void StartNextPreload()
{
// Print("Start Next Preload");
if (nextPathToLoad != null)
{
var success = Load(nextPathToLoad, nextMode, nextMetaData);
//TODO this needs to be tested more
if (success == false)
{
// loading = false;
DisplayError(ErrorCode.LoadError, new Dictionary<string, string> { { "@{path}", nextPathToLoad } });
}
else
{
// Clear the old data
nextPathToLoad = null;
nextMetaData = null;
loadService.StartLoading();
}
}
}
// public virtual void BootDone(bool safeMode = false)
// {
// // Only call BootDone when the runner is booting.
// if (mode != RunnerMode.Booting) return;
//
// // Test to see if we are in save mode before loading the bios
// if (safeMode)
// {
// // Clear the current bios
// bios.Clear();
//
// // Read the bios text
// var biosText = workspaceService.ReadTextFromFile(biosPath);
//
// // Reparse the bios text
// bios.ParseBiosText(biosText);
//
// }
//
// AutoLoadDefaultGame();
// }
/// <summary>
/// This mthod manually loads the game file's binary data then configures the engine and processes the files.
/// </summary>
protected virtual void LoadDefaultGame()
{
Load(bios.ReadBiosData("BootTool", "/PixelVisionOS/Tools/BootTool/"), RunnerMode.Booting);
}
public virtual void DisplayError(ErrorCode code, Dictionary<string, string> tokens = null,
Exception exception = null)
{
if (mode == RunnerMode.Error) return;
// TODO should this only work on special cases?
autoRunEnabled = true;
var sb = new StringBuilder();
// Pull the error message from the bios
var message = GetErrorMessage(code);
sb.Append(message);
if (tokens != null)
foreach (var entry in tokens)
sb.Replace(entry.Key, entry.Value);
var messageString = sb.ToString();
var metaData = new Dictionary<string, string>
{
{"errorMessage", messageString}
};
if (exception != null) metaData["exceptionMessage"] = exception.StackTrace;
// TODO need to be able to pass in an error
LoadError(metaData);
}
// TODO need to make sure this still works correctly
public virtual void AutoLoadDefaultGame()
{
// This doesn't call the base AutoLoadDefaultGame becasue it needs to check for disks
// Enable auto run by default
autoRunEnabled = true;
loadHistory.Clear();
// metaDataHistory.Clear();
// Look to see if we have the bios default tool in the OS folder
try
{
var biosAutoRun = bios.ReadBiosData("AutoRun");
// Check to see if this path exists
if (workspaceServicePlus.Exists(WorkspacePath.Parse(biosAutoRun)))
// Validate that the path is actually a game
if (workspaceService.ValidateGameInDir(WorkspacePath.Parse(biosAutoRun)))
{
// Attempt to load the game
Load(biosAutoRun, RunnerMode.Loading);
return;
}
}
catch
{
// Do nothing
}
// Try to boot from the first disk
try
{
var firstDiskPath = workspaceServicePlus.Disks.First().EntityName;
AutoRunGameFromDisk(firstDiskPath);
return;
}
catch
{