summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/modules/xr/xr_frame.cc
blob: e67ff0c4ba09fcfc17ca8128d37094a69b4012d6 (plain)
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
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/modules/xr/xr_frame.h"

#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/modules/xr/xr_hit_test_source.h"
#include "third_party/blink/renderer/modules/xr/xr_input_source.h"
#include "third_party/blink/renderer/modules/xr/xr_joint_space.h"
#include "third_party/blink/renderer/modules/xr/xr_light_estimate.h"
#include "third_party/blink/renderer/modules/xr/xr_light_probe.h"
#include "third_party/blink/renderer/modules/xr/xr_plane_set.h"
#include "third_party/blink/renderer/modules/xr/xr_reference_space.h"
#include "third_party/blink/renderer/modules/xr/xr_session.h"
#include "third_party/blink/renderer/modules/xr/xr_transient_input_hit_test_source.h"
#include "third_party/blink/renderer/modules/xr/xr_view.h"
#include "third_party/blink/renderer/modules/xr/xr_viewer_pose.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"

namespace blink {

namespace {

const char kInvalidView[] =
    "XRView passed in to the method did not originate from current XRFrame.";

const char kSessionMismatch[] = "XRSpace and XRFrame sessions do not match.";

const char kCannotReportPoses[] =
    "Poses cannot be given out for the current state.";

const char kHitTestSourceUnavailable[] =
    "Unable to obtain hit test results for specified hit test source. Ensure "
    "that it was not already canceled.";

const char kCannotObtainNativeOrigin[] =
    "The operation was unable to obtain necessary information and could not be "
    "completed.";

const char kSpacesSequenceTooLarge[] =
    "Insufficient buffer capacity for pose results.";

const char kMismatchedBufferSizes[] = "Buffer sizes must be equal";

absl::optional<uint64_t> GetPlaneId(
    const device::mojom::blink::XRNativeOriginInformation& native_origin) {
  if (native_origin.is_plane_id()) {
    return native_origin.get_plane_id();
  }

  return absl::nullopt;
}

}  // namespace

constexpr char XRFrame::kInactiveFrame[];
constexpr char XRFrame::kNonAnimationFrame[];

XRFrame::XRFrame(XRSession* session, bool is_animation_frame)
    : session_(session), is_animation_frame_(is_animation_frame) {}

XRViewerPose* XRFrame::getViewerPose(XRReferenceSpace* reference_space,
                                     ExceptionState& exception_state) {
  DCHECK(reference_space);

  DVLOG(3) << __func__ << ": is_active_=" << is_active_
           << ", is_animation_frame_=" << is_animation_frame_
           << ", reference_space->ToString()=" << reference_space->ToString();

  if (!is_active_) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      kInactiveFrame);
    return nullptr;
  }

  if (!is_animation_frame_) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      kNonAnimationFrame);
    return nullptr;
  }

  // Must use a reference space created from the same session.
  if (!IsSameSession(reference_space->session(), exception_state)) {
    return nullptr;
  }

  if (!session_->CanReportPoses()) {
    exception_state.ThrowSecurityError(kCannotReportPoses);
    return nullptr;
  }

  session_->LogGetPose();

  device::mojom::blink::XRReferenceSpaceType type = reference_space->GetType();
  absl::optional<TransformationMatrix> offset_space_from_viewer =
      reference_space->OffsetFromViewer();

  // Can only update an XRViewerPose's views with an invertible matrix.
  if (!(offset_space_from_viewer && offset_space_from_viewer->IsInvertible())) {
    DVLOG(1) << __func__
             << ": offset_space_from_viewer is invalid or not invertible - "
                "returning nullptr, offset_space_from_viewer valid? "
             << (offset_space_from_viewer ? true : false);
    return nullptr;
  }

  // If the |reference_space| type is kViewer, we know that the pose is not
  // emulated. Otherwise, ask the session if the poses are emulated or not.
  return MakeGarbageCollected<XRViewerPose>(
      this, *offset_space_from_viewer,
      (type == device::mojom::blink::XRReferenceSpaceType::kViewer)
          ? false
          : session_->EmulatedPosition());
}

XRAnchorSet* XRFrame::trackedAnchors() const {
  return session_->TrackedAnchors();
}

XRPlaneSet* XRFrame::detectedPlanes(ExceptionState& exception_state) const {
  DVLOG(3) << __func__;

  if (!is_active_) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      kInactiveFrame);
    return nullptr;
  }

  return session_->GetDetectedPlanes();
}

XRLightEstimate* XRFrame::getLightEstimate(
    XRLightProbe* light_probe,
    ExceptionState& exception_state) const {
  if (!is_active_) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      kInactiveFrame);
    return nullptr;
  }

  if (!is_animation_frame_) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      kNonAnimationFrame);
    return nullptr;
  }

  if (!light_probe) {
    return nullptr;
  }

  // Must use a light probe created from the same session.
  if (!IsSameSession(light_probe->session(), exception_state)) {
    return nullptr;
  }

  return light_probe->getLightEstimate();
}

XRCPUDepthInformation* XRFrame::getDepthInformation(
    XRView* view,
    ExceptionState& exception_state) const {
  DVLOG(2) << __func__;

  if (!session_->IsFeatureEnabled(device::mojom::XRSessionFeature::DEPTH)) {
    DVLOG(2) << __func__ << ": depth sensing is not enabled on a session";
    exception_state.ThrowDOMException(
        DOMExceptionCode::kNotSupportedError,
        XRSession::kDepthSensingFeatureNotSupported);
    return nullptr;
  }

  if (!is_active_) {
    DVLOG(2) << __func__ << ": frame is not active";
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      kInactiveFrame);
    return nullptr;
  }

  if (!is_animation_frame_) {
    DVLOG(2) << __func__ << ": frame is not animating";
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      kNonAnimationFrame);
    return nullptr;
  }

  if (this != view->frame()) {
    DVLOG(2) << __func__ << ": view did not originate from the frame";
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      kInvalidView);
    return nullptr;
  }

  return session_->GetCpuDepthInformation(this, exception_state);
}

// Return an XRPose that has a transform of basespace_from_space, while
// accounting for the base pose matrix of this frame. If computing a transform
// isn't possible, return nullptr.
XRPose* XRFrame::getPose(XRSpace* space,
                         XRSpace* basespace,
                         ExceptionState& exception_state) {
  DCHECK(space);
  DCHECK(basespace);

  DVLOG(2) << __func__ << ": is_active=" << is_active_
           << ", space->ToString()=" << space->ToString()
           << ", basespace->ToString()=" << basespace->ToString();

  if (!is_active_) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      kInactiveFrame);
    return nullptr;
  }

  if (!IsSameSession(space->session(), exception_state) ||
      !IsSameSession(basespace->session(), exception_state)) {
    return nullptr;
  }

  if (!session_->CanReportPoses()) {
    exception_state.ThrowSecurityError(kCannotReportPoses);
    return nullptr;
  }

  // If the addresses match, the pose between the spaces is definitely an
  // identity & we can skip the rest of the logic. The pose is not emulated.
  if (space == basespace) {
    DVLOG(3) << __func__ << ": addresses match, returning identity";
    return MakeGarbageCollected<XRPose>(TransformationMatrix{}, false);
  }

  // If the native origins match, the pose between the spaces is fixed and
  // depends only on their offsets from the same native origin - we can compute
  // it here and skip the rest of the logic. The pose is not emulated.
  if (space->NativeOrigin() == basespace->NativeOrigin()) {
    DVLOG(3) << __func__
             << ": native origins match, returning a pose based on offesets";
    auto basespace_from_native_origin = basespace->OffsetFromNativeMatrix();
    auto native_origin_from_space = space->NativeFromOffsetMatrix();

    return MakeGarbageCollected<XRPose>(
        basespace_from_native_origin * native_origin_from_space, false);
  }

  return space->getPose(basespace);
}

void XRFrame::Deactivate() {
  is_active_ = false;
  is_animation_frame_ = false;
}

bool XRFrame::IsActive() const {
  return is_active_;
}

HeapVector<Member<XRHitTestResult>> XRFrame::getHitTestResults(
    XRHitTestSource* hit_test_source,
    ExceptionState& exception_state) {
  if (!hit_test_source ||
      !session_->ValidateHitTestSourceExists(hit_test_source)) {
    // This should only happen when hit test source was already canceled.
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      kHitTestSourceUnavailable);
    return {};
  }

  return hit_test_source->Results();
}

HeapVector<Member<XRTransientInputHitTestResult>>
XRFrame::getHitTestResultsForTransientInput(
    XRTransientInputHitTestSource* hit_test_source,
    ExceptionState& exception_state) {
  if (!hit_test_source ||
      !session_->ValidateHitTestSourceExists(hit_test_source)) {
    // This should only happen when hit test source was already canceled.
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      kHitTestSourceUnavailable);
    return {};
  }

  return hit_test_source->Results();
}

ScriptPromise XRFrame::createAnchor(ScriptState* script_state,
                                    XRRigidTransform* offset_space_from_anchor,
                                    XRSpace* space,
                                    ExceptionState& exception_state) {
  DVLOG(2) << __func__;

  if (!session_->IsFeatureEnabled(device::mojom::XRSessionFeature::ANCHORS)) {
    DVLOG(2) << __func__
             << ": feature not enabled on a session, failing anchor creation";
    exception_state.ThrowDOMException(DOMExceptionCode::kNotSupportedError,
                                      XRSession::kAnchorsFeatureNotSupported);
    return {};
  }

  if (!is_active_) {
    DVLOG(2) << __func__ << ": frame not active, failing anchor creation";
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      kInactiveFrame);
    return {};
  }

  if (!offset_space_from_anchor) {
    DVLOG(2) << __func__
             << ": offset_space_from_anchor not set, failing anchor creation";
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      XRSession::kNoRigidTransformSpecified);
    return {};
  }

  if (!space) {
    DVLOG(2) << __func__ << ": space not set, failing anchor creation";
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      XRSession::kNoSpaceSpecified);
    return {};
  }

  device::mojom::blink::XRNativeOriginInformationPtr maybe_native_origin =
      space->NativeOrigin();
  if (!maybe_native_origin) {
    DVLOG(2) << __func__ << ": native origin not set, failing anchor creation";
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      kCannotObtainNativeOrigin);
    return {};
  }

  DVLOG(3) << __func__ << ": space->ToString()=" << space->ToString();
  auto maybe_plane_id = GetPlaneId(*maybe_native_origin);

  // The passed in space may be an offset space, we need to transform the pose
  // to account for origin-offset:
  auto native_origin_from_offset_space = space->NativeFromOffsetMatrix();
  auto native_origin_from_anchor = native_origin_from_offset_space *
                                   offset_space_from_anchor->TransformMatrix();

  // We should strive to create an anchor whose location aligns with the pose
  // |offset_space_from_anchor| relative to |space|. For spaces that are
  // dynamically changing, this means we need to convert the pose to be relative
  // to stationary space, using data valid in the current frame, and change the
  // native origin relative to which the pose is expressed when communicating
  // with the device. For spaces that are classified as stationary, this
  // adjustment is not needed.

  if (space->IsStationary()) {
    // Space is considered stationary, no adjustments are needed.
    return session_->CreateAnchorHelper(script_state, native_origin_from_anchor,
                                        maybe_native_origin, maybe_plane_id,
                                        exception_state);
  }

  return CreateAnchorFromNonStationarySpace(script_state,
                                            native_origin_from_anchor, space,
                                            maybe_plane_id, exception_state);
}

ScriptPromise XRFrame::CreateAnchorFromNonStationarySpace(
    ScriptState* script_state,
    const blink::TransformationMatrix& native_origin_from_anchor,
    XRSpace* space,
    absl::optional<uint64_t> maybe_plane_id,
    ExceptionState& exception_state) {
  DVLOG(2) << __func__;

  // Space is not considered stationary - need to adjust the app-provided pose.
  // Let's ask the session about the appropriate stationary reference space:
  absl::optional<XRSession::ReferenceSpaceInformation>
      reference_space_information = session_->GetStationaryReferenceSpace();

  if (!reference_space_information) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      XRSession::kUnableToRetrieveMatrix);
    return {};
  }

  const TransformationMatrix& mojo_from_stationary_space =
      reference_space_information->mojo_from_space;

  DCHECK(mojo_from_stationary_space.IsInvertible());
  auto stationary_space_from_mojo = mojo_from_stationary_space.Inverse();

  // We now have 2 spaces - the dynamic one passed in to create anchor
  // call, and the stationary one. We also have a rigid transform
  // expressed relative to the dynamic space. Time to convert it so that it's
  // expressed relative to stationary space.

  auto mojo_from_native_origin = space->MojoFromNative();
  if (!mojo_from_native_origin) {
    DVLOG(2) << __func__ << ": native_origin not set, failing anchor creation";
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      XRSession::kUnableToRetrieveMatrix);
    return {};
  }

  auto mojo_from_anchor = *mojo_from_native_origin * native_origin_from_anchor;
  auto stationary_space_from_anchor =
      stationary_space_from_mojo * mojo_from_anchor;

  // Conversion done, make the adjusted call:
  return session_->CreateAnchorHelper(
      script_state, stationary_space_from_anchor,
      reference_space_information->native_origin, maybe_plane_id,
      exception_state);
}

bool XRFrame::IsSameSession(XRSession* space_session,
                            ExceptionState& exception_state) const {
  if (space_session != session_) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      kSessionMismatch);
    return false;
  }
  return true;
}

HeapVector<Member<XRImageTrackingResult>> XRFrame::getImageTrackingResults(
    ExceptionState& exception_state) {
  return session_->ImageTrackingResults(exception_state);
}

XRJointPose* XRFrame::getJointPose(XRJointSpace* joint,
                                   XRSpace* baseSpace,
                                   ExceptionState& exception_state) const {
  if (!is_active_) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      kInactiveFrame);
    return nullptr;
  }

  if (!IsSameSession(baseSpace->session(), exception_state) ||
      !IsSameSession(joint->session(), exception_state)) {
    return nullptr;
  }

  if (!session_->CanReportPoses()) {
    exception_state.ThrowSecurityError(kCannotReportPoses);
    return nullptr;
  }

  const XRPose* pose = joint->getPose(baseSpace);
  if (!pose) {
    return nullptr;
  }

  const float radius = joint->radius();

  return MakeGarbageCollected<XRJointPose>(pose->transform()->TransformMatrix(),
                                           radius);
}

bool XRFrame::fillJointRadii(HeapVector<Member<XRJointSpace>>& jointSpaces,
                             NotShared<DOMFloat32Array> radii,
                             ExceptionState& exception_state) const {
  if (!is_active_) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      kInactiveFrame);
    return false;
  }

  for (const auto& joint_space : jointSpaces) {
    if (!IsSameSession(joint_space->session(), exception_state)) {
      return false;
    }
  }

  if (jointSpaces.size() != radii->length()) {
    exception_state.ThrowTypeError(kMismatchedBufferSizes);
    return false;
  }

  bool all_valid = true;

  for (unsigned offset = 0; offset < jointSpaces.size(); offset++) {
    const XRJointSpace* joint_space = jointSpaces[offset];
    if (joint_space->handHasMissingPoses()) {
      radii->Data()[offset] = NAN;
      all_valid = false;
    } else {
      radii->Data()[offset] = joint_space->radius();
    }
  }

  return all_valid;
}

bool XRFrame::fillPoses(HeapVector<Member<XRSpace>>& spaces,
                        XRSpace* baseSpace,
                        NotShared<DOMFloat32Array> transforms,
                        ExceptionState& exception_state) const {
  const unsigned floats_per_transform = 16;

  if (!is_active_) {
    exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
                                      kInactiveFrame);
    return false;
  }

  for (const auto& space : spaces) {
    if (!IsSameSession(space->session(), exception_state)) {
      return false;
    }
  }

  if (!IsSameSession(baseSpace->session(), exception_state)) {
    return false;
  }

  if (spaces.size() * floats_per_transform > transforms->length()) {
    exception_state.ThrowTypeError(kSpacesSequenceTooLarge);
    return false;
  }

  if (!session_->CanReportPoses()) {
    exception_state.ThrowSecurityError(kCannotReportPoses);
    return false;
  }

  bool allValid = true;
  unsigned offset = 0;
  for (const auto& space : spaces) {
    const XRPose* pose = space->getPose(baseSpace);
    if (!pose) {
      for (unsigned i = 0; i < floats_per_transform; i++) {
        transforms->Data()[offset + i] = NAN;
      }
      allValid = false;
    } else {
      const float* const poseMatrix = pose->transform()->matrix()->Data();
      for (unsigned i = 0; i < floats_per_transform; i++) {
        transforms->Data()[offset + i] = poseMatrix[i];
      }
    }

    offset += floats_per_transform;
  }

  return allValid;
}

void XRFrame::Trace(Visitor* visitor) const {
  visitor->Trace(session_);
  ScriptWrappable::Trace(visitor);
}

}  // namespace blink