Debian Codegraph @

testing/web-platform/tests/resources/chromium/webxr-test.js

raw
1 import * as vrMojom from '/gen/device/vr/public/mojom/vr_service.mojom.m.js';
2 import * as xrSessionMojom from '/gen/device/vr/public/mojom/xr_session.mojom.m.js';
3 import {GamepadHand, GamepadMapping} from '/gen/device/gamepad/public/mojom/gamepad.mojom.m.js';
4
5 // This polyfill library implements the WebXR Test API as specified here:
6 // https://github.com/immersive-web/webxr-test-api
7
8 const defaultMojoFromStage = {
9 matrix: [1, 0, 0, 0,
10 0, 1, 0, 0,
11 0, 0, 1, 0,
12 0, -1.65, 0, 1]
13 };
14 const default_stage_parameters = {
15 mojoFromStage: defaultMojoFromStage,
16 bounds: null
17 };
18
19 const default_framebuffer_scale = 0.7;
20
21 function getMatrixFromTransform(transform) {
22 const x = transform.orientation[0];
23 const y = transform.orientation[1];
24 const z = transform.orientation[2];
25 const w = transform.orientation[3];
26
27 const m11 = 1.0 - 2.0 * (y * y + z * z);
28 const m21 = 2.0 * (x * y + z * w);
29 const m31 = 2.0 * (x * z - y * w);
30
31 const m12 = 2.0 * (x * y - z * w);
32 const m22 = 1.0 - 2.0 * (x * x + z * z);
33 const m32 = 2.0 * (y * z + x * w);
34
35 const m13 = 2.0 * (x * z + y * w);
36 const m23 = 2.0 * (y * z - x * w);
37 const m33 = 1.0 - 2.0 * (x * x + y * y);
38
39 const m14 = transform.position[0];
40 const m24 = transform.position[1];
41 const m34 = transform.position[2];
42
43 // Column-major linearized order is expected.
44 return [m11, m21, m31, 0,
45 m12, m22, m32, 0,
46 m13, m23, m33, 0,
47 m14, m24, m34, 1];
48 }
49
50 function getPoseFromTransform(transform) {
51 const [px, py, pz] = transform.position;
52 const [ox, oy, oz, ow] = transform.orientation;
53 return {
54 position: {x: px, y: py, z: pz},
55 orientation: {x: ox, y: oy, z: oz, w: ow},
56 };
57 }
58
59 function composeGFXTransform(fakeTransformInit) {
60 return {matrix: getMatrixFromTransform(fakeTransformInit)};
61 }
62
63 // Value equality for camera image init objects - they must contain `width` &
64 // `height` properties and may contain `pixels` property.
65 function isSameCameraImageInit(rhs, lhs) {
66 return lhs.width === rhs.width && lhs.height === rhs.height && lhs.pixels === rhs.pixels;
67 }
68
69 class ChromeXRTest {
70 constructor() {
71 this.mockVRService_ = new MockVRService();
72 }
73
74 // WebXR Test API
75 simulateDeviceConnection(init_params) {
76 return Promise.resolve(this.mockVRService_._addRuntime(init_params));
77 }
78
79 disconnectAllDevices() {
80 this.mockVRService_._removeAllRuntimes();
81 return Promise.resolve();
82 }
83
84 simulateUserActivation(callback) {
85 if (window.top !== window) {
86 // test_driver.click only works for the toplevel frame. This alternate
87 // Chrome-specific method is sufficient for starting an XR session in an
88 // iframe, and is used in platform-specific tests.
89 //
90 // TODO(https://github.com/web-platform-tests/wpt/issues/20282): use
91 // a cross-platform method if available.
92 xr_debug('simulateUserActivation', 'use eventSender');
93 document.addEventListener('click', callback);
94 eventSender.mouseMoveTo(0, 0);
95 eventSender.mouseDown();
96 eventSender.mouseUp();
97 document.removeEventListener('click', callback);
98 return;
99 }
100 const button = document.createElement('button');
101 button.textContent = 'click to continue test';
102 button.style.display = 'block';
103 button.style.fontSize = '20px';
104 button.style.padding = '10px';
105 button.onclick = () => {
106 callback();
107 document.body.removeChild(button);
108 };
109 document.body.appendChild(button);
110 test_driver.click(button);
111 }
112
113 // Helper method leveraged by chrome-specific setups.
114 Debug(name, msg) {
115 console.log(new Date().toISOString() + ' DEBUG[' + name + '] ' + msg);
116 }
117 }
118
119 // Mocking class definitions
120
121 // Mock service implements the VRService mojo interface.
122 class MockVRService {
123 constructor() {
124 this.receiver_ = new vrMojom.VRServiceReceiver(this);
125 this.runtimes_ = [];
126
127 this.interceptor_ =
128 new MojoInterfaceInterceptor(vrMojom.VRService.$interfaceName);
129 this.interceptor_.oninterfacerequest =
130 e => this.receiver_.$.bindHandle(e.handle);
131 this.interceptor_.start();
132 }
133
134 // WebXR Test API Implementation Helpers
135 _addRuntime(fakeDeviceInit) {
136 const runtime = new MockRuntime(fakeDeviceInit, this);
137 this.runtimes_.push(runtime);
138
139 if (this.client_) {
140 this.client_.onDeviceChanged();
141 }
142
143 return runtime;
144 }
145
146 _removeAllRuntimes() {
147 if (this.client_) {
148 this.client_.onDeviceChanged();
149 }
150
151 this.runtimes_ = [];
152 }
153
154 _removeRuntime(device) {
155 const index = this.runtimes_.indexOf(device);
156 if (index >= 0) {
157 this.runtimes_.splice(index, 1);
158 if (this.client_) {
159 this.client_.onDeviceChanged();
160 }
161 }
162 }
163
164 // VRService overrides
165 setClient(client) {
166 if (this.client_) {
167 throw new Error("setClient should only be called once");
168 }
169
170 this.client_ = client;
171 }
172
173 requestSession(sessionOptions) {
174 const requests = [];
175 // Request a session from all the runtimes.
176 for (let i = 0; i < this.runtimes_.length; i++) {
177 requests[i] = this.runtimes_[i]._requestRuntimeSession(sessionOptions);
178 }
179
180 return Promise.all(requests).then((results) => {
181 // Find and return the first successful result.
182 for (let i = 0; i < results.length; i++) {
183 if (results[i].session) {
184 // Construct a dummy metrics recorder
185 const metricsRecorderPtr = new vrMojom.XRSessionMetricsRecorderRemote();
186 metricsRecorderPtr.$.bindNewPipeAndPassReceiver().handle.close();
187
188 const success = {
189 session: results[i].session,
190 metricsRecorder: metricsRecorderPtr,
191 };
192
193 return {result: {success}};
194 }
195 }
196
197 // If there were no successful results, returns a null session.
198 return {
199 result: {failureReason: xrSessionMojom.RequestSessionError.NO_RUNTIME_FOUND}
200 };
201 });
202 }
203
204 supportsSession(sessionOptions) {
205 const requests = [];
206 // Check supports on all the runtimes.
207 for (let i = 0; i < this.runtimes_.length; i++) {
208 requests[i] = this.runtimes_[i]._runtimeSupportsSession(sessionOptions);
209 }
210
211 return Promise.all(requests).then((results) => {
212 // Find and return the first successful result.
213 for (let i = 0; i < results.length; i++) {
214 if (results[i].supportsSession) {
215 return results[i];
216 }
217 }
218
219 // If there were no successful results, returns false.
220 return {supportsSession: false};
221 });
222 }
223
224 exitPresent() {
225 return Promise.resolve();
226 }
227
228 setFramesThrottled(throttled) {
229 this.setFramesThrottledImpl(throttled);
230 }
231
232 // We cannot override the mojom interceptors via the prototype; so this method
233 // and the above indirection exist to allow overrides by internal code.
234 setFramesThrottledImpl(throttled) {}
235
236 // Only handles asynchronous calls to makeXrCompatible. Synchronous calls are
237 // not supported in Javascript.
238 makeXrCompatible() {
239 if (this.runtimes_.length == 0) {
240 return {
241 xrCompatibleResult: vrMojom.XrCompatibleResult.kNoDeviceAvailable
242 };
243 }
244 return {xrCompatibleResult: vrMojom.XrCompatibleResult.kAlreadyCompatible};
245 }
246 }
247
248 class FakeXRAnchorController {
249 constructor() {
250 // Private properties.
251 this.device_ = null;
252 this.id_ = null;
253 this.dirty_ = true;
254
255 // Properties backing up public attributes / methods.
256 this.deleted_ = false;
257 this.paused_ = false;
258 this.anchorOrigin_ = XRMathHelper.identity();
259 }
260
261 // WebXR Test API (Anchors Extension)
262 get deleted() {
263 return this.deleted_;
264 }
265
266 pauseTracking() {
267 if(!this.paused_) {
268 this.paused_ = true;
269 this.dirty_ = true;
270 }
271 }
272
273 resumeTracking() {
274 if(this.paused_) {
275 this.paused_ = false;
276 this.dirty_ = true;
277 }
278 }
279
280 stopTracking() {
281 if(!this.deleted_) {
282 this.device_._deleteAnchorController(this.id_);
283
284 this.deleted_ = true;
285 this.dirty_ = true;
286 }
287 }
288
289 setAnchorOrigin(anchorOrigin) {
290 this.anchorOrigin_ = getMatrixFromTransform(anchorOrigin);
291 this.dirty_ = true;
292 }
293
294 // Internal implementation:
295 set id(value) {
296 this.id_ = value;
297 }
298
299 set device(value) {
300 this.device_ = value;
301 }
302
303 get dirty() {
304 return this.dirty_;
305 }
306
307 get paused() {
308 return this.paused_;
309 }
310
311 _markProcessed() {
312 this.dirty_ = false;
313 }
314
315 _getAnchorOrigin() {
316 return this.anchorOrigin_;
317 }
318 }
319
320 // Implements XRFrameDataProvider and XRPresentationProvider. Maintains a mock
321 // for XRPresentationProvider. Implements FakeXRDevice test API.
322 class MockRuntime {
323 // Mapping from string feature names to the corresponding mojo types.
324 // This is exposed as a member for extensibility.
325 static _featureToMojoMap = {
326 'viewer': xrSessionMojom.XRSessionFeature.REF_SPACE_VIEWER,
327 'local': xrSessionMojom.XRSessionFeature.REF_SPACE_LOCAL,
328 'local-floor': xrSessionMojom.XRSessionFeature.REF_SPACE_LOCAL_FLOOR,
329 'bounded-floor': xrSessionMojom.XRSessionFeature.REF_SPACE_BOUNDED_FLOOR,
330 'unbounded': xrSessionMojom.XRSessionFeature.REF_SPACE_UNBOUNDED,
331 'hit-test': xrSessionMojom.XRSessionFeature.HIT_TEST,
332 'dom-overlay': xrSessionMojom.XRSessionFeature.DOM_OVERLAY,
333 'light-estimation': xrSessionMojom.XRSessionFeature.LIGHT_ESTIMATION,
334 'anchors': xrSessionMojom.XRSessionFeature.ANCHORS,
335 'depth-sensing': xrSessionMojom.XRSessionFeature.DEPTH,
336 'secondary-views': xrSessionMojom.XRSessionFeature.SECONDARY_VIEWS,
337 'camera-access': xrSessionMojom.XRSessionFeature.CAMERA_ACCESS,
338 'layers': xrSessionMojom.XRSessionFeature.LAYERS,
339 };
340
341 static _sessionModeToMojoMap = {
342 "inline": xrSessionMojom.XRSessionMode.kInline,
343 "immersive-vr": xrSessionMojom.XRSessionMode.kImmersiveVr,
344 "immersive-ar": xrSessionMojom.XRSessionMode.kImmersiveAr,
345 };
346
347 static _environmentBlendModeToMojoMap = {
348 "opaque": vrMojom.XREnvironmentBlendMode.kOpaque,
349 "alpha-blend": vrMojom.XREnvironmentBlendMode.kAlphaBlend,
350 "additive": vrMojom.XREnvironmentBlendMode.kAdditive,
351 };
352
353 static _interactionModeToMojoMap = {
354 "screen-space": vrMojom.XRInteractionMode.kScreenSpace,
355 "world-space": vrMojom.XRInteractionMode.kWorldSpace,
356 };
357
358 static _depthTypeToMojoMap = {
359 "raw": xrSessionMojom.XRDepthType.kRawDepth,
360 "smooth": xrSessionMojom.XRDepthType.kSmoothDepth,
361 };
362
363 static _depthUsageToMojoMap = {
364 "cpu-optimized": xrSessionMojom.XRDepthUsage.kCPUOptimized,
365 "gpu-optimized": xrSessionMojom.XRDepthUsage.kGPUOptimized,
366 };
367
368 static _depthDataFormatToMojoMap = {
369 "luminance-alpha": xrSessionMojom.XRDepthDataFormat.kLuminanceAlpha,
370 "float32": xrSessionMojom.XRDepthDataFormat.kFloat32,
371 "unsigned-short": xrSessionMojom.XRDepthDataFormat.kUnsignedShort,
372 };
373
374
375 constructor(fakeDeviceInit, service) {
376 this.sessionClient_ = null;
377 this.presentation_provider_ = new MockXRPresentationProvider();
378
379 this.pose_ = null;
380 this.next_frame_id_ = 0;
381 this.bounds_ = null;
382 this.send_mojo_space_reset_ = false;
383 this.stageParameters_ = null;
384 this.stageParametersId_ = 1;
385
386 this.service_ = service;
387
388 this.framesOfReference = {};
389
390 this.input_sources_ = new Map();
391 this.next_input_source_index_ = 1;
392
393 // Currently active hit test subscriptons.
394 this.hitTestSubscriptions_ = new Map();
395 // Currently active transient hit test subscriptions.
396 this.transientHitTestSubscriptions_ = new Map();
397 // ID of the next subscription to be assigned.
398 this.next_hit_test_id_ = 1n;
399
400 this.anchor_controllers_ = new Map();
401 // ID of the next anchor to be assigned.
402 this.next_anchor_id_ = 1n;
403 // Anchor creation callback (initially null, can be set by tests).
404 this.anchor_creation_callback_ = null;
405
406 this.depthSensingData_ = null;
407 this.depthSensingDataDirty_ = false;
408
409 let supportedModes = [];
410 if (fakeDeviceInit.supportedModes) {
411 supportedModes = fakeDeviceInit.supportedModes.slice();
412 if (fakeDeviceInit.supportedModes.length === 0) {
413 supportedModes = ["inline"];
414 }
415 } else {
416 // Back-compat mode.
417 console.warn("Please use `supportedModes` to signal which modes are supported by this device.");
418 if (fakeDeviceInit.supportsImmersive == null) {
419 throw new TypeError("'supportsImmersive' must be set");
420 }
421
422 supportedModes = ["inline"];
423 if (fakeDeviceInit.supportsImmersive) {
424 supportedModes.push("immersive-vr");
425 }
426 }
427
428 this.supportedModes_ = this._convertModesToEnum(supportedModes);
429 if (this.supportedModes_.length == 0) {
430 console.error("Device has empty supported modes array!");
431 throw new InvalidStateError();
432 }
433
434 if (fakeDeviceInit.viewerOrigin != null) {
435 this.setViewerOrigin(fakeDeviceInit.viewerOrigin);
436 }
437
438 if (fakeDeviceInit.floorOrigin != null) {
439 this.setFloorOrigin(fakeDeviceInit.floorOrigin);
440 }
441
442 if (fakeDeviceInit.world) {
443 this.setWorld(fakeDeviceInit.world);
444 }
445
446 if (fakeDeviceInit.depthSensingData) {
447 this.setDepthSensingData(fakeDeviceInit.depthSensingData);
448 }
449
450 this.defaultFramebufferScale_ = default_framebuffer_scale;
451 this.enviromentBlendMode_ = this._convertBlendModeToEnum(fakeDeviceInit.environmentBlendMode);
452 this.interactionMode_ = this._convertInteractionModeToEnum(fakeDeviceInit.interactionMode);
453
454 // This appropriately handles if the coordinates are null
455 this.setBoundsGeometry(fakeDeviceInit.boundsCoordinates);
456
457 this.setViews(fakeDeviceInit.views, fakeDeviceInit.secondaryViews);
458
459 this._setDepthSupport(fakeDeviceInit.depthSupport || {});
460
461 // Need to support webVR which doesn't have a notion of features
462 this._setFeatures(fakeDeviceInit.supportedFeatures || []);
463 }
464
465 // WebXR Test API
466 setViews(primaryViews, secondaryViews) {
467 this.cameraImage_ = null;
468 this.primaryViews_ = [];
469 this.secondaryViews_ = [];
470 let xOffset = 0;
471 if (primaryViews) {
472 this.primaryViews_ = [];
473 xOffset = this._setViews(primaryViews, xOffset, this.primaryViews_);
474 const cameraImage = this._findCameraImage(primaryViews);
475
476 if (cameraImage) {
477 this.cameraImage_ = cameraImage;
478 }
479 }
480
481 if (secondaryViews) {
482 this.secondaryViews_ = [];
483 this._setViews(secondaryViews, xOffset, this.secondaryViews_);
484 const cameraImage = this._findCameraImage(secondaryViews);
485
486 if (cameraImage) {
487 if (!isSameCameraImageInit(this.cameraImage_, cameraImage)) {
488 throw new Error("If present, camera resolutions on each view must match each other!"
489 + " Secondary views' camera doesn't match primary views.");
490 }
491
492 this.cameraImage_ = cameraImage;
493 }
494 }
495 }
496
497 disconnect() {
498 this.service_._removeRuntime(this);
499 this.presentation_provider_._close();
500 if (this.sessionClient_) {
501 this.sessionClient_.$.close();
502 this.sessionClient_ = null;
503 }
504
505 return Promise.resolve();
506 }
507
508 setViewerOrigin(origin, emulatedPosition = false) {
509 const p = origin.position;
510 const q = origin.orientation;
511 this.pose_ = {
512 orientation: { x: q[0], y: q[1], z: q[2], w: q[3] },
513 position: { x: p[0], y: p[1], z: p[2] },
514 emulatedPosition: emulatedPosition,
515 angularVelocity: null,
516 linearVelocity: null,
517 angularAcceleration: null,
518 linearAcceleration: null,
519 inputState: null,
520 poseIndex: 0
521 };
522 }
523
524 clearViewerOrigin() {
525 this.pose_ = null;
526 }
527
528 setFloorOrigin(floorOrigin) {
529 if (!this.stageParameters_) {
530 this.stageParameters_ = default_stage_parameters;
531 this.stageParameters_.bounds = this.bounds_;
532 }
533
534 // floorOrigin is passed in as mojoFromStage.
535 this.stageParameters_.mojoFromStage =
536 {matrix: getMatrixFromTransform(floorOrigin)};
537
538 this._onStageParametersUpdated();
539 }
540
541 clearFloorOrigin() {
542 if (this.stageParameters_) {
543 this.stageParameters_ = null;
544 this._onStageParametersUpdated();
545 }
546 }
547
548 setBoundsGeometry(bounds) {
549 if (bounds == null) {
550 this.bounds_ = null;
551 } else if (bounds.length < 3) {
552 throw new Error("Bounds must have a length of at least 3");
553 } else {
554 this.bounds_ = bounds;
555 }
556
557 // We can only set bounds if we have stageParameters set; otherwise, we
558 // don't know the transform from local space to bounds space.
559 // We'll cache the bounds so that they can be set in the future if the
560 // floorLevel transform is set, but we won't update them just yet.
561 if (this.stageParameters_) {
562 this.stageParameters_.bounds = this.bounds_;
563 this._onStageParametersUpdated();
564 }
565 }
566
567 simulateResetPose() {
568 this.send_mojo_space_reset_ = true;
569 }
570
571 simulateVisibilityChange(visibilityState) {
572 let mojoState = null;
573 switch (visibilityState) {
574 case "visible":
575 mojoState = vrMojom.XRVisibilityState.VISIBLE;
576 break;
577 case "visible-blurred":
578 mojoState = vrMojom.XRVisibilityState.VISIBLE_BLURRED;
579 break;
580 case "hidden":
581 mojoState = vrMojom.XRVisibilityState.HIDDEN;
582 break;
583 }
584 if (mojoState && this.sessionClient_) {
585 this.sessionClient_.onVisibilityStateChanged(mojoState);
586 }
587 }
588
589 simulateInputSourceConnection(fakeInputSourceInit) {
590 const index = this.next_input_source_index_;
591 this.next_input_source_index_++;
592
593 const source = new MockXRInputSource(fakeInputSourceInit, index, this);
594 this.input_sources_.set(index, source);
595 return source;
596 }
597
598 // WebXR Test API Hit Test extensions
599 setWorld(world) {
600 this.world_ = world;
601 }
602
603 clearWorld() {
604 this.world_ = null;
605 }
606
607 // WebXR Test API Anchor extensions
608 setAnchorCreationCallback(callback) {
609 this.anchor_creation_callback_ = callback;
610 }
611
612 setHitTestSourceCreationCallback(callback) {
613 this.hit_test_source_creation_callback_ = callback;
614 }
615
616 // WebXR Test API Lighting estimation extensions
617 setLightEstimate(fakeXrLightEstimateInit) {
618 if (!fakeXrLightEstimateInit.sphericalHarmonicsCoefficients) {
619 throw new TypeError("sphericalHarmonicsCoefficients must be set");
620 }
621
622 if (fakeXrLightEstimateInit.sphericalHarmonicsCoefficients.length != 27) {
623 throw new TypeError("Must supply all 27 sphericalHarmonicsCoefficients");
624 }
625
626 if (fakeXrLightEstimateInit.primaryLightDirection && fakeXrLightEstimateInit.primaryLightDirection.w != 0) {
627 throw new TypeError("W component of primaryLightDirection must be 0");
628 }
629
630 if (fakeXrLightEstimateInit.primaryLightIntensity && fakeXrLightEstimateInit.primaryLightIntensity.w != 1) {
631 throw new TypeError("W component of primaryLightIntensity must be 1");
632 }
633
634 // If the primaryLightDirection or primaryLightIntensity aren't set, we need to set them
635 // to the defaults that the spec expects. ArCore will either give us everything or nothing,
636 // so these aren't nullable on the mojom.
637 if (!fakeXrLightEstimateInit.primaryLightDirection) {
638 fakeXrLightEstimateInit.primaryLightDirection = { x: 0.0, y: 1.0, z: 0.0, w: 0.0 };
639 }
640
641 if (!fakeXrLightEstimateInit.primaryLightIntensity) {
642 fakeXrLightEstimateInit.primaryLightIntensity = { x: 0.0, y: 0.0, z: 0.0, w: 1.0 };
643 }
644
645 let c = fakeXrLightEstimateInit.sphericalHarmonicsCoefficients;
646
647 this.light_estimate_ = {
648 lightProbe: {
649 // XRSphereicalHarmonics
650 sphericalHarmonics: {
651 coefficients: [
652 { red: c[0], green: c[1], blue: c[2] },
653 { red: c[3], green: c[4], blue: c[5] },
654 { red: c[6], green: c[7], blue: c[8] },
655 { red: c[9], green: c[10], blue: c[11] },
656 { red: c[12], green: c[13], blue: c[14] },
657 { red: c[15], green: c[16], blue: c[17] },
658 { red: c[18], green: c[19], blue: c[20] },
659 { red: c[21], green: c[22], blue: c[23] },
660 { red: c[24], green: c[25], blue: c[26] }
661 ]
662 },
663 // Vector3dF
664 mainLightDirection: {
665 x: fakeXrLightEstimateInit.primaryLightDirection.x,
666 y: fakeXrLightEstimateInit.primaryLightDirection.y,
667 z: fakeXrLightEstimateInit.primaryLightDirection.z
668 },
669 // RgbTupleF32
670 mainLightIntensity: {
671 red: fakeXrLightEstimateInit.primaryLightIntensity.x,
672 green: fakeXrLightEstimateInit.primaryLightIntensity.y,
673 blue: fakeXrLightEstimateInit.primaryLightIntensity.z
674 }
675 }
676 }
677 }
678
679 // WebXR Test API depth Sensing Extensions
680 _setDepthSupport(depthSupport) {
681 this.depthSupport_ = {};
682
683 this.depthSupport_.depthTypes = [];
684 for (const type of (depthSupport.depthTypes || [])) {
685 this.depthSupport_.depthTypes.push(MockRuntime._depthTypeToMojoMap[type]);
686 }
687
688 this.depthSupport_.depthFormats = [];
689 for (const format of (depthSupport.depthFormats || [])) {
690 this.depthSupport_.depthFormats.push(MockRuntime._depthDataFormatToMojoMap[format]);
691 }
692
693 this.depthSupport_.depthUsages = [];
694 for (const usage of (depthSupport.depthUsages || [])) {
695 // Because chrome doesn't support gpu-optimized for any devices at present
696 // avoid "false positive" WPTs by indicating that we don't support
697 // gpu-optimized.
698 if (usage === "gpu-optimized") {
699 continue;
700 }
701
702 this.depthSupport_.depthUsages.push(MockRuntime._depthUsageToMojoMap[usage]);
703 }
704 }
705
706 setDepthSensingData(depthSensingData) {
707 for(const key of ["depthData", "normDepthBufferFromNormView", "rawValueToMeters", "width", "height"]) {
708 if(!(key in depthSensingData)) {
709 throw new TypeError("Required key not present. Key: " + key);
710 }
711 }
712
713 if(depthSensingData.depthData != null) {
714 // Create new object w/ properties based on the depthSensingData, but
715 // convert the FakeXRRigidTransformInit into a transformation matrix object.
716 this.depthSensingData_ = Object.assign({},
717 depthSensingData, {
718 normDepthBufferFromNormView: composeGFXTransform(depthSensingData.normDepthBufferFromNormView),
719 });
720 } else {
721 throw new TypeError("`depthData` is not set");
722 }
723
724 this.depthSensingDataDirty_ = true;
725 }
726
727 clearDepthSensingData() {
728 this.depthSensingData_ = null;
729 this.depthSensingDataDirty_ = true;
730 }
731
732 // Internal Implementation/Helper Methods
733 _convertModeToEnum(sessionMode) {
734 if (sessionMode in MockRuntime._sessionModeToMojoMap) {
735 return MockRuntime._sessionModeToMojoMap[sessionMode];
736 }
737
738 throw new TypeError("Unrecognized value for XRSessionMode enum: " + sessionMode);
739 }
740
741 _convertModesToEnum(sessionModes) {
742 return sessionModes.map(mode => this._convertModeToEnum(mode));
743 }
744
745 _convertBlendModeToEnum(blendMode) {
746 if (blendMode in MockRuntime._environmentBlendModeToMojoMap) {
747 return MockRuntime._environmentBlendModeToMojoMap[blendMode];
748 } else {
749 if (this.supportedModes_.includes(xrSessionMojom.XRSessionMode.kImmersiveAr)) {
750 return vrMojom.XREnvironmentBlendMode.kAdditive;
751 } else if (this.supportedModes_.includes(
752 xrSessionMojom.XRSessionMode.kImmersiveVr)) {
753 return vrMojom.XREnvironmentBlendMode.kOpaque;
754 }
755 }
756 }
757
758 _convertInteractionModeToEnum(interactionMode) {
759 if (interactionMode in MockRuntime._interactionModeToMojoMap) {
760 return MockRuntime._interactionModeToMojoMap[interactionMode];
761 } else {
762 return vrMojom.XRInteractionMode.kWorldSpace;
763 }
764 }
765
766 _setViews(deviceViews, xOffset, views) {
767 for (let i = 0; i < deviceViews.length; i++) {
768 views[i] = this._getView(deviceViews[i], xOffset);
769 xOffset += deviceViews[i].resolution.width;
770 }
771
772 return xOffset;
773 }
774
775 _findCameraImage(views) {
776 const viewWithCamera = views.find(view => view.cameraImageInit);
777 if (viewWithCamera) {
778 //If we have one view with a camera resolution, all views should have the same camera resolution.
779 const allViewsHaveSameCamera = views.every(
780 view => isSameCameraImageInit(view.cameraImageInit, viewWithCamera.cameraImageInit));
781
782 if (!allViewsHaveSameCamera) {
783 throw new Error("If present, camera resolutions on each view must match each other!");
784 }
785
786 return viewWithCamera.cameraImageInit;
787 }
788
789 return null;
790 }
791
792 _onStageParametersUpdated() {
793 // Indicate for the frame loop that the stage parameters have been updated.
794 this.stageParametersId_++;
795 }
796
797 _getDefaultViews() {
798 if (this.primaryViews_) {
799 return this.primaryViews_;
800 }
801
802 const viewport_size = 20;
803 return [{
804 eye: vrMojom.XREye.kLeft,
805 geometry: {
806 fieldOfView: {
807 upDegrees: 48.316,
808 downDegrees: 50.099,
809 leftDegrees: 50.899,
810 rightDegrees: 35.197
811 },
812 mojoFromView: this._getMojoFromViewerWithOffset(composeGFXTransform({
813 position: [-0.032, 0, 0],
814 orientation: [0, 0, 0, 1]
815 }))
816 },
817 viewport: { x: 0, y: 0, width: viewport_size, height: viewport_size }
818 },
819 {
820 eye: vrMojom.XREye.kRight,
821 geometry: {
822 fieldOfView: {
823 upDegrees: 48.316,
824 downDegrees: 50.099,
825 leftDegrees: 50.899,
826 rightDegrees: 35.197
827 },
828 mojoFromView: this._getMojoFromViewerWithOffset(composeGFXTransform({
829 position: [0.032, 0, 0],
830 orientation: [0, 0, 0, 1]
831 }))
832 },
833 viewport: { x: viewport_size, y: 0, width: viewport_size, height: viewport_size }
834 }];
835 }
836
837 _getFovFromProjectionMatrix(projectionMatrix) {
838 const m = projectionMatrix;
839
840 function toDegrees(tan) {
841 return Math.atan(tan) * 180 / Math.PI;
842 }
843
844 const leftTan = (1 - m[8]) / m[0];
845 const rightTan = (1 + m[8]) / m[0];
846 const upTan = (1 + m[9]) / m[5];
847 const downTan = (1 - m[9]) / m[5];
848
849 return {
850 upDegrees: toDegrees(upTan),
851 downDegrees: toDegrees(downTan),
852 leftDegrees: toDegrees(leftTan),
853 rightDegrees: toDegrees(rightTan)
854 };
855 }
856
857 // This function converts between the matrix provided by the WebXR test API
858 // and the internal data representation.
859 _getView(fakeXRViewInit, xOffset) {
860 let fov = null;
861
862 if (fakeXRViewInit.fieldOfView) {
863 fov = {
864 upDegrees: fakeXRViewInit.fieldOfView.upDegrees,
865 downDegrees: fakeXRViewInit.fieldOfView.downDegrees,
866 leftDegrees: fakeXRViewInit.fieldOfView.leftDegrees,
867 rightDegrees: fakeXRViewInit.fieldOfView.rightDegrees
868 };
869 } else {
870 fov = this._getFovFromProjectionMatrix(fakeXRViewInit.projectionMatrix);
871 }
872
873 let viewEye = vrMojom.XREye.kNone;
874 // The eye passed in corresponds to the values in the WebXR spec, which are
875 // the strings "none", "left", and "right". They should be converted to the
876 // corresponding values of XREye in vr_service.mojom.
877 switch(fakeXRViewInit.eye) {
878 case "none":
879 viewEye = vrMojom.XREye.kNone;
880 break;
881 case "left":
882 viewEye = vrMojom.XREye.kLeft;
883 break;
884 case "right":
885 viewEye = vrMojom.XREye.kRight;
886 break;
887 }
888
889 return {
890 eye: viewEye,
891 geometry: {
892 fieldOfView: fov,
893 mojoFromView: this._getMojoFromViewerWithOffset(composeGFXTransform(fakeXRViewInit.viewOffset)),
894 // Mojo will ignore extra members, we stash the raw projection matrix
895 // here for ease of use with the depth extensions.
896 projectionMatrix: fakeXRViewInit.projectionMatrix,
897 },
898 viewport: {
899 x: xOffset,
900 y: 0,
901 width: fakeXRViewInit.resolution.width,
902 height: fakeXRViewInit.resolution.height
903 },
904 isFirstPersonObserver: fakeXRViewInit.isFirstPersonObserver ? true : false,
905 viewOffset: composeGFXTransform(fakeXRViewInit.viewOffset)
906 };
907 }
908
909 _setFeatures(supportedFeatures) {
910 function convertFeatureToMojom(feature) {
911 if (feature in MockRuntime._featureToMojoMap) {
912 return MockRuntime._featureToMojoMap[feature];
913 } else {
914 return xrSessionMojom.XRSessionFeature.INVALID;
915 }
916 }
917
918 this.supportedFeatures_ = [];
919
920 for (let i = 0; i < supportedFeatures.length; i++) {
921 const feature = convertFeatureToMojom(supportedFeatures[i]);
922 if (feature !== xrSessionMojom.XRSessionFeature.INVALID) {
923 this.supportedFeatures_.push(feature);
924 }
925 }
926 }
927
928 // These methods are intended to be used by MockXRInputSource only.
929 _addInputSource(source) {
930 if (!this.input_sources_.has(source.source_id_)) {
931 this.input_sources_.set(source.source_id_, source);
932 }
933 }
934
935 _removeInputSource(source) {
936 this.input_sources_.delete(source.source_id_);
937 }
938
939 // These methods are intended to be used by FakeXRAnchorController only.
940 _deleteAnchorController(controllerId) {
941 this.anchor_controllers_.delete(controllerId);
942 }
943
944 // Extension point for non-standard modules.
945 _injectAdditionalFrameData(options, frameData) {
946 }
947
948 // Mojo function implementations.
949
950 // XRFrameDataProvider implementation.
951 getFrameData(options) {
952 return new Promise((resolve) => {
953
954 const populatePose = () => {
955 const mojo_space_reset = this.send_mojo_space_reset_;
956 this.send_mojo_space_reset_ = false;
957
958 if (this.pose_) {
959 this.pose_.poseIndex++;
960 }
961
962 // Setting the input_state to null tests a slightly different path than
963 // the browser tests where if the last input source is removed, the device
964 // code always sends up an empty array, but it's also valid mojom to send
965 // up a null array.
966 let input_state = null;
967 if (this.input_sources_.size > 0) {
968 input_state = [];
969 for (const input_source of this.input_sources_.values()) {
970 input_state.push(input_source._getInputSourceState());
971 }
972 }
973
974 let frame_views = this.primaryViews_;
975 for (let i = 0; i < this.primaryViews_.length; i++) {
976 this.primaryViews_[i].geometry.mojoFromView =
977 this._getMojoFromViewerWithOffset(this.primaryViews_[i].viewOffset);
978 }
979 if (this.enabledFeatures_.includes(xrSessionMojom.XRSessionFeature.SECONDARY_VIEWS)) {
980 for (let i = 0; i < this.secondaryViews_.length; i++) {
981 this.secondaryViews_[i].geometry.mojoFromView =
982 this._getMojoFromViewerWithOffset(this.secondaryViews_[i].viewOffset);
983 }
984
985 frame_views = frame_views.concat(this.secondaryViews_);
986 }
987
988 const frameData = {
989 renderInfo: {
990 frameId: this.next_frame_id_,
991 mojoFromViewer: this.pose_,
992 views: frame_views
993 },
994 mojoSpaceReset: mojo_space_reset,
995 inputState: input_state,
996 timeDelta: {
997 // window.performance.now() is in milliseconds, so convert to microseconds.
998 microseconds: BigInt(Math.floor(window.performance.now() * 1000)),
999 },
1000 bufferHolder: null,
1001 cameraImageSize: this.cameraImage_ ? {
1002 width: this.cameraImage_.width,
1003 height: this.cameraImage_.height
1004 } : null,
1005 renderingTimeRatio: 0,
1006 stageParameters: this.stageParameters_,
1007 stageParametersId: this.stageParametersId_,
1008 lightEstimationData: this.light_estimate_
1009 };
1010
1011 this.next_frame_id_++;
1012
1013 this._calculateHitTestResults(frameData);
1014
1015 this._calculateAnchorInformation(frameData);
1016
1017 if (options.depthActive) {
1018 this._calculateDepthInformation(frameData);
1019 }
1020
1021 this._injectAdditionalFrameData(options, frameData);
1022
1023 resolve({frameData});
1024 };
1025
1026 if(this.sessionOptions_.mode == xrSessionMojom.XRSessionMode.kInline) {
1027 // Inline sessions should not have a delay introduced since it causes them
1028 // to miss a vsync blink-side and delays propagation of changes that happened
1029 // within a rAFcb by one frame (e.g. setViewerOrigin() calls would take 2 frames
1030 // to propagate).
1031 populatePose();
1032 } else {
1033 // For immerive sessions, add additional delay to allow for anchor creation
1034 // promises to run.
1035 setTimeout(populatePose, 3); // note: according to MDN, the timeout is not exact
1036 }
1037 });
1038 }
1039
1040 getEnvironmentIntegrationProvider(environmentProviderRequest) {
1041 if (this.environmentProviderReceiver_) {
1042 this.environmentProviderReceiver_.$.close();
1043 }
1044 this.environmentProviderReceiver_ =
1045 new vrMojom.XREnvironmentIntegrationProviderReceiver(this);
1046 this.environmentProviderReceiver_.$.bindHandle(
1047 environmentProviderRequest.handle);
1048 }
1049
1050 // XREnvironmentIntegrationProvider implementation:
1051 subscribeToHitTest(nativeOriginInformation, entityTypes, ray) {
1052 if (!this.supportedModes_.includes(xrSessionMojom.XRSessionMode.kImmersiveAr)) {
1053 // Reject outside of AR.
1054 return Promise.resolve({
1055 result : vrMojom.SubscribeToHitTestResult.FAILURE_GENERIC,
1056 subscriptionId : 0n
1057 });
1058 }
1059
1060 if (!this._nativeOriginKnown(nativeOriginInformation)) {
1061 return Promise.resolve({
1062 result : vrMojom.SubscribeToHitTestResult.FAILURE_GENERIC,
1063 subscriptionId : 0n
1064 });
1065 }
1066
1067 // Reserve the id for hit test source:
1068 const id = this.next_hit_test_id_++;
1069 const hitTestParameters = { isTransient: false, profileName: null };
1070 const controller = new FakeXRHitTestSourceController(id);
1071
1072
1073 return this._shouldHitTestSourceCreationSucceed(hitTestParameters, controller)
1074 .then((succeeded) => {
1075 if(succeeded) {
1076 // Store the subscription information as-is (including controller):
1077 this.hitTestSubscriptions_.set(id, { nativeOriginInformation, entityTypes, ray, controller });
1078
1079 return Promise.resolve({
1080 result : vrMojom.SubscribeToHitTestResult.SUCCESS,
1081 subscriptionId : id
1082 });
1083 } else {
1084 return Promise.resolve({
1085 result : vrMojom.SubscribeToHitTestResult.FAILURE_GENERIC,
1086 subscriptionId : 0n
1087 });
1088 }
1089 });
1090 }
1091
1092 subscribeToHitTestForTransientInput(profileName, entityTypes, ray){
1093 if (!this.supportedModes_.includes(xrSessionMojom.XRSessionMode.kImmersiveAr)) {
1094 // Reject outside of AR.
1095 return Promise.resolve({
1096 result : vrMojom.SubscribeToHitTestResult.FAILURE_GENERIC,
1097 subscriptionId : 0n
1098 });
1099 }
1100
1101 const id = this.next_hit_test_id_++;
1102 const hitTestParameters = { isTransient: true, profileName: profileName };
1103 const controller = new FakeXRHitTestSourceController(id);
1104
1105 // Check if we have hit test source creation callback.
1106 // If yes, ask it if the hit test source creation should succeed.
1107 // If no, for back-compat, assume the hit test source creation succeeded.
1108 return this._shouldHitTestSourceCreationSucceed(hitTestParameters, controller)
1109 .then((succeeded) => {
1110 if(succeeded) {
1111 // Store the subscription information as-is (including controller):
1112 this.transientHitTestSubscriptions_.set(id, { profileName, entityTypes, ray, controller });
1113
1114 return Promise.resolve({
1115 result : vrMojom.SubscribeToHitTestResult.SUCCESS,
1116 subscriptionId : id
1117 });
1118 } else {
1119 return Promise.resolve({
1120 result : vrMojom.SubscribeToHitTestResult.FAILURE_GENERIC,
1121 subscriptionId : 0n
1122 });
1123 }
1124 });
1125 }
1126
1127 unsubscribeFromHitTest(subscriptionId) {
1128 let controller = null;
1129 if(this.transientHitTestSubscriptions_.has(subscriptionId)){
1130 controller = this.transientHitTestSubscriptions_.get(subscriptionId).controller;
1131 this.transientHitTestSubscriptions_.delete(subscriptionId);
1132 } else if(this.hitTestSubscriptions_.has(subscriptionId)){
1133 controller = this.hitTestSubscriptions_.get(subscriptionId).controller;
1134 this.hitTestSubscriptions_.delete(subscriptionId);
1135 }
1136
1137 if(controller) {
1138 controller.deleted = true;
1139 }
1140 }
1141
1142 createAnchor(nativeOriginInformation, nativeOriginFromAnchor) {
1143 return new Promise((resolve) => {
1144 if(this.anchor_creation_callback_ == null) {
1145 resolve({
1146 result : vrMojom.CreateAnchorResult.FAILURE,
1147 anchorId : 0n
1148 });
1149
1150 return;
1151 }
1152
1153 const mojoFromNativeOrigin = this._getMojoFromNativeOrigin(nativeOriginInformation);
1154 if(mojoFromNativeOrigin == null) {
1155 resolve({
1156 result : vrMojom.CreateAnchorResult.FAILURE,
1157 anchorId : 0n
1158 });
1159
1160 return;
1161 }
1162
1163 const mojoFromAnchor = XRMathHelper.mul4x4(mojoFromNativeOrigin, nativeOriginFromAnchor);
1164
1165 const anchorCreationParameters = {
1166 requestedAnchorOrigin: mojoFromAnchor,
1167 isAttachedToEntity: false,
1168 };
1169
1170 const anchorController = new FakeXRAnchorController();
1171
1172 this.anchor_creation_callback_(anchorCreationParameters, anchorController)
1173 .then((result) => {
1174 if(result) {
1175 // If the test allowed the anchor creation,
1176 // store the anchor controller & return success.
1177
1178 const anchor_id = this.next_anchor_id_;
1179 this.next_anchor_id_++;
1180
1181 this.anchor_controllers_.set(anchor_id, anchorController);
1182 anchorController.device = this;
1183 anchorController.id = anchor_id;
1184
1185 resolve({
1186 result : vrMojom.CreateAnchorResult.SUCCESS,
1187 anchorId : anchor_id
1188 });
1189 } else {
1190 // The test has rejected anchor creation.
1191 resolve({
1192 result : vrMojom.CreateAnchorResult.FAILURE,
1193 anchorId : 0n
1194 });
1195 }
1196 })
1197 .catch(() => {
1198 // The test threw an error, treat anchor creation as failed.
1199 resolve({
1200 result : vrMojom.CreateAnchorResult.FAILURE,
1201 anchorId : 0n
1202 });
1203 });
1204 });
1205 }
1206
1207 createPlaneAnchor(planeFromAnchor, planeId) {
1208 return new Promise((resolve) => {
1209
1210 // Not supported yet.
1211
1212 resolve({
1213 result : vrMojom.CreateAnchorResult.FAILURE,
1214 anchorId : 0n,
1215 });
1216 });
1217 }
1218
1219 detachAnchor(anchorId) {}
1220
1221 // Utility function
1222 _requestRuntimeSession(sessionOptions) {
1223 return this._runtimeSupportsSession(sessionOptions).then((result) => {
1224 // The JavaScript bindings convert c_style_names to camelCase names.
1225 const options = {
1226 transportMethod:
1227 vrMojom.XRPresentationTransportMethod.SUBMIT_AS_MAILBOX_HOLDER,
1228 waitForTransferNotification: true,
1229 waitForRenderNotification: true,
1230 waitForGpuFence: false,
1231 };
1232
1233 let submit_frame_sink;
1234 if (result.supportsSession) {
1235 submit_frame_sink = {
1236 clientReceiver: this.presentation_provider_._getClientReceiver(),
1237 provider: this.presentation_provider_._bindProvider(sessionOptions),
1238 transportOptions: options
1239 };
1240
1241 const dataProviderPtr = new vrMojom.XRFrameDataProviderRemote();
1242 this.dataProviderReceiver_ =
1243 new vrMojom.XRFrameDataProviderReceiver(this);
1244 this.dataProviderReceiver_.$.bindHandle(
1245 dataProviderPtr.$.bindNewPipeAndPassReceiver().handle);
1246 this.sessionOptions_ = sessionOptions;
1247
1248 this.sessionClient_ = new vrMojom.XRSessionClientRemote();
1249 const clientReceiver = this.sessionClient_.$.bindNewPipeAndPassReceiver();
1250
1251 const enabled_features = [];
1252 for (let i = 0; i < sessionOptions.requiredFeatures.length; i++) {
1253 const feature = sessionOptions.requiredFeatures[i];
1254 if (this._maybeEnableFeature(feature, sessionOptions)) {
1255 enabled_features.push(feature);
1256 } else {
1257 return Promise.resolve({session: null});
1258 }
1259 }
1260
1261 for (let i =0; i < sessionOptions.optionalFeatures.length; i++) {
1262 const feature = sessionOptions.optionalFeatures[i];
1263 if (this._maybeEnableFeature(feature, sessionOptions)) {
1264 enabled_features.push(feature);
1265 }
1266 }
1267
1268 this.enabledFeatures_ = enabled_features;
1269
1270 return Promise.resolve({
1271 session: {
1272 submitFrameSink: submit_frame_sink,
1273 dataProvider: dataProviderPtr,
1274 clientReceiver: clientReceiver,
1275 enabledFeatures: enabled_features,
1276 deviceConfig: {
1277 defaultFramebufferScale: this.defaultFramebufferScale_,
1278 supportsViewportScaling: true,
1279 // If depth was not enabled above, this should be null.
1280 depthConfiguration: this.depthConfiguration_,
1281 views: this._getDefaultViews(),
1282 },
1283 enviromentBlendMode: this.enviromentBlendMode_,
1284 interactionMode: this.interactionMode_
1285 }
1286 });
1287 } else {
1288 return Promise.resolve({session: null});
1289 }
1290 });
1291 }
1292
1293 _runtimeSupportsSession(options) {
1294 let result = this.supportedModes_.includes(options.mode);
1295 return Promise.resolve({
1296 supportsSession: result,
1297 });
1298 }
1299
1300 _tryGetDepthConfig(options) {
1301 if (!options.depthOptions) {
1302 return null;
1303 }
1304
1305 // At present, there are only two depth usages, and we only support CPU.
1306 if (options.depthOptions.usagePreferences.length !== 0 &&
1307 !options.depthOptions.usagePreferences.includes(
1308 xrSessionMojom.XRDepthUsage.kCPUOptimized)) {
1309 return null;
1310 }
1311 const selectedUsage = xrSessionMojom.XRDepthUsage.kCPUOptimized;
1312
1313 let selectedFormat = null;
1314 if (options.depthOptions.dataFormatPreferences.length === 0) {
1315 selectedFormat = this.depthSupport_.depthFormats.length === 0 ?
1316 xrSessionMojom.XRDepthDataFormat.kLuminanceAlpha : this.depthSupport_.depthFormats[0];
1317 } else {
1318 for (const dataFormatRequest of options.depthOptions.dataFormatPreferences) {
1319 if (this.depthSupport_.depthFormats.length === 0 ||
1320 this.depthSupport_.depthFormats.includes(dataFormatRequest)) {
1321 selectedFormat = dataFormatRequest;
1322 break;
1323 }
1324 }
1325 }
1326
1327 if (selectedFormat === null) {
1328 return null;
1329 }
1330
1331 // Default to our first supported depth type. If it's empty (meaning all),
1332 // then just default to raw.
1333 let selectedDepthType = this.depthSupport_.depthTypes.length === 0 ?
1334 xrSessionMojom.XRDepthType.kRawDepth : this.depthSupport_.depthTypes[0];
1335 // Try to set the depthType to the earliest requested one if it's supported.
1336 for (const depthTypeRequest of options.depthOptions.depthTypeRequest) {
1337 if (this.depthSupport_.depthTypes.length === 0 ||
1338 this.depthSupport_.depthTypes.includes(depthTypeRequest)) {
1339 selectedDepthType = depthTypeRequest;
1340 break;
1341 }
1342 }
1343
1344 return {
1345 depthUsage: selectedUsage,
1346 depthDataFormat: selectedFormat,
1347 depthType: selectedDepthType,
1348 };
1349 }
1350
1351 _maybeEnableFeature(feature, options) {
1352 if (this.supportedFeatures_.indexOf(feature) === -1) {
1353 return false;
1354 }
1355
1356 switch (feature) {
1357 case xrSessionMojom.XRSessionFeature.DEPTH:
1358 this.depthConfiguration_ = this._tryGetDepthConfig(options);
1359 this.matchDepthView_ = options.depthOptions && options.depthOptions.matchDepthView;
1360 return this.depthConfiguration_ != null;
1361 default:
1362 return true;
1363 }
1364 }
1365
1366 // Private functions - utilities:
1367 _nativeOriginKnown(nativeOriginInformation){
1368
1369 if (nativeOriginInformation.inputSourceSpaceInfo !== undefined) {
1370 if (!this.input_sources_.has(nativeOriginInformation.inputSourceSpaceInfo.inputSourceId)) {
1371 // Unknown input source.
1372 return false;
1373 }
1374
1375 return true;
1376 } else if (nativeOriginInformation.referenceSpaceType !== undefined) {
1377 // Bounded_floor & unbounded ref spaces are not yet supported for AR:
1378 if (nativeOriginInformation.referenceSpaceType == vrMojom.XRReferenceSpaceType.kUnbounded
1379 || nativeOriginInformation.referenceSpaceType == vrMojom.XRReferenceSpaceType.kBoundedFloor) {
1380 return false;
1381 }
1382
1383 return true;
1384 } else {
1385 // Planes and anchors are not yet supported by the mock interface.
1386 return false;
1387 }
1388 }
1389
1390 // Private functions - anchors implementation:
1391
1392 // Modifies passed in frameData to add anchor information.
1393 _calculateAnchorInformation(frameData) {
1394 if (!this.supportedModes_.includes(xrSessionMojom.XRSessionMode.kImmersiveAr)) {
1395 return;
1396 }
1397
1398 frameData.anchorsData = {allAnchorsIds: [], updatedAnchorsData: []};
1399 for(const [id, controller] of this.anchor_controllers_) {
1400 frameData.anchorsData.allAnchorsIds.push(id);
1401
1402 // Send the entire anchor data over if there was a change since last GetFrameData().
1403 if(controller.dirty) {
1404 const anchorData = {id};
1405 if(!controller.paused) {
1406 anchorData.mojoFromAnchor = getPoseFromTransform(
1407 XRMathHelper.decomposeRigidTransform(
1408 controller._getAnchorOrigin()));
1409 }
1410
1411 controller._markProcessed();
1412
1413 frameData.anchorsData.updatedAnchorsData.push(anchorData);
1414 }
1415 }
1416 }
1417
1418 // Private functions - depth sensing implementation:
1419
1420 /**
1421 * Helper to get a TypedArray view for a given depth format.
1422 * @param {ArrayBuffer} buffer The ArrayBuffer.
1423 * @param {xrSessionMojom.XRDepthDataFormat} format The depth format.
1424 * @return {Uint16Array|Float32Array} A typed array view.
1425 */
1426 static _getTypedArrayForFormat(buffer, format) {
1427 if (format === xrSessionMojom.XRDepthDataFormat.kFloat32) {
1428 return new Float32Array(buffer);
1429 } else { // "luminance-alpha" or "unsigned-short"
1430 return new Uint16Array(buffer);
1431 }
1432 }
1433
1434 /**
1435 * Helper to get a TypedArray for the given depth format.
1436 * @param {xrSessionMojom.XRDepthDataFormat} format - The Depth format
1437 * @param {number} size - The size of the array to be created.
1438 * @return {Uint16Array|Float32Array} A typed array view.
1439 */
1440 static _getEmptyTypedArrayForFormat(format, size) {
1441 if (format === xrSessionMojom.XRDepthDataFormat.kFloat32) {
1442 return new Float32Array(size).fill(0.0);
1443 } else { // "luminance-alpha" or "unsigned-short" (Uint16)
1444 return new Uint16Array(size).fill(0);
1445 }
1446 }
1447
1448 /**
1449 * Reprojects depth data from a source view to a target view.
1450 * The returned array will be the same width/height, but will be returned as a
1451 * Uint8Array of the targetFormat (essentially a byte array that can be sent
1452 * across mojo), so the overall returned size may be different.
1453 *
1454 * @param {ArrayBuffer} sourceDepthArrayBuffer - Raw depth data for the source.
1455 * @param {number} width - Width of the depth data.
1456 * @param {number} height - Height of the depth data.
1457 * @param {xrSessionMojom.XRDepthDataFormat} sourceFormatEnum - Format of the source depth data.
1458 * @param {Float32Array} sourceClipFromSourceView - Projection matrix for the source view.
1459 * @param {Float32Array} mojoFromSourceView- Matrix of the transform for the source view.
1460 * @param {xrSessionMojom.XRDepthDataFormat} targetFormatEnum - Format of the target depth data.
1461 * @param {Float32Array} targetClipFromTargetView - Projection matrix for the target view.
1462 * @param {Float32Array} mojoFromTargetView - Matrix of the transform for the target view.
1463 * @return {Uint8Array | null} The reprojected depth data as an Uint8Array, or null on matrix error.
1464 */
1465 static copyDepthData(
1466 sourceDepthArrayBuffer, width, height, sourceFormatEnum,
1467 sourceClipFromSourceView, mojoFromSourceView,
1468 targetFormatEnum,
1469 targetClipFromTargetView, mojoFromTargetView) {
1470
1471 const targetViewFromTargetClip = XRMathHelper.inverse(targetClipFromTargetView);
1472 const sourceViewFromMojo = XRMathHelper.inverse(mojoFromSourceView);
1473
1474 // Check if any matrices were not supplied or matrix inversions failed.
1475 if (!targetViewFromTargetClip || !sourceViewFromMojo || !mojoFromTargetView) {
1476 return null;
1477 }
1478
1479 // Build the full transformation from Target Clip space to Source Clip space.
1480 const mojoFromTargetClip = XRMathHelper.mul4x4(mojoFromTargetView, targetViewFromTargetClip);
1481 if (!mojoFromTargetClip) return null;
1482
1483 const sourceViewFromTargetClip = XRMathHelper.mul4x4(sourceViewFromMojo, mojoFromTargetClip);
1484 if (!sourceViewFromTargetClip) return null;
1485
1486 const sourceClipFromTargetClip = XRMathHelper.mul4x4(sourceClipFromSourceView, sourceViewFromTargetClip);
1487 if (!sourceClipFromTargetClip) return null;
1488
1489 const sourceTypedArray = MockRuntime._getTypedArrayForFormat(sourceDepthArrayBuffer, sourceFormatEnum);
1490 let internalTargetDepthTypedArray = MockRuntime._getEmptyTypedArrayForFormat(targetFormatEnum, width * height);
1491
1492 // Iterate over target pixels (Backward Mapping)
1493 for (let ty = 0; ty < height; ++ty) {
1494 for (let tx = 0; tx < width; ++tx) {
1495 // Convert target pixel (tx, ty) to target NDC coordinates
1496 const u_tgt_pixel = (tx + 0.5) / width; // u in [0, 1], Y-down from top-left
1497 const v_tgt_pixel = (ty + 0.5) / height; // v in [0, 1], Y-down from top-left
1498
1499 const ndc_x_tgt = u_tgt_pixel * 2.0 - 1.0; // NDC X in [-1, 1]
1500 const ndc_y_tgt = 1.0 - v_tgt_pixel * 2.0; // NDC Y in [-1, 1], Y-up
1501
1502 // Define a point on the near plane in target clip space
1503 const P_clip_tgt = { x: ndc_x_tgt, y: ndc_y_tgt, z: -1.0, w: 1.0 };
1504
1505 // Transform this point to source clip space
1506 const P_clip_src = XRMathHelper.transform_by_matrix(sourceClipFromTargetClip, P_clip_tgt);
1507
1508 // Homogenize to get source NDC coordinates
1509 if (Math.abs(P_clip_src.w) < XRMathHelper.EPSILON) {
1510 internalTargetDepthTypedArray[ty * width + tx] = 0; // Cannot project
1511 continue;
1512 }
1513 const ndc_x_src = P_clip_src.x / P_clip_src.w;
1514 const ndc_y_src = P_clip_src.y / P_clip_src.w;
1515
1516 // Convert source NDC to source pixel coordinates
1517 const u_src_pixel = (ndc_x_src + 1.0) / 2.0;
1518 const v_src_pixel = (1.0 - ndc_y_src) / 2.0; // Convert source NDC Y-up to pixel Y-down
1519
1520 const sx = Math.floor(u_src_pixel * width);
1521 const sy = Math.floor(v_src_pixel * height);
1522
1523 let target_raw_depth = 0; // Default to 0 (no data)
1524
1525 // Check if the calculated source pixel is within bounds
1526 if (sx >= 0 && sx < width && sy >= 0 && sy < height) {
1527 const source_raw_value = sourceTypedArray[sy * width + sx];
1528
1529 let isValidSourceDepth = false;
1530 if (sourceFormatEnum === xrSessionMojom.XRDepthDataFormat.kFloat32) {
1531 if (source_raw_value > 0 && isFinite(source_raw_value)) {
1532 isValidSourceDepth = true;
1533 }
1534 } else { // Uint16 source
1535 if (source_raw_value > 0) {
1536 isValidSourceDepth = true;
1537 }
1538 }
1539
1540 if (isValidSourceDepth) {
1541 if (targetFormatEnum === xrSessionMojom.XRDepthDataFormat.kFloat32) {
1542 target_raw_depth = source_raw_value;
1543 } else {
1544 // Clamp to the valid range for Uint16
1545 target_raw_depth = Math.max(0, Math.min(0xFFFF, Math.round(source_raw_value)));
1546 }
1547 }
1548 }
1549
1550 // If not in bounds or source depth invalid, target_raw_depth remains 0.
1551 internalTargetDepthTypedArray[ty * width + tx] = target_raw_depth;
1552 }
1553 }
1554
1555 return new Uint8Array(internalTargetDepthTypedArray.buffer);
1556 }
1557
1558 _getDepthPixelData(depthGeometry) {
1559 if (!this.matchDepthView_ || !depthGeometry) {
1560 return { bytes: this.depthSensingData_.depthData };
1561 }
1562
1563 const sourceProjectionMatrix = depthGeometry.projectionMatrix;
1564 const sourceViewOffset = depthGeometry.mojoFromView;
1565 if (!sourceProjectionMatrix || !sourceViewOffset) {
1566 return { bytes: this.depthSensingData_.depthData };
1567 }
1568
1569 if (this.primaryViews_.length === 0) {
1570 return { bytes: this.depthSensingData_.depthData };
1571 }
1572
1573 const targetView = this.primaryViews_[0];
1574 const targetProjectionMatrix = targetView.geometry.projectionMatrix;
1575 const targetViewOffset = targetView.geometry.mojoFromView;
1576 if (!targetProjectionMatrix || !targetViewOffset) {
1577 return { bytes: this.depthSensingData_.depthData };
1578 }
1579
1580 return { bytes: MockRuntime.copyDepthData(
1581 this.depthSensingData_.depthData,
1582 this.depthSensingData_.width,
1583 this.depthSensingData_.height,
1584 MockRuntime._depthDataFormatToMojoMap[this.depthSensingData_.depthFormat],
1585 sourceProjectionMatrix,
1586 sourceViewOffset.matrix,
1587 this.depthConfiguration_.depthDataFormat,
1588 targetProjectionMatrix,
1589 targetViewOffset.matrix
1590 )};
1591 }
1592
1593 // Modifies passed in frameData to add anchor information.
1594 _calculateDepthInformation(frameData) {
1595 if (!this.supportedModes_.includes(xrSessionMojom.XRSessionMode.kImmersiveAr)) {
1596 return;
1597 }
1598
1599 if (!this.enabledFeatures_.includes(xrSessionMojom.XRSessionFeature.DEPTH)) {
1600 return;
1601 }
1602
1603 let newDepthData;
1604
1605 // If we don't have a current depth data, we'll return null
1606 // (i.e. no data is not a valid data, so it cannot be "StillValid").
1607 if (this.depthSensingData_ == null) {
1608 newDepthData = null;
1609 } else if(!this.depthSensingDataDirty_) {
1610 newDepthData = { dataStillValid: {}};
1611 } else {
1612 let viewGeometry = null;
1613 const projectionMatrix = this.depthSensingData_.projectionMatrix;
1614 const viewOffset = this.depthSensingData_.viewOffset;
1615
1616 if (projectionMatrix && viewOffset) {
1617 const fov = this._getFovFromProjectionMatrix(projectionMatrix);
1618
1619 viewGeometry = {
1620 fieldOfView: fov,
1621 mojoFromView: this._getMojoFromViewerWithOffset(composeGFXTransform(viewOffset)),
1622 // Convenience member for `_getDepthPixelData`
1623 projectionMatrix: projectionMatrix
1624 };
1625 }
1626
1627 newDepthData = {
1628 updatedDepthData: {
1629 timeDelta: frameData.timeDelta,
1630 normTextureFromNormView: this.depthSensingData_.normDepthBufferFromNormView,
1631 rawValueToMeters: this.depthSensingData_.rawValueToMeters,
1632 size: { width: this.depthSensingData_.width, height: this.depthSensingData_.height },
1633 pixelData: this._getDepthPixelData(viewGeometry),
1634 viewGeometry: this.matchDepthView_ ? null : viewGeometry
1635 }
1636 };
1637 }
1638
1639 for (let i = 0; i < this.primaryViews_.length; i++) {
1640 this.primaryViews_[i].depthData = newDepthData;
1641 }
1642 if (this.enabledFeatures_.includes(xrSessionMojom.XRSessionFeature.SECONDARY_VIEWS)) {
1643 for (let i = 0; i < this.secondaryViews_.length; i++) {
1644 this.secondaryViews_[i].depthData = newDepthData;
1645 }
1646 }
1647
1648 this.depthSensingDataDirty_ = false;
1649 }
1650
1651 // Private functions - hit test implementation:
1652
1653 // Returns a Promise<bool> that signifies whether hit test source creation should succeed.
1654 // If we have a hit test source creation callback installed, invoke it and return its result.
1655 // If it's not installed, for back-compat just return a promise that resolves to true.
1656 _shouldHitTestSourceCreationSucceed(hitTestParameters, controller) {
1657 if(this.hit_test_source_creation_callback_) {
1658 return this.hit_test_source_creation_callback_(hitTestParameters, controller);
1659 } else {
1660 return Promise.resolve(true);
1661 }
1662 }
1663
1664 // Modifies passed in frameData to add hit test results.
1665 _calculateHitTestResults(frameData) {
1666 if (!this.supportedModes_.includes(xrSessionMojom.XRSessionMode.kImmersiveAr)) {
1667 return;
1668 }
1669
1670 frameData.hitTestSubscriptionResults = {results: [],
1671 transientInputResults: []};
1672 if (!this.world_) {
1673 return;
1674 }
1675
1676 // Non-transient hit test:
1677 for (const [id, subscription] of this.hitTestSubscriptions_) {
1678 const mojo_from_native_origin = this._getMojoFromNativeOrigin(subscription.nativeOriginInformation);
1679 if (!mojo_from_native_origin) continue;
1680
1681 const [mojo_ray_origin, mojo_ray_direction] = this._transformRayToMojoSpace(
1682 subscription.ray,
1683 mojo_from_native_origin
1684 );
1685
1686 const results = this._hitTestWorld(mojo_ray_origin, mojo_ray_direction, subscription.entityTypes);
1687 frameData.hitTestSubscriptionResults.results.push(
1688 {subscriptionId: id, hitTestResults: results});
1689 }
1690
1691 // Transient hit test:
1692 const mojo_from_viewer = this._getMojoFromViewer();
1693
1694 for (const [id, subscription] of this.transientHitTestSubscriptions_) {
1695 const result = {subscriptionId: id,
1696 inputSourceIdToHitTestResults: new Map()};
1697
1698 // Find all input sources that match the profile name:
1699 const matching_input_sources = Array.from(this.input_sources_.values())
1700 .filter(input_source => input_source.profiles_.includes(subscription.profileName));
1701
1702 for (const input_source of matching_input_sources) {
1703 const mojo_from_native_origin = input_source._getMojoFromInputSource(mojo_from_viewer);
1704
1705 const [mojo_ray_origin, mojo_ray_direction] = this._transformRayToMojoSpace(
1706 subscription.ray,
1707 mojo_from_native_origin
1708 );
1709
1710 const results = this._hitTestWorld(mojo_ray_origin, mojo_ray_direction, subscription.entityTypes);
1711
1712 result.inputSourceIdToHitTestResults.set(input_source.source_id_, results);
1713 }
1714
1715 frameData.hitTestSubscriptionResults.transientInputResults.push(result);
1716 }
1717 }
1718
1719 // Returns 2-element array [origin, direction] of a ray in mojo space.
1720 // |ray| is expressed relative to native origin.
1721 _transformRayToMojoSpace(ray, mojo_from_native_origin) {
1722 const ray_origin = {
1723 x: ray.origin.x,
1724 y: ray.origin.y,
1725 z: ray.origin.z,
1726 w: 1
1727 };
1728 const ray_direction = {
1729 x: ray.direction.x,
1730 y: ray.direction.y,
1731 z: ray.direction.z,
1732 w: 0
1733 };
1734
1735 const mojo_ray_origin = XRMathHelper.transform_by_matrix(
1736 mojo_from_native_origin,
1737 ray_origin);
1738 const mojo_ray_direction = XRMathHelper.transform_by_matrix(
1739 mojo_from_native_origin,
1740 ray_direction);
1741
1742 return [mojo_ray_origin, mojo_ray_direction];
1743 }
1744
1745 // Hit tests the passed in ray (expressed as origin and direction) against the mocked world data.
1746 _hitTestWorld(origin, direction, entityTypes) {
1747 let result = [];
1748
1749 for (const region of this.world_.hitTestRegions) {
1750 const partial_result = this._hitTestRegion(
1751 region,
1752 origin, direction,
1753 entityTypes);
1754
1755 result = result.concat(partial_result);
1756 }
1757
1758 return result.sort((lhs, rhs) => lhs.distance - rhs.distance).map((hitTest) => {
1759 delete hitTest.distance;
1760 return hitTest;
1761 });
1762 }
1763
1764 // Hit tests the passed in ray (expressed as origin and direction) against world region.
1765 // |entityTypes| is a set of FakeXRRegionTypes.
1766 // |region| is FakeXRRegion.
1767 // Returns array of XRHitResults, each entry will be decorated with the distance from the ray origin (along the ray).
1768 _hitTestRegion(region, origin, direction, entityTypes) {
1769 const regionNameToMojoEnum = {
1770 "point": vrMojom.EntityTypeForHitTest.POINT,
1771 "plane": vrMojom.EntityTypeForHitTest.PLANE,
1772 "mesh":null
1773 };
1774
1775 if (!entityTypes.includes(regionNameToMojoEnum[region.type])) {
1776 return [];
1777 }
1778
1779 const result = [];
1780 for (const face of region.faces) {
1781 const maybe_hit = this._hitTestFace(face, origin, direction);
1782 if (maybe_hit) {
1783 result.push(maybe_hit);
1784 }
1785 }
1786
1787 // The results should be sorted by distance and there should be no 2 entries with
1788 // the same distance from ray origin - that would mean they are the same point.
1789 // This situation is possible when a ray intersects the region through an edge shared
1790 // by 2 faces.
1791 return result.sort((lhs, rhs) => lhs.distance - rhs.distance)
1792 .filter((val, index, array) => index === 0 || val.distance !== array[index - 1].distance);
1793 }
1794
1795 // Hit tests the passed in ray (expressed as origin and direction) against a single face.
1796 // |face|, |origin|, and |direction| are specified in world (aka mojo) coordinates.
1797 // |face| is an array of DOMPointInits.
1798 // Returns null if the face does not intersect with the ray, otherwise the result is
1799 // an XRHitResult with matrix describing the pose of the intersection point.
1800 _hitTestFace(face, origin, direction) {
1801 const add = XRMathHelper.add;
1802 const sub = XRMathHelper.sub;
1803 const mul = XRMathHelper.mul;
1804 const normalize = XRMathHelper.normalize;
1805 const dot = XRMathHelper.dot;
1806 const cross = XRMathHelper.cross;
1807 const neg = XRMathHelper.neg;
1808
1809 //1. Calculate plane normal in world coordinates.
1810 const point_A = face.vertices[0];
1811 const point_B = face.vertices[1];
1812 const point_C = face.vertices[2];
1813
1814 const edge_AB = sub(point_B, point_A);
1815 const edge_AC = sub(point_C, point_A);
1816
1817 const normal = normalize(cross(edge_AB, edge_AC));
1818
1819 const numerator = dot(sub(point_A, origin), normal);
1820 const denominator = dot(direction, normal);
1821
1822 if (Math.abs(denominator) < XRMathHelper.EPSILON) {
1823 // Planes are nearly parallel - there's either infinitely many intersection points or 0.
1824 // Both cases signify a "no hit" for us.
1825 return null;
1826 } else {
1827 // Single intersection point between the infinite plane and the line (*not* ray).
1828 // Need to calculate the hit test matrix taking into account the face vertices.
1829 const distance = numerator / denominator;
1830 if (distance < 0) {
1831 // Line - plane intersection exists, but not the half-line - plane does not.
1832 return null;
1833 } else {
1834 const intersection_point = add(origin, mul(distance, direction));
1835 // Since we are treating the face as a solid, flip the normal so that its
1836 // half-space will contain the ray origin.
1837 const y_axis = denominator > 0 ? neg(normal) : normal;
1838
1839 let z_axis = null;
1840 const cos_direction_and_y_axis = dot(direction, y_axis);
1841 if (Math.abs(cos_direction_and_y_axis) > (1 - XRMathHelper.EPSILON)) {
1842 // Ray and the hit test normal are co-linear - try using the 'up' or 'right' vector's projection on the face plane as the Z axis.
1843 // Note: this edge case is currently not covered by the spec.
1844 const up = {x: 0.0, y: 1.0, z: 0.0, w: 0.0};
1845 const right = {x: 1.0, y: 0.0, z: 0.0, w: 0.0};
1846
1847 z_axis = Math.abs(dot(up, y_axis)) > (1 - XRMathHelper.EPSILON)
1848 ? sub(up, mul(dot(right, y_axis), y_axis)) // `up is also co-linear with hit test normal, use `right`
1849 : sub(up, mul(dot(up, y_axis), y_axis)); // `up` is not co-linear with hit test normal, use it
1850 } else {
1851 // Project the ray direction onto the plane, negate it and use as a Z axis.
1852 z_axis = neg(sub(direction, mul(cos_direction_and_y_axis, y_axis))); // Z should point towards the ray origin, not away.
1853 }
1854
1855 z_axis = normalize(z_axis);
1856 const x_axis = normalize(cross(y_axis, z_axis));
1857
1858 // Filter out the points not in polygon.
1859 if (!XRMathHelper.pointInFace(intersection_point, face)) {
1860 return null;
1861 }
1862
1863 const hitResult = {planeId: 0n};
1864 hitResult.distance = distance; // Extend the object with additional information used by higher layers.
1865 // It will not be serialized over mojom.
1866
1867 const matrix = new Array(16);
1868
1869 matrix[0] = x_axis.x;
1870 matrix[1] = x_axis.y;
1871 matrix[2] = x_axis.z;
1872 matrix[3] = 0;
1873
1874 matrix[4] = y_axis.x;
1875 matrix[5] = y_axis.y;
1876 matrix[6] = y_axis.z;
1877 matrix[7] = 0;
1878
1879 matrix[8] = z_axis.x;
1880 matrix[9] = z_axis.y;
1881 matrix[10] = z_axis.z;
1882 matrix[11] = 0;
1883
1884 matrix[12] = intersection_point.x;
1885 matrix[13] = intersection_point.y;
1886 matrix[14] = intersection_point.z;
1887 matrix[15] = 1;
1888
1889 hitResult.mojoFromResult = getPoseFromTransform(
1890 XRMathHelper.decomposeRigidTransform(matrix));
1891 return hitResult;
1892 }
1893 }
1894 }
1895
1896 _getMojoFromViewer() {
1897 if (!this.pose_) {
1898 return XRMathHelper.identity();
1899 }
1900 const transform = {
1901 position: [
1902 this.pose_.position.x,
1903 this.pose_.position.y,
1904 this.pose_.position.z],
1905 orientation: [
1906 this.pose_.orientation.x,
1907 this.pose_.orientation.y,
1908 this.pose_.orientation.z,
1909 this.pose_.orientation.w],
1910 };
1911
1912 return getMatrixFromTransform(transform);
1913 }
1914
1915 _getMojoFromViewerWithOffset(viewOffset) {
1916 return { matrix: XRMathHelper.mul4x4(this._getMojoFromViewer(), viewOffset.matrix) };
1917 }
1918
1919 _getMojoFromNativeOrigin(nativeOriginInformation) {
1920 const mojo_from_viewer = this._getMojoFromViewer();
1921
1922 if (nativeOriginInformation.inputSourceSpaceInfo !== undefined) {
1923 if (!this.input_sources_.has(nativeOriginInformation.inputSourceSpaceInfo.inputSourceId)) {
1924 return null;
1925 } else {
1926 const inputSource = this.input_sources_.get(nativeOriginInformation.inputSourceSpaceInfo.inputSourceId);
1927 return inputSource._getMojoFromInputSource(mojo_from_viewer);
1928 }
1929 } else if (nativeOriginInformation.referenceSpaceType !== undefined) {
1930 switch (nativeOriginInformation.referenceSpaceType) {
1931 case vrMojom.XRReferenceSpaceType.kLocal:
1932 return XRMathHelper.identity();
1933 case vrMojom.XRReferenceSpaceType.kLocalFloor:
1934 if (this.stageParameters_ == null || this.stageParameters_.mojoFromStage == null) {
1935 console.warn("Standing transform not available.");
1936 return null;
1937 }
1938 return this.stageParameters_.mojoFromStage.matrix;
1939 case vrMojom.XRReferenceSpaceType.kViewer:
1940 return mojo_from_viewer;
1941 case vrMojom.XRReferenceSpaceType.kBoundedFloor:
1942 return null;
1943 case vrMojom.XRReferenceSpaceType.kUnbounded:
1944 return null;
1945 default:
1946 throw new TypeError("Unrecognized XRReferenceSpaceType!");
1947 }
1948 } else {
1949 // Anchors & planes are not yet supported for hit test.
1950 return null;
1951 }
1952 }
1953 }
1954
1955 class MockXRInputSource {
1956 constructor(fakeInputSourceInit, id, pairedDevice) {
1957 this.source_id_ = id;
1958 this.pairedDevice_ = pairedDevice;
1959 this.handedness_ = fakeInputSourceInit.handedness;
1960 this.target_ray_mode_ = fakeInputSourceInit.targetRayMode;
1961
1962 if (fakeInputSourceInit.pointerOrigin == null) {
1963 throw new TypeError("FakeXRInputSourceInit.pointerOrigin is required.");
1964 }
1965
1966 this.setPointerOrigin(fakeInputSourceInit.pointerOrigin);
1967 this.setProfiles(fakeInputSourceInit.profiles);
1968
1969 this.primary_input_pressed_ = false;
1970 if (fakeInputSourceInit.selectionStarted != null) {
1971 this.primary_input_pressed_ = fakeInputSourceInit.selectionStarted;
1972 }
1973
1974 this.primary_input_clicked_ = false;
1975 if (fakeInputSourceInit.selectionClicked != null) {
1976 this.primary_input_clicked_ = fakeInputSourceInit.selectionClicked;
1977 }
1978
1979 this.primary_squeeze_pressed_ = false;
1980 this.primary_squeeze_clicked_ = false;
1981
1982 this.mojo_from_input_ = null;
1983 if (fakeInputSourceInit.gripOrigin != null) {
1984 this.setGripOrigin(fakeInputSourceInit.gripOrigin);
1985 }
1986
1987 // This properly handles if supportedButtons were not specified.
1988 this.setSupportedButtons(fakeInputSourceInit.supportedButtons);
1989
1990 this.emulated_position_ = false;
1991 this.desc_dirty_ = true;
1992 }
1993
1994 // WebXR Test API
1995 setHandedness(handedness) {
1996 if (this.handedness_ != handedness) {
1997 this.desc_dirty_ = true;
1998 this.handedness_ = handedness;
1999 }
2000 }
2001
2002 setTargetRayMode(targetRayMode) {
2003 if (this.target_ray_mode_ != targetRayMode) {
2004 this.desc_dirty_ = true;
2005 this.target_ray_mode_ = targetRayMode;
2006 }
2007 }
2008
2009 setProfiles(profiles) {
2010 this.desc_dirty_ = true;
2011 this.profiles_ = profiles;
2012 }
2013
2014 setGripOrigin(transform, emulatedPosition = false) {
2015 // grip_origin was renamed to mojo_from_input in mojo
2016 this.mojo_from_input_ = composeGFXTransform(transform);
2017 this.emulated_position_ = emulatedPosition;
2018
2019 // Technically, setting the grip shouldn't make the description dirty, but
2020 // the webxr-test-api sets our pointer as mojoFromPointer; however, we only
2021 // support it across mojom as inputFromPointer, so we need to recalculate it
2022 // whenever the grip moves.
2023 this.desc_dirty_ = true;
2024 }
2025
2026 clearGripOrigin() {
2027 // grip_origin was renamed to mojo_from_input in mojo
2028 if (this.mojo_from_input_ != null) {
2029 this.mojo_from_input_ = null;
2030 this.emulated_position_ = false;
2031 this.desc_dirty_ = true;
2032 }
2033 }
2034
2035 setPointerOrigin(transform, emulatedPosition = false) {
2036 // pointer_origin is mojo_from_pointer.
2037 this.desc_dirty_ = true;
2038 this.mojo_from_pointer_ = composeGFXTransform(transform);
2039 this.emulated_position_ = emulatedPosition;
2040 }
2041
2042 disconnect() {
2043 this.pairedDevice_._removeInputSource(this);
2044 }
2045
2046 reconnect() {
2047 this.pairedDevice_._addInputSource(this);
2048 }
2049
2050 startSelection() {
2051 this.primary_input_pressed_ = true;
2052 if (this.gamepad_) {
2053 this.gamepad_.buttons[0].pressed = true;
2054 this.gamepad_.buttons[0].touched = true;
2055 }
2056 }
2057
2058 endSelection() {
2059 if (!this.primary_input_pressed_) {
2060 throw new Error("Attempted to end selection which was not started");
2061 }
2062
2063 this.primary_input_pressed_ = false;
2064 this.primary_input_clicked_ = true;
2065
2066 if (this.gamepad_) {
2067 this.gamepad_.buttons[0].pressed = false;
2068 this.gamepad_.buttons[0].touched = false;
2069 }
2070 }
2071
2072 simulateSelect() {
2073 this.primary_input_clicked_ = true;
2074 }
2075
2076 setSupportedButtons(supportedButtons) {
2077 this.gamepad_ = null;
2078 this.supported_buttons_ = [];
2079
2080 // If there are no supported buttons, we can stop now.
2081 if (supportedButtons == null || supportedButtons.length < 1) {
2082 return;
2083 }
2084
2085 const supported_button_map = {};
2086 this.gamepad_ = this._getEmptyGamepad();
2087 for (let i = 0; i < supportedButtons.length; i++) {
2088 const buttonType = supportedButtons[i].buttonType;
2089 this.supported_buttons_.push(buttonType);
2090 supported_button_map[buttonType] = supportedButtons[i];
2091 }
2092
2093 // Let's start by building the button state in order of priority:
2094 // Primary button is index 0.
2095 this.gamepad_.buttons.push({
2096 pressed: this.primary_input_pressed_,
2097 touched: this.primary_input_pressed_,
2098 value: this.primary_input_pressed_ ? 1.0 : 0.0
2099 });
2100
2101 // Now add the rest of our buttons
2102 this._addGamepadButton(supported_button_map['grip']);
2103 this._addGamepadButton(supported_button_map['touchpad']);
2104 this._addGamepadButton(supported_button_map['thumbstick']);
2105 this._addGamepadButton(supported_button_map['optional-button']);
2106 this._addGamepadButton(supported_button_map['optional-thumbstick']);
2107
2108 // Finally, back-fill placeholder buttons/axes
2109 for (let i = 0; i < this.gamepad_.buttons.length; i++) {
2110 if (this.gamepad_.buttons[i] == null) {
2111 this.gamepad_.buttons[i] = {
2112 pressed: false,
2113 touched: false,
2114 value: 0
2115 };
2116 }
2117 }
2118
2119 for (let i=0; i < this.gamepad_.axes.length; i++) {
2120 if (this.gamepad_.axes[i] == null) {
2121 this.gamepad_.axes[i] = 0;
2122 }
2123 }
2124 }
2125
2126 updateButtonState(buttonState) {
2127 if (this.supported_buttons_.indexOf(buttonState.buttonType) == -1) {
2128 throw new Error("Tried to update state on an unsupported button");
2129 }
2130
2131 const buttonIndex = this._getButtonIndex(buttonState.buttonType);
2132 const axesStartIndex = this._getAxesStartIndex(buttonState.buttonType);
2133
2134 if (buttonIndex == -1) {
2135 throw new Error("Unknown Button Type!");
2136 }
2137
2138 // is this a 'squeeze' button?
2139 if (buttonIndex === this._getButtonIndex('grip')) {
2140 // squeeze
2141 if (buttonState.pressed) {
2142 this.primary_squeeze_pressed_ = true;
2143 } else if (this.gamepad_.buttons[buttonIndex].pressed) {
2144 this.primary_squeeze_clicked_ = true;
2145 this.primary_squeeze_pressed_ = false;
2146 } else {
2147 this.primary_squeeze_clicked_ = false;
2148 this.primary_squeeze_pressed_ = false;
2149 }
2150 }
2151
2152 this.gamepad_.buttons[buttonIndex].pressed = buttonState.pressed;
2153 this.gamepad_.buttons[buttonIndex].touched = buttonState.touched;
2154 this.gamepad_.buttons[buttonIndex].value = buttonState.pressedValue;
2155
2156 if (axesStartIndex != -1) {
2157 this.gamepad_.axes[axesStartIndex] = buttonState.xValue == null ? 0.0 : buttonState.xValue;
2158 this.gamepad_.axes[axesStartIndex + 1] = buttonState.yValue == null ? 0.0 : buttonState.yValue;
2159 }
2160 }
2161
2162 // DOM Overlay Extensions
2163 setOverlayPointerPosition(x, y) {
2164 this.overlay_pointer_position_ = {x: x, y: y};
2165 }
2166
2167 // Helpers for Mojom
2168 _getInputSourceState() {
2169 const input_state = {};
2170
2171 input_state.sourceId = this.source_id_;
2172 input_state.isAuxiliary = false;
2173
2174 input_state.primaryInputPressed = this.primary_input_pressed_;
2175 input_state.primaryInputClicked = this.primary_input_clicked_;
2176
2177 input_state.primarySqueezePressed = this.primary_squeeze_pressed_;
2178 input_state.primarySqueezeClicked = this.primary_squeeze_clicked_;
2179 // Setting the input source's "clicked" state should generate one "select"
2180 // event. Reset the input value to prevent it from continuously generating
2181 // events.
2182 this.primary_input_clicked_ = false;
2183 // Setting the input source's "clicked" state should generate one "squeeze"
2184 // event. Reset the input value to prevent it from continuously generating
2185 // events.
2186 this.primary_squeeze_clicked_ = false;
2187
2188 input_state.mojoFromInput = this.mojo_from_input_;
2189
2190 input_state.gamepad = this.gamepad_;
2191
2192 input_state.emulatedPosition = this.emulated_position_;
2193
2194 if (this.desc_dirty_) {
2195 const input_desc = {};
2196
2197 switch (this.target_ray_mode_) {
2198 case 'gaze':
2199 input_desc.targetRayMode = vrMojom.XRTargetRayMode.GAZING;
2200 break;
2201 case 'tracked-pointer':
2202 input_desc.targetRayMode = vrMojom.XRTargetRayMode.POINTING;
2203 break;
2204 case 'screen':
2205 input_desc.targetRayMode = vrMojom.XRTargetRayMode.TAPPING;
2206 break;
2207 default:
2208 throw new Error('Unhandled target ray mode ' + this.target_ray_mode_);
2209 }
2210
2211 switch (this.handedness_) {
2212 case 'left':
2213 input_desc.handedness = vrMojom.XRHandedness.LEFT;
2214 break;
2215 case 'right':
2216 input_desc.handedness = vrMojom.XRHandedness.RIGHT;
2217 break;
2218 default:
2219 input_desc.handedness = vrMojom.XRHandedness.NONE;
2220 break;
2221 }
2222
2223 // Mojo requires us to send the pointerOrigin as relative to the grip
2224 // space. If we don't have a grip space, we'll just assume that there
2225 // is a grip at identity. This allows tests to simulate controllers that
2226 // are really just a pointer with no tracked grip, though we will end up
2227 // exposing that grip space.
2228 let mojo_from_input = XRMathHelper.identity();
2229 switch (this.target_ray_mode_) {
2230 case 'gaze':
2231 case 'screen':
2232 // For gaze and screen space, we won't have a mojo_from_input; however
2233 // the "input" position is just the viewer, so use mojo_from_viewer.
2234 mojo_from_input = this.pairedDevice_._getMojoFromViewer();
2235 break;
2236 case 'tracked-pointer':
2237 // If we have a tracked grip position (e.g. mojo_from_input), then use
2238 // that. If we don't, then we'll just set the pointer offset directly,
2239 // using identity as set above.
2240 if (this.mojo_from_input_) {
2241 mojo_from_input = this.mojo_from_input_.matrix;
2242 }
2243 break;
2244 default:
2245 throw new Error('Unhandled target ray mode ' + this.target_ray_mode_);
2246 }
2247
2248 // To convert mojo_from_pointer to input_from_pointer, we need:
2249 // input_from_pointer = input_from_mojo * mojo_from_pointer
2250 // Since we store mojo_from_input, we need to invert it here before
2251 // multiplying.
2252 let input_from_mojo = XRMathHelper.inverse(mojo_from_input);
2253 input_desc.inputFromPointer = {};
2254 input_desc.inputFromPointer.matrix =
2255 XRMathHelper.mul4x4(input_from_mojo, this.mojo_from_pointer_.matrix);
2256
2257 input_desc.profiles = this.profiles_;
2258
2259 input_state.description = input_desc;
2260
2261 this.desc_dirty_ = false;
2262 }
2263
2264 // Pointer data for DOM Overlay, set by setOverlayPointerPosition()
2265 if (this.overlay_pointer_position_) {
2266 input_state.overlayPointerPosition = this.overlay_pointer_position_;
2267 this.overlay_pointer_position_ = null;
2268 }
2269
2270 return input_state;
2271 }
2272
2273 _getEmptyGamepad() {
2274 // Mojo complains if some of the properties on Gamepad are null, so set
2275 // everything to reasonable defaults that tests can override.
2276 const gamepad = {
2277 connected: true,
2278 id: [],
2279 timestamp: 0n,
2280 axes: [],
2281 buttons: [],
2282 touchEvents: [],
2283 mapping: GamepadMapping.GamepadMappingStandard,
2284 displayId: 0,
2285 };
2286
2287 switch (this.handedness_) {
2288 case 'left':
2289 gamepad.hand = GamepadHand.GamepadHandLeft;
2290 break;
2291 case 'right':
2292 gamepad.hand = GamepadHand.GamepadHandRight;
2293 break;
2294 default:
2295 gamepad.hand = GamepadHand.GamepadHandNone;
2296 break;
2297 }
2298
2299 return gamepad;
2300 }
2301
2302 _addGamepadButton(buttonState) {
2303 if (buttonState == null) {
2304 return;
2305 }
2306
2307 const buttonIndex = this._getButtonIndex(buttonState.buttonType);
2308 const axesStartIndex = this._getAxesStartIndex(buttonState.buttonType);
2309
2310 if (buttonIndex == -1) {
2311 throw new Error("Unknown Button Type!");
2312 }
2313
2314 this.gamepad_.buttons[buttonIndex] = {
2315 pressed: buttonState.pressed,
2316 touched: buttonState.touched,
2317 value: buttonState.pressedValue
2318 };
2319
2320 // Add x/y value if supported.
2321 if (axesStartIndex != -1) {
2322 this.gamepad_.axes[axesStartIndex] = (buttonState.xValue == null ? 0.0 : buttonSate.xValue);
2323 this.gamepad_.axes[axesStartIndex + 1] = (buttonState.yValue == null ? 0.0 : buttonSate.yValue);
2324 }
2325 }
2326
2327 // General Helper methods
2328 _getButtonIndex(buttonType) {
2329 switch (buttonType) {
2330 case 'grip':
2331 return 1;
2332 case 'touchpad':
2333 return 2;
2334 case 'thumbstick':
2335 return 3;
2336 case 'optional-button':
2337 return 4;
2338 case 'optional-thumbstick':
2339 return 5;
2340 default:
2341 return -1;
2342 }
2343 }
2344
2345 _getAxesStartIndex(buttonType) {
2346 switch (buttonType) {
2347 case 'touchpad':
2348 return 0;
2349 case 'thumbstick':
2350 return 2;
2351 case 'optional-thumbstick':
2352 return 4;
2353 default:
2354 return -1;
2355 }
2356 }
2357
2358 _getMojoFromInputSource(mojo_from_viewer) {
2359 return this.mojo_from_pointer_.matrix;
2360 }
2361 }
2362
2363 // Mojo helper classes
2364 class FakeXRHitTestSourceController {
2365 constructor(id) {
2366 this.id_ = id;
2367 this.deleted_ = false;
2368 }
2369
2370 get deleted() {
2371 return this.deleted_;
2372 }
2373
2374 // Internal setter:
2375 set deleted(value) {
2376 this.deleted_ = value;
2377 }
2378 }
2379
2380 class MockXRPresentationProvider {
2381 constructor() {
2382 this.receiver_ = null;
2383 this.submit_frame_count_ = 0;
2384 this.missing_frame_count_ = 0;
2385 }
2386
2387 _bindProvider() {
2388 const provider = new vrMojom.XRPresentationProviderRemote();
2389
2390 if (this.receiver_) {
2391 this.receiver_.$.close();
2392 }
2393 this.receiver_ = new vrMojom.XRPresentationProviderReceiver(this);
2394 this.receiver_.$.bindHandle(provider.$.bindNewPipeAndPassReceiver().handle);
2395 return provider;
2396 }
2397
2398 _getClientReceiver() {
2399 this.submitFrameClient_ = new vrMojom.XRPresentationClientRemote();
2400 return this.submitFrameClient_.$.bindNewPipeAndPassReceiver();
2401 }
2402
2403 // XRPresentationProvider mojo implementation
2404 updateLayerBounds(frameId, leftBounds, rightBounds, sourceSize) {}
2405
2406 submitFrameMissing(frameId, mailboxHolder, timeWaited) {
2407 this.missing_frame_count_++;
2408 }
2409
2410 submitFrame(frameId, mailboxHolder, timeWaited) {
2411 this.submit_frame_count_++;
2412
2413 // Trigger the submit completion callbacks here. WARNING: The
2414 // Javascript-based mojo mocks are *not* re-entrant. It's OK to
2415 // wait for these notifications on the next frame, but waiting
2416 // within the current frame would never finish since the incoming
2417 // calls would be queued until the current execution context finishes.
2418 this.submitFrameClient_.onSubmitFrameTransferred(true);
2419 this.submitFrameClient_.onSubmitFrameRendered();
2420 }
2421
2422 submitFrameWithTextureHandle(frameId, texture, syncToken) {}
2423
2424 submitFrameDrawnIntoTexture(frameId, syncToken, timeWaited) {}
2425
2426 // Utility methods
2427 _close() {
2428 if (this.receiver_) {
2429 this.receiver_.$.close();
2430 }
2431 }
2432 }
2433
2434 // Export these into the global object as a side effect of importing this
2435 // module.
2436 self.ChromeXRTest = ChromeXRTest;
2437 self.MockRuntime = MockRuntime;
2438 self.MockVRService = MockVRService;
2439 self.SubscribeToHitTestResult = vrMojom.SubscribeToHitTestResult;
2440
2441 navigator.xr.test = new ChromeXRTest();