@loaders.gl/draco 4.0.2 → 4.0.3

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.
@@ -1,2 +1,1054 @@
1
- "use strict";(()=>{var Y=Object.create;var R=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames;var H=Object.getPrototypeOf,K=Object.prototype.hasOwnProperty;var Z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var ee=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of J(e))!K.call(t,a)&&a!==r&&R(t,a,{get:()=>e[a],enumerable:!(o=X(e,a))||o.enumerable});return t};var te=(t,e,r)=>(r=t!=null?Y(H(t)):{},ee(e||!t||!t.__esModule?R(r,"default",{value:t,enumerable:!0}):r,t));var k=Z(()=>{"use strict"});function re(){return globalThis._loadersgl_?.version||(globalThis._loadersgl_=globalThis._loadersgl_||{},globalThis._loadersgl_.version="4.0.2"),globalThis._loadersgl_.version}var S=re();function F(t,e){if(!t)throw new Error(e||"loaders.gl assertion failed.")}var y={self:typeof self<"u"&&self,window:typeof window<"u"&&window,global:typeof global<"u"&&global,document:typeof document<"u"&&document},Oe=y.self||y.window||y.global||{},Ee=y.window||y.self||y.global||{},Le=y.global||y.self||y.window||{},Ie=y.document||{};var A=typeof process!="object"||String(process)!=="[object process]"||process.browser,_=typeof importScripts=="function",Pe=typeof window<"u"&&typeof window.orientation<"u",C=typeof process<"u"&&process.version&&/v([0-9]*)/.exec(process.version),Re=C&&parseFloat(C[1])||0;function x(t,e=!0,r){let o=r||new Set;if(t){if(B(t))o.add(t);else if(B(t.buffer))o.add(t.buffer);else if(!ArrayBuffer.isView(t)){if(e&&typeof t=="object")for(let a in t)x(t[a],e,o)}}return r===void 0?Array.from(o):[]}function B(t){return t?t instanceof ArrayBuffer||typeof MessagePort<"u"&&t instanceof MessagePort||typeof ImageBitmap<"u"&&t instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas:!1}async function g(){let parentPort;try{eval("globalThis.parentPort = require('worker_threads').parentPort"),parentPort=globalThis.parentPort}catch{try{eval("globalThis.workerThreadsPromise = import('worker_threads')");let workerThreads=await globalThis.workerThreadsPromise;parentPort=workerThreads.parentPort}catch(t){console.error(t.message)}}return parentPort}var M=new Map,l=class{static async inWorkerThread(){return typeof self<"u"||Boolean(await g())}static set onmessage(e){async function r(o){let a=await g(),{type:n,payload:s}=a?o:o.data;e(n,s)}g().then(o=>{o?(o.on("message",r),o.on("exit",()=>console.debug("Node worker closing"))):globalThis.onmessage=r})}static async addEventListener(e){let r=M.get(e);r||(r=async a=>{if(!oe(a))return;let n=await g(),{type:s,payload:i}=n?a:a.data;e(s,i)}),await g()?console.error("not implemented"):globalThis.addEventListener("message",r)}static async removeEventListener(e){let r=M.get(e);M.delete(e),await g()?console.error("not implemented"):globalThis.removeEventListener("message",r)}static async postMessage(e,r){let o={source:"loaders.gl",type:e,payload:r},a=x(r),n=await g();n?n.postMessage(o,a):globalThis.postMessage(o,a)}};function oe(t){let{type:e,data:r}=t;return e==="message"&&r&&typeof r.source=="string"&&r.source.startsWith("loaders.gl")}var p=te(k(),1);var w={};async function b(t,e=null,r={},o=null){return e&&(t=N(t,e,r,o)),w[t]=w[t]||ae(t),await w[t]}function N(t,e,r={},o=null){if(!r.useLocalLibraries&&t.startsWith("http"))return t;o=o||t;let a=r.modules||{};return a[o]?a[o]:A?r.CDN?(F(r.CDN.startsWith("http")),`${r.CDN}/${e}@${S}/dist/libs/${o}`):_?`../src/libs/${o}`:`modules/${e}/src/libs/${o}`:`modules/${e}/dist/libs/${o}`}async function ae(t){if(t.endsWith("wasm"))return await se(t);if(!A)try{return p&&void 0&&await(void 0)(t)}catch(r){return console.error(r),null}if(_)return importScripts(t);let e=await ie(t);return ne(e,t)}function ne(t,e){if(!A)return void 0&&(void 0)(t,e);if(_)return eval.call(globalThis,t),null;let r=document.createElement("script");r.id=e;try{r.appendChild(document.createTextNode(t))}catch{r.text=t}return document.body.appendChild(r),null}async function se(t){return A||!void 0||t.startsWith("http")?await(await fetch(t)).arrayBuffer():await(void 0)(t)}async function ie(t){return A||!void 0||t.startsWith("http")?await(await fetch(t)).text():await(void 0)(t)}var ce=0;async function O(t){await l.inWorkerThread()&&(l.onmessage=async(e,r)=>{switch(e){case"process":try{let{input:o,options:a={},context:n={}}=r,s=await ue({loader:t,arrayBuffer:o,options:a,context:{...n,_parse:de}});l.postMessage("done",{result:s})}catch(o){let a=o instanceof Error?o.message:"";l.postMessage("error",{error:a})}break;default:}})}function de(t,e,r,o){return new Promise((a,n)=>{let s=ce++,i=(f,d)=>{if(d.id===s)switch(f){case"done":l.removeEventListener(i),a(d.result);break;case"error":l.removeEventListener(i),n(d.error);break;default:}};l.addEventListener(i);let c={id:s,input:t,options:r};l.postMessage("process",c)})}async function ue({loader:t,arrayBuffer:e,options:r,context:o}){let a,n;if(t.parseSync||t.parse)a=e,n=t.parseSync||t.parse;else if(t.parseTextSync)a=new TextDecoder().decode(e),n=t.parseTextSync;else throw new Error(`Could not load data with ${t.name} loader`);return r={...r,modules:t&&t.options&&t.options.modules||{},worker:!1},await n(a,{...r},o,t)}var W="4.0.2";var le={draco:{decoderType:typeof WebAssembly=="object"?"wasm":"js",libraryPath:"libs/",extraAttributes:{},attributeNameEntry:void 0}},v={name:"Draco",id:"draco",module:"draco",version:W,worker:!0,extensions:["drc"],mimeTypes:["application/octet-stream"],binary:!0,tests:["DRACO"],options:le};function z(t){switch(t.constructor){case Int8Array:return"int8";case Uint8Array:case Uint8ClampedArray:return"uint8";case Int16Array:return"int16";case Uint16Array:return"uint16";case Int32Array:return"int32";case Uint32Array:return"uint32";case Float32Array:return"float32";case Float64Array:return"float64";default:return"null"}}function E(t){let e=1/0,r=1/0,o=1/0,a=-1/0,n=-1/0,s=-1/0,i=t.POSITION?t.POSITION.value:[],c=i&&i.length;for(let f=0;f<c;f+=3){let d=i[f],m=i[f+1],h=i[f+2];e=d<e?d:e,r=m<r?m:r,o=h<o?h:o,a=d>a?d:a,n=m>n?m:n,s=h>s?h:s}return[[e,r,o],[a,n,s]]}function L(t,e,r){let o=z(e.value),a=r||V(e);return{name:t,type:{type:"fixed-size-list",listSize:e.size,children:[{name:"value",type:o}]},nullable:!1,metadata:a}}function V(t){let e={};return"byteOffset"in t&&(e.byteOffset=t.byteOffset.toString(10)),"byteStride"in t&&(e.byteStride=t.byteStride.toString(10)),"normalized"in t&&(e.normalized=t.normalized.toString()),e}function U(t,e,r){let o=q(e.metadata),a=[],n=pe(e.attributes);for(let s in t){let i=t[s],c=G(s,i,n[s]);a.push(c)}if(r){let s=G("indices",r);a.push(s)}return{fields:a,metadata:o}}function pe(t){let e={};for(let r in t){let o=t[r];e[o.name||"undefined"]=o}return e}function G(t,e,r){let o=r?q(r.metadata):void 0;return L(t,e,o)}function q(t){Object.entries(t);let e={};for(let r in t)e[`${r}.string`]=JSON.stringify(t[r]);return e}var $={POSITION:"POSITION",NORMAL:"NORMAL",COLOR:"COLOR_0",TEX_COORD:"TEXCOORD_0"},fe={1:Int8Array,2:Uint8Array,3:Int16Array,4:Uint16Array,5:Int32Array,6:Uint32Array,9:Float32Array},ye=4,T=class{draco;decoder;metadataQuerier;constructor(e){this.draco=e,this.decoder=new this.draco.Decoder,this.metadataQuerier=new this.draco.MetadataQuerier}destroy(){this.draco.destroy(this.decoder),this.draco.destroy(this.metadataQuerier)}parseSync(e,r={}){let o=new this.draco.DecoderBuffer;o.Init(new Int8Array(e),e.byteLength),this._disableAttributeTransforms(r);let a=this.decoder.GetEncodedGeometryType(o),n=a===this.draco.TRIANGULAR_MESH?new this.draco.Mesh:new this.draco.PointCloud;try{let s;switch(a){case this.draco.TRIANGULAR_MESH:s=this.decoder.DecodeBufferToMesh(o,n);break;case this.draco.POINT_CLOUD:s=this.decoder.DecodeBufferToPointCloud(o,n);break;default:throw new Error("DRACO: Unknown geometry type.")}if(!s.ok()||!n.ptr){let h=`DRACO decompression failed: ${s.error_msg()}`;throw new Error(h)}let i=this._getDracoLoaderData(n,a,r),c=this._getMeshData(n,i,r),f=E(c.attributes),d=U(c.attributes,i,c.indices);return{loader:"draco",loaderData:i,header:{vertexCount:n.num_points(),boundingBox:f},...c,schema:d}}finally{this.draco.destroy(o),n&&this.draco.destroy(n)}}_getDracoLoaderData(e,r,o){let a=this._getTopLevelMetadata(e),n=this._getDracoAttributes(e,o);return{geometry_type:r,num_attributes:e.num_attributes(),num_points:e.num_points(),num_faces:e instanceof this.draco.Mesh?e.num_faces():0,metadata:a,attributes:n}}_getDracoAttributes(e,r){let o={};for(let a=0;a<e.num_attributes();a++){let n=this.decoder.GetAttribute(e,a),s=this._getAttributeMetadata(e,a);o[n.unique_id()]={unique_id:n.unique_id(),attribute_type:n.attribute_type(),data_type:n.data_type(),num_components:n.num_components(),byte_offset:n.byte_offset(),byte_stride:n.byte_stride(),normalized:n.normalized(),attribute_index:a,metadata:s};let i=this._getQuantizationTransform(n,r);i&&(o[n.unique_id()].quantization_transform=i);let c=this._getOctahedronTransform(n,r);c&&(o[n.unique_id()].octahedron_transform=c)}return o}_getMeshData(e,r,o){let a=this._getMeshAttributes(r,e,o);if(!a.POSITION)throw new Error("DRACO: No position attribute found.");if(e instanceof this.draco.Mesh)switch(o.topology){case"triangle-strip":return{topology:"triangle-strip",mode:4,attributes:a,indices:{value:this._getTriangleStripIndices(e),size:1}};case"triangle-list":default:return{topology:"triangle-list",mode:5,attributes:a,indices:{value:this._getTriangleListIndices(e),size:1}}}return{topology:"point-list",mode:0,attributes:a}}_getMeshAttributes(e,r,o){let a={};for(let n of Object.values(e.attributes)){let s=this._deduceAttributeName(n,o);n.name=s;let{value:i,size:c}=this._getAttributeValues(r,n);a[s]={value:i,size:c,byteOffset:n.byte_offset,byteStride:n.byte_stride,normalized:n.normalized}}return a}_getTriangleListIndices(e){let o=e.num_faces()*3,a=o*ye,n=this.draco._malloc(a);try{return this.decoder.GetTrianglesUInt32Array(e,a,n),new Uint32Array(this.draco.HEAPF32.buffer,n,o).slice()}finally{this.draco._free(n)}}_getTriangleStripIndices(e){let r=new this.draco.DracoInt32Array;try{return this.decoder.GetTriangleStripsFromMesh(e,r),he(r)}finally{this.draco.destroy(r)}}_getAttributeValues(e,r){let o=fe[r.data_type],a=r.num_components,s=e.num_points()*a,i=s*o.BYTES_PER_ELEMENT,c=me(this.draco,o),f,d=this.draco._malloc(i);try{let m=this.decoder.GetAttribute(e,r.attribute_index);this.decoder.GetAttributeDataArrayForAllPoints(e,m,c,i,d),f=new o(this.draco.HEAPF32.buffer,d,s).slice()}finally{this.draco._free(d)}return{value:f,size:a}}_deduceAttributeName(e,r){let o=e.unique_id;for(let[s,i]of Object.entries(r.extraAttributes||{}))if(i===o)return s;let a=e.attribute_type;for(let s in $)if(this.draco[s]===a)return $[s];let n=r.attributeNameEntry||"name";return e.metadata[n]?e.metadata[n].string:`CUSTOM_ATTRIBUTE_${o}`}_getTopLevelMetadata(e){let r=this.decoder.GetMetadata(e);return this._getDracoMetadata(r)}_getAttributeMetadata(e,r){let o=this.decoder.GetAttributeMetadata(e,r);return this._getDracoMetadata(o)}_getDracoMetadata(e){if(!e||!e.ptr)return{};let r={},o=this.metadataQuerier.NumEntries(e);for(let a=0;a<o;a++){let n=this.metadataQuerier.GetEntryName(e,a);r[n]=this._getDracoMetadataField(e,n)}return r}_getDracoMetadataField(e,r){let o=new this.draco.DracoInt32Array;try{this.metadataQuerier.GetIntEntryArray(e,r,o);let a=ge(o);return{int:this.metadataQuerier.GetIntEntry(e,r),string:this.metadataQuerier.GetStringEntry(e,r),double:this.metadataQuerier.GetDoubleEntry(e,r),intArray:a}}finally{this.draco.destroy(o)}}_disableAttributeTransforms(e){let{quantizedAttributes:r=[],octahedronAttributes:o=[]}=e,a=[...r,...o];for(let n of a)this.decoder.SkipAttributeTransform(this.draco[n])}_getQuantizationTransform(e,r){let{quantizedAttributes:o=[]}=r,a=e.attribute_type();if(o.map(s=>this.decoder[s]).includes(a)){let s=new this.draco.AttributeQuantizationTransform;try{if(s.InitFromAttribute(e))return{quantization_bits:s.quantization_bits(),range:s.range(),min_values:new Float32Array([1,2,3]).map(i=>s.min_value(i))}}finally{this.draco.destroy(s)}}return null}_getOctahedronTransform(e,r){let{octahedronAttributes:o=[]}=r,a=e.attribute_type();if(o.map(s=>this.decoder[s]).includes(a)){let s=new this.draco.AttributeQuantizationTransform;try{if(s.InitFromAttribute(e))return{quantization_bits:s.quantization_bits()}}finally{this.draco.destroy(s)}}return null}};function me(t,e){switch(e){case Float32Array:return t.DT_FLOAT32;case Int8Array:return t.DT_INT8;case Int16Array:return t.DT_INT16;case Int32Array:return t.DT_INT32;case Uint8Array:return t.DT_UINT8;case Uint16Array:return t.DT_UINT16;case Uint32Array:return t.DT_UINT32;default:return t.DT_INVALID}}function ge(t){let e=t.size(),r=new Int32Array(e);for(let o=0;o<e;o++)r[o]=t.GetValue(o);return r}function he(t){let e=t.size(),r=new Int32Array(e);for(let o=0;o<e;o++)r[o]=t.GetValue(o);return r}var Ae="1.5.6",be="1.4.1",I=`https://www.gstatic.com/draco/versioned/decoders/${Ae}`,u={DECODER:"draco_wasm_wrapper.js",DECODER_WASM:"draco_decoder.wasm",FALLBACK_DECODER:"draco_decoder.js",ENCODER:"draco_encoder.js"},P={[u.DECODER]:`${I}/${u.DECODER}`,[u.DECODER_WASM]:`${I}/${u.DECODER_WASM}`,[u.FALLBACK_DECODER]:`${I}/${u.FALLBACK_DECODER}`,[u.ENCODER]:`https://raw.githubusercontent.com/google/draco/${be}/javascript/${u.ENCODER}`},D;async function Q(t){let e=t.modules||{};return e.draco3d?D=D||e.draco3d.createDecoderModule({}).then(r=>({draco:r})):D=D||Te(t),await D}async function Te(t){let e,r;switch(t.draco&&t.draco.decoderType){case"js":e=await b(P[u.FALLBACK_DECODER],"draco",t,u.FALLBACK_DECODER);break;case"wasm":default:[e,r]=await Promise.all([await b(P[u.DECODER],"draco",t,u.DECODER),await b(P[u.DECODER_WASM],"draco",t,u.DECODER_WASM)])}return e=e||globalThis.DracoDecoderModule,await De(e,r)}function De(t,e){let r={};return e&&(r.wasmBinary=e),new Promise(o=>{t({...r,onModuleLoaded:a=>o({draco:a})})})}var j={...v,parse:_e};async function _e(t,e){let{draco:r}=await Q(e),o=new T(r);try{return o.parseSync(t,e?.draco)}finally{o.destroy()}}O(j);})();
1
+ "use strict";
2
+ (() => {
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __commonJS = (cb, mod) => function __require() {
10
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+
29
+ // (disabled):../worker-utils/src/lib/node/require-utils.node
30
+ var require_require_utils = __commonJS({
31
+ "(disabled):../worker-utils/src/lib/node/require-utils.node"() {
32
+ "use strict";
33
+ }
34
+ });
35
+
36
+ // ../worker-utils/src/lib/env-utils/version.ts
37
+ function getVersion() {
38
+ if (!globalThis._loadersgl_?.version) {
39
+ globalThis._loadersgl_ = globalThis._loadersgl_ || {};
40
+ if (false) {
41
+ console.warn(
42
+ "loaders.gl: The __VERSION__ variable is not injected using babel plugin. Latest unstable workers would be fetched from the CDN."
43
+ );
44
+ globalThis._loadersgl_.version = NPM_TAG;
45
+ } else {
46
+ globalThis._loadersgl_.version = "4.0.3";
47
+ }
48
+ }
49
+ return globalThis._loadersgl_.version;
50
+ }
51
+ var VERSION = getVersion();
52
+
53
+ // ../worker-utils/src/lib/env-utils/assert.ts
54
+ function assert(condition, message) {
55
+ if (!condition) {
56
+ throw new Error(message || "loaders.gl assertion failed.");
57
+ }
58
+ }
59
+
60
+ // ../worker-utils/src/lib/env-utils/globals.ts
61
+ var globals = {
62
+ self: typeof self !== "undefined" && self,
63
+ window: typeof window !== "undefined" && window,
64
+ global: typeof global !== "undefined" && global,
65
+ document: typeof document !== "undefined" && document
66
+ };
67
+ var self_ = globals.self || globals.window || globals.global || {};
68
+ var window_ = globals.window || globals.self || globals.global || {};
69
+ var global_ = globals.global || globals.self || globals.window || {};
70
+ var document_ = globals.document || {};
71
+ var isBrowser = (
72
+ // @ts-ignore process.browser
73
+ typeof process !== "object" || String(process) !== "[object process]" || process.browser
74
+ );
75
+ var isWorker = typeof importScripts === "function";
76
+ var isMobile = typeof window !== "undefined" && typeof window.orientation !== "undefined";
77
+ var matches = typeof process !== "undefined" && process.version && /v([0-9]*)/.exec(process.version);
78
+ var nodeVersion = matches && parseFloat(matches[1]) || 0;
79
+
80
+ // ../worker-utils/src/lib/worker-utils/get-transfer-list.ts
81
+ function getTransferList(object, recursive = true, transfers) {
82
+ const transfersSet = transfers || /* @__PURE__ */ new Set();
83
+ if (!object) {
84
+ } else if (isTransferable(object)) {
85
+ transfersSet.add(object);
86
+ } else if (isTransferable(object.buffer)) {
87
+ transfersSet.add(object.buffer);
88
+ } else if (ArrayBuffer.isView(object)) {
89
+ } else if (recursive && typeof object === "object") {
90
+ for (const key in object) {
91
+ getTransferList(object[key], recursive, transfersSet);
92
+ }
93
+ }
94
+ return transfers === void 0 ? Array.from(transfersSet) : [];
95
+ }
96
+ function isTransferable(object) {
97
+ if (!object) {
98
+ return false;
99
+ }
100
+ if (object instanceof ArrayBuffer) {
101
+ return true;
102
+ }
103
+ if (typeof MessagePort !== "undefined" && object instanceof MessagePort) {
104
+ return true;
105
+ }
106
+ if (typeof ImageBitmap !== "undefined" && object instanceof ImageBitmap) {
107
+ return true;
108
+ }
109
+ if (typeof OffscreenCanvas !== "undefined" && object instanceof OffscreenCanvas) {
110
+ return true;
111
+ }
112
+ return false;
113
+ }
114
+
115
+ // ../worker-utils/src/lib/worker-farm/worker-body.ts
116
+ async function getParentPort() {
117
+ let parentPort;
118
+ try {
119
+ eval("globalThis.parentPort = require('worker_threads').parentPort");
120
+ parentPort = globalThis.parentPort;
121
+ } catch {
122
+ try {
123
+ eval("globalThis.workerThreadsPromise = import('worker_threads')");
124
+ const workerThreads = await globalThis.workerThreadsPromise;
125
+ parentPort = workerThreads.parentPort;
126
+ } catch (error) {
127
+ console.error(error.message);
128
+ }
129
+ }
130
+ return parentPort;
131
+ }
132
+ var onMessageWrapperMap = /* @__PURE__ */ new Map();
133
+ var WorkerBody = class {
134
+ /** Check that we are actually in a worker thread */
135
+ static async inWorkerThread() {
136
+ return typeof self !== "undefined" || Boolean(await getParentPort());
137
+ }
138
+ /*
139
+ * (type: WorkerMessageType, payload: WorkerMessagePayload) => any
140
+ */
141
+ static set onmessage(onMessage) {
142
+ async function handleMessage(message) {
143
+ const parentPort2 = await getParentPort();
144
+ const { type, payload } = parentPort2 ? message : message.data;
145
+ onMessage(type, payload);
146
+ }
147
+ getParentPort().then((parentPort2) => {
148
+ if (parentPort2) {
149
+ parentPort2.on("message", handleMessage);
150
+ parentPort2.on("exit", () => console.debug("Node worker closing"));
151
+ } else {
152
+ globalThis.onmessage = handleMessage;
153
+ }
154
+ });
155
+ }
156
+ static async addEventListener(onMessage) {
157
+ let onMessageWrapper = onMessageWrapperMap.get(onMessage);
158
+ if (!onMessageWrapper) {
159
+ onMessageWrapper = async (message) => {
160
+ if (!isKnownMessage(message)) {
161
+ return;
162
+ }
163
+ const parentPort3 = await getParentPort();
164
+ const { type, payload } = parentPort3 ? message : message.data;
165
+ onMessage(type, payload);
166
+ };
167
+ }
168
+ const parentPort2 = await getParentPort();
169
+ if (parentPort2) {
170
+ console.error("not implemented");
171
+ } else {
172
+ globalThis.addEventListener("message", onMessageWrapper);
173
+ }
174
+ }
175
+ static async removeEventListener(onMessage) {
176
+ const onMessageWrapper = onMessageWrapperMap.get(onMessage);
177
+ onMessageWrapperMap.delete(onMessage);
178
+ const parentPort2 = await getParentPort();
179
+ if (parentPort2) {
180
+ console.error("not implemented");
181
+ } else {
182
+ globalThis.removeEventListener("message", onMessageWrapper);
183
+ }
184
+ }
185
+ /**
186
+ * Send a message from a worker to creating thread (main thread)
187
+ * @param type
188
+ * @param payload
189
+ */
190
+ static async postMessage(type, payload) {
191
+ const data = { source: "loaders.gl", type, payload };
192
+ const transferList = getTransferList(payload);
193
+ const parentPort2 = await getParentPort();
194
+ if (parentPort2) {
195
+ parentPort2.postMessage(data, transferList);
196
+ } else {
197
+ globalThis.postMessage(data, transferList);
198
+ }
199
+ }
200
+ };
201
+ function isKnownMessage(message) {
202
+ const { type, data } = message;
203
+ return type === "message" && data && typeof data.source === "string" && data.source.startsWith("loaders.gl");
204
+ }
205
+
206
+ // ../worker-utils/src/lib/library-utils/library-utils.ts
207
+ var node = __toESM(require_require_utils(), 1);
208
+ var loadLibraryPromises = {};
209
+ async function loadLibrary(libraryUrl, moduleName = null, options = {}, libraryName = null) {
210
+ if (moduleName) {
211
+ libraryUrl = getLibraryUrl(libraryUrl, moduleName, options, libraryName);
212
+ }
213
+ loadLibraryPromises[libraryUrl] = // eslint-disable-next-line @typescript-eslint/no-misused-promises
214
+ loadLibraryPromises[libraryUrl] || loadLibraryFromFile(libraryUrl);
215
+ return await loadLibraryPromises[libraryUrl];
216
+ }
217
+ function getLibraryUrl(library, moduleName, options = {}, libraryName = null) {
218
+ if (!options.useLocalLibraries && library.startsWith("http")) {
219
+ return library;
220
+ }
221
+ libraryName = libraryName || library;
222
+ const modules = options.modules || {};
223
+ if (modules[libraryName]) {
224
+ return modules[libraryName];
225
+ }
226
+ if (!isBrowser) {
227
+ return `modules/${moduleName}/dist/libs/${libraryName}`;
228
+ }
229
+ if (options.CDN) {
230
+ assert(options.CDN.startsWith("http"));
231
+ return `${options.CDN}/${moduleName}@${VERSION}/dist/libs/${libraryName}`;
232
+ }
233
+ if (isWorker) {
234
+ return `../src/libs/${libraryName}`;
235
+ }
236
+ return `modules/${moduleName}/src/libs/${libraryName}`;
237
+ }
238
+ async function loadLibraryFromFile(libraryUrl) {
239
+ if (libraryUrl.endsWith("wasm")) {
240
+ return await loadAsArrayBuffer(libraryUrl);
241
+ }
242
+ if (!isBrowser) {
243
+ try {
244
+ return node && void 0 && await (void 0)(libraryUrl);
245
+ } catch (error) {
246
+ console.error(error);
247
+ return null;
248
+ }
249
+ }
250
+ if (isWorker) {
251
+ return importScripts(libraryUrl);
252
+ }
253
+ const scriptSource = await loadAsText(libraryUrl);
254
+ return loadLibraryFromString(scriptSource, libraryUrl);
255
+ }
256
+ function loadLibraryFromString(scriptSource, id) {
257
+ if (!isBrowser) {
258
+ return void 0 && (void 0)(scriptSource, id);
259
+ }
260
+ if (isWorker) {
261
+ eval.call(globalThis, scriptSource);
262
+ return null;
263
+ }
264
+ const script = document.createElement("script");
265
+ script.id = id;
266
+ try {
267
+ script.appendChild(document.createTextNode(scriptSource));
268
+ } catch (e) {
269
+ script.text = scriptSource;
270
+ }
271
+ document.body.appendChild(script);
272
+ return null;
273
+ }
274
+ async function loadAsArrayBuffer(url) {
275
+ if (isBrowser || !void 0 || url.startsWith("http")) {
276
+ const response = await fetch(url);
277
+ return await response.arrayBuffer();
278
+ }
279
+ return await (void 0)(url);
280
+ }
281
+ async function loadAsText(url) {
282
+ if (isBrowser || !void 0 || url.startsWith("http")) {
283
+ const response = await fetch(url);
284
+ return await response.text();
285
+ }
286
+ return await (void 0)(url);
287
+ }
288
+
289
+ // ../loader-utils/src/lib/worker-loader-utils/create-loader-worker.ts
290
+ var requestId = 0;
291
+ async function createLoaderWorker(loader) {
292
+ if (!await WorkerBody.inWorkerThread()) {
293
+ return;
294
+ }
295
+ WorkerBody.onmessage = async (type, payload) => {
296
+ switch (type) {
297
+ case "process":
298
+ try {
299
+ const { input, options = {}, context = {} } = payload;
300
+ const result = await parseData({
301
+ loader,
302
+ arrayBuffer: input,
303
+ options,
304
+ // @ts-expect-error fetch missing
305
+ context: {
306
+ ...context,
307
+ _parse: parseOnMainThread
308
+ }
309
+ });
310
+ WorkerBody.postMessage("done", { result });
311
+ } catch (error) {
312
+ const message = error instanceof Error ? error.message : "";
313
+ WorkerBody.postMessage("error", { error: message });
314
+ }
315
+ break;
316
+ default:
317
+ }
318
+ };
319
+ }
320
+ function parseOnMainThread(arrayBuffer, loader, options, context) {
321
+ return new Promise((resolve, reject) => {
322
+ const id = requestId++;
323
+ const onMessage = (type, payload2) => {
324
+ if (payload2.id !== id) {
325
+ return;
326
+ }
327
+ switch (type) {
328
+ case "done":
329
+ WorkerBody.removeEventListener(onMessage);
330
+ resolve(payload2.result);
331
+ break;
332
+ case "error":
333
+ WorkerBody.removeEventListener(onMessage);
334
+ reject(payload2.error);
335
+ break;
336
+ default:
337
+ }
338
+ };
339
+ WorkerBody.addEventListener(onMessage);
340
+ const payload = { id, input: arrayBuffer, options };
341
+ WorkerBody.postMessage("process", payload);
342
+ });
343
+ }
344
+ async function parseData({
345
+ loader,
346
+ arrayBuffer,
347
+ options,
348
+ context
349
+ }) {
350
+ let data;
351
+ let parser;
352
+ if (loader.parseSync || loader.parse) {
353
+ data = arrayBuffer;
354
+ parser = loader.parseSync || loader.parse;
355
+ } else if (loader.parseTextSync) {
356
+ const textDecoder = new TextDecoder();
357
+ data = textDecoder.decode(arrayBuffer);
358
+ parser = loader.parseTextSync;
359
+ } else {
360
+ throw new Error(`Could not load data with ${loader.name} loader`);
361
+ }
362
+ options = {
363
+ ...options,
364
+ modules: loader && loader.options && loader.options.modules || {},
365
+ worker: false
366
+ };
367
+ return await parser(data, { ...options }, context, loader);
368
+ }
369
+
370
+ // src/lib/utils/version.ts
371
+ var VERSION2 = true ? "4.0.3" : "latest";
372
+
373
+ // src/draco-loader.ts
374
+ var DEFAULT_DRACO_OPTIONS = {
375
+ draco: {
376
+ decoderType: typeof WebAssembly === "object" ? "wasm" : "js",
377
+ // 'js' for IE11
378
+ libraryPath: "libs/",
379
+ extraAttributes: {},
380
+ attributeNameEntry: void 0
381
+ }
382
+ };
383
+ var DracoLoader = {
384
+ name: "Draco",
385
+ id: "draco",
386
+ module: "draco",
387
+ // shapes: ['mesh'],
388
+ version: VERSION2,
389
+ worker: true,
390
+ extensions: ["drc"],
391
+ mimeTypes: ["application/octet-stream"],
392
+ binary: true,
393
+ tests: ["DRACO"],
394
+ options: DEFAULT_DRACO_OPTIONS
395
+ };
396
+
397
+ // ../schema/src/lib/table/simple-table/data-type.ts
398
+ function getDataTypeFromTypedArray(array) {
399
+ switch (array.constructor) {
400
+ case Int8Array:
401
+ return "int8";
402
+ case Uint8Array:
403
+ case Uint8ClampedArray:
404
+ return "uint8";
405
+ case Int16Array:
406
+ return "int16";
407
+ case Uint16Array:
408
+ return "uint16";
409
+ case Int32Array:
410
+ return "int32";
411
+ case Uint32Array:
412
+ return "uint32";
413
+ case Float32Array:
414
+ return "float32";
415
+ case Float64Array:
416
+ return "float64";
417
+ default:
418
+ return "null";
419
+ }
420
+ }
421
+
422
+ // ../schema/src/lib/mesh/mesh-utils.ts
423
+ function getMeshBoundingBox(attributes) {
424
+ let minX = Infinity;
425
+ let minY = Infinity;
426
+ let minZ = Infinity;
427
+ let maxX = -Infinity;
428
+ let maxY = -Infinity;
429
+ let maxZ = -Infinity;
430
+ const positions = attributes.POSITION ? attributes.POSITION.value : [];
431
+ const len = positions && positions.length;
432
+ for (let i = 0; i < len; i += 3) {
433
+ const x = positions[i];
434
+ const y = positions[i + 1];
435
+ const z = positions[i + 2];
436
+ minX = x < minX ? x : minX;
437
+ minY = y < minY ? y : minY;
438
+ minZ = z < minZ ? z : minZ;
439
+ maxX = x > maxX ? x : maxX;
440
+ maxY = y > maxY ? y : maxY;
441
+ maxZ = z > maxZ ? z : maxZ;
442
+ }
443
+ return [
444
+ [minX, minY, minZ],
445
+ [maxX, maxY, maxZ]
446
+ ];
447
+ }
448
+
449
+ // ../schema/src/lib/mesh/deduce-mesh-schema.ts
450
+ function deduceMeshField(name, attribute, optionalMetadata) {
451
+ const type = getDataTypeFromTypedArray(attribute.value);
452
+ const metadata = optionalMetadata ? optionalMetadata : makeMeshAttributeMetadata(attribute);
453
+ return {
454
+ name,
455
+ type: { type: "fixed-size-list", listSize: attribute.size, children: [{ name: "value", type }] },
456
+ nullable: false,
457
+ metadata
458
+ };
459
+ }
460
+ function makeMeshAttributeMetadata(attribute) {
461
+ const result = {};
462
+ if ("byteOffset" in attribute) {
463
+ result.byteOffset = attribute.byteOffset.toString(10);
464
+ }
465
+ if ("byteStride" in attribute) {
466
+ result.byteStride = attribute.byteStride.toString(10);
467
+ }
468
+ if ("normalized" in attribute) {
469
+ result.normalized = attribute.normalized.toString();
470
+ }
471
+ return result;
472
+ }
473
+
474
+ // src/lib/utils/get-draco-schema.ts
475
+ function getDracoSchema(attributes, loaderData, indices) {
476
+ const metadata = makeMetadata(loaderData.metadata);
477
+ const fields = [];
478
+ const namedLoaderDataAttributes = transformAttributesLoaderData(loaderData.attributes);
479
+ for (const attributeName in attributes) {
480
+ const attribute = attributes[attributeName];
481
+ const field = getArrowFieldFromAttribute(
482
+ attributeName,
483
+ attribute,
484
+ namedLoaderDataAttributes[attributeName]
485
+ );
486
+ fields.push(field);
487
+ }
488
+ if (indices) {
489
+ const indicesField = getArrowFieldFromAttribute("indices", indices);
490
+ fields.push(indicesField);
491
+ }
492
+ return { fields, metadata };
493
+ }
494
+ function transformAttributesLoaderData(loaderData) {
495
+ const result = {};
496
+ for (const key in loaderData) {
497
+ const dracoAttribute = loaderData[key];
498
+ result[dracoAttribute.name || "undefined"] = dracoAttribute;
499
+ }
500
+ return result;
501
+ }
502
+ function getArrowFieldFromAttribute(attributeName, attribute, loaderData) {
503
+ const metadataMap = loaderData ? makeMetadata(loaderData.metadata) : void 0;
504
+ const field = deduceMeshField(attributeName, attribute, metadataMap);
505
+ return field;
506
+ }
507
+ function makeMetadata(metadata) {
508
+ Object.entries(metadata);
509
+ const serializedMetadata = {};
510
+ for (const key in metadata) {
511
+ serializedMetadata[`${key}.string`] = JSON.stringify(metadata[key]);
512
+ }
513
+ return serializedMetadata;
514
+ }
515
+
516
+ // src/lib/draco-parser.ts
517
+ var DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP = {
518
+ POSITION: "POSITION",
519
+ NORMAL: "NORMAL",
520
+ COLOR: "COLOR_0",
521
+ TEX_COORD: "TEXCOORD_0"
522
+ };
523
+ var DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP = {
524
+ 1: Int8Array,
525
+ 2: Uint8Array,
526
+ 3: Int16Array,
527
+ 4: Uint16Array,
528
+ 5: Int32Array,
529
+ 6: Uint32Array,
530
+ 9: Float32Array
531
+ };
532
+ var INDEX_ITEM_SIZE = 4;
533
+ var DracoParser = class {
534
+ draco;
535
+ decoder;
536
+ metadataQuerier;
537
+ // draco - the draco decoder, either import `draco3d` or load dynamically
538
+ constructor(draco) {
539
+ this.draco = draco;
540
+ this.decoder = new this.draco.Decoder();
541
+ this.metadataQuerier = new this.draco.MetadataQuerier();
542
+ }
543
+ /**
544
+ * Destroy draco resources
545
+ */
546
+ destroy() {
547
+ this.draco.destroy(this.decoder);
548
+ this.draco.destroy(this.metadataQuerier);
549
+ }
550
+ /**
551
+ * NOTE: caller must call `destroyGeometry` on the return value after using it
552
+ * @param arrayBuffer
553
+ * @param options
554
+ */
555
+ parseSync(arrayBuffer, options = {}) {
556
+ const buffer = new this.draco.DecoderBuffer();
557
+ buffer.Init(new Int8Array(arrayBuffer), arrayBuffer.byteLength);
558
+ this._disableAttributeTransforms(options);
559
+ const geometry_type = this.decoder.GetEncodedGeometryType(buffer);
560
+ const dracoGeometry = geometry_type === this.draco.TRIANGULAR_MESH ? new this.draco.Mesh() : new this.draco.PointCloud();
561
+ try {
562
+ let dracoStatus;
563
+ switch (geometry_type) {
564
+ case this.draco.TRIANGULAR_MESH:
565
+ dracoStatus = this.decoder.DecodeBufferToMesh(buffer, dracoGeometry);
566
+ break;
567
+ case this.draco.POINT_CLOUD:
568
+ dracoStatus = this.decoder.DecodeBufferToPointCloud(buffer, dracoGeometry);
569
+ break;
570
+ default:
571
+ throw new Error("DRACO: Unknown geometry type.");
572
+ }
573
+ if (!dracoStatus.ok() || !dracoGeometry.ptr) {
574
+ const message = `DRACO decompression failed: ${dracoStatus.error_msg()}`;
575
+ throw new Error(message);
576
+ }
577
+ const loaderData = this._getDracoLoaderData(dracoGeometry, geometry_type, options);
578
+ const geometry = this._getMeshData(dracoGeometry, loaderData, options);
579
+ const boundingBox = getMeshBoundingBox(geometry.attributes);
580
+ const schema = getDracoSchema(geometry.attributes, loaderData, geometry.indices);
581
+ const data = {
582
+ loader: "draco",
583
+ loaderData,
584
+ header: {
585
+ vertexCount: dracoGeometry.num_points(),
586
+ boundingBox
587
+ },
588
+ ...geometry,
589
+ schema
590
+ };
591
+ return data;
592
+ } finally {
593
+ this.draco.destroy(buffer);
594
+ if (dracoGeometry) {
595
+ this.draco.destroy(dracoGeometry);
596
+ }
597
+ }
598
+ }
599
+ // Draco specific "loader data"
600
+ /**
601
+ * Extract
602
+ * @param dracoGeometry
603
+ * @param geometry_type
604
+ * @param options
605
+ * @returns
606
+ */
607
+ _getDracoLoaderData(dracoGeometry, geometry_type, options) {
608
+ const metadata = this._getTopLevelMetadata(dracoGeometry);
609
+ const attributes = this._getDracoAttributes(dracoGeometry, options);
610
+ return {
611
+ geometry_type,
612
+ num_attributes: dracoGeometry.num_attributes(),
613
+ num_points: dracoGeometry.num_points(),
614
+ num_faces: dracoGeometry instanceof this.draco.Mesh ? dracoGeometry.num_faces() : 0,
615
+ metadata,
616
+ attributes
617
+ };
618
+ }
619
+ /**
620
+ * Extract all draco provided information and metadata for each attribute
621
+ * @param dracoGeometry
622
+ * @param options
623
+ * @returns
624
+ */
625
+ _getDracoAttributes(dracoGeometry, options) {
626
+ const dracoAttributes = {};
627
+ for (let attributeId = 0; attributeId < dracoGeometry.num_attributes(); attributeId++) {
628
+ const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attributeId);
629
+ const metadata = this._getAttributeMetadata(dracoGeometry, attributeId);
630
+ dracoAttributes[dracoAttribute.unique_id()] = {
631
+ unique_id: dracoAttribute.unique_id(),
632
+ attribute_type: dracoAttribute.attribute_type(),
633
+ data_type: dracoAttribute.data_type(),
634
+ num_components: dracoAttribute.num_components(),
635
+ byte_offset: dracoAttribute.byte_offset(),
636
+ byte_stride: dracoAttribute.byte_stride(),
637
+ normalized: dracoAttribute.normalized(),
638
+ attribute_index: attributeId,
639
+ metadata
640
+ };
641
+ const quantization = this._getQuantizationTransform(dracoAttribute, options);
642
+ if (quantization) {
643
+ dracoAttributes[dracoAttribute.unique_id()].quantization_transform = quantization;
644
+ }
645
+ const octahedron = this._getOctahedronTransform(dracoAttribute, options);
646
+ if (octahedron) {
647
+ dracoAttributes[dracoAttribute.unique_id()].octahedron_transform = octahedron;
648
+ }
649
+ }
650
+ return dracoAttributes;
651
+ }
652
+ /**
653
+ * Get standard loaders.gl mesh category data
654
+ * Extracts the geometry from draco
655
+ * @param dracoGeometry
656
+ * @param options
657
+ */
658
+ _getMeshData(dracoGeometry, loaderData, options) {
659
+ const attributes = this._getMeshAttributes(loaderData, dracoGeometry, options);
660
+ const positionAttribute = attributes.POSITION;
661
+ if (!positionAttribute) {
662
+ throw new Error("DRACO: No position attribute found.");
663
+ }
664
+ if (dracoGeometry instanceof this.draco.Mesh) {
665
+ switch (options.topology) {
666
+ case "triangle-strip":
667
+ return {
668
+ topology: "triangle-strip",
669
+ mode: 4,
670
+ // GL.TRIANGLES
671
+ attributes,
672
+ indices: {
673
+ value: this._getTriangleStripIndices(dracoGeometry),
674
+ size: 1
675
+ }
676
+ };
677
+ case "triangle-list":
678
+ default:
679
+ return {
680
+ topology: "triangle-list",
681
+ mode: 5,
682
+ // GL.TRIANGLE_STRIP
683
+ attributes,
684
+ indices: {
685
+ value: this._getTriangleListIndices(dracoGeometry),
686
+ size: 1
687
+ }
688
+ };
689
+ }
690
+ }
691
+ return {
692
+ topology: "point-list",
693
+ mode: 0,
694
+ // GL.POINTS
695
+ attributes
696
+ };
697
+ }
698
+ _getMeshAttributes(loaderData, dracoGeometry, options) {
699
+ const attributes = {};
700
+ for (const loaderAttribute of Object.values(loaderData.attributes)) {
701
+ const attributeName = this._deduceAttributeName(loaderAttribute, options);
702
+ loaderAttribute.name = attributeName;
703
+ const { value, size } = this._getAttributeValues(dracoGeometry, loaderAttribute);
704
+ attributes[attributeName] = {
705
+ value,
706
+ size,
707
+ byteOffset: loaderAttribute.byte_offset,
708
+ byteStride: loaderAttribute.byte_stride,
709
+ normalized: loaderAttribute.normalized
710
+ };
711
+ }
712
+ return attributes;
713
+ }
714
+ // MESH INDICES EXTRACTION
715
+ /**
716
+ * For meshes, we need indices to define the faces.
717
+ * @param dracoGeometry
718
+ */
719
+ _getTriangleListIndices(dracoGeometry) {
720
+ const numFaces = dracoGeometry.num_faces();
721
+ const numIndices = numFaces * 3;
722
+ const byteLength = numIndices * INDEX_ITEM_SIZE;
723
+ const ptr = this.draco._malloc(byteLength);
724
+ try {
725
+ this.decoder.GetTrianglesUInt32Array(dracoGeometry, byteLength, ptr);
726
+ return new Uint32Array(this.draco.HEAPF32.buffer, ptr, numIndices).slice();
727
+ } finally {
728
+ this.draco._free(ptr);
729
+ }
730
+ }
731
+ /**
732
+ * For meshes, we need indices to define the faces.
733
+ * @param dracoGeometry
734
+ */
735
+ _getTriangleStripIndices(dracoGeometry) {
736
+ const dracoArray = new this.draco.DracoInt32Array();
737
+ try {
738
+ this.decoder.GetTriangleStripsFromMesh(dracoGeometry, dracoArray);
739
+ return getUint32Array(dracoArray);
740
+ } finally {
741
+ this.draco.destroy(dracoArray);
742
+ }
743
+ }
744
+ /**
745
+ *
746
+ * @param dracoGeometry
747
+ * @param dracoAttribute
748
+ * @param attributeName
749
+ */
750
+ _getAttributeValues(dracoGeometry, attribute) {
751
+ const TypedArrayCtor = DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP[attribute.data_type];
752
+ const numComponents = attribute.num_components;
753
+ const numPoints = dracoGeometry.num_points();
754
+ const numValues = numPoints * numComponents;
755
+ const byteLength = numValues * TypedArrayCtor.BYTES_PER_ELEMENT;
756
+ const dataType = getDracoDataType(this.draco, TypedArrayCtor);
757
+ let value;
758
+ const ptr = this.draco._malloc(byteLength);
759
+ try {
760
+ const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attribute.attribute_index);
761
+ this.decoder.GetAttributeDataArrayForAllPoints(
762
+ dracoGeometry,
763
+ dracoAttribute,
764
+ dataType,
765
+ byteLength,
766
+ ptr
767
+ );
768
+ value = new TypedArrayCtor(this.draco.HEAPF32.buffer, ptr, numValues).slice();
769
+ } finally {
770
+ this.draco._free(ptr);
771
+ }
772
+ return { value, size: numComponents };
773
+ }
774
+ // Attribute names
775
+ /**
776
+ * DRACO does not store attribute names - We need to deduce an attribute name
777
+ * for each attribute
778
+ _getAttributeNames(
779
+ dracoGeometry: Mesh | PointCloud,
780
+ options: DracoParseOptions
781
+ ): {[unique_id: number]: string} {
782
+ const attributeNames: {[unique_id: number]: string} = {};
783
+ for (let attributeId = 0; attributeId < dracoGeometry.num_attributes(); attributeId++) {
784
+ const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attributeId);
785
+ const attributeName = this._deduceAttributeName(dracoAttribute, options);
786
+ attributeNames[attributeName] = attributeName;
787
+ }
788
+ return attributeNames;
789
+ }
790
+ */
791
+ /**
792
+ * Deduce an attribute name.
793
+ * @note DRACO does not save attribute names, just general type (POSITION, COLOR)
794
+ * to help optimize compression. We generate GLTF compatible names for the Draco-recognized
795
+ * types
796
+ * @param attributeData
797
+ */
798
+ _deduceAttributeName(attribute, options) {
799
+ const uniqueId = attribute.unique_id;
800
+ for (const [attributeName, attributeUniqueId] of Object.entries(
801
+ options.extraAttributes || {}
802
+ )) {
803
+ if (attributeUniqueId === uniqueId) {
804
+ return attributeName;
805
+ }
806
+ }
807
+ const thisAttributeType = attribute.attribute_type;
808
+ for (const dracoAttributeConstant in DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP) {
809
+ const attributeType = this.draco[dracoAttributeConstant];
810
+ if (attributeType === thisAttributeType) {
811
+ return DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP[dracoAttributeConstant];
812
+ }
813
+ }
814
+ const entryName = options.attributeNameEntry || "name";
815
+ if (attribute.metadata[entryName]) {
816
+ return attribute.metadata[entryName].string;
817
+ }
818
+ return `CUSTOM_ATTRIBUTE_${uniqueId}`;
819
+ }
820
+ // METADATA EXTRACTION
821
+ /** Get top level metadata */
822
+ _getTopLevelMetadata(dracoGeometry) {
823
+ const dracoMetadata = this.decoder.GetMetadata(dracoGeometry);
824
+ return this._getDracoMetadata(dracoMetadata);
825
+ }
826
+ /** Get per attribute metadata */
827
+ _getAttributeMetadata(dracoGeometry, attributeId) {
828
+ const dracoMetadata = this.decoder.GetAttributeMetadata(dracoGeometry, attributeId);
829
+ return this._getDracoMetadata(dracoMetadata);
830
+ }
831
+ /**
832
+ * Extract metadata field values
833
+ * @param dracoMetadata
834
+ * @returns
835
+ */
836
+ _getDracoMetadata(dracoMetadata) {
837
+ if (!dracoMetadata || !dracoMetadata.ptr) {
838
+ return {};
839
+ }
840
+ const result = {};
841
+ const numEntries = this.metadataQuerier.NumEntries(dracoMetadata);
842
+ for (let entryIndex = 0; entryIndex < numEntries; entryIndex++) {
843
+ const entryName = this.metadataQuerier.GetEntryName(dracoMetadata, entryIndex);
844
+ result[entryName] = this._getDracoMetadataField(dracoMetadata, entryName);
845
+ }
846
+ return result;
847
+ }
848
+ /**
849
+ * Extracts possible values for one metadata entry by name
850
+ * @param dracoMetadata
851
+ * @param entryName
852
+ */
853
+ _getDracoMetadataField(dracoMetadata, entryName) {
854
+ const dracoArray = new this.draco.DracoInt32Array();
855
+ try {
856
+ this.metadataQuerier.GetIntEntryArray(dracoMetadata, entryName, dracoArray);
857
+ const intArray = getInt32Array(dracoArray);
858
+ return {
859
+ int: this.metadataQuerier.GetIntEntry(dracoMetadata, entryName),
860
+ string: this.metadataQuerier.GetStringEntry(dracoMetadata, entryName),
861
+ double: this.metadataQuerier.GetDoubleEntry(dracoMetadata, entryName),
862
+ intArray
863
+ };
864
+ } finally {
865
+ this.draco.destroy(dracoArray);
866
+ }
867
+ }
868
+ // QUANTIZED ATTRIBUTE SUPPORT (NO DECOMPRESSION)
869
+ /** Skip transforms for specific attribute types */
870
+ _disableAttributeTransforms(options) {
871
+ const { quantizedAttributes = [], octahedronAttributes = [] } = options;
872
+ const skipAttributes = [...quantizedAttributes, ...octahedronAttributes];
873
+ for (const dracoAttributeName of skipAttributes) {
874
+ this.decoder.SkipAttributeTransform(this.draco[dracoAttributeName]);
875
+ }
876
+ }
877
+ /**
878
+ * Extract (and apply?) Position Transform
879
+ * @todo not used
880
+ */
881
+ _getQuantizationTransform(dracoAttribute, options) {
882
+ const { quantizedAttributes = [] } = options;
883
+ const attribute_type = dracoAttribute.attribute_type();
884
+ const skip = quantizedAttributes.map((type) => this.decoder[type]).includes(attribute_type);
885
+ if (skip) {
886
+ const transform = new this.draco.AttributeQuantizationTransform();
887
+ try {
888
+ if (transform.InitFromAttribute(dracoAttribute)) {
889
+ return {
890
+ quantization_bits: transform.quantization_bits(),
891
+ range: transform.range(),
892
+ min_values: new Float32Array([1, 2, 3]).map((i) => transform.min_value(i))
893
+ };
894
+ }
895
+ } finally {
896
+ this.draco.destroy(transform);
897
+ }
898
+ }
899
+ return null;
900
+ }
901
+ _getOctahedronTransform(dracoAttribute, options) {
902
+ const { octahedronAttributes = [] } = options;
903
+ const attribute_type = dracoAttribute.attribute_type();
904
+ const octahedron = octahedronAttributes.map((type) => this.decoder[type]).includes(attribute_type);
905
+ if (octahedron) {
906
+ const transform = new this.draco.AttributeQuantizationTransform();
907
+ try {
908
+ if (transform.InitFromAttribute(dracoAttribute)) {
909
+ return {
910
+ quantization_bits: transform.quantization_bits()
911
+ };
912
+ }
913
+ } finally {
914
+ this.draco.destroy(transform);
915
+ }
916
+ }
917
+ return null;
918
+ }
919
+ // HELPERS
920
+ };
921
+ function getDracoDataType(draco, attributeType) {
922
+ switch (attributeType) {
923
+ case Float32Array:
924
+ return draco.DT_FLOAT32;
925
+ case Int8Array:
926
+ return draco.DT_INT8;
927
+ case Int16Array:
928
+ return draco.DT_INT16;
929
+ case Int32Array:
930
+ return draco.DT_INT32;
931
+ case Uint8Array:
932
+ return draco.DT_UINT8;
933
+ case Uint16Array:
934
+ return draco.DT_UINT16;
935
+ case Uint32Array:
936
+ return draco.DT_UINT32;
937
+ default:
938
+ return draco.DT_INVALID;
939
+ }
940
+ }
941
+ function getInt32Array(dracoArray) {
942
+ const numValues = dracoArray.size();
943
+ const intArray = new Int32Array(numValues);
944
+ for (let i = 0; i < numValues; i++) {
945
+ intArray[i] = dracoArray.GetValue(i);
946
+ }
947
+ return intArray;
948
+ }
949
+ function getUint32Array(dracoArray) {
950
+ const numValues = dracoArray.size();
951
+ const intArray = new Int32Array(numValues);
952
+ for (let i = 0; i < numValues; i++) {
953
+ intArray[i] = dracoArray.GetValue(i);
954
+ }
955
+ return intArray;
956
+ }
957
+
958
+ // src/lib/draco-module-loader.ts
959
+ var DRACO_DECODER_VERSION = "1.5.6";
960
+ var DRACO_ENCODER_VERSION = "1.4.1";
961
+ var STATIC_DECODER_URL = `https://www.gstatic.com/draco/versioned/decoders/${DRACO_DECODER_VERSION}`;
962
+ var DRACO_EXTERNAL_LIBRARIES = {
963
+ /** The primary Draco3D encoder, javascript wrapper part */
964
+ DECODER: "draco_wasm_wrapper.js",
965
+ /** The primary draco decoder, compiled web assembly part */
966
+ DECODER_WASM: "draco_decoder.wasm",
967
+ /** Fallback decoder for non-webassebly environments. Very big bundle, lower performance */
968
+ FALLBACK_DECODER: "draco_decoder.js",
969
+ /** Draco encoder */
970
+ ENCODER: "draco_encoder.js"
971
+ };
972
+ var DRACO_EXTERNAL_LIBRARY_URLS = {
973
+ [DRACO_EXTERNAL_LIBRARIES.DECODER]: `${STATIC_DECODER_URL}/${DRACO_EXTERNAL_LIBRARIES.DECODER}`,
974
+ [DRACO_EXTERNAL_LIBRARIES.DECODER_WASM]: `${STATIC_DECODER_URL}/${DRACO_EXTERNAL_LIBRARIES.DECODER_WASM}`,
975
+ [DRACO_EXTERNAL_LIBRARIES.FALLBACK_DECODER]: `${STATIC_DECODER_URL}/${DRACO_EXTERNAL_LIBRARIES.FALLBACK_DECODER}`,
976
+ [DRACO_EXTERNAL_LIBRARIES.ENCODER]: `https://raw.githubusercontent.com/google/draco/${DRACO_ENCODER_VERSION}/javascript/${DRACO_EXTERNAL_LIBRARIES.ENCODER}`
977
+ };
978
+ var loadDecoderPromise;
979
+ async function loadDracoDecoderModule(options) {
980
+ const modules = options.modules || {};
981
+ if (modules.draco3d) {
982
+ loadDecoderPromise = loadDecoderPromise || modules.draco3d.createDecoderModule({}).then((draco) => {
983
+ return { draco };
984
+ });
985
+ } else {
986
+ loadDecoderPromise = loadDecoderPromise || loadDracoDecoder(options);
987
+ }
988
+ return await loadDecoderPromise;
989
+ }
990
+ async function loadDracoDecoder(options) {
991
+ let DracoDecoderModule;
992
+ let wasmBinary;
993
+ switch (options.draco && options.draco.decoderType) {
994
+ case "js":
995
+ DracoDecoderModule = await loadLibrary(
996
+ DRACO_EXTERNAL_LIBRARY_URLS[DRACO_EXTERNAL_LIBRARIES.FALLBACK_DECODER],
997
+ "draco",
998
+ options,
999
+ DRACO_EXTERNAL_LIBRARIES.FALLBACK_DECODER
1000
+ );
1001
+ break;
1002
+ case "wasm":
1003
+ default:
1004
+ [DracoDecoderModule, wasmBinary] = await Promise.all([
1005
+ await loadLibrary(
1006
+ DRACO_EXTERNAL_LIBRARY_URLS[DRACO_EXTERNAL_LIBRARIES.DECODER],
1007
+ "draco",
1008
+ options,
1009
+ DRACO_EXTERNAL_LIBRARIES.DECODER
1010
+ ),
1011
+ await loadLibrary(
1012
+ DRACO_EXTERNAL_LIBRARY_URLS[DRACO_EXTERNAL_LIBRARIES.DECODER_WASM],
1013
+ "draco",
1014
+ options,
1015
+ DRACO_EXTERNAL_LIBRARIES.DECODER_WASM
1016
+ )
1017
+ ]);
1018
+ }
1019
+ DracoDecoderModule = DracoDecoderModule || globalThis.DracoDecoderModule;
1020
+ return await initializeDracoDecoder(DracoDecoderModule, wasmBinary);
1021
+ }
1022
+ function initializeDracoDecoder(DracoDecoderModule, wasmBinary) {
1023
+ const options = {};
1024
+ if (wasmBinary) {
1025
+ options.wasmBinary = wasmBinary;
1026
+ }
1027
+ return new Promise((resolve) => {
1028
+ DracoDecoderModule({
1029
+ ...options,
1030
+ onModuleLoaded: (draco) => resolve({ draco })
1031
+ // Module is Promise-like. Wrap in object to avoid loop.
1032
+ });
1033
+ });
1034
+ }
1035
+
1036
+ // src/index.ts
1037
+ var DracoLoader2 = {
1038
+ ...DracoLoader,
1039
+ parse
1040
+ };
1041
+ async function parse(arrayBuffer, options) {
1042
+ const { draco } = await loadDracoDecoderModule(options);
1043
+ const dracoParser = new DracoParser(draco);
1044
+ try {
1045
+ return dracoParser.parseSync(arrayBuffer, options?.draco);
1046
+ } finally {
1047
+ dracoParser.destroy();
1048
+ }
1049
+ }
1050
+
1051
+ // src/workers/draco-worker.ts
1052
+ createLoaderWorker(DracoLoader2);
1053
+ })();
2
1054
  //# sourceMappingURL=draco-worker.js.map