-
Notifications
You must be signed in to change notification settings - Fork 746
Expand file tree
/
Copy pathSharedUserInterfaceSystem.cs
More file actions
1347 lines (1112 loc) · 43.6 KB
/
Copy pathSharedUserInterfaceSystem.cs
File metadata and controls
1347 lines (1112 loc) · 43.6 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
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Numerics;
using System.Runtime.InteropServices;
using JetBrains.Annotations;
using Robust.Shared.Collections;
using Robust.Shared.GameStates;
using Robust.Shared.IoC;
using Robust.Shared.Network;
using Robust.Shared.Player;
using Robust.Shared.Reflection;
using Robust.Shared.Threading;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
namespace Robust.Shared.GameObjects;
public abstract partial class SharedUserInterfaceSystem : EntitySystem
{
[Dependency] private IDynamicTypeFactory _factory = default!;
[Dependency] private IGameTiming _timing = default!;
[Dependency] private INetManager _netManager = default!;
[Dependency] private IParallelManager _parallel = default!;
[Dependency] private IReflectionManager _reflection = default!;
[Dependency] protected ISharedPlayerManager Player = default!;
[Dependency] private SharedTransformSystem _transforms = default!;
private EntityQuery<IgnoreUIRangeComponent> _ignoreUIRangeQuery;
private EntityQuery<TransformComponent> _xformQuery;
protected EntityQuery<UserInterfaceComponent> UIQuery;
protected EntityQuery<UserInterfaceUserComponent> UserQuery;
private ActorRangeCheckJob _rangeJob;
/// <summary>
/// Defer BUIs during state handling so client doesn't spam a BUI constantly during prediction.
/// </summary>
private readonly List<(BoundUserInterface Bui, bool value)> _queuedBuis = new();
public override void Initialize()
{
base.Initialize();
EntityManager.ComponentFactory.RegisterNetworkedFields<UserInterfaceComponent>(
nameof(UserInterfaceComponent.Actors),
nameof(UserInterfaceComponent.Interfaces),
nameof(UserInterfaceComponent.States));
_ignoreUIRangeQuery = GetEntityQuery<IgnoreUIRangeComponent>();
_xformQuery = GetEntityQuery<TransformComponent>();
UIQuery = GetEntityQuery<UserInterfaceComponent>();
UserQuery = GetEntityQuery<UserInterfaceUserComponent>();
_rangeJob = new()
{
System = this,
XformQuery = _xformQuery,
};
SubscribeAllEvent<BoundUIWrapMessage>((msg, args) =>
{
if (args.SenderSession.AttachedEntity is not { } player)
return;
OnMessageReceived(msg, player);
});
SubscribeLocalEvent<UserInterfaceComponent, OpenBoundInterfaceMessage>(OnUserInterfaceOpen);
SubscribeLocalEvent<UserInterfaceComponent, CloseBoundInterfaceMessage>(OnUserInterfaceClosed);
SubscribeLocalEvent<UserInterfaceComponent, ComponentStartup>(OnUserInterfaceStartup);
SubscribeLocalEvent<UserInterfaceComponent, ComponentShutdown>(OnUserInterfaceShutdown);
SubscribeLocalEvent<UserInterfaceComponent, ComponentGetState>(OnUserInterfaceGetState);
SubscribeLocalEvent<UserInterfaceComponent, ComponentHandleState>(OnUserInterfaceHandleState);
SubscribeLocalEvent<PlayerAttachedEvent>(OnPlayerAttached);
SubscribeLocalEvent<PlayerDetachedEvent>(OnPlayerDetached);
SubscribeLocalEvent<UserInterfaceUserComponent, ComponentShutdown>(OnActorShutdown);
}
private void AddQueued(BoundUserInterface bui, bool value)
{
_queuedBuis.Add((bui, value));
}
/// <summary>
/// Validates the received message, and then pass it onto systems/components
/// </summary>
private void OnMessageReceived(BoundUIWrapMessage msg, EntityUid sender)
{
// This is more or less the main BUI method that handles all messages.
var uid = GetEntity(msg.Entity);
if (!UIQuery.TryComp(uid, out var uiComp))
{
return;
}
if (!uiComp.Interfaces.TryGetValue(msg.UiKey, out var ui))
{
Log.Debug($"Got BoundInterfaceMessageWrapMessage for unknown UI key: {msg.UiKey}");
return;
}
var received = new BoundUserInterfaceMessageReceivedEvent(sender, uid, msg.UiKey);
RaiseLocalEvent(ref received);
// If it's not an open message check we're even a subscriber.
if (msg.Message is not OpenBoundInterfaceMessage &&
(!uiComp.Actors.TryGetValue(msg.UiKey, out var actors) ||
!actors.Contains(sender)))
{
Log.Debug($"UI {msg.UiKey} got BoundInterfaceMessageWrapMessage from a client who was not subscribed: {ToPrettyString(sender)}");
return;
}
// verify that the user is allowed to press buttons on this UI:
// If it's a close message something else might try to cancel it but we want to force it.
if (msg.Message is not CloseBoundInterfaceMessage && ui.RequireInputValidation)
{
var attempt = new BoundUserInterfaceMessageAttempt(sender, uid, msg.UiKey, msg.Message);
RaiseLocalEvent(ref attempt);
if (attempt.Cancelled)
return;
RaiseLocalEvent(uid, ref attempt);
if (attempt.Cancelled)
return;
}
// get the wrapped message and populate it with the sender & UI key information.
var message = msg.Message;
message.Actor = sender;
message.Entity = msg.Entity;
message.UiKey = msg.UiKey;
if (uiComp.ClientOpenInterfaces.TryGetValue(msg.UiKey, out var cBui))
{
cBui.ReceiveMessage(message);
}
// Raise as object so the correct type is used.
RaiseLocalEvent(uid, (object)message, true);
}
#region User
private void OnActorShutdown(Entity<UserInterfaceUserComponent> ent, ref ComponentShutdown args)
{
CloseUserUis((ent.Owner, ent.Comp));
}
#endregion
private void OnPlayerAttached(PlayerAttachedEvent ev)
{
if (!UserQuery.TryGetComponent(ev.Entity, out var actor))
return;
// Open BUIs upon attachment
foreach (var (uid, keys) in actor.OpenInterfaces)
{
if (!UIQuery.TryGetComponent(uid, out var uiComp))
continue;
// Player can now receive information about open UIs
Dirty(uid, uiComp);
foreach (var key in keys)
{
if (!uiComp.Interfaces.TryGetValue(key, out var data))
continue;
EnsureClientBui((uid, uiComp), key, data);
}
}
}
private void OnPlayerDetached(PlayerDetachedEvent ev)
{
if (!UserQuery.TryGetComponent(ev.Entity, out var actor))
return;
// Close BUIs open detachment.
foreach (var (uid, keys) in actor.OpenInterfaces)
{
if (!UIQuery.TryGetComponent(uid, out var uiComp))
continue;
// Player can no longer receive information about open UIs
Dirty(uid, uiComp);
foreach (var key in keys)
{
if (!uiComp.ClientOpenInterfaces.Remove(key, out var cBui))
continue;
cBui.Dispose();
}
}
}
private void OnUserInterfaceClosed(Entity<UserInterfaceComponent> ent, ref CloseBoundInterfaceMessage args)
{
CloseUiInternal(ent!, args.UiKey, args.Actor);
}
private void CloseUiInternal(Entity<UserInterfaceComponent?> ent, Enum key, EntityUid actor)
{
if (!UIQuery.Resolve(ent.Owner, ref ent.Comp, false))
return;
if (!ent.Comp.Actors.TryGetValue(key, out var actors))
return;
actors.Remove(actor);
if (actors.Count == 0)
ent.Comp.Actors.Remove(key);
DirtyField(ent, nameof(UserInterfaceComponent.Actors));
// If the actor is also deleting then don't worry about updating what they have open.
if (!TerminatingOrDeleted(actor)
&& UserQuery.TryComp(actor, out var actorComp)
&& actorComp.OpenInterfaces.TryGetValue(ent.Owner, out var keys))
{
keys.Remove(key);
if (keys.Count == 0)
{
actorComp.OpenInterfaces.Remove(ent.Owner);
if (actorComp.OpenInterfaces.Count == 0)
RemCompDeferred<UserInterfaceUserComponent>(actor);
}
}
if (ent.Comp.ClientOpenInterfaces.TryGetValue(key, out var cBui))
{
AddQueued(cBui, false);
}
if (ent.Comp.Actors.Count == 0)
RemCompDeferred<ActiveUserInterfaceComponent>(ent.Owner);
var ev = new BoundUIClosedEvent(key, ent.Owner, actor);
RaiseLocalEvent(ent.Owner, ev);
}
private void OnUserInterfaceOpen(Entity<UserInterfaceComponent> ent, ref OpenBoundInterfaceMessage args)
{
OpenUiInternal(ent!, args.UiKey, args.Actor);
}
private void OpenUiInternal(Entity<UserInterfaceComponent?> ent, Enum key, EntityUid actor)
{
if (!UIQuery.Resolve(ent.Owner, ref ent.Comp, false))
return;
// Similar to the close method this handles actually opening a UI, it just gets relayed here
EnsureComp<ActiveUserInterfaceComponent>(ent.Owner);
var actorComp = EnsureComp<UserInterfaceUserComponent>(actor);
// Let state handling open the UI clientside.
actorComp.OpenInterfaces.GetOrNew(ent.Owner).Add(key);
ent.Comp.Actors.GetOrNew(key).Add(actor);
DirtyField(ent, nameof(UserInterfaceComponent.Actors));
var ev = new BoundUIOpenedEvent(key, ent.Owner, actor);
RaiseLocalEvent(ent.Owner, ev);
// If we're client we want this handled immediately.
EnsureClientBui(ent!, key, ent.Comp.Interfaces[key]);
}
private void OnUserInterfaceStartup(Entity<UserInterfaceComponent> ent, ref ComponentStartup args)
{
// PlayerAttachedEvent will catch some of these.
foreach (var (key, bui) in ent.Comp.ClientOpenInterfaces)
{
AddQueued(bui, true);
}
}
protected void OnUserInterfaceShutdown(Entity<UserInterfaceComponent> ent, ref ComponentShutdown args)
{
var ents = new ValueList<EntityUid>();
foreach (var (key, acts) in ent.Comp.Actors)
{
ents.Clear();
ents.AddRange(acts);
foreach (var actor in ents)
{
CloseUiInternal(ent!, key, actor);
DebugTools.Assert(!acts.Contains(actor));
}
DebugTools.Assert(!ent.Comp.Actors.ContainsKey(key));
}
DebugTools.Assert(ent.Comp.ClientOpenInterfaces.Values.All(x => _queuedBuis.Contains((x, false))));
}
private void OnUserInterfaceGetState(Entity<UserInterfaceComponent> ent, ref ComponentGetState args)
{
var aspects = EntityManager.GetModifiedAspects(ent.Comp, args.FromTick);
switch (aspects)
{
case >= DeltaAspect.Unclassified:
break;
case 1 << 0:
{
var state = new UserInterfaceActorsDeltaState();
AddActors(ent, state.Actors, ref args);
args.State = state;
return;
}
case 1 << 2:
{
var states = ent.Comp.States;
// TODO Game State
// Force the client to serialize & de-serialize implicitly generated component states.
if (_netManager.IsClient)
states = new(states);
args.State = new UserInterfaceStatesDeltaState {States = states};
return;
}
}
var actors = new Dictionary<Enum, List<NetEntity>>();
var dataCopy = new Dictionary<Enum, InterfaceData>(ent.Comp.Interfaces.Count);
// TODO Game State
// Force the client to serialize & de-serialize implicitly generated component states.
foreach (var (weh, a) in ent.Comp.Interfaces)
{
dataCopy[weh] = new InterfaceData(a);
}
args.State = new UserInterfaceComponentState(actors, new(ent.Comp.States), dataCopy);
// Ensure that only the player that currently has the UI open gets to know what they have it open.
AddActors(ent, actors, ref args);
}
private void AddActors(Entity<UserInterfaceComponent> ent, Dictionary<Enum, List<NetEntity>> actors, ref ComponentGetState args)
{
// Ensure that only the player that currently has the UI open gets to know what they have it open.
if (args.ReplayState)
{
foreach (var (key, acts) in ent.Comp.Actors)
{
actors[key] = GetNetEntityList(acts);
}
}
else if (args.Player.AttachedEntity is { } player)
{
var netPlayer = new List<NetEntity> { GetNetEntity(player) };
foreach (var (key, acts) in ent.Comp.Actors)
{
if (acts.Contains(player))
actors[key] = netPlayer;
}
}
}
private void OnUserInterfaceHandleState(Entity<UserInterfaceComponent> ent, ref ComponentHandleState args)
{
Dictionary<Enum, List<NetEntity>>? stateActors = null;
Dictionary<Enum, InterfaceData>? stateData = null;
Dictionary<Enum, BoundUserInterfaceState>? stateStates = null;
if (args.Current is UserInterfaceComponentState state)
{
stateActors = state.Actors;
stateData = state.Data;
stateStates = state.States;
}
else if (args.Current is UserInterfaceActorsDeltaState actorDelta)
{
stateActors = actorDelta.Actors;
}
else if (args.Current is UserInterfaceStatesDeltaState stateDelta)
{
stateStates = stateDelta.States;
}
else
{
return;
}
// Interfaces
if (stateData != null)
{
ent.Comp.Interfaces.Clear();
foreach (var data in stateData)
{
ent.Comp.Interfaces[data.Key] = new(data.Value);
}
}
var attachedEnt = Player.LocalEntity;
// Actors
if (stateActors != null)
{
foreach (var key in ent.Comp.Actors.Keys)
{
if (!stateActors.ContainsKey(key))
CloseUi(ent!, key);
}
var toRemoveActors = new ValueList<EntityUid>();
var newSet = new HashSet<EntityUid>();
foreach (var (key, acts) in stateActors)
{
var actors = ent.Comp.Actors.GetOrNew(key);
newSet.Clear();
foreach (var netEntity in acts)
{
var uid = EnsureEntity<UserInterfaceComponent>(netEntity, ent.Owner);
if (uid.IsValid())
newSet.Add(uid);
}
foreach (var actor in newSet)
{
if (!actors.Contains(actor))
OpenUiInternal(ent!, key, actor);
}
foreach (var actor in actors)
{
if (!newSet.Contains(actor))
toRemoveActors.Add(actor);
}
foreach (var actor in toRemoveActors)
{
CloseUiInternal(ent!, key, actor);
}
}
var clientBuis = new ValueList<Enum>(ent.Comp.ClientOpenInterfaces.Keys);
// Check if the UI is open by us, otherwise dispose of it.
foreach (var key in clientBuis)
{
if (ent.Comp.Actors.TryGetValue(key, out var actors) &&
(attachedEnt == null || actors.Contains(attachedEnt.Value)))
{
continue;
}
var bui = ent.Comp.ClientOpenInterfaces[key];
AddQueued(bui, false);
}
}
// States
if (stateStates != null)
{
foreach (var key in ent.Comp.States.Keys)
{
if (!stateStates.ContainsKey(key))
ent.Comp.States.Remove(key);
}
// update any states we have open
foreach (var (key, buiState) in stateStates)
{
if (ent.Comp.States.TryGetValue(key, out var existing) &&
existing.Equals(buiState))
{
continue;
}
ent.Comp.States[key] = buiState;
if (!ent.Comp.ClientOpenInterfaces.TryGetValue(key, out var cBui) || !cBui.IsOpened)
continue;
cBui.State = buiState;
cBui.UpdateState(buiState);
cBui.Update();
}
}
// If UI not open then open it
// If we get the first state for an ent coming in then don't open BUIs yet, just defer it until later.
var open = ent.Comp.LifeStage > ComponentLifeStage.Added;
if (attachedEnt != null && stateActors != null)
{
foreach (var (key, value) in ent.Comp.Interfaces)
{
EnsureClientBui(ent, key, value, open);
}
}
}
/// <summary>
/// Opens a client's BUI if not already open and applies the state to it.
/// </summary>
private void EnsureClientBui(Entity<UserInterfaceComponent> entity, Enum key, InterfaceData data, bool open = true)
{
// If it's out BUI open it up and apply the state, otherwise do nothing.
var player = Player.LocalEntity;
// Existing BUI just keep it.
if (entity.Comp.ClientOpenInterfaces.TryGetValue(key, out var existing))
{
_queuedBuis.Remove((existing, false));
return;
}
if (player == null ||
!entity.Comp.Actors.TryGetValue(key, out var actors) ||
!actors.Contains(player.Value))
{
return;
}
DebugTools.Assert(_netManager.IsClient);
// Try-catch to try prevent error loops / bricked clients that constantly throw exceptions while applying game
// states. E.g., stripping UI used to throw NREs in some instances while fetching the identity of unknown
// entities.
var type = _reflection.LooseGetType(data.ClientType);
// No dependency injection because the BUI constructor will handle it.
var boundUserInterface = (BoundUserInterface) _factory.CreateInstance(type, [entity.Owner, key], inject: false);
entity.Comp.ClientOpenInterfaces[key] = boundUserInterface;
// This is just so we don't open while applying UI states.
if (!open)
return;
AddQueued(boundUserInterface, true);
}
/// <summary>
/// Yields all the entities + keys currently open by this entity.
/// </summary>
public IEnumerable<(EntityUid Entity, Enum Key)> GetActorUis(Entity<UserInterfaceUserComponent?> entity)
{
if (!UserQuery.Resolve(entity.Owner, ref entity.Comp, false))
yield break;
foreach (var berry in entity.Comp.OpenInterfaces)
{
foreach (var key in berry.Value)
{
yield return (berry.Key, key);
}
}
}
/// <summary>
/// Gets the actors that have the specified key attached to this entity open.
/// </summary>
public IEnumerable<EntityUid> GetActors(Entity<UserInterfaceComponent?> entity, Enum key)
{
if (!UIQuery.Resolve(entity.Owner, ref entity.Comp, false) || !entity.Comp.Actors.TryGetValue(key, out var actors))
yield break;
foreach (var actorUid in actors)
{
yield return actorUid;
}
}
/// <summary>
/// Closes the attached UI for all entities.
/// </summary>
public void CloseUi(Entity<UserInterfaceComponent?> entity, Enum key)
{
if (!UIQuery.Resolve(entity.Owner, ref entity.Comp, false))
return;
if (!entity.Comp.Actors.TryGetValue(key, out var actorSet))
return;
var actors = actorSet.ToArray();
foreach (var actor in actors)
{
CloseUiInternal(entity, key, actor);
}
}
/// <summary>
/// Closes the attached UI only for the specified actor.
/// </summary>
public void CloseUi(Entity<UserInterfaceComponent?> entity, Enum key, ICommonSession? actor, bool predicted = false)
{
var actorEnt = actor?.AttachedEntity;
if (actorEnt == null)
return;
CloseUi(entity, key, actorEnt.Value, predicted);
}
/// <summary>
/// Closes the attached Ui only for the specified actor.
/// </summary>
public void CloseUi(Entity<UserInterfaceComponent?> entity, Enum key, EntityUid? actor, bool predicted = false)
{
if (actor == null)
return;
if (!UIQuery.Resolve(entity.Owner, ref entity.Comp, false))
return;
// Short-circuit if no UI.
if (!entity.Comp.Interfaces.ContainsKey(key))
return;
if (!entity.Comp.Actors.TryGetValue(key, out var actors) || !actors.Contains(actor.Value))
return;
// Rely upon the client telling us.
if (!predicted)
{
CloseUiInternal(entity, key, actor.Value);
return;
}
if (!_timing.IsFirstTimePredicted)
return;
RaisePredictiveEvent(new BoundUIWrapMessage(GetNetEntity(entity.Owner), new CloseBoundInterfaceMessage(), key));
}
/// <summary>
/// Tries to call OpenUi and return false if it isn't open.
/// </summary>
public bool TryOpenUi(Entity<UserInterfaceComponent?> entity, Enum key, EntityUid actor, bool predicted = false)
{
if (!UIQuery.Resolve(entity.Owner, ref entity.Comp, false))
return false;
OpenUi(entity, key, actor, predicted);
// Due to the event actually handling the UI open / closed we can't
if (!entity.Comp.Actors.TryGetValue(key, out var actors) ||
!actors.Contains(actor))
{
return false;
}
return true;
}
/// <summary>
/// Opens the UI for the local client. Does nothing on server.
/// </summary>
public virtual void OpenUi(Entity<UserInterfaceComponent?> entity, Enum key, bool predicted = false)
{
}
public void OpenUi(Entity<UserInterfaceComponent?> entity, Enum key, EntityUid? actor, bool predicted = false)
{
if (actor == null || !UIQuery.Resolve(entity.Owner, ref entity.Comp, false))
return;
// No implementation for that UI key on this ent so short-circuit.
if (!entity.Comp.Interfaces.ContainsKey(key))
return;
if (entity.Comp.Actors.TryGetValue(key, out var actors) && actors.Contains(actor.Value))
return;
if (predicted)
{
if (_timing.IsFirstTimePredicted)
{
// Not guaranteed to open so rely upon the event handling it.
// Also lets client request it to be opened remotely too.
RaisePredictiveEvent(new BoundUIWrapMessage(GetNetEntity(entity.Owner), new OpenBoundInterfaceMessage(), key));
}
}
else
{
OnMessageReceived(new BoundUIWrapMessage(GetNetEntity(entity.Owner), new OpenBoundInterfaceMessage(), key), actor.Value);
}
}
public void OpenUi(Entity<UserInterfaceComponent?> entity, Enum key, ICommonSession actor, bool predicted = false)
{
var actorEnt = actor.AttachedEntity;
if (actorEnt == null)
return;
OpenUi(entity, key, actorEnt.Value, predicted);
}
/// <summary>
/// Tries to return the saved position of a user interface.
/// </summary>
public virtual bool TryGetPosition(Entity<UserInterfaceComponent?> entity, Enum key, out Vector2 position)
{
position = Vector2.Zero;
return false;
}
/// <summary>
/// Saves a position for the BUI.
/// </summary>
protected virtual void SavePosition(BoundUserInterface bui)
{
}
/// <summary>
/// Sets a BUI state and networks it to all clients.
/// </summary>
public void SetUiState(Entity<UserInterfaceComponent?> entity, Enum key, BoundUserInterfaceState? state)
{
if (!UIQuery.Resolve(entity.Owner, ref entity.Comp, false))
return;
if (!entity.Comp.Interfaces.ContainsKey(key))
return;
// Null state
if (state == null)
{
if (!entity.Comp.States.Remove(key))
return;
DirtyField(entity, nameof(UserInterfaceComponent.States));
}
// Non-null state, check if it matches existing.
else
{
ref var stateRef = ref CollectionsMarshal.GetValueRefOrAddDefault(entity.Comp.States, key, out var exists);
if (exists && stateRef?.Equals(state) == true)
return;
stateRef = state;
}
// Predict the change on client
if (state != null && _netManager.IsClient && entity.Comp.ClientOpenInterfaces.TryGetValue(key, out var bui))
{
if (bui.State?.Equals(state) != true)
{
bui.UpdateState(state);
bui.Update();
}
}
DirtyField(entity, nameof(UserInterfaceComponent.States));
}
/// <summary>
/// Returns true if this entity has the specified Ui key available, even if not currently open.
/// </summary>
public bool HasUi(EntityUid uid, Enum uiKey, UserInterfaceComponent? ui = null)
{
if (!Resolve(uid, ref ui, false))
return false;
return ui.Interfaces.ContainsKey(uiKey);
}
/// <summary>
/// Returns true if the specified UI key is open for this entity by anyone.
/// </summary>
public bool IsUiOpen(Entity<UserInterfaceComponent?> entity, Enum uiKey)
{
if (!UIQuery.Resolve(entity.Owner, ref entity.Comp, false))
return false;
if (!entity.Comp.Actors.TryGetValue(uiKey, out var actors))
return false;
DebugTools.Assert(actors.Count > 0);
return actors.Count > 0;
}
public bool IsUiOpen(Entity<UserInterfaceComponent?> entity, Enum uiKey, EntityUid actor)
{
if (!UIQuery.Resolve(entity.Owner, ref entity.Comp, false))
return false;
if (!entity.Comp.Actors.TryGetValue(uiKey, out var actors))
return false;
return actors.Contains(actor);
}
/// <summary>
/// Returns true if any of the specified UI keys are open for this entity by anyone.
/// </summary>
/// <param name="entity">The entity to check.</param>
/// <param name="uiKeys">The UI keys to check.</param>
/// <returns>True if any UI is open, false otherwise.</returns>
[PublicAPI]
public bool IsUiOpen(Entity<UserInterfaceComponent?> entity, IEnumerable<Enum> uiKeys)
{
if (!UIQuery.Resolve(entity.Owner, ref entity.Comp, false))
return false;
foreach (var key in uiKeys)
{
if (entity.Comp.Actors.ContainsKey(key))
return true;
}
return false;
}
/// <summary>
/// Returns true if any UI is open for this entity by anyone.
/// </summary>
/// <param name="entity">The entity to check.</param>
/// <returns>True if any UI is open, false otherwise.</returns>
[PublicAPI]
public bool IsAnyUiOpen(Entity<UserInterfaceComponent?> entity)
{
if (!UIQuery.Resolve(entity.Owner, ref entity.Comp, false))
return false;
return entity.Comp.Actors.Count > 0;
}
/// <summary>
/// Raises a BUI message locally (on client or server) without networking it.
/// </summary>
[PublicAPI]
public void RaiseUiMessage(Entity<UserInterfaceComponent?> entity, Enum key, BoundUserInterfaceMessage message)
{
if (!UIQuery.Resolve(entity.Owner, ref entity.Comp, false))
return;
if (!entity.Comp.Actors.TryGetValue(key, out var actors))
return;
OnMessageReceived(new BoundUIWrapMessage(GetNetEntity(entity.Owner), message, key), message.Actor);
}
#region Server messages
/// <summary>
/// Sends a BUI message to any actors who have the specified Ui key open.
/// </summary>
public void ServerSendUiMessage(Entity<UserInterfaceComponent?> entity, Enum key, BoundUserInterfaceMessage message)
{
if (!UIQuery.Resolve(entity.Owner, ref entity.Comp, false))
return;
if (!entity.Comp.Actors.TryGetValue(key, out var actors))
return;
var filter = Filter.Entities(actors.ToArray());
RaiseNetworkEvent(new BoundUIWrapMessage(GetNetEntity(entity.Owner), message, key), filter);
}
/// <summary>
/// Sends a Bui message to the specified actor only.
/// </summary>
public void ServerSendUiMessage(Entity<UserInterfaceComponent?> entity, Enum key, BoundUserInterfaceMessage message, EntityUid actor)
{
if (!UIQuery.Resolve(entity.Owner, ref entity.Comp, false))
return;
if (!entity.Comp.Actors.TryGetValue(key, out var actors) || !actors.Contains(actor))
return;
RaiseNetworkEvent(new BoundUIWrapMessage(GetNetEntity(entity.Owner), message, key), actor);
}
/// <summary>
/// Sends a Bui message to the specified actor only.
/// </summary>
public void ServerSendUiMessage(Entity<UserInterfaceComponent?> entity, Enum key, BoundUserInterfaceMessage message, ICommonSession actor)
{
if (!_netManager.IsClient)
return;
if (!UIQuery.Resolve(entity.Owner, ref entity.Comp, false) || actor.AttachedEntity is not { } attachedEntity)
return;
if (!entity.Comp.Actors.TryGetValue(key, out var actors) || !actors.Contains(attachedEntity))
return;
RaiseNetworkEvent(new BoundUIWrapMessage(GetNetEntity(entity.Owner), message, key), actor);
}
#endregion
/// <summary>
/// Raises a BUI message from the client to the server.
/// </summary>
public void ClientSendUiMessage(Entity<UserInterfaceComponent?> entity, Enum key, BoundUserInterfaceMessage message)
{
var player = Player.LocalEntity;
// Don't send it if we're not a valid actor for it just in case.
if (player == null ||
!UIQuery.Resolve(entity.Owner, ref entity.Comp, false) ||
!entity.Comp.Actors.TryGetValue(key, out var actors) ||
!actors.Contains(player.Value))
{
return;
}
RaiseNetworkEvent(new BoundUIWrapMessage(GetNetEntity(entity.Owner), message, key));
}
/// <summary>
/// Closes the user's UIs that match the specified key.
/// </summary>
public void CloseUserUis<T>(Entity<UserInterfaceUserComponent?> actor) where T: Enum
{
if (!UserQuery.Resolve(actor.Owner, ref actor.Comp, false))
return;
if (actor.Comp.OpenInterfaces.Count == 0)
return;
var keys = new ValueList<Enum>();
foreach (var (uid, enums) in actor.Comp.OpenInterfaces)
{
keys.Clear();
keys.AddRange(enums);
foreach (var weh in keys)
{
if (weh is not T)
continue;
CloseUiInternal(uid, weh, actor.Owner);
}
}
}
/// <summary>
/// Closes all Uis for the actor.
/// </summary>
public void CloseUserUis(Entity<UserInterfaceUserComponent?> actor)
{
if (!UserQuery.Resolve(actor.Owner, ref actor.Comp, false))
return;
if (actor.Comp.OpenInterfaces.Count == 0)
return;
var keys = new ValueList<Enum>();
foreach (var (uid, enums) in actor.Comp.OpenInterfaces)
{
keys.Clear();
keys.AddRange(enums);
foreach (var key in keys)
{
CloseUiInternal(uid, key, actor.Owner);
}
}
}
/// <summary>
/// Closes all Uis for the entity.
/// </summary>
public void CloseUis(Entity<UserInterfaceComponent?> entity)
{
if (!UIQuery.Resolve(entity.Owner, ref entity.Comp, false))
return;
var toClose = new ValueList<EntityUid>();
foreach (var (key, actors) in entity.Comp.Actors)
{
toClose.Clear();
toClose.AddRange(actors);
foreach (var actor in toClose)
{
CloseUiInternal(entity, key, actor);
}
}
}
/// <summary>
/// Closes all Uis for the entity that the specified actor has open.
/// </summary>
public void CloseUis(Entity<UserInterfaceComponent?> entity, EntityUid actor)
{