This repository was archived by the owner on Jun 28, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathSharedTransformSystem.Component.cs
More file actions
1790 lines (1486 loc) · 65.8 KB
/
Copy pathSharedTransformSystem.Component.cs
File metadata and controls
1790 lines (1486 loc) · 65.8 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.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Numerics;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
using Robust.Shared.Containers;
using Robust.Shared.GameStates;
using Robust.Shared.Map;
using Robust.Shared.Map.Components;
using Robust.Shared.Maths;
using Robust.Shared.Physics;
using Robust.Shared.Utility;
namespace Robust.Shared.GameObjects;
public abstract partial class SharedTransformSystem
{
#region Anchoring
internal void ReAnchor(
EntityUid uid,
TransformComponent xform,
MapGridComponent oldGrid,
MapGridComponent newGrid,
Vector2i oldTilePos,
Vector2i tilePos,
EntityUid oldGridUid,
EntityUid newGridUid,
TransformComponent oldGridXform,
TransformComponent newGridXform,
Angle rotation)
{
// Bypass some of the expensive stuff in unanchoring / anchoring.
_map.RemoveFromSnapGridCell(oldGridUid, oldGrid, oldTilePos, uid);
_map.AddToSnapGridCell(newGridUid, newGrid, tilePos, uid);
// TODO: Could do this re-parent way better.
// Unfortunately we don't want any anchoring events to go out hence... this.
xform._anchored = false;
oldGridXform._children.Remove(uid);
newGridXform._children.Add(uid);
xform._parent = newGridUid;
xform._anchored = true;
var oldPos = xform._localPosition;
var oldRot = xform._localRotation;
var oldMap = xform.MapUid;
xform._localPosition = tilePos + newGrid.TileSizeHalfVector;
xform._localRotation += rotation;
var meta = MetaData(uid);
SetGridId((uid, xform, meta), newGridUid);
RaiseMoveEvent((uid, xform, meta), oldGridUid, oldPos, oldRot, oldMap);
DebugTools.Assert(XformQuery.GetComponent(oldGridUid).MapID == XformQuery.GetComponent(newGridUid).MapID);
DebugTools.Assert(xform._anchored);
Dirty(uid, xform, meta);
var ev = new ReAnchorEvent(uid, oldGridUid, newGridUid, tilePos, xform);
RaiseLocalEvent(uid, ref ev);
}
[Obsolete("Use Entity<T> variant")]
public bool AnchorEntity(
EntityUid uid,
TransformComponent xform,
EntityUid gridUid,
MapGridComponent grid,
Vector2i tileIndices)
{
return AnchorEntity((uid, xform), (gridUid, grid), tileIndices);
}
public bool AnchorEntity(
Entity<TransformComponent> entity,
Entity<MapGridComponent> grid,
Vector2i tileIndices)
{
var (uid, xform) = entity;
if (!_map.AddToSnapGridCell(grid, grid, tileIndices, uid))
return false;
var wasAnchored = entity.Comp._anchored;
xform._anchored = true;
var meta = MetaData(uid);
Dirty(entity, meta);
// Mark as static before doing position changes, to avoid the velocity change on parent change.
_physics.TrySetBodyType(uid, BodyType.Static, xform: xform);
if (!wasAnchored && xform.Running)
{
var ev = new AnchorStateChangedEvent(uid, xform);
RaiseLocalEvent(uid, ref ev, true);
}
// Anchor snapping. If there is a coordinate change, it will dirty the component for us.
var pos = new EntityCoordinates(grid, _map.GridTileToLocal(grid, grid, tileIndices).Position);
SetCoordinates((uid, xform, meta), pos, unanchor: false);
return true;
}
[Obsolete("Use Entity<T> variants")]
public bool AnchorEntity(EntityUid uid, TransformComponent xform, MapGridComponent grid)
{
var tileIndices = _map.TileIndicesFor(grid.Owner, grid, xform.Coordinates);
return AnchorEntity(uid, xform, grid.Owner, grid, tileIndices);
}
public bool AnchorEntity(EntityUid uid)
{
return AnchorEntity(uid, XformQuery.GetComponent(uid));
}
public bool AnchorEntity(EntityUid uid, TransformComponent xform)
{
return AnchorEntity((uid, xform));
}
public bool AnchorEntity(Entity<TransformComponent> entity, Entity<MapGridComponent>? grid = null)
{
if (grid != null && grid.Value.Owner != entity.Comp.GridUid)
{
Log.Error($"Tried to anchor entity {Name(entity)} to a grid ({grid.Value.Owner}) different from its GridUid ({entity.Comp.GridUid})");
return false;
}
if (grid == null)
{
if (!TryComp(entity.Comp.GridUid, out MapGridComponent? gridComp))
return false;
grid = (entity.Comp.GridUid.Value, gridComp);
}
var tileIndices = _map.TileIndicesFor(grid.Value, grid.Value, entity.Comp.Coordinates);
return AnchorEntity(entity, grid.Value, tileIndices);
}
public void Unanchor(EntityUid uid)
{
Unanchor(uid, XformQuery.GetComponent(uid));
}
public void Unanchor(EntityUid uid, TransformComponent xform, bool setPhysics = true)
{
if (!xform._anchored)
return;
Dirty(uid, xform);
xform._anchored = false;
if (setPhysics)
_physics.TrySetBodyType(uid, BodyType.Dynamic, xform: xform);
if (xform.LifeStage < ComponentLifeStage.Initialized)
return;
if (_gridQuery.TryGetComponent(xform.GridUid, out var grid))
{
var tileIndices = _map.TileIndicesFor(xform.GridUid.Value, grid, xform.Coordinates);
_map.RemoveFromSnapGridCell(xform.GridUid.Value, grid, tileIndices, uid);
}
if (!xform.Running)
return;
var ev = new AnchorStateChangedEvent(uid, xform);
RaiseLocalEvent(uid, ref ev, true);
}
#endregion
#region Contains
/// <summary>
/// Checks whether the first entity or one of it's children is the parent of some other entity.
/// </summary>
public bool ContainsEntity(EntityUid parent, Entity<TransformComponent?> child)
{
if (!Resolve(child.Owner, ref child.Comp))
return false;
if (!child.Comp.ParentUid.IsValid())
return false;
if (parent == child.Comp.ParentUid)
return true;
if (!XformQuery.TryGetComponent(child.Comp.ParentUid, out var parentXform))
return false;
return ContainsEntity(parent, (child.Comp.ParentUid, parentXform));
}
/// <summary>
/// Checks whether the given component is the parent of the entity without having to fetch the child's
/// transform component.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsParentOf(TransformComponent parent, EntityUid child)
{
return parent._children.Contains(child);
}
#endregion
#region Component Lifetime
internal (EntityUid?, MapId) InitializeMapUid(EntityUid uid, TransformComponent xform)
{
if (xform._mapIdInitialized)
return (xform.MapUid, xform.MapID);
if (xform.ParentUid.IsValid())
{
(xform.MapUid, xform.MapID) = InitializeMapUid(xform.ParentUid, Transform(xform.ParentUid));
}
else if (_mapQuery.TryComp(uid, out var mapComp))
{
if (mapComp.MapId == MapId.Nullspace)
{
#if !EXCEPTION_TOLERANCE
throw new Exception("Transform is initialising before map ids have been assigned?");
#else
Log.Error($"Transform is initialising before map ids have been assigned?");
_map.AssignMapId((uid, mapComp));
#endif
}
xform.MapUid = uid;
xform.MapID = mapComp.MapId;
}
else
{
xform.MapUid = null;
xform.MapID = MapId.Nullspace;
}
xform._mapIdInitialized = true;
return (xform.MapUid, xform.MapID);
}
private void OnCompInit(EntityUid uid, TransformComponent component, ComponentInit args)
{
InitializeMapUid(uid, component);
// Has to be done if _parent is set from ExposeData.
if (component.ParentUid.IsValid())
{
// Note that _children is a HashSet<EntityUid>,
// so duplicate additions (which will happen) don't matter.
var parentXform = XformQuery.GetComponent(component.ParentUid);
if (parentXform.LifeStage > ComponentLifeStage.Running || LifeStage(component.ParentUid) > EntityLifeStage.MapInitialized)
{
var msg = $"Attempted to re-parent to a terminating object. Entity: {ToPrettyString(component.ParentUid)}, new parent: {ToPrettyString(uid)}";
#if EXCEPTION_TOLERANCE
Log.Error(msg);
Del(uid);
#else
throw new InvalidOperationException(msg);
#endif
}
parentXform._children.Add(uid);
}
InitializeGridUid(uid, component);
component.MatricesDirty = true;
DebugTools.Assert(component._gridUid == uid || !HasComp<MapGridComponent>(uid));
if (!component._anchored)
return;
Entity<MapGridComponent>? grid = null;
// First try find grid via parent:
if (component.GridUid == component.ParentUid && TryComp(component.ParentUid, out MapGridComponent? gridComp))
{
grid = (component.ParentUid, gridComp);
}
else
{
// Entity may not be directly parented to the grid (e.g., spawned using some relative entity coordinates)
// in that case, we attempt to attach to a grid.
var pos = new MapCoordinates(GetWorldPosition(component), component.MapID);
if (_mapManager.TryFindGridAt(pos, out var gridUid, out gridComp))
grid = (gridUid, gridComp);
}
if (grid == null)
{
Unanchor(uid, component);
return;
}
if (!AnchorEntity((uid, component), grid))
component._anchored = false;
}
internal void InitializeGridUid(
EntityUid uid,
TransformComponent xform)
{
if (xform._gridInitialized)
return;
if (_gridQuery.HasComponent(uid))
{
xform._gridUid = uid;
xform._gridInitialized = true;
return;
}
// We don't set _gridInitialized to true unless the transform (and hence entity) is already being initialized,
// as otherwise the current entity's grid component might just not have been added yet.
//
// We don't just return early, on the off chance that what is happening here is some convoluted entity
// initialization pasta, where an an entity has been attached to an un-initialized entity on an already
// initialized grid. In that case, the newly attached entity needs to be able to figure out the new grid id.
// AFAIK this shouldn't happen anymore, but might as well keep this just in case.
if (xform.LifeStage >= ComponentLifeStage.Initializing)
xform._gridInitialized = true;
if (!xform._parent.IsValid())
return;
var parentXform = XformQuery.GetComponent(xform._parent);
InitializeGridUid(xform._parent, parentXform);
xform._gridUid = parentXform._gridUid;
}
private void OnCompStartup(EntityUid uid, TransformComponent xform, ComponentStartup args)
{
// TODO PERFORMANCE remove AnchorStateChangedEvent and EntParentChangedMessage events here.
// I hate this. Apparently some entities rely on this to perform their initialization logic (e.g., power
// receivers or lights?). Those components should just do their own init logic, instead of wasting time raising
// this event on every entity that gets created.
if (xform.Anchored)
{
DebugTools.Assert(xform.ParentUid == xform.GridUid && xform.ParentUid.IsValid());
var anchorEv = new AnchorStateChangedEvent(uid, xform);
RaiseLocalEvent(uid, ref anchorEv, true);
}
// I hate this too. Once again, required for shit like containers because they CBF doing their own init logic
// and rely on parent changed messages instead. Might also be used by broadphase stuff?
var parentEv = new EntParentChangedMessage(uid, null, null, xform);
RaiseLocalEvent(uid, ref parentEv, true);
var ev = new TransformStartupEvent((uid, xform));
RaiseLocalEvent(uid, ref ev, true);
DebugTools.Assert(!xform.NoLocalRotation || xform.LocalRotation == 0, $"NoRot entity has a non-zero local rotation. entity: {ToPrettyString(uid)}");
}
#endregion
#region GridId
/// <inheritdoc cref="SetGridId(Entity{TransformComponent,MetaDataComponent},EntityUid?)"/>
public void SetGridId(EntityUid uid, TransformComponent xform, EntityUid? gridId, EntityQuery<TransformComponent>? xformQuery = null)
{
SetGridId((uid, xform, MetaData(uid)), gridId);
}
/// <summary>
/// Sets <see cref="TransformComponent.GridUid"/> for the entity and any children. Note that this does not dirty
/// the component, as this is implicitly networked via the transform hierarchy.
/// </summary>
public void SetGridId(Entity<TransformComponent, MetaDataComponent?> ent, EntityUid? gridId)
{
if (!ent.Comp1._gridInitialized || ent.Comp1._gridUid == gridId || ent.Comp1.GridUid == ent.Owner)
return;
DebugTools.Assert(!HasComp<MapGridComponent>(ent.Owner) || gridId == ent.Owner);
// ReSharper disable once ReturnValueOfPureMethodIsNotUsed
_metaQuery.ResolveInternal(ent.Owner, ref ent.Comp2);
if ((ent.Comp2!.Flags & MetaDataFlags.ExtraTransformEvents) != 0)
{
#if DEBUG
var childCount = ent.Comp1.ChildCount;
var oldParent = ent.Comp1.ParentUid;
#endif
var ev = new GridUidChangedEvent((ent.Owner, ent.Comp1, ent.Comp2), ent.Comp1._gridUid);
ent.Comp1._gridUid = gridId;
RaiseLocalEvent(ent, ref ev);
#if DEBUG
// Lets check content didn't do anything silly with the event.
DebugTools.AssertEqual(ent.Comp1._gridUid, gridId);
DebugTools.AssertEqual(ent.Comp1.ChildCount, childCount);
DebugTools.AssertEqual(ent.Comp1.ParentUid, oldParent);
#endif
}
ent.Comp1._gridUid = gridId;
foreach (var child in ent.Comp1._children)
{
SetGridId((child, XformQuery.GetComponent(child), null), gridId);
}
}
#endregion
#region Local Position
[Obsolete("use override with EntityUid")]
public void SetLocalPosition(TransformComponent xform, Vector2 value)
{
SetLocalPosition(xform.Owner, value, xform);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public virtual void SetLocalPosition(EntityUid uid, Vector2 value, TransformComponent? xform = null)
=> SetLocalPositionNoLerp(uid, value, xform);
[Obsolete("use override with EntityUid")]
public void SetLocalPositionNoLerp(TransformComponent xform, Vector2 value)
=> SetLocalPositionNoLerp(xform.Owner, value, xform);
public void SetLocalPositionNoLerp(EntityUid uid, Vector2 value, TransformComponent? xform = null)
{
if (!XformQuery.Resolve(uid, ref xform))
return;
#pragma warning disable CS0618
xform.LocalPosition = value;
#pragma warning restore CS0618
}
#endregion
#region Local Rotation
public void SetLocalRotationNoLerp(EntityUid uid, Angle value, TransformComponent? xform = null)
{
if (!XformQuery.Resolve(uid, ref xform))
return;
xform.LocalRotation = value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public virtual void SetLocalRotation(EntityUid uid, Angle value, TransformComponent? xform = null)
=> SetLocalRotationNoLerp(uid, value, xform);
[Obsolete("use override with EntityUid")]
public void SetLocalRotation(TransformComponent xform, Angle value)
{
SetLocalRotation(xform.Owner, value, xform);
}
#endregion
#region Coordinates
public void SetCoordinates(EntityUid uid, EntityCoordinates value)
{
SetCoordinates((uid, Transform(uid), MetaData(uid)), value);
}
/// <summary>
/// This sets the local position and parent of an entity.
/// </summary>
/// <param name="rotation">Final local rotation. If not specified, this will attempt to preserve world
/// rotation.</param>
/// <param name="unanchor">Whether or not to unanchor the entity before moving. Note that this will still move the
/// entity even when false. If you set this to false, you need to manually manage the grid lookup changes and ensure
/// the final position is valid</param>
public void SetCoordinates(
Entity<TransformComponent, MetaDataComponent> entity,
EntityCoordinates value,
Angle? rotation = null,
bool unanchor = true,
TransformComponent? newParent = null,
TransformComponent? oldParent = null)
{
var (uid, xform, meta) = entity;
// NOTE: This setter must be callable from before initialize.
if (xform.ParentUid == value.EntityId
&& xform._localPosition.EqualsApprox(value.Position)
&& (rotation == null || MathHelper.CloseTo(rotation.Value.Theta, xform._localRotation.Theta)))
{
return;
}
if (xform.Anchored && unanchor)
Unanchor(uid, xform);
if (value.EntityId != xform.ParentUid && value.EntityId.IsValid())
{
if (meta.EntityLifeStage >= EntityLifeStage.Terminating)
{
Log.Error($"{ToPrettyString(uid)} is attempting to move while terminating. New parent: {ToPrettyString(value.EntityId)}. Trace: {Environment.StackTrace}");
return;
}
if (TerminatingOrDeleted(value.EntityId))
{
Log.Error($"{ToPrettyString(uid)} is attempting to attach itself to a terminating entity {ToPrettyString(value.EntityId)}. Trace: {Environment.StackTrace}");
return;
}
}
var oldParentUid = xform._parent;
var oldPosition = xform._localPosition;
var oldRotation = xform._localRotation;
var oldMap = xform.MapUid;
// Set new values
Dirty(uid, xform, meta);
xform.MatricesDirty = true;
xform._localPosition = value.Position;
if (rotation != null && !xform.NoLocalRotation)
xform._localRotation = rotation.Value;
DebugTools.Assert(!xform.NoLocalRotation || xform.LocalRotation == 0);
// Perform parent change logic
if (value.EntityId != xform._parent)
{
if (value.EntityId == uid)
{
DetachEntity(uid, xform);
if (_netMan.IsServer || IsClientSide(uid))
QueueDel(uid);
throw new InvalidOperationException($"Attempted to parent an entity to itself: {ToPrettyString(uid)}");
}
if (value.EntityId.IsValid())
{
if (!XformQuery.Resolve(value.EntityId, ref newParent, false))
{
DetachEntity(uid, xform);
if (_netMan.IsServer || IsClientSide(uid))
QueueDel(uid);
throw new InvalidOperationException($"Attempted to parent entity {ToPrettyString(uid)} to non-existent entity {value.EntityId}");
}
if (newParent.LifeStage >= ComponentLifeStage.Stopping || LifeStage(value.EntityId) >= EntityLifeStage.Terminating)
{
DetachEntity(uid, xform);
if (_netMan.IsServer || IsClientSide(uid))
QueueDel(uid);
throw new InvalidOperationException($"Attempted to re-parent to a terminating object. Entity: {ToPrettyString(uid)}, new parent: {ToPrettyString(value.EntityId)}");
}
InitializeMapUid(value.EntityId, newParent);
// Check for recursive/circular transform hierarchies.
if (xform.MapUid == newParent.MapUid)
{
var recursiveUid = value.EntityId;
var recursiveXform = newParent;
while (recursiveXform.ParentUid.IsValid())
{
if (recursiveXform.ParentUid == uid)
{
if (!_gameTiming.ApplyingState)
throw new InvalidOperationException($"Attempted to parent an entity to one of its descendants! {ToPrettyString(uid)}. new parent: {ToPrettyString(value.EntityId)}");
// Client is halfway through applying server state, which can sometimes lead to a temporarily circular transform hierarchy.
// E.g., client is holding a foldable bed and predicts dropping & sitting in it -> reset to holding it -> bed is parent of player and vice versa.
// Even though its temporary, this can still cause the client to get stuck in infinite loops while applying the game state.
// So we will just break the loop by detaching to null and just trusting that the loop wasn't actually a real feature of the server state.
Log.Warning($"Encountered circular transform hierarchy while applying state for entity: {ToPrettyString(uid)}. Detaching child to null: {ToPrettyString(recursiveUid)}");
DetachEntity(recursiveUid, recursiveXform);
break;
}
recursiveUid = recursiveXform.ParentUid;
recursiveXform = XformQuery.GetComponent(recursiveUid);
}
}
}
if (xform._parent.IsValid())
XformQuery.Resolve(xform._parent, ref oldParent);
oldParent?._children.Remove(uid);
newParent?._children.Add(uid);
xform._parent = value.EntityId;
if (newParent != null)
{
// TODO PERF
// if both map & grid id change, we should simultaneously update both.
ChangeMapId(entity, newParent.MapID);
if (!xform._gridInitialized)
InitializeGridUid(uid, xform);
else
{
if (!newParent._gridInitialized)
InitializeGridUid(value.EntityId, newParent);
SetGridId(entity!, newParent.GridUid);
}
}
else
{
// TODO PERF
// if both map & grid id change, we should simultaneously update both.
ChangeMapId(entity, MapId.Nullspace);
if (!xform._gridInitialized)
InitializeGridUid(uid, xform);
else
SetGridId(entity!, null);
}
if (xform.Initialized)
{
// preserve world rotation
if (rotation == null && oldParent != null && newParent != null && !xform.NoLocalRotation)
xform._localRotation += GetWorldRotation(oldParent) - GetWorldRotation(newParent);
DebugTools.Assert(!xform.NoLocalRotation || xform.LocalRotation == 0);
}
}
if (!xform.Initialized)
return;
#if DEBUG
// If an entity is parented to the map, its grid uid should be null (unless it is itself a grid or we have a map-grid)
if (xform.ParentUid == xform.MapUid)
DebugTools.Assert(xform.GridUid == null || xform.GridUid == uid || xform.GridUid == xform.MapUid);
#endif
// No need to check for grid traversal since we've already handled it
RaiseMoveEvent(entity, oldParentUid, oldPosition, oldRotation, oldMap, checkTraversal: false);
}
public void SetCoordinates(
EntityUid uid,
TransformComponent xform,
EntityCoordinates value,
Angle? rotation = null,
bool unanchor = true,
TransformComponent? newParent = null,
TransformComponent? oldParent = null)
{
SetCoordinates((uid, xform, _metaQuery.GetComponent(uid)), value, rotation, unanchor, newParent, oldParent);
}
private void ChangeMapId(Entity<TransformComponent, MetaDataComponent> ent, MapId newMapId)
{
if (newMapId == ent.Comp1.MapID)
return;
EntityUid? newUid = newMapId == MapId.Nullspace ? null : _map.GetMap(newMapId);
bool? mapPaused = null;
// Client may be moving entities across maps due to things leaving or entering PVS range.
// In that case, we don't want to pause or unpause entities.
if (!_gameTiming.ApplyingState)
{
mapPaused = _map.IsPaused(newMapId);
_metaData.SetEntityPaused(ent.Owner, mapPaused.Value, ent.Comp2);
}
ChangeMapIdRecursive(ent, newUid, newMapId, mapPaused);
}
private void ChangeMapIdRecursive(
Entity<TransformComponent, MetaDataComponent> ent,
EntityUid? newMap,
MapId newMapId,
bool? paused)
{
if (paused is { } p)
{
_metaData.SetEntityPaused(ent.Owner, p, ent.Comp2);
}
if ((ent.Comp2.Flags & MetaDataFlags.ExtraTransformEvents) != 0)
{
#if DEBUG
var childCount = ent.Comp1.ChildCount;
var oldParent = ent.Comp1.ParentUid;
#endif
var ev = new MapUidChangedEvent(ent, ent.Comp1.MapUid, ent.Comp1.MapID);
ent.Comp1.MapUid = newMap;
ent.Comp1.MapID = newMapId;
RaiseLocalEvent(ent.Owner, ref ev);
#if DEBUG
// Lets check content didn't do anything silly with the event.
DebugTools.AssertEqual(ent.Comp1.MapUid, newMap);
DebugTools.AssertEqual(ent.Comp1.MapID, newMapId);
DebugTools.AssertEqual(ent.Comp1.ChildCount, childCount);
DebugTools.AssertEqual(ent.Comp1.ParentUid, oldParent);
#endif
}
ent.Comp1.MapUid = newMap;
ent.Comp1.MapID = newMapId;
foreach (var uid in ent.Comp1._children)
{
var child = new Entity<TransformComponent, MetaDataComponent>(uid, Transform(uid), MetaData(uid));
ChangeMapIdRecursive(child, newMap, newMapId, paused);
}
}
#endregion
#region Parent
public void ReparentChildren(EntityUid oldUid, EntityUid uid)
{
ReparentChildren(oldUid, uid, XformQuery);
}
/// <summary>
/// Re-parents all of the oldUid's children to the new entity.
/// </summary>
public void ReparentChildren(EntityUid oldUid, EntityUid uid, EntityQuery<TransformComponent> xformQuery)
{
if (oldUid == uid)
{
Log.Error($"Tried to reparent entities from the same entity, {ToPrettyString(oldUid)}");
return;
}
var oldXform = xformQuery.GetComponent(oldUid);
var xform = xformQuery.GetComponent(uid);
foreach (var child in oldXform._children.ToArray())
{
SetParent(child, xformQuery.GetComponent(child), uid, xformQuery, xform);
}
DebugTools.Assert(oldXform.ChildCount == 0);
}
public TransformComponent? GetParent(EntityUid uid)
{
return GetParent(XformQuery.GetComponent(uid));
}
public TransformComponent? GetParent(TransformComponent xform)
{
if (!xform.ParentUid.IsValid())
return null;
return XformQuery.GetComponent(xform.ParentUid);
}
public EntityUid GetParentUid(EntityUid uid)
{
return XformQuery.GetComponent(uid).ParentUid;
}
public void SetParent(EntityUid uid, EntityUid parent)
{
SetParent(uid, XformQuery.GetComponent(uid), parent, XformQuery);
}
public void SetParent(EntityUid uid, TransformComponent xform, EntityUid parent, TransformComponent? parentXform = null)
{
SetParent(uid, xform, parent, XformQuery, parentXform);
}
public void SetParent(EntityUid uid, TransformComponent xform, EntityUid parent, EntityQuery<TransformComponent> xformQuery, TransformComponent? parentXform = null)
{
DebugTools.AssertOwner(uid, xform);
if (xform.ParentUid == parent)
return;
if (!parent.IsValid())
{
DetachEntity(uid, xform);
return;
}
if (!xformQuery.Resolve(parent, ref parentXform))
return;
var (_, parRot, parInvMatrix) = GetWorldPositionRotationInvMatrix(parentXform, xformQuery);
var (pos, rot) = GetWorldPositionRotation(xform, xformQuery);
var newPos = Vector2.Transform(pos, parInvMatrix);
var newRot = rot - parRot;
SetCoordinates(uid, xform, new EntityCoordinates(parent, newPos), newRot, newParent: parentXform);
}
#endregion
#region States
public virtual void ActivateLerp(EntityUid uid, TransformComponent xform) { }
internal void OnGetState(EntityUid uid, TransformComponent component, ref ComponentGetState args)
{
DebugTools.Assert(!component.ParentUid.IsValid() || (!Deleted(component.ParentUid) && !EntityManager.IsQueuedForDeletion(component.ParentUid)));
var parent = GetNetEntity(component.ParentUid);
args.State = new TransformComponentState(
component.LocalPosition,
component.LocalRotation,
parent,
component.NoLocalRotation,
component.Anchored);
}
internal void OnHandleState(EntityUid uid, TransformComponent xform, ref ComponentHandleState args)
{
if (args.Current is TransformComponentState newState)
{
// TODO Delta-states
// If the transform component ever gets delta states, then the client state manager needs to be updated.
// Currently it explicitly looks for a "TransformComponentState" when determining an entity's parent for the
// sake of sorting the states that need to be applied base on the transform hierarchy.
var parent = EnsureEntity<TransformComponent>(newState.ParentID, uid);
var oldAnchored = xform.Anchored;
// update actual position data, if required
if (!xform.LocalPosition.EqualsApprox(newState.LocalPosition)
|| !xform.LocalRotation.EqualsApprox(newState.Rotation)
|| xform.ParentUid != parent)
{
// remove from any old grid lookups
if (xform.Anchored && TryComp(xform.ParentUid, out MapGridComponent? grid))
{
var tileIndices = _map.TileIndicesFor(xform.ParentUid, grid, xform.Coordinates);
_map.RemoveFromSnapGridCell(xform.ParentUid, grid, tileIndices, uid);
}
// Set anchor state true during the move event unless the entity wasn't and isn't being anchored. This avoids unnecessary entity lookup changes.
xform._anchored |= newState.Anchored;
// Update the action position, rotation, and parent (and hence also map, grid, etc).
SetCoordinates(uid, xform, new EntityCoordinates(parent, newState.LocalPosition), newState.Rotation, unanchor: false);
xform._anchored = newState.Anchored;
// Add to any new grid lookups. Normal entity lookups will either have been handled by the move event,
// or by the following AnchorStateChangedEvent
if (xform._anchored && xform.Initialized)
{
if (xform.ParentUid == xform.GridUid && TryComp(xform.GridUid, out MapGridComponent? newGrid))
{
var tileIndices = _map.TileIndicesFor(xform.GridUid.Value, newGrid, xform.Coordinates);
_map.AddToSnapGridCell(xform.GridUid.Value, newGrid, tileIndices, uid);
}
else
{
DebugTools.Assert("New transform state coordinates are incompatible with anchoring.");
xform._anchored = false;
}
}
}
else
{
xform.Anchored = newState.Anchored;
}
if (oldAnchored != newState.Anchored && xform.Initialized)
{
var ev = new AnchorStateChangedEvent(uid, xform);
RaiseLocalEvent(uid, ref ev, true);
}
xform._noLocalRotation = newState.NoLocalRotation;
DebugTools.Assert(xform.ParentUid == parent, "Transform state failed to set parent");
DebugTools.Assert(xform.Anchored == newState.Anchored, "Transform state failed to set anchored");
}
if (args.Next is TransformComponentState nextTransform
&& nextTransform.ParentID == GetNetEntity(xform.ParentUid))
{
xform.NextPosition = nextTransform.LocalPosition;
xform.NextRotation = nextTransform.Rotation;
ActivateLerp(uid, xform);
}
}
#endregion
#region World Matrix
[Pure]
public Matrix3x2 GetWorldMatrix(EntityUid uid)
{
return GetWorldMatrix(XformQuery.GetComponent(uid), XformQuery);
}
// Temporary until it's moved here
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Matrix3x2 GetWorldMatrix(TransformComponent component)
{
return GetWorldMatrix(component, XformQuery);
}
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Matrix3x2 GetWorldMatrix(EntityUid uid, EntityQuery<TransformComponent> xformQuery)
{
return GetWorldMatrix(xformQuery.GetComponent(uid), xformQuery);
}
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Matrix3x2 GetWorldMatrix(TransformComponent component, EntityQuery<TransformComponent> xformQuery)
{
var (pos, rot) = GetWorldPositionRotation(component, xformQuery);
return Matrix3Helpers.CreateTransform(pos, rot);
}
#endregion
#region World Position
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector2 GetWorldPosition(EntityUid uid)
{
return GetWorldPosition(XformQuery.GetComponent(uid));
}
// Temporary until it's moved here
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector2 GetWorldPosition(TransformComponent component)
{
Vector2 pos = component._localPosition;
while (component.ParentUid != component.MapUid && component.ParentUid.IsValid())
{
component = XformQuery.GetComponent(component.ParentUid);
pos = component._localRotation.RotateVec(pos) + component._localPosition;
}
return pos;
}
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector2 GetWorldPosition(EntityUid uid, EntityQuery<TransformComponent> xformQuery)
{
return GetWorldPosition(xformQuery.GetComponent(uid));
}
[Pure]
public Vector2 GetWorldPosition(TransformComponent component, EntityQuery<TransformComponent> xformQuery)
{
return GetWorldPosition(component);
}
[Pure]
public MapCoordinates GetMapCoordinates(EntityUid entity, TransformComponent? xform = null)
{
if (!XformQuery.Resolve(entity, ref xform))
return MapCoordinates.Nullspace;
return GetMapCoordinates(xform);
}
[Pure]
public MapCoordinates GetMapCoordinates(TransformComponent xform)
{
return new MapCoordinates(GetWorldPosition(xform), xform.MapID);
}
[Pure]
public MapCoordinates GetMapCoordinates(Entity<TransformComponent> entity)
{
return GetMapCoordinates(entity.Comp);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetMapCoordinates(EntityUid entity, MapCoordinates coordinates)
{
var xform = XformQuery.GetComponent(entity);
SetMapCoordinates((entity, xform), coordinates);
}
public void SetMapCoordinates(Entity<TransformComponent> entity, MapCoordinates coordinates)
{
var mapUid = _map.GetMap(coordinates.MapId);
if (!_gridQuery.HasComponent(entity) &&
_mapManager.TryFindGridAt(mapUid, coordinates.Position, out var targetGrid, out _))
{
var invWorldMatrix = GetInvWorldMatrix(targetGrid);
SetCoordinates((entity.Owner, entity.Comp, MetaData(entity.Owner)), new EntityCoordinates(targetGrid, Vector2.Transform(coordinates.Position, invWorldMatrix)));
}
else
{
SetCoordinates((entity.Owner, entity.Comp, MetaData(entity.Owner)), new EntityCoordinates(mapUid, coordinates.Position));