packages\engine\Source\Core\Cartesian3.js

js 复制代码
// @ts-check

import Check from "./Check.js";
import defined from "./defined.js";
import DeveloperError from "./DeveloperError.js";
import CesiumMath from "./Math.js";

/** @import {TypedArray} from "./globalTypes.js"; */
/** @import Cartesian4 from "./Cartesian4.js"; */
/** @import Ellipsoid from "./Ellipsoid.js"; */
/** @import Spherical from "./Spherical.js"; */

/**
 * A 3D Cartesian point.
 *
 * @see Cartesian2
 * @see Cartesian4
 * @see Packable
 */
class Cartesian3 {
  /**
   * @param {number} [x=0.0] The X component.
   * @param {number} [y=0.0] The Y component.
   * @param {number} [z=0.0] The Z component.
   */
  constructor(x, y, z) {
    /**
     * The X component.
     * @type {number}
     * @default 0.0
     */
    this.x = x ?? 0.0;

    /**
     * The Y component.
     * @type {number}
     * @default 0.0
     */
    this.y = y ?? 0.0;

    /**
     * The Z component.
     * @type {number}
     * @default 0.0
     */
    this.z = z ?? 0.0;
  }

  /**
   * Converts the provided Spherical into Cartesian3 coordinates.
   *
   * @param {Spherical} spherical The Spherical to be converted to Cartesian3.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
   */
  static fromSpherical(spherical, result) {

    Check.typeOf.object("spherical", spherical);


    if (!defined(result)) {
      result = new Cartesian3();
    }

    const clock = spherical.clock;
    const cone = spherical.cone;
    const magnitude = spherical.magnitude ?? 1.0;
    const radial = magnitude * Math.sin(cone);
    result.x = radial * Math.cos(clock);
    result.y = radial * Math.sin(clock);
    result.z = magnitude * Math.cos(cone);
    return result;
  }

  /**
   * Creates a Cartesian3 instance from x, y and z coordinates.
   *
   * @param {number} x The x coordinate.
   * @param {number} y The y coordinate.
   * @param {number} z The z coordinate.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
   */
  static fromElements(x, y, z, result) {
    if (!defined(result)) {
      return new Cartesian3(x, y, z);
    }

    result.x = x;
    result.y = y;
    result.z = z;
    return result;
  }

  /**
   * Duplicates a Cartesian3 instance.
   *
   * @param {Cartesian3} cartesian The Cartesian to duplicate.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided. (Returns undefined if cartesian is undefined)
   */
  static clone(cartesian, result) {
    if (!defined(cartesian)) {
      return undefined;
    }
    if (!defined(result)) {
      return new Cartesian3(cartesian.x, cartesian.y, cartesian.z);
    }

    result.x = cartesian.x;
    result.y = cartesian.y;
    result.z = cartesian.z;
    return result;
  }

  /**
   * Stores the provided instance into the provided array.
   *
   * @param {Cartesian3} value The value to pack.
   * @param {number[]|TypedArray} array The array to pack into.
   * @param {number} [startingIndex=0] The index into the array at which to start packing the elements.
   *
   * @returns {number[]|TypedArray} The array that was packed into
   */
  static pack(value, array, startingIndex) {

    Check.typeOf.object("value", value);
    Check.defined("array", array);


    startingIndex = startingIndex ?? 0;

    array[startingIndex++] = value.x;
    array[startingIndex++] = value.y;
    array[startingIndex] = value.z;

    return array;
  }

  /**
   * Retrieves an instance from a packed array.
   *
   * @param {number[]|TypedArray} array The packed array.
   * @param {number} [startingIndex=0] The starting index of the element to be unpacked.
   * @param {Cartesian3} [result] The object into which to store the result.
   * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
   */
  static unpack(array, startingIndex, result) {

    Check.defined("array", array);


    startingIndex = startingIndex ?? 0;

    if (!defined(result)) {
      result = new Cartesian3();
    }
    result.x = array[startingIndex++];
    result.y = array[startingIndex++];
    result.z = array[startingIndex];
    return result;
  }

  /**
   * Flattens an array of Cartesian3s into an array of components.
   *
   * @param {Cartesian3[]} array The array of cartesians to pack.
   * @param {number[]|TypedArray} [result] The array onto which to store the result. If this is a typed array, it must have array.length * 3 components, else a {@link DeveloperError} will be thrown. If it is a regular array, it will be resized to have (array.length * 3) elements.
   * @returns {number[]|TypedArray} The packed array.
   */
  static packArray(array, result) {

    Check.defined("array", array);


    const length = array.length;
    const resultLength = length * 3;
    if (!defined(result)) {
      result = new Array(resultLength);
    } else if (!Array.isArray(result) && result.length !== resultLength) {

      throw new DeveloperError(
        "If result is a typed array, it must have exactly array.length * 3 elements",
      );

    } else if (result.length !== resultLength) {
      /** @type {number[]} */ (result).length = resultLength;
    }

    for (let i = 0; i < length; ++i) {
      Cartesian3.pack(array[i], result, i * 3);
    }
    return result;
  }

  /**
   * Unpacks an array of cartesian components into an array of Cartesian3s.
   *
   * @param {number[]|TypedArray} array The array of components to unpack.
   * @param {Cartesian3[]} [result] The array onto which to store the result.
   * @returns {Cartesian3[]} The unpacked array.
   */
  static unpackArray(array, result) {

    Check.defined("array", array);
    Check.typeOf.number.greaterThanOrEquals("array.length", array.length, 3);
    if (array.length % 3 !== 0) {
      throw new DeveloperError("array length must be a multiple of 3.");
    }


    const length = array.length;
    if (!defined(result)) {
      result = new Array(length / 3);
    } else {
      result.length = length / 3;
    }

    for (let i = 0; i < length; i += 3) {
      const index = i / 3;
      result[index] = Cartesian3.unpack(array, i, result[index]);
    }
    return result;
  }

  /**
   * Computes the value of the maximum component for the supplied Cartesian.
   *
   * @param {Cartesian3} cartesian The cartesian to use.
   * @returns {number} The value of the maximum component.
   */
  static maximumComponent(cartesian) {

    Check.typeOf.object("cartesian", cartesian);


    return Math.max(cartesian.x, cartesian.y, cartesian.z);
  }

  /**
   * Computes the value of the minimum component for the supplied Cartesian.
   *
   * @param {Cartesian3} cartesian The cartesian to use.
   * @returns {number} The value of the minimum component.
   */
  static minimumComponent(cartesian) {

    Check.typeOf.object("cartesian", cartesian);


    return Math.min(cartesian.x, cartesian.y, cartesian.z);
  }

  /**
   * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
   *
   * @param {Cartesian3} first A cartesian to compare.
   * @param {Cartesian3} second A cartesian to compare.
   * @param {Cartesian3} result The object into which to store the result.
   * @returns {Cartesian3} A cartesian with the minimum components.
   */
  static minimumByComponent(first, second, result) {

    Check.typeOf.object("first", first);
    Check.typeOf.object("second", second);
    Check.typeOf.object("result", result);


    result.x = Math.min(first.x, second.x);
    result.y = Math.min(first.y, second.y);
    result.z = Math.min(first.z, second.z);

    return result;
  }

  /**
   * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
   *
   * @param {Cartesian3} first A cartesian to compare.
   * @param {Cartesian3} second A cartesian to compare.
   * @param {Cartesian3} result The object into which to store the result.
   * @returns {Cartesian3} A cartesian with the maximum components.
   */
  static maximumByComponent(first, second, result) {

    Check.typeOf.object("first", first);
    Check.typeOf.object("second", second);
    Check.typeOf.object("result", result);


    result.x = Math.max(first.x, second.x);
    result.y = Math.max(first.y, second.y);
    result.z = Math.max(first.z, second.z);
    return result;
  }

  /**
   * Constrain a value to lie between two values.
   *
   * @param {Cartesian3} value The value to clamp.
   * @param {Cartesian3} min The minimum bound.
   * @param {Cartesian3} max The maximum bound.
   * @param {Cartesian3} result The object into which to store the result.
   * @returns {Cartesian3} The clamped value such that min <= value <= max.
   */
  static clamp(value, min, max, result) {

    Check.typeOf.object("value", value);
    Check.typeOf.object("min", min);
    Check.typeOf.object("max", max);
    Check.typeOf.object("result", result);


    const x = CesiumMath.clamp(value.x, min.x, max.x);
    const y = CesiumMath.clamp(value.y, min.y, max.y);
    const z = CesiumMath.clamp(value.z, min.z, max.z);

    result.x = x;
    result.y = y;
    result.z = z;

    return result;
  }

  /**
   * Computes the provided Cartesian's squared magnitude.
   *
   * @param {Cartesian3} cartesian The Cartesian instance whose squared magnitude is to be computed.
   * @returns {number} The squared magnitude.
   */
  static magnitudeSquared(cartesian) {

    Check.typeOf.object("cartesian", cartesian);


    return (
      cartesian.x * cartesian.x +
      cartesian.y * cartesian.y +
      cartesian.z * cartesian.z
    );
  }

  /**
   * Computes the Cartesian's magnitude (length).
   *
   * @param {Cartesian3} cartesian The Cartesian instance whose magnitude is to be computed.
   * @returns {number} The magnitude.
   */
  static magnitude(cartesian) {
    return Math.sqrt(Cartesian3.magnitudeSquared(cartesian));
  }

  /**
   * Computes the distance between two points.
   *
   * @param {Cartesian3} left The first point to compute the distance from.
   * @param {Cartesian3} right The second point to compute the distance to.
   * @returns {number} The distance between two points.
   *
   * @example
   * // Returns 1.0
   * const d = Cesium.Cartesian3.distance(new Cesium.Cartesian3(1.0, 0.0, 0.0), new Cesium.Cartesian3(2.0, 0.0, 0.0));
   */
  static distance(left, right) {

    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);


    Cartesian3.subtract(left, right, distanceScratch);
    return Cartesian3.magnitude(distanceScratch);
  }

  /**
   * Computes the squared distance between two points.  Comparing squared distances
   * using this function is more efficient than comparing distances using {@link Cartesian3#distance}.
   *
   * @param {Cartesian3} left The first point to compute the distance from.
   * @param {Cartesian3} right The second point to compute the distance to.
   * @returns {number} The distance between two points.
   *
   * @example
   * // Returns 4.0, not 2.0
   * const d = Cesium.Cartesian3.distanceSquared(new Cesium.Cartesian3(1.0, 0.0, 0.0), new Cesium.Cartesian3(3.0, 0.0, 0.0));
   */
  static distanceSquared(left, right) {

    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);


    Cartesian3.subtract(left, right, distanceScratch);
    return Cartesian3.magnitudeSquared(distanceScratch);
  }

  /**
   * Computes the normalized form of the supplied Cartesian.
   *
   * @param {Cartesian3} cartesian The Cartesian to be normalized.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   */
  static normalize(cartesian, result) {

    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);


    const magnitude = Cartesian3.magnitude(cartesian);

    result.x = cartesian.x / magnitude;
    result.y = cartesian.y / magnitude;
    result.z = cartesian.z / magnitude;


    if (isNaN(result.x) || isNaN(result.y) || isNaN(result.z)) {
      throw new DeveloperError("normalized result is not a number");
    }


    return result;
  }

  /**
   * Computes the dot (scalar) product of two Cartesians.
   *
   * @param {Cartesian3} left The first Cartesian.
   * @param {Cartesian3} right The second Cartesian.
   * @returns {number} The dot product.
   */
  static dot(left, right) {

    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);


    return left.x * right.x + left.y * right.y + left.z * right.z;
  }

  /**
   * Computes the componentwise product of two Cartesians.
   *
   * @param {Cartesian3} left The first Cartesian.
   * @param {Cartesian3} right The second Cartesian.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   */
  static multiplyComponents(left, right, result) {

    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);


    result.x = left.x * right.x;
    result.y = left.y * right.y;
    result.z = left.z * right.z;
    return result;
  }

  /**
   * Computes the componentwise quotient of two Cartesians.
   *
   * @param {Cartesian3} left The first Cartesian.
   * @param {Cartesian3} right The second Cartesian.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   */
  static divideComponents(left, right, result) {

    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);


    result.x = left.x / right.x;
    result.y = left.y / right.y;
    result.z = left.z / right.z;
    return result;
  }

  /**
   * Computes the componentwise sum of two Cartesians.
   *
   * @param {Cartesian3} left The first Cartesian.
   * @param {Cartesian3} right The second Cartesian.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   */
  static add(left, right, result) {

    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);


    result.x = left.x + right.x;
    result.y = left.y + right.y;
    result.z = left.z + right.z;
    return result;
  }

  /**
   * Computes the componentwise difference of two Cartesians.
   *
   * @param {Cartesian3} left The first Cartesian.
   * @param {Cartesian3} right The second Cartesian.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   */
  static subtract(left, right, result) {

    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);


    result.x = left.x - right.x;
    result.y = left.y - right.y;
    result.z = left.z - right.z;
    return result;
  }

  /**
   * Multiplies the provided Cartesian componentwise by the provided scalar.
   *
   * @param {Cartesian3} cartesian The Cartesian to be scaled.
   * @param {number} scalar The scalar to multiply with.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   */
  static multiplyByScalar(cartesian, scalar, result) {

    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.number("scalar", scalar);
    Check.typeOf.object("result", result);


    result.x = cartesian.x * scalar;
    result.y = cartesian.y * scalar;
    result.z = cartesian.z * scalar;
    return result;
  }

  /**
   * Divides the provided Cartesian componentwise by the provided scalar.
   *
   * @param {Cartesian3} cartesian The Cartesian to be divided.
   * @param {number} scalar The scalar to divide by.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   */
  static divideByScalar(cartesian, scalar, result) {

    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.number("scalar", scalar);
    Check.typeOf.object("result", result);


    result.x = cartesian.x / scalar;
    result.y = cartesian.y / scalar;
    result.z = cartesian.z / scalar;
    return result;
  }

  /**
   * Negates the provided Cartesian.
   *
   * @param {Cartesian3} cartesian The Cartesian to be negated.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   */
  static negate(cartesian, result) {

    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);


    result.x = -cartesian.x;
    result.y = -cartesian.y;
    result.z = -cartesian.z;
    return result;
  }

  /**
   * Computes the absolute value of the provided Cartesian.
   *
   * @param {Cartesian3} cartesian The Cartesian whose absolute value is to be computed.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   */
  static abs(cartesian, result) {

    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);


    result.x = Math.abs(cartesian.x);
    result.y = Math.abs(cartesian.y);
    result.z = Math.abs(cartesian.z);
    return result;
  }

  /**
   * Computes the linear interpolation or extrapolation at t using the provided cartesians.
   *
   * @param {Cartesian3} start The value corresponding to t at 0.0.
   * @param {Cartesian3} end The value corresponding to t at 1.0.
   * @param {number} t The point along t at which to interpolate.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter.
   */
  static lerp(start, end, t, result) {

    Check.typeOf.object("start", start);
    Check.typeOf.object("end", end);
    Check.typeOf.number("t", t);
    Check.typeOf.object("result", result);


    Cartesian3.multiplyByScalar(end, t, lerpScratch);
    result = Cartesian3.multiplyByScalar(start, 1.0 - t, result);
    return Cartesian3.add(lerpScratch, result, result);
  }

  /**
   * Returns the angle, in radians, between the provided Cartesians.
   *
   * @param {Cartesian3} left The first Cartesian.
   * @param {Cartesian3} right The second Cartesian.
   * @returns {number} The angle between the Cartesians.
   */
  static angleBetween(left, right) {

    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);


    Cartesian3.normalize(left, angleBetweenScratch);
    Cartesian3.normalize(right, angleBetweenScratch2);
    const cosine = Cartesian3.dot(angleBetweenScratch, angleBetweenScratch2);
    const sine = Cartesian3.magnitude(
      Cartesian3.cross(
        angleBetweenScratch,
        angleBetweenScratch2,
        angleBetweenScratch,
      ),
    );
    return Math.atan2(sine, cosine);
  }

  /**
   * Returns the axis that is most orthogonal to the provided Cartesian.
   *
   * @param {Cartesian3} cartesian The Cartesian on which to find the most orthogonal axis.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The most orthogonal axis.
   */
  static mostOrthogonalAxis(cartesian, result) {

    Check.typeOf.object("cartesian", cartesian);
    Check.typeOf.object("result", result);


    const f = Cartesian3.normalize(cartesian, mostOrthogonalAxisScratch);
    Cartesian3.abs(f, f);

    if (f.x <= f.y) {
      if (f.x <= f.z) {
        result = Cartesian3.clone(Cartesian3.UNIT_X, result);
      } else {
        result = Cartesian3.clone(Cartesian3.UNIT_Z, result);
      }
    } else if (f.y <= f.z) {
      result = Cartesian3.clone(Cartesian3.UNIT_Y, result);
    } else {
      result = Cartesian3.clone(Cartesian3.UNIT_Z, result);
    }

    return result;
  }

  /**
   * Projects vector a onto vector b
   * @param {Cartesian3} a The vector that needs projecting
   * @param {Cartesian3} b The vector to project onto
   * @param {Cartesian3} result The result cartesian
   * @returns {Cartesian3} The modified result parameter
   */
  static projectVector(a, b, result) {

    Check.defined("a", a);
    Check.defined("b", b);
    Check.defined("result", result);


    const scalar = Cartesian3.dot(a, b) / Cartesian3.dot(b, b);
    return Cartesian3.multiplyByScalar(b, scalar, result);
  }

  /**
   * Compares the provided Cartesians componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Cartesian3} [left] The first Cartesian.
   * @param {Cartesian3} [right] The second Cartesian.
   * @returns {boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
   */
  static equals(left, right) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        left.x === right.x &&
        left.y === right.y &&
        left.z === right.z)
    );
  }

  /**
   * @param {Cartesian3} cartesian
   * @param {number[]} array
   * @param {number} offset
   * @private
   */
  static equalsArray(cartesian, array, offset) {
    return (
      cartesian.x === array[offset] &&
      cartesian.y === array[offset + 1] &&
      cartesian.z === array[offset + 2]
    );
  }

  /**
   * Compares the provided Cartesians componentwise and returns
   * <code>true</code> if they pass an absolute or relative tolerance test,
   * <code>false</code> otherwise.
   *
   * @param {Cartesian3} [left] The first Cartesian.
   * @param {Cartesian3} [right] The second Cartesian.
   * @param {number} [relativeEpsilon=0] The relative epsilon tolerance to use for equality testing.
   * @param {number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
   * @returns {boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
   */
  static equalsEpsilon(left, right, relativeEpsilon, absoluteEpsilon) {
    return (
      left === right ||
      (defined(left) &&
        defined(right) &&
        CesiumMath.equalsEpsilon(
          left.x,
          right.x,
          relativeEpsilon,
          absoluteEpsilon,
        ) &&
        CesiumMath.equalsEpsilon(
          left.y,
          right.y,
          relativeEpsilon,
          absoluteEpsilon,
        ) &&
        CesiumMath.equalsEpsilon(
          left.z,
          right.z,
          relativeEpsilon,
          absoluteEpsilon,
        ))
    );
  }

  /**
   * Computes the cross (outer) product of two Cartesians.
   *
   * @param {Cartesian3} left The first Cartesian.
   * @param {Cartesian3} right The second Cartesian.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The cross product.
   */
  static cross(left, right, result) {

    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);


    const leftX = left.x;
    const leftY = left.y;
    const leftZ = left.z;
    const rightX = right.x;
    const rightY = right.y;
    const rightZ = right.z;

    const x = leftY * rightZ - leftZ * rightY;
    const y = leftZ * rightX - leftX * rightZ;
    const z = leftX * rightY - leftY * rightX;

    result.x = x;
    result.y = y;
    result.z = z;
    return result;
  }

  /**
   * Computes the midpoint between the right and left Cartesian.
   * @param {Cartesian3} left The first Cartesian.
   * @param {Cartesian3} right The second Cartesian.
   * @param {Cartesian3} result The object onto which to store the result.
   * @returns {Cartesian3} The midpoint.
   */
  static midpoint(left, right, result) {

    Check.typeOf.object("left", left);
    Check.typeOf.object("right", right);
    Check.typeOf.object("result", result);


    result.x = (left.x + right.x) * 0.5;
    result.y = (left.y + right.y) * 0.5;
    result.z = (left.z + right.z) * 0.5;

    return result;
  }

  /**
   * Returns a Cartesian3 position from longitude and latitude values given in degrees.
   *
   * @param {number} longitude The longitude, in degrees
   * @param {number} latitude The latitude, in degrees
   * @param {number} [height=0.0] The height, in meters, above the ellipsoid.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid on which the position lies.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The position
   *
   * @example
   * const position = Cesium.Cartesian3.fromDegrees(-115.0, 37.0);
   */
  static fromDegrees(longitude, latitude, height, ellipsoid, result) {

    Check.typeOf.number("longitude", longitude);
    Check.typeOf.number("latitude", latitude);


    longitude = CesiumMath.toRadians(longitude);
    latitude = CesiumMath.toRadians(latitude);
    return Cartesian3.fromRadians(
      longitude,
      latitude,
      height,
      ellipsoid,
      result,
    );
  }

  /**
   * Returns a Cartesian3 position from longitude and latitude values given in radians.
   *
   * @param {number} longitude The longitude, in radians
   * @param {number} latitude The latitude, in radians
   * @param {number} [height=0.0] The height, in meters, above the ellipsoid.
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid on which the position lies.
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The position
   *
   * @example
   * const position = Cesium.Cartesian3.fromRadians(-2.007, 0.645);
   */
  static fromRadians(longitude, latitude, height, ellipsoid, result) {

    Check.typeOf.number("longitude", longitude);
    Check.typeOf.number("latitude", latitude);


    height = height ?? 0.0;

    const radiiSquared = !defined(ellipsoid)
      ? Cartesian3._ellipsoidRadiiSquared
      : // @ts-expect-error Requires type-checking on Ellipsoid.js.
      ellipsoid.radiiSquared;

    const cosLatitude = Math.cos(latitude);
    scratchN.x = cosLatitude * Math.cos(longitude);
    scratchN.y = cosLatitude * Math.sin(longitude);
    scratchN.z = Math.sin(latitude);
    scratchN = Cartesian3.normalize(scratchN, scratchN);

    Cartesian3.multiplyComponents(radiiSquared, scratchN, scratchK);
    const gamma = Math.sqrt(Cartesian3.dot(scratchN, scratchK));
    scratchK = Cartesian3.divideByScalar(scratchK, gamma, scratchK);
    scratchN = Cartesian3.multiplyByScalar(scratchN, height, scratchN);

    if (!defined(result)) {
      result = new Cartesian3();
    }
    return Cartesian3.add(scratchK, scratchN, result);
  }

  /**
   * Returns an array of Cartesian3 positions given an array of longitude and latitude values given in degrees.
   *
   * @param {number[]} coordinates A list of longitude and latitude values. Values alternate [longitude, latitude, longitude, latitude...].
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid on which the coordinates lie.
   * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
   * @returns {Cartesian3[]} The array of positions.
   *
   * @example
   * const positions = Cesium.Cartesian3.fromDegreesArray([-115.0, 37.0, -107.0, 33.0]);
   */
  static fromDegreesArray(coordinates, ellipsoid, result) {

    Check.defined("coordinates", coordinates);
    if (coordinates.length < 2 || coordinates.length % 2 !== 0) {
      throw new DeveloperError(
        "the number of coordinates must be a multiple of 2 and at least 2",
      );
    }


    const length = coordinates.length;
    if (!defined(result)) {
      result = new Array(length / 2);
    } else {
      result.length = length / 2;
    }

    for (let i = 0; i < length; i += 2) {
      const longitude = coordinates[i];
      const latitude = coordinates[i + 1];
      const index = i / 2;
      result[index] = Cartesian3.fromDegrees(
        longitude,
        latitude,
        0,
        ellipsoid,
        result[index],
      );
    }

    return result;
  }

  /**
   * Returns an array of Cartesian3 positions given an array of longitude and latitude values given in radians.
   *
   * @param {number[]} coordinates A list of longitude and latitude values. Values alternate [longitude, latitude, longitude, latitude...].
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid on which the coordinates lie.
   * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
   * @returns {Cartesian3[]} The array of positions.
   *
   * @example
   * const positions = Cesium.Cartesian3.fromRadiansArray([-2.007, 0.645, -1.867, .575]);
   */
  static fromRadiansArray(coordinates, ellipsoid, result) {

    Check.defined("coordinates", coordinates);
    if (coordinates.length < 2 || coordinates.length % 2 !== 0) {
      throw new DeveloperError(
        "the number of coordinates must be a multiple of 2 and at least 2",
      );
    }


    const length = coordinates.length;
    if (!defined(result)) {
      result = new Array(length / 2);
    } else {
      result.length = length / 2;
    }

    for (let i = 0; i < length; i += 2) {
      const longitude = coordinates[i];
      const latitude = coordinates[i + 1];
      const index = i / 2;
      result[index] = Cartesian3.fromRadians(
        longitude,
        latitude,
        0,
        ellipsoid,
        result[index],
      );
    }

    return result;
  }

  /**
   * Returns an array of Cartesian3 positions given an array of longitude, latitude and height values where longitude and latitude are given in degrees.
   *
   * @param {number[]} coordinates A list of longitude, latitude and height values. Values alternate [longitude, latitude, height, longitude, latitude, height...].
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid on which the position lies.
   * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
   * @returns {Cartesian3[]} The array of positions.
   *
   * @example
   * const positions = Cesium.Cartesian3.fromDegreesArrayHeights([-115.0, 37.0, 100000.0, -107.0, 33.0, 150000.0]);
   */
  static fromDegreesArrayHeights(coordinates, ellipsoid, result) {

    Check.defined("coordinates", coordinates);
    if (coordinates.length < 3 || coordinates.length % 3 !== 0) {
      throw new DeveloperError(
        "the number of coordinates must be a multiple of 3 and at least 3",
      );
    }


    const length = coordinates.length;
    if (!defined(result)) {
      result = new Array(length / 3);
    } else {
      result.length = length / 3;
    }

    for (let i = 0; i < length; i += 3) {
      const longitude = coordinates[i];
      const latitude = coordinates[i + 1];
      const height = coordinates[i + 2];
      const index = i / 3;
      result[index] = Cartesian3.fromDegrees(
        longitude,
        latitude,
        height,
        ellipsoid,
        result[index],
      );
    }

    return result;
  }

  /**
   * Returns an array of Cartesian3 positions given an array of longitude, latitude and height values where longitude and latitude are given in radians.
   *
   * @param {number[]} coordinates A list of longitude, latitude and height values. Values alternate [longitude, latitude, height, longitude, latitude, height...].
   * @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid on which the position lies.
   * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
   * @returns {Cartesian3[]} The array of positions.
   *
   * @example
   * const positions = Cesium.Cartesian3.fromRadiansArrayHeights([-2.007, 0.645, 100000.0, -1.867, .575, 150000.0]);
   */
  static fromRadiansArrayHeights(coordinates, ellipsoid, result) {

    Check.defined("coordinates", coordinates);
    if (coordinates.length < 3 || coordinates.length % 3 !== 0) {
      throw new DeveloperError(
        "the number of coordinates must be a multiple of 3 and at least 3",
      );
    }


    const length = coordinates.length;
    if (!defined(result)) {
      result = new Array(length / 3);
    } else {
      result.length = length / 3;
    }

    for (let i = 0; i < length; i += 3) {
      const longitude = coordinates[i];
      const latitude = coordinates[i + 1];
      const height = coordinates[i + 2];
      const index = i / 3;
      result[index] = Cartesian3.fromRadians(
        longitude,
        latitude,
        height,
        ellipsoid,
        result[index],
      );
    }

    return result;
  }

  /**
   * Duplicates this Cartesian3 instance.
   *
   * @param {Cartesian3} [result] The object onto which to store the result.
   * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
   */
  clone(result) {
    return Cartesian3.clone(this, result);
  }

  /**
   * Compares this Cartesian against the provided Cartesian componentwise and returns
   * <code>true</code> if they are equal, <code>false</code> otherwise.
   *
   * @param {Cartesian3} [right] The right hand side Cartesian.
   * @returns {boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
   */
  equals(right) {
    return Cartesian3.equals(this, right);
  }

  /**
   * Compares this Cartesian against the provided Cartesian componentwise and returns
   * <code>true</code> if they pass an absolute or relative tolerance test,
   * <code>false</code> otherwise.
   *
   * @param {Cartesian3} [right] The right hand side Cartesian.
   * @param {number} [relativeEpsilon=0] The relative epsilon tolerance to use for equality testing.
   * @param {number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
   * @returns {boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
   */
  equalsEpsilon(right, relativeEpsilon, absoluteEpsilon) {
    return Cartesian3.equalsEpsilon(
      this,
      right,
      relativeEpsilon,
      absoluteEpsilon,
    );
  }

  /**
   * Creates a string representing this Cartesian in the format '(x, y, z)'.
   *
   * @returns {string} A string representing this Cartesian in the format '(x, y, z)'.
   */
  toString() {
    return `(${this.x}, ${this.y}, ${this.z})`;
  }
}

/**
 * Creates a Cartesian3 instance from an existing Cartesian4.  This simply takes the
 * x, y, and z properties of the Cartesian4 and drops w.
 * @function
 *
 * @param {Cartesian4} cartesian The Cartesian4 instance to create a Cartesian3 instance from.
 * @param {Cartesian3} [result] The object onto which to store the result.
 * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
 */
Cartesian3.fromCartesian4 = Cartesian3.clone;

/**
 * The number of elements used to pack the object into an array.
 * @type {number}
 */
Cartesian3.packedLength = 3;

/**
 * Creates a Cartesian3 from three consecutive elements in an array.
 * @function
 *
 * @param {number[]} array The array whose three consecutive elements correspond to the x, y, and z components, respectively.
 * @param {number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
 * @param {Cartesian3} [result] The object onto which to store the result.
 * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
 *
 * @example
 * // Create a Cartesian3 with (1.0, 2.0, 3.0)
 * const v = [1.0, 2.0, 3.0];
 * const p = Cesium.Cartesian3.fromArray(v);
 *
 * // Create a Cartesian3 with (1.0, 2.0, 3.0) using an offset into an array
 * const v2 = [0.0, 0.0, 1.0, 2.0, 3.0];
 * const p2 = Cesium.Cartesian3.fromArray(v2, 2);
 */
Cartesian3.fromArray = Cartesian3.unpack;

const distanceScratch = new Cartesian3();

const lerpScratch = new Cartesian3();

const angleBetweenScratch = new Cartesian3();
const angleBetweenScratch2 = new Cartesian3();

const mostOrthogonalAxisScratch = new Cartesian3();

let scratchN = new Cartesian3();
let scratchK = new Cartesian3();

// To prevent a circular dependency, this value is overridden by Ellipsoid when Ellipsoid.default is set
Cartesian3._ellipsoidRadiiSquared = new Cartesian3(
  6378137.0 * 6378137.0,
  6378137.0 * 6378137.0,
  6356752.3142451793 * 6356752.3142451793,
);

/**
 * An immutable Cartesian3 instance initialized to (0.0, 0.0, 0.0).
 *
 * @type {Cartesian3}
 * @constant
 */
Cartesian3.ZERO = Object.freeze(new Cartesian3(0.0, 0.0, 0.0));

/**
 * An immutable Cartesian3 instance initialized to (1.0, 1.0, 1.0).
 *
 * @type {Cartesian3}
 * @constant
 */
Cartesian3.ONE = Object.freeze(new Cartesian3(1.0, 1.0, 1.0));

/**
 * An immutable Cartesian3 instance initialized to (1.0, 0.0, 0.0).
 *
 * @type {Cartesian3}
 * @constant
 */
Cartesian3.UNIT_X = Object.freeze(new Cartesian3(1.0, 0.0, 0.0));

/**
 * An immutable Cartesian3 instance initialized to (0.0, 1.0, 0.0).
 *
 * @type {Cartesian3}
 * @constant
 */
Cartesian3.UNIT_Y = Object.freeze(new Cartesian3(0.0, 1.0, 0.0));

/**
 * An immutable Cartesian3 instance initialized to (0.0, 0.0, 1.0).
 *
 * @type {Cartesian3}
 * @constant
 */
Cartesian3.UNIT_Z = Object.freeze(new Cartesian3(0.0, 0.0, 1.0));

export default Cartesian3;

这段代码实现了 Cartesian3 类,代表三维空间中的点或向量。它是 Cesium.js 等三维图形库中的核心数学类型,提供了丰富的向量运算和坐标转换功能。


1. 类概述

Cartesian3 是一个简单的数据容器,包含 xyz 三个分量。

它采用静态方法为主的设计,所有运算都通过静态方法实现,实例方法只是对静态方法的薄封装。这种模式便于复用 scratch 变量,减少内存分配。

js 复制代码
class Cartesian3 {
  constructor(x, y, z) {
    this.x = x ?? 0.0;
    this.y = y ?? 0.0;
    this.z = z ?? 0.0;
  }
  // 实例方法委托给静态方法
  clone(result) { return Cartesian3.clone(this, result); }
  equals(right) { return Cartesian3.equals(this, right); }
  // ...
}

2. 核心功能分类

2.1 创建与克隆

  • constructor(x, y, z) -- 构造实例,支持默认值。
  • fromElements(x, y, z, result) -- 从分量创建。
  • clone(cartesian, result) -- 深拷贝。
  • fromArray (别名 unpack) -- 从数组解包。
  • fromDegrees / fromRadians -- 经纬度转笛卡尔坐标(需 Ellipsoid)。
  • fromDegreesArray / fromRadiansArray -- 批量转换经纬度序列。
  • fromDegreesArrayHeights / fromRadiansArrayHeights -- 批量转换经纬度+高程序列。

2.2 向量运算(静态方法)

  • 加减add, subtract
  • 数乘multiplyByScalar, divideByScalar
  • 点积dot
  • 叉积cross
  • 模长magnitude, magnitudeSquared
  • 归一化normalize
  • 分量运算multiplyComponents, divideComponents
  • 线性插值lerp
  • 投影projectVector
  • 距离distance, distanceSquared
  • 角度angleBetween
  • 最正交轴mostOrthogonalAxis -- 返回与给定向量最正交的单位轴。

2.3 比较与容差

  • equals -- 严格相等。
  • equalsEpsilon -- 带相对/绝对误差的相等判断。
  • maximumComponent / minimumComponent -- 取最大/最小分量值。
  • minimumByComponent / maximumByComponent -- 逐分量取最小/最大。
  • clamp -- 逐分量限制在 [min, max] 区间。

2.4 序列化(Packable 接口)

  • packedLength = 3 -- 序列化所需元素个数。
  • pack(value, array, startingIndex) -- 将对象写入数组。
  • unpack(array, startingIndex, result) -- 从数组还原对象。
  • packArray(array, result) -- 批量打包。
  • unpackArray(array, result) -- 批量解包。

2.5 工具与常量

  • toString() -- 返回 (x, y, z) 字符串。
  • 常量:ZERO, ONE, UNIT_X, UNIT_Y, UNIT_Z(均为冻结对象)。

3. 设计亮点

3.1 性能优化:Scratch 变量

许多方法使用全局的临时变量 (如 distanceScratchlerpScratch)来避免频繁创建新对象。这种技巧在高性能计算场景(如每帧大量向量运算)中至关重要。

js 复制代码
const distanceScratch = new Cartesian3();

static distance(left, right) {
  Cartesian3.subtract(left, right, distanceScratch);
  return Cartesian3.magnitude(distanceScratch);
}

3.2 参数校验与调试支持

所有公开方法都通过 Check 工具类验证参数类型和存在性,在开发模式下抛出 DeveloperError,帮助快速定位 API 误用。

js 复制代码
Check.typeOf.object("left", left);
Check.typeOf.object("right", right);

这些校验在代码中通过 //>>includeStart('debug', pragmas.debug) 条件编译,在生产构建中可以被移除,避免运行时开销。

3.3 灵活的返回参数模式

大多数运算方法都接受一个可选的 result 参数,允许调用者传入预分配的对象,避免产生垃圾回收压力。如果未提供,则自动创建新实例。

js 复制代码
static add(left, right, result) {
  if (!defined(result)) result = new Cartesian3();
  // ...
  return result;
}

3.4 避免循环依赖

Cartesian3 在内部使用了 Ellipsoid 类型,但为了避免循环依赖,没有直接导入 Ellipsoid 类,而是通过属性 Cartesian3._ellipsoidRadiiSquared 在运行时由 Ellipsoid 设置(见文件末尾注释)。这是一种常见的解耦方式。

3.5 不可变常量

ZEROUNIT_X 等常量被 Object.freeze,确保它们不会被意外修改,提高安全性。


4. 依赖关系

  • Check -- 参数校验,依赖 definedDeveloperError
  • defined -- 存在性检查。
  • DeveloperError -- 自定义错误类型。
  • CesiumMath -- 数学工具(如 clampequalsEpsilon、角度转换等)。
  • Ellipsoid(间接) -- 经纬度转换时使用,但通过动态属性避免直接依赖。

5. 使用示例

js 复制代码
import Cartesian3 from './Cartesian3.js';

// 创建点
const p1 = new Cartesian3(1, 2, 3);
const p2 = Cartesian3.fromDegrees(116.397, 39.907, 100); // 天安门附近

// 向量运算
const sum = Cartesian3.add(p1, p2, new Cartesian3());
const distance = Cartesian3.distance(p1, p2);
const unit = Cartesian3.normalize(p1, new Cartesian3());

// 序列化
const array = [];
Cartesian3.pack(p1, array); // array = [1,2,3]
const unpacked = Cartesian3.unpack(array);

// 批量转换经纬度数组
const lonsLats = [116.397, 39.907, 121.480, 31.222]; // 北京、上海
const positions = Cartesian3.fromDegreesArray(lonsLats);

6. 总结

Cartesian3 是一个高度优化、功能全面的三维向量类,体现了 Cesium 对性能和正确性的重视。它通过静态方法、scratch 变量、参数校验、灵活的返回值模式,为三维应用提供了可靠的基础数学工具。与之前分析的 definedCheckEvent 等工具类协同工作,共同构成了 Cesium 核心库的基石。

相关推荐
颜酱2 小时前
吃透回溯算法:从框架到实战
javascript·后端·算法
爱学习的程序媛2 小时前
【Web前端】WebAssembly实战项目
前端·web·wasm
木斯佳2 小时前
前端八股文面经大全:阿里云AI应用开发二面(2026-03-21)·面经深度解析
前端·css·人工智能·阿里云·ai·面试·vue
IT_陈寒2 小时前
JavaScript原型链解密:3个关键概念帮你彻底搞懂继承机制
前端·人工智能·后端
专注API从业者2 小时前
淘宝商品详情 API 的 Webhook 回调机制设计与实现:实现数据主动推送
大数据·前端·数据结构·数据库
哈哈哈hhhhhh2 小时前
vue----v-model
前端·javascript·vue.js
QD_ANJING2 小时前
2026年大厂前端高频面试原题-React框架200题
开发语言·前端·javascript·react.js·面试·职场和发展·前端框架
happymaker06262 小时前
web前端学习日记——DAY03(盒子模型,flex布局,表格)
前端·学习
爱丽_2 小时前
Axios 二次封装:拦截器、统一错误处理与文件下载
前端