-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathVisualScriptingGamelogicEngine.cs
255 lines (209 loc) · 8.6 KB
/
VisualScriptingGamelogicEngine.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
// Visual Pinball Engine
// Copyright (C) 2022 freezy and VPE Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
// ReSharper disable InconsistentNaming
using System;
using System.Collections.Generic;
using System.Linq;
using Unity.VisualScripting;
using UnityEngine;
using VisualPinball.Engine.Game.Engines;
using System.Threading.Tasks;
using System.Threading;
namespace VisualPinball.Unity.VisualScripting
{
[DisallowMultipleComponent]
[AddComponentMenu("Pinball/Gamelogic Engine/Visual Scripting Game Logic")]
public class VisualScriptingGamelogicEngine : MonoBehaviour, IGamelogicEngine, ISerializationCallbackReceiver
{
public string Name => "Visual Scripting Gamelogic Engine";
[Tooltip("Define here the global variables of the Visual Scripting engine.")]
public List<TableVariableDefinition> TableVariableDefinitions;
[Tooltip("Define here the player-specific variables of the Visual Scripting engine.")]
public List<PlayerVariableDefinition> PlayerVariableDefinitions;
[Tooltip("Declare your custom events here for easy access with our event nodes.")]
public List<EventDefinition> EventDefinitions;
[Tooltip("Define the displays this game is going to use.")]
public DisplayDefinition[] Displays;
[Tooltip("The switches that are exposed in the Visual Scripting nodes.")]
public VisualScriptingSwitch[] Switches;
[Tooltip("The coils that are exposed in the Visual Scripting nodes.")]
public VisualScriptingCoil[] Coils;
[Tooltip("The lamps that are exposed in the Visual Scripting nodes.")]
public VisualScriptingLamp[] Lamps;
public GamelogicEngineWire[] Wires;
public DisplayConfig[] RequiredDisplays => Displays.Select(d => d.DisplayConfig).ToArray();
public GamelogicEngineSwitch[] RequestedSwitches => Switches.Select(sw => sw as GamelogicEngineSwitch).ToArray();
public GamelogicEngineLamp[] RequestedLamps => Lamps.Select(lamp => lamp as GamelogicEngineLamp).ToArray();
public GamelogicEngineCoil[] RequestedCoils => Coils.Select(c => c as GamelogicEngineCoil).ToArray();
public GamelogicEngineWire[] AvailableWires => Wires;
public event EventHandler<RequestedDisplays> OnDisplaysRequested;
public event EventHandler<string> OnDisplayClear;
public event EventHandler<DisplayFrameData> OnDisplayUpdateFrame;
public event EventHandler<DisplayFrameData> OnDisplayUpdated;
public event EventHandler<LampEventArgs> OnLampChanged;
public event EventHandler<LampsEventArgs> OnLampsChanged;
public event EventHandler<CoilEventArgs> OnCoilChanged;
public event EventHandler<SwitchEventArgs2> OnSwitchChanged;
public event EventHandler<EventArgs> OnStarted;
[NonSerialized] public BallManager BallManager;
[NonSerialized] private Player _player;
[NonSerialized] private int _currentPlayer;
[NonSerialized] public readonly TableState TableState = new ();
[NonSerialized] public readonly Dictionary<int, PlayerState> PlayerStates = new ();
public PlayerState CurrentPlayerState {
get {
if (!PlayerStates.ContainsKey(_currentPlayer)) {
throw new InvalidOperationException("Must create a player state before accessing it!");
}
return PlayerStates[_currentPlayer];
}
}
public void SetCurrentPlayer(int value, bool forceNotify = false)
{
if (!PlayerStates.ContainsKey(value)) {
Debug.LogError($"Cannot change to non-existing player {value}.");
return;
}
var previousPlayer = _currentPlayer;
_currentPlayer = value;
if (forceNotify || previousPlayer != _currentPlayer) {
EventBus.Trigger(VisualScriptingEventNames.CurrentPlayerChanged, EventArgs.Empty);
}
// also trigger updates for each variable
foreach (var varDef in PlayerVariableDefinitions) {
var before = PlayerStates[previousPlayer].GetVariable(varDef.Id);
var now = PlayerStates[_currentPlayer].GetVariable(varDef.Id);
if (PlayerStates.ContainsKey(previousPlayer)) {
if (forceNotify || before != now) {
EventBus.Trigger(VisualScriptingEventNames.PlayerVariableChanged, new VariableChangedArgs(varDef.Id, before.Get<object>(), now.Get<object>()));
}
} else {
EventBus.Trigger(VisualScriptingEventNames.PlayerVariableChanged, new VariableChangedArgs(varDef.Id, before.Get<object>(), now.Get<object>()));
}
}
}
public void CreatePlayerState(int playerId)
{
if (PlayerStates.ContainsKey(playerId)) {
Debug.LogWarning($"Tried to create new player state for existing state {playerId}, skipping.");
return;
}
var playerState = new PlayerState(playerId);
foreach (var propertyDefinition in PlayerVariableDefinitions) {
playerState.AddProperty(propertyDefinition.Instantiate());
}
PlayerStates[playerId] = playerState;
// switch to this state if current state is invalid
if (!PlayerStates.ContainsKey(_currentPlayer)) {
SetCurrentPlayer(playerId, true);
}
}
public void DestroyPlayerStates()
{
PlayerStates.Clear();
_currentPlayer = 0;
}
public Task OnInit(Player player, TableApi tableApi, BallManager ballManager, CancellationToken ct)
{
_player = player;
BallManager = ballManager;
// request displays
OnDisplaysRequested?.Invoke(this, new RequestedDisplays(Displays.Select(d => d.DisplayConfig).ToArray()));
// create table variables
foreach (var propertyDefinition in TableVariableDefinitions) {
TableState.AddProperty(propertyDefinition.Instantiate());
}
OnStarted?.Invoke(this, EventArgs.Empty);
EventBus.Trigger(VisualScriptingEventNames.GleStartedEvent, EventArgs.Empty);
return Task.CompletedTask;
}
public void DisplayClear(string id)
{
OnDisplayClear?.Invoke(this, id);
}
public void DisplayUpdateFrame(DisplayFrameData data)
{
OnDisplayUpdateFrame?.Invoke(this, data);
}
public void Switch(string id, bool isClosed)
{
var args = new SwitchEventArgs2(id, isClosed);
OnSwitchChanged?.Invoke(this, args);
EventBus.Trigger(VisualScriptingEventNames.SwitchEvent, args);
}
public void SetCoil(string id, bool isEnabled)
{
OnCoilChanged?.Invoke(this, new CoilEventArgs(id, isEnabled));
}
public void SetLamp(string id, float value, bool isCoil = false, LampSource source = LampSource.Lamp)
{
OnLampChanged?.Invoke(this, new LampEventArgs(id, value, isCoil, source));
}
public void DisplayChanged(DisplayFrameData data)
{
EventBus.Trigger(VisualScriptingEventNames.DisplayChangedEvent, new DisplayChangedEventArgs(data));
}
public LampState GetLamp(string id)
{
return _player.LampStatuses.ContainsKey(id) ? _player.LampStatuses[id] : LampState.Default;
}
public bool GetSwitch(string id)
{
return _player.SwitchStatuses.ContainsKey(id) && _player.SwitchStatuses[id].IsSwitchEnabled;
}
public bool GetCoil(string id)
{
return _player.CoilStatuses.ContainsKey(id) && _player.CoilStatuses[id];
}
public void OnBeforeSerialize()
{
#if UNITY_EDITOR
TableVariableDefinitions ??= new List<TableVariableDefinition>();
PlayerVariableDefinitions ??= new List<PlayerVariableDefinition>();
EventDefinitions ??= new List<EventDefinition>();
Displays ??= Array.Empty<DisplayDefinition>();
Switches ??= Array.Empty<VisualScriptingSwitch>();
Coils ??= Array.Empty<VisualScriptingCoil>();
Lamps ??= Array.Empty<VisualScriptingLamp>();
Wires ??= Array.Empty<GamelogicEngineWire>();
var ids = new HashSet<string>();
foreach (var def in PlayerVariableDefinitions) {
if (!def.HasId || ids.Contains(def.Id)) {
def.GenerateId();
}
ids.Add(def.Id);
}
ids.Clear();
foreach (var def in TableVariableDefinitions) {
if (!def.HasId || ids.Contains(def.Id)) {
def.GenerateId();
}
ids.Add(def.Id);
}
ids.Clear();
foreach (var def in EventDefinitions) {
if (!def.HasId || ids.Contains(def.Id)) {
def.GenerateId();
}
ids.Add(def.Id);
}
#endif
}
public void OnAfterDeserialize()
{
}
}
}