-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathStateNode.cs
More file actions
333 lines (279 loc) · 9.65 KB
/
Copy pathStateNode.cs
File metadata and controls
333 lines (279 loc) · 9.65 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
// Copyright © Gamesmiths Guild.
using Gamesmiths.Forge.Core;
using Gamesmiths.Forge.Statescript.Ports;
namespace Gamesmiths.Forge.Statescript.Nodes;
/// <summary>
/// Node representing a state in the graph. It has input ports for activation and abortion, output ports for activation,
/// deactivation, and abortion events, as well as a subgraph output port.
/// </summary>
/// <typeparam name="T">The type of the state node context.</typeparam>
public abstract class StateNode<T> : Node
where T : StateNodeContext, new()
{
/// <summary>
/// Port index for the input port.
/// </summary>
#pragma warning disable RCS1158 // Static member in generic type should use a type parameter
public const byte InputPort = 0;
/// <summary>
/// Port index for the abort port.
/// </summary>
public const byte AbortPort = 1;
/// <summary>
/// Port index for the on activate port.
/// </summary>
public const byte OnActivatePort = 0;
/// <summary>
/// Port index for the on deactivate port.
/// </summary>
public const byte OnDeactivatePort = 1;
/// <summary>
/// Port index for the on abort port.
/// </summary>
public const byte OnAbortPort = 2;
/// <summary>
/// Port index for the subgraph port.
/// </summary>
public const byte SubgraphPort = 3;
#pragma warning restore RCS1158 // Static member in generic type should use a type parameter
/// <summary>
/// Called when the node is activated.
/// </summary>
/// <param name="graphContext">The graph's context.</param>
protected abstract void OnActivate(GraphContext graphContext);
/// <summary>
/// Called when the node is deactivated.
/// </summary>
/// <param name="graphContext">The graph's context.</param>
protected abstract void OnDeactivate(GraphContext graphContext);
/// <inheritdoc/>
public override string Description => $"A {GetType().Name.Replace("Node", string.Empty)} state node.";
/// <summary>
/// Updates this state node with the given delta time. Only processes the update if the node is currently active.
/// </summary>
/// <param name="deltaTime">The time elapsed since the last update, in seconds.</param>
/// <param name="graphContext">The graph's context.</param>
#pragma warning disable SA1202 // Elements should be ordered by access
internal override void Update(double deltaTime, GraphContext graphContext)
#pragma warning restore SA1202 // Elements should be ordered by access
{
if (!graphContext.HasNodeContext(NodeID))
{
return;
}
StateNodeContext nodeContext = graphContext.GetNodeContext<StateNodeContext>(NodeID);
if (!nodeContext.Active)
{
return;
}
OnUpdate(deltaTime, graphContext);
}
/// <inheritdoc/>
internal override IEnumerable<int> GetReachableOutputPorts(byte inputPortIndex)
{
if (inputPortIndex == InputPort)
{
// InputPort fires OnActivatePort and SubgraphPort directly, and may fire OnDeactivatePort and custom
// EventPorts via deferred deactivation.
yield return OnActivatePort;
yield return OnDeactivatePort;
yield return SubgraphPort;
for (int i = SubgraphPort + 1; i < OutputPorts.Length; i++)
{
yield return i;
}
}
else if (inputPortIndex == AbortPort)
{
// AbortPort fires OnAbortPort directly, then DeactivateNode fires OnDeactivatePort and all SubgraphPorts
// via BeforeDisable.
yield return OnDeactivatePort;
yield return OnAbortPort;
for (int i = 0; i < SubgraphPorts.Length; i++)
{
yield return SubgraphPorts[i].Index;
}
}
}
/// <inheritdoc/>
internal override IEnumerable<int> GetMessagePortsOnDisable()
{
// BeforeDisable fires OnDeactivatePort.EmitMessage() as a regular message.
yield return OnDeactivatePort;
}
/// <summary>
/// Called every update tick while the node is active. Override this method to implement per-frame or per-tick logic
/// such as timers, animations, or continuous state evaluation.
/// </summary>
/// <param name="deltaTime">The time elapsed since the last update, in seconds.</param>
/// <param name="graphContext">The graph's context.</param>
protected virtual void OnUpdate(double deltaTime, GraphContext graphContext)
{
}
/// <inheritdoc/>
protected override void DefinePorts(List<InputPort> inputPorts, List<OutputPort> outputPorts)
{
inputPorts.Add(CreatePort<InputPort>(InputPort, "Input"));
inputPorts.Add(CreatePort<InputPort>(AbortPort, "Abort"));
outputPorts.Add(CreatePort<EventPort>(OnActivatePort, "OnActivate"));
outputPorts.Add(CreatePort<EventPort>(OnDeactivatePort, "OnDeactivate"));
outputPorts.Add(CreatePort<EventPort>(OnAbortPort, "OnAbort"));
outputPorts.Add(CreatePort<SubgraphPort>(SubgraphPort, "Subgraph"));
}
/// <inheritdoc/>
protected sealed override void HandleMessage(InputPort receiverPort, GraphContext graphContext)
{
if (receiverPort.Index == InputPort)
{
var nodeContext = (StateNodeContext)graphContext.GetOrCreateNodeContext<T>(NodeID);
nodeContext.Activating = true;
ActivateNode(graphContext);
OutputPorts[OnActivatePort].EmitMessage(graphContext);
OutputPorts[SubgraphPort].EmitMessage(graphContext);
nodeContext.Activating = false;
HandleDeferredEmitMessages(graphContext, nodeContext);
HandleDeferredDeactivationMessages(graphContext, nodeContext);
}
else if (receiverPort.Index == AbortPort)
{
OutputPorts[OnAbortPort].EmitMessage(graphContext);
DeactivateNode(graphContext);
}
}
/// <inheritdoc/>
protected override void EmitMessage(GraphContext graphContext, params int[] portIds)
{
StateNodeContext nodeContext = graphContext.GetNodeContext<StateNodeContext>(NodeID);
if (nodeContext.Activating)
{
nodeContext.DeferredEmitMessageData.AddRange(portIds);
return;
}
base.EmitMessage(graphContext, portIds);
}
/// <summary>
/// Deactivates the node and emits messages through the specified event ports.
/// </summary>
/// <remarks>
/// <para>If the node is currently in the process of activating, the deactivation and message emissions will be
/// deferred until activation is complete. This prevents race conditions during the activation process.</para>
/// <para>Use this method because it guarantees that the messages are fired in the right order.</para>
/// <para>OutputPort[OnDeactivatePort] (OnDeactivate) will always be called upon node deactivation and should not be
/// used here.</para>
/// </remarks>
/// <param name="graphContext">The graph's context.</param>
/// <param name="eventPortIds">ID of ports you want to Emit a message to.</param>
protected void DeactivateNodeAndEmitMessage(GraphContext graphContext, params int[] eventPortIds)
{
StateNodeContext nodeContext = graphContext.GetNodeContext<StateNodeContext>(NodeID);
if (nodeContext.Activating)
{
nodeContext.DeferredDeactivationEventPortIds = eventPortIds;
return;
}
graphContext.FinalizationDeferralCount++;
try
{
DeactivateNode(graphContext);
for (int i = 0; i < eventPortIds.Length; i++)
{
Validation.Assert(
eventPortIds[i] > OnAbortPort,
"DeactivateNodeAndEmitMessage should be used only with custom ports.");
Validation.Assert(
OutputPorts[eventPortIds[i]] is EventPort,
"Only EventPorts can be used for deactivation events.");
OutputPorts[eventPortIds[i]].EmitMessage(graphContext);
}
}
finally
{
graphContext.FinalizationDeferralCount--;
}
if (graphContext.HasStarted
&& graphContext.FinalizationDeferralCount == 0
&& graphContext.ActiveStateNodes.Count == 0)
{
graphContext.Processor?.FinalizeGraph();
}
}
/// <summary>
/// Deactivates the node without emitting any custom messages.
/// </summary>
/// <param name="graphContext">The graph's context.</param>
protected void DeactivateNode(GraphContext graphContext)
{
BeforeDisable(graphContext);
foreach (SubgraphPort subgraphPort in SubgraphPorts)
{
subgraphPort.EmitDisableSubgraphMessage(graphContext);
}
AfterDisable(graphContext);
}
/// <inheritdoc/>
protected sealed override void BeforeDisable(GraphContext graphContext)
{
if (!graphContext.HasNodeContext(NodeID))
{
return;
}
StateNodeContext nodeContext = graphContext.GetNodeContext<StateNodeContext>(NodeID);
if (!nodeContext.Active)
{
return;
}
nodeContext.Active = false;
base.BeforeDisable(graphContext);
OutputPorts[OnDeactivatePort].EmitMessage(graphContext);
}
/// <inheritdoc/>
protected sealed override void AfterDisable(GraphContext graphContext)
{
if (!graphContext.HasNodeContext(NodeID))
{
return;
}
StateNodeContext nodeContext = graphContext.GetNodeContext<StateNodeContext>(NodeID);
if (nodeContext.Active)
{
return;
}
if (!graphContext.ActiveStateNodes.Remove(this))
{
return;
}
base.AfterDisable(graphContext);
OnDeactivate(graphContext);
if (graphContext.FinalizationDeferralCount == 0
&& graphContext.ActiveStateNodes.Count == 0)
{
graphContext.Processor?.FinalizeGraph();
}
}
private void ActivateNode(GraphContext graphContext)
{
StateNodeContext nodeContext = graphContext.GetNodeContext<StateNodeContext>(NodeID);
nodeContext.Active = true;
graphContext.ActiveStateNodes.Add(this);
OnActivate(graphContext);
}
private void HandleDeferredEmitMessages(GraphContext graphContext, StateNodeContext nodeContext)
{
if (nodeContext.DeferredEmitMessageData.Count > 0)
{
foreach (int emitEvent in nodeContext.DeferredEmitMessageData)
{
OutputPorts[emitEvent].EmitMessage(graphContext);
}
nodeContext.DeferredEmitMessageData.Clear();
}
}
private void HandleDeferredDeactivationMessages(GraphContext graphContext, StateNodeContext nodeContext)
{
if (nodeContext.DeferredDeactivationEventPortIds is not null)
{
DeactivateNodeAndEmitMessage(graphContext, nodeContext.DeferredDeactivationEventPortIds);
nodeContext.DeferredDeactivationEventPortIds = null;
}
}
}