-
Notifications
You must be signed in to change notification settings - Fork 712
Expand file tree
/
Copy pathTransformComponent.cs
More file actions
648 lines (551 loc) · 23 KB
/
Copy pathTransformComponent.cs
File metadata and controls
648 lines (551 loc) · 23 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
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Numerics;
using JetBrains.Annotations;
using Robust.Shared.Animations;
using Robust.Shared.GameStates;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Physics;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
using Robust.Shared.ViewVariables;
namespace Robust.Shared.GameObjects
{
/// <summary>
/// Stores the relative and global position and orientation of the entity.<br/>
/// This also tracks the overall transform hierarchy, which allows entities to be children of other entities
/// and move when their parent moves cheaply.
/// </summary>
/// <seealso cref="SharedTransformSystem"/>
[DenseComponent]
[RegisterComponent, NetworkedComponent]
public sealed partial class TransformComponent : Component, IComponentDebug
{
[Dependency] private IEntityManager _entMan = default!;
// Currently this field just exists for VV. In future, it might become a real field
[ViewVariables, PublicAPI]
private NetEntity NetParent => _entMan.GetNetEntity(_parent);
[DataField("parent")] internal EntityUid _parent;
[DataField("pos")] internal Vector2 _localPosition = Vector2.Zero; // holds offset from parent
[DataField("rot")] internal Angle _localRotation; // local rotation
[DataField("noRot")] internal bool _noLocalRotation;
[DataField("anchored")]
internal bool _anchored;
/// <summary>
/// Indicates this entity can traverse grids.
/// </summary>
[DataField]
public bool GridTraversal = true;
/// <summary>
/// The broadphase that this entity is currently stored on, if any.
/// </summary>
/// <remarks>
/// Maybe this should be moved to its own component eventually, but at least currently comps are not structs
/// and this data is required whenever any entity moves, so this will just save a component lookup.
/// </remarks>
[ViewVariables]
internal BroadphaseData? Broadphase;
internal bool MatricesDirty = true;
private Matrix3x2 _localMatrix = Matrix3x2.Identity;
private Matrix3x2 _invLocalMatrix = Matrix3x2.Identity;
// these should just be system methods, but existing component functions like InvWorldMatrix still rely on
// getting these so those have to be fully ECS-ed first.
public Matrix3x2 LocalMatrix
{
get
{
if (MatricesDirty)
RebuildMatrices();
return _localMatrix;
}
}
public Matrix3x2 InvLocalMatrix
{
get
{
if (MatricesDirty)
RebuildMatrices();
return _invLocalMatrix;
}
}
// used for lerping
[ViewVariables]
public Vector2? NextPosition { get; internal set; }
[ViewVariables]
public Angle? NextRotation { get; internal set; }
[ViewVariables]
public Vector2 PrevPosition { get; internal set; }
[ViewVariables]
public Angle PrevRotation { get; internal set; }
[ViewVariables] public bool ActivelyLerping;
[ViewVariables] public GameTick LastLerp = GameTick.Zero;
[ViewVariables] internal readonly HashSet<EntityUid> _children = new();
[Dependency] private IMapManager _mapManager = default!;
/// <summary>
/// Returns the index of the map which this object is on
/// </summary>
[ViewVariables]
public MapId MapID { get; internal set; }
internal bool _mapIdInitialized;
internal bool _gridInitialized;
/// <summary>
/// The EntityUid of the map which this object is on, if any.
/// </summary>
public EntityUid? MapUid { get; internal set; }
/// <summary>
/// The EntityUid of the grid which this object is on, if any.
/// </summary>
[ViewVariables]
public EntityUid? GridUid => _gridUid;
[Access(typeof(SharedTransformSystem))]
internal EntityUid? _gridUid = null;
/// <summary>
/// Disables or enables to ability to locally rotate the entity. When set it removes any local rotation.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
public bool NoLocalRotation
{
get => _noLocalRotation;
set
{
if (value)
LocalRotation = Angle.Zero;
_noLocalRotation = value;
_entMan.Dirty(Owner, this);
}
}
/// <summary>
/// Current rotation offset of the entity.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
[Animatable]
public Angle LocalRotation
{
get => _localRotation;
set
{
if(_noLocalRotation)
return;
if (_localRotation.EqualsApprox(value))
return;
var oldRotation = _localRotation;
_localRotation = value;
var meta = _entMan.GetComponent<MetaDataComponent>(Owner);
_entMan.Dirty(Owner, this, meta);
MatricesDirty = true;
if (!Initialized)
return;
_entMan.System<SharedTransformSystem>().RaiseMoveEvent((Owner, this, meta), _parent, _localPosition, oldRotation, MapUid, checkTraversal: false);
}
}
/// <summary>
/// Current world rotation of the entity.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
[Obsolete("Use the system method instead")]
public Angle WorldRotation
{
get
{
var parent = _parent;
var xformQuery = _entMan.GetEntityQuery<TransformComponent>();
var rotation = _localRotation;
while (parent.IsValid())
{
var parentXform = xformQuery.GetComponent(parent);
rotation += parentXform._localRotation;
parent = parentXform.ParentUid;
}
return rotation;
}
set
{
if (NoLocalRotation)
return;
var current = WorldRotation;
var diff = value - current;
LocalRotation += diff;
}
}
// lazy VV convenience variable.
[ViewVariables]
private TransformComponent? _parentXform => !_parent.IsValid() ? null : _entMan.GetComponent<TransformComponent>(_parent);
/// <summary>
/// The UID of the parent entity that this entity is attached to.
/// </summary>
public EntityUid ParentUid => _parent;
/// <summary>
/// Matrix for transforming points from local to world space.
/// </summary>
[Obsolete("Use the system method instead")]
public Matrix3x2 WorldMatrix
{
get
{
var xformQuery = _entMan.GetEntityQuery<TransformComponent>();
var parent = _parent;
var myMatrix = LocalMatrix;
while (parent.IsValid())
{
var parentXform = xformQuery.GetComponent(parent);
var parentMatrix = parentXform.LocalMatrix;
parent = parentXform.ParentUid;
var result = Matrix3x2.Multiply(myMatrix, parentMatrix);
myMatrix = result;
}
return myMatrix;
}
}
/// <summary>
/// Matrix for transforming points from world to local space.
/// </summary>
[Obsolete("Use the system method instead")]
public Matrix3x2 InvWorldMatrix
{
get
{
var xformQuery = _entMan.GetEntityQuery<TransformComponent>();
var parent = _parent;
var myMatrix = InvLocalMatrix;
while (parent.IsValid())
{
var parentXform = xformQuery.GetComponent(parent);
var parentMatrix = parentXform.InvLocalMatrix;
parent = parentXform.ParentUid;
var result = Matrix3x2.Multiply(parentMatrix, myMatrix);
myMatrix = result;
}
return myMatrix;
}
}
/// <summary>
/// Current position offset of the entity relative to the world.
/// Can de-parent from its parent if the parent is a grid.
/// </summary>
[Animatable]
[ViewVariables(VVAccess.ReadWrite)]
[Obsolete("Use the system method instead")]
public Vector2 WorldPosition
{
get
{
if (_parent.IsValid())
{
// parent coords to world coords
return Vector2.Transform(_localPosition, _entMan.GetComponent<TransformComponent>(ParentUid).WorldMatrix);
}
else
{
return Vector2.Zero;
}
}
set
{
if (!_parent.IsValid())
{
DebugTools.Assert("Parent is invalid while attempting to set WorldPosition - did you try to move root node?");
return;
}
// world coords to parent coords
var newPos = Vector2.Transform(value, _entMan.GetComponent<TransformComponent>(ParentUid).InvWorldMatrix);
LocalPosition = newPos;
}
}
/// <summary>
/// Position offset of this entity relative to its parent.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
public EntityCoordinates Coordinates
{
get
{
var valid = _parent.IsValid();
return new EntityCoordinates(valid ? _parent : Owner, valid ? LocalPosition : Vector2.Zero);
}
[Obsolete("Use the system's setter method instead.")]
set => _entMan.EntitySysManager.GetEntitySystem<SharedTransformSystem>().SetCoordinates(Owner, this, value);
}
/// <summary>
/// Current position offset of the entity relative to the world.
/// This is effectively a more complete version of <see cref="WorldPosition"/>
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
[Obsolete("Use TransformSystem.GetMapCoordinates")]
public MapCoordinates MapPosition => new(WorldPosition, MapID);
/// <summary>
/// Local offset of this entity relative to its parent
/// (<see cref="Parent"/> if it's not null, to <see cref="GridUid"/> otherwise).
/// </summary>
[Animatable]
[ViewVariables(VVAccess.ReadWrite)]
public Vector2 LocalPosition
{
get => _localPosition;
[Obsolete("Use the system method instead")]
set
{
if(Anchored)
return;
if (_localPosition.EqualsApprox(value))
return;
var oldParent = _parent;
var oldPos = _localPosition;
_localPosition = value;
var meta = _entMan.GetComponent<MetaDataComponent>(Owner);
_entMan.Dirty(Owner, this, meta);
MatricesDirty = true;
if (!Initialized)
return;
_entMan.System<SharedTransformSystem>().RaiseMoveEvent((Owner, this, meta), oldParent, oldPos, _localRotation, MapUid);
}
}
/// <summary>
/// Is this transform anchored to a grid tile?
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
public bool Anchored
{
get => _anchored;
[Obsolete("Use the SharedTransformSystem.AnchorEntity/Unanchor methods instead.")]
set
{
// This will be set again when the transform initializes, actually anchoring it.
if (!Initialized)
{
_anchored = value;
}
else if (value && !_anchored && _mapManager.TryFindGridAt(MapPosition, out _, out var grid))
{
_anchored = _entMan.EntitySysManager.GetEntitySystem<SharedTransformSystem>().AnchorEntity(Owner, this, grid);
}
else if (!value && _anchored)
{
// An anchored entity is always parented to the grid.
// If Transform.Anchored is true in the prototype but the entity was not spawned with a grid as the parent,
// then this will be false.
_entMan.EntitySysManager.GetEntitySystem<SharedTransformSystem>().Unanchor(Owner, this);
}
}
}
public TransformChildrenEnumerator ChildEnumerator => new(_children.GetEnumerator());
[ViewVariables] public int ChildCount => _children.Count;
[ViewVariables] public EntityUid LerpParent;
public bool PredictedLerp;
/// <summary>
/// Detaches this entity from its parent.
/// </summary>
[Obsolete("Use the system's method instead.")]
public void AttachToGridOrMap()
{
_entMan.EntitySysManager.GetEntitySystem<SharedTransformSystem>().AttachToGridOrMap(Owner, this);
}
[Obsolete("Use TransformSystem.SetParent() instead")]
public void AttachParent(EntityUid parent)
{
_entMan.EntitySysManager.GetEntitySystem<SharedTransformSystem>().SetParent(Owner, this, parent, _entMan.GetEntityQuery<TransformComponent>());
}
/// <summary>
/// Get the WorldPosition and WorldRotation of this entity faster than each individually.
/// </summary>
[Obsolete("Use the system method instead")]
public (Vector2 WorldPosition, Angle WorldRotation) GetWorldPositionRotation()
{
// Worldmatrix needs calculating anyway for worldpos so we'll just drop it.
var (worldPos, worldRot, _) = GetWorldPositionRotationMatrix();
return (worldPos, worldRot);
}
/// <summary>
/// Get the WorldPosition, WorldRotation, and WorldMatrix of this entity faster than each individually.
/// </summary>
[Obsolete("Use the system method instead")]
public (Vector2 WorldPosition, Angle WorldRotation, Matrix3x2 WorldMatrix) GetWorldPositionRotationMatrix(EntityQuery<TransformComponent> xforms)
{
var parent = _parent;
var worldRot = _localRotation;
var worldMatrix = LocalMatrix;
// By doing these all at once we can elide multiple IsValid + GetComponent calls
while (parent.IsValid())
{
var xform = xforms.GetComponent(parent);
worldRot += xform.LocalRotation;
var parentMatrix = xform.LocalMatrix;
var result = Matrix3x2.Multiply(worldMatrix, parentMatrix);
worldMatrix = result;
parent = xform.ParentUid;
}
var worldPosition = worldMatrix.Translation;
return (worldPosition, worldRot, worldMatrix);
}
/// <summary>
/// Get the WorldPosition, WorldRotation, and WorldMatrix of this entity faster than each individually.
/// </summary>
[Obsolete("Use the system method instead")]
public (Vector2 WorldPosition, Angle WorldRotation, Matrix3x2 WorldMatrix) GetWorldPositionRotationMatrix()
{
var xforms = _entMan.GetEntityQuery<TransformComponent>();
return GetWorldPositionRotationMatrix(xforms);
}
/// <summary>
/// Get the WorldPosition, WorldRotation, and InvWorldMatrix of this entity faster than each individually.
/// </summary>
[Obsolete("Use the system method instead")]
public (Vector2 WorldPosition, Angle WorldRotation, Matrix3x2 InvWorldMatrix) GetWorldPositionRotationInvMatrix(EntityQuery<TransformComponent> xformQuery)
{
var (worldPos, worldRot, _, invWorldMatrix) = GetWorldPositionRotationMatrixWithInv(xformQuery);
return (worldPos, worldRot, invWorldMatrix);
}
/// <summary>
/// Get the WorldPosition, WorldRotation, WorldMatrix, and InvWorldMatrix of this entity faster than each individually.
/// </summary>
[Obsolete("Use the system method instead")]
public (Vector2 WorldPosition, Angle WorldRotation, Matrix3x2 WorldMatrix, Matrix3x2 InvWorldMatrix) GetWorldPositionRotationMatrixWithInv()
{
var xformQuery = _entMan.GetEntityQuery<TransformComponent>();
return GetWorldPositionRotationMatrixWithInv(xformQuery);
}
/// <summary>
/// Get the WorldPosition, WorldRotation, WorldMatrix, and InvWorldMatrix of this entity faster than each individually.
/// </summary>
[Obsolete("Use the system method instead")]
public (Vector2 WorldPosition, Angle WorldRotation, Matrix3x2 WorldMatrix, Matrix3x2 InvWorldMatrix) GetWorldPositionRotationMatrixWithInv(EntityQuery<TransformComponent> xformQuery)
{
var parent = _parent;
var worldRot = _localRotation;
var invMatrix = InvLocalMatrix;
var worldMatrix = LocalMatrix;
// By doing these all at once we can avoid multiple IsValid + GetComponent calls
while (parent.IsValid())
{
var xform = xformQuery.GetComponent(parent);
worldRot += xform.LocalRotation;
var parentMatrix = xform.LocalMatrix;
var result = Matrix3x2.Multiply(worldMatrix, parentMatrix);
worldMatrix = result;
var parentInvMatrix = xform.InvLocalMatrix;
var invResult = Matrix3x2.Multiply(parentInvMatrix, invMatrix);
invMatrix = invResult;
parent = xform.ParentUid;
}
var worldPosition = worldMatrix.Translation;
return (worldPosition, worldRot, worldMatrix, invMatrix);
}
public void RebuildMatrices()
{
MatricesDirty = false;
if (!_parent.IsValid()) // Root Node
{
_localMatrix = Matrix3x2.Identity;
_invLocalMatrix = Matrix3x2.Identity;
}
_localMatrix = Matrix3Helpers.CreateTransform(_localPosition, _localRotation);
_invLocalMatrix = Matrix3Helpers.CreateInverseTransform(_localPosition, _localRotation);
}
public string GetDebugString()
{
return $"pos/rot/wpos/wrot: {Coordinates}/{LocalRotation}/{WorldPosition}/{WorldRotation}";
}
}
/// <summary>
/// Raised directed at an entity whenever is position or rotation changes relative to their parent, or if their
/// parent changed. Note that this event does not get broadcast. If you need to receive information about ALL
/// move events, subscribe to the <see cref="SharedTransformSystem.OnGlobalMoveEvent"/>.
/// </summary>
[ByRefEvent]
public readonly struct MoveEvent(
Entity<TransformComponent, MetaDataComponent> entity,
EntityCoordinates oldPos,
EntityCoordinates newPos,
Angle oldRotation,
Angle newRotation)
{
public readonly Entity<TransformComponent, MetaDataComponent> Entity = entity;
public readonly EntityCoordinates OldPosition = oldPos;
public readonly EntityCoordinates NewPosition = newPos;
public readonly Angle OldRotation = oldRotation;
public readonly Angle NewRotation = newRotation;
public EntityUid Sender => Entity.Owner;
public TransformComponent Component => Entity.Comp1;
public bool ParentChanged => NewPosition.EntityId != OldPosition.EntityId;
}
public struct TransformChildrenEnumerator : IDisposable
{
private HashSet<EntityUid>.Enumerator _children;
public TransformChildrenEnumerator(HashSet<EntityUid>.Enumerator children)
{
_children = children;
}
public bool MoveNext(out EntityUid child)
{
if (!_children.MoveNext())
{
child = default;
return false;
}
child = _children.Current;
return true;
}
public void Dispose()
{
_children.Dispose();
}
}
/// <summary>
/// Raised when the Anchor state of the transform is changed.
/// </summary>
[ByRefEvent]
public readonly struct AnchorStateChangedEvent(
EntityUid entity,
TransformComponent transform,
bool detaching = false)
{
public readonly TransformComponent Transform = transform;
public EntityUid Entity { get; } = entity;
public bool Anchored => Transform.Anchored;
/// <summary>
/// If true, the entity is being detached to null-space
/// </summary>
public readonly bool Detaching = detaching;
}
/// <summary>
/// Raised when an entity is re-anchored to another grid.
/// </summary>
[ByRefEvent]
public readonly struct ReAnchorEvent
{
public readonly EntityUid Entity;
public readonly EntityUid OldGrid;
public readonly EntityUid Grid;
public readonly TransformComponent Xform;
/// <summary>
/// Tile on both the old and new grid being re-anchored.
/// </summary>
public readonly Vector2i TilePos;
public ReAnchorEvent(EntityUid uid, EntityUid oldGrid, EntityUid grid, Vector2i tilePos, TransformComponent xform)
{
Entity = uid;
OldGrid = oldGrid;
Grid = grid;
TilePos = tilePos;
Xform = xform;
}
}
/// <summary>
/// Data used to store information about the broad-phase that any given entity is currently on.
/// </summary>
/// <remarks>
/// A null value means that this entity is simply not on a broadphase (e.g., in null-space or in a container).
/// An invalid entity UID indicates that this entity has intentionally been removed from broadphases and should
/// not automatically be re-added by movement events.
/// </remarks>
internal record struct BroadphaseData(EntityUid Uid, bool CanCollide, bool Static)
{
public bool IsValid() => Uid.IsValid();
public bool Valid => IsValid();
public static readonly BroadphaseData Invalid = default;
// TODO include MapId if ever grids are allowed to enter null-space (leave PVS).
}
}