ARCoreFaceSubsystem.cs
13.1 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
using System;
using System.Runtime.InteropServices;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
using UnityEngine.Scripting;
using UnityEngine.XR.ARSubsystems;
namespace UnityEngine.XR.ARCore
{
/// <summary>
/// The ARCore implementation of the
/// [XRFaceSubsystem](xref:UnityEngine.XR.ARSubsystems.XRFaceSubsystem).
/// Do not create this directly. Use the
/// [SubsystemManager](xref:UnityEngine.SubsystemManager)
/// instead.
/// </summary>
[Preserve]
public class ARCoreFaceSubsystem : XRFaceSubsystem
{
/// <summary>
/// Get all the available <see cref="ARCoreFaceRegion"/>s.
/// </summary>
/// <param name="trackableId">The id associated with the face to query.</param>
/// <param name="allocator">The allocator to use if <paramref name="regions"/> requires a resize. C# Jobs are used, so the allocator
/// must be either <c>Allocator.TempJob</c> or <c>Allocator.Persistent</c>.</param>
/// <param name="regions">An array of <see cref="ARCoreFaceRegionData"/>s. If <paramref name="regions"/> is allocated
/// and the correct size, then its memory is reused. Otherwise, it is reallocated.</param>
/// <exception cref="System.InvalidOperationException">Thrown if <paramref name="allocator"/> is <c>Allocator.Temp</c>.</exception>
/// <exception cref="System.InvalidOperationException">Thrown if <paramref name="allocator"/> is <c>Allocator.None</c>.</exception>
public unsafe void GetRegionPoses(
TrackableId trackableId,
Allocator allocator,
ref NativeArray<ARCoreFaceRegionData> regions)
{
if (allocator == Allocator.Temp)
throw new InvalidOperationException("Allocator.Temp is not supported. Use Allocator.TempJob if you wish to use a temporary allocator.");
if (allocator == Allocator.None)
throw new InvalidOperationException("Allocator.None is not a valid allocator.");
int count;
var regionPtr = UnityARCore_faceTracking_acquireRegions(trackableId, out count);
if (regionPtr == null)
{
if (regions.IsCreated)
regions.Dispose();
regions = default(NativeArray<ARCoreFaceRegionData>);
return;
}
try
{
// Resize regions if necessary
if (regions.IsCreated)
{
if (regions.Length != count)
{
regions.Dispose();
regions = new NativeArray<ARCoreFaceRegionData>(count, allocator);
}
}
else
{
regions = new NativeArray<ARCoreFaceRegionData>(count, allocator);
}
new TransformPoseJob
{
regionsIn = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<FaceRegionWithARCorePose>(regionPtr, count, Allocator.None),
regionsOut = regions
}.Schedule(count, 1).Complete();
}
finally
{
UnityARCore_faceTracking_deallocateTemp(regionPtr);
}
}
// ARCore stores its poses as (rotation, position) whereas a
// UnityEngine.Pose is (position, rotation).
struct ARCorePose
{
public Quaternion rotation;
public Vector3 position;
public ARCorePose(Vector3 position, Quaternion rotation)
{
this.position = position;
this.rotation = rotation;
}
}
struct FaceRegionWithARCorePose
{
public ARCoreFaceRegion regionType;
public ARCorePose pose;
public FaceRegionWithARCorePose(ARCoreFaceRegion regionType, ARCorePose pose)
{
this.regionType = regionType;
this.pose = pose;
}
}
struct TransformPoseJob : IJobParallelFor
{
[ReadOnly]
public NativeArray<FaceRegionWithARCorePose> regionsIn;
[WriteOnly]
public NativeArray<ARCoreFaceRegionData> regionsOut;
public void Execute(int index)
{
var arcorePose = regionsIn[index].pose;
var position = arcorePose.position;
var rotation = arcorePose.rotation;
// Flip handedness
var pose = new Pose(
new Vector3(position.x, position.y, -position.z),
new Quaternion(-rotation.x, -rotation.y, rotation.z, rotation.w));
regionsOut[index] = new ARCoreFaceRegionData(
regionsIn[index].regionType, pose);
}
}
#if !UNITY_2020_2_OR_NEWER
/// <summary>
/// Creates the ARCore-specific implementation which will service the `XRFaceSubsystem`.
/// </summary>
/// <returns>A new instance of the `Provider` specific to ARCore.</returns>
protected override Provider CreateProvider() => new ARCoreProvider();
#endif
class ARCoreProvider : Provider
{
public override void Start() => UnityARCore_faceTracking_Start();
public override void Stop() => UnityARCore_faceTracking_Stop();
public override void Destroy() => UnityARCore_faceTracking_Destroy();
public unsafe override void GetFaceMesh(
TrackableId faceId,
Allocator allocator,
ref XRFaceMesh faceMesh)
{
int vertexCount, triangleCount;
void* vertexPtr, normalPtr, indexPtr, uvPtr;
if (!UnityARCore_faceTracking_TryGetFaceData(
faceId,
out vertexPtr, out normalPtr, out uvPtr, out vertexCount,
out indexPtr, out triangleCount))
{
faceMesh.Dispose();
faceMesh = default(XRFaceMesh);
return;
}
faceMesh.Resize(
vertexCount,
triangleCount,
XRFaceMesh.Attributes.Normals | XRFaceMesh.Attributes.UVs,
allocator);
var vertexJobHandle = new TransformVerticesJob
{
verticesIn = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<Vector3>(vertexPtr, vertexCount, Allocator.None),
verticesOut = faceMesh.vertices
}.Schedule(vertexCount, 32);
var normalJobHandle = new TransformVerticesJob
{
verticesIn = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<Vector3>(normalPtr, vertexCount, Allocator.None),
verticesOut = faceMesh.normals
}.Schedule(vertexCount, 32);
var uvJobHandle = new TransformUVsJob
{
uvsIn = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<Vector2>(uvPtr, vertexCount, Allocator.None),
uvsOut = faceMesh.uvs
}.Schedule(vertexCount, 32);
var indexJobHandle = new TransformIndicesJob
{
triangleIndicesIn = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<Triangle<ushort>>(indexPtr, triangleCount, Allocator.None),
// "cast" it to an array of Triangles
triangleIndicesOut = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<Triangle<int>>(faceMesh.indices.GetUnsafePtr(), triangleCount, Allocator.None)
}.Schedule(triangleCount, 32);
// Wait on all four
JobHandle.CombineDependencies(
JobHandle.CombineDependencies(vertexJobHandle, normalJobHandle),
indexJobHandle, uvJobHandle).Complete();
}
struct TransformVerticesJob : IJobParallelFor
{
[ReadOnly]
public NativeArray<Vector3> verticesIn;
[WriteOnly]
public NativeArray<Vector3> verticesOut;
public void Execute(int i)
{
verticesOut[i] = new Vector3(
verticesIn[i].x,
verticesIn[i].y,
-verticesIn[i].z);
}
}
struct TransformUVsJob : IJobParallelFor
{
[ReadOnly]
public NativeArray<Vector2> uvsIn;
[WriteOnly]
public NativeArray<Vector2> uvsOut;
public void Execute(int i)
{
uvsOut[i] = new Vector2(
uvsIn[i].x,
uvsIn[i].y);
}
}
struct Triangle<T> where T : struct
{
public T a;
public T b;
public T c;
public Triangle(T a, T b, T c)
{
this.a = a;
this.b = c;
this.c = b;
}
}
struct TransformIndicesJob : IJobParallelFor
{
[ReadOnly]
public NativeArray<Triangle<ushort>> triangleIndicesIn;
[WriteOnly]
public NativeArray<Triangle<int>> triangleIndicesOut;
public void Execute(int i)
{
triangleIndicesOut[i] = new Triangle<int>(
triangleIndicesIn[i].a,
triangleIndicesIn[i].b,
triangleIndicesIn[i].c);
}
}
public unsafe override TrackableChanges<XRFace> GetChanges(
XRFace defaultFace,
Allocator allocator)
{
void* addedPtr, updatedPtr, removedPtr;
int addedLength, updatedLength, removedLength, elementSize;
var context = UnityARCore_faceTracking_AcquireChanges(
out addedPtr, out addedLength,
out updatedPtr, out updatedLength,
out removedPtr, out removedLength,
out elementSize);
try
{
return new TrackableChanges<XRFace>(
addedPtr, addedLength,
updatedPtr, updatedLength,
removedPtr, removedLength,
defaultFace, elementSize,
allocator);
}
finally
{
UnityARCore_faceTracking_ReleaseChanges(context);
}
}
}
[DllImport("UnityARCore")]
static extern void UnityARCore_faceTracking_Start();
[DllImport("UnityARCore")]
static extern void UnityARCore_faceTracking_Stop();
[DllImport("UnityARCore")]
static extern void UnityARCore_faceTracking_Destroy();
[DllImport("UnityARCore")]
static extern unsafe bool UnityARCore_faceTracking_TryGetFaceData(
TrackableId faceId,
out void* vertexPtr, out void* normalPtr, out void* uvPtr, out int vertexCount,
out void* indexPtr, out int triangleCount);
[DllImport("UnityARCore")]
static extern unsafe void* UnityARCore_faceTracking_AcquireChanges(
out void* addedPtr, out int addedCount,
out void* updatedPtr, out int updatedCount,
out void* removedPtr, out int removedCount,
out int elementSize);
[DllImport("UnityARCore")]
static extern unsafe void UnityARCore_faceTracking_ReleaseChanges(void* changes);
[DllImport("UnityARCore")]
static extern unsafe void* UnityARCore_faceTracking_acquireRegions(
TrackableId trackableId,
out int count);
[DllImport("UnityARCore")]
static extern unsafe void UnityARCore_faceTracking_deallocateTemp(void* regions);
// this method is run on startup of the app to register this provider with XR Subsystem Manager
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
static void RegisterDescriptor()
{
if (!Api.platformAndroid || !Api.loaderPresent)
return;
var descriptorParams = new FaceSubsystemParams
{
supportsFacePose = true,
supportsFaceMeshVerticesAndIndices = true,
supportsFaceMeshUVs = true,
supportsFaceMeshNormals = true,
id = "ARCore-Face",
#if UNITY_2020_2_OR_NEWER
providerType = typeof(ARCoreFaceSubsystem.ARCoreProvider),
subsystemTypeOverride = typeof(ARCoreFaceSubsystem)
#else
subsystemImplementationType = typeof(ARCoreFaceSubsystem)
#endif
};
XRFaceSubsystemDescriptor.Create(descriptorParams);
}
}
}