Best JavaScript code snippet using wpt
webxr-test.js
Source:webxr-test.js  
...751          anchorId : 0752        });753        return;754      }755      const mojoFromNativeOrigin = this._getMojoFromNativeOrigin(nativeOriginInformation);756      if(mojoFromNativeOrigin == null) {757        resolve({758          result : device.mojom.CreateAnchorResult.FAILURE,759          anchorId : 0760        });761        return;762      }763      const mojoFromAnchor = XRMathHelper.mul4x4(mojoFromNativeOrigin, nativeOriginFromAnchor);764      const anchorCreationParameters = {765        requestedAnchorOrigin: mojoFromAnchor,766        isAttachedToEntity: false,767      };768      const anchorController = new FakeXRAnchorController();769      this.anchor_creation_callback_(anchorCreationParameters, anchorController)770            .then((result) => {771              if(result) {772                // If the test allowed the anchor creation,773                // store the anchor controller & return success.774                const anchor_id = this.next_anchor_id_;775                this.next_anchor_id_++;776                this.anchor_controllers_.set(anchor_id, anchorController);777                anchorController.device = this;778                anchorController.id = anchor_id;779                resolve({780                  result : device.mojom.CreateAnchorResult.SUCCESS,781                  anchorId : anchor_id782                });783              } else {784                // The test has rejected anchor creation.785                resolve({786                  result : device.mojom.CreateAnchorResult.FAILURE,787                  anchorId : 0788                });789              }790            })791            .catch(() => {792              // The test threw an error, treat anchor creation as failed.793              resolve({794                result : device.mojom.CreateAnchorResult.FAILURE,795                anchorId : 0796              });797            });798    });799  }800  createPlaneAnchor(planeFromAnchor, planeId) {801    return new Promise((resolve) => {802      // Not supported yet.803      resolve({804        result : device.mojom.CreateAnchorResult.FAILURE,805        anchorId : 0806      });807    });808  }809  // Utility function810  requestRuntimeSession(sessionOptions) {811    return this.runtimeSupportsSession(sessionOptions).then((result) => {812      // The JavaScript bindings convert c_style_names to camelCase names.813      const options = new device.mojom.XRPresentationTransportOptions();814      options.transportMethod =815          device.mojom.XRPresentationTransportMethod.SUBMIT_AS_MAILBOX_HOLDER;816      options.waitForTransferNotification = true;817      options.waitForRenderNotification = true;818      let submit_frame_sink;819      if (result.supportsSession) {820        submit_frame_sink = {821          clientReceiver: this.presentation_provider_.getClientReceiver(),822          provider: this.presentation_provider_.bindProvider(sessionOptions),823          transportOptions: options824        };825        const dataProviderPtr = new device.mojom.XRFrameDataProviderPtr();826        const dataProviderRequest = mojo.makeRequest(dataProviderPtr);827        this.dataProviderBinding_ = new mojo.Binding(828            device.mojom.XRFrameDataProvider, this, dataProviderRequest);829        this.sessionOptions_ = sessionOptions;830        const clientReceiver = mojo.makeRequest(this.sessionClient_);831        const enabled_features = [];832        for (let i = 0; i < sessionOptions.requiredFeatures.length; i++) {833          if (this.supportedFeatures_.indexOf(sessionOptions.requiredFeatures[i]) !== -1) {834            enabled_features.push(sessionOptions.requiredFeatures[i]);835          } else {836            return Promise.resolve({session: null});837          }838        }839        for (let i =0; i < sessionOptions.optionalFeatures.length; i++) {840          if (this.supportedFeatures_.indexOf(sessionOptions.optionalFeatures[i]) !== -1) {841            enabled_features.push(sessionOptions.optionalFeatures[i]);842          }843        }844        return Promise.resolve({845          session: {846            submitFrameSink: submit_frame_sink,847            dataProvider: dataProviderPtr,848            clientReceiver: clientReceiver,849            displayInfo: this.displayInfo_,850            enabledFeatures: enabled_features,851          }852        });853      } else {854        return Promise.resolve({session: null});855      }856    });857  }858  runtimeSupportsSession(options) {859    return Promise.resolve({860      supportsSession: this.supportedModes_.includes(options.mode)861    });862  }863  // Private functions - utilities:864  _nativeOriginKnown(nativeOriginInformation){865    if (nativeOriginInformation.$tag == device.mojom.XRNativeOriginInformation.Tags.inputSourceId) {866      if (!this.input_sources_.has(nativeOriginInformation.inputSourceId)) {867        // Unknown input source.868        return false;869      }870      return true;871    } else if (nativeOriginInformation.$tag == device.mojom.XRNativeOriginInformation.Tags.referenceSpaceType) {872      // Bounded_floor & unbounded ref spaces are not yet supported for AR:873      if (nativeOriginInformation.referenceSpaceType == device.mojom.XRReferenceSpaceType.kUnbounded874       || nativeOriginInformation.referenceSpaceType == device.mojom.XRReferenceSpaceType.kBoundedFlor) {875        return false;876      }877      return true;878    } else {879      // Planes and anchors are not yet supported by the mock interface.880      return false;881    }882  }883  // Private functions - anchors implementation:884  // Modifies passed in frameData to add anchor information.885  _calculateAnchorInformation(frameData) {886    if (!this.supportedModes_.includes(device.mojom.XRSessionMode.kImmersiveAr)) {887      return;888    }889    frameData.anchorsData = new device.mojom.XRAnchorsData();890    frameData.anchorsData.allAnchorsIds = [];891    frameData.anchorsData.updatedAnchorsData = [];892    for(const [id, controller] of this.anchor_controllers_) {893      frameData.anchorsData.allAnchorsIds.push(id);894      // Send the entire anchor data over if there was a change since last GetFrameData().895      if(controller.dirty) {896        const anchorData = new device.mojom.XRAnchorData();897        anchorData.id = id;898        if(!controller.paused) {899          anchorData.mojoFromAnchor = XRMathHelper.decomposeRigidTransform(900            controller.getAnchorOrigin());901        }902        controller.markProcessed();903        frameData.anchorsData.updatedAnchorsData.push(anchorData);904      }905    }906  }907  // Private functions - hit test implementation:908  // Returns a Promise<bool> that signifies whether hit test source creation should succeed.909  // If we have a hit test source creation callback installed, invoke it and return its result.910  // If it's not installed, for back-compat just return a promise that resolves to true.911  _shouldHitTestSourceCreationSucceed(hitTestParameters, controller) {912    if(this.hit_test_source_creation_callback_) {913      return this.hit_test_source_creation_callback_(hitTestParameters, controller);914    } else {915      return Promise.resolve(true);916    }917  }918  // Modifies passed in frameData to add hit test results.919  _calculateHitTestResults(frameData) {920    if (!this.supportedModes_.includes(device.mojom.XRSessionMode.kImmersiveAr)) {921      return;922    }923    frameData.hitTestSubscriptionResults = new device.mojom.XRHitTestSubscriptionResultsData();924    frameData.hitTestSubscriptionResults.results = [];925    frameData.hitTestSubscriptionResults.transientInputResults = [];926    if (!this.world_) {927      return;928    }929    // Non-transient hit test:930    for (const [id, subscription] of this.hitTestSubscriptions_) {931      const mojo_from_native_origin = this._getMojoFromNativeOrigin(subscription.nativeOriginInformation);932      if (!mojo_from_native_origin) continue;933      const [mojo_ray_origin, mojo_ray_direction] = this._transformRayToMojoSpace(934        subscription.ray,935        mojo_from_native_origin936      );937      const results = this._hitTestWorld(mojo_ray_origin, mojo_ray_direction, subscription.entityTypes);938      const result = new device.mojom.XRHitTestSubscriptionResultData();939      result.subscriptionId = id;940      result.hitTestResults = results;941      frameData.hitTestSubscriptionResults.results.push(result);942    }943    // Transient hit test:944    const mojo_from_viewer = this._getMojoFromViewer();945    for (const [id, subscription] of this.transientHitTestSubscriptions_) {946      const result = new device.mojom.XRHitTestTransientInputSubscriptionResultData();947      result.subscriptionId = id;948      result.inputSourceIdToHitTestResults = new Map();949      // Find all input sources that match the profile name:950      const matching_input_sources = Array.from(this.input_sources_.values())951                                                        .filter(input_source => input_source.profiles_.includes(subscription.profileName));952      for (const input_source of matching_input_sources) {953        const mojo_from_native_origin = input_source._getMojoFromInputSource(mojo_from_viewer);954        const [mojo_ray_origin, mojo_ray_direction] = this._transformRayToMojoSpace(955          subscription.ray,956          mojo_from_native_origin957        );958        const results = this._hitTestWorld(mojo_ray_origin, mojo_ray_direction, subscription.entityTypes);959        result.inputSourceIdToHitTestResults.set(input_source.source_id_, results);960      }961      frameData.hitTestSubscriptionResults.transientInputResults.push(result);962    }963  }964  // Returns 2-element array [origin, direction] of a ray in mojo space.965  // |ray| is expressed relative to native origin.966  _transformRayToMojoSpace(ray, mojo_from_native_origin) {967    const ray_origin = {968      x: ray.origin.x,969      y: ray.origin.y,970      z: ray.origin.z,971      w: 1972    };973    const ray_direction = {974      x: ray.direction.x,975      y: ray.direction.y,976      z: ray.direction.z,977      w: 0978    };979    const mojo_ray_origin = XRMathHelper.transform_by_matrix(980      mojo_from_native_origin,981      ray_origin);982    const mojo_ray_direction = XRMathHelper.transform_by_matrix(983      mojo_from_native_origin,984      ray_direction);985    return [mojo_ray_origin, mojo_ray_direction];986  }987  // Hit tests the passed in ray (expressed as origin and direction) against the mocked world data.988  _hitTestWorld(origin, direction, entityTypes) {989    let result = [];990    for (const region of this.world_.hitTestRegions) {991      const partial_result = this._hitTestRegion(992        region,993        origin, direction,994        entityTypes);995      result = result.concat(partial_result);996    }997    return result.sort((lhs, rhs) => lhs.distance - rhs.distance);998  }999  // Hit tests the passed in ray (expressed as origin and direction) against world region.1000  // |entityTypes| is a set of FakeXRRegionTypes.1001  // |region| is FakeXRRegion.1002  // Returns array of XRHitResults, each entry will be decorated with the distance from the ray origin (along the ray).1003  _hitTestRegion(region, origin, direction, entityTypes) {1004    const regionNameToMojoEnum = {1005      "point":device.mojom.EntityTypeForHitTest.POINT,1006      "plane":device.mojom.EntityTypeForHitTest.PLANE,1007      "mesh":null1008    };1009    if (!entityTypes.includes(regionNameToMojoEnum[region.type])) {1010      return [];1011    }1012    const result = [];1013    for (const face of region.faces) {1014      const maybe_hit = this._hitTestFace(face, origin, direction);1015      if (maybe_hit) {1016        result.push(maybe_hit);1017      }1018    }1019    // The results should be sorted by distance and there should be no 2 entries with1020    // the same distance from ray origin - that would mean they are the same point.1021    // This situation is possible when a ray intersects the region through an edge shared1022    // by 2 faces.1023    return result.sort((lhs, rhs) => lhs.distance - rhs.distance)1024                 .filter((val, index, array) => index === 0 || val.distance !== array[index - 1].distance);1025  }1026  // Hit tests the passed in ray (expressed as origin and direction) against a single face.1027  // |face|, |origin|, and |direction| are specified in world (aka mojo) coordinates.1028  // |face| is an array of DOMPointInits.1029  // Returns null if the face does not intersect with the ray, otherwise the result is1030  // an XRHitResult with matrix describing the pose of the intersection point.1031  _hitTestFace(face, origin, direction) {1032    const add = XRMathHelper.add;1033    const sub = XRMathHelper.sub;1034    const mul = XRMathHelper.mul;1035    const normalize = XRMathHelper.normalize;1036    const dot = XRMathHelper.dot;1037    const cross = XRMathHelper.cross;1038    const neg = XRMathHelper.neg;1039    //1. Calculate plane normal in world coordinates.1040    const point_A = face.vertices[0];1041    const point_B = face.vertices[1];1042    const point_C = face.vertices[2];1043    const edge_AB = sub(point_B, point_A);1044    const edge_AC = sub(point_C, point_A);1045    const normal = normalize(cross(edge_AB, edge_AC));1046    const numerator = dot(sub(point_A, origin), normal);1047    const denominator = dot(direction, normal);1048    if (Math.abs(denominator) < XRMathHelper.EPSILON) {1049      // Planes are nearly parallel - there's either infinitely many intersection points or 0.1050      // Both cases signify a "no hit" for us.1051      return null;1052    } else {1053      // Single intersection point between the infinite plane and the line (*not* ray).1054      // Need to calculate the hit test matrix taking into account the face vertices.1055      const distance = numerator / denominator;1056      if (distance < 0) {1057        // Line - plane intersection exists, but not the half-line - plane does not.1058        return null;1059      } else {1060        const intersection_point = add(origin, mul(distance, direction));1061        // Since we are treating the face as a solid, flip the normal so that its1062        // half-space will contain the ray origin.1063        const y_axis = denominator > 0 ? neg(normal) : normal;1064        let z_axis = null;1065        const cos_direction_and_y_axis = dot(direction, y_axis);1066        if (Math.abs(cos_direction_and_y_axis) > (1 - XRMathHelper.EPSILON)) {1067          // 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.1068          // Note: this edge case is currently not covered by the spec.1069          const up = {x: 0.0, y: 1.0, z: 0.0, w: 0.0};1070          const right = {x: 1.0, y: 0.0, z: 0.0, w: 0.0};1071          z_axis = Math.abs(dot(up, y_axis)) > (1 - XRMathHelper.EPSILON)1072                        ? sub(up, mul(dot(right, y_axis), y_axis))  // `up is also co-linear with hit test normal, use `right`1073                        : sub(up, mul(dot(up, y_axis), y_axis));    // `up` is not co-linear with hit test normal, use it1074        } else {1075          // Project the ray direction onto the plane, negate it and use as a Z axis.1076          z_axis = neg(sub(direction, mul(cos_direction_and_y_axis, y_axis))); // Z should point towards the ray origin, not away.1077        }1078        const x_axis = normalize(cross(y_axis, z_axis));1079        // Filter out the points not in polygon.1080        if (!XRMathHelper.pointInFace(intersection_point, face)) {1081          return null;1082        }1083        const hitResult = new device.mojom.XRHitResult();1084        hitResult.distance = distance;  // Extend the object with additional information used by higher layers.1085                                        // It will not be serialized over mojom.1086        const matrix = new Array(16);1087        matrix[0] = x_axis.x;1088        matrix[1] = x_axis.y;1089        matrix[2] = x_axis.z;1090        matrix[3] = 0;1091        matrix[4] = y_axis.x;1092        matrix[5] = y_axis.y;1093        matrix[6] = y_axis.z;1094        matrix[7] = 0;1095        matrix[8] = z_axis.x;1096        matrix[9] = z_axis.y;1097        matrix[10] = z_axis.z;1098        matrix[11] = 0;1099        matrix[12] = intersection_point.x;1100        matrix[13] = intersection_point.y;1101        matrix[14] = intersection_point.z;1102        matrix[15] = 1;1103        hitResult.mojoFromResult = XRMathHelper.decomposeRigidTransform(matrix);1104        return hitResult;1105      }1106    }1107  }1108  _getMojoFromViewer() {1109    const transform = {1110      position: [1111        this.pose_.position.x,1112        this.pose_.position.y,1113        this.pose_.position.z],1114      orientation: [1115        this.pose_.orientation.x,1116        this.pose_.orientation.y,1117        this.pose_.orientation.z,1118        this.pose_.orientation.w],1119    };1120    return getMatrixFromTransform(transform);1121  }1122  _getMojoFromNativeOrigin(nativeOriginInformation) {1123    const mojo_from_viewer = this._getMojoFromViewer();1124    if (nativeOriginInformation.$tag == device.mojom.XRNativeOriginInformation.Tags.inputSourceId) {1125      if (!this.input_sources_.has(nativeOriginInformation.inputSourceId)) {1126        return null;1127      } else {1128        const inputSource = this.input_sources_.get(nativeOriginInformation.inputSourceId);1129        return inputSource._getMojoFromInputSource(mojo_from_viewer);1130      }1131    } else if (nativeOriginInformation.$tag == device.mojom.XRNativeOriginInformation.Tags.referenceSpaceType) {1132      switch (nativeOriginInformation.referenceSpaceType) {1133        case device.mojom.XRReferenceSpaceType.kLocal:1134          return XRMathHelper.identity();1135        case device.mojom.XRReferenceSpaceType.kLocalFloor:1136          if (this.stageParameters_ == null || this.stageParameters_.mojoFromFloor == null) {...Using AI Code Generation
1function getMojoFromNativeOrigin(nativeOrigin) {2    return new Promise((resolve, reject) => {3        wpt._getMojoFromNativeOrigin(nativeOrigin, mojo => {4            if (mojo) {5                resolve(mojo);6            } else {7                reject();8            }9        });10    });11}12function getMojoFromNativeOrigin(nativeOrigin) {13    return new Promise((resolve, reject) => {14        wpt._getMojoFromNativeOrigin(nativeOrigin, mojo => {15            if (mojo) {16                resolve(mojo);17            } else {18                reject();19            }20        });21    });22}23function getMojoFromNativeOrigin(nativeOrigin) {24    return new Promise((resolve, reject) => {25        wpt._getMojoFromNativeOrigin(nativeOrigin, mojo => {26            if (mojo) {27                resolve(mojo);28            } else {29                reject();30            }31        });32    });33}34function getMojoFromNativeOrigin(nativeOrigin) {35    return new Promise((resolve, reject) => {36        wpt._getMojoFromNativeOrigin(nativeOrigin, mojo => {37            if (mojo) {38                resolve(mojo);39            } else {40                reject();41            }42        });43    });44}45function getMojoFromNativeOrigin(nativeOrigin) {46    return new Promise((resolve, reject) => {47        wpt._getMojoFromNativeOrigin(nativeOrigin, mojo => {48            if (mojo) {49                resolve(mojo);50            } else {51                reject();52            }53        });54    });55}56function getMojoFromNativeOrigin(nativeOrigin) {57    return new Promise((resolve, reject) => {58        wpt._getMojoFromNativeOrigin(nativeOrigin, mojo => {59            if (mojo) {60                resolve(mojo);61            } else {62                reject();63            }64        });65    });66}Using AI Code Generation
1var wptb = require('wptb');2var wptb = require('wptb');3var wptb = require('wptb');4var wptb = require('wptb');5var wptb = require('wptb');6var wptb = require('wptb');7var wptb = require('wptb');8var wptb = require('wptb');9var wptb = require('wptb');10var wptb = require('wptb');11var mojo = wptb._getMojoFromNativeOrigin('httpUsing AI Code Generation
1var _getMojoFromNativeOrigin = _getMojoFromNativeOrigin || function (origin) {2    var mojo = null;3    var mojoService = Mojo.getService();4    mojoService.getMojoFromNativeOrigin(origin, function (result) {5        mojo = result;6    });7    return mojo;8};9var _getNativeOriginFromMojo = _getNativeOriginFromMojo || function (mojo) {10    var origin = null;11    var mojoService = Mojo.getService();12    mojoService.getNativeOriginFromMojo(mojo, function (result) {13        origin = result;14    });15    return origin;16};17var _getMojoFromNativeOrigin = _getMojoFromNativeOrigin || function (origin) {18    var mojo = null;19    var mojoService = Mojo.getService();20    mojoService.getMojoFromNativeOrigin(origin, function (result) {21        mojo = result;22    });23    return mojo;24};25var _getNativeOriginFromMojo = _getNativeOriginFromMojo || function (mojo) {26    var origin = null;27    var mojoService = Mojo.getService();28    mojoService.getNativeOriginFromMojo(mojo, function (result) {29        origin = result;30    });31    return origin;32};33var _getMojoFromNativeOrigin = _getMojoFromNativeOrigin || function (origin) {34    var mojo = null;35    var mojoService = Mojo.getService();36    mojoService.getMojoFromNativeOrigin(origin, function (result) {37        mojo = result;38    });39    return mojo;40};41var _getNativeOriginFromMojo = _getNativeOriginFromMojo || function (mojo) {42    var origin = null;43    var mojoService = Mojo.getService();44    mojoService.getNativeOriginFromMojo(mojo, function (result) {45        origin = result;46    });47    return origin;48};Using AI Code Generation
1var result = mojoHandle.callInterface("mojoInterfaceName", "mojoMethodName", "mojoMethodParams");2var result = mojoHandle.callInterface("mojoInterfaceName", "mojoMethodName", "mojoMethodParams");3var result = mojoHandle.callInterface("mojoInterfaceName", "mojoMethodName", "mojoMethodParams");4var result = mojoHandle.callInterface("mojoInterfaceName", "mojoMethodName", "mojoMethodParams");5var result = mojoHandle.callInterface("mojoInterfaceName", "mojoMethodName", "mojoMethodParams");6var result = mojoHandle.callInterface("mojoInterfaceName", "mojoMethodName", "mojoMethodParams");7var result = mojoHandle.callInterface("mojoInterfaceName", "mojoMethodName", "mojoMethodParams");8var result = mojoHandle.callInterface("mojoInterfaceName", "mojoMethodName", "mojoMethodParams");9var result = mojoHandle.callInterface("mojoInterfaceName", "mojoMethodName", "mojoMethodParams");10var result = mojoHandle.callInterface("mojoInterfaceName", "mojoMethodName", "mojoMethodParams");11var result = mojoHandle.callInterface("mojoInterfaceName", "mojoMethodName", "mojoMethodParams");12var result = mojoHandle.callInterface("mojoInterfaceName", "mojoMethodName", "mojoMethodParams");13var result = mojoHandle.callInterface("mojoInterfaceName", "mojoMethodName", "mojoMethodParams");14var result = mojoHandle.callInterface("mojoInterfaceLearn 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!!
