-
Notifications
You must be signed in to change notification settings - Fork 53
/
OperatorPart.cs
766 lines (645 loc) · 25.8 KB
/
OperatorPart.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
// Copyright (c) 2016 Framefield. All rights reserved.
// Released under the MIT license. (see LICENSE.txt)
using System;
using System.Collections.Generic;
using System.Linq;
using Framefield.Core.OperatorPartTraits;
namespace Framefield.Core
{
public class OperatorPart : IDisposable
{
public static bool EnableEventPropagationByDefault = true;
public static bool HasValidInvalidationMarksOnOperatorPartsForTraversing = false;
public abstract class Function : IDisposable
{
private bool _changed;
public event EventHandler<EventArgs> ChangedEvent;
public virtual OperatorPart OperatorPart { get; set; }
public bool Changed
{
get { return _changed; }
set
{
_changed = value;
if (!value)
{
ChangedState = ChangedState.Nothing;
}
}
}
public ChangedState ChangedState { get; set; }
protected Function()
{
Changed = true;
ChangedState = ChangedState.Value | ChangedState.Subtree;
}
public virtual void Dispose()
{
Utilities.RemoveAllEventHandlerFrom(this);
}
public virtual Function Clone()
{
throw new Exception("should be handled in specific function");
}
public int EvaluationIndex { get; set; }
public abstract OperatorPartContext Eval(OperatorPartContext context, List<OperatorPart> inputs, int outputIdx);
protected void TriggerChangedEvent(EventArgs e)
{
if (ChangedEvent != null)
ChangedEvent(this, e);
}
protected static void EvalMultiInput(OperatorPart multiInput, OperatorPartContext context)
{
foreach (var input in multiInput.Connections)
{
input.Eval(context);
}
}
}
#region events
[Flags]
public enum ChangedState
{
Nothing = 0,
Value = 1,
Subtree = 2
};
public class ChangedEventArgs : EventArgs
{
public float Time { get; private set; }
public ChangedState ChangedState { get; private set; }
public ChangedEventArgs(float time) : this(time, ChangedState.Value)
{
}
public ChangedEventArgs(float time, ChangedState changedState)
{
Time = time;
ChangedState = changedState;
}
}
public delegate void ChangedDelegate(object obj, ChangedEventArgs args);
public class TypeChangedEventArgs : EventArgs
{
public FunctionType Type { get; set; }
public TypeChangedEventArgs(FunctionType type) {
Type = type;
}
}
public delegate void TypeChangedDelegate(object obj, TypeChangedEventArgs args);
public event ChangedDelegate ChangedEvent = (o, a) => {};
public event TypeChangedDelegate TypeChangedEvent = (o, a) => {};
public event EventHandler<EventArgs> ManipulatedEvent = (o, a) => {};
#endregion
#region properties
public Guid ID { get; private set; }
public Function Func {
get { return _function; }
set {
if (_function != null) {
_function.ChangedEvent -= FunctionChangedHandler;
_function.Dispose();
}
_function = value;
if (_function != null) {
_function.Changed = true;
_function.ChangedEvent += FunctionChangedHandler;
_function.OperatorPart = this;
}
ChangedEvent(this, new ChangedEventArgs(_changedTime));
ManipulatedEvent(this, EventArgs.Empty);
}
}
internal Function DefaultFunc
{
get { return _defaultFunc; }
set
{
if (_defaultFunc != null)
_defaultFunc.ChangedEvent -= DefaultFunctionChangedHandler;
_defaultFunc = value;
_defaultFunc.ChangedEvent += DefaultFunctionChangedHandler;
}
}
private Function _defaultFunc;
public List<OperatorPart> Connections { get { return _connections; } }
internal bool Disabled
{
get { return _disabled; }
set
{
_disabled = value;
EmitChangedEvent();
}
}
public FunctionType Type {
get {
if (_type == FunctionType.Generic && Connections.Count() > 0)
return Connections[0].Type;
else
return _type;
}
set {
_type = value;
ManipulatedEvent(this, EventArgs.Empty);
}
}
public float ChangedTime { get { return _changedTime; } }
public bool IsMultiInput {
get {
return _isMultiInput;
}
set {
_isMultiInput = value;
ManipulatedEvent(this, EventArgs.Empty);
}
}
public string Name {
get {
return _name;
}
set {
_name = value;
ManipulatedEvent(this, EventArgs.Empty);
}
}
public Operator Parent {
get {
return _parent;
}
set {
_parent = value;
ManipulatedEvent(this, EventArgs.Empty);
}
}
public delegate void EvaluateCallbackDelegate();
public static EvaluateCallbackDelegate EvaluateCallback { get; set; }
#endregion
public void Dispose()
{
if (_function != null)
_function.ChangedEvent -= FunctionChangedHandler;
if (_defaultFunc != null)
_defaultFunc.ChangedEvent -= DefaultFunctionChangedHandler;
Utilities.DisposeObj(ref _function);
Utilities.RemoveAllEventHandlerFrom(this);
}
public override string ToString() {
return Parent + "." + Name;
}
public OperatorPart(Guid id, Function defaultFunc) {
ID = id;
Func = defaultFunc;
IsMultiInput = false;
ChangedPropagationEnabled = EnableEventPropagationByDefault;
DefaultFunc = defaultFunc;
}
public OperatorPartContext Eval(OperatorPartContext context, int outputIdx)
{
if (Disabled)
return context;
if (EvaluateCallback != null)
EvaluateCallback();
return _function.Eval(context, _connections, outputIdx);
}
public OperatorPartContext Eval(OperatorPartContext context)
{
return Eval(context, Func.EvaluationIndex);
}
#region connections
public void InsertConnectionAt(OperatorPart inputToConnect, int index) {
if ((_connections.Count > 0) && !IsMultiInput)
throw new Exception("multiple connections not allowed");
if ((index < 0) || (index > _connections.Count))
throw new Exception("index out of range");
_connections.Insert(index, inputToConnect);
if (IsDefaultFuncSet)
ReplaceDefaultWithValueFunc();
inputToConnect.ChangedEvent += ChangedHandler;
inputToConnect.TypeChangedEvent += TypeChangedHandler;
if ((_type == FunctionType.Generic) && (inputToConnect.Type != FunctionType.Generic))
EmitTypeChangedEvent(Type);
_function.Changed = true;
ChangedEvent(this, new ChangedEventArgs(_changedTime, ChangedState.Subtree));
ManipulatedEvent(this, EventArgs.Empty);
}
public void ReplaceConnectionAt(OperatorPart connection, int index) {
RemoveConnectionAt(index);
InsertConnectionAt(connection, index);
}
public void AppendConnection(OperatorPart connection) {
InsertConnectionAt(connection, _connections.Count);
}
public void RemoveConnectionAt(int index)
{
var prevConnection = _connections[index];
prevConnection.ChangedEvent -= ChangedHandler;
prevConnection.TypeChangedEvent -= TypeChangedHandler;
_connections.RemoveAt(index);
var prevValueFunction = prevConnection.Func as Utilities.ValueFunction;
if (prevValueFunction != null)
{
// if it was a value function we set that previous input value as the new one
SetValue(prevValueFunction.Value);
}
ChangedEvent(this, new ChangedEventArgs(_changedTime, ChangedState.Subtree));
ManipulatedEvent(this, EventArgs.Empty);
}
public void ClearConnections() {
_connections.ForEach(c => {
c.ChangedEvent -= ChangedHandler;
c.TypeChangedEvent -= TypeChangedHandler;
});
_connections.Clear();
ManipulatedEvent(this, EventArgs.Empty);
}
#endregion
#region event handling
public bool ChangedPropagationEnabled { get; set; }
private void ChangedHandler(object sender, ChangedEventArgs args)
{
Func.Changed = true;
Func.ChangedState |= args.ChangedState;
if (ChangedPropagationEnabled)
ChangedEvent(this, args);
}
private void TypeChangedHandler(object sender, TypeChangedEventArgs args) {
if (Type != args.Type) {
int index = Connections.IndexOf(sender as OperatorPart);
EmitTypeChangedEvent(args.Type);
}
else if (_type == FunctionType.Generic)
EmitTypeChangedEvent(args.Type); // in case of generic we need to propagate this event further
}
private void EmitTypeChangedEvent(FunctionType type) {
TypeChangedEvent(this, new TypeChangedEventArgs(type));
}
private void FunctionChangedHandler(object sender, EventArgs args) {
ChangedEvent(this, new ChangedEventArgs(_changedTime));
}
private void DefaultFunctionChangedHandler(object sender, EventArgs args)
{
if (Parent != null)
Parent.Definition.Changed = true; // set defintion dirty
}
#endregion
public void EmitChangedEvent() {
ChangedEvent(this, new ChangedEventArgs(_changedTime));
}
public void EmitChangedEventForOutput(int outputId)
{
OperatorPart output = (from o in Parent.Outputs
where o.Func.EvaluationIndex == outputId
select o).Single();
output.Func.Changed = true;
output.EmitChangedEvent();
}
public interface IPreTraverseEvaluator
{
void PreEvaluate(OperatorPart opPart);
}
public interface IPostTraverseEvaluator
{
void ChildrenStart();
void ChildrenEnd();
void PostEvaluate(OperatorPart opPart);
void AlreadyVisited(OperatorPart opPart);
}
public abstract class Invalidator
{
protected Invalidator()
{
Clear();
}
public void ChildrenStart()
{
_changedStates.Push(false);
}
public void ChildrenEnd()
{
UpdateStackTop(_changedStates.Pop());
}
private void UpdateStackTop(bool changed)
{
if (changed && !_changedStates.Peek())
{
_changedStates.Pop();
_changedStates.Push(changed);
}
}
public void AlreadyVisited(OperatorPart opPart)
{
if (opPart.Func != null)
UpdateStackTop(opPart.Func.Changed);
}
public void Clear()
{
_changedStates.Clear();
_changedStates.Push(false);
}
protected Stack<bool> _changedStates = new Stack<bool>();
}
public class InvalidateTimeAccessors : Invalidator, IPostTraverseEvaluator
{
public void PostEvaluate(OperatorPart opPart)
{
if (_changedStates.Peek())
{
if (opPart.Func != null)
opPart.Func.Changed = true;
return;
}
if (opPart.Func is ITimeAccessor)
{
opPart.Func.Changed = true;
_changedStates.Pop();
_changedStates.Push(true);
}
}
}
public class InvalidateInvalidatables : Invalidator, IPostTraverseEvaluator
{
public void PostEvaluate(OperatorPart opPart)
{
if (_changedStates.Peek())
{
if (opPart.Func != null)
opPart.Func.Changed = true;
return;
}
var isTimeAccessor = opPart.Func is ITimeAccessor;
var asyncDependend = opPart.Func as IAsyncDependend;
var isVariableAccessor = opPart.Func is IVariableAccessor;
if (isTimeAccessor || (asyncDependend != null && asyncDependend.AsyncChanged) || isVariableAccessor)
{
opPart.Func.Changed = true;
_changedStates.Pop();
_changedStates.Push(true);
}
}
}
public class InvalidateVariableAccessors : Invalidator, IPostTraverseEvaluator
{
public InvalidateVariableAccessors(string variableName)
{
_variableName = variableName;
}
public void PostEvaluate(OperatorPart opPart)
{
if (_changedStates.Peek())
{
if (opPart.Func != null)
opPart.Func.Changed = true;
return;
}
var variableAccessor = opPart.Func as IVariableAccessor;
if (variableAccessor != null && variableAccessor.VariableName == _variableName)
{
opPart.Func.Changed = true;
_changedStates.Pop();
_changedStates.Push(true);
}
}
private string _variableName;
}
public class CycleChecker : IPreTraverseEvaluator
{
public bool HasCycle { get; private set; }
// the input is a list of op parts that should not be found traversing a subtree,
// normally here are the outputs of a specific op given when trying to add a
// connection to it
public CycleChecker(IEnumerable<OperatorPart> opPartThatWouldBuildACycle)
{
HasCycle = false;
_opPartThatWouldBuildACycle = opPartThatWouldBuildACycle;
}
public void PreEvaluate(OperatorPart opPart)
{
if (_opPartThatWouldBuildACycle.Contains(opPart))
{
HasCycle = true;
}
}
private readonly IEnumerable<OperatorPart> _opPartThatWouldBuildACycle;
}
public class InvalidateAllVariableAccessors : Invalidator, IPostTraverseEvaluator
{
public void PostEvaluate(OperatorPart opPart)
{
if (_changedStates.Peek())
{
if (opPart.Func != null)
opPart.Func.Changed = true;
return;
}
if (opPart.Func is IVariableAccessor)
{
opPart.Func.Changed = true;
_changedStates.Pop();
_changedStates.Push(true);
}
}
}
public void MarkInvalidatables()
{
var invalidator = new MarkInvalidatablesInSubTree();
TraverseWithFunction(null, invalidator);
}
private class MarkInvalidatablesInSubTree : IPostTraverseEvaluator
{
int intending = 0;
public MarkInvalidatablesInSubTree()
{
intending = 0;
Clear();
}
public void ChildrenStart()
{
intending += 2;
_markedStates.Push(false);
}
public void ChildrenEnd()
{
intending -= 2;
UpdateStackTop(_markedStates.Pop());
}
private void UpdateStackTop(bool marked)
{
if (marked && !_markedStates.Peek())
{
_markedStates.Pop();
_markedStates.Push(marked);
}
}
public void PostEvaluate(OperatorPart opPart)
{
if (_markedStates.Peek())
{
opPart.SubTreeContainsInvalidatable = true;
return;
}
var isTimeAccessor = opPart.Func is ITimeAccessor;
var isAsyncDependend = opPart.Func is IAsyncDependend;
var isVariableAccessor = opPart.Func is IVariableAccessor;
opPart.SubTreeContainsInvalidatable = isTimeAccessor || isAsyncDependend || isVariableAccessor;
if (opPart.SubTreeContainsInvalidatable)
{
_markedStates.Pop();
_markedStates.Push(true);
}
}
public void AlreadyVisited(OperatorPart opPart)
{
UpdateStackTop(opPart.SubTreeContainsInvalidatable);
}
public void Clear()
{
_markedStates.Clear();
_markedStates.Push(false);
}
private Stack<bool> _markedStates = new Stack<bool>();
}
public class CollectOpPartFunctionsOfType<T> : IPreTraverseEvaluator where T : class
{
public HashSet<T> CollectedOpPartFunctions { get; private set; }
public CollectOpPartFunctionsOfType() {
CollectedOpPartFunctions = new HashSet<T>();
}
public void PreEvaluate(OperatorPart opPart) {
T func = opPart.Func as T;
if (func != null)
CollectedOpPartFunctions.Add(func);
}
public void Clear() {
CollectedOpPartFunctions.Clear();
}
}
public class CollectAllOperators : IPreTraverseEvaluator
{
public HashSet<MetaOperator> CollectedOperators { get; private set; }
public CollectAllOperators()
{
CollectedOperators = new HashSet<MetaOperator>();
}
public void PreEvaluate(OperatorPart opPart)
{
var metaOperator = opPart.Parent.Definition;
if (!CollectedOperators.Contains(metaOperator))
{
// new op, add
CollectedOperators.Add(metaOperator);
}
}
public void Clear()
{
CollectedOperators.Clear();
}
}
public class WriteChangedStates : IPreTraverseEvaluator
{
public void PreEvaluate(OperatorPart opPart)
{
// Logger.Info("{0} changed: {1}", opPart.Func.ToString(), opPart.Func.Changed);
}
}
public bool SubTreeContainsInvalidatable { get; private set; }
[Flags]
enum TraverseOption
{
None = 0,
UseInvalidationMarks = 1,
}
public void TraverseWithFunction(IPreTraverseEvaluator preTraverseEvaluator, IPostTraverseEvaluator postTraverseEvaluator)
{
_referenceTraverseID++;
_traverseOptions = preTraverseEvaluator is Invalidator || postTraverseEvaluator is Invalidator ? TraverseOption.UseInvalidationMarks : TraverseOption.None;
TraverseWithFunctionInternal(preTraverseEvaluator, postTraverseEvaluator);
}
private void TraverseWithFunctionInternal(IPreTraverseEvaluator preTraverseEvaluator, IPostTraverseEvaluator postTraverseEvaluator)
{
if ((_traverseOptions.HasFlag(TraverseOption.UseInvalidationMarks) && HasValidInvalidationMarksOnOperatorPartsForTraversing && !SubTreeContainsInvalidatable) ||
_traverseID == _referenceTraverseID)
{
if (postTraverseEvaluator != null)
postTraverseEvaluator.AlreadyVisited(this);
return;
}
_traverseID = _referenceTraverseID;
if (preTraverseEvaluator != null)
preTraverseEvaluator.PreEvaluate(this);
foreach (var input in Connections)
{
if (postTraverseEvaluator != null)
postTraverseEvaluator.ChildrenStart();
if (!input.Disabled)
input.TraverseWithFunctionInternal(preTraverseEvaluator, postTraverseEvaluator);
if (postTraverseEvaluator != null)
postTraverseEvaluator.ChildrenEnd();
}
if (postTraverseEvaluator != null)
postTraverseEvaluator.PostEvaluate(this);
}
public void TraverseWithFunctionUseSpecificBehavior(IPreTraverseEvaluator preTraverseEvaluator, IPostTraverseEvaluator postTraverseEvaluator)
{
_referenceTraverseID++;
_traverseOptions = preTraverseEvaluator is Invalidator || postTraverseEvaluator is Invalidator ? TraverseOption.UseInvalidationMarks : TraverseOption.None;
TraverseWithFunctionUseSpecificBehaviorInternal(preTraverseEvaluator, postTraverseEvaluator);
}
private void TraverseWithFunctionUseSpecificBehaviorInternal(IPreTraverseEvaluator preTraverseEvaluator, IPostTraverseEvaluator postTraverseEvaluator)
{
if ((_traverseOptions.HasFlag(TraverseOption.UseInvalidationMarks) && HasValidInvalidationMarksOnOperatorPartsForTraversing && !SubTreeContainsInvalidatable) ||
_traverseID == _referenceTraverseID)
{
if (postTraverseEvaluator != null)
postTraverseEvaluator.AlreadyVisited(this);
return;
}
_traverseID = _referenceTraverseID;
if (preTraverseEvaluator != null)
preTraverseEvaluator.PreEvaluate(this);
IEnumerable<OperatorPart> connections;
ITraverseModifier traversModifier = Func as ITraverseModifier;
if (traversModifier != null)
connections = traversModifier.GetRelevantConnections();
else
connections = Connections;
foreach (var opPart in connections)
{
if (postTraverseEvaluator != null)
postTraverseEvaluator.ChildrenStart();
opPart.TraverseWithFunctionUseSpecificBehaviorInternal(preTraverseEvaluator, postTraverseEvaluator);
if (postTraverseEvaluator != null)
postTraverseEvaluator.ChildrenEnd();
}
if (postTraverseEvaluator != null)
postTraverseEvaluator.PostEvaluate(this);
}
internal void SetValueToDefault()
{
Func = DefaultFunc;
}
public void SetValue(IValue value)
{
Func = Utilities.CreateValueFunction(value);
}
public void ReplaceDefaultWithValueFunc()
{
var func = Func as Utilities.DefaultValueFunction;
if (func != null)
SetValue(func.Value);
}
public bool IsDefaultFuncSet { get { return Func == DefaultFunc; } }
#region private members
private Function _function = null;
private List<OperatorPart> _connections = new List<OperatorPart>();
private float _changedTime = 0.0f;
private FunctionType _type;
private bool _isMultiInput;
private Operator _parent;
private string _name;
private bool _disabled;
private int _traverseID;
private static int _referenceTraverseID = 0;
private static TraverseOption _traverseOptions = TraverseOption.None;
#endregion
}
}