All files / engine/Source/Scene ImageBasedLighting.js

82.47% Statements 80/97
74.68% Branches 59/79
83.33% Functions 15/18
82.47% Lines 80/97

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                    485x 485x         485x       485x         483x         483x         483x             483x   483x     483x         1x         482x     482x 482x 482x 482x 482x   482x 482x 482x     482x 482x     482x     482x 482x     1x                           10x       33x 33x         32x         32x         32x           32x       32x                                                     4183x       2x 1x         1x   1x                           794x                                             1747x                                   14068x                           6x                           2x                                                       3x                   299x 299x                                               1x 14068x       6945x     7123x 7123x   7123x 7123x   7123x 7123x 7123x 5x     5x         5x           7123x                         7123x         7123x     7123x 299x 299x     7123x               7123x       7123x       7123x       7123x     7123x             7123x     7123x                               1x 313x                                     1x 313x     313x   313x        
import Cartesian2 from "../Core/Cartesian2.js";
import Check from "../Core/Check.js";
import defined from "../Core/defined.js";
import Frozen from "../Core/Frozen.js";
import destroyObject from "../Core/destroyObject.js";
import DeveloperError from "../Core/DeveloperError.js";
import SpecularEnvironmentCubeMap from "./SpecularEnvironmentCubeMap.js";
 
/**
 * Properties for managing image-based lighting on tilesets and models.
 * Also manages the necessary resources and textures.
 * <p>
 * If specular environment maps are used, {@link ImageBasedLighting#destroy} must be called
 * when the image-based lighting is no longer needed to clean up GPU resources properly.
 * If a model or tileset creates an instance of ImageBasedLighting, it will handle this.
 * Otherwise, the application is responsible for calling destroy().
 *</p>
 *
 * @alias ImageBasedLighting
 * @constructor
 *
 * @param {Cartesian2} [options.imageBasedLightingFactor=Cartesian2(1.0, 1.0)] Scales diffuse and specular image-based lighting from the earth, sky, atmosphere and star skybox.
 * @param {Cartesian3[]} [options.sphericalHarmonicCoefficients] The third order spherical harmonic coefficients used for the diffuse color of image-based lighting.
 * @param {string} [options.specularEnvironmentMaps] A URL to a KTX2 file that contains a cube map of the specular lighting and the convoluted specular mipmaps.
 */
function ImageBasedLighting(options) {
  options = options ?? Frozen.EMPTY_OBJECT;
  const imageBasedLightingFactor = defined(options.imageBasedLightingFactor)
    ? Cartesian2.clone(options.imageBasedLightingFactor)
    : new Cartesian2(1.0, 1.0);
 
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.object(
    "options.imageBasedLightingFactor",
    imageBasedLightingFactor,
  );
  Check.typeOf.number.greaterThanOrEquals(
    "options.imageBasedLightingFactor.x",
    imageBasedLightingFactor.x,
    0.0,
  );
  Check.typeOf.number.lessThanOrEquals(
    "options.imageBasedLightingFactor.x",
    imageBasedLightingFactor.x,
    1.0,
  );
  Check.typeOf.number.greaterThanOrEquals(
    "options.imageBasedLightingFactor.y",
    imageBasedLightingFactor.y,
    0.0,
  );
  Check.typeOf.number.lessThanOrEquals(
    "options.imageBasedLightingFactor.y",
    imageBasedLightingFactor.y,
    1.0,
  );
  //>>includeEnd('debug');
 
  this._imageBasedLightingFactor = imageBasedLightingFactor;
 
  const sphericalHarmonicCoefficients = options.sphericalHarmonicCoefficients;
 
  //>>includeStart('debug', pragmas.debug);
  if (
    defined(sphericalHarmonicCoefficients) &&
    (!Array.isArray(sphericalHarmonicCoefficients) ||
      sphericalHarmonicCoefficients.length !== 9)
  ) {
    throw new DeveloperError(
      "options.sphericalHarmonicCoefficients must be an array of 9 Cartesian3 values.",
    );
  }
  //>>includeEnd('debug');
  this._sphericalHarmonicCoefficients = sphericalHarmonicCoefficients;
 
  // The specular environment map texture is created in update();
  this._specularEnvironmentMaps = options.specularEnvironmentMaps;
  this._specularEnvironmentCubeMap = undefined;
  this._specularEnvironmentCubeMapDirty = true;
  this._specularEnvironmentMapLoaded = false;
  this._previousSpecularEnvironmentMapLoaded = false;
 
  this._useDefaultSpecularMaps = false;
  this._useDefaultSphericalHarmonics = false;
  this._shouldRegenerateShaders = false;
 
  // Store the previous frame number to prevent redundant update calls
  this._previousFrameNumber = undefined;
  this._previousFrameContext = undefined;
 
  // Keeps track of the last values for use during update logic
  this._previousImageBasedLightingFactor = Cartesian2.clone(
    imageBasedLightingFactor,
  );
  this._previousSphericalHarmonicCoefficients = sphericalHarmonicCoefficients;
  this._removeErrorListener = undefined;
}
 
Object.defineProperties(ImageBasedLighting.prototype, {
  /**
   * Cesium adds lighting from the earth, sky, atmosphere, and star skybox.
   * This cartesian is used to scale the final diffuse and specular lighting
   * contribution from those sources to the final color. A value of 0.0 will
   * disable those light sources.
   *
   * @memberof ImageBasedLighting.prototype
   *
   * @type {Cartesian2}
   * @default Cartesian2(1.0, 1.0)
   */
  imageBasedLightingFactor: {
    get: function () {
      return this._imageBasedLightingFactor;
    },
    set: function (value) {
      //>>includeStart('debug', pragmas.debug);
      Check.typeOf.object("imageBasedLightingFactor", value);
      Check.typeOf.number.greaterThanOrEquals(
        "imageBasedLightingFactor.x",
        value.x,
        0.0,
      );
      Check.typeOf.number.lessThanOrEquals(
        "imageBasedLightingFactor.x",
        value.x,
        1.0,
      );
      Check.typeOf.number.greaterThanOrEquals(
        "imageBasedLightingFactor.y",
        value.y,
        0.0,
      );
      Check.typeOf.number.lessThanOrEquals(
        "imageBasedLightingFactor.y",
        value.y,
        1.0,
      );
      //>>includeEnd('debug');
      this._previousImageBasedLightingFactor = Cartesian2.clone(
        this._imageBasedLightingFactor,
        this._previousImageBasedLightingFactor,
      );
      this._imageBasedLightingFactor = Cartesian2.clone(
        value,
        this._imageBasedLightingFactor,
      );
    },
  },
 
  /**
   * The third order spherical harmonic coefficients used for the diffuse color of image-based lighting. When <code>undefined</code>, a diffuse irradiance
   * computed from the atmosphere color is used.
   * <p>
   * There are nine <code>Cartesian3</code> coefficients.
   * The order of the coefficients is: L<sub>0,0</sub>, L<sub>1,-1</sub>, L<sub>1,0</sub>, L<sub>1,1</sub>, L<sub>2,-2</sub>, L<sub>2,-1</sub>, L<sub>2,0</sub>, L<sub>2,1</sub>, L<sub>2,2</sub>
   * </p>
   *
   * These values can be obtained by preprocessing the environment map using the <code>cmgen</code> tool of
   * {@link https://github.com/google/filament/releases|Google's Filament project}.
   * Be sure to use the <code>--no-mirror</code> option in <code>cmgen</code>.
   *
   * @memberof ImageBasedLighting.prototype
   *
   * @type {Cartesian3[]}
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Image-Based Lighting.html|Sandcastle Image Based Lighting Demo}
   * @see {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf|An Efficient Representation for Irradiance Environment Maps}
   */
  sphericalHarmonicCoefficients: {
    get: function () {
      return this._sphericalHarmonicCoefficients;
    },
    set: function (value) {
      //>>includeStart('debug', pragmas.debug);
      if (defined(value) && (!Array.isArray(value) || value.length !== 9)) {
        throw new DeveloperError(
          "sphericalHarmonicCoefficients must be an array of 9 Cartesian3 values.",
        );
      }
      //>>includeEnd('debug');
      this._previousSphericalHarmonicCoefficients =
        this._sphericalHarmonicCoefficients;
      this._sphericalHarmonicCoefficients = value;
    },
  },
 
  /**
   * A URL to a KTX2 file that contains a cube map of the specular lighting and the convoluted specular mipmaps.
   *
   * @memberof ImageBasedLighting.prototype
   * @demo {@link https://sandcastle.cesium.com/index.html?src=Image-Based Lighting.html|Sandcastle Image Based Lighting Demo}
   * @type {string}
   * @see ImageBasedLighting#sphericalHarmonicCoefficients
   */
  specularEnvironmentMaps: {
    get: function () {
      return this._specularEnvironmentMaps;
    },
    set: function (value) {
      if (value !== this._specularEnvironmentMaps) {
        this._specularEnvironmentCubeMapDirty =
          this._specularEnvironmentCubeMapDirty ||
          value !== this._specularEnvironmentMaps;
        this._specularEnvironmentMapLoaded = false;
      }
      this._specularEnvironmentMaps = value;
    },
  },
 
  /**
   * Whether or not image-based lighting is enabled.
   *
   * @memberof ImageBasedLighting.prototype
   * @type {boolean}
   *
   * @private
   */
  enabled: {
    get: function () {
      return (
        this._imageBasedLightingFactor.x > 0.0 ||
        this._imageBasedLightingFactor.y > 0.0
      );
    },
  },
 
  /**
   * Whether or not the models that use this lighting should regenerate their shaders,
   * based on the properties and resources have changed.
   *
   * @memberof ImageBasedLighting.prototype
   * @type {boolean}
   *
   * @private
   */
  shouldRegenerateShaders: {
    get: function () {
      return this._shouldRegenerateShaders;
    },
  },
 
  /**
   * The texture atlas for the specular environment maps.
   *
   * @memberof ImageBasedLighting.prototype
   * @type {SpecularEnvironmentCubeMap}
   *
   * @private
   */
  specularEnvironmentCubeMap: {
    get: function () {
      return this._specularEnvironmentCubeMap;
    },
  },
 
  /**
   * Whether or not to use the default spherical harmonics coefficients.
   *
   * @memberof ImageBasedLighting.prototype
   * @type {boolean}
   *
   * @private
   */
  useDefaultSphericalHarmonics: {
    get: function () {
      return this._useDefaultSphericalHarmonics;
    },
  },
 
  /**
   * Whether or not to use the default specular environment maps.
   *
   * @memberof ImageBasedLighting.prototype
   * @type {boolean}
   *
   * @private
   */
  useDefaultSpecularMaps: {
    get: function () {
      return this._useDefaultSpecularMaps;
    },
  },
 
  /**
   * Whether or not the image-based lighting settings use specular environment maps.
   *
   * @memberof ImageBasedLighting.prototype
   * @type {boolean}
   *
   * @private
   */
  useSpecularEnvironmentMaps: {
    get: function () {
      return (
        (defined(this._specularEnvironmentCubeMap) &&
          this._specularEnvironmentCubeMap.ready) ||
        this._useDefaultSpecularMaps
      );
    },
  },
});
 
function createSpecularEnvironmentCubeMap(imageBasedLighting, context) {
  Eif (!SpecularEnvironmentCubeMap.isSupported(context)) {
    return;
  }
 
  imageBasedLighting._specularEnvironmentCubeMap =
    imageBasedLighting._specularEnvironmentCubeMap &&
    imageBasedLighting._specularEnvironmentCubeMap.destroy();
 
  if (defined(imageBasedLighting._specularEnvironmentMaps)) {
    const cubeMap = new SpecularEnvironmentCubeMap(
      imageBasedLighting._specularEnvironmentMaps,
    );
    imageBasedLighting._specularEnvironmentCubeMap = cubeMap;
 
    imageBasedLighting._removeErrorListener =
      cubeMap.errorEvent.addEventListener((error) => {
        console.error(`Error loading specularEnvironmentMaps: ${error}`);
      });
  }
 
  // Regenerate shaders so they do not use an environment map.
  // Will be set to true again if there was a new environment map and it is ready.
  imageBasedLighting._shouldRegenerateShaders = true;
}
 
ImageBasedLighting.prototype.update = function (frameState) {
  if (
    frameState.frameNumber === this._previousFrameNumber &&
    frameState.context === this._previousFrameContext
  ) {
    return;
  }
 
  this._previousFrameNumber = frameState.frameNumber;
  const context = (this._previousFrameContext = frameState.context);
 
  frameState.brdfLutGenerator.update(frameState);
  this._shouldRegenerateShaders = false;
 
  const iblFactor = this._imageBasedLightingFactor;
  const previousIBLFactor = this._previousImageBasedLightingFactor;
  if (!Cartesian2.equals(iblFactor, previousIBLFactor)) {
    this._shouldRegenerateShaders =
      (iblFactor.x > 0.0 && previousIBLFactor.x === 0.0) ||
      (iblFactor.x === 0.0 && previousIBLFactor.x > 0.0);
    this._shouldRegenerateShaders =
      this._shouldRegenerateShaders ||
      (iblFactor.y > 0.0 && previousIBLFactor.y === 0.0) ||
      (iblFactor.y === 0.0 && previousIBLFactor.y > 0.0);
 
    this._previousImageBasedLightingFactor = Cartesian2.clone(
      this._imageBasedLightingFactor,
      this._previousImageBasedLightingFactor,
    );
  }
 
  Iif (
    this._previousSphericalHarmonicCoefficients !==
    this._sphericalHarmonicCoefficients
  ) {
    this._shouldRegenerateShaders =
      this._shouldRegenerateShaders ||
      defined(this._previousSphericalHarmonicCoefficients) !==
        defined(this._sphericalHarmonicCoefficients);
 
    this._previousSphericalHarmonicCoefficients =
      this._sphericalHarmonicCoefficients;
  }
 
  this._shouldRegenerateShaders =
    this._shouldRegenerateShaders ||
    this._previousSpecularEnvironmentMapLoaded !==
      this._specularEnvironmentMapLoaded;
 
  this._previousSpecularEnvironmentMapLoaded =
    this._specularEnvironmentMapLoaded;
 
  if (this._specularEnvironmentCubeMapDirty) {
    createSpecularEnvironmentCubeMap(this, context);
    this._specularEnvironmentCubeMapDirty = false;
  }
 
  Iif (defined(this._specularEnvironmentCubeMap)) {
    this._specularEnvironmentCubeMap.update(frameState);
    if (this._specularEnvironmentCubeMap.ready) {
      this._specularEnvironmentMapLoaded = true;
    }
  }
 
  const recompileWithDefaultCubeMap =
    !defined(this._specularEnvironmentCubeMap) &&
    defined(frameState.specularEnvironmentMaps) &&
    !this._useDefaultSpecularMaps;
  const recompileWithoutDefaultCubeMap =
    !defined(frameState.specularEnvironmentMaps) &&
    this._useDefaultSpecularMaps;
 
  const recompileWithDefaultSHCoeffs =
    !defined(this._sphericalHarmonicCoefficients) &&
    defined(frameState.sphericalHarmonicCoefficients) &&
    !this._useDefaultSphericalHarmonics;
  const recompileWithoutDefaultSHCoeffs =
    !defined(frameState.sphericalHarmonicCoefficients) &&
    this._useDefaultSphericalHarmonics;
 
  this._shouldRegenerateShaders =
    this._shouldRegenerateShaders ||
    recompileWithDefaultCubeMap ||
    recompileWithoutDefaultCubeMap ||
    recompileWithDefaultSHCoeffs ||
    recompileWithoutDefaultSHCoeffs;
 
  this._useDefaultSpecularMaps =
    !defined(this._specularEnvironmentCubeMap) &&
    defined(frameState.specularEnvironmentMaps);
  this._useDefaultSphericalHarmonics =
    !defined(this._sphericalHarmonicCoefficients) &&
    defined(frameState.sphericalHarmonicCoefficients);
};
 
/**
 * 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 ImageBasedLighting#destroy
 * @private
 */
ImageBasedLighting.prototype.isDestroyed = function () {
  return false;
};
 
/**
 * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
 * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
 * <br /><br />
 * Once an 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
 * imageBasedLighting = imageBasedLighting && imageBasedLighting.destroy();
 *
 * @see ImageBasedLighting#isDestroyed
 * @private
 */
ImageBasedLighting.prototype.destroy = function () {
  this._specularEnvironmentCubeMap =
    this._specularEnvironmentCubeMap &&
    this._specularEnvironmentCubeMap.destroy();
  this._removeErrorListener =
    this._removeErrorListener && this._removeErrorListener();
  return destroyObject(this);
};
 
export default ImageBasedLighting;