@xeokit/xeokit-sdk 2.3.0-beta-11 → 2.3.0-beta-14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15299,7 +15299,7 @@ class RenderBufferManager {
15299
15299
  /**
15300
15300
  * @private
15301
15301
  */
15302
- function getExtension$1 (gl, name) {
15302
+ function getExtension (gl, name) {
15303
15303
  if (gl._cachedExtensions === undefined) {
15304
15304
  gl._cachedExtensions = {};
15305
15305
  }
@@ -15365,12 +15365,12 @@ const Renderer = function (scene, options) {
15365
15365
  this._occlusionTester = null; // Lazy-created in #addMarker()
15366
15366
 
15367
15367
  this.capabilities = {
15368
- astcSupported: !!getExtension$1(gl, 'WEBGL_compressed_texture_astc'),
15368
+ astcSupported: !!getExtension(gl, 'WEBGL_compressed_texture_astc'),
15369
15369
  etc1Supported: true, // WebGL2
15370
- etc2Supported: !!getExtension$1(gl, 'WEBGL_compressed_texture_etc'),
15371
- dxtSupported: !!getExtension$1(gl, 'WEBGL_compressed_texture_s3tc'),
15372
- bptcSupported: !!getExtension$1(gl, 'EXT_texture_compression_bptc'),
15373
- pvrtcSupported: !!(getExtension$1(gl, 'WEBGL_compressed_texture_pvrtc') || getExtension$1(gl, 'WEBKIT_WEBGL_compressed_texture_pvrtc'))
15370
+ etc2Supported: !!getExtension(gl, 'WEBGL_compressed_texture_etc'),
15371
+ dxtSupported: !!getExtension(gl, 'WEBGL_compressed_texture_s3tc'),
15372
+ bptcSupported: !!getExtension(gl, 'EXT_texture_compression_bptc'),
15373
+ pvrtcSupported: !!(getExtension(gl, 'WEBGL_compressed_texture_pvrtc') || getExtension(gl, 'WEBKIT_WEBGL_compressed_texture_pvrtc'))
15374
15374
  };
15375
15375
 
15376
15376
  this.setTransparentEnabled = function (enabled) {
@@ -27801,6 +27801,7 @@ const ClampToEdgeWrapping = 1001;
27801
27801
  const MirroredRepeatWrapping = 1002;
27802
27802
  const NearestFilter = 1003;
27803
27803
  const NearestMipMapNearestFilter = 1004;
27804
+ const NearestMipmapNearestFilter = 1004;
27804
27805
  const NearestMipmapLinearFilter = 1005;
27805
27806
  const NearestMipMapLinearFilter = 1005;
27806
27807
  const LinearFilter = 1006;
@@ -64417,7 +64418,7 @@ function convertConstant(gl, constantVal, encoding = null) {
64417
64418
 
64418
64419
  if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
64419
64420
  if (encoding === sRGBEncoding) {
64420
- const extension = getExtension$1(gl, 'WEBGL_compressed_texture_s3tc_srgb');
64421
+ const extension = getExtension(gl, 'WEBGL_compressed_texture_s3tc_srgb');
64421
64422
  if (extension !== null) {
64422
64423
  if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
64423
64424
  if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
@@ -64427,7 +64428,7 @@ function convertConstant(gl, constantVal, encoding = null) {
64427
64428
  return null;
64428
64429
  }
64429
64430
  } else {
64430
- extension = getExtension$1(gl, 'WEBGL_compressed_texture_s3tc');
64431
+ extension = getExtension(gl, 'WEBGL_compressed_texture_s3tc');
64431
64432
  if (extension !== null) {
64432
64433
  if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
64433
64434
  if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
@@ -64442,7 +64443,7 @@ function convertConstant(gl, constantVal, encoding = null) {
64442
64443
  // PVRTC
64443
64444
 
64444
64445
  if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
64445
- const extension = getExtension$1(gl, 'WEBGL_compressed_texture_pvrtc');
64446
+ const extension = getExtension(gl, 'WEBGL_compressed_texture_pvrtc');
64446
64447
  if (extension !== null) {
64447
64448
  if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
64448
64449
  if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
@@ -64456,7 +64457,7 @@ function convertConstant(gl, constantVal, encoding = null) {
64456
64457
  // ETC1
64457
64458
 
64458
64459
  if (p === RGB_ETC1_Format) {
64459
- const extension = getExtension$1(gl, 'WEBGL_compressed_texture_etc1');
64460
+ const extension = getExtension(gl, 'WEBGL_compressed_texture_etc1');
64460
64461
  if (extension !== null) {
64461
64462
  return extension.COMPRESSED_RGB_ETC1_WEBGL;
64462
64463
  } else {
@@ -64467,7 +64468,7 @@ function convertConstant(gl, constantVal, encoding = null) {
64467
64468
  // ETC2
64468
64469
 
64469
64470
  if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
64470
- const extension = getExtension$1(gl, 'WEBGL_compressed_texture_etc');
64471
+ const extension = getExtension(gl, 'WEBGL_compressed_texture_etc');
64471
64472
  if (extension !== null) {
64472
64473
  if (p === RGB_ETC2_Format) return (encoding === sRGBEncoding) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
64473
64474
  if (p === RGBA_ETC2_EAC_Format) return (encoding === sRGBEncoding) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
@@ -64483,7 +64484,7 @@ function convertConstant(gl, constantVal, encoding = null) {
64483
64484
  p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
64484
64485
  p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
64485
64486
  p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format) {
64486
- const extension = getExtension$1(gl, 'WEBGL_compressed_texture_astc');
64487
+ const extension = getExtension(gl, 'WEBGL_compressed_texture_astc');
64487
64488
  if (extension !== null) {
64488
64489
  if (p === RGBA_ASTC_4x4_Format) return (encoding === sRGBEncoding) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
64489
64490
  if (p === RGBA_ASTC_5x4_Format) return (encoding === sRGBEncoding) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
@@ -64507,7 +64508,7 @@ function convertConstant(gl, constantVal, encoding = null) {
64507
64508
  // BPTC
64508
64509
 
64509
64510
  if (p === RGBA_BPTC_Format) {
64510
- const extension = getExtension$1(gl, 'EXT_texture_compression_bptc');
64511
+ const extension = getExtension(gl, 'EXT_texture_compression_bptc');
64511
64512
  if (extension !== null) {
64512
64513
  if (p === RGBA_BPTC_Format) {
64513
64514
  return (encoding === sRGBEncoding) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
@@ -64540,9 +64541,6 @@ function convertConstant(gl, constantVal, encoding = null) {
64540
64541
  if (p === LinearMipMapLinearFilter) {
64541
64542
  return gl.LINEAR_MIPMAP_LINEAR;
64542
64543
  }
64543
- if (p === NearestMipMapLinearFilter) {
64544
- return gl.NEAREST_MIPMAP_LINEAR;
64545
- }
64546
64544
  if (p === NearestFilter) {
64547
64545
  return gl.NEAREST;
64548
64546
  }
@@ -64580,7 +64578,7 @@ class Texture2D {
64580
64578
  this.texture = gl.createTexture();
64581
64579
 
64582
64580
  if (preloadColor) {
64583
- this.setPreloadColor(preloadColor || [0, 0, 0, 1]); // Prevents "there is no texture bound to the unit 0" error
64581
+ this.setPreloadColor(preloadColor); // Prevents "there is no texture bound to the unit 0" error
64584
64582
  }
64585
64583
 
64586
64584
  this.allocated = true;
@@ -64599,9 +64597,6 @@ class Texture2D {
64599
64597
  color$2[3] = Math.floor((value[3] !== undefined ? value[3] : 1) * 255);
64600
64598
  }
64601
64599
  const gl = this.gl;
64602
- const glFormat = convertConstant(gl, this.format, this.encoding);
64603
- const glType = convertConstant(gl, this.type);
64604
- const glInternalFormat = getInternalFormat(gl, this.internalFormat, glFormat, glType, this.encoding, false);
64605
64600
  gl.bindTexture(this.target, this.texture);
64606
64601
  if (this.target === gl.TEXTURE_CUBE_MAP) {
64607
64602
  const faces = [
@@ -64613,10 +64608,10 @@ class Texture2D {
64613
64608
  gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
64614
64609
  ];
64615
64610
  for (let i = 0, len = faces.length; i < len; i++) {
64616
- gl.texImage2D(faces[i], 0, glInternalFormat, 1, 1, 0, glFormat, glType, color$2);
64611
+ gl.texImage2D(faces[i], 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, color$2);
64617
64612
  }
64618
64613
  } else {
64619
- gl.texImage2D(this.target, 0, glInternalFormat, 1, 1, 0, glFormat, glType, color$2);
64614
+ gl.texImage2D(this.target, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, color$2);
64620
64615
  }
64621
64616
  gl.bindTexture(this.target, null);
64622
64617
  }
@@ -64776,44 +64771,38 @@ class Texture2D {
64776
64771
  gl.activeTexture(gl.TEXTURE0 + 0);
64777
64772
  gl.bindTexture(this.target, this.texture);
64778
64773
 
64779
- let generateMipMap = false;
64774
+ let supportsMips = mipmaps.length > 1;
64780
64775
 
64781
64776
  gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, this.flipY);
64782
64777
  gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha);
64783
64778
  gl.pixelStorei(gl.UNPACK_ALIGNMENT, this.unpackAlignment);
64784
64779
  gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE);
64785
64780
 
64786
- {
64787
-
64788
- const minFilter = convertConstant(gl, this.minFilter);
64789
- gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, minFilter);
64790
- if (minFilter === gl.NEAREST_MIPMAP_NEAREST || minFilter === gl.LINEAR_MIPMAP_NEAREST || minFilter === gl.NEAREST_MIPMAP_LINEAR || minFilter === gl.LINEAR_MIPMAP_LINEAR) {
64791
- generateMipMap = true;
64792
- }
64793
-
64794
- const magFilter = convertConstant(gl, this.magFilter);
64795
- if (magFilter) {
64796
- gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, magFilter);
64797
- }
64781
+ const wrapS = convertConstant(gl, this.wrapS);
64782
+ if (wrapS) {
64783
+ gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, wrapS);
64784
+ }
64798
64785
 
64799
- const wrapS = convertConstant(gl, this.wrapS);
64800
- if (wrapS) {
64801
- gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, wrapS);
64802
- }
64786
+ const wrapT = convertConstant(gl, this.wrapT);
64787
+ if (wrapT) {
64788
+ gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, wrapT);
64789
+ }
64803
64790
 
64804
- const wrapT = convertConstant(gl, this.wrapT);
64805
- if (wrapT) {
64806
- gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, wrapT);
64791
+ if (this.type === gl.TEXTURE_3D || this.type === gl.TEXTURE_2D_ARRAY) {
64792
+ const wrapR = convertConstant(gl, this.wrapR);
64793
+ if (wrapR) {
64794
+ gl.texParameteri(this.target, gl.TEXTURE_WRAP_R, wrapR);
64807
64795
  }
64796
+ gl.texParameteri(this.type, gl.TEXTURE_WRAP_R, wrapR);
64797
+ }
64808
64798
 
64809
- if (this.type === gl.TEXTURE_3D || this.type === gl.TEXTURE_2D_ARRAY) {
64810
- const wrapR = convertConstant(gl, this.wrapR);
64811
- if (wrapR) {
64812
- gl.texParameteri(this.target, gl.TEXTURE_WRAP_R, wrapR);
64813
- }
64814
- gl.texParameteri(this.type, gl.TEXTURE_WRAP_R, wrapR);
64815
- }
64799
+ if (supportsMips) {
64800
+ gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, filterFallback(gl, this.minFilter));
64801
+ gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, filterFallback(gl, this.magFilter));
64816
64802
 
64803
+ } else {
64804
+ gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, convertConstant(gl, this.minFilter));
64805
+ gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, convertConstant(gl, this.magFilter));
64817
64806
  }
64818
64807
 
64819
64808
  const glFormat = convertConstant(gl, this.format, this.encoding);
@@ -64833,13 +64822,13 @@ class Texture2D {
64833
64822
  console.warn('Attempt to load unsupported compressed texture format in .setCompressedData()');
64834
64823
  }
64835
64824
  } else {
64836
- gl.texSubImage2D(gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
64825
+ gl.texSubImage2D(gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
64837
64826
  }
64838
64827
  }
64839
64828
 
64840
- if (generateMipMap) {
64841
- gl.generateMipmap(this.target);
64842
- }
64829
+ // if (generateMipMap) {
64830
+ // // gl.generateMipmap(this.target); // Only for roughness textures?
64831
+ // }
64843
64832
 
64844
64833
  gl.bindTexture(this.target, null);
64845
64834
  }
@@ -64966,6 +64955,14 @@ function getInternalFormat(gl, internalFormatName, glFormat, glType, encoding, i
64966
64955
  return internalFormat;
64967
64956
  }
64968
64957
 
64958
+ function filterFallback(gl, f) {
64959
+ if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
64960
+ return gl.NEAREST;
64961
+ }
64962
+ return gl.LINEAR;
64963
+
64964
+ }
64965
+
64969
64966
  /**
64970
64967
  * Instantiated by VBOSceneModel#createTexture
64971
64968
  *
@@ -65886,6 +65883,1059 @@ class SceneModel {
65886
65883
  }
65887
65884
  }
65888
65885
 
65886
+ class LoadingManager {
65887
+
65888
+ constructor(onLoad, onProgress, onError) {
65889
+
65890
+ this.isLoading = false;
65891
+ this.itemsLoaded = 0;
65892
+ this.itemsTotal = 0;
65893
+ this.urlModifier = undefined;
65894
+ this.handlers = [];
65895
+
65896
+ this.onStart = undefined;
65897
+ this.onLoad = onLoad;
65898
+ this.onProgress = onProgress;
65899
+ this.onError = onError;
65900
+ }
65901
+
65902
+ itemStart(url) {
65903
+ this.itemsTotal++;
65904
+ if (this.isLoading === false) {
65905
+ if (this.onStart !== undefined) {
65906
+ this.onStart(url, this.itemsLoaded, this.itemsTotal);
65907
+ }
65908
+ }
65909
+ this.isLoading = true;
65910
+ }
65911
+
65912
+ itemEnd(url) {
65913
+ this.itemsLoaded++;
65914
+ if (this.onProgress !== undefined) {
65915
+ this.onProgress(url, this.itemsLoaded, this.itemsTotal);
65916
+ }
65917
+ if (this.itemsLoaded === this.itemsTotal) {
65918
+ this.isLoading = false;
65919
+ if (this.onLoad !== undefined) {
65920
+ this.onLoad();
65921
+ }
65922
+ }
65923
+ }
65924
+
65925
+ itemError(url) {
65926
+ if (this.onError !== undefined) {
65927
+ this.onError(url);
65928
+ }
65929
+ }
65930
+
65931
+ resolveURL(url) {
65932
+ if (this.urlModifier) {
65933
+ return this.urlModifier(url);
65934
+ }
65935
+ return url;
65936
+ }
65937
+
65938
+ setURLModifier(transform) {
65939
+ this.urlModifier = transform;
65940
+ return this;
65941
+ }
65942
+
65943
+ addHandler(regex, loader) {
65944
+ this.handlers.push(regex, loader);
65945
+ return this;
65946
+ }
65947
+
65948
+ removeHandler(regex) {
65949
+ const index = this.handlers.indexOf(regex);
65950
+ if (index !== -1) {
65951
+ this.handlers.splice(index, 2);
65952
+ }
65953
+ return this;
65954
+ }
65955
+
65956
+ getHandler(file) {
65957
+ for (let i = 0, l = this.handlers.length; i < l; i += 2) {
65958
+ const regex = this.handlers[i];
65959
+ const loader = this.handlers[i + 1];
65960
+ if (regex.global) regex.lastIndex = 0; // see #17920
65961
+ if (regex.test(file)) {
65962
+ return loader;
65963
+ }
65964
+ }
65965
+ return null;
65966
+ }
65967
+ }
65968
+
65969
+ const DefaultLoadingManager = new LoadingManager();
65970
+
65971
+ class Loader {
65972
+
65973
+ constructor(manager) {
65974
+
65975
+ this.manager = (manager !== undefined) ? manager : DefaultLoadingManager;
65976
+
65977
+ this.crossOrigin = 'anonymous';
65978
+ this.withCredentials = false;
65979
+ this.path = '';
65980
+ this.resourcePath = '';
65981
+ this.requestHeader = {};
65982
+ }
65983
+
65984
+ load( /* url, onLoad, onProgress, onError */) {
65985
+ }
65986
+
65987
+ loadAsync(url, onProgress) {
65988
+ const scope = this;
65989
+ return new Promise(function (resolve, reject) {
65990
+ scope.load(url, resolve, onProgress, reject);
65991
+ });
65992
+ }
65993
+
65994
+ parse( /* data */) {
65995
+ }
65996
+
65997
+ setCrossOrigin(crossOrigin) {
65998
+ this.crossOrigin = crossOrigin;
65999
+ return this;
66000
+ }
66001
+
66002
+ setWithCredentials(value) {
66003
+ this.withCredentials = value;
66004
+ return this;
66005
+ }
66006
+
66007
+ setPath(path) {
66008
+ this.path = path;
66009
+ return this;
66010
+ }
66011
+
66012
+ setResourcePath(resourcePath) {
66013
+ this.resourcePath = resourcePath;
66014
+ return this;
66015
+ }
66016
+
66017
+ setRequestHeader(requestHeader) {
66018
+ this.requestHeader = requestHeader;
66019
+ return this;
66020
+ }
66021
+ }
66022
+
66023
+ /**
66024
+ * @author Deepkolos / https://github.com/deepkolos
66025
+ */
66026
+
66027
+ class WorkerPool$1 {
66028
+
66029
+ constructor(pool = 4) {
66030
+ this.pool = pool;
66031
+ this.queue = [];
66032
+ this.workers = [];
66033
+ this.workersResolve = [];
66034
+ this.workerStatus = 0;
66035
+ }
66036
+
66037
+ _initWorker(workerId) {
66038
+ if (!this.workers[workerId]) {
66039
+ const worker = this.workerCreator();
66040
+ worker.addEventListener('message', this._onMessage.bind(this, workerId));
66041
+ this.workers[workerId] = worker;
66042
+ }
66043
+ }
66044
+
66045
+ _getIdleWorker() {
66046
+ for (let i = 0; i < this.pool; i++)
66047
+ if (!(this.workerStatus & (1 << i))) return i;
66048
+ return -1;
66049
+ }
66050
+
66051
+ _onMessage(workerId, msg) {
66052
+ const resolve = this.workersResolve[workerId];
66053
+ resolve && resolve(msg);
66054
+ if (this.queue.length) {
66055
+ const {resolve, msg, transfer} = this.queue.shift();
66056
+ this.workersResolve[workerId] = resolve;
66057
+ this.workers[workerId].postMessage(msg, transfer);
66058
+ } else {
66059
+ this.workerStatus ^= 1 << workerId;
66060
+ }
66061
+ }
66062
+
66063
+ setWorkerCreator(workerCreator) {
66064
+ this.workerCreator = workerCreator;
66065
+ }
66066
+
66067
+ setWorkerLimit(pool) {
66068
+ this.pool = pool;
66069
+ }
66070
+
66071
+ postMessage(msg, transfer) {
66072
+ return new Promise((resolve) => {
66073
+ const workerId = this._getIdleWorker();
66074
+ if (workerId !== -1) {
66075
+ this._initWorker(workerId);
66076
+ this.workerStatus |= 1 << workerId;
66077
+ this.workersResolve[workerId] = resolve;
66078
+ this.workers[workerId].postMessage(msg, transfer);
66079
+ } else {
66080
+ this.queue.push({resolve, msg, transfer});
66081
+ }
66082
+ });
66083
+ }
66084
+
66085
+ destroy() {
66086
+
66087
+ this.workers.forEach((worker) => worker.terminate());
66088
+ this.workersResolve.length = 0;
66089
+ this.workers.length = 0;
66090
+ this.queue.length = 0;
66091
+ this.workerStatus = 0;
66092
+
66093
+ }
66094
+
66095
+ }
66096
+
66097
+ /**
66098
+ * Transcodes texture data.
66099
+ *
66100
+ * A {@link SceneModel} configured with an appropriate TextureTranscoder will allow us to add textures from
66101
+ * transcoded buffers or files. For a concrete example, see {@link VBOSceneModel}, which can be configured with
66102
+ * a {@link KTX2TextureTranscoder}, which allows us to add textures from KTX2 buffers and files.
66103
+ *
66104
+ * @interface
66105
+ */
66106
+ class TextureTranscoder {
66107
+
66108
+ /**
66109
+ * Transcodes texture data from transcoded buffers into a {@link Texture2D}.
66110
+ *
66111
+ * @param {ArrayBuffer[]} buffers Transcoded texture data. Given as an array of buffers so that we can support
66112
+ * multi-image textures, such as cube maps.
66113
+ * @param {*} config Transcoding options.
66114
+ * @param {Texture2D} texture The texture to load.
66115
+ * @returns {Promise} Resolves when the texture has loaded.
66116
+ */
66117
+ transcode(buffers, texture, config = {}) {
66118
+ }
66119
+
66120
+ /**
66121
+ * Destroys this transcoder.
66122
+ */
66123
+ destroy() {
66124
+ }
66125
+ }
66126
+
66127
+ const Cache = {
66128
+
66129
+ enabled: false,
66130
+ files: {},
66131
+
66132
+ add: function (key, file) {
66133
+ if (this.enabled === false) {
66134
+ return;
66135
+ }
66136
+ this.files[key] = file;
66137
+ },
66138
+
66139
+ get: function (key) {
66140
+ if (this.enabled === false) {
66141
+ return;
66142
+ }
66143
+ return this.files[key];
66144
+ },
66145
+
66146
+ remove: function (key) {
66147
+ delete this.files[key];
66148
+ },
66149
+
66150
+ clear: function () {
66151
+ this.files = {};
66152
+ }
66153
+ };
66154
+
66155
+ const loading = {};
66156
+
66157
+ class FileLoader extends Loader {
66158
+
66159
+ constructor(manager) {
66160
+ super(manager);
66161
+ }
66162
+
66163
+ load(url, onLoad, onProgress, onError) {
66164
+ if (url === undefined) {
66165
+ url = '';
66166
+ }
66167
+ if (this.path !== undefined) {
66168
+ url = this.path + url;
66169
+ }
66170
+ url = this.manager.resolveURL(url);
66171
+ const cached = Cache.get(url);
66172
+ if (cached !== undefined) {
66173
+ this.manager.itemStart(url);
66174
+ setTimeout(() => {
66175
+ if (onLoad) {
66176
+ onLoad(cached);
66177
+ }
66178
+ this.manager.itemEnd(url);
66179
+ }, 0);
66180
+ return cached;
66181
+ }
66182
+ if (loading[url] !== undefined) {
66183
+ loading[url].push({onLoad, onProgress, onError});
66184
+ return;
66185
+ }
66186
+ loading[url] = [];
66187
+ loading[url].push({onLoad, onProgress, onError});
66188
+ const req = new Request(url, {
66189
+ headers: new Headers(this.requestHeader),
66190
+ credentials: this.withCredentials ? 'include' : 'same-origin'
66191
+ });
66192
+ const mimeType = this.mimeType;
66193
+ const responseType = this.responseType;
66194
+ fetch(req).then(response => {
66195
+ if (response.status === 200 || response.status === 0) {
66196
+ // Some browsers return HTTP Status 0 when using non-http protocol
66197
+ // e.g. 'file://' or 'data://'. Handle as success.
66198
+ if (response.status === 0) {
66199
+ console.warn('FileLoader: HTTP Status 0 received.');
66200
+ }
66201
+ if (typeof ReadableStream === 'undefined' || response.body.getReader === undefined) {
66202
+ return response;
66203
+ }
66204
+ const callbacks = loading[url];
66205
+ const reader = response.body.getReader();
66206
+ const contentLength = response.headers.get('Content-Length');
66207
+ const total = contentLength ? parseInt(contentLength) : 0;
66208
+ const lengthComputable = total !== 0;
66209
+ let loaded = 0;
66210
+ const stream = new ReadableStream({
66211
+ start(controller) {
66212
+ readData();
66213
+
66214
+ function readData() {
66215
+ reader.read().then(({done, value}) => {
66216
+ if (done) {
66217
+ controller.close();
66218
+ } else {
66219
+ loaded += value.byteLength;
66220
+ const event = new ProgressEvent('progress', {lengthComputable, loaded, total});
66221
+ for (let i = 0, il = callbacks.length; i < il; i++) {
66222
+ const callback = callbacks[i];
66223
+ if (callback.onProgress) {
66224
+ callback.onProgress(event);
66225
+ }
66226
+ }
66227
+ controller.enqueue(value);
66228
+ readData();
66229
+ }
66230
+ });
66231
+ }
66232
+ }
66233
+ });
66234
+ return new Response(stream);
66235
+ } else {
66236
+ throw Error(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`);
66237
+ }
66238
+ }).then(response => {
66239
+ switch (responseType) {
66240
+ case 'arraybuffer':
66241
+ return response.arrayBuffer();
66242
+ case 'blob':
66243
+ return response.blob();
66244
+ case 'document':
66245
+ return response.text()
66246
+ .then(text => {
66247
+ const parser = new DOMParser();
66248
+ return parser.parseFromString(text, mimeType);
66249
+ });
66250
+ case 'json':
66251
+ return response.json();
66252
+ default:
66253
+ if (mimeType === undefined) {
66254
+ return response.text();
66255
+ } else {
66256
+ // sniff encoding
66257
+ const re = /charset="?([^;"\s]*)"?/i;
66258
+ const exec = re.exec(mimeType);
66259
+ const label = exec && exec[1] ? exec[1].toLowerCase() : undefined;
66260
+ const decoder = new TextDecoder(label);
66261
+ return response.arrayBuffer().then(ab => decoder.decode(ab));
66262
+ }
66263
+ }
66264
+ }).then(data => {
66265
+ // Add to cache only on HTTP success, so that we do not cache
66266
+ // error response bodies as proper responses to requests.
66267
+ Cache.add(url, data);
66268
+ const callbacks = loading[url];
66269
+ delete loading[url];
66270
+ for (let i = 0, il = callbacks.length; i < il; i++) {
66271
+ const callback = callbacks[i];
66272
+ if (callback.onLoad) {
66273
+ callback.onLoad(data);
66274
+ }
66275
+ }
66276
+ }).catch(err => {
66277
+ // Abort errors and other errors are handled the same
66278
+ const callbacks = loading[url];
66279
+ if (callbacks === undefined) {
66280
+ // When onLoad was called and url was deleted in `loading`
66281
+ this.manager.itemError(url);
66282
+ throw err;
66283
+
66284
+ }
66285
+ delete loading[url];
66286
+ for (let i = 0, il = callbacks.length; i < il; i++) {
66287
+ const callback = callbacks[i];
66288
+ if (callback.onError) {
66289
+ callback.onError(err);
66290
+ }
66291
+ }
66292
+ this.manager.itemError(url);
66293
+ }).finally(() => {
66294
+ this.manager.itemEnd(url);
66295
+ });
66296
+ this.manager.itemStart(url);
66297
+ }
66298
+
66299
+ setResponseType(value) {
66300
+ this.responseType = value;
66301
+ return this;
66302
+ }
66303
+
66304
+ setMimeType(value) {
66305
+ this.mimeType = value;
66306
+ return this;
66307
+ }
66308
+ }
66309
+
66310
+ const KTX2TransferSRGB = 2;
66311
+ const KTX2_ALPHA_PREMULTIPLIED = 1;
66312
+
66313
+ let activeTranscoders = 0;
66314
+
66315
+ /**
66316
+ * Transcodes texture data from KTX2.
66317
+ *
66318
+ * ## Overview
66319
+ *
66320
+ * * Uses the [Basis Universal GPU Texture Codec](https://github.com/BinomialLLC/basis_universal) to
66321
+ * transcode [KTX2](https://github.khronos.org/KTX-Specification/) textures.
66322
+ * * {@link XKTLoaderPlugin} uses a KTX2TextureTranscoder to load textures in XKT files.
66323
+ * * {@link VBOSceneModel} uses a KTX2TextureTranscoder to enable us to add KTX2-encoded textures.
66324
+ * * Loads the Basis Codec from [CDN](https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/) by default, but can
66325
+ * also be configured to load the Codec from local files.
66326
+ * * We also bundle the Basis Codec with the xeokit-sdk npm package, and in the [repository](https://github.com/xeokit/xeokit-sdk/tree/master/dist/basis).
66327
+ *
66328
+ * ## What is KTX2?
66329
+ *
66330
+ * A [KTX2](https://github.khronos.org/KTX-Specification/) file stores GPU texture data in the Khronos Texture 2.0 (KTX2) container format. It contains image data for
66331
+ * a texture asset compressed with Basis Universal (BasisU) supercompression that can be transcoded to different formats
66332
+ * depending on the support provided by the target devices. KTX2 provides a lightweight format for distributing texture
66333
+ * assets to GPUs. Due to BasisU compression, KTX2 files can store any image format supported by GPUs.
66334
+ *
66335
+ * ## Loading XKT files containing KTX2 textures
66336
+ *
66337
+ * {@link XKTLoaderPlugin} uses a KTX2TextureTranscoder to load textures in XKT files. An XKTLoaderPlugin has its own
66338
+ * default KTX2TextureTranscoder, configured to load the Basis Codec from the [CDN](https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/). If we wish, we can override that with our own
66339
+ * KTX2TextureTranscoder, configured to load the Codec locally.
66340
+ *
66341
+ * In the example below, we'll create a {@link Viewer} and add an {@link XKTLoaderPlugin}
66342
+ * configured with a KTX2TextureTranscoder. Then we'll use the XKTLoaderPlugin to load an
66343
+ * XKT file that contains KTX2 textures, which the plugin will transcode using
66344
+ * its KTX2TextureTranscoder.
66345
+ *
66346
+ * We'll configure our KTX2TextureTranscoder to load the Basis Codec from a local directory. If we were happy with loading the
66347
+ * Codec from our [CDN](https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/) (ie. our app will always have an Internet connection) then we could just leave out the
66348
+ * KTX2TextureTranscoder altogether, and let the XKTLoaderPlugin use its internal default KTX2TextureTranscoder, which is configured to
66349
+ * load the Codec from the CDN. We'll stick with loading our own Codec, in case we want to run our app without an Internet connection.
66350
+ *
66351
+ * <a href="https://xeokit.github.io/xeokit-sdk/examples/#loading_XKT_Textures_HousePlan"><img src="https://xeokit.github.io/xeokit-sdk/assets/images/xktWithTextures.png"></a>
66352
+ *
66353
+ * * [[Run this example](https://xeokit.github.io/xeokit-sdk/examples/#loading_XKT_Textures_HousePlan)]
66354
+ *
66355
+ * ````javascript
66356
+ * const viewer = new Viewer({
66357
+ * canvasId: "myCanvas",
66358
+ * transparent: true
66359
+ * });
66360
+ *
66361
+ * viewer.camera.eye = [-2.56, 8.38, 8.27];
66362
+ * viewer.camera.look = [13.44, 3.31, -14.83];
66363
+ * viewer.camera.up = [0.10, 0.98, -0.14];
66364
+ *
66365
+ * const textureTranscoder = new KTX2TextureTranscoder({
66366
+ * viewer,
66367
+ * transcoderPath: "./../dist/basis/" // <------ Path to Basis Universal transcoder
66368
+ * });
66369
+ *
66370
+ * const xktLoader = new XKTLoaderPlugin(viewer, {
66371
+ * textureTranscoder // <<------------- Transcodes KTX2 textures in XKT files
66372
+ * });
66373
+ *
66374
+ * const sceneModel = xktLoader.load({
66375
+ * id: "myModel",
66376
+ * src: "./HousePlan.xkt" // <<------ XKT file with KTX2 textures
66377
+ * });
66378
+ * ````
66379
+ *
66380
+ * ## Loading KTX2 files into a VBOSceneModel
66381
+ *
66382
+ * A {@link SceneModel} that is configured with a KTX2TextureTranscoder will
66383
+ * allow us to load textures into it from KTX2-transcoded buffers or files.
66384
+ *
66385
+ * In the example below, we'll create a {@link Viewer}, containing a {@link VBOSceneModel} configured with a
66386
+ * KTX2TextureTranscoder.
66387
+ *
66388
+ * We'll then programmatically create a simple object within the VBOSceneModel, consisting of
66389
+ * a single box mesh with a texture loaded from a KTX2 file, which our VBOSceneModel internally transcodes, using
66390
+ * its KTX2TextureTranscoder.
66391
+ *
66392
+ * As in the previous example, we'll configure our KTX2TextureTranscoder to load the Basis Codec from a local directory.
66393
+ *
66394
+ * * [Run a similar example](http://localhost:8080/examples/sceneRepresentation_VBOSceneModel_batching_textures_ktx2.html)
66395
+ *
66396
+ * ````javascript
66397
+ * const viewer = new Viewer({
66398
+ * canvasId: "myCanvas",
66399
+ * transparent: true
66400
+ * });
66401
+ *
66402
+ * viewer.scene.camera.eye = [-21.80, 4.01, 6.56];
66403
+ * viewer.scene.camera.look = [0, -5.75, 0];
66404
+ * viewer.scene.camera.up = [0.37, 0.91, -0.11];
66405
+ *
66406
+ * const textureTranscoder = new KTX2TextureTranscoder({
66407
+ * viewer,
66408
+ * transcoderPath: "./../dist/basis/" // <------ Path to BasisU transcoder module
66409
+ * });
66410
+ *
66411
+ * const vboSceneModel = new VBOSceneModel(viewer.scene, {
66412
+ * id: "myModel",
66413
+ * textureTranscoder // <<-------------------- Configure model with our transcoder
66414
+ * });
66415
+ *
66416
+ * vboSceneModel.createTexture({
66417
+ * id: "myColorTexture",
66418
+ * src: "../assets/textures/compressed/sample_uastc_zstd.ktx2" // <<----- KTX2 texture asset
66419
+ * });
66420
+ *
66421
+ * vboSceneModel.createTexture({
66422
+ * id: "myMetallicRoughnessTexture",
66423
+ * src: "../assets/textures/alpha/crosshatchAlphaMap.jpg" // <<----- JPEG texture asset
66424
+ * });
66425
+ *
66426
+ * vboSceneModel.createTextureSet({
66427
+ * id: "myTextureSet",
66428
+ * colorTextureId: "myColorTexture",
66429
+ * metallicRoughnessTextureId: "myMetallicRoughnessTexture"
66430
+ * });
66431
+ *
66432
+ * vboSceneModel.createMesh({
66433
+ * id: "myMesh",
66434
+ * textureSetId: "myTextureSet",
66435
+ * primitive: "triangles",
66436
+ * positions: [1, 1, 1, ...],
66437
+ * normals: [0, 0, 1, 0, ...],
66438
+ * uv: [1, 0, 0, ...],
66439
+ * indices: [0, 1, 2, ...],
66440
+ * });
66441
+ *
66442
+ * vboSceneModel.createEntity({
66443
+ * id: "myEntity",
66444
+ * meshIds: ["myMesh"]
66445
+ * });
66446
+ *
66447
+ * vboSceneModel.finalize();
66448
+ * ````
66449
+ *
66450
+ * ## Loading KTX2 ArrayBuffers into a VBOSceneModel
66451
+ *
66452
+ * A {@link SceneModel} that is configured with a KTX2TextureTranscoder will also allow us to load textures into
66453
+ * it from KTX2 ArrayBuffers.
66454
+ *
66455
+ * In the example below, we'll create a {@link Viewer}, containing a {@link VBOSceneModel} configured with a
66456
+ * KTX2TextureTranscoder.
66457
+ *
66458
+ * We'll then programmatically create a simple object within the VBOSceneModel, consisting of
66459
+ * a single mesh with a texture loaded from a KTX2 ArrayBuffer, which our VBOSceneModel internally transcodes, using
66460
+ * its KTX2TextureTranscoder.
66461
+ *
66462
+ * ````javascript
66463
+ * const viewer = new Viewer({
66464
+ * canvasId: "myCanvas",
66465
+ * transparent: true
66466
+ * });
66467
+ *
66468
+ * viewer.scene.camera.eye = [-21.80, 4.01, 6.56];
66469
+ * viewer.scene.camera.look = [0, -5.75, 0];
66470
+ * viewer.scene.camera.up = [0.37, 0.91, -0.11];
66471
+ *
66472
+ * const textureTranscoder = new KTX2TextureTranscoder({
66473
+ * viewer,
66474
+ * transcoderPath: "./../dist/basis/" // <------ Path to BasisU transcoder module
66475
+ * });
66476
+ *
66477
+ * const vboSceneModel = new VBOSceneModel(viewer.scene, {
66478
+ * id: "myModel",
66479
+ * textureTranscoder // <<-------------------- Configure model with our transcoder
66480
+ * });
66481
+ *
66482
+ * utils.loadArraybuffer("../assets/textures/compressed/sample_uastc_zstd.ktx2",(arrayBuffer) => {
66483
+ *
66484
+ * vboSceneModel.createTexture({
66485
+ * id: "myColorTexture",
66486
+ * buffers: [arrayBuffer] // <<----- KTX2 texture asset
66487
+ * });
66488
+ *
66489
+ * vboSceneModel.createTexture({
66490
+ * id: "myMetallicRoughnessTexture",
66491
+ * src: "../assets/textures/alpha/crosshatchAlphaMap.jpg" // <<----- JPEG texture asset
66492
+ * });
66493
+ *
66494
+ * vboSceneModel.createTextureSet({
66495
+ * id: "myTextureSet",
66496
+ * colorTextureId: "myColorTexture",
66497
+ * metallicRoughnessTextureId: "myMetallicRoughnessTexture"
66498
+ * });
66499
+ *
66500
+ * vboSceneModel.createMesh({
66501
+ * id: "myMesh",
66502
+ * textureSetId: "myTextureSet",
66503
+ * primitive: "triangles",
66504
+ * positions: [1, 1, 1, ...],
66505
+ * normals: [0, 0, 1, 0, ...],
66506
+ * uv: [1, 0, 0, ...],
66507
+ * indices: [0, 1, 2, ...],
66508
+ * });
66509
+ *
66510
+ * vboSceneModel.createEntity({
66511
+ * id: "myEntity",
66512
+ * meshIds: ["myMesh"]
66513
+ * });
66514
+ *
66515
+ * vboSceneModel.finalize();
66516
+ * });
66517
+ * ````
66518
+ *
66519
+ * @implements {TextureTranscoder}
66520
+ */
66521
+ class KTX2TextureTranscoder {
66522
+
66523
+ /**
66524
+ * Creates a new KTX2TextureTranscoder.
66525
+ *
66526
+ * @param {Viewer} viewer The Viewer that our KTX2TextureTranscoder will be used with. This KTX2TextureTranscoder
66527
+ * must only be used to transcode textures for this Viewer. This is because the Viewer's capabilities will decide
66528
+ * what target GPU formats this KTX2TextureTranscoder will transcode to.
66529
+ * @param {String} [transcoderPath="https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/"] Path to the Basis
66530
+ * transcoder module that internally does the heavy lifting for our KTX2TextureTranscoder. If we omit this configuration,
66531
+ * then our KTX2TextureTranscoder will load it from ````https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/```` by
66532
+ * default. Therefore, make sure your application is connected to the internet if you wish to use the default transcoder path.
66533
+ * @param {Number} [workerLimit] The maximum number of Workers to use for transcoding.
66534
+ */
66535
+ constructor({viewer, transcoderPath, workerLimit}) {
66536
+
66537
+ this._transcoderPath = transcoderPath || "https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/";
66538
+ this._transcoderBinary = null;
66539
+ this._transcoderPending = null;
66540
+ this._workerPool = new WorkerPool$1();
66541
+ this._workerSourceURL = '';
66542
+
66543
+ if (workerLimit) {
66544
+ this._workerPool.setWorkerLimit(workerLimit);
66545
+ }
66546
+
66547
+ const viewerCapabilities = viewer.capabilities;
66548
+
66549
+ this._workerConfig = {
66550
+ astcSupported: viewerCapabilities.astcSupported,
66551
+ etc1Supported: viewerCapabilities.etc1Supported,
66552
+ etc2Supported: viewerCapabilities.etc2Supported,
66553
+ dxtSupported: viewerCapabilities.dxtSupported,
66554
+ bptcSupported: viewerCapabilities.bptcSupported,
66555
+ pvrtcSupported: viewerCapabilities.pvrtcSupported
66556
+ };
66557
+
66558
+ this._supportedFileTypes = ["xkt2"];
66559
+ }
66560
+
66561
+ _init() {
66562
+ if (!this._transcoderPending) {
66563
+ const jsLoader = new FileLoader();
66564
+ jsLoader.setPath(this._transcoderPath);
66565
+ jsLoader.setWithCredentials(this.withCredentials);
66566
+ const jsContent = jsLoader.loadAsync('basis_transcoder.js');
66567
+ const binaryLoader = new FileLoader();
66568
+ binaryLoader.setPath(this._transcoderPath);
66569
+ binaryLoader.setResponseType('arraybuffer');
66570
+ binaryLoader.setWithCredentials(this.withCredentials);
66571
+ const binaryContent = binaryLoader.loadAsync('basis_transcoder.wasm');
66572
+ this._transcoderPending = Promise.all([jsContent, binaryContent])
66573
+ .then(([jsContent, binaryContent]) => {
66574
+ const fn = KTX2TextureTranscoder.BasisWorker.toString();
66575
+ const body = [
66576
+ '/* constants */',
66577
+ 'let _EngineFormat = ' + JSON.stringify(KTX2TextureTranscoder.EngineFormat),
66578
+ 'let _TranscoderFormat = ' + JSON.stringify(KTX2TextureTranscoder.TranscoderFormat),
66579
+ 'let _BasisFormat = ' + JSON.stringify(KTX2TextureTranscoder.BasisFormat),
66580
+ '/* basis_transcoder.js */',
66581
+ jsContent,
66582
+ '/* worker */',
66583
+ fn.substring(fn.indexOf('{') + 1, fn.lastIndexOf('}'))
66584
+ ].join('\n');
66585
+ this._workerSourceURL = URL.createObjectURL(new Blob([body]));
66586
+ this._transcoderBinary = binaryContent;
66587
+ this._workerPool.setWorkerCreator(() => {
66588
+ const worker = new Worker(this._workerSourceURL);
66589
+ const transcoderBinary = this._transcoderBinary.slice(0);
66590
+ worker.postMessage({
66591
+ type: 'init',
66592
+ config: this._workerConfig,
66593
+ transcoderBinary
66594
+ }, [transcoderBinary]);
66595
+ return worker;
66596
+ });
66597
+ });
66598
+ if (activeTranscoders > 0) {
66599
+ console.warn('KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues.' + ' Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances.');
66600
+ }
66601
+ activeTranscoders++;
66602
+ }
66603
+ return this._transcoderPending;
66604
+ }
66605
+
66606
+ /**
66607
+ * Transcodes texture data from transcoded buffers into a {@link Texture2D}.
66608
+ *
66609
+ * @param {ArrayBuffer[]} buffers Transcoded texture data. Given as an array of buffers so that we can support multi-image textures, such as cube maps.
66610
+ * @param {*} config Transcoding options.
66611
+ * @param {Texture2D} texture The texture to load.
66612
+ * @returns {Promise} Resolves when the texture has loaded.
66613
+ */
66614
+ transcode(buffers, texture, config = {}) {
66615
+ return new Promise((resolve, reject) => {
66616
+ const taskConfig = config;
66617
+ this._init().then(() => {
66618
+ return this._workerPool.postMessage({
66619
+ type: 'transcode',
66620
+ buffers,
66621
+ taskConfig: taskConfig
66622
+ }, buffers);
66623
+ }).then((e) => {
66624
+ const transcodeResult = e.data;
66625
+ const {mipmaps, width, height, format, type, error, dfdTransferFn, dfdFlags} = transcodeResult;
66626
+ if (type === 'error') {
66627
+ return reject(error);
66628
+ }
66629
+ texture.setCompressedData({
66630
+ mipmaps,
66631
+ props: {
66632
+ format: format,
66633
+ minFilter: mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter,
66634
+ magFilter: mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter,
66635
+ encoding: dfdTransferFn === KTX2TransferSRGB ? sRGBEncoding : LinearEncoding,
66636
+ premultiplyAlpha: !!(dfdFlags & KTX2_ALPHA_PREMULTIPLIED)
66637
+ }
66638
+ });
66639
+ resolve();
66640
+ });
66641
+ });
66642
+ }
66643
+
66644
+ /**
66645
+ * Destroys this KTX2TextureTranscoder
66646
+ */
66647
+ destroy() {
66648
+ URL.revokeObjectURL(this._workerSourceURL);
66649
+ this._workerPool.destroy();
66650
+ activeTranscoders--;
66651
+ }
66652
+ }
66653
+
66654
+ /**
66655
+ * @private
66656
+ */
66657
+ KTX2TextureTranscoder.BasisFormat = {
66658
+ ETC1S: 0,
66659
+ UASTC_4x4: 1
66660
+ };
66661
+
66662
+ /**
66663
+ * @private
66664
+ */
66665
+ KTX2TextureTranscoder.TranscoderFormat = {
66666
+ ETC1: 0,
66667
+ ETC2: 1,
66668
+ BC1: 2,
66669
+ BC3: 3,
66670
+ BC4: 4,
66671
+ BC5: 5,
66672
+ BC7_M6_OPAQUE_ONLY: 6,
66673
+ BC7_M5: 7,
66674
+ PVRTC1_4_RGB: 8,
66675
+ PVRTC1_4_RGBA: 9,
66676
+ ASTC_4x4: 10,
66677
+ ATC_RGB: 11,
66678
+ ATC_RGBA_INTERPOLATED_ALPHA: 12,
66679
+ RGBA32: 13,
66680
+ RGB565: 14,
66681
+ BGR565: 15,
66682
+ RGBA4444: 16
66683
+ };
66684
+
66685
+ /**
66686
+ * @private
66687
+ */
66688
+ KTX2TextureTranscoder.EngineFormat = {
66689
+ RGBAFormat: RGBAFormat,
66690
+ RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format,
66691
+ RGBA_BPTC_Format: RGBA_BPTC_Format,
66692
+ RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format,
66693
+ RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format,
66694
+ RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format,
66695
+ RGB_ETC1_Format: RGB_ETC1_Format,
66696
+ RGB_ETC2_Format: RGB_ETC2_Format,
66697
+ RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format,
66698
+ RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format
66699
+ };
66700
+
66701
+ /* WEB WORKER */
66702
+
66703
+ /**
66704
+ * @private
66705
+ * @constructor
66706
+ */
66707
+ KTX2TextureTranscoder.BasisWorker = function () {
66708
+
66709
+ let config;
66710
+ let transcoderPending;
66711
+ let BasisModule;
66712
+
66713
+ const EngineFormat = _EngineFormat; // eslint-disable-line no-undef
66714
+ const TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef
66715
+ const BasisFormat = _BasisFormat; // eslint-disable-line no-undef
66716
+
66717
+ self.addEventListener('message', function (e) {
66718
+ const message = e.data;
66719
+ switch (message.type) {
66720
+ case 'init':
66721
+ config = message.config;
66722
+ init(message.transcoderBinary);
66723
+ break;
66724
+ case 'transcode':
66725
+ transcoderPending.then(() => {
66726
+ try {
66727
+ const {
66728
+ width,
66729
+ height,
66730
+ hasAlpha,
66731
+ mipmaps,
66732
+ format,
66733
+ dfdTransferFn,
66734
+ dfdFlags
66735
+ } = transcode(message.buffers[0]);
66736
+ const buffers = [];
66737
+ for (let i = 0; i < mipmaps.length; ++i) {
66738
+ buffers.push(mipmaps[i].data.buffer);
66739
+ }
66740
+ self.postMessage({
66741
+ type: 'transcode',
66742
+ id: message.id,
66743
+ width,
66744
+ height,
66745
+ hasAlpha,
66746
+ mipmaps,
66747
+ format,
66748
+ dfdTransferFn,
66749
+ dfdFlags
66750
+ }, buffers);
66751
+ } catch (error) {
66752
+ console.error(`[KTX2TextureTranscoder.BasisWorker]: ${error}`);
66753
+ self.postMessage({type: 'error', id: message.id, error: error.message});
66754
+ }
66755
+ });
66756
+ break;
66757
+ }
66758
+ });
66759
+
66760
+ function init(wasmBinary) {
66761
+ transcoderPending = new Promise(resolve => {
66762
+ BasisModule = {
66763
+ wasmBinary,
66764
+ onRuntimeInitialized: resolve
66765
+ };
66766
+ BASIS(BasisModule); // eslint-disable-line no-undef
66767
+ }).then(() => {
66768
+ BasisModule.initializeBasis();
66769
+ if (BasisModule.KTX2File === undefined) {
66770
+ console.warn('KTX2TextureTranscoder: Please update Basis Universal transcoder.');
66771
+ }
66772
+ });
66773
+ }
66774
+
66775
+ function transcode(buffer) {
66776
+ const ktx2File = new BasisModule.KTX2File(new Uint8Array(buffer));
66777
+
66778
+ function cleanup() {
66779
+ ktx2File.close();
66780
+ ktx2File.delete();
66781
+ }
66782
+
66783
+ if (!ktx2File.isValid()) {
66784
+ cleanup();
66785
+ throw new Error('KTX2TextureTranscoder: Invalid or unsupported .ktx2 file');
66786
+ }
66787
+ const basisFormat = ktx2File.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S;
66788
+ const width = ktx2File.getWidth();
66789
+ const height = ktx2File.getHeight();
66790
+ const levels = ktx2File.getLevels();
66791
+ const hasAlpha = ktx2File.getHasAlpha();
66792
+ const dfdTransferFn = ktx2File.getDFDTransferFunc();
66793
+ const dfdFlags = ktx2File.getDFDFlags();
66794
+ const {transcoderFormat, engineFormat} = getTranscoderFormat(basisFormat, width, height, hasAlpha);
66795
+ if (!width || !height || !levels) {
66796
+ cleanup();
66797
+ throw new Error('KTX2TextureTranscoder: Invalid texture');
66798
+ }
66799
+ if (!ktx2File.startTranscoding()) {
66800
+ cleanup();
66801
+ throw new Error('KTX2TextureTranscoder: .startTranscoding failed');
66802
+ }
66803
+ const mipmaps = [];
66804
+ for (let mip = 0; mip < levels; mip++) {
66805
+ const levelInfo = ktx2File.getImageLevelInfo(mip, 0, 0);
66806
+ const mipWidth = levelInfo.origWidth;
66807
+ const mipHeight = levelInfo.origHeight;
66808
+ const dst = new Uint8Array(ktx2File.getImageTranscodedSizeInBytes(mip, 0, 0, transcoderFormat));
66809
+ const status = ktx2File.transcodeImage(dst, mip, 0, 0, transcoderFormat, 0, -1, -1);
66810
+ if (!status) {
66811
+ cleanup();
66812
+ throw new Error('KTX2TextureTranscoder: .transcodeImage failed.');
66813
+ }
66814
+ mipmaps.push({data: dst, width: mipWidth, height: mipHeight});
66815
+ }
66816
+ cleanup();
66817
+ return {width, height, hasAlpha, mipmaps, format: engineFormat, dfdTransferFn, dfdFlags};
66818
+ }
66819
+
66820
+ // Optimal choice of a transcoder target format depends on the Basis format (ETC1S or UASTC),
66821
+ // device capabilities, and texture dimensions. The list below ranks the formats separately
66822
+ // for ETC1S and UASTC.
66823
+ //
66824
+ // In some cases, transcoding UASTC to RGBA32 might be preferred for higher quality (at
66825
+ // significant memory cost) compared to ETC1/2, BC1/3, and PVRTC. The transcoder currently
66826
+ // chooses RGBA32 only as a last resort and does not expose that option to the caller.
66827
+
66828
+ const FORMAT_OPTIONS = [{
66829
+ if: 'astcSupported',
66830
+ basisFormat: [BasisFormat.UASTC_4x4],
66831
+ transcoderFormat: [TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4],
66832
+ engineFormat: [EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format],
66833
+ priorityETC1S: Infinity,
66834
+ priorityUASTC: 1,
66835
+ needsPowerOfTwo: false
66836
+ }, {
66837
+ if: 'bptcSupported',
66838
+ basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4],
66839
+ transcoderFormat: [TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5],
66840
+ engineFormat: [EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format],
66841
+ priorityETC1S: 3,
66842
+ priorityUASTC: 2,
66843
+ needsPowerOfTwo: false
66844
+ }, {
66845
+ if: 'dxtSupported',
66846
+ basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4],
66847
+ transcoderFormat: [TranscoderFormat.BC1, TranscoderFormat.BC3],
66848
+ engineFormat: [EngineFormat.RGB_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format],
66849
+ priorityETC1S: 4,
66850
+ priorityUASTC: 5,
66851
+ needsPowerOfTwo: false
66852
+ }, {
66853
+ if: 'etc2Supported',
66854
+ basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4],
66855
+ transcoderFormat: [TranscoderFormat.ETC1, TranscoderFormat.ETC2],
66856
+ engineFormat: [EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format],
66857
+ priorityETC1S: 1,
66858
+ priorityUASTC: 3,
66859
+ needsPowerOfTwo: false
66860
+ }, {
66861
+ if: 'etc1Supported',
66862
+ basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4],
66863
+ transcoderFormat: [TranscoderFormat.ETC1],
66864
+ engineFormat: [EngineFormat.RGB_ETC1_Format],
66865
+ priorityETC1S: 2,
66866
+ priorityUASTC: 4,
66867
+ needsPowerOfTwo: false
66868
+ }, {
66869
+ if: 'pvrtcSupported',
66870
+ basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4],
66871
+ transcoderFormat: [TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA],
66872
+ engineFormat: [EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format],
66873
+ priorityETC1S: 5,
66874
+ priorityUASTC: 6,
66875
+ needsPowerOfTwo: true
66876
+ }];
66877
+ const ETC1S_OPTIONS = FORMAT_OPTIONS.sort(function (a, b) {
66878
+ return a.priorityETC1S - b.priorityETC1S;
66879
+ });
66880
+ const UASTC_OPTIONS = FORMAT_OPTIONS.sort(function (a, b) {
66881
+ return a.priorityUASTC - b.priorityUASTC;
66882
+ });
66883
+
66884
+ function getTranscoderFormat(basisFormat, width, height, hasAlpha) {
66885
+ let transcoderFormat;
66886
+ let engineFormat;
66887
+ const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS;
66888
+ for (let i = 0; i < options.length; i++) {
66889
+ const opt = options[i];
66890
+ if (!config[opt.if]) continue;
66891
+ if (!opt.basisFormat.includes(basisFormat)) continue;
66892
+ if (hasAlpha && opt.transcoderFormat.length < 2) continue;
66893
+ if (opt.needsPowerOfTwo && !(isPowerOfTwo(width) && isPowerOfTwo(height))) continue;
66894
+ transcoderFormat = opt.transcoderFormat[hasAlpha ? 1 : 0];
66895
+ engineFormat = opt.engineFormat[hasAlpha ? 1 : 0];
66896
+ return {
66897
+ transcoderFormat,
66898
+ engineFormat
66899
+ };
66900
+ }
66901
+ console.warn('KTX2TextureTranscoder: No suitable compressed texture format found. Decoding to RGBA32.');
66902
+ transcoderFormat = TranscoderFormat.RGBA32;
66903
+ engineFormat = EngineFormat.RGBAFormat;
66904
+ return {
66905
+ transcoderFormat,
66906
+ engineFormat
66907
+ };
66908
+ }
66909
+
66910
+ function isPowerOfTwo(value) {
66911
+ if (value <= 2) return true;
66912
+ return (value & value - 1) === 0 && value !== 0;
66913
+ }
66914
+ };
66915
+
66916
+ const cachedTranscoders = {};
66917
+
66918
+ /**
66919
+ * Returns a new {@link KTX2TextureTranscoder}.
66920
+ *
66921
+ * The ````transcoderPath```` config will be set to: "https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/"
66922
+ *
66923
+ * @private
66924
+ */
66925
+ function getKTX2TextureTranscoder(viewer) {
66926
+ const sceneId = viewer.scene.id;
66927
+ let transcoder = cachedTranscoders[sceneId];
66928
+ if (!transcoder) {
66929
+ transcoder = new KTX2TextureTranscoder({viewer});
66930
+ cachedTranscoders[sceneId] = transcoder;
66931
+ viewer.scene.on("destroyed", () => {
66932
+ delete cachedTranscoders[sceneId];
66933
+ transcoder.destroy();
66934
+ });
66935
+ }
66936
+ return transcoder;
66937
+ }
66938
+
65889
66939
  const tempVec3a$9 = math.vec3();
65890
66940
  const tempMat4$1 = math.mat4();
65891
66941
 
@@ -66961,7 +68011,7 @@ class VBOSceneModel extends Component {
66961
68011
 
66962
68012
  super(owner, cfg);
66963
68013
 
66964
- this._textureTranscoder = cfg.textureTranscoder;
68014
+ this._textureTranscoder = cfg.textureTranscoder || getKTX2TextureTranscoder(this.scene.viewer);
66965
68015
 
66966
68016
  this._maxGeometryBatchSize = cfg.maxGeometryBatchSize;
66967
68017
 
@@ -67937,7 +68987,7 @@ class VBOSceneModel extends Component {
67937
68987
  * @param {String} [cfg.src] Image file for the texture. Assumed to be transcoded if not having a recognized image file
67938
68988
  * extension (jpg, jpeg, png etc.). If transcoded, then assumes ````VBOSceneModel```` is configured with a {@link TextureTranscoder}.
67939
68989
  * @param {ArrayBuffer[]} [cfg.buffers] Transcoded texture data. Assumes ````VBOSceneModel```` is
67940
- * configured with a {@link TextureTranscoder}. Given as an array of buffers so we can potentially support multi-image textures, such as cube maps.
68990
+ * configured with a {@link TextureTranscoder}. This parameter is given as an array of buffers so we can potentially support multi-image textures, such as cube maps.
67941
68991
  * @param {HTMLImageElement} [cfg.image] HTML Image object to load into this texture. Overrides ````src```` and ````buffers````. Never transcoded.
67942
68992
  * @param {Number} [cfg.minFilter=LinearMipmapLinearFilter] How the texture is sampled when a texel covers less than one pixel.
67943
68993
  * Supported values are {@link LinearMipmapLinearFilter}, {@link LinearMipMapNearestFilter}, {@link NearestMipMapNearestFilter}, {@link NearestMipMapLinearFilter} and {@link LinearMipMapLinearFilter}.
@@ -67957,8 +69007,8 @@ class VBOSceneModel extends Component {
67957
69007
  this.error("Texture already created: " + textureId);
67958
69008
  return;
67959
69009
  }
67960
- if (!cfg.src && !cfg.image) {
67961
- this.error("Param expected: `src` or `image'");
69010
+ if (!cfg.src && !cfg.image && !cfg.buffers) {
69011
+ this.error("Param expected: `src`, `image' or 'buffers'");
67962
69012
  return null;
67963
69013
  }
67964
69014
  let minFilter = cfg.minFilter || LinearMipmapLinearFilter;
@@ -74059,7 +75109,7 @@ class WorkerThread {
74059
75109
 
74060
75110
  }
74061
75111
 
74062
- class WorkerPool$1 {
75112
+ class WorkerPool {
74063
75113
  constructor(props) {
74064
75114
  _defineProperty(this, "name", 'unnamed');
74065
75115
 
@@ -74267,7 +75317,7 @@ class WorkerFarm {
74267
75317
  let workerPool = this.workerPools.get(name);
74268
75318
 
74269
75319
  if (!workerPool) {
74270
- workerPool = new WorkerPool$1({
75320
+ workerPool = new WorkerPool({
74271
75321
  name,
74272
75322
  source,
74273
75323
  url
@@ -100446,7 +101496,7 @@ function inflate(deflatedData) {
100446
101496
 
100447
101497
  return {
100448
101498
  metadata: JSON.parse(pako.inflate(deflatedData.metadata, {to: 'string'})),
100449
- textureData: new Uint8ClampedArray(inflate(deflatedData.textureData)),
101499
+ textureData: new Uint8Array(inflate(deflatedData.textureData)),
100450
101500
  eachTextureDataPortion: new Uint32Array(inflate(deflatedData.eachTextureDataPortion)),
100451
101501
  eachTextureDimensions: new Uint16Array(inflate(deflatedData.eachTextureDimensions)),
100452
101502
  positions: new Uint16Array(inflate(deflatedData.positions)),
@@ -100486,7 +101536,7 @@ const decompressColor = (function () {
100486
101536
  };
100487
101537
  })();
100488
101538
 
100489
- const imagDataToImage = (function () {
101539
+ ((function () {
100490
101540
  const canvas = document.createElement('canvas');
100491
101541
  const context = canvas.getContext('2d');
100492
101542
  return function (imagedata) {
@@ -100495,14 +101545,14 @@ const imagDataToImage = (function () {
100495
101545
  context.putImageData(imagedata, 0, 0);
100496
101546
  return canvas.toDataURL();
100497
101547
  };
100498
- })();
101548
+ }))();
100499
101549
 
100500
101550
  function load(viewer, options, inflatedData, sceneModel) {
100501
101551
 
100502
101552
  const metadata = inflatedData.metadata;
100503
101553
  const textureData = inflatedData.textureData;
100504
101554
  const eachTextureDataPortion = inflatedData.eachTextureDataPortion;
100505
- const eachTextureDimensions = inflatedData.eachTextureDimensions;
101555
+ inflatedData.eachTextureDimensions;
100506
101556
  const positions = inflatedData.positions;
100507
101557
  const normals = inflatedData.normals;
100508
101558
  const colors = inflatedData.colors;
@@ -100563,20 +101613,13 @@ function load(viewer, options, inflatedData, sceneModel) {
100563
101613
  const textureDataPortionSize = textureDataPortionEnd - textureDataPortionStart;
100564
101614
  const textureDataPortionExists = (textureDataPortionSize > 0);
100565
101615
  if (textureDataPortionExists) {
100566
- const imageDataSubarray = textureData.subarray(textureDataPortionStart, textureDataPortionEnd);
100567
- const width = eachTextureDimensions[textureIndex * 2 + 0];
100568
- const height = eachTextureDimensions[textureIndex * 2 + 1];
100569
- const imageData = new ImageData(imageDataSubarray, width, height);
100570
-
100571
- //////////////////////////////////////////////////////////////
100572
- // TODO: This is super inefficient - replace with Basis:
100573
- //////////////////////////////////////////////////////////////
100574
101616
 
100575
- const image = imagDataToImage(imageData);
101617
+ const imageDataSubarray = new Uint8Array(textureData.subarray(textureDataPortionStart, textureDataPortionEnd));
101618
+ const arrayBuffer = imageDataSubarray.buffer;
100576
101619
 
100577
101620
  sceneModel.createTexture({
100578
101621
  id: `texture-${textureIndex}`,
100579
- src: image
101622
+ buffers: [arrayBuffer]
100580
101623
  });
100581
101624
  }
100582
101625
  }
@@ -100998,6 +102041,7 @@ parsers[ParserV10.version] = ParserV10;
100998
102041
  * * An *````.XKT````* file is a single BLOB containing a model, compressed using geometry quantization
100999
102042
  * and [pako](https://nodeca.github.io/pako/).
101000
102043
  * * Supports double-precision coordinates.
102044
+ * * Supports compressed textures.
101001
102045
  * * Set the position, scale and rotation of each model as you load it.
101002
102046
  * * Filter which IFC types get loaded.
101003
102047
  * * Configure initial default appearances for IFC types.
@@ -101116,17 +102160,26 @@ parsers[ParserV10.version] = ParserV10;
101116
102160
  * model.destroy();
101117
102161
  * ````
101118
102162
  *
101119
- * ## Loading XKT files containing KTX2 textures
102163
+ * ## Loading XKT files containing textures
101120
102164
  *
101121
- * An XKTLoaderPlugin that is configured with a {@link KTX2TextureTranscoder} will allow us to load XKT files that
101122
- * contain KTX2 textures. If we don't configure a KTX2TextureTranscoder, then the XKTLoaderPlugin will simply ignore
101123
- * the textures in the XKT.
102165
+ * XKTLoaderPlugin uses a {@link KTX2TextureTranscoder} to load textures in XKT files (XKT v10+). An XKTLoaderPlugin has its own
102166
+ * default KTX2TextureTranscoder, configured to load the Basis Codec from the CDN. If we wish, we can override that with our own
102167
+ * KTX2TextureTranscoder instance that's configured to load the Codec locally.
101124
102168
  *
101125
102169
  * In the example below, we'll create a {@link Viewer} and add an XKTLoaderPlugin
101126
- * configured with a KTX2TextureTranscoder. Then we'll use the XKTLoaderPlugin to load an
101127
- * XKT file that contains KTX2 textures, which the plugin will transcode using
102170
+ * configured with a KTX2TextureTranscoder that finds the Codec in our local file system. Then we'll use the
102171
+ * XKTLoaderPlugin to load an XKT file that contains KTX2 textures, which the plugin will transcode using
101128
102172
  * its KTX2TextureTranscoder.
101129
102173
  *
102174
+ * We'll configure our KTX2TextureTranscoder to load the Basis Codec from a local directory. If we were happy with loading the
102175
+ * Codec from our CDN (ie. our app will always have an Internet connection) then we could just leave out the
102176
+ * KTX2TextureTranscoder altogether, and let the XKTLoaderPlugin use its internal default KTX2TextureTranscoder, which is configured to
102177
+ * load the Codec from the CDN. We'll stick with loading our own Codec, in case we want to run our app without an Internet connection.
102178
+ *
102179
+ * <a href="https://xeokit.github.io/xeokit-sdk/examples/#loading_XKT_Textures_HousePlan"><img src="https://xeokit.github.io/xeokit-sdk/assets/images/xktWithTextures.png"></a>
102180
+ *
102181
+ * * [[Run this example](https://xeokit.github.io/xeokit-sdk/examples/#loading_XKT_Textures_HousePlan)]
102182
+ *
101130
102183
  * ````javascript
101131
102184
  * const viewer = new Viewer({
101132
102185
  * canvasId: "myCanvas",
@@ -154212,1016 +155265,6 @@ class PerformanceModel extends VBOSceneModel {
154212
155265
  }
154213
155266
  }
154214
155267
 
154215
- class LoadingManager {
154216
-
154217
- constructor(onLoad, onProgress, onError) {
154218
-
154219
- this.isLoading = false;
154220
- this.itemsLoaded = 0;
154221
- this.itemsTotal = 0;
154222
- this.urlModifier = undefined;
154223
- this.handlers = [];
154224
-
154225
- this.onStart = undefined;
154226
- this.onLoad = onLoad;
154227
- this.onProgress = onProgress;
154228
- this.onError = onError;
154229
- }
154230
-
154231
- itemStart(url) {
154232
- this.itemsTotal++;
154233
- if (this.isLoading === false) {
154234
- if (this.onStart !== undefined) {
154235
- this.onStart(url, this.itemsLoaded, this.itemsTotal);
154236
- }
154237
- }
154238
- this.isLoading = true;
154239
- }
154240
-
154241
- itemEnd(url) {
154242
- this.itemsLoaded++;
154243
- if (this.onProgress !== undefined) {
154244
- this.onProgress(url, this.itemsLoaded, this.itemsTotal);
154245
- }
154246
- if (this.itemsLoaded === this.itemsTotal) {
154247
- this.isLoading = false;
154248
- if (this.onLoad !== undefined) {
154249
- this.onLoad();
154250
- }
154251
- }
154252
- }
154253
-
154254
- itemError(url) {
154255
- if (this.onError !== undefined) {
154256
- this.onError(url);
154257
- }
154258
- }
154259
-
154260
- resolveURL(url) {
154261
- if (this.urlModifier) {
154262
- return this.urlModifier(url);
154263
- }
154264
- return url;
154265
- }
154266
-
154267
- setURLModifier(transform) {
154268
- this.urlModifier = transform;
154269
- return this;
154270
- }
154271
-
154272
- addHandler(regex, loader) {
154273
- this.handlers.push(regex, loader);
154274
- return this;
154275
- }
154276
-
154277
- removeHandler(regex) {
154278
- const index = this.handlers.indexOf(regex);
154279
- if (index !== -1) {
154280
- this.handlers.splice(index, 2);
154281
- }
154282
- return this;
154283
- }
154284
-
154285
- getHandler(file) {
154286
- for (let i = 0, l = this.handlers.length; i < l; i += 2) {
154287
- const regex = this.handlers[i];
154288
- const loader = this.handlers[i + 1];
154289
- if (regex.global) regex.lastIndex = 0; // see #17920
154290
- if (regex.test(file)) {
154291
- return loader;
154292
- }
154293
- }
154294
- return null;
154295
- }
154296
- }
154297
-
154298
- const DefaultLoadingManager = new LoadingManager();
154299
-
154300
- class Loader {
154301
-
154302
- constructor(manager) {
154303
-
154304
- this.manager = (manager !== undefined) ? manager : DefaultLoadingManager;
154305
-
154306
- this.crossOrigin = 'anonymous';
154307
- this.withCredentials = false;
154308
- this.path = '';
154309
- this.resourcePath = '';
154310
- this.requestHeader = {};
154311
- }
154312
-
154313
- load( /* url, onLoad, onProgress, onError */) {
154314
- }
154315
-
154316
- loadAsync(url, onProgress) {
154317
- const scope = this;
154318
- return new Promise(function (resolve, reject) {
154319
- scope.load(url, resolve, onProgress, reject);
154320
- });
154321
- }
154322
-
154323
- parse( /* data */) {
154324
- }
154325
-
154326
- setCrossOrigin(crossOrigin) {
154327
- this.crossOrigin = crossOrigin;
154328
- return this;
154329
- }
154330
-
154331
- setWithCredentials(value) {
154332
- this.withCredentials = value;
154333
- return this;
154334
- }
154335
-
154336
- setPath(path) {
154337
- this.path = path;
154338
- return this;
154339
- }
154340
-
154341
- setResourcePath(resourcePath) {
154342
- this.resourcePath = resourcePath;
154343
- return this;
154344
- }
154345
-
154346
- setRequestHeader(requestHeader) {
154347
- this.requestHeader = requestHeader;
154348
- return this;
154349
- }
154350
- }
154351
-
154352
- /**
154353
- * @author Deepkolos / https://github.com/deepkolos
154354
- */
154355
-
154356
- class WorkerPool {
154357
-
154358
- constructor(pool = 4) {
154359
- this.pool = pool;
154360
- this.queue = [];
154361
- this.workers = [];
154362
- this.workersResolve = [];
154363
- this.workerStatus = 0;
154364
- }
154365
-
154366
- _initWorker(workerId) {
154367
- if (!this.workers[workerId]) {
154368
- const worker = this.workerCreator();
154369
- worker.addEventListener('message', this._onMessage.bind(this, workerId));
154370
- this.workers[workerId] = worker;
154371
- }
154372
- }
154373
-
154374
- _getIdleWorker() {
154375
- for (let i = 0; i < this.pool; i++)
154376
- if (!(this.workerStatus & (1 << i))) return i;
154377
- return -1;
154378
- }
154379
-
154380
- _onMessage(workerId, msg) {
154381
- const resolve = this.workersResolve[workerId];
154382
- resolve && resolve(msg);
154383
- if (this.queue.length) {
154384
- const {resolve, msg, transfer} = this.queue.shift();
154385
- this.workersResolve[workerId] = resolve;
154386
- this.workers[workerId].postMessage(msg, transfer);
154387
- } else {
154388
- this.workerStatus ^= 1 << workerId;
154389
- }
154390
- }
154391
-
154392
- setWorkerCreator(workerCreator) {
154393
- this.workerCreator = workerCreator;
154394
- }
154395
-
154396
- setWorkerLimit(pool) {
154397
- this.pool = pool;
154398
- }
154399
-
154400
- postMessage(msg, transfer) {
154401
- return new Promise((resolve) => {
154402
- const workerId = this._getIdleWorker();
154403
- if (workerId !== -1) {
154404
- this._initWorker(workerId);
154405
- this.workerStatus |= 1 << workerId;
154406
- this.workersResolve[workerId] = resolve;
154407
- this.workers[workerId].postMessage(msg, transfer);
154408
- } else {
154409
- this.queue.push({resolve, msg, transfer});
154410
- }
154411
- });
154412
- }
154413
-
154414
- destroy() {
154415
-
154416
- this.workers.forEach((worker) => worker.terminate());
154417
- this.workersResolve.length = 0;
154418
- this.workers.length = 0;
154419
- this.queue.length = 0;
154420
- this.workerStatus = 0;
154421
-
154422
- }
154423
-
154424
- }
154425
-
154426
- /**
154427
- * Transcodes texture data.
154428
- *
154429
- * A {@link SceneModel} configured with an appropriate TextureTranscoder will allow us to add textures from
154430
- * transcoded buffers or files. For a concrete example, see {@link VBOSceneModel}, which can be configured with
154431
- * a {@link KTX2TextureTranscoder}, which allows us to add textures from KTX2 buffers and files.
154432
- *
154433
- * @interface
154434
- */
154435
- class TextureTranscoder {
154436
-
154437
- /**
154438
- * Transcodes texture data from transcoded buffers into a {@link Texture2D}.
154439
- *
154440
- * @param {ArrayBuffer[]} buffers Transcoded texture data. Given as an array of buffers so that we can support
154441
- * multi-image textures, such as cube maps.
154442
- * @param {*} config Transcoding options.
154443
- * @param {Texture2D} texture The texture to load.
154444
- * @returns {Promise} Resolves when the texture has loaded.
154445
- */
154446
- transcode(buffers, texture, config = {}) {
154447
- }
154448
-
154449
- /**
154450
- * Destroys this transcoder.
154451
- */
154452
- destroy() {
154453
- }
154454
- }
154455
-
154456
- const Cache = {
154457
-
154458
- enabled: false,
154459
- files: {},
154460
-
154461
- add: function (key, file) {
154462
- if (this.enabled === false) {
154463
- return;
154464
- }
154465
- this.files[key] = file;
154466
- },
154467
-
154468
- get: function (key) {
154469
- if (this.enabled === false) {
154470
- return;
154471
- }
154472
- return this.files[key];
154473
- },
154474
-
154475
- remove: function (key) {
154476
- delete this.files[key];
154477
- },
154478
-
154479
- clear: function () {
154480
- this.files = {};
154481
- }
154482
- };
154483
-
154484
- const loading = {};
154485
-
154486
- class FileLoader extends Loader {
154487
-
154488
- constructor(manager) {
154489
- super(manager);
154490
- }
154491
-
154492
- load(url, onLoad, onProgress, onError) {
154493
- if (url === undefined) {
154494
- url = '';
154495
- }
154496
- if (this.path !== undefined) {
154497
- url = this.path + url;
154498
- }
154499
- url = this.manager.resolveURL(url);
154500
- const cached = Cache.get(url);
154501
- if (cached !== undefined) {
154502
- this.manager.itemStart(url);
154503
- setTimeout(() => {
154504
- if (onLoad) {
154505
- onLoad(cached);
154506
- }
154507
- this.manager.itemEnd(url);
154508
- }, 0);
154509
- return cached;
154510
- }
154511
- if (loading[url] !== undefined) {
154512
- loading[url].push({onLoad, onProgress, onError});
154513
- return;
154514
- }
154515
- loading[url] = [];
154516
- loading[url].push({onLoad, onProgress, onError});
154517
- const req = new Request(url, {
154518
- headers: new Headers(this.requestHeader),
154519
- credentials: this.withCredentials ? 'include' : 'same-origin'
154520
- });
154521
- const mimeType = this.mimeType;
154522
- const responseType = this.responseType;
154523
- fetch(req).then(response => {
154524
- if (response.status === 200 || response.status === 0) {
154525
- // Some browsers return HTTP Status 0 when using non-http protocol
154526
- // e.g. 'file://' or 'data://'. Handle as success.
154527
- if (response.status === 0) {
154528
- console.warn('FileLoader: HTTP Status 0 received.');
154529
- }
154530
- if (typeof ReadableStream === 'undefined' || response.body.getReader === undefined) {
154531
- return response;
154532
- }
154533
- const callbacks = loading[url];
154534
- const reader = response.body.getReader();
154535
- const contentLength = response.headers.get('Content-Length');
154536
- const total = contentLength ? parseInt(contentLength) : 0;
154537
- const lengthComputable = total !== 0;
154538
- let loaded = 0;
154539
- const stream = new ReadableStream({
154540
- start(controller) {
154541
- readData();
154542
-
154543
- function readData() {
154544
- reader.read().then(({done, value}) => {
154545
- if (done) {
154546
- controller.close();
154547
- } else {
154548
- loaded += value.byteLength;
154549
- const event = new ProgressEvent('progress', {lengthComputable, loaded, total});
154550
- for (let i = 0, il = callbacks.length; i < il; i++) {
154551
- const callback = callbacks[i];
154552
- if (callback.onProgress) {
154553
- callback.onProgress(event);
154554
- }
154555
- }
154556
- controller.enqueue(value);
154557
- readData();
154558
- }
154559
- });
154560
- }
154561
- }
154562
- });
154563
- return new Response(stream);
154564
- } else {
154565
- throw Error(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`);
154566
- }
154567
- }).then(response => {
154568
- switch (responseType) {
154569
- case 'arraybuffer':
154570
- return response.arrayBuffer();
154571
- case 'blob':
154572
- return response.blob();
154573
- case 'document':
154574
- return response.text()
154575
- .then(text => {
154576
- const parser = new DOMParser();
154577
- return parser.parseFromString(text, mimeType);
154578
- });
154579
- case 'json':
154580
- return response.json();
154581
- default:
154582
- if (mimeType === undefined) {
154583
- return response.text();
154584
- } else {
154585
- // sniff encoding
154586
- const re = /charset="?([^;"\s]*)"?/i;
154587
- const exec = re.exec(mimeType);
154588
- const label = exec && exec[1] ? exec[1].toLowerCase() : undefined;
154589
- const decoder = new TextDecoder(label);
154590
- return response.arrayBuffer().then(ab => decoder.decode(ab));
154591
- }
154592
- }
154593
- }).then(data => {
154594
- // Add to cache only on HTTP success, so that we do not cache
154595
- // error response bodies as proper responses to requests.
154596
- Cache.add(url, data);
154597
- const callbacks = loading[url];
154598
- delete loading[url];
154599
- for (let i = 0, il = callbacks.length; i < il; i++) {
154600
- const callback = callbacks[i];
154601
- if (callback.onLoad) {
154602
- callback.onLoad(data);
154603
- }
154604
- }
154605
- }).catch(err => {
154606
- // Abort errors and other errors are handled the same
154607
- const callbacks = loading[url];
154608
- if (callbacks === undefined) {
154609
- // When onLoad was called and url was deleted in `loading`
154610
- this.manager.itemError(url);
154611
- throw err;
154612
-
154613
- }
154614
- delete loading[url];
154615
- for (let i = 0, il = callbacks.length; i < il; i++) {
154616
- const callback = callbacks[i];
154617
- if (callback.onError) {
154618
- callback.onError(err);
154619
- }
154620
- }
154621
- this.manager.itemError(url);
154622
- }).finally(() => {
154623
- this.manager.itemEnd(url);
154624
- });
154625
- this.manager.itemStart(url);
154626
- }
154627
-
154628
- setResponseType(value) {
154629
- this.responseType = value;
154630
- return this;
154631
- }
154632
-
154633
- setMimeType(value) {
154634
- this.mimeType = value;
154635
- return this;
154636
- }
154637
- }
154638
-
154639
- const KTX2TransferSRGB = 2;
154640
- const KTX2_ALPHA_PREMULTIPLIED = 1;
154641
-
154642
- let activeTranscoders = 0;
154643
-
154644
- /**
154645
- * Transcodes texture data from KTX2.
154646
- *
154647
- * ## Overview
154648
- *
154649
- * * Uses the Basis Universal codec to transcode KTX2 texture assets.
154650
- * * An {@link XKTLoaderPlugin} that is configured with a KTX2TextureTranscoder will allow us to load KTX2 textures in
154651
- * XKT files. Textures in XKT are always KTX2. If we do not configure a KTX2TextureTranscoder, the XKTLoaderPlugin will
154652
- * simply ignore the textures in the XKT.
154653
- * * A {@link SceneModel} implementation (eg. {@link VBOSceneModel}) that is configured with a KTX2TextureTranscoder will
154654
- * allow us to load textures into it from KTX2 files or ArrayBuffers.
154655
- *
154656
- * ## What is KTX2?
154657
- *
154658
- * A KTX2 file stores GPU texture data in the Khronos Texture 2.0 (KTX2) container format. It contains image data for
154659
- * a texture asset compressed with Basis Universal (BasisU) supercompression that can be transcoded to different formats
154660
- * depending on the support provided by the target devices. KTX2 provides a lightweight format for distributing texture
154661
- * assets to GPUs. Due to BasisU compression, KTX2 files can store any image format supported by GPUs.
154662
- *
154663
- * ## Loading XKT files containing KTX2 textures
154664
- *
154665
- * An {@link XKTLoaderPlugin} that is configured with a KTX2TextureTranscoder will allow us to load XKT files that
154666
- * contain KTX2 textures. If we don't configure a KTX2TextureTranscoder, then the XKTLoaderPlugin will simply ignore
154667
- * the textures in the XKT.
154668
- *
154669
- * In the example below, we'll create a {@link Viewer} and add an {@link XKTLoaderPlugin}
154670
- * configured with a KTX2TextureTranscoder. Then we'll use the XKTLoaderPlugin to load an
154671
- * XKT file that contains KTX2 textures, which the plugin will transcode using
154672
- * its KTX2TextureTranscoder.
154673
- *
154674
- * ````javascript
154675
- * const viewer = new Viewer({
154676
- * canvasId: "myCanvas",
154677
- * transparent: true
154678
- * });
154679
- *
154680
- * viewer.camera.eye = [-2.56, 8.38, 8.27];
154681
- * viewer.camera.look = [13.44, 3.31, -14.83];
154682
- * viewer.camera.up = [0.10, 0.98, -0.14];
154683
- *
154684
- * const textureTranscoder = new KTX2TextureTranscoder({
154685
- * viewer,
154686
- * transcoderPath: "./../dist/basis/" // <------ Path to Basis Universal transcoder
154687
- * });
154688
- *
154689
- * const xktLoader = new XKTLoaderPlugin(viewer, {
154690
- * textureTranscoder // <<------------- Transcodes KTX2 textures in XKT files
154691
- * });
154692
- *
154693
- * const sceneModel = xktLoader.load({
154694
- * id: "myModel",
154695
- * src: "./HousePlan.xkt" // <<------ XKT file with KTX2 textures
154696
- * });
154697
- * ````
154698
- *
154699
- * ## Loading KTX2 files into a VBOSceneModel
154700
- *
154701
- * A {@link SceneModel} that is configured with a KTX2TextureTranscoder will
154702
- * allow us to load textures into it from KTX2-transcoded buffers or files.
154703
- *
154704
- * In the example below, we'll create a {@link Viewer}, containing a {@link VBOSceneModel} configured with a
154705
- * KTX2TextureTranscoder. We'll then programmatically create a simple object within the VBOSceneModel, consisting of
154706
- * a single mesh with a texture loaded from a KTX2 file, which our VBOSceneModel internally transcodes, using
154707
- * its KTX2TextureTranscoder. Note how we configure our KTX2TextureTranscoder with a path to the Basis Universal
154708
- * transcoder WASM module.
154709
- *
154710
- * ````javascript
154711
- * const viewer = new Viewer({
154712
- * canvasId: "myCanvas",
154713
- * transparent: true
154714
- * });
154715
- *
154716
- * viewer.scene.camera.eye = [-21.80, 4.01, 6.56];
154717
- * viewer.scene.camera.look = [0, -5.75, 0];
154718
- * viewer.scene.camera.up = [0.37, 0.91, -0.11];
154719
- *
154720
- * const textureTranscoder = new KTX2TextureTranscoder({
154721
- * viewer,
154722
- * transcoderPath: "./../dist/basis/" // <------ Path to BasisU transcoder module
154723
- * });
154724
- *
154725
- * const vboSceneModel = new VBOSceneModel(viewer.scene, {
154726
- * id: "myModel",
154727
- * textureTranscoder // <<-------------------- Configure model with our transcoder
154728
- * });
154729
- *
154730
- * vboSceneModel.createTexture({
154731
- * id: "myColorTexture",
154732
- * src: "../assets/textures/compressed/sample_uastc_zstd.ktx2" // <<----- KTX2 texture asset
154733
- * });
154734
- *
154735
- * vboSceneModel.createTexture({
154736
- * id: "myMetallicRoughnessTexture",
154737
- * src: "../assets/textures/alpha/crosshatchAlphaMap.jpg" // <<----- JPEG texture asset
154738
- * });
154739
- *
154740
- * vboSceneModel.createTextureSet({
154741
- * id: "myTextureSet",
154742
- * colorTextureId: "myColorTexture",
154743
- * metallicRoughnessTextureId: "myMetallicRoughnessTexture"
154744
- * });
154745
- *
154746
- * vboSceneModel.createMesh({
154747
- * id: "myMesh",
154748
- * textureSetId: "myTextureSet",
154749
- * primitive: "triangles",
154750
- * positions: [1, 1, 1, ...],
154751
- * normals: [0, 0, 1, 0, ...],
154752
- * uv: [1, 0, 0, ...],
154753
- * indices: [0, 1, 2, ...],
154754
- * });
154755
- *
154756
- * vboSceneModel.createEntity({
154757
- * id: "myEntity",
154758
- * meshIds: ["myMesh"]
154759
- * });
154760
- *
154761
- * vboSceneModel.finalize();
154762
- * ````
154763
- *
154764
- * ## Loading KTX2 ArrayBuffers into a VBOSceneModel
154765
- *
154766
- * A {@link SceneModel} that is configured with a KTX2TextureTranscoder will allow us to load textures into
154767
- * it from KTX2 ArrayBuffers.
154768
- *
154769
- * In the example below, we'll create a {@link Viewer}, containing a {@link VBOSceneModel} configured with a
154770
- * KTX2TextureTranscoder. We'll then programmatically create a simple object within the VBOSceneModel, consisting of
154771
- * a single mesh with a texture loaded from a KTX2 ArrayBuffer, which our VBOSceneModel internally transcodes, using
154772
- * its KTX2TextureTranscoder.
154773
- *
154774
- * ````javascript
154775
- * const viewer = new Viewer({
154776
- * canvasId: "myCanvas",
154777
- * transparent: true
154778
- * });
154779
- *
154780
- * viewer.scene.camera.eye = [-21.80, 4.01, 6.56];
154781
- * viewer.scene.camera.look = [0, -5.75, 0];
154782
- * viewer.scene.camera.up = [0.37, 0.91, -0.11];
154783
- *
154784
- * const textureTranscoder = new KTX2TextureTranscoder({
154785
- * viewer,
154786
- * transcoderPath: "./../dist/basis/" // <------ Path to BasisU transcoder module
154787
- * });
154788
- *
154789
- * const vboSceneModel = new VBOSceneModel(viewer.scene, {
154790
- * id: "myModel",
154791
- * textureTranscoder // <<-------------------- Configure model with our transcoder
154792
- * });
154793
- *
154794
- * utils.loadArraybuffer("../assets/textures/compressed/sample_uastc_zstd.ktx2",(arrayBuffer) => {
154795
- *
154796
- * vboSceneModel.createTexture({
154797
- * id: "myColorTexture",
154798
- * buffers: [arrayBuffer] // <<----- KTX2 texture asset
154799
- * });
154800
- *
154801
- * vboSceneModel.createTexture({
154802
- * id: "myMetallicRoughnessTexture",
154803
- * src: "../assets/textures/alpha/crosshatchAlphaMap.jpg" // <<----- JPEG texture asset
154804
- * });
154805
- *
154806
- * vboSceneModel.createTextureSet({
154807
- * id: "myTextureSet",
154808
- * colorTextureId: "myColorTexture",
154809
- * metallicRoughnessTextureId: "myMetallicRoughnessTexture"
154810
- * });
154811
- *
154812
- * vboSceneModel.createMesh({
154813
- * id: "myMesh",
154814
- * textureSetId: "myTextureSet",
154815
- * primitive: "triangles",
154816
- * positions: [1, 1, 1, ...],
154817
- * normals: [0, 0, 1, 0, ...],
154818
- * uv: [1, 0, 0, ...],
154819
- * indices: [0, 1, 2, ...],
154820
- * });
154821
- *
154822
- * vboSceneModel.createEntity({
154823
- * id: "myEntity",
154824
- * meshIds: ["myMesh"]
154825
- * });
154826
- *
154827
- * vboSceneModel.finalize();
154828
- * });
154829
- * ````
154830
- *
154831
- * @implements {TextureTranscoder}
154832
- */
154833
- class KTX2TextureTranscoder {
154834
-
154835
- /**
154836
- * Creates a new KTX2TextureTranscoder.
154837
- *
154838
- * @param {Viewer} viewer The Viewer that our KTX2TextureTranscoder will be used with. This KTX2TextureTranscoder
154839
- * must only be used to transcode textures for this Viewer. This is because the Viewer's capabilities will decide
154840
- * what target GPU formats this KTX2TextureTranscoder will transcode to.
154841
- * @param {String} transcoderPath Path to the Basis transcoder module that internally does the heavy lifting for our KTX2TextureTranscoder.
154842
- * @param {Number} [workerLimit] The maximum number of Workers to use for transcoding.
154843
- */
154844
- constructor({viewer, transcoderPath, workerLimit}) {
154845
-
154846
- this._transcoderPath = transcoderPath;
154847
- this._transcoderBinary = null;
154848
- this._transcoderPending = null;
154849
- this._workerPool = new WorkerPool();
154850
- this._workerSourceURL = '';
154851
-
154852
- if (workerLimit) {
154853
- this._workerPool.setWorkerLimit(workerLimit);
154854
- }
154855
-
154856
- const viewerCapabilities = viewer.capabilities;
154857
-
154858
- this._workerConfig = {
154859
- astcSupported: viewerCapabilities.astcSupported,
154860
- etc1Supported: viewerCapabilities.etc1Supported,
154861
- etc2Supported: viewerCapabilities.etc2Supported,
154862
- dxtSupported: viewerCapabilities.dxtSupported,
154863
- bptcSupported: viewerCapabilities.bptcSupported,
154864
- pvrtcSupported: viewerCapabilities.pvrtcSupported
154865
- };
154866
-
154867
- this._supportedFileTypes = ["xkt2"];
154868
- }
154869
-
154870
- _init() {
154871
- if (!this._transcoderPending) {
154872
- const jsLoader = new FileLoader();
154873
- jsLoader.setPath(this._transcoderPath);
154874
- jsLoader.setWithCredentials(this.withCredentials);
154875
- const jsContent = jsLoader.loadAsync('basis_transcoder.js');
154876
- const binaryLoader = new FileLoader();
154877
- binaryLoader.setPath(this._transcoderPath);
154878
- binaryLoader.setResponseType('arraybuffer');
154879
- binaryLoader.setWithCredentials(this.withCredentials);
154880
- const binaryContent = binaryLoader.loadAsync('basis_transcoder.wasm');
154881
- this._transcoderPending = Promise.all([jsContent, binaryContent])
154882
- .then(([jsContent, binaryContent]) => {
154883
- const fn = KTX2TextureTranscoder.BasisWorker.toString();
154884
- const body = [
154885
- '/* constants */',
154886
- 'let _EngineFormat = ' + JSON.stringify(KTX2TextureTranscoder.EngineFormat),
154887
- 'let _TranscoderFormat = ' + JSON.stringify(KTX2TextureTranscoder.TranscoderFormat),
154888
- 'let _BasisFormat = ' + JSON.stringify(KTX2TextureTranscoder.BasisFormat),
154889
- '/* basis_transcoder.js */',
154890
- jsContent,
154891
- '/* worker */',
154892
- fn.substring(fn.indexOf('{') + 1, fn.lastIndexOf('}'))
154893
- ].join('\n');
154894
- this._workerSourceURL = URL.createObjectURL(new Blob([body]));
154895
- this._transcoderBinary = binaryContent;
154896
- this._workerPool.setWorkerCreator(() => {
154897
- const worker = new Worker(this._workerSourceURL);
154898
- const transcoderBinary = this._transcoderBinary.slice(0);
154899
- worker.postMessage({
154900
- type: 'init',
154901
- config: this._workerConfig,
154902
- transcoderBinary
154903
- }, [transcoderBinary]);
154904
- return worker;
154905
- });
154906
- });
154907
- if (activeTranscoders > 0) {
154908
- console.warn('KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues.' + ' Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances.');
154909
- }
154910
- activeTranscoders++;
154911
- }
154912
- return this._transcoderPending;
154913
- }
154914
-
154915
- /**
154916
- * Transcodes texture data from transcoded buffers into a {@link Texture2D}.
154917
- *
154918
- * @param {ArrayBuffer[]} buffers Transcoded texture data. Given as an array of buffers so that we can support multi-image textures, such as cube maps.
154919
- * @param {*} config Transcoding options.
154920
- * @param {Texture2D} texture The texture to load.
154921
- * @returns {Promise} Resolves when the texture has loaded.
154922
- */
154923
- transcode(buffers, texture, config = {}) {
154924
- return new Promise((resolve, reject) => {
154925
- const taskConfig = config;
154926
- this._init().then(() => {
154927
- return this._workerPool.postMessage({
154928
- type: 'transcode',
154929
- buffers,
154930
- taskConfig: taskConfig
154931
- }, buffers);
154932
- }).then((e) => {
154933
- const transcodeResult = e.data;
154934
- const {mipmaps, width, height, format, type, error, dfdTransferFn, dfdFlags} = transcodeResult;
154935
- if (type === 'error') {
154936
- return reject(error);
154937
- }
154938
- texture.setCompressedData({
154939
- mipmaps,
154940
- props: {
154941
- format: format,
154942
- minFilter: mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter,
154943
- magFilter: mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter,
154944
- encoding: dfdTransferFn === KTX2TransferSRGB ? sRGBEncoding : LinearEncoding,
154945
- premultiplyAlpha : !!(dfdFlags & KTX2_ALPHA_PREMULTIPLIED)
154946
- }
154947
- });
154948
- resolve();
154949
- });
154950
- });
154951
- }
154952
-
154953
- /**
154954
- * Destroys this KTX2TextureTranscoder
154955
- */
154956
- destroy() {
154957
- URL.revokeObjectURL(this._workerSourceURL);
154958
- this._workerPool.destroy();
154959
- activeTranscoders--;
154960
- }
154961
- }
154962
-
154963
- /**
154964
- * @private
154965
- */
154966
- KTX2TextureTranscoder.BasisFormat = {
154967
- ETC1S: 0,
154968
- UASTC_4x4: 1
154969
- };
154970
-
154971
- /**
154972
- * @private
154973
- */
154974
- KTX2TextureTranscoder.TranscoderFormat = {
154975
- ETC1: 0,
154976
- ETC2: 1,
154977
- BC1: 2,
154978
- BC3: 3,
154979
- BC4: 4,
154980
- BC5: 5,
154981
- BC7_M6_OPAQUE_ONLY: 6,
154982
- BC7_M5: 7,
154983
- PVRTC1_4_RGB: 8,
154984
- PVRTC1_4_RGBA: 9,
154985
- ASTC_4x4: 10,
154986
- ATC_RGB: 11,
154987
- ATC_RGBA_INTERPOLATED_ALPHA: 12,
154988
- RGBA32: 13,
154989
- RGB565: 14,
154990
- BGR565: 15,
154991
- RGBA4444: 16
154992
- };
154993
-
154994
- /**
154995
- * @private
154996
- */
154997
- KTX2TextureTranscoder.EngineFormat = {
154998
- RGBAFormat: RGBAFormat,
154999
- RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format,
155000
- RGBA_BPTC_Format: RGBA_BPTC_Format,
155001
- RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format,
155002
- RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format,
155003
- RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format,
155004
- RGB_ETC1_Format: RGB_ETC1_Format,
155005
- RGB_ETC2_Format: RGB_ETC2_Format,
155006
- RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format,
155007
- RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format
155008
- };
155009
-
155010
- /* WEB WORKER */
155011
-
155012
- /**
155013
- * @private
155014
- * @constructor
155015
- */
155016
- KTX2TextureTranscoder.BasisWorker = function () {
155017
-
155018
- let config;
155019
- let transcoderPending;
155020
- let BasisModule;
155021
-
155022
- const EngineFormat = _EngineFormat; // eslint-disable-line no-undef
155023
- const TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef
155024
- const BasisFormat = _BasisFormat; // eslint-disable-line no-undef
155025
-
155026
- self.addEventListener('message', function (e) {
155027
- const message = e.data;
155028
- switch (message.type) {
155029
- case 'init':
155030
- config = message.config;
155031
- init(message.transcoderBinary);
155032
- break;
155033
- case 'transcode':
155034
- transcoderPending.then(() => {
155035
- try {
155036
- const {
155037
- width,
155038
- height,
155039
- hasAlpha,
155040
- mipmaps,
155041
- format,
155042
- dfdTransferFn,
155043
- dfdFlags
155044
- } = transcode(message.buffers[0]);
155045
- const buffers = [];
155046
- for (let i = 0; i < mipmaps.length; ++i) {
155047
- buffers.push(mipmaps[i].data.buffer);
155048
- }
155049
- self.postMessage({
155050
- type: 'transcode',
155051
- id: message.id,
155052
- width,
155053
- height,
155054
- hasAlpha,
155055
- mipmaps,
155056
- format,
155057
- dfdTransferFn,
155058
- dfdFlags
155059
- }, buffers);
155060
- } catch (error) {
155061
- console.error(`[KTX2TextureTranscoder.BasisWorker]: ${error}`);
155062
- self.postMessage({type: 'error', id: message.id, error: error.message});
155063
- }
155064
- });
155065
- break;
155066
- }
155067
- });
155068
-
155069
- function init(wasmBinary) {
155070
- transcoderPending = new Promise(resolve => {
155071
- BasisModule = {
155072
- wasmBinary,
155073
- onRuntimeInitialized: resolve
155074
- };
155075
- BASIS(BasisModule); // eslint-disable-line no-undef
155076
- }).then(() => {
155077
- BasisModule.initializeBasis();
155078
- if (BasisModule.KTX2File === undefined) {
155079
- console.warn('KTX2TextureTranscoder: Please update Basis Universal transcoder.');
155080
- }
155081
- });
155082
- }
155083
-
155084
- function transcode(buffer) {
155085
- const ktx2File = new BasisModule.KTX2File(new Uint8Array(buffer));
155086
-
155087
- function cleanup() {
155088
- ktx2File.close();
155089
- ktx2File.delete();
155090
- }
155091
-
155092
- if (!ktx2File.isValid()) {
155093
- cleanup();
155094
- throw new Error('KTX2TextureTranscoder: Invalid or unsupported .ktx2 file');
155095
- }
155096
- const basisFormat = ktx2File.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S;
155097
- const width = ktx2File.getWidth();
155098
- const height = ktx2File.getHeight();
155099
- const levels = ktx2File.getLevels();
155100
- const hasAlpha = ktx2File.getHasAlpha();
155101
- const dfdTransferFn = ktx2File.getDFDTransferFunc();
155102
- const dfdFlags = ktx2File.getDFDFlags();
155103
- const {transcoderFormat, engineFormat} = getTranscoderFormat(basisFormat, width, height, hasAlpha);
155104
- if (!width || !height || !levels) {
155105
- cleanup();
155106
- throw new Error('KTX2TextureTranscoder: Invalid texture');
155107
- }
155108
- if (!ktx2File.startTranscoding()) {
155109
- cleanup();
155110
- throw new Error('KTX2TextureTranscoder: .startTranscoding failed');
155111
- }
155112
- const mipmaps = [];
155113
- for (let mip = 0; mip < levels; mip++) {
155114
- const levelInfo = ktx2File.getImageLevelInfo(mip, 0, 0);
155115
- const mipWidth = levelInfo.origWidth;
155116
- const mipHeight = levelInfo.origHeight;
155117
- const dst = new Uint8Array(ktx2File.getImageTranscodedSizeInBytes(mip, 0, 0, transcoderFormat));
155118
- const status = ktx2File.transcodeImage(dst, mip, 0, 0, transcoderFormat, 0, -1, -1);
155119
- if (!status) {
155120
- cleanup();
155121
- throw new Error('KTX2TextureTranscoder: .transcodeImage failed.');
155122
- }
155123
- mipmaps.push({data: dst, width: mipWidth, height: mipHeight});
155124
- }
155125
- cleanup();
155126
- return {width, height, hasAlpha, mipmaps, format: engineFormat, dfdTransferFn, dfdFlags};
155127
- }
155128
-
155129
- // Optimal choice of a transcoder target format depends on the Basis format (ETC1S or UASTC),
155130
- // device capabilities, and texture dimensions. The list below ranks the formats separately
155131
- // for ETC1S and UASTC.
155132
- //
155133
- // In some cases, transcoding UASTC to RGBA32 might be preferred for higher quality (at
155134
- // significant memory cost) compared to ETC1/2, BC1/3, and PVRTC. The transcoder currently
155135
- // chooses RGBA32 only as a last resort and does not expose that option to the caller.
155136
-
155137
- const FORMAT_OPTIONS = [{
155138
- if: 'astcSupported',
155139
- basisFormat: [BasisFormat.UASTC_4x4],
155140
- transcoderFormat: [TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4],
155141
- engineFormat: [EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format],
155142
- priorityETC1S: Infinity,
155143
- priorityUASTC: 1,
155144
- needsPowerOfTwo: false
155145
- }, {
155146
- if: 'bptcSupported',
155147
- basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4],
155148
- transcoderFormat: [TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5],
155149
- engineFormat: [EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format],
155150
- priorityETC1S: 3,
155151
- priorityUASTC: 2,
155152
- needsPowerOfTwo: false
155153
- }, {
155154
- if: 'dxtSupported',
155155
- basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4],
155156
- transcoderFormat: [TranscoderFormat.BC1, TranscoderFormat.BC3],
155157
- engineFormat: [EngineFormat.RGB_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format],
155158
- priorityETC1S: 4,
155159
- priorityUASTC: 5,
155160
- needsPowerOfTwo: false
155161
- }, {
155162
- if: 'etc2Supported',
155163
- basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4],
155164
- transcoderFormat: [TranscoderFormat.ETC1, TranscoderFormat.ETC2],
155165
- engineFormat: [EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format],
155166
- priorityETC1S: 1,
155167
- priorityUASTC: 3,
155168
- needsPowerOfTwo: false
155169
- }, {
155170
- if: 'etc1Supported',
155171
- basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4],
155172
- transcoderFormat: [TranscoderFormat.ETC1],
155173
- engineFormat: [EngineFormat.RGB_ETC1_Format],
155174
- priorityETC1S: 2,
155175
- priorityUASTC: 4,
155176
- needsPowerOfTwo: false
155177
- }, {
155178
- if: 'pvrtcSupported',
155179
- basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4],
155180
- transcoderFormat: [TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA],
155181
- engineFormat: [EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format],
155182
- priorityETC1S: 5,
155183
- priorityUASTC: 6,
155184
- needsPowerOfTwo: true
155185
- }];
155186
- const ETC1S_OPTIONS = FORMAT_OPTIONS.sort(function (a, b) {
155187
- return a.priorityETC1S - b.priorityETC1S;
155188
- });
155189
- const UASTC_OPTIONS = FORMAT_OPTIONS.sort(function (a, b) {
155190
- return a.priorityUASTC - b.priorityUASTC;
155191
- });
155192
-
155193
- function getTranscoderFormat(basisFormat, width, height, hasAlpha) {
155194
- let transcoderFormat;
155195
- let engineFormat;
155196
- const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS;
155197
- for (let i = 0; i < options.length; i++) {
155198
- const opt = options[i];
155199
- if (!config[opt.if]) continue;
155200
- if (!opt.basisFormat.includes(basisFormat)) continue;
155201
- if (hasAlpha && opt.transcoderFormat.length < 2) continue;
155202
- if (opt.needsPowerOfTwo && !(isPowerOfTwo(width) && isPowerOfTwo(height))) continue;
155203
- transcoderFormat = opt.transcoderFormat[hasAlpha ? 1 : 0];
155204
- engineFormat = opt.engineFormat[hasAlpha ? 1 : 0];
155205
- return {
155206
- transcoderFormat,
155207
- engineFormat
155208
- };
155209
- }
155210
- console.warn('KTX2TextureTranscoder: No suitable compressed texture format found. Decoding to RGBA32.');
155211
- transcoderFormat = TranscoderFormat.RGBA32;
155212
- engineFormat = EngineFormat.RGBAFormat;
155213
- return {
155214
- transcoderFormat,
155215
- engineFormat
155216
- };
155217
- }
155218
-
155219
- function isPowerOfTwo(value) {
155220
- if (value <= 2) return true;
155221
- return (value & value - 1) === 0 && value !== 0;
155222
- }
155223
- };
155224
-
155225
155268
  const screenPos = math.vec4();
155226
155269
  const viewPos = math.vec4();
155227
155270
 
@@ -161998,11 +162041,9 @@ class LASLoaderPlugin extends Plugin {
161998
162041
  try {
161999
162042
  parse$3(arrayBuffer, LASLoader, options).then((parsedData) => {
162000
162043
 
162001
- const loaderData = parsedData.loaderData;
162002
- const loaderDataHeader = loaderData.header;
162003
- const pointsFormatId = loaderDataHeader.pointsFormatId;
162004
-
162005
162044
  const attributes = parsedData.attributes;
162045
+ const loaderData = parsedData.loaderData;
162046
+ const pointsFormatId = loaderData.pointsFormatId !== undefined ? loaderData.pointsFormatId : -1;
162006
162047
 
162007
162048
  if (!attributes.POSITION) {
162008
162049
  sceneModel.finalize();
@@ -163599,6 +163640,7 @@ exports.NearestFilter = NearestFilter;
163599
163640
  exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
163600
163641
  exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
163601
163642
  exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
163643
+ exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
163602
163644
  exports.Node = Node$1;
163603
163645
  exports.OBJLoaderPlugin = OBJLoaderPlugin;
163604
163646
  exports.ObjectsMemento = ObjectsMemento;
@@ -163672,7 +163714,7 @@ exports.VBOSceneModel = VBOSceneModel;
163672
163714
  exports.ViewCullPlugin = ViewCullPlugin;
163673
163715
  exports.Viewer = Viewer;
163674
163716
  exports.WebIFCLoaderPlugin = WebIFCLoaderPlugin;
163675
- exports.WorkerPool = WorkerPool;
163717
+ exports.WorkerPool = WorkerPool$1;
163676
163718
  exports.XKTDefaultDataSource = XKTDefaultDataSource;
163677
163719
  exports.XKTLoaderPlugin = XKTLoaderPlugin;
163678
163720
  exports.XML3DLoaderPlugin = XML3DLoaderPlugin;
@@ -163685,6 +163727,7 @@ exports.buildPlaneGeometry = buildPlaneGeometry;
163685
163727
  exports.buildSphereGeometry = buildSphereGeometry;
163686
163728
  exports.buildTorusGeometry = buildTorusGeometry;
163687
163729
  exports.buildVectorTextGeometry = buildVectorTextGeometry;
163730
+ exports.getKTX2TextureTranscoder = getKTX2TextureTranscoder;
163688
163731
  exports.load3DSGeometry = load3DSGeometry;
163689
163732
  exports.loadOBJGeometry = loadOBJGeometry;
163690
163733
  exports.math = math;