Repository navigation
Expand file tree
/
Copy pathBasicGameEngine.cpp
More file actions
5929 lines (5287 loc) · 208 KB
/
Copy pathBasicGameEngine.cpp
File metadata and controls
5929 lines (5287 loc) · 208 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
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
// BasicGameEngine.cpp : Defines the entry point for the application.
#include "../include/StatusBarMgr.h"
#include "../framework.h"
#include "../include/BasicGameEngine.h"
#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <commdlg.h>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cwchar>
#include <cwctype>
#include <fstream> // Pass A: bge.toml config reader
#include <iostream>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>
#include <thread>
#include <mutex> // For std::mutex and std::lock_guard
#include <vector>
#include "../resource.h"
#include <shellapi.h>
#include <windowsx.h>
#include "../include/TaskBarMgr.h"
#include "../include/WindowMutexMgr.h"
#include "../include/InterprocessCommMgr.h" // Include the InterprocessCommMgr header
#include "../include/SharedMemoryData.h" // Include the shared memory struct
#include "../include/UserPrivilegeMgr.h"
#include "../../OpNode/OpNode.h"
#include "../include/BgeScenePrimitives.h"
#include "../include/BasicGameRoleOperation.h"
#include "../include/DirectX11BouncingBallOperation.h"
#include "../include/DirectX11BouncingBallRenderer.h"
#include "../include/DirectX12BouncingBallRenderer.h"
UserPrivilegeMgr userPrivilegeMgr;
WindowMutexMgr windowMutexMgr; // Instance of the WindowMutexMgr
TaskBarMgr taskBarMgr; // Instance of the TaskBarMgr class
StatusBarMgr statusBarMgr; // Instance of the StatusBarMgr class
HINSTANCE hInst;
WCHAR szTitle[MAX_LOADSTRING];
WCHAR szWindowClass[MAX_LOADSTRING];
std::thread gameThread; // Game loop thread
std::mutex gameLoopMutex; // Mutex for synchronizing game loop
std::mutex ballConfigMutex;
bool isFocused = true; // Indicates whether this instance is focused
bool shouldRun = true; // Controls the main game loop
bool isPaused = false; // Indicates whether the game is paused
double lineX = 10.0; // Initial X position of the line
double lineY = 10.0; // Initial Y position of the line
bool movingRight = true; // Direction of movement
double speed = 0.1; // Speed in pixels per millisecond (adjustable)
// Pass A: diagnostic toggles loaded from bge.toml (next to exe).
// Default true preserves existing behavior if bge.toml is absent.
bool g_showMutexLine = true;
std::wstring g_bgeSharedMemoryName = L"Local\\BasicGameEngineSharedMemory";
std::wstring g_bgeCoordMutexName = L"Local\\BasicGameEngineCoordMutex";
constexpr UINT IDM_BGE_LAUNCH_STACK = 41001;
constexpr UINT IDM_BGE_LAUNCH_GAME_LOOP = 41002;
constexpr UINT IDM_BGE_LAUNCH_SCENE_3D = 41003;
constexpr UINT IDM_BGE_LAUNCH_IMAGES = 41004;
constexpr UINT IDM_BGE_LAUNCH_SOUND = 41005;
constexpr UINT IDM_BGE_LAUNCH_SAMPLE_ONE = 41006;
constexpr UINT IDM_BGE_LAUNCH_SAMPLE_TWO = 41007;
constexpr int IDC_BGE_ADD_BALL = 42001;
constexpr int IDC_BGE_START_ANIMATION = 42002;
constexpr int IDC_BGE_RENDERER = 42003;
constexpr int IDC_BGE_VELOCITY_X = 42004;
constexpr int IDC_BGE_VELOCITY_Y = 42005;
constexpr int IDC_BGE_APPLY_VECTOR = 42006;
constexpr int IDC_BGE_COLOR_R = 42007;
constexpr int IDC_BGE_COLOR_G = 42008;
constexpr int IDC_BGE_COLOR_B = 42009;
constexpr int IDC_BGE_APPLY_COLOR = 42010;
constexpr int IDC_BGE_LOAD_BACKGROUND = 42011;
constexpr int IDC_BGE_STOP_ANIMATION = 42012;
constexpr int IDC_BGE_OPEN_MAPPING = 42013;
constexpr int IDC_BGE_EDIT_MODE_STATUS = 42014;
constexpr int IDC_BGE_MAPPING_TEXT = 42015;
constexpr int IDC_BGE_OBJECT_SLOT_BASE = 42100;
constexpr int IDC_BGE_SOUND_SLOT_BASE = 42200;
constexpr int IDC_BGE_COMMAND_EDIT = 42300;
constexpr int IDC_BGE_RUN_COMMAND = 42301;
constexpr int IDC_BGE_COMMAND_STATUS = 42302;
constexpr int IDC_BGE_CONTROLLER_TARGET_BASE = 42400;
constexpr int IDC_BGE_CONTROLLER_LAUNCH_BASE = 42500;
constexpr int IDC_BGE_CONTROLLER_INSPECT_BASE = 42600;
constexpr int IDC_BGE_CONTROLLER_HIDE_BASE = 42700;
constexpr int IDC_BGE_CONTROLLER_STATUS_BASE = 42800;
constexpr int IDC_BGE_CONTROLLER_TARGET_LABEL = 42900;
constexpr int IDC_BGE_CONTROLLER_RUNTIME_STATUS = 42901;
constexpr int IDC_BGE_CONTROLLER_HISTORY = 42902;
constexpr int IDC_BGE_CONTROLLER_HISTORY_DETAIL = 42903;
constexpr int IDC_BGE_OPEN_HISTORY = 42904;
constexpr int IDC_BGE_OBJECT_GROUP_COMBO = 42910;
constexpr int IDC_BGE_ADD_OBJECT_GROUP = 42911;
constexpr int IDC_BGE_GHOST_GROUP_COMBO = 42912;
constexpr int IDC_BGE_TOGGLE_GHOST = 42913;
constexpr int IDC_BGE_SET_PLAYER = 42914;
constexpr int IDC_BGE_PLAYER_STATUS = 42915;
constexpr ULONG_PTR BGE_COPYDATA_WORKER_COMMAND = 0xB6E00001;
constexpr int BGE_CONTROLLER_ARTIFACT_COUNT = 6;
constexpr size_t BGE_CONTROLLER_HISTORY_LIMIT = 128;
constexpr size_t BGE_DELETE_HISTORY_LIMIT = 64;
constexpr float BGE_RENDER_TOP_INSET = 140.0f;
constexpr float BGE_TRANSLATE_STEP = 12.0f;
constexpr float BGE_RESIZE_STEP = 4.0f;
constexpr float BGE_ROTATE_STEP_DEGREES = 5.0f;
constexpr float BGE_VECTOR_MAGNITUDE_STEP = 20.0f;
constexpr float BGE_MIN_OBJECT_RADIUS = 8.0f;
constexpr float BGE_MAX_OBJECT_RADIUS = 160.0f;
constexpr double BGE_ANIMATION_STEP_MILLISECONDS = 1000.0 / 60.0;
constexpr int BGE_EDIT_RATE_DEFAULT_INDEX = 2;
constexpr std::array<float, 5> BGE_EDIT_RATE_MULTIPLIERS = { 0.25f, 0.5f, 1.0f, 2.0f, 4.0f };
constexpr std::array<const wchar_t*, 5> BGE_EDIT_RATE_LABELS = { L"0.25x", L"0.5x", L"1x", L"2x", L"4x" };
const wchar_t kBgeHistoryWindowClass[] = L"BasicGameEngineHistoryWindow";
const wchar_t kBgeMappingWindowClass[] = L"BasicGameEngineMappingWindow";
enum class BgeEditMode {
Translate,
Resize,
Rotate,
};
enum class BgeKeyboardFocus {
None,
Object,
Group,
Animation,
};
struct BgeObjectGroupState {
std::wstring label;
std::array<BgeObjectSlotState, BGE_OBJECT_SLOT_COUNT> slots{};
int selectedObjectSlot = 0;
bool objectSelectionActive = true;
bool deleteMarked = false;
bool isDeleted = false;
};
struct BgeObjectDeleteSnapshot {
int groupIndex = -1;
int slotIndex = -1;
BgeObjectSlotState slot;
};
struct BgeGroupDeleteSnapshot {
int groupIndex = -1;
bool deleteMarked = false;
bool isDeleted = false;
};
struct BgeDeleteHistoryEntry {
std::wstring label;
int activeGroupIndex = 0;
int selectedObjectSlot = 0;
bool objectSelectionActive = false;
std::vector<BgeObjectDeleteSnapshot> objectSnapshots;
std::vector<BgeGroupDeleteSnapshot> groupSnapshots;
};
struct BgeControllerArtifactSpec {
const wchar_t* group;
const wchar_t* displayName;
const wchar_t* role;
const wchar_t* summary;
bool visualByDefault;
};
const std::array<BgeControllerArtifactSpec, BGE_CONTROLLER_ARTIFACT_COUNT> kControllerArtifacts = {{
{ L"Scene And Render", L"Game Loop", L"bge.game-loop", L"renderer, objects, animation", true },
{ L"Scene And Render", L"Scene 3D", L"bge.scene-3d", L"3D scene surface", false },
{ L"Scene And Render", L"Sample Game One", L"bge.sample-game-one", L"sample game plugin", false },
{ L"Scene And Render", L"Sample Game Two", L"bge.sample-game-two", L"sample game plugin", false },
{ L"Assets", L"Images", L"bge.images", L"backgrounds and image assets", false },
{ L"Audio", L"Sound", L"bge.sound", L"sound slots and playback", false },
}};
enum class BgeRendererApi {
DirectX11,
DirectX12,
};
DWORD g_currentPid = 0;
bool g_isController = false;
bool g_closeBroadcastSent = false;
std::wstring g_workerName = L"worker";
bool g_workerRoleRequested = false;
bool g_launchBasicGameStack = false;
std::wstring g_sessionCliName;
std::vector<std::wstring> g_launchRoles;
std::vector<std::wstring> g_workerCliArgs;
HANDLE g_coordMutex = nullptr;
SharedMemoryData* g_sharedData = nullptr;
DWORD64 g_lastHeartbeatTick = 0;
std::unique_ptr<DirectX11BouncingBallRenderer> g_directX11Renderer;
std::unique_ptr<DirectX12BouncingBallRenderer> g_directX12Renderer;
std::atomic<BgeRendererApi> g_rendererApi = BgeRendererApi::DirectX11;
bool g_ballAdded = false;
bool g_ballAnimationRunning = false;
bool g_rendererStateDirty = false;
bool g_rendererSwitchRequested = false;
bool g_rendererResizeRequested = false;
bool g_backgroundImageDirty = false;
bool g_draggingVectorTip = false;
float g_ballVelocityX = 180.0f;
float g_ballVelocityY = 135.0f;
float g_ballColorR = 0.96f;
float g_ballColorG = 0.34f;
float g_ballColorB = 0.22f;
int g_selectedObjectSlot = 0;
bool g_objectSelectionActive = true;
int g_activeSoundSlot = 0;
DWORD64 g_lastSoundSlotTick = 0;
std::array<BgeObjectSlotState, BGE_OBJECT_SLOT_COUNT> g_objectSlots;
std::vector<BgeObjectGroupState> g_objectGroups;
int g_activeObjectGroupIndex = 0;
int g_ghostObjectGroupIndex = -1;
bool g_ghostOverlayEnabled = false;
BgeKeyboardFocus g_keyboardFocus = BgeKeyboardFocus::None;
int g_mainPlayerGroupIndex = -1;
int g_mainPlayerSlot = -1;
std::vector<BgeDeleteHistoryEntry> g_deleteHistory;
std::wstring g_backgroundImagePath;
HWND g_addBallButton = nullptr;
HWND g_startAnimationButton = nullptr;
HWND g_stopAnimationButton = nullptr;
HWND g_rendererCombo = nullptr;
HWND g_objectGroupCombo = nullptr;
HWND g_addObjectGroupButton = nullptr;
HWND g_ghostGroupCombo = nullptr;
HWND g_toggleGhostButton = nullptr;
HWND g_setPlayerButton = nullptr;
HWND g_playerStatus = nullptr;
HWND g_loadBackgroundButton = nullptr;
HWND g_openMappingButton = nullptr;
HWND g_editModeStatus = nullptr;
HWND g_velocityXEdit = nullptr;
HWND g_velocityYEdit = nullptr;
HWND g_applyVectorButton = nullptr;
HWND g_colorREdit = nullptr;
HWND g_colorGEdit = nullptr;
HWND g_colorBEdit = nullptr;
HWND g_applyColorButton = nullptr;
HWND g_commandEdit = nullptr;
HWND g_runCommandButton = nullptr;
HWND g_commandStatus = nullptr;
WNDPROC g_commandEditOriginalProc = nullptr;
std::array<HWND, BGE_OBJECT_SLOT_COUNT> g_objectSlotButtons{};
std::array<HWND, BGE_OBJECT_SLOT_COUNT> g_soundSlotButtons{};
HWND g_controllerTargetLabel = nullptr;
HWND g_controllerRuntimeStatus = nullptr;
HWND g_controllerHistoryList = nullptr;
HWND g_controllerHistoryDetail = nullptr;
HWND g_controllerHistoryWindow = nullptr;
HWND g_openHistoryButton = nullptr;
HWND g_controllerHistoryListLabel = nullptr;
HWND g_controllerHistoryDetailLabel = nullptr;
HWND g_mappingWindow = nullptr;
HWND g_mappingText = nullptr;
std::array<HWND, BGE_CONTROLLER_ARTIFACT_COUNT> g_controllerTargetButtons{};
std::array<HWND, BGE_CONTROLLER_ARTIFACT_COUNT> g_controllerStatusLabels{};
std::array<HWND, BGE_CONTROLLER_ARTIFACT_COUNT> g_controllerLaunchButtons{};
std::array<HWND, BGE_CONTROLLER_ARTIFACT_COUNT> g_controllerInspectButtons{};
std::array<HWND, BGE_CONTROLLER_ARTIFACT_COUNT> g_controllerHideButtons{};
int g_selectedControllerArtifact = 0;
bool g_hideWorkerWindowsByDefault = true;
std::wstring g_cliControllerTarget;
std::vector<std::wstring> g_cliInspectSelectors;
std::vector<std::wstring> g_cliHideSelectors;
std::vector<std::wstring> g_revealedWorkerRoles;
std::vector<std::wstring> g_pendingControllerCommands;
std::vector<std::wstring> g_controllerHistory;
std::vector<std::wstring> g_controllerHistoryDetails;
BgeEditMode g_editMode = BgeEditMode::Translate;
int g_editRateIndex = BGE_EDIT_RATE_DEFAULT_INDEX;
HWND g_hWnd; // Global handle to the main window
// Interprocess communication manager
InterprocessCommMgr& commMgr = InterprocessCommMgr::GetInstance();
InterprocessComm* comm = nullptr; // Pointer to the shared memory communication
// Function declarations
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK HistoryWndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK MappingWndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
void GameLoop(); // Game loop function
void LoadConfig(); // Pass A: read bge.toml from the exe directory
void ParseRuntimeArgs();
void InitializeObjectSlots();
void InitializeObjectGroups();
bool RegisterCurrentProcess(SharedMemoryData* sharedData);
void UnregisterCurrentProcess();
void UpdateCurrentHeartbeat();
void RequestManagedWorkersClose();
bool EnsureCoordMutex();
bool IsProcessAlive(DWORD pid);
bool ConfirmControllerClose(HWND hWnd);
bool CloseWindowFromEscape(HWND sourceWindow);
bool HandleEscapeKey(HWND sourceWindow);
bool IsEditControl(HWND sourceWindow);
std::wstring LowerArg(std::wstring value);
bool TryParseFloatArg(const std::wstring& text, float& value);
bool CurrentProcessOwnsGameLoop();
bool CurrentProcessOwnsSoundLoop();
bool DirectXRendererActive();
bool AnyObjectSlotVisibleLocked();
int FirstHiddenObjectSlotLocked();
void RefreshSelectedObjectGlobalsLocked();
void SelectObjectSlotStateLocked(int slotIndex);
int ResolveObjectAddTargetLocked(int requestedSlotIndex);
void AddObjectSlotStateLocked(int requestedSlotIndex);
void ApplyObjectVectorStateLocked(float velocityX, float velocityY);
void ApplyObjectColorStateLocked(float colorR, float colorG, float colorB);
void RefreshObjectGroupGlobalsLocked();
void PersistActiveObjectGroupLocked();
bool SelectObjectGroupStateLocked(int groupIndex);
int AddObjectGroupStateLocked(const std::wstring& requestedLabel);
std::wstring ObjectGroupLabel(int groupIndex);
int ResolveObjectGroupIndex(const std::wstring& selector);
void PushDeleteHistoryLocked(const BgeDeleteHistoryEntry& entry);
bool ClearObjectSelectionLocked();
bool ClearObjectSelectionFromRendererClick(int x, int y);
bool ToggleSelectedObjectDeleteMark(std::wstring& statusText);
bool CommitMarkedObjectDeletes(std::wstring& statusText);
bool UndoLastDeleteAction(std::wstring& statusText);
bool HandleEditorShortcutKey(HWND sourceWindow, WPARAM key);
void InitializeSelectedRenderer(HWND hWnd);
void ShutdownActiveRenderer();
void ResizeActiveRenderer();
void TickActiveRenderer(double deltaMilliseconds);
void RenderActiveRenderer();
void ApplyBallStateToRenderer();
void LogRendererMessage(const std::string& message);
void LogRuntimeSceneState();
void LoadBackgroundOnActiveRenderer(const std::wstring& path);
void ProcessPendingRendererCommands();
void AddBallFromControls();
void StartAnimationFromControls();
void StopAnimationFromControls();
void ApplyVectorFromControls();
void ApplyColorFromControls();
void SwitchRendererFromControls();
void LoadBackgroundFromDialog();
void SelectObjectSlotFromControls(int slotIndex);
void SelectObjectGroupFromControls();
void AddObjectGroupFromControls();
void SelectGhostGroupFromControls();
void ToggleGhostGroupFromControls();
void SetMainPlayerFromControls();
void SelectSoundSlotFromControls(int slotIndex);
void AdvanceSoundSlotLoop();
void ExecuteCommandBarInput();
bool ExecuteCommandText(const std::wstring& commandText, std::wstring& statusText);
bool ExecuteControllerCommandText(const std::wstring& commandText, std::wstring& statusText);
bool SendControllerCommandToWorker(const std::wstring& role, const std::wstring& commandText, std::wstring& statusText);
void SetCommandStatus(const std::wstring& statusText);
void AddControllerHistory(const std::wstring& historyText, const std::wstring& detailText = L"");
void UpdateControllerHistoryDetail(const std::wstring& detailText);
void UpdateControllerHistoryDetailFromSelection();
void ShowControllerHistoryWindow();
bool RegisterHistoryWindowClass();
void CreateControllerHistoryWindowControls(HWND hWnd);
void LayoutControllerHistoryWindow(HWND hWnd);
void RefreshControllerHistoryWindow();
void ShowMappingWindow();
bool RegisterMappingWindowClass();
void CreateMappingWindowControls(HWND hWnd);
void LayoutMappingWindow(HWND hWnd);
void RefreshMappingWindow();
std::wstring MappingWindowText();
std::wstring ControllerBaseCli();
std::wstring ControllerCommandDetail(const std::wstring& commandText);
std::wstring WorkerCommandDetail(const std::wstring& role, const std::wstring& commandText);
std::wstring TargetCommandDetail(const BgeControllerArtifactSpec& spec);
std::wstring LaunchCommandDetail(const std::wstring& role);
std::wstring InspectCommandDetail(const std::wstring& role);
std::wstring HideCommandDetail(const std::wstring& role);
std::wstring RoleShortName(const std::wstring& role);
int ArtifactIndexForRole(const std::wstring& role);
LRESULT CALLBACK CommandEditProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
bool HandleWorkerCommandCopyData(COPYDATASTRUCT* copyData);
bool TryStartVectorDrag(int x, int y);
bool TrySelectObjectAtPoint(int x, int y);
void UpdateVectorDrag(int x, int y);
void EndVectorDrag();
int ObjectSlotIndexFromNumberKey(WPARAM key);
bool SelectObjectSlotFromKeyboard(int slotIndex);
bool FocusObjectGroupsFromKeyboard();
bool CycleObjectGroupFromKeyboard(int direction);
bool FocusAnimationFromKeyboard();
bool StartAnimationState(std::wstring& statusText);
bool StopAnimationState(std::wstring& statusText);
bool StepAnimationOneTick(std::wstring& statusText);
bool HandleRendererKeyDown(WPARAM key);
void CycleEditMode(int direction);
bool SetEditModeFromText(const std::wstring& modeText);
std::wstring EditModeName(BgeEditMode mode);
float CurrentEditRateMultiplier();
std::wstring EditRateLabel();
void AdjustEditRate(int direction);
bool SetEditRateFromText(const std::wstring& rateText);
std::wstring TrimText(const std::wstring& value);
void UpdateEditModeStatus();
bool TranslateSelectedObject(float deltaX, float deltaY, std::wstring& statusText);
bool ResizeSelectedObject(float deltaRadius, std::wstring& statusText);
bool RotateSelectedObject(float deltaDegrees, std::wstring& statusText);
bool AdjustSelectedObjectVectorMagnitude(float deltaMagnitude, std::wstring& statusText);
bool ApplySelectedObjectVectorIntent(float deltaDegrees, float deltaMagnitude, const std::wstring& actionName, std::wstring& statusText);
void CreateBallControls(HWND hWnd);
void CreateControllerControls(HWND hWnd);
void LayoutBallControls(HWND hWnd);
void SyncBallControls();
void SyncObjectGroupControls();
void SyncControllerControls();
void SelectControllerArtifact(int artifactIndex, bool recordHistory = true);
void LaunchControllerArtifact(int artifactIndex);
void InspectControllerArtifact(int artifactIndex);
void HideControllerArtifact(int artifactIndex);
void ProcessControllerUiAutomation();
void AddControllerMenu(HWND hWnd);
void UpdateRoleWindowTitle(HWND hWnd);
void BootstrapRoleOpNode();
void LaunchWorkerRole(const std::wstring& role);
void LaunchBasicGameStack();
bool EnsureCoordMutex();
void PruneStaleWorkersLocked(SharedMemoryData* sharedData);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
g_currentPid = GetCurrentProcessId();
InitializeObjectSlots();
LoadConfig(); // Pass A: read bge.toml (toggles diagnostics; defaults preserved if absent)
ParseRuntimeArgs();
InitializeObjectGroups();
// Try to create a new instance mutex
std::wstring mutexName = windowMutexMgr.CreateInstanceMutex();
if (mutexName.empty()) {
// Mutex already exists, another instance is running
MessageBox(NULL, L"Another instance is already running.", L"Basic Game Engine", MB_OK | MB_ICONWARNING);
return 0;
}
// Initialize shared memory using InterprocessCommMgr
comm = commMgr.CreateInterprocessComm(g_bgeSharedMemoryName.c_str(), sizeof(SharedMemoryData));
if (!comm)
{
MessageBox(NULL, L"Could not create or access shared memory.", L"Error", MB_OK | MB_ICONERROR);
return 0;
}
// Update the status bar with the privilege status
std::wstring privilegeStatus = userPrivilegeMgr.GetUserPrivilege().GetPrivilegeStatus();
statusBarMgr.UpdatePrivilegeStatus(privilegeStatus);
// Access the shared data structure
SharedMemoryData* sharedData = comm->GetSharedMemoryPointer();
if (sharedData)
{
//InterlockedIncrement(&sharedData->instanceCount); // Safely increment the instance count
g_sharedData = sharedData;
if (!RegisterCurrentProcess(sharedData)) {
MessageBox(NULL, L"Could not register controller/worker state.", L"Error", MB_OK | MB_ICONERROR);
return 0;
}
}
else
{
MessageBox(NULL, L"Could not access shared memory.", L"Error", MB_OK | MB_ICONERROR);
return 0; // Handle the error appropriately
}
// Initialize global strings, register class, etc.
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_BASICGAMEENGINE, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
if (!InitInstance(hInstance, nCmdShow))
{
return FALSE;
}
AddControllerMenu(g_hWnd);
UpdateRoleWindowTitle(g_hWnd);
CreateBallControls(g_hWnd);
SyncBallControls();
BootstrapRoleOpNode();
InitializeSelectedRenderer(g_hWnd);
LogRuntimeSceneState();
if (g_isController) {
if (g_launchBasicGameStack) {
LaunchBasicGameStack();
}
for (const auto& role : g_launchRoles) {
LaunchWorkerRole(role);
}
}
// Update the instance count in the status bar
if (sharedData) {
statusBarMgr.UpdateInstanceCount(sharedData->instanceCount); // Update status bar with instance count
}
// Start the per-process runtime loop. Only the bge.game-loop worker runs
// frame/update work; other processes keep their shared-memory heartbeat.
gameThread = std::thread(GameLoop);
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_BASICGAMEENGINE));
MSG msg;
while (GetMessage(&msg, nullptr, 0, 0))
{
if (msg.message == WM_KEYDOWN && msg.wParam == VK_ESCAPE && HandleEscapeKey(msg.hwnd)) {
continue;
}
if (msg.message == WM_KEYDOWN && HandleEditorShortcutKey(msg.hwnd, msg.wParam)) {
continue;
}
if (msg.message == WM_KEYDOWN && !IsEditControl(msg.hwnd) && HandleRendererKeyDown(msg.wParam)) {
continue;
}
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
// Clean up when exiting
if (g_isController && !g_closeBroadcastSent) {
RequestManagedWorkersClose();
}
shouldRun = false; // Signal the thread to stop
if (gameThread.joinable())
{
gameThread.join(); // Wait for the game thread to finish
}
ShutdownActiveRenderer();
UnregisterCurrentProcess();
windowMutexMgr.ReleaseInstanceMutex(mutexName); // Release the unique mutex
commMgr.ReleaseInterprocessComm(g_bgeSharedMemoryName.c_str());
if (g_coordMutex) {
CloseHandle(g_coordMutex);
g_coordMutex = nullptr;
}
return (int)msg.wParam;
}
// Pass A: minimal TOML-shaped config reader. Looks for `bge.toml` next to
// the running exe and pulls out a handful of `key = value` lines. Ignores
// sections and unknown keys. Pass B will swap this for toml++ when the
// schema grows (operation tree, factory, etc.).
void LoadConfig()
{
wchar_t exePath[MAX_PATH];
if (GetModuleFileNameW(NULL, exePath, MAX_PATH) == 0) return;
std::wstring dir(exePath);
size_t slash = dir.find_last_of(L"\\/");
if (slash == std::wstring::npos) return;
std::wstring path = dir.substr(0, slash + 1) + L"bge.toml";
std::ifstream file(path);
if (!file) return; // no config — keep defaults
auto trim = [](std::string& s) {
s.erase(0, s.find_first_not_of(" \t\r"));
if (!s.empty()) s.erase(s.find_last_not_of(" \t\r") + 1);
};
std::string line;
while (std::getline(file, line)) {
auto hash = line.find('#');
if (hash != std::string::npos) line = line.substr(0, hash);
auto eq = line.find('=');
if (eq == std::string::npos) continue;
std::string key = line.substr(0, eq);
std::string val = line.substr(eq + 1);
trim(key);
trim(val);
// Strip surrounding double quotes from string values.
if (val.size() >= 2 && val.front() == '"' && val.back() == '"') {
val = val.substr(1, val.size() - 2);
}
if (key == "show_mutex_line") {
g_showMutexLine = (val == "true" || val == "1");
}
else if (key == "background_image") {
g_backgroundImagePath = std::wstring(val.begin(), val.end());
g_backgroundImageDirty = true;
}
}
}
void ResetObjectSlotArray(std::array<BgeObjectSlotState, BGE_OBJECT_SLOT_COUNT>& slots, int groupIndex)
{
const float colors[BGE_OBJECT_SLOT_COUNT][3] = {
{ 0.96f, 0.34f, 0.22f },
{ 0.20f, 0.72f, 0.95f },
{ 0.34f, 0.82f, 0.40f },
{ 0.95f, 0.78f, 0.22f },
{ 0.68f, 0.44f, 0.94f },
{ 0.95f, 0.42f, 0.72f },
{ 0.35f, 0.86f, 0.72f },
{ 0.92f, 0.50f, 0.20f },
{ 0.75f, 0.75f, 0.78f },
{ 0.55f, 0.82f, 0.24f },
};
for (int index = 0; index < BGE_OBJECT_SLOT_COUNT; ++index) {
BgeObjectSlotState& slot = slots[index];
slot.visible = false;
slot.deleteMarked = false;
slot.isDeleted = false;
slot.x = 180.0f + static_cast<float>(index) * 24.0f + static_cast<float>(groupIndex) * 16.0f;
slot.y = 180.0f + static_cast<float>(index) * 10.0f + static_cast<float>(groupIndex % 4) * 18.0f;
slot.velocityX = 150.0f + static_cast<float>(index) * 20.0f;
slot.velocityY = (index % 2 == 0 ? 110.0f : -130.0f) + static_cast<float>(index) * 8.0f;
slot.radius = 28.0f + static_cast<float>(index % 3) * 3.0f;
slot.colorR = colors[index][0];
slot.colorG = colors[index][1];
slot.colorB = colors[index][2];
}
}
void InitializeObjectSlots()
{
ResetObjectSlotArray(g_objectSlots, 0);
g_selectedObjectSlot = 0;
g_objectSelectionActive = true;
g_ballVelocityX = g_objectSlots[0].velocityX;
g_ballVelocityY = g_objectSlots[0].velocityY;
g_ballColorR = g_objectSlots[0].colorR;
g_ballColorG = g_objectSlots[0].colorG;
g_ballColorB = g_objectSlots[0].colorB;
}
void InitializeObjectGroups()
{
BgeObjectGroupState firstGroup;
firstGroup.label = L"Group 1";
firstGroup.slots = g_objectSlots;
firstGroup.selectedObjectSlot = g_selectedObjectSlot;
firstGroup.objectSelectionActive = g_objectSelectionActive;
g_objectGroups.clear();
g_objectGroups.push_back(firstGroup);
g_activeObjectGroupIndex = 0;
g_ghostObjectGroupIndex = -1;
g_ghostOverlayEnabled = false;
g_mainPlayerGroupIndex = -1;
g_mainPlayerSlot = -1;
g_deleteHistory.clear();
}
std::wstring ObjectGroupLabel(int groupIndex)
{
if (groupIndex < 0 || groupIndex >= static_cast<int>(g_objectGroups.size())) {
return L"";
}
return g_objectGroups[static_cast<size_t>(groupIndex)].label;
}
void RefreshObjectGroupGlobalsLocked()
{
if (g_objectGroups.empty()) {
return;
}
g_activeObjectGroupIndex = (std::max)(0, (std::min)(g_activeObjectGroupIndex, static_cast<int>(g_objectGroups.size()) - 1));
BgeObjectGroupState& activeGroup = g_objectGroups[static_cast<size_t>(g_activeObjectGroupIndex)];
activeGroup.selectedObjectSlot = (std::max)(0, (std::min)(activeGroup.selectedObjectSlot, BGE_OBJECT_SLOT_COUNT - 1));
g_objectSlots = activeGroup.slots;
g_selectedObjectSlot = activeGroup.selectedObjectSlot;
g_objectSelectionActive = activeGroup.objectSelectionActive;
RefreshSelectedObjectGlobalsLocked();
g_rendererStateDirty = true;
}
void PersistActiveObjectGroupLocked()
{
if (g_objectGroups.empty() || g_activeObjectGroupIndex < 0 || g_activeObjectGroupIndex >= static_cast<int>(g_objectGroups.size())) {
return;
}
BgeObjectGroupState& activeGroup = g_objectGroups[static_cast<size_t>(g_activeObjectGroupIndex)];
activeGroup.slots = g_objectSlots;
activeGroup.selectedObjectSlot = g_selectedObjectSlot;
activeGroup.objectSelectionActive = g_objectSelectionActive;
}
bool SelectObjectGroupStateLocked(int groupIndex)
{
if (groupIndex < 0 || groupIndex >= static_cast<int>(g_objectGroups.size())) {
return false;
}
PersistActiveObjectGroupLocked();
g_activeObjectGroupIndex = groupIndex;
RefreshObjectGroupGlobalsLocked();
g_keyboardFocus = BgeKeyboardFocus::Group;
return true;
}
int AddObjectGroupStateLocked(const std::wstring& requestedLabel)
{
PersistActiveObjectGroupLocked();
int groupIndex = static_cast<int>(g_objectGroups.size());
std::wstring label = TrimText(requestedLabel);
if (label.empty()) {
label = L"Group " + std::to_wstring(groupIndex + 1);
}
std::wstring baseLabel = label;
int suffix = 2;
bool labelExists = true;
while (labelExists) {
labelExists = false;
for (const auto& group : g_objectGroups) {
if (LowerArg(group.label) == LowerArg(label)) {
labelExists = true;
label = baseLabel + L" " + std::to_wstring(suffix++);
break;
}
}
}
BgeObjectGroupState newGroup;
newGroup.label = label;
ResetObjectSlotArray(newGroup.slots, groupIndex);
newGroup.selectedObjectSlot = 0;
newGroup.objectSelectionActive = true;
g_objectGroups.push_back(newGroup);
g_activeObjectGroupIndex = groupIndex;
RefreshObjectGroupGlobalsLocked();
g_keyboardFocus = BgeKeyboardFocus::Group;
return groupIndex;
}
int ResolveObjectGroupIndex(const std::wstring& selector)
{
std::wstring cleanSelector = TrimText(selector);
if (cleanSelector.empty()) {
return g_activeObjectGroupIndex;
}
float numericValue = 0.0f;
if (TryParseFloatArg(cleanSelector, numericValue)) {
int oneBasedGroup = static_cast<int>(numericValue);
if (oneBasedGroup >= 1 && oneBasedGroup <= static_cast<int>(g_objectGroups.size())) {
return oneBasedGroup - 1;
}
}
std::wstring selectorLower = LowerArg(cleanSelector);
for (int groupIndex = 0; groupIndex < static_cast<int>(g_objectGroups.size()); ++groupIndex) {
if (LowerArg(g_objectGroups[static_cast<size_t>(groupIndex)].label) == selectorLower) {
return groupIndex;
}
}
return -1;
}
void PushDeleteHistoryLocked(const BgeDeleteHistoryEntry& entry)
{
if (entry.objectSnapshots.empty() && entry.groupSnapshots.empty()) {
return;
}
g_deleteHistory.push_back(entry);
if (g_deleteHistory.size() > BGE_DELETE_HISTORY_LIMIT) {
g_deleteHistory.erase(g_deleteHistory.begin());
}
}
BgeDeleteHistoryEntry MakeDeleteHistoryEntryLocked(const std::wstring& label)
{
BgeDeleteHistoryEntry entry;
entry.label = label;
entry.activeGroupIndex = g_activeObjectGroupIndex;
entry.selectedObjectSlot = g_selectedObjectSlot;
entry.objectSelectionActive = g_objectSelectionActive;
return entry;
}
void AddObjectDeleteSnapshotLocked(BgeDeleteHistoryEntry& entry, int groupIndex, int slotIndex)
{
if (groupIndex < 0 || groupIndex >= static_cast<int>(g_objectGroups.size()) || slotIndex < 0 || slotIndex >= BGE_OBJECT_SLOT_COUNT) {
return;
}
PersistActiveObjectGroupLocked();
BgeObjectDeleteSnapshot snapshot;
snapshot.groupIndex = groupIndex;
snapshot.slotIndex = slotIndex;
snapshot.slot = g_objectGroups[static_cast<size_t>(groupIndex)].slots[slotIndex];
entry.objectSnapshots.push_back(snapshot);
}
bool ClearObjectSelectionLocked()
{
if (!g_objectSelectionActive) {
return false;
}
g_objectSelectionActive = false;
g_keyboardFocus = BgeKeyboardFocus::None;
PersistActiveObjectGroupLocked();
g_rendererStateDirty = true;
return true;
}
bool ClearObjectSelectionFromRendererClick(int x, int y)
{
UNREFERENCED_PARAMETER(x);
if (!CurrentProcessOwnsGameLoop() || y < static_cast<int>(BGE_RENDER_TOP_INSET)) {
return false;
}
bool cleared = false;
{
std::lock_guard<std::mutex> lock(ballConfigMutex);
if (g_ballAnimationRunning) {
return false;
}
cleared = ClearObjectSelectionLocked();
}
if (cleared) {
SyncBallControls();
SetCommandStatus(L"Object selection cleared; Delete commits marked objects");
}
return cleared;
}
bool ToggleSelectedObjectDeleteMark(std::wstring& statusText)
{
if (!CurrentProcessOwnsGameLoop()) {
statusText = L"Delete commands run in bge.game-loop";
return false;
}
int selectedSlot = 0;
bool marked = false;
{
std::lock_guard<std::mutex> lock(ballConfigMutex);
if (g_ballAnimationRunning) {
statusText = L"Stop animation before marking deletes";
return false;
}
if (!g_objectSelectionActive) {
statusText = L"No object selected; Delete commits marked objects";
return false;
}
BgeObjectSlotState& slot = g_objectSlots[g_selectedObjectSlot];
if (!slot.visible || slot.isDeleted) {
statusText = L"Select a visible object";
return false;
}
BgeDeleteHistoryEntry entry = MakeDeleteHistoryEntryLocked(slot.deleteMarked ? L"unmark object delete" : L"mark object delete");
AddObjectDeleteSnapshotLocked(entry, g_activeObjectGroupIndex, g_selectedObjectSlot);
PushDeleteHistoryLocked(entry);
slot.deleteMarked = !slot.deleteMarked;
selectedSlot = g_selectedObjectSlot;
marked = slot.deleteMarked;
g_rendererStateDirty = true;
PersistActiveObjectGroupLocked();
}
SyncBallControls();
statusText = std::wstring(marked ? L"Marked object " : L"Unmarked object ") + std::to_wstring(selectedSlot + 1) + L" for delete";
return true;
}
bool CommitMarkedObjectDeletes(std::wstring& statusText)
{
if (!CurrentProcessOwnsGameLoop()) {
statusText = L"Delete commands run in bge.game-loop";
return false;
}
int deletedCount = 0;
{
std::lock_guard<std::mutex> lock(ballConfigMutex);
if (g_ballAnimationRunning) {
statusText = L"Stop animation before deleting objects";
return false;
}
BgeDeleteHistoryEntry entry = MakeDeleteHistoryEntryLocked(L"commit object deletes");
for (int slotIndex = 0; slotIndex < BGE_OBJECT_SLOT_COUNT; ++slotIndex) {
const BgeObjectSlotState& slot = g_objectSlots[slotIndex];
if (slot.visible && !slot.isDeleted && slot.deleteMarked) {
AddObjectDeleteSnapshotLocked(entry, g_activeObjectGroupIndex, slotIndex);
}
}
if (entry.objectSnapshots.empty()) {
statusText = L"No delete-marked objects";
return false;
}
PushDeleteHistoryLocked(entry);
for (const auto& snapshot : entry.objectSnapshots) {
BgeObjectSlotState& slot = g_objectSlots[snapshot.slotIndex];
slot.deleteMarked = false;
slot.isDeleted = true;
slot.visible = false;
++deletedCount;
if (g_mainPlayerGroupIndex == g_activeObjectGroupIndex && g_mainPlayerSlot == snapshot.slotIndex) {
g_mainPlayerGroupIndex = -1;
g_mainPlayerSlot = -1;
}
}
ClearObjectSelectionLocked();
RefreshSelectedObjectGlobalsLocked();
g_rendererStateDirty = true;
PersistActiveObjectGroupLocked();
}
SyncBallControls();
statusText = L"Deleted " + std::to_wstring(deletedCount) + L" marked object" + (deletedCount == 1 ? L"" : L"s");
return true;
}
bool UndoLastDeleteAction(std::wstring& statusText)
{
if (!CurrentProcessOwnsGameLoop()) {
statusText = L"Undo commands run in bge.game-loop";
return false;
}
std::wstring actionLabel;
{
std::lock_guard<std::mutex> lock(ballConfigMutex);
if (g_deleteHistory.empty()) {
statusText = L"Nothing to undo";
return false;
}
PersistActiveObjectGroupLocked();
BgeDeleteHistoryEntry entry = g_deleteHistory.back();
g_deleteHistory.pop_back();
actionLabel = entry.label;
for (const auto& snapshot : entry.objectSnapshots) {
if (snapshot.groupIndex < 0 || snapshot.groupIndex >= static_cast<int>(g_objectGroups.size()) || snapshot.slotIndex < 0 || snapshot.slotIndex >= BGE_OBJECT_SLOT_COUNT) {
continue;
}
g_objectGroups[static_cast<size_t>(snapshot.groupIndex)].slots[snapshot.slotIndex] = snapshot.slot;
}
for (const auto& snapshot : entry.groupSnapshots) {
if (snapshot.groupIndex < 0 || snapshot.groupIndex >= static_cast<int>(g_objectGroups.size())) {
continue;
}
BgeObjectGroupState& group = g_objectGroups[static_cast<size_t>(snapshot.groupIndex)];
group.deleteMarked = snapshot.deleteMarked;
group.isDeleted = snapshot.isDeleted;
}
if (entry.activeGroupIndex >= 0 && entry.activeGroupIndex < static_cast<int>(g_objectGroups.size())) {
g_activeObjectGroupIndex = entry.activeGroupIndex;
}
RefreshObjectGroupGlobalsLocked();
g_selectedObjectSlot = (std::max)(0, (std::min)(entry.selectedObjectSlot, BGE_OBJECT_SLOT_COUNT - 1));
g_objectSelectionActive = entry.objectSelectionActive;