15832144755
2022-01-06 7b4c8991dca9cf2a809a95e239d144697d3afb56
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
import arraySlice from "../Core/arraySlice.js";
import ComponentDatatype from "../Core/ComponentDatatype.js";
import defined from "../Core/defined.js";
import FeatureDetection from "../Core/FeatureDetection.js";
import TaskProcessor from "../Core/TaskProcessor.js";
import ForEach from "./GltfPipeline/ForEach.js";
import when from "../ThirdParty/when.js";
 
/**
 * @private
 */
function DracoLoader() {}
 
// Maximum concurrency to use when decoding draco models
DracoLoader._maxDecodingConcurrency = Math.max(
  FeatureDetection.hardwareConcurrency - 1,
  1
);
 
// Exposed for testing purposes
DracoLoader._decoderTaskProcessor = undefined;
DracoLoader._taskProcessorReady = false;
DracoLoader._getDecoderTaskProcessor = function () {
  if (!defined(DracoLoader._decoderTaskProcessor)) {
    var processor = new TaskProcessor(
      "decodeDraco",
      DracoLoader._maxDecodingConcurrency
    );
    processor
      .initWebAssemblyModule({
        modulePath: "ThirdParty/Workers/draco_decoder_nodejs.js",
        wasmBinaryFile: "ThirdParty/draco_decoder.wasm",
      })
      .then(function () {
        DracoLoader._taskProcessorReady = true;
      });
    DracoLoader._decoderTaskProcessor = processor;
  }
 
  return DracoLoader._decoderTaskProcessor;
};
 
/**
 * Returns true if the model uses or requires KHR_draco_mesh_compression.
 *
 * @private
 */
DracoLoader.hasExtension = function (model) {
  return (
    defined(model.extensionsRequired.KHR_draco_mesh_compression) ||
    defined(model.extensionsUsed.KHR_draco_mesh_compression)
  );
};
 
function addBufferToLoadResources(loadResources, typedArray) {
  // Create a new id to differentiate from original glTF bufferViews
  var bufferViewId =
    "runtime." + Object.keys(loadResources.createdBufferViews).length;
 
  var loadResourceBuffers = loadResources.buffers;
  var id = Object.keys(loadResourceBuffers).length;
  loadResourceBuffers[id] = typedArray;
  loadResources.createdBufferViews[bufferViewId] = {
    buffer: id,
    byteOffset: 0,
    byteLength: typedArray.byteLength,
  };
 
  return bufferViewId;
}
 
function addNewVertexBuffer(typedArray, model, context) {
  var loadResources = model._loadResources;
  var id = addBufferToLoadResources(loadResources, typedArray);
  loadResources.vertexBuffersToCreate.enqueue(id);
  return id;
}
 
function addNewIndexBuffer(indexArray, model, context) {
  var typedArray = indexArray.typedArray;
  var loadResources = model._loadResources;
  var id = addBufferToLoadResources(loadResources, typedArray);
  loadResources.indexBuffersToCreate.enqueue({
    id: id,
    componentType: ComponentDatatype.fromTypedArray(typedArray),
  });
 
  return {
    bufferViewId: id,
    numberOfIndices: indexArray.numberOfIndices,
  };
}
 
function scheduleDecodingTask(
  decoderTaskProcessor,
  model,
  loadResources,
  context
) {
  if (!DracoLoader._taskProcessorReady) {
    // The task processor is not ready to schedule tasks
    return;
  }
 
  var taskData = loadResources.primitivesToDecode.peek();
  if (!defined(taskData)) {
    // All primitives are processing
    return;
  }
 
  var promise = decoderTaskProcessor.scheduleTask(taskData, [
    taskData.array.buffer,
  ]);
  if (!defined(promise)) {
    // Cannot schedule another task this frame
    return;
  }
 
  loadResources.activeDecodingTasks++;
  loadResources.primitivesToDecode.dequeue();
  return promise.then(function (result) {
    loadResources.activeDecodingTasks--;
 
    var decodedIndexBuffer = addNewIndexBuffer(
      result.indexArray,
      model,
      context
    );
 
    var attributes = {};
    var decodedAttributeData = result.attributeData;
    for (var attributeName in decodedAttributeData) {
      if (decodedAttributeData.hasOwnProperty(attributeName)) {
        var attribute = decodedAttributeData[attributeName];
        var vertexArray = attribute.array;
        var vertexBufferView = addNewVertexBuffer(vertexArray, model, context);
 
        var data = attribute.data;
        data.bufferView = vertexBufferView;
 
        attributes[attributeName] = data;
      }
    }
 
    model._decodedData[taskData.mesh + ".primitive." + taskData.primitive] = {
      bufferView: decodedIndexBuffer.bufferViewId,
      numberOfIndices: decodedIndexBuffer.numberOfIndices,
      attributes: attributes,
    };
  });
}
 
DracoLoader._decodedModelResourceCache = undefined;
 
/**
 * Parses draco extension on model primitives and
 * adds the decoding data to the model's load resources.
 *
 * @private
 */
DracoLoader.parse = function (model, context) {
  if (!DracoLoader.hasExtension(model)) {
    return;
  }
 
  var loadResources = model._loadResources;
  var cacheKey = model.cacheKey;
  if (defined(cacheKey)) {
    if (!defined(DracoLoader._decodedModelResourceCache)) {
      if (!defined(context.cache.modelDecodingCache)) {
        context.cache.modelDecodingCache = {};
      }
 
      DracoLoader._decodedModelResourceCache = context.cache.modelDecodingCache;
    }
 
    // Decoded data for model will be loaded from cache
    var cachedData = DracoLoader._decodedModelResourceCache[cacheKey];
    if (defined(cachedData)) {
      cachedData.count++;
      loadResources.pendingDecodingCache = true;
      return;
    }
  }
 
  var dequantizeInShader = model._dequantizeInShader;
  var gltf = model.gltf;
  ForEach.mesh(gltf, function (mesh, meshId) {
    ForEach.meshPrimitive(mesh, function (primitive, primitiveId) {
      if (!defined(primitive.extensions)) {
        return;
      }
 
      var compressionData = primitive.extensions.KHR_draco_mesh_compression;
      if (!defined(compressionData)) {
        return;
      }
 
      var bufferView = gltf.bufferViews[compressionData.bufferView];
      var typedArray = arraySlice(
        gltf.buffers[bufferView.buffer].extras._pipeline.source,
        bufferView.byteOffset,
        bufferView.byteOffset + bufferView.byteLength
      );
      loadResources.primitivesToDecode.enqueue({
        mesh: meshId,
        primitive: primitiveId,
        array: typedArray,
        bufferView: bufferView,
        compressedAttributes: compressionData.attributes,
        dequantizeInShader: dequantizeInShader,
      });
    });
  });
};
 
/**
 * Schedules decoding tasks available this frame.
 * @private
 */
DracoLoader.decodeModel = function (model, context) {
  if (!DracoLoader.hasExtension(model)) {
    return when.resolve();
  }
 
  var loadResources = model._loadResources;
  var cacheKey = model.cacheKey;
  if (defined(cacheKey) && defined(DracoLoader._decodedModelResourceCache)) {
    var cachedData = DracoLoader._decodedModelResourceCache[cacheKey];
    // Load decoded data for model when cache is ready
    if (defined(cachedData) && loadResources.pendingDecodingCache) {
      return when(cachedData.ready, function () {
        model._decodedData = cachedData.data;
        loadResources.pendingDecodingCache = false;
      });
    }
 
    // Decoded data for model should be cached when ready
    DracoLoader._decodedModelResourceCache[cacheKey] = {
      ready: false,
      count: 1,
      data: undefined,
    };
  }
 
  if (loadResources.primitivesToDecode.length === 0) {
    // No more tasks to schedule
    return when.resolve();
  }
 
  var decoderTaskProcessor = DracoLoader._getDecoderTaskProcessor();
  var decodingPromises = [];
 
  var promise = scheduleDecodingTask(
    decoderTaskProcessor,
    model,
    loadResources,
    context
  );
  while (defined(promise)) {
    decodingPromises.push(promise);
    promise = scheduleDecodingTask(
      decoderTaskProcessor,
      model,
      loadResources,
      context
    );
  }
 
  return when.all(decodingPromises);
};
 
/**
 * Decodes a compressed point cloud. Returns undefined if the task cannot be scheduled.
 * @private
 */
DracoLoader.decodePointCloud = function (parameters) {
  var decoderTaskProcessor = DracoLoader._getDecoderTaskProcessor();
  if (!DracoLoader._taskProcessorReady) {
    // The task processor is not ready to schedule tasks
    return;
  }
  return decoderTaskProcessor.scheduleTask(parameters, [
    parameters.buffer.buffer,
  ]);
};
 
/**
 * Decodes a buffer view. Returns undefined if the task cannot be scheduled.
 *
 * @param {Object} options Object with the following properties:
 * @param {Uint8Array} options.array The typed array containing the buffer view data.
 * @param {Object} options.bufferView The glTF buffer view object.
 * @param {Object.<String, Number>} options.compressedAttributes The compressed attributes.
 * @param {Boolean} options.dequantizeInShader Whether POSITION and NORMAL attributes should be dequantized on the GPU.
 *
 * @returns {Promise} A promise that resolves to the decoded indices and attributes.
 * @private
 */
DracoLoader.decodeBufferView = function (options) {
  var decoderTaskProcessor = DracoLoader._getDecoderTaskProcessor();
  if (!DracoLoader._taskProcessorReady) {
    // The task processor is not ready to schedule tasks
    return;
  }
 
  return decoderTaskProcessor.scheduleTask(options, [options.array.buffer]);
};
 
/**
 * Caches a models decoded data so it doesn't need to decode more than once.
 * @private
 */
DracoLoader.cacheDataForModel = function (model) {
  var cacheKey = model.cacheKey;
  if (defined(cacheKey) && defined(DracoLoader._decodedModelResourceCache)) {
    var cachedData = DracoLoader._decodedModelResourceCache[cacheKey];
    if (defined(cachedData)) {
      cachedData.ready = true;
      cachedData.data = model._decodedData;
    }
  }
};
 
/**
 * Destroys the cached data that this model references if it is no longer in use.
 * @private
 */
DracoLoader.destroyCachedDataForModel = function (model) {
  var cacheKey = model.cacheKey;
  if (defined(cacheKey) && defined(DracoLoader._decodedModelResourceCache)) {
    var cachedData = DracoLoader._decodedModelResourceCache[cacheKey];
    if (defined(cachedData) && --cachedData.count === 0) {
      delete DracoLoader._decodedModelResourceCache[cacheKey];
    }
  }
};
export default DracoLoader;