Best JavaScript code snippet using wpt
webxr-test.js
Source:webxr-test.js
...164 supportsSession(sessionOptions) {165 const requests = [];166 // Check supports on all the runtimes.167 for (let i = 0; i < this.runtimes_.length; i++) {168 requests[i] = this.runtimes_[i]._runtimeSupportsSession(sessionOptions);169 }170 return Promise.all(requests).then((results) => {171 // Find and return the first successful result.172 for (let i = 0; i < results.length; i++) {173 if (results[i].supportsSession) {174 return results[i];175 }176 }177 // If there were no successful results, returns false.178 return {supportsSession: false};179 });180 }181 exitPresent() {182 return Promise.resolve();183 }184 setFramesThrottled(throttled) {185 this.setFramesThrottledImpl(throttled);186 }187 // We cannot override the mojom interceptors via the prototype; so this method188 // and the above indirection exist to allow overrides by internal code.189 setFramesThrottledImpl(throttled) {}190 // Only handles asynchronous calls to makeXrCompatible. Synchronous calls are191 // not supported in Javascript.192 makeXrCompatible() {193 if (this.runtimes_.length == 0) {194 return {195 xrCompatibleResult: vrMojom.XrCompatibleResult.kNoDeviceAvailable196 };197 }198 return {xrCompatibleResult: vrMojom.XrCompatibleResult.kAlreadyCompatible};199 }200}201class FakeXRAnchorController {202 constructor() {203 // Private properties.204 this.device_ = null;205 this.id_ = null;206 this.dirty_ = true;207 // Properties backing up public attributes / methods.208 this.deleted_ = false;209 this.paused_ = false;210 this.anchorOrigin_ = XRMathHelper.identity();211 }212 // WebXR Test API (Anchors Extension)213 get deleted() {214 return this.deleted_;215 }216 pauseTracking() {217 if(!this.paused_) {218 this.paused_ = true;219 this.dirty_ = true;220 }221 }222 resumeTracking() {223 if(this.paused_) {224 this.paused_ = false;225 this.dirty_ = true;226 }227 }228 stopTracking() {229 if(!this.deleted_) {230 this.device_._deleteAnchorController(this.id_);231 this.deleted_ = true;232 this.dirty_ = true;233 }234 }235 setAnchorOrigin(anchorOrigin) {236 this.anchorOrigin_ = getMatrixFromTransform(anchorOrigin);237 this.dirty_ = true;238 }239 // Internal implementation:240 set id(value) {241 this.id_ = value;242 }243 set device(value) {244 this.device_ = value;245 }246 get dirty() {247 return this.dirty_;248 }249 get paused() {250 return this.paused_;251 }252 _markProcessed() {253 this.dirty_ = false;254 }255 _getAnchorOrigin() {256 return this.anchorOrigin_;257 }258}259// Implements XRFrameDataProvider and XRPresentationProvider. Maintains a mock260// for XRPresentationProvider. Implements FakeXRDevice test API.261class MockRuntime {262 // Mapping from string feature names to the corresponding mojo types.263 // This is exposed as a member for extensibility.264 static _featureToMojoMap = {265 'viewer': vrMojom.XRSessionFeature.REF_SPACE_VIEWER,266 'local': vrMojom.XRSessionFeature.REF_SPACE_LOCAL,267 'local-floor': vrMojom.XRSessionFeature.REF_SPACE_LOCAL_FLOOR,268 'bounded-floor': vrMojom.XRSessionFeature.REF_SPACE_BOUNDED_FLOOR,269 'unbounded': vrMojom.XRSessionFeature.REF_SPACE_UNBOUNDED,270 'hit-test': vrMojom.XRSessionFeature.HIT_TEST,271 'dom-overlay': vrMojom.XRSessionFeature.DOM_OVERLAY,272 'light-estimation': vrMojom.XRSessionFeature.LIGHT_ESTIMATION,273 'anchors': vrMojom.XRSessionFeature.ANCHORS,274 'depth-sensing': vrMojom.XRSessionFeature.DEPTH,275 };276 static _sessionModeToMojoMap = {277 "inline": vrMojom.XRSessionMode.kInline,278 "immersive-vr": vrMojom.XRSessionMode.kImmersiveVr,279 "immersive-ar": vrMojom.XRSessionMode.kImmersiveAr,280 };281 static _environmentBlendModeToMojoMap = {282 "opaque": vrMojom.XREnvironmentBlendMode.kOpaque,283 "alpha-blend": vrMojom.XREnvironmentBlendMode.kAlphaBlend,284 "additive": vrMojom.XREnvironmentBlendMode.kAdditive,285 };286 static _interactionModeToMojoMap = {287 "screen-space": vrMojom.XRInteractionMode.kScreenSpace,288 "world-space": vrMojom.XRInteractionMode.kWorldSpace,289 };290 constructor(fakeDeviceInit, service) {291 this.sessionClient_ = null;292 this.presentation_provider_ = new MockXRPresentationProvider();293 this.pose_ = null;294 this.next_frame_id_ = 0;295 this.bounds_ = null;296 this.send_mojo_space_reset_ = false;297 this.stageParameters_ = null;298 this.stageParametersId_ = 1;299 this.service_ = service;300 this.framesOfReference = {};301 this.input_sources_ = new Map();302 this.next_input_source_index_ = 1;303 // Currently active hit test subscriptons.304 this.hitTestSubscriptions_ = new Map();305 // Currently active transient hit test subscriptions.306 this.transientHitTestSubscriptions_ = new Map();307 // ID of the next subscription to be assigned.308 this.next_hit_test_id_ = 1n;309 this.anchor_controllers_ = new Map();310 // ID of the next anchor to be assigned.311 this.next_anchor_id_ = 1n;312 // Anchor creation callback (initially null, can be set by tests).313 this.anchor_creation_callback_ = null;314 this.depthSensingData_ = null;315 this.depthSensingDataDirty_ = false;316 let supportedModes = [];317 if (fakeDeviceInit.supportedModes) {318 supportedModes = fakeDeviceInit.supportedModes.slice();319 if (fakeDeviceInit.supportedModes.length === 0) {320 supportedModes = ["inline"];321 }322 } else {323 // Back-compat mode.324 console.warn("Please use `supportedModes` to signal which modes are supported by this device.");325 if (fakeDeviceInit.supportsImmersive == null) {326 throw new TypeError("'supportsImmersive' must be set");327 }328 supportedModes = ["inline"];329 if (fakeDeviceInit.supportsImmersive) {330 supportedModes.push("immersive-vr");331 }332 }333 this.supportedModes_ = this._convertModesToEnum(supportedModes);334 // Initialize DisplayInfo first to set the defaults, then override with335 // anything from the deviceInit336 if (this.supportedModes_.includes(vrMojom.XRSessionMode.kImmersiveVr) ||337 this.supportedModes_.includes(vrMojom.XRSessionMode.kImmersiveAr)) {338 this.displayInfo_ = this._getImmersiveDisplayInfo();339 } else if (this.supportedModes_.includes(vrMojom.XRSessionMode.kInline)) {340 this.displayInfo_ = this._getNonImmersiveDisplayInfo();341 } else {342 // This should never happen!343 console.error("Device has empty supported modes array!");344 throw new InvalidStateError();345 }346 if (fakeDeviceInit.viewerOrigin != null) {347 this.setViewerOrigin(fakeDeviceInit.viewerOrigin);348 }349 if (fakeDeviceInit.floorOrigin != null) {350 this.setFloorOrigin(fakeDeviceInit.floorOrigin);351 }352 if (fakeDeviceInit.world) {353 this.setWorld(fakeDeviceInit.world);354 }355 if (fakeDeviceInit.depthSensingData) {356 this.setDepthSensingData(fakeDeviceInit.depthSensingData);357 }358 this.defaultFramebufferScale_ = default_framebuffer_scale;359 this.enviromentBlendMode_ = this._convertBlendModeToEnum(fakeDeviceInit.environmentBlendMode);360 this.interactionMode_ = this._convertInteractionModeToEnum(fakeDeviceInit.interactionMode);361 // This appropriately handles if the coordinates are null362 this.setBoundsGeometry(fakeDeviceInit.boundsCoordinates);363 this.setViews(fakeDeviceInit.views);364 // Need to support webVR which doesn't have a notion of features365 this._setFeatures(fakeDeviceInit.supportedFeatures || []);366 }367 // WebXR Test API368 setViews(views) {369 if (views) {370 this.displayInfo_.views = [];371 this.viewOffsets_ = [];372 for (let i = 0; i < views.length; i++) {373 this.displayInfo_.views[i] = this._getView(views[i]);374 this.viewOffsets_[i] = composeGFXTransform(views[i].viewOffset);375 }376 if (this.sessionClient_) {377 this.sessionClient_.onChanged(this.displayInfo_);378 }379 }380 }381 disconnect() {382 this.service_._removeRuntime(this);383 this.presentation_provider_._close();384 if (this.sessionClient_) {385 this.sessionClient_.$.close();386 this.sessionClient_ = null;387 }388 return Promise.resolve();389 }390 setViewerOrigin(origin, emulatedPosition = false) {391 const p = origin.position;392 const q = origin.orientation;393 this.pose_ = {394 orientation: { x: q[0], y: q[1], z: q[2], w: q[3] },395 position: { x: p[0], y: p[1], z: p[2] },396 emulatedPosition: emulatedPosition,397 angularVelocity: null,398 linearVelocity: null,399 angularAcceleration: null,400 linearAcceleration: null,401 inputState: null,402 poseIndex: 0403 };404 }405 clearViewerOrigin() {406 this.pose_ = null;407 }408 setFloorOrigin(floorOrigin) {409 if (!this.stageParameters_) {410 this.stageParameters_ = default_stage_parameters;411 this.stageParameters_.bounds = this.bounds_;412 }413 // floorOrigin is passed in as mojoFromFloor.414 this.stageParameters_.mojoFromFloor =415 {matrix: getMatrixFromTransform(floorOrigin)};416 this._onStageParametersUpdated();417 }418 clearFloorOrigin() {419 if (this.stageParameters_) {420 this.stageParameters_ = null;421 this._onStageParametersUpdated();422 }423 }424 setBoundsGeometry(bounds) {425 if (bounds == null) {426 this.bounds_ = null;427 } else if (bounds.length < 3) {428 throw new Error("Bounds must have a length of at least 3");429 } else {430 this.bounds_ = bounds;431 }432 // We can only set bounds if we have stageParameters set; otherwise, we433 // don't know the transform from local space to bounds space.434 // We'll cache the bounds so that they can be set in the future if the435 // floorLevel transform is set, but we won't update them just yet.436 if (this.stageParameters_) {437 this.stageParameters_.bounds = this.bounds_;438 this._onStageParametersUpdated();439 }440 }441 simulateResetPose() {442 this.send_mojo_space_reset_ = true;443 }444 simulateVisibilityChange(visibilityState) {445 let mojoState = null;446 switch (visibilityState) {447 case "visible":448 mojoState = vrMojom.XRVisibilityState.VISIBLE;449 break;450 case "visible-blurred":451 mojoState = vrMojom.XRVisibilityState.VISIBLE_BLURRED;452 break;453 case "hidden":454 mojoState = vrMojom.XRVisibilityState.HIDDEN;455 break;456 }457 if (mojoState && this.sessionClient_) {458 this.sessionClient_.onVisibilityStateChanged(mojoState);459 }460 }461 simulateInputSourceConnection(fakeInputSourceInit) {462 const index = this.next_input_source_index_;463 this.next_input_source_index_++;464 const source = new MockXRInputSource(fakeInputSourceInit, index, this);465 this.input_sources_.set(index, source);466 return source;467 }468 // WebXR Test API Hit Test extensions469 setWorld(world) {470 this.world_ = world;471 }472 clearWorld() {473 this.world_ = null;474 }475 // WebXR Test API Anchor extensions476 setAnchorCreationCallback(callback) {477 this.anchor_creation_callback_ = callback;478 }479 setHitTestSourceCreationCallback(callback) {480 this.hit_test_source_creation_callback_ = callback;481 }482 // WebXR Test API Lighting estimation extensions483 setLightEstimate(fakeXrLightEstimateInit) {484 if (!fakeXrLightEstimateInit.sphericalHarmonicsCoefficients) {485 throw new TypeError("sphericalHarmonicsCoefficients must be set");486 }487 if (fakeXrLightEstimateInit.sphericalHarmonicsCoefficients.length != 27) {488 throw new TypeError("Must supply all 27 sphericalHarmonicsCoefficients");489 }490 if (fakeXrLightEstimateInit.primaryLightDirection && fakeXrLightEstimateInit.primaryLightDirection.w != 0) {491 throw new TypeError("W component of primaryLightDirection must be 0");492 }493 if (fakeXrLightEstimateInit.primaryLightIntensity && fakeXrLightEstimateInit.primaryLightIntensity.w != 1) {494 throw new TypeError("W component of primaryLightIntensity must be 1");495 }496 // If the primaryLightDirection or primaryLightIntensity aren't set, we need to set them497 // to the defaults that the spec expects. ArCore will either give us everything or nothing,498 // so these aren't nullable on the mojom.499 if (!fakeXrLightEstimateInit.primaryLightDirection) {500 fakeXrLightEstimateInit.primaryLightDirection = { x: 0.0, y: 1.0, z: 0.0, w: 0.0 };501 }502 if (!fakeXrLightEstimateInit.primaryLightIntensity) {503 fakeXrLightEstimateInit.primaryLightIntensity = { x: 0.0, y: 0.0, z: 0.0, w: 1.0 };504 }505 let c = fakeXrLightEstimateInit.sphericalHarmonicsCoefficients;506 this.light_estimate_ = {507 lightProbe: {508 // XRSphereicalHarmonics509 sphericalHarmonics: {510 coefficients: [511 { red: c[0], green: c[1], blue: c[2] },512 { red: c[3], green: c[4], blue: c[5] },513 { red: c[6], green: c[7], blue: c[8] },514 { red: c[9], green: c[10], blue: c[11] },515 { red: c[12], green: c[13], blue: c[14] },516 { red: c[15], green: c[16], blue: c[17] },517 { red: c[18], green: c[19], blue: c[20] },518 { red: c[21], green: c[22], blue: c[23] },519 { red: c[24], green: c[25], blue: c[26] }520 ]521 },522 // Vector3dF523 mainLightDirection: {524 x: fakeXrLightEstimateInit.primaryLightDirection.x,525 y: fakeXrLightEstimateInit.primaryLightDirection.y,526 z: fakeXrLightEstimateInit.primaryLightDirection.z527 },528 // RgbTupleF32529 mainLightIntensity: {530 red: fakeXrLightEstimateInit.primaryLightIntensity.x,531 green: fakeXrLightEstimateInit.primaryLightIntensity.y,532 blue: fakeXrLightEstimateInit.primaryLightIntensity.z533 }534 }535 }536 }537 // WebXR Test API depth Sensing Extensions538 setDepthSensingData(depthSensingData) {539 for(const key of ["depthData", "normDepthBufferFromNormView", "rawValueToMeters", "width", "height"]) {540 if(!(key in depthSensingData)) {541 throw new TypeError("Required key not present. Key: " + key);542 }543 }544 if(depthSensingData.depthData != null) {545 // Create new object w/ properties based on the depthSensingData, but546 // convert the FakeXRRigidTransformInit into a transformation matrix object.547 this.depthSensingData_ = Object.assign({},548 depthSensingData, {549 normDepthBufferFromNormView: composeGFXTransform(depthSensingData.normDepthBufferFromNormView),550 });551 } else {552 throw new TypeError("`depthData` is not set");553 }554 this.depthSensingDataDirty_ = true;555 }556 clearDepthSensingData() {557 this.depthSensingData_ = null;558 this.depthSensingDataDirty_ = true;559 }560 // Internal Implementation/Helper Methods561 _convertModeToEnum(sessionMode) {562 if (sessionMode in MockRuntime._sessionModeToMojoMap) {563 return MockRuntime._sessionModeToMojoMap[sessionMode];564 }565 throw new TypeError("Unrecognized value for XRSessionMode enum: " + sessionMode);566 }567 _convertModesToEnum(sessionModes) {568 return sessionModes.map(mode => this._convertModeToEnum(mode));569 }570 _convertBlendModeToEnum(blendMode) {571 if (blendMode in MockRuntime._environmentBlendModeToMojoMap) {572 return MockRuntime._environmentBlendModeToMojoMap[blendMode];573 } else {574 if (this.supportedModes_.includes(vrMojom.XRSessionMode.kImmersiveAr)) {575 return vrMojom.XREnvironmentBlendMode.kAdditive;576 } else if (this.supportedModes_.includes(577 vrMojom.XRSessionMode.kImmersiveVr)) {578 return vrMojom.XREnvironmentBlendMode.kOpaque;579 }580 }581 }582 _convertInteractionModeToEnum(interactionMode) {583 if (interactionMode in MockRuntime._interactionModeToMojoMap) {584 return MockRuntime._interactionModeToMojoMap[interactionMode];585 } else {586 return vrMojom.XRInteractionMode.kWorldSpace;587 }588 }589 _onStageParametersUpdated() {590 // Indicate for the frame loop that the stage parameters have been updated.591 this.stageParametersId_++;592 }593 _getNonImmersiveDisplayInfo() {594 const displayInfo = this._getImmersiveDisplayInfo();595 displayInfo.capabilities.canPresent = false;596 displayInfo.views = [];597 return displayInfo;598 }599 // Function to generate some valid display information for the device.600 _getImmersiveDisplayInfo() {601 const viewport_size = 20;602 return {603 displayName: 'FakeDevice',604 capabilities: {605 hasPosition: false,606 hasExternalDisplay: false,607 canPresent: true,608 maxLayers: 1609 },610 stageParameters: null,611 views: [{612 eye: vrMojom.XREye.kLeft,613 fieldOfView: {614 upDegrees: 48.316,615 downDegrees: 50.099,616 leftDegrees: 50.899,617 rightDegrees: 35.197618 },619 mojoFromView: this._getMojoFromViewerWithOffset(composeGFXTransform({620 position: [-0.032, 0, 0],621 orientation: [0, 0, 0, 1]622 })),623 viewport: { width: viewport_size, height: viewport_size }624 },625 {626 eye: vrMojom.XREye.kRight,627 fieldOfView: {628 upDegrees: 48.316,629 downDegrees: 50.099,630 leftDegrees: 50.899,631 rightDegrees: 35.197632 },633 mojoFromView: this._getMojoFromViewerWithOffset(composeGFXTransform({634 position: [0.032, 0, 0],635 orientation: [0, 0, 0, 1]636 })),637 viewport: { width: viewport_size, height: viewport_size }638 }]639 };640 }641 // This function converts between the matrix provided by the WebXR test API642 // and the internal data representation.643 _getView(fakeXRViewInit) {644 let fov = null;645 if (fakeXRViewInit.fieldOfView) {646 fov = {647 upDegrees: fakeXRViewInit.fieldOfView.upDegrees,648 downDegrees: fakeXRViewInit.fieldOfView.downDegrees,649 leftDegrees: fakeXRViewInit.fieldOfView.leftDegrees,650 rightDegrees: fakeXRViewInit.fieldOfView.rightDegrees651 };652 } else {653 const m = fakeXRViewInit.projectionMatrix;654 function toDegrees(tan) {655 return Math.atan(tan) * 180 / Math.PI;656 }657 const leftTan = (1 - m[8]) / m[0];658 const rightTan = (1 + m[8]) / m[0];659 const upTan = (1 + m[9]) / m[5];660 const downTan = (1 - m[9]) / m[5];661 fov = {662 upDegrees: toDegrees(upTan),663 downDegrees: toDegrees(downTan),664 leftDegrees: toDegrees(leftTan),665 rightDegrees: toDegrees(rightTan)666 };667 }668 let viewEye = vrMojom.XREye.kNone;669 // The eye passed in corresponds to the values in the WebXR spec, which are670 // the strings "none", "left", and "right". They should be converted to the671 // corresponding values of XREye in vr_service.mojom.672 switch(fakeXRViewInit.eye) {673 case "none":674 viewEye = vrMojom.XREye.kNone;675 break;676 case "left":677 viewEye = vrMojom.XREye.kLeft;678 break;679 case "right":680 viewEye = vrMojom.XREye.kRight;681 break;682 }683 return {684 eye: viewEye,685 fieldOfView: fov,686 mojoFromView: this._getMojoFromViewerWithOffset(composeGFXTransform(fakeXRViewInit.viewOffset)),687 viewport: {688 width: fakeXRViewInit.resolution.width,689 height: fakeXRViewInit.resolution.height690 }691 };692 }693 _setFeatures(supportedFeatures) {694 function convertFeatureToMojom(feature) {695 if (feature in MockRuntime._featureToMojoMap) {696 return MockRuntime._featureToMojoMap[feature];697 } else {698 return vrMojom.XRSessionFeature.INVALID;699 }700 }701 this.supportedFeatures_ = [];702 for (let i = 0; i < supportedFeatures.length; i++) {703 const feature = convertFeatureToMojom(supportedFeatures[i]);704 if (feature !== vrMojom.XRSessionFeature.INVALID) {705 this.supportedFeatures_.push(feature);706 }707 }708 }709 // These methods are intended to be used by MockXRInputSource only.710 _addInputSource(source) {711 if (!this.input_sources_.has(source.source_id_)) {712 this.input_sources_.set(source.source_id_, source);713 }714 }715 _removeInputSource(source) {716 this.input_sources_.delete(source.source_id_);717 }718 // These methods are intended to be used by FakeXRAnchorController only.719 _deleteAnchorController(controllerId) {720 this.anchor_controllers_.delete(controllerId);721 }722 // Extension point for non-standard modules.723 _injectAdditionalFrameData(options, frameData) {724 }725 // Mojo function implementations.726 // XRFrameDataProvider implementation.727 getFrameData(options) {728 return new Promise((resolve) => {729 const populatePose = () => {730 const mojo_space_reset = this.send_mojo_space_reset_;731 this.send_mojo_space_reset_ = false;732 if (this.pose_) {733 this.pose_.poseIndex++;734 }735 // Setting the input_state to null tests a slightly different path than736 // the browser tests where if the last input source is removed, the device737 // code always sends up an empty array, but it's also valid mojom to send738 // up a null array.739 let input_state = null;740 if (this.input_sources_.size > 0) {741 input_state = [];742 for (const input_source of this.input_sources_.values()) {743 input_state.push(input_source._getInputSourceState());744 }745 }746 let views = this.displayInfo_.views;747 for (let i = 0; i < views.length; i++) {748 views[i].mojoFromView = this._getMojoFromViewerWithOffset(this.viewOffsets_[i]);749 }750 const frameData = {751 mojoFromViewer: this.pose_,752 views: views,753 mojoSpaceReset: mojo_space_reset,754 inputState: input_state,755 timeDelta: {756 // window.performance.now() is in milliseconds, so convert to microseconds.757 microseconds: BigInt(Math.floor(window.performance.now() * 1000)),758 },759 frameId: this.next_frame_id_,760 bufferHolder: null,761 bufferSize: {},762 renderingTimeRatio: 0,763 stageParameters: this.stageParameters_,764 stageParametersId: this.stageParametersId_,765 lightEstimationData: this.light_estimate_766 };767 this.next_frame_id_++;768 this._calculateHitTestResults(frameData);769 this._calculateAnchorInformation(frameData);770 this._calculateDepthInformation(frameData);771 this._injectAdditionalFrameData(options, frameData);772 resolve({frameData});773 };774 if(this.sessionOptions_.mode == vrMojom.XRSessionMode.kInline) {775 // Inline sessions should not have a delay introduced since it causes them776 // to miss a vsync blink-side and delays propagation of changes that happened777 // within a rAFcb by one frame (e.g. setViewerOrigin() calls would take 2 frames778 // to propagate).779 populatePose();780 } else {781 // For immerive sessions, add additional delay to allow for anchor creation782 // promises to run.783 setTimeout(populatePose, 3); // note: according to MDN, the timeout is not exact784 }785 });786 }787 getEnvironmentIntegrationProvider(environmentProviderRequest) {788 if (this.environmentProviderReceiver_) {789 this.environmentProviderReceiver_.$.close();790 }791 this.environmentProviderReceiver_ =792 new vrMojom.XREnvironmentIntegrationProviderReceiver(this);793 this.environmentProviderReceiver_.$.bindHandle(794 environmentProviderRequest.handle);795 }796 setInputSourceButtonListener(listener) { listener.$.close(); }797 // XREnvironmentIntegrationProvider implementation:798 subscribeToHitTest(nativeOriginInformation, entityTypes, ray) {799 if (!this.supportedModes_.includes(vrMojom.XRSessionMode.kImmersiveAr)) {800 // Reject outside of AR.801 return Promise.resolve({802 result : vrMojom.SubscribeToHitTestResult.FAILURE_GENERIC,803 subscriptionId : 0n804 });805 }806 if (!this._nativeOriginKnown(nativeOriginInformation)) {807 return Promise.resolve({808 result : vrMojom.SubscribeToHitTestResult.FAILURE_GENERIC,809 subscriptionId : 0n810 });811 }812 // Reserve the id for hit test source:813 const id = this.next_hit_test_id_++;814 const hitTestParameters = { isTransient: false, profileName: null };815 const controller = new FakeXRHitTestSourceController(id);816 return this._shouldHitTestSourceCreationSucceed(hitTestParameters, controller)817 .then((succeeded) => {818 if(succeeded) {819 // Store the subscription information as-is (including controller):820 this.hitTestSubscriptions_.set(id, { nativeOriginInformation, entityTypes, ray, controller });821 return Promise.resolve({822 result : vrMojom.SubscribeToHitTestResult.SUCCESS,823 subscriptionId : id824 });825 } else {826 return Promise.resolve({827 result : vrMojom.SubscribeToHitTestResult.FAILURE_GENERIC,828 subscriptionId : 0n829 });830 }831 });832 }833 subscribeToHitTestForTransientInput(profileName, entityTypes, ray){834 if (!this.supportedModes_.includes(vrMojom.XRSessionMode.kImmersiveAr)) {835 // Reject outside of AR.836 return Promise.resolve({837 result : vrMojom.SubscribeToHitTestResult.FAILURE_GENERIC,838 subscriptionId : 0n839 });840 }841 const id = this.next_hit_test_id_++;842 const hitTestParameters = { isTransient: true, profileName: profileName };843 const controller = new FakeXRHitTestSourceController(id);844 // Check if we have hit test source creation callback.845 // If yes, ask it if the hit test source creation should succeed.846 // If no, for back-compat, assume the hit test source creation succeeded.847 return this._shouldHitTestSourceCreationSucceed(hitTestParameters, controller)848 .then((succeeded) => {849 if(succeeded) {850 // Store the subscription information as-is (including controller):851 this.transientHitTestSubscriptions_.set(id, { profileName, entityTypes, ray, controller });852 return Promise.resolve({853 result : vrMojom.SubscribeToHitTestResult.SUCCESS,854 subscriptionId : id855 });856 } else {857 return Promise.resolve({858 result : vrMojom.SubscribeToHitTestResult.FAILURE_GENERIC,859 subscriptionId : 0n860 });861 }862 });863 }864 unsubscribeFromHitTest(subscriptionId) {865 let controller = null;866 if(this.transientHitTestSubscriptions_.has(subscriptionId)){867 controller = this.transientHitTestSubscriptions_.get(subscriptionId).controller;868 this.transientHitTestSubscriptions_.delete(subscriptionId);869 } else if(this.hitTestSubscriptions_.has(subscriptionId)){870 controller = this.hitTestSubscriptions_.get(subscriptionId).controller;871 this.hitTestSubscriptions_.delete(subscriptionId);872 }873 if(controller) {874 controller.deleted = true;875 }876 }877 createAnchor(nativeOriginInformation, nativeOriginFromAnchor) {878 return new Promise((resolve) => {879 if(this.anchor_creation_callback_ == null) {880 resolve({881 result : vrMojom.CreateAnchorResult.FAILURE,882 anchorId : 0n883 });884 return;885 }886 const mojoFromNativeOrigin = this._getMojoFromNativeOrigin(nativeOriginInformation);887 if(mojoFromNativeOrigin == null) {888 resolve({889 result : vrMojom.CreateAnchorResult.FAILURE,890 anchorId : 0n891 });892 return;893 }894 const mojoFromAnchor = XRMathHelper.mul4x4(mojoFromNativeOrigin, nativeOriginFromAnchor);895 const anchorCreationParameters = {896 requestedAnchorOrigin: mojoFromAnchor,897 isAttachedToEntity: false,898 };899 const anchorController = new FakeXRAnchorController();900 this.anchor_creation_callback_(anchorCreationParameters, anchorController)901 .then((result) => {902 if(result) {903 // If the test allowed the anchor creation,904 // store the anchor controller & return success.905 const anchor_id = this.next_anchor_id_;906 this.next_anchor_id_++;907 this.anchor_controllers_.set(anchor_id, anchorController);908 anchorController.device = this;909 anchorController.id = anchor_id;910 resolve({911 result : vrMojom.CreateAnchorResult.SUCCESS,912 anchorId : anchor_id913 });914 } else {915 // The test has rejected anchor creation.916 resolve({917 result : vrMojom.CreateAnchorResult.FAILURE,918 anchorId : 0n919 });920 }921 })922 .catch(() => {923 // The test threw an error, treat anchor creation as failed.924 resolve({925 result : vrMojom.CreateAnchorResult.FAILURE,926 anchorId : 0n927 });928 });929 });930 }931 createPlaneAnchor(planeFromAnchor, planeId) {932 return new Promise((resolve) => {933 // Not supported yet.934 resolve({935 result : vrMojom.CreateAnchorResult.FAILURE,936 anchorId : 0n,937 });938 });939 }940 detachAnchor(anchorId) {}941 // Utility function942 _requestRuntimeSession(sessionOptions) {943 return this._runtimeSupportsSession(sessionOptions).then((result) => {944 // The JavaScript bindings convert c_style_names to camelCase names.945 const options = {946 transportMethod:947 vrMojom.XRPresentationTransportMethod.SUBMIT_AS_MAILBOX_HOLDER,948 waitForTransferNotification: true,949 waitForRenderNotification: true,950 waitForGpuFence: false,951 };952 let submit_frame_sink;953 if (result.supportsSession) {954 submit_frame_sink = {955 clientReceiver: this.presentation_provider_._getClientReceiver(),956 provider: this.presentation_provider_._bindProvider(sessionOptions),957 transportOptions: options958 };959 const dataProviderPtr = new vrMojom.XRFrameDataProviderRemote();960 this.dataProviderReceiver_ =961 new vrMojom.XRFrameDataProviderReceiver(this);962 this.dataProviderReceiver_.$.bindHandle(963 dataProviderPtr.$.bindNewPipeAndPassReceiver().handle);964 this.sessionOptions_ = sessionOptions;965 this.sessionClient_ = new vrMojom.XRSessionClientRemote();966 const clientReceiver = this.sessionClient_.$.bindNewPipeAndPassReceiver();967 const enabled_features = [];968 for (let i = 0; i < sessionOptions.requiredFeatures.length; i++) {969 if (this.supportedFeatures_.indexOf(sessionOptions.requiredFeatures[i]) !== -1) {970 enabled_features.push(sessionOptions.requiredFeatures[i]);971 } else {972 return Promise.resolve({session: null});973 }974 }975 for (let i =0; i < sessionOptions.optionalFeatures.length; i++) {976 if (this.supportedFeatures_.indexOf(sessionOptions.optionalFeatures[i]) !== -1) {977 enabled_features.push(sessionOptions.optionalFeatures[i]);978 }979 }980 this.enabledFeatures_ = enabled_features;981 return Promise.resolve({982 session: {983 submitFrameSink: submit_frame_sink,984 dataProvider: dataProviderPtr,985 clientReceiver: clientReceiver,986 displayInfo: this.displayInfo_,987 enabledFeatures: enabled_features,988 deviceConfig: {989 usesInputEventing: false,990 defaultFramebufferScale: this.defaultFramebufferScale_,991 supportsViewportScaling: true,992 depthConfiguration:993 enabled_features.includes(vrMojom.XRSessionFeature.DEPTH) ? {994 depthUsage: vrMojom.XRDepthUsage.kCPUOptimized,995 depthDataFormat: vrMojom.XRDepthDataFormat.kLuminanceAlpha,996 } : null,997 },998 enviromentBlendMode: this.enviromentBlendMode_,999 interactionMode: this.interactionMode_1000 }1001 });1002 } else {1003 return Promise.resolve({session: null});1004 }1005 });1006 }1007 _runtimeSupportsSession(options) {1008 let result = this.supportedModes_.includes(options.mode);1009 if (options.requiredFeatures.includes(vrMojom.XRSessionFeature.DEPTH)1010 || options.optionalFeatures.includes(vrMojom.XRSessionFeature.DEPTH)) {1011 result &= options.depthOptions.usagePreferences.includes(vrMojom.XRDepthUsage.kCPUOptimized);1012 result &= options.depthOptions.dataFormatPreferences.includes(vrMojom.XRDepthDataFormat.kLuminanceAlpha);1013 }1014 return Promise.resolve({1015 supportsSession: result,1016 });1017 }1018 // Private functions - utilities:1019 _nativeOriginKnown(nativeOriginInformation){1020 if (nativeOriginInformation.inputSourceSpaceInfo !== undefined) {1021 if (!this.input_sources_.has(nativeOriginInformation.inputSourceSpaceInfo.inputSourceId)) {...
Using AI Code Generation
1var win = Components.classes["@mozilla.org/appshell/window-mediator;1"]2.getService(Components.interfaces.nsIWindowMediator)3.getMostRecentWindow("navigator:browser");4var wpt = win.wptoolkit;5var supportsSession = wpt._runtimeSupportsSession();6var win = Components.classes["@mozilla.org/appshell/window-mediator;1"]7.getService(Components.interfaces.nsIWindowMediator)8.getMostRecentWindow("navigator:browser");9var wpt = win.wptoolkit;10var supportsSession = wpt._runtimeSupportsSession();11wptoolkit._runtimeSupportsSession()12wptoolkit._runtimeGetCurrentSession()
Using AI Code Generation
1var wpt = require('wpt');2var wpt = new wpt('API_KEY');3wpt._runtimeSupportsSession(function(err, result) {4 if (err) {5 console.log(err);6 } else {7 console.log(result);8 }9});10var wpt = require('wpt');11var wpt = new wpt('API_KEY');12wpt._runtimeSupportsSession(function(err, result) {13 if (err) {14 console.log(err);15 } else {16 console.log(result);17 }18});19var wpt = require('wpt');20var wpt = new wpt('API_KEY');21wpt._runtimeSupportsSession(function(err, result) {22 if (err) {23 console.log(err);24 } else {25 console.log(result);26 }27});28var wpt = require('wpt');29var wpt = new wpt('API_KEY');30wpt._runtimeSupportsSession(function(err, result) {31 if (err) {32 console.log(err);33 } else {34 console.log(result);35 }36});37var wpt = require('wpt');38var wpt = new wpt('API_KEY');39wpt._runtimeSupportsSession(function(err, result) {40 if (err) {41 console.log(err);42 } else {43 console.log(result);44 }45});46var wpt = require('wpt');47var wpt = new wpt('API_KEY');48wpt._runtimeSupportsSession(function(err, result) {49 if (err) {50 console.log(err);51 } else {52 console.log(result);53 }54});
Using AI Code Generation
1var wptdriver = require('./wptdriver');2var wpt = new wptdriver();3wpt._runtimeSupportsSession(function(error, result) {4 console.log('error: ' + error);5 console.log('result: ' + result);6});7var Wptdriver = function () {8 this._runtimeSupportsSession = function(callback) {9 var error = 'error';10 var result = 'result';11 callback(error, result);12 };13};14module.exports = Wptdriver;15var wptdriver = require('./wptdriver');16var wpt = new wptdriver();17var async = require('async');18async.waterfall([19 function(callback) {20 wpt._runtimeSupportsSession(function(error, result) {21 console.log('error: ' + error);22 console.log('result: ' + result);23 });24 }25]);26var Wptdriver = function () {27 this._runtimeSupportsSession = function(callback) {28 var error = 'error';29 var result = 'result';30 callback(error, result);31 };32};33module.exports = Wptdriver;
Using AI Code Generation
1var wpt = require('wpt.js');2var wpt = new WebPageTest('www.webpagetest.org');3var wptOptions = {4};5wpt.runTest(testUrl, wptOptions, function(err, data) {6 if (err) {7 console.log(err);8 } else {9 console.log(data);10 }11});
Using AI Code Generation
1var wptk = require('wptoolkit');2var wptkUtil = new wptk.Util();3var wptkUtil = new wptk.Util();4var test = function(){5 this._runtimeSupportsSession = wptkUtil._runtimeSupportsSession;6 console.log(this._runtimeSupportsSession());7}8var testObj = new test();9testObj.test();
Using AI Code Generation
1if(_runtimeSupportsSession()){2 var name = sessionStorage.getItem("name");3 if(name){4 alert("Welcome back, " + name);5 }else{6 name = prompt("What is your name?");7 sessionStorage.setItem("name", name);8 alert("Thanks, " + name);9 }10}else{11 alert("Sorry, your browser doesn't support session storage.");12}13function _runtimeSupportsSession(){14 try{15 return 'sessionStorage' in window && window['sessionStorage'] !== null;16 }catch(e){17 return false;18 }19}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!