-
Notifications
You must be signed in to change notification settings - Fork 0
/
GrabInfoSlimBlock.cs
104 lines (90 loc) · 3.04 KB
/
GrabInfoSlimBlock.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
using VRage.Game.ModAPI;
using VRageMath;
using VRage.ModAPI;
using VRage.Game.Components;
using Sandbox.ModAPI;
namespace Jimmacle.Manipulator
{
public class GrabInfoSlimBlock : IGrabInfo
{
private bool dirty = false;
private bool gridChanged = false;
private Vector3D worldPosition;
private IMyCubeGrid grid;
public Vector3D LocalPosition { get; }
public Vector3D GridOffset { get; private set; }
public IMySlimBlock Block { get; }
public IMyEntity PhysicsEntity => CurrentGrid;
public Vector3D WorldPosition
{
get
{
UpdateWorldPosition();
return worldPosition;
}
}
public IMyCubeGrid CurrentGrid
{
get
{
UpdateGridOffset();
return grid;
}
}
object IGrabInfo.GrabbedObject => Block;
bool IGrabInfo.IsValid => CurrentGrid?.Physics != null && !CurrentGrid.Closed && CurrentGrid.GetCubeBlock(Block.Position) != null;
public GrabInfoSlimBlock(IMySlimBlock block, Vector3D worldGrabPos)
{
Block = block;
grid = block.CubeGrid;
LocalPosition = Vector3D.Transform(worldGrabPos, MatrixD.Invert(GetBlockWorldMatrix()));
worldPosition = worldGrabPos;
UpdateGridOffset();
UpdateWorldPosition();
}
private void OnPositionChanged(MyPositionComponentBase obj)
{
dirty = true;
}
private void UpdateWorldPosition()
{
if (dirty)
{
worldPosition = Vector3D.Transform(GridOffset, CurrentGrid.WorldMatrix);
dirty = false;
}
}
private void OnBlockRemoved(IMySlimBlock obj)
{
if (obj == Block)
{
grid.OnBlockRemoved -= OnBlockRemoved;
grid.PositionComp.OnPositionChanged -= OnPositionChanged;
grid = null;
gridChanged = true;
}
}
private void UpdateGridOffset()
{
if (gridChanged)
{
grid = Block.CubeGrid;
grid.OnBlockRemoved += OnBlockRemoved;
grid.PositionComp.OnPositionChanged += OnPositionChanged;
var currentWorldPos = Vector3D.Transform(LocalPosition, GetBlockWorldMatrix());
GridOffset = Vector3D.Transform(currentWorldPos, grid.WorldMatrixNormalizedInv);
MyAPIGateway.Utilities.ShowMessage("", GridOffset.ToString());
gridChanged = false;
}
}
public MatrixD GetBlockWorldMatrix()
{
var position = grid.GridIntegerToWorld(Block.Position);
Matrix blockMatrix;
Block.Orientation.GetMatrix(out blockMatrix);
var transform = blockMatrix * grid.WorldMatrix;
transform.Translation = position;
return transform;
}
}
}