All files / engine/Source/Scene GltfDracoLoader.js

98.31% Statements 117/119
80% Branches 32/40
100% Functions 10/10
98.31% Lines 117/119

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                                                              53x 53x 53x 53x 53x 53x 53x 53x     53x 52x 51x 50x 49x 48x     47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x     1x 1x 1x     1x                       198x                           119x           46x 46x 46x           46x 46x   45x 2x     43x 43x 43x   1x       1x                 1x 127x 81x     46x 46x 46x       5x 5x 5x 5x       43x 43x 36x 1x       35x   35x       35x 35x   7x 1x       6x       1x 1x 1x 1x 1x     447x 1006x 1006x 437x         10x                 1x   486x     486x 110x     376x 1x     375x 4x     371x         371x   215x     156x 156x 156x 156x 156x 156x 156x       156x   156x 447x 447x 447x 437x 437x 437x 437x             156x                       156x   156x   113x     43x             1x 84x 46x     84x 84x 84x 84x 84x        
import Check from "../Core/Check.js";
import ComponentDatatype from "../Core/ComponentDatatype.js";
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import DracoLoader from "./DracoLoader.js";
import ResourceLoader from "./ResourceLoader.js";
import ResourceLoaderState from "./ResourceLoaderState.js";
import VertexAttributeSemantic from "./VertexAttributeSemantic.js";
 
/**
 * Load a draco buffer from a glTF.
 * <p>
 * Implements the {@link ResourceLoader} interface.
 * </p>
 *
 * @alias GltfDracoLoader
 * @constructor
 * @augments ResourceLoader
 *
 * @param {object} options Object with the following properties:
 * @param {ResourceCache} options.resourceCache The {@link ResourceCache} (to avoid circular dependencies).
 * @param {object} options.gltf The glTF JSON.
 * @param {object} options.primitive The primitive containing the Draco extension.
 * @param {object} options.draco The Draco extension object.
 * @param {Resource} options.gltfResource The {@link Resource} containing the glTF.
 * @param {Resource} options.baseResource The {@link Resource} that paths in the glTF JSON are relative to.
 * @param {string} [options.cacheKey] The cache key of the resource.
 *
 * @private
 */
function GltfDracoLoader(options) {
  options = options ?? Frozen.EMPTY_OBJECT;
  const resourceCache = options.resourceCache;
  const gltf = options.gltf;
  const primitive = options.primitive;
  const draco = options.draco;
  const gltfResource = options.gltfResource;
  const baseResource = options.baseResource;
  const cacheKey = options.cacheKey;
 
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.func("options.resourceCache", resourceCache);
  Check.typeOf.object("options.gltf", gltf);
  Check.typeOf.object("options.primitive", primitive);
  Check.typeOf.object("options.draco", draco);
  Check.typeOf.object("options.gltfResource", gltfResource);
  Check.typeOf.object("options.baseResource", baseResource);
  //>>includeEnd('debug');
 
  this._resourceCache = resourceCache;
  this._gltfResource = gltfResource;
  this._baseResource = baseResource;
  this._gltf = gltf;
  this._primitive = primitive;
  this._draco = draco;
  this._cacheKey = cacheKey;
  this._bufferViewLoader = undefined;
  this._bufferViewTypedArray = undefined;
  this._decodePromise = undefined;
  this._decodedData = undefined;
  this._state = ResourceLoaderState.UNLOADED;
  this._promise = undefined;
  this._dracoError = undefined;
}
 
Eif (defined(Object.create)) {
  GltfDracoLoader.prototype = Object.create(ResourceLoader.prototype);
  GltfDracoLoader.prototype.constructor = GltfDracoLoader;
}
 
Object.defineProperties(GltfDracoLoader.prototype, {
  /**
   * The cache key of the resource.
   *
   * @memberof GltfDracoLoader.prototype
   *
   * @type {string}
   * @readonly
   * @private
   */
  cacheKey: {
    get: function () {
      return this._cacheKey;
    },
  },
  /**
   * The decoded data.
   *
   * @memberof GltfDracoLoader.prototype
   *
   * @type {object}
   * @readonly
   * @private
   */
  decodedData: {
    get: function () {
      return this._decodedData;
    },
  },
});
 
async function loadResources(loader) {
  const resourceCache = loader._resourceCache;
  try {
    const bufferViewLoader = resourceCache.getBufferViewLoader({
      gltf: loader._gltf,
      bufferViewId: loader._draco.bufferView,
      gltfResource: loader._gltfResource,
      baseResource: loader._baseResource,
    });
    loader._bufferViewLoader = bufferViewLoader;
    await bufferViewLoader.load();
 
    if (loader.isDestroyed()) {
      return;
    }
 
    loader._bufferViewTypedArray = bufferViewLoader.typedArray;
    loader._state = ResourceLoaderState.PROCESSING;
    return loader;
  } catch (error) {
    Iif (loader.isDestroyed()) {
      return;
    }
 
    handleError(loader, error);
  }
}
 
/**
 * Loads the resource.
 * @returns {Promise<GltfDracoLoader>} A promise which resolves to the loader when the resource loading is completed.
 * @private
 */
GltfDracoLoader.prototype.load = async function () {
  if (defined(this._promise)) {
    return this._promise;
  }
 
  this._state = ResourceLoaderState.LOADING;
  this._promise = loadResources(this);
  return this._promise;
};
 
function handleError(dracoLoader, error) {
  dracoLoader.unload();
  dracoLoader._state = ResourceLoaderState.FAILED;
  const errorMessage = "Failed to load Draco";
  throw dracoLoader.getError(errorMessage, error);
}
 
async function processDecode(loader, decodePromise) {
  try {
    const results = await decodePromise;
    if (loader.isDestroyed()) {
      return;
    }
 
    // Unload everything except the decoded data
    loader.unload();
 
    loader._decodedData = {
      indices: results.indexArray,
      vertexAttributes: results.attributeData,
    };
    loader._state = ResourceLoaderState.READY;
    return loader._baseResource;
  } catch (error) {
    if (loader.isDestroyed()) {
      return;
    }
 
    // Capture this error so it can be thrown on the next `process` call
    loader._dracoError = error;
  }
}
 
const SemanticToDracoAttributeType = {};
SemanticToDracoAttributeType[VertexAttributeSemantic.POSITION] = "POSITION";
SemanticToDracoAttributeType[VertexAttributeSemantic.NORMAL] = "NORMAL";
SemanticToDracoAttributeType[VertexAttributeSemantic.COLOR] = "COLOR";
SemanticToDracoAttributeType[VertexAttributeSemantic.TEXCOORD] = "TEX_COORD";
 
function getDracoAttributeType(attribute) {
  for (const semantic in SemanticToDracoAttributeType) {
    Eif (SemanticToDracoAttributeType.hasOwnProperty(semantic)) {
      if (attribute.startsWith(semantic)) {
        return SemanticToDracoAttributeType[semantic];
      }
    }
  }
 
  return undefined;
}
 
/**
 * Processes the resource until it becomes ready.
 *
 * @param {FrameState} frameState The frame state.
 * @private
 */
GltfDracoLoader.prototype.process = function (frameState) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.object("frameState", frameState);
  //>>includeEnd('debug');
 
  if (this._state === ResourceLoaderState.READY) {
    return true;
  }
 
  if (this._state !== ResourceLoaderState.PROCESSING) {
    return false;
  }
 
  if (defined(this._dracoError)) {
    handleError(this, this._dracoError);
  }
 
  Iif (!defined(this._bufferViewTypedArray)) {
    // Not ready to decode the Draco buffer
    return false;
  }
 
  if (defined(this._decodePromise)) {
    // Currently decoding
    return false;
  }
 
  const draco = this._draco;
  const primitive = this._primitive;
  const gltf = this._gltf;
  const bufferViews = gltf.bufferViews;
  const bufferViewId = draco.bufferView;
  const bufferView = bufferViews[bufferViewId];
  const compressedAttributes = draco.attributes;
 
  // Skip de-quantization transform if present for floating point attributes.
  // They will stay quantized in memory and be dequantized in the shader.
  const attributesToSkipTransform = [];
 
  for (const attribute in primitive.attributes) {
    Eif (primitive.attributes.hasOwnProperty(attribute)) {
      const dracoAttributeType = getDracoAttributeType(attribute);
      if (defined(dracoAttributeType)) {
        const accessor = gltf.accessors[primitive.attributes[attribute]];
        Eif (accessor.componentType === ComponentDatatype.FLOAT) {
          Eif (!attributesToSkipTransform.includes(dracoAttributeType)) {
            attributesToSkipTransform.push(dracoAttributeType);
          }
        }
      }
    }
  }
 
  const decodeOptions = {
    // Need to make a copy of the typed array otherwise the underlying
    // ArrayBuffer may be accessed on both the worker and the main thread. This
    // leads to errors such as "ArrayBuffer at index 0 is already detached".
    // PERFORMANCE_IDEA: Look into SharedArrayBuffer to get around this.
    array: new Uint8Array(this._bufferViewTypedArray),
    bufferView: bufferView,
    compressedAttributes: compressedAttributes,
    dequantizeInShader: true,
    attributesToSkipTransform: attributesToSkipTransform,
  };
 
  const decodePromise = DracoLoader.decodeBufferView(decodeOptions);
 
  if (!defined(decodePromise)) {
    // Cannot schedule task this frame
    return false;
  }
 
  this._decodePromise = processDecode(this, decodePromise);
};
 
/**
 * Unloads the resource.
 * @private
 */
GltfDracoLoader.prototype.unload = function () {
  if (defined(this._bufferViewLoader)) {
    this._resourceCache.unload(this._bufferViewLoader);
  }
 
  this._bufferViewLoader = undefined;
  this._bufferViewTypedArray = undefined;
  this._decodedData = undefined;
  this._gltf = undefined;
  this._primitive = undefined;
};
 
export default GltfDracoLoader;