ImageryLayerCollection.js 18.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
import defaultValue from "../Core/defaultValue.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import DeveloperError from "../Core/DeveloperError.js";
import Event from "../Core/Event.js";
import CesiumMath from "../Core/Math.js";
import Rectangle from "../Core/Rectangle.js";
import when from "../ThirdParty/when.js";
import ImageryLayer from "./ImageryLayer.js";

/**
 * An ordered collection of imagery layers.
 *
 * @alias ImageryLayerCollection
 * @constructor
 *
 * @demo {@link https://sandcastle.cesium.com/index.html?src=Imagery%20Adjustment.html|Cesium Sandcastle Imagery Adjustment Demo}
 * @demo {@link https://sandcastle.cesium.com/index.html?src=Imagery%20Layers%20Manipulation.html|Cesium Sandcastle Imagery Manipulation Demo}
 */
function ImageryLayerCollection() {
  this._layers = [];

  /**
   * An event that is raised when a layer is added to the collection.  Event handlers are passed the layer that
   * was added and the index at which it was added.
   * @type {Event}
   * @default Event()
   */
  this.layerAdded = new Event();

  /**
   * An event that is raised when a layer is removed from the collection.  Event handlers are passed the layer that
   * was removed and the index from which it was removed.
   * @type {Event}
   * @default Event()
   */
  this.layerRemoved = new Event();

  /**
   * An event that is raised when a layer changes position in the collection.  Event handlers are passed the layer that
   * was moved, its new index after the move, and its old index prior to the move.
   * @type {Event}
   * @default Event()
   */
  this.layerMoved = new Event();

  /**
   * An event that is raised when a layer is shown or hidden by setting the
   * {@link ImageryLayer#show} property.  Event handlers are passed a reference to this layer,
   * the index of the layer in the collection, and a flag that is true if the layer is now
   * shown or false if it is now hidden.
   *
   * @type {Event}
   * @default Event()
   */
  this.layerShownOrHidden = new Event();
}

Object.defineProperties(ImageryLayerCollection.prototype, {
  /**
   * Gets the number of layers in this collection.
   * @memberof ImageryLayerCollection.prototype
   * @type {Number}
   */
  length: {
    get: function () {
      return this._layers.length;
    },
  },
});

/**
 * Adds a layer to the collection.
 *
 * @param {ImageryLayer} layer the layer to add.
 * @param {Number} [index] the index to add the layer at.  If omitted, the layer will
 *                         be added on top of all existing layers.
 *
 * @exception {DeveloperError} index, if supplied, must be greater than or equal to zero and less than or equal to the number of the layers.
 */
ImageryLayerCollection.prototype.add = function (layer, index) {
  var hasIndex = defined(index);

  //>>includeStart('debug', pragmas.debug);
  if (!defined(layer)) {
    throw new DeveloperError("layer is required.");
  }
  if (hasIndex) {
    if (index < 0) {
      throw new DeveloperError("index must be greater than or equal to zero.");
    } else if (index > this._layers.length) {
      throw new DeveloperError(
        "index must be less than or equal to the number of layers."
      );
    }
  }
  //>>includeEnd('debug');

  if (!hasIndex) {
    index = this._layers.length;
    this._layers.push(layer);
  } else {
    this._layers.splice(index, 0, layer);
  }

  this._update();
  this.layerAdded.raiseEvent(layer, index);
};

/**
 * Creates a new layer using the given ImageryProvider and adds it to the collection.
 *
 * @param {ImageryProvider} imageryProvider the imagery provider to create a new layer for.
 * @param {Number} [index] the index to add the layer at.  If omitted, the layer will
 *                         added on top of all existing layers.
 * @returns {ImageryLayer} The newly created layer.
 */
ImageryLayerCollection.prototype.addImageryProvider = function (
  imageryProvider,
  index
) {
  //>>includeStart('debug', pragmas.debug);
  if (!defined(imageryProvider)) {
    throw new DeveloperError("imageryProvider is required.");
  }
  //>>includeEnd('debug');

  var layer = new ImageryLayer(imageryProvider);
  this.add(layer, index);
  return layer;
};

/**
 * Removes a layer from this collection, if present.
 *
 * @param {ImageryLayer} layer The layer to remove.
 * @param {Boolean} [destroy=true] whether to destroy the layers in addition to removing them.
 * @returns {Boolean} true if the layer was in the collection and was removed,
 *                    false if the layer was not in the collection.
 */
ImageryLayerCollection.prototype.remove = function (layer, destroy) {
  destroy = defaultValue(destroy, true);

  var index = this._layers.indexOf(layer);
  if (index !== -1) {
    this._layers.splice(index, 1);

    this._update();

    this.layerRemoved.raiseEvent(layer, index);

    if (destroy) {
      layer.destroy();
    }

    return true;
  }

  return false;
};

/**
 * Removes all layers from this collection.
 *
 * @param {Boolean} [destroy=true] whether to destroy the layers in addition to removing them.
 */
ImageryLayerCollection.prototype.removeAll = function (destroy) {
  destroy = defaultValue(destroy, true);

  var layers = this._layers;
  for (var i = 0, len = layers.length; i < len; i++) {
    var layer = layers[i];
    this.layerRemoved.raiseEvent(layer, i);

    if (destroy) {
      layer.destroy();
    }
  }

  this._layers = [];
};

/**
 * Checks to see if the collection contains a given layer.
 *
 * @param {ImageryLayer} layer the layer to check for.
 *
 * @returns {Boolean} true if the collection contains the layer, false otherwise.
 */
ImageryLayerCollection.prototype.contains = function (layer) {
  return this.indexOf(layer) !== -1;
};

/**
 * Determines the index of a given layer in the collection.
 *
 * @param {ImageryLayer} layer The layer to find the index of.
 *
 * @returns {Number} The index of the layer in the collection, or -1 if the layer does not exist in the collection.
 */
ImageryLayerCollection.prototype.indexOf = function (layer) {
  return this._layers.indexOf(layer);
};

/**
 * Gets a layer by index from the collection.
 *
 * @param {Number} index the index to retrieve.
 *
 * @returns {ImageryLayer} The imagery layer at the given index.
 */
ImageryLayerCollection.prototype.get = function (index) {
  //>>includeStart('debug', pragmas.debug);
  if (!defined(index)) {
    throw new DeveloperError("index is required.", "index");
  }
  //>>includeEnd('debug');

  return this._layers[index];
};

function getLayerIndex(layers, layer) {
  //>>includeStart('debug', pragmas.debug);
  if (!defined(layer)) {
    throw new DeveloperError("layer is required.");
  }
  //>>includeEnd('debug');

  var index = layers.indexOf(layer);

  //>>includeStart('debug', pragmas.debug);
  if (index === -1) {
    throw new DeveloperError("layer is not in this collection.");
  }
  //>>includeEnd('debug');

  return index;
}

function swapLayers(collection, i, j) {
  var arr = collection._layers;
  i = CesiumMath.clamp(i, 0, arr.length - 1);
  j = CesiumMath.clamp(j, 0, arr.length - 1);

  if (i === j) {
    return;
  }

  var temp = arr[i];
  arr[i] = arr[j];
  arr[j] = temp;

  collection._update();

  collection.layerMoved.raiseEvent(temp, j, i);
}

/**
 * Raises a layer up one position in the collection.
 *
 * @param {ImageryLayer} layer the layer to move.
 *
 * @exception {DeveloperError} layer is not in this collection.
 * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
 */
ImageryLayerCollection.prototype.raise = function (layer) {
  var index = getLayerIndex(this._layers, layer);
  swapLayers(this, index, index + 1);
};

/**
 * Lowers a layer down one position in the collection.
 *
 * @param {ImageryLayer} layer the layer to move.
 *
 * @exception {DeveloperError} layer is not in this collection.
 * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
 */
ImageryLayerCollection.prototype.lower = function (layer) {
  var index = getLayerIndex(this._layers, layer);
  swapLayers(this, index, index - 1);
};

/**
 * Raises a layer to the top of the collection.
 *
 * @param {ImageryLayer} layer the layer to move.
 *
 * @exception {DeveloperError} layer is not in this collection.
 * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
 */
ImageryLayerCollection.prototype.raiseToTop = function (layer) {
  var index = getLayerIndex(this._layers, layer);
  if (index === this._layers.length - 1) {
    return;
  }
  this._layers.splice(index, 1);
  this._layers.push(layer);

  this._update();

  this.layerMoved.raiseEvent(layer, this._layers.length - 1, index);
};

/**
 * Lowers a layer to the bottom of the collection.
 *
 * @param {ImageryLayer} layer the layer to move.
 *
 * @exception {DeveloperError} layer is not in this collection.
 * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
 */
ImageryLayerCollection.prototype.lowerToBottom = function (layer) {
  var index = getLayerIndex(this._layers, layer);
  if (index === 0) {
    return;
  }
  this._layers.splice(index, 1);
  this._layers.splice(0, 0, layer);

  this._update();

  this.layerMoved.raiseEvent(layer, 0, index);
};

var applicableRectangleScratch = new Rectangle();

function pickImageryHelper(scene, pickedLocation, pickFeatures, callback) {
  // Find the terrain tile containing the picked location.
  var tilesToRender = scene.globe._surface._tilesToRender;
  var pickedTile;

  for (
    var textureIndex = 0;
    !defined(pickedTile) && textureIndex < tilesToRender.length;
    ++textureIndex
  ) {
    var tile = tilesToRender[textureIndex];
    if (Rectangle.contains(tile.rectangle, pickedLocation)) {
      pickedTile = tile;
    }
  }

  if (!defined(pickedTile)) {
    return;
  }

  // Pick against all attached imagery tiles containing the pickedLocation.
  var imageryTiles = pickedTile.data.imagery;

  for (var i = imageryTiles.length - 1; i >= 0; --i) {
    var terrainImagery = imageryTiles[i];
    var imagery = terrainImagery.readyImagery;
    if (!defined(imagery)) {
      continue;
    }
    var provider = imagery.imageryLayer.imageryProvider;
    if (pickFeatures && !defined(provider.pickFeatures)) {
      continue;
    }

    if (!Rectangle.contains(imagery.rectangle, pickedLocation)) {
      continue;
    }

    // If this imagery came from a parent, it may not be applicable to its entire rectangle.
    // Check the textureCoordinateRectangle.
    var applicableRectangle = applicableRectangleScratch;

    var epsilon = 1 / 1024; // 1/4 of a pixel in a typical 256x256 tile.
    applicableRectangle.west = CesiumMath.lerp(
      pickedTile.rectangle.west,
      pickedTile.rectangle.east,
      terrainImagery.textureCoordinateRectangle.x - epsilon
    );
    applicableRectangle.east = CesiumMath.lerp(
      pickedTile.rectangle.west,
      pickedTile.rectangle.east,
      terrainImagery.textureCoordinateRectangle.z + epsilon
    );
    applicableRectangle.south = CesiumMath.lerp(
      pickedTile.rectangle.south,
      pickedTile.rectangle.north,
      terrainImagery.textureCoordinateRectangle.y - epsilon
    );
    applicableRectangle.north = CesiumMath.lerp(
      pickedTile.rectangle.south,
      pickedTile.rectangle.north,
      terrainImagery.textureCoordinateRectangle.w + epsilon
    );
    if (!Rectangle.contains(applicableRectangle, pickedLocation)) {
      continue;
    }

    callback(imagery);
  }
}

/**
 * Determines the imagery layers that are intersected by a pick ray. To compute a pick ray from a
 * location on the screen, use {@link Camera.getPickRay}.
 *
 * @param {Ray} ray The ray to test for intersection.
 * @param {Scene} scene The scene.
 * @return {ImageryLayer[]|undefined} An array that includes all of
 *                                 the layers that are intersected by a given pick ray. Undefined if
 *                                 no layers are selected.
 *
 */
ImageryLayerCollection.prototype.pickImageryLayers = function (ray, scene) {
  // Find the picked location on the globe.
  var pickedPosition = scene.globe.pick(ray, scene);
  if (!defined(pickedPosition)) {
    return;
  }

  var pickedLocation = scene.globe.ellipsoid.cartesianToCartographic(
    pickedPosition
  );

  var imageryLayers = [];

  pickImageryHelper(scene, pickedLocation, false, function (imagery) {
    imageryLayers.push(imagery.imageryLayer);
  });

  if (imageryLayers.length === 0) {
    return undefined;
  }

  return imageryLayers;
};

/**
 * Asynchronously determines the imagery layer features that are intersected by a pick ray.  The intersected imagery
 * layer features are found by invoking {@link ImageryProvider#pickFeatures} for each imagery layer tile intersected
 * by the pick ray.  To compute a pick ray from a location on the screen, use {@link Camera.getPickRay}.
 *
 * @param {Ray} ray The ray to test for intersection.
 * @param {Scene} scene The scene.
 * @return {Promise.<ImageryLayerFeatureInfo[]>|undefined} A promise that resolves to an array of features intersected by the pick ray.
 *                                             If it can be quickly determined that no features are intersected (for example,
 *                                             because no active imagery providers support {@link ImageryProvider#pickFeatures}
 *                                             or because the pick ray does not intersect the surface), this function will
 *                                             return undefined.
 *
 * @example
 * var pickRay = viewer.camera.getPickRay(windowPosition);
 * var featuresPromise = viewer.imageryLayers.pickImageryLayerFeatures(pickRay, viewer.scene);
 * if (!Cesium.defined(featuresPromise)) {
 *     console.log('No features picked.');
 * } else {
 *     Cesium.when(featuresPromise, function(features) {
 *         // This function is called asynchronously when the list if picked features is available.
 *         console.log('Number of features: ' + features.length);
 *         if (features.length > 0) {
 *             console.log('First feature name: ' + features[0].name);
 *         }
 *     });
 * }
 */
ImageryLayerCollection.prototype.pickImageryLayerFeatures = function (
  ray,
  scene
) {
  // Find the picked location on the globe.
  var pickedPosition = scene.globe.pick(ray, scene);
  if (!defined(pickedPosition)) {
    return;
  }

  var pickedLocation = scene.globe.ellipsoid.cartesianToCartographic(
    pickedPosition
  );

  var promises = [];
  var imageryLayers = [];

  pickImageryHelper(scene, pickedLocation, true, function (imagery) {
    var provider = imagery.imageryLayer.imageryProvider;
    var promise = provider.pickFeatures(
      imagery.x,
      imagery.y,
      imagery.level,
      pickedLocation.longitude,
      pickedLocation.latitude
    );
    if (defined(promise)) {
      promises.push(promise);
      imageryLayers.push(imagery.imageryLayer);
    }
  });

  if (promises.length === 0) {
    return undefined;
  }
  return when.all(promises, function (results) {
    var features = [];
    for (var resultIndex = 0; resultIndex < results.length; ++resultIndex) {
      var result = results[resultIndex];
      var image = imageryLayers[resultIndex];
      if (defined(result) && result.length > 0) {
        for (
          var featureIndex = 0;
          featureIndex < result.length;
          ++featureIndex
        ) {
          var feature = result[featureIndex];
          feature.imageryLayer = image;
          // For features without a position, use the picked location.
          if (!defined(feature.position)) {
            feature.position = pickedLocation;
          }
          features.push(feature);
        }
      }
    }
    return features;
  });
};

/**
 * Updates frame state to execute any queued texture re-projections.
 *
 * @private
 *
 * @param {FrameState} frameState The frameState.
 */
ImageryLayerCollection.prototype.queueReprojectionCommands = function (
  frameState
) {
  var layers = this._layers;
  for (var i = 0, len = layers.length; i < len; ++i) {
    layers[i].queueReprojectionCommands(frameState);
  }
};

/**
 * Cancels re-projection commands queued for the next frame.
 *
 * @private
 */
ImageryLayerCollection.prototype.cancelReprojections = function () {
  var layers = this._layers;
  for (var i = 0, len = layers.length; i < len; ++i) {
    layers[i].cancelReprojections();
  }
};

/**
 * Returns true if this object was destroyed; otherwise, false.
 * <br /><br />
 * If this object was destroyed, it should not be used; calling any function other than
 * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
 *
 * @returns {Boolean} true if this object was destroyed; otherwise, false.
 *
 * @see ImageryLayerCollection#destroy
 */
ImageryLayerCollection.prototype.isDestroyed = function () {
  return false;
};

/**
 * Destroys the WebGL resources held by all layers in this collection.  Explicitly destroying this
 * object allows for deterministic release of WebGL resources, instead of relying on the garbage
 * collector.
 * <br /><br />
 * Once this object is destroyed, it should not be used; calling any function other than
 * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
 * assign the return value (<code>undefined</code>) to the object as done in the example.
 *
 * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
 *
 *
 * @example
 * layerCollection = layerCollection && layerCollection.destroy();
 *
 * @see ImageryLayerCollection#isDestroyed
 */
ImageryLayerCollection.prototype.destroy = function () {
  this.removeAll(true);
  return destroyObject(this);
};

ImageryLayerCollection.prototype._update = function () {
  var isBaseLayer = true;
  var layers = this._layers;
  var layersShownOrHidden;
  var layer;
  var i, len;
  for (i = 0, len = layers.length; i < len; ++i) {
    layer = layers[i];

    layer._layerIndex = i;

    if (layer.show) {
      layer._isBaseLayer = isBaseLayer;
      isBaseLayer = false;
    } else {
      layer._isBaseLayer = false;
    }

    if (layer.show !== layer._show) {
      if (defined(layer._show)) {
        if (!defined(layersShownOrHidden)) {
          layersShownOrHidden = [];
        }
        layersShownOrHidden.push(layer);
      }
      layer._show = layer.show;
    }
  }

  if (defined(layersShownOrHidden)) {
    for (i = 0, len = layersShownOrHidden.length; i < len; ++i) {
      layer = layersShownOrHidden[i];
      this.layerShownOrHidden.raiseEvent(layer, layer._layerIndex, layer.show);
    }
  }
};
export default ImageryLayerCollection;