ARPointCloudManager.cs
10.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
using System;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Jobs;
using UnityEngine.XR.ARSubsystems;
namespace UnityEngine.XR.ARFoundation
{
/// <summary>
/// A manager for <see cref="ARTrackedObject"/>s. Uses the <c>XRDepthSubsystem</c>
/// to recognize and track depth data in the physical environment.
/// </summary>
[DefaultExecutionOrder(ARUpdateOrder.k_PointCloudManager)]
[RequireComponent(typeof(ARSessionOrigin))]
[DisallowMultipleComponent]
[HelpURL(HelpUrls.ApiWithNamespace + nameof(ARPointCloudManager) + ".html")]
public class ARPointCloudManager : ARTrackableManager<
XRDepthSubsystem,
XRDepthSubsystemDescriptor,
#if UNITY_2020_2_OR_NEWER
XRDepthSubsystem.Provider,
#endif
XRPointCloud,
ARPointCloud>, IRaycaster
{
[SerializeField]
[Tooltip("If not null, instantiates this prefab for each point cloud.")]
GameObject m_PointCloudPrefab;
/// <summary>
/// Getter/setter for the Point Cloud Prefab.
/// </summary>
public GameObject pointCloudPrefab
{
get => m_PointCloudPrefab;
set => m_PointCloudPrefab = value;
}
/// <summary>
/// Invoked once per frame with information about the <see cref="ARTrackedObject"/>s that have changed, i.e., been added, updated, or removed.
/// This happens just before <see cref="ARTrackedObject"/>s are destroyed, so you can set <c>ARTrackedObject.destroyOnRemoval</c> to <c>false</c>
/// from this event to suppress this behavior.
/// </summary>
public event Action<ARPointCloudChangedEventArgs> pointCloudsChanged;
/// <summary>
/// Invoked when this `MonoBehaviour` is enabled. Used to register with the <see cref="ARRaycastManager"/>.
/// </summary>
protected override void OnEnable()
{
base.OnEnable();
if (subsystem != null)
{
var raycastManager = GetComponent<ARRaycastManager>();
if (raycastManager != null)
raycastManager.RegisterRaycaster(this);
}
}
/// <summary>
/// Invoked when this `MonoBehaviour` is disabled. Used to unregister with the <see cref="ARRaycastManager"/>.
/// </summary>
protected override void OnDisable()
{
base.OnDisable();
var raycastManager = GetComponent<ARRaycastManager>();
if (raycastManager != null)
raycastManager.UnregisterRaycaster(this);
}
/// <summary>
/// The prefab that will be instantiated for each <see cref="ARPointCloud"/>. May be `null`.
/// </summary>
/// <returns>The prefab that will be instantiated for each <see cref="ARPointCloud"/>.</returns>
protected override GameObject GetPrefab() => m_PointCloudPrefab;
/// <summary>
/// The name to be used for the <c>GameObject</c> whenever a new Object is detected.
/// </summary>
protected override string gameObjectName => "ARPointCloud";
/// <summary>
/// Invoked after each point cloud is updated with new data.
/// </summary>
/// <param name="pointCloud">The <see cref="ARPointCloud"/> being updated.</param>
/// <param name="sessionRelativeData">The new data associated with the point cloud.
/// All spatial data is relative to the <see cref="ARSessionOrigin"/>.</param>
protected override void OnAfterSetSessionRelativeData(
ARPointCloud pointCloud,
XRPointCloud sessionRelativeData)
{
pointCloud.UpdateData(subsystem);
}
/// <summary>
/// Invokes the <see cref="pointCloudsChanged"/> event.
/// </summary>
/// <param name="added">A list of objects added this frame.</param>
/// <param name="updated">A list of objects updated this frame.</param>
/// <param name="removed">A list of objects removed this frame.</param>
protected override void OnTrackablesChanged(
List<ARPointCloud> added,
List<ARPointCloud> updated,
List<ARPointCloud> removed)
{
if (pointCloudsChanged != null)
{
using (new ScopedProfiler("OnPointCloudsChanged"))
pointCloudsChanged(
new ARPointCloudChangedEventArgs(
added,
updated,
removed));
}
}
/// <summary>
/// Implementation for the <c>IRaycaster</c> interface. Raycasts against every point cloud.
/// </summary>
/// <param name="rayInSessionSpace">A <c>Ray</c>, in session space.</param>
/// <param name="trackableTypeMask">The type of trackables to raycast against.
/// If <c>TrackableType.FeaturePoint</c> is not set, this method returns an empty array.</param>
/// <param name="allocator">The allocator to use for the returned <c>NativeArray</c>.</param>
/// <returns>A new <c>NativeArray</c>, allocated using <paramref name="allocator"/>, containing
/// a list of <c>XRRaycastHit</c>s of points hit by the raycast.</returns>
public NativeArray<XRRaycastHit> Raycast(
Ray rayInSessionSpace,
TrackableType trackableTypeMask,
Allocator allocator)
{
if ((trackableTypeMask & TrackableType.FeaturePoint) == TrackableType.None)
return new NativeArray<XRRaycastHit>(0, allocator);
// TODO: Expose this as a property
float raycastAngleInRadians = Mathf.Deg2Rad * 5f;
var trackableCollection = trackables;
var allHits = new NativeArray<XRRaycastHit>(0, allocator);
foreach (var pointCloud in trackableCollection)
{
// Collect the points in the point cloud
if (!pointCloud.positions.HasValue)
continue;
var points = pointCloud.positions.Value;
var sessionSpacePose = new Pose(
pointCloud.transform.localPosition,
pointCloud.transform.localRotation);
var invRotation = Quaternion.Inverse(sessionSpacePose.rotation);
// Get the ray in "point cloud space", i.e., relative to the point cloud's local transform
var ray = new Ray(
invRotation * (rayInSessionSpace.origin - sessionSpacePose.position),
invRotation * rayInSessionSpace.direction);
// Perform the raycast against each point
var infos = new NativeArray<PointCloudRaycastInfo>(points.Length, Allocator.TempJob);
var raycastJob = new PointCloudRaycastJob
{
points = points,
ray = ray,
infoOut = infos
};
var raycastHandle = raycastJob.Schedule(infos.Length, 1);
// Collect the hits
using (var hitBuffer = new NativeArray<XRRaycastHit>(infos.Length, Allocator.TempJob))
using (infos)
using (var count = new NativeArray<int>(1, Allocator.TempJob))
{
var collectResultsJob = new PointCloudRaycastCollectResultsJob
{
points = points,
infos = infos,
hits = hitBuffer,
cosineThreshold = Mathf.Cos(raycastAngleInRadians * .5f),
pose = sessionSpacePose,
trackableId = pointCloud.trackableId,
count = count
};
var collectResultsHandle = collectResultsJob.Schedule(raycastHandle);
// Wait for it to finish
collectResultsHandle.Complete();
// Copy out the results
Append(ref allHits, hitBuffer, count[0], allocator);
}
}
return allHits;
}
static void Append<T>(
ref NativeArray<T> currentArray,
NativeArray<T> arrayToAppend,
int lengthToCopy,
Allocator allocator) where T : struct
{
var dstArray = new NativeArray<T>(currentArray.Length + lengthToCopy, allocator);
NativeArray<T>.Copy(currentArray, dstArray);
NativeArray<T>.Copy(arrayToAppend, 0, dstArray, currentArray.Length, lengthToCopy);
currentArray.Dispose();
currentArray = dstArray;
}
struct PointCloudRaycastInfo
{
public float distance;
public float cosineAngleWithRay;
}
struct PointCloudRaycastJob : IJobParallelFor
{
[ReadOnly]
public NativeSlice<Vector3> points;
[WriteOnly]
public NativeArray<PointCloudRaycastInfo> infoOut;
public Ray ray;
public void Execute(int i)
{
var originToPoint = points[i] - ray.origin;
float distance = originToPoint.magnitude;
var info = new PointCloudRaycastInfo
{
distance = distance,
cosineAngleWithRay = Vector3.Dot(originToPoint, ray.direction) / distance
};
infoOut[i] = info;
}
}
struct PointCloudRaycastCollectResultsJob : IJob
{
[ReadOnly]
public NativeSlice<Vector3> points;
[ReadOnly]
public NativeArray<PointCloudRaycastInfo> infos;
[WriteOnly]
public NativeArray<XRRaycastHit> hits;
[WriteOnly]
public NativeArray<int> count;
public float cosineThreshold;
public Pose pose;
public TrackableId trackableId;
public void Execute()
{
var hitIndex = 0;
for (int i = 0; i < points.Length; ++i)
{
if (infos[i].cosineAngleWithRay >= cosineThreshold)
{
hits[hitIndex++] = new XRRaycastHit(
trackableId,
new Pose(pose.rotation * points[i] + pose.position, Quaternion.identity),
infos[i].distance,
TrackableType.FeaturePoint);
}
}
count[0] = hitIndex;
}
}
}
}