All files / engine/Source/Scene/Model CustomShader.js

99.06% Statements 106/107
94.73% Branches 36/38
100% Functions 15/15
99.06% Lines 106/107

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 465 466 467 468 469 470                                                                                                                                                                                                                                                    77x                 77x               77x             77x               77x             77x             77x                       77x                     77x                 77x                 77x               77x                     77x             77x 77x       77x 77x 77x 11x 11x 11x   11x             11x 3x 3x         8x             77x       3x 4x               8x 6x           275x 95x         95x         77x 77x 77x     77x 77x 37x 37x   37x 37x   37x 37x     77x 77x 41x 41x   41x 41x   41x 41x   41x 41x 41x         32x 32x 32x   32x 12x     20x 1x     19x 11x     8x                 1112x 16x         16x         77x     77x 76x 75x 74x     73x 72x     71x 70x 69x   68x     68x 67x 66x 65x       64x 63x 62x               1x   7x 6x 5x 1x         4x 4x   1x 3x   2x   1x       1x 136x 136x                         1x 3x                                   1x 3x 3x        
import Check from "../../Core/Check.js";
import Frozen from "../../Core/Frozen.js";
import defined from "../../Core/defined.js";
import destroyObject from "../../Core/destroyObject.js";
import DeveloperError from "../../Core/DeveloperError.js";
import CustomShaderMode from "./CustomShaderMode.js";
import UniformType from "./UniformType.js";
import TextureManager from "./TextureManager.js";
import CustomShaderTranslucencyMode from "./CustomShaderTranslucencyMode.js";
 
/**
 * An object describing a uniform, its type, and an initial value
 *
 * @typedef {object} UniformSpecifier
 * @property {UniformType} type The Glsl type of the uniform.
 * @property {boolean|number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4|TextureUniform} value The initial value of the uniform
 *
 * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
 */
 
/**
 * A set of variables parsed from the user-defined shader code. These can be
 * used for optimizations when generating the overall shader. Though they are
 * represented as JS objects, the intended use is like a set, so only the
 * existence of keys matter. The values will always be <code>true</code> if
 * defined. This data structure is used because:
 * <ul>
 *   <li>We cannot yet use ES6 Set objects</li>
 *   <li>Using a dictionary automatically de-duplicates variable names</li>
 *   <li>Queries such as <code>variableSet.hasOwnProperty("position")</code> are straightforward</li>
 * </ul>
 * @typedef {Object<string, boolean>} VariableSet
 * @private
 */
 
/**
 * Variable sets parsed from the user-defined vertex shader text.
 * @typedef {object} VertexVariableSets
 * @property {VariableSet} attributeSet A set of all unique attributes used in the vertex shader via the <code>vsInput.attributes</code> struct.
 * @property {VariableSet} featureIdSet A set of all unique feature ID sets used in the vertex shader via the <code>vsInput.featureIds</code> struct.
 * @property {VariableSet} metadataSet A set of all unique metadata properties used in the vertex shader via the <code>vsInput.metadata</code> struct.
 * @private
 */
 
/**
 * Variable sets parsed from the user-defined fragment shader text.
 * @typedef {object} FragmentVariableSets
 * @property {VariableSet} attributeSet A set of all unique attributes used in the fragment shader via the <code>fsInput.attributes</code> struct
 * @property {VariableSet} featureIdSet A set of all unique feature ID sets used in the fragment shader via the <code>fsInput.featureIds</code> struct.
 * @property {VariableSet} metadataSet A set of all unique metadata properties used in the fragment shader via the <code>fsInput.metadata</code> struct.
 * @property {VariableSet} materialSet A set of all material variables such as diffuse, specular or alpha that are used in the fragment shader via the <code>material</code> struct.
 * @private
 */
 
/**
 * A user defined GLSL shader used with {@link Model} as well
 * as {@link Cesium3DTileset}.
 * <p>
 * If texture uniforms are used, additional resource management must be done:
 * </p>
 * <ul>
 *   <li>
 *      The <code>update</code> function must be called each frame. When a
 *      custom shader is passed to a {@link Model} or a
 *      {@link Cesium3DTileset}, this step is handled automaticaly
 *   </li>
 *   <li>
 *      {@link CustomShader#destroy} must be called when the custom shader is
 *      no longer needed to clean up GPU resources properly. The application
 *      is responsible for calling this method.
 *   </li>
 * </ul>
 * <p>
 * See the {@link https://github.com/CesiumGS/cesium/tree/main/Documentation/CustomShaderGuide|Custom Shader Guide} for more detailed documentation.
 * </p>
 *
 * @param {object} options An object with the following options
 * @param {CustomShaderMode} [options.mode=CustomShaderMode.MODIFY_MATERIAL] The custom shader mode, which determines how the custom shader code is inserted into the fragment shader.
 * @param {LightingModel} [options.lightingModel] The lighting model (e.g. PBR or unlit). If present, this overrides the default lighting for the model.
 * @param {CustomShaderTranslucencyMode} [options.translucencyMode=CustomShaderTranslucencyMode.INHERIT] The translucency mode, which determines how the custom shader will be applied. If the value is CustomShaderTransulcencyMode.OPAQUE or CustomShaderTransulcencyMode.TRANSLUCENT, the custom shader will override settings from the model's material. If the value is CustomShaderTransulcencyMode.INHERIT, the custom shader will render as either opaque or translucent depending on the primitive's material settings.
 * @param {Object<string, UniformSpecifier>} [options.uniforms] A dictionary for user-defined uniforms. The key is the uniform name that will appear in the GLSL code. The value is an object that describes the uniform type and initial value
 * @param {Object<string, VaryingType>} [options.varyings] A dictionary for declaring additional GLSL varyings used in the shader. The key is the varying name that will appear in the GLSL code. The value is the data type of the varying. For each varying, the declaration will be added to the top of the shader automatically. The caller is responsible for assigning a value in the vertex shader and using the value in the fragment shader.
 * @param {string} [options.vertexShaderText] The custom vertex shader as a string of GLSL code. It must include a GLSL function called vertexMain. See the example for the expected signature. If not specified, the custom vertex shader step will be skipped in the computed vertex shader.
 * @param {string} [options.fragmentShaderText] The custom fragment shader as a string of GLSL code. It must include a GLSL function called fragmentMain. See the example for the expected signature. If not specified, the custom fragment shader step will be skipped in the computed fragment shader.
 *
 * @alias CustomShader
 * @constructor
 *
 * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
 *
 * @example
 * const customShader = new CustomShader({
 *   uniforms: {
 *     u_colorIndex: {
 *       type: Cesium.UniformType.FLOAT,
 *       value: 1.0
 *     },
 *     u_normalMap: {
 *       type: Cesium.UniformType.SAMPLER_2D,
 *       value: new Cesium.TextureUniform({
 *         url: "http://example.com/normal.png"
 *       })
 *     }
 *   },
 *   varyings: {
 *     v_selectedColor: Cesium.VaryingType.VEC3
 *   },
 *   vertexShaderText: `
 *   void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput) {
 *     v_selectedColor = mix(vsInput.attributes.color_0, vsInput.attributes.color_1, u_colorIndex);
 *     vsOutput.positionMC += 0.1 * vsInput.attributes.normal;
 *   }
 *   `,
 *   fragmentShaderText: `
 *   void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
 *     material.normal = texture(u_normalMap, fsInput.attributes.texCoord_0);
 *     material.diffuse = v_selectedColor;
 *   }
 *   `
 * });
 */
function CustomShader(options) {
  options = options ?? Frozen.EMPTY_OBJECT;
 
  /**
   * A value determining how the custom shader interacts with the overall
   * fragment shader. This is used by {@link CustomShaderPipelineStage}
   *
   * @type {CustomShaderMode}
   * @readonly
   */
  this.mode = options.mode ?? CustomShaderMode.MODIFY_MATERIAL;
  /**
   * The lighting model to use when using the custom shader.
   * This is used by {@link CustomShaderPipelineStage}
   *
   * @type {LightingModel}
   * @readonly
   */
  this.lightingModel = options.lightingModel;
  /**
   * Additional uniforms as declared by the user.
   *
   * @type {Object<string, UniformSpecifier>}
   * @readonly
   */
  this.uniforms = options.uniforms ?? Frozen.EMPTY_OBJECT;
  /**
   * Additional varyings as declared by the user.
   * This is used by {@link CustomShaderPipelineStage}
   *
   * @type {Object<string, VaryingType>}
   * @readonly
   */
  this.varyings = options.varyings ?? Frozen.EMPTY_OBJECT;
  /**
   * The user-defined GLSL code for the vertex shader
   *
   * @type {string}
   * @readonly
   */
  this.vertexShaderText = options.vertexShaderText;
  /**
   * The user-defined GLSL code for the fragment shader
   *
   * @type {string}
   * @readonly
   */
  this.fragmentShaderText = options.fragmentShaderText;
 
  /**
   * The translucency mode, which determines how the custom shader will be applied. If the value is
   * CustomShaderTransulcencyMode.OPAQUE or CustomShaderTransulcencyMode.TRANSLUCENT, the custom shader
   * will override settings from the model's material. If the value isCustomShaderTransulcencyMode.INHERIT,
   * the custom shader will render as either opaque or translucent depending on the primitive's material settings.
   *
   * @type {CustomShaderTranslucencyMode}
   * @default CustomShaderTranslucencyMode.INHERIT
   * @readonly
   */
  this.translucencyMode =
    options.translucencyMode ?? CustomShaderTranslucencyMode.INHERIT;
 
  /**
   * texture uniforms require some asynchronous processing. This is delegated
   * to a texture manager.
   *
   * @type {TextureManager}
   * @readonly
   * @private
   */
  this._textureManager = new TextureManager();
  /**
   * The default texture (from the {@link Context}) to use while textures
   * are loading
   *
   * @type {Texture}
   * @readonly
   * @private
   */
  this._defaultTexture = undefined;
  /**
   * The map of uniform names to a function that returns a value. This map
   * is combined with the overall uniform map used by the {@link DrawCommand}
   *
   * @type {Object<string, Function>}
   * @readonly
   * @private
   */
  this.uniformMap = buildUniformMap(this);
 
  /**
   * A collection of variables used in <code>vertexShaderText</code>. This
   * is used only for optimizations in {@link CustomShaderPipelineStage}.
   * @type {VertexVariableSets}
   * @private
   */
  this.usedVariablesVertex = {
    attributeSet: {},
    featureIdSet: {},
    metadataSet: {},
  };
  /**
   * A collection of variables used in <code>fragmentShaderText</code>. This
   * is used only for optimizations in {@link CustomShaderPipelineStage}.
   * @type {FragmentVariableSets}
   * @private
   */
  this.usedVariablesFragment = {
    attributeSet: {},
    featureIdSet: {},
    metadataSet: {},
    materialSet: {},
  };
 
  findUsedVariables(this);
  validateBuiltinVariables(this);
}
 
function buildUniformMap(customShader) {
  const uniforms = customShader.uniforms;
  const uniformMap = {};
  for (const uniformName in uniforms) {
    Eif (uniforms.hasOwnProperty(uniformName)) {
      const uniform = uniforms[uniformName];
      const type = uniform.type;
      //>>includeStart('debug', pragmas.debug);
      Iif (type === UniformType.SAMPLER_CUBE) {
        throw new DeveloperError(
          "CustomShader does not support samplerCube uniforms",
        );
      }
      //>>includeEnd('debug');
 
      if (type === UniformType.SAMPLER_2D) {
        customShader._textureManager.loadTexture2D(uniformName, uniform.value);
        uniformMap[uniformName] = createUniformTexture2DFunction(
          customShader,
          uniformName,
        );
      } else {
        uniformMap[uniformName] = createUniformFunction(
          customShader,
          uniformName,
        );
      }
    }
  }
  return uniformMap;
}
 
function createUniformTexture2DFunction(customShader, uniformName) {
  return function () {
    return (
      customShader._textureManager.getTexture(uniformName) ??
      customShader._defaultTexture
    );
  };
}
 
function createUniformFunction(customShader, uniformName) {
  return function () {
    return customShader.uniforms[uniformName].value;
  };
}
 
function getVariables(shaderText, regex, outputSet) {
  let match;
  while ((match = regex.exec(shaderText)) !== null) {
    const variableName = match[1];
 
    // Using a dictionary like a set. The value doesn't
    // matter, as this will only be used for queries such as
    // if (set.hasOwnProperty(variableName)) { ... }
    outputSet[variableName] = true;
  }
}
 
function findUsedVariables(customShader) {
  const attributeRegex = /[vf]sInput\.attributes\.(\w+)/g;
  const featureIdRegex = /[vf]sInput\.featureIds\.(\w+)/g;
  const metadataRegex = /[vf]sInput\.metadata.(\w+)/g;
  let attributeSet;
 
  const vertexShaderText = customShader.vertexShaderText;
  if (defined(vertexShaderText)) {
    attributeSet = customShader.usedVariablesVertex.attributeSet;
    getVariables(vertexShaderText, attributeRegex, attributeSet);
 
    attributeSet = customShader.usedVariablesVertex.featureIdSet;
    getVariables(vertexShaderText, featureIdRegex, attributeSet);
 
    attributeSet = customShader.usedVariablesVertex.metadataSet;
    getVariables(vertexShaderText, metadataRegex, attributeSet);
  }
 
  const fragmentShaderText = customShader.fragmentShaderText;
  if (defined(fragmentShaderText)) {
    attributeSet = customShader.usedVariablesFragment.attributeSet;
    getVariables(fragmentShaderText, attributeRegex, attributeSet);
 
    attributeSet = customShader.usedVariablesFragment.featureIdSet;
    getVariables(fragmentShaderText, featureIdRegex, attributeSet);
 
    attributeSet = customShader.usedVariablesFragment.metadataSet;
    getVariables(fragmentShaderText, metadataRegex, attributeSet);
 
    const materialRegex = /material\.(\w+)/g;
    const materialSet = customShader.usedVariablesFragment.materialSet;
    getVariables(fragmentShaderText, materialRegex, materialSet);
  }
}
 
function expandCoordinateAbbreviations(variableName) {
  const modelCoordinatesRegex = /^.*MC$/;
  const worldCoordinatesRegex = /^.*WC$/;
  const eyeCoordinatesRegex = /^.*EC$/;
 
  if (modelCoordinatesRegex.test(variableName)) {
    return `${variableName} (model coordinates)`;
  }
 
  if (worldCoordinatesRegex.test(variableName)) {
    return `${variableName} (Cartesian world coordinates)`;
  }
 
  if (eyeCoordinatesRegex.test(variableName)) {
    return `${variableName} (eye coordinates)`;
  }
 
  return variableName;
}
 
function validateVariableUsage(
  variableSet,
  incorrectVariable,
  correctVariable,
  vertexOrFragment,
) {
  if (variableSet.hasOwnProperty(incorrectVariable)) {
    const message = `${expandCoordinateAbbreviations(
      incorrectVariable,
    )} is not available in the ${vertexOrFragment} shader. Did you mean ${expandCoordinateAbbreviations(
      correctVariable,
    )} instead?`;
    throw new DeveloperError(message);
  }
}
 
function validateBuiltinVariables(customShader) {
  const attributesVS = customShader.usedVariablesVertex.attributeSet;
 
  // names without MC/WC/EC are ambiguous
  validateVariableUsage(attributesVS, "position", "positionMC", "vertex");
  validateVariableUsage(attributesVS, "normal", "normalMC", "vertex");
  validateVariableUsage(attributesVS, "tangent", "tangentMC", "vertex");
  validateVariableUsage(attributesVS, "bitangent", "bitangentMC", "vertex");
 
  // world and eye coordinate positions are only available in the fragment shader.
  validateVariableUsage(attributesVS, "positionWC", "positionMC", "vertex");
  validateVariableUsage(attributesVS, "positionEC", "positionMC", "vertex");
 
  // normal, tangent and bitangent are in model coordinates in the vertex shader
  validateVariableUsage(attributesVS, "normalEC", "normalMC", "vertex");
  validateVariableUsage(attributesVS, "tangentEC", "tangentMC", "vertex");
  validateVariableUsage(attributesVS, "bitangentEC", "bitangentMC", "vertex");
 
  const attributesFS = customShader.usedVariablesFragment.attributeSet;
 
  // names without MC/WC/EC are ambiguous
  validateVariableUsage(attributesFS, "position", "positionEC", "fragment");
  validateVariableUsage(attributesFS, "normal", "normalEC", "fragment");
  validateVariableUsage(attributesFS, "tangent", "tangentEC", "fragment");
  validateVariableUsage(attributesFS, "bitangent", "bitangentEC", "fragment");
 
  // normal, tangent, and bitangent are in eye coordinates in the fragment
  // shader.
  validateVariableUsage(attributesFS, "normalMC", "normalEC", "fragment");
  validateVariableUsage(attributesFS, "tangentMC", "tangentEC", "fragment");
  validateVariableUsage(attributesFS, "bitangentMC", "bitangentEC", "fragment");
}
 
/**
 * Update the value of a uniform declared in the shader
 * @param {string} uniformName The GLSL name of the uniform. This must match one of the uniforms declared in the constructor
 * @param {boolean|number|Cartesian2|Cartesian3|Cartesian4|Matrix2|Matrix3|Matrix4|string|Resource|TextureUniform} value The new value of the uniform.
 */
CustomShader.prototype.setUniform = function (uniformName, value) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.string("uniformName", uniformName);
  Check.defined("value", value);
  if (!defined(this.uniforms[uniformName])) {
    throw new DeveloperError(
      `Uniform ${uniformName} must be declared in the CustomShader constructor.`,
    );
  }
  //>>includeEnd('debug');
  const uniform = this.uniforms[uniformName];
  if (uniform.type === UniformType.SAMPLER_2D) {
    // Textures are loaded asynchronously
    this._textureManager.loadTexture2D(uniformName, value);
  } else if (defined(value.clone)) {
    // clone Cartesian and Matrix types.
    uniform.value = value.clone(uniform.value);
  } else {
    uniform.value = value;
  }
};
 
CustomShader.prototype.update = function (frameState) {
  this._defaultTexture = frameState.context.defaultTexture;
  this._textureManager.update(frameState);
};
 
/**
 * 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 CustomShader#destroy
 */
CustomShader.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
 * customShader = customShader && customShader.destroy();
 *
 * @see CustomShader#isDestroyed
 */
CustomShader.prototype.destroy = function () {
  this._textureManager = this._textureManager && this._textureManager.destroy();
  destroyObject(this);
};
 
export default CustomShader;