@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,4 +1,721 @@
1
- "use strict";(()=>{var S=Object.create;var O=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var $=Object.getPrototypeOf,v=Object.prototype.hasOwnProperty;var V=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var G=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of F(e))!v.call(r,a)&&a!==t&&O(r,a,{get:()=>e[a],enumerable:!(o=N(e,a))||o.enumerable});return r};var j=(r,e,t)=>(t=r!=null?S($(r)):{},G(e||!r||!r.__esModule?O(t,"default",{value:r,enumerable:!0}):t,r));var B=V(()=>{"use strict"});function q(){return globalThis._loadersgl_?.version||(globalThis._loadersgl_=globalThis._loadersgl_||{},globalThis._loadersgl_.version="4.0.2"),globalThis._loadersgl_.version}var b=q();function T(r,e){if(!r)throw new Error(e||"loaders.gl assertion failed.")}var l={self:typeof self<"u"&&self,window:typeof window<"u"&&window,global:typeof global<"u"&&global,document:typeof document<"u"&&document},ie=l.self||l.window||l.global||{},de=l.window||l.self||l.global||{},ce=l.global||l.self||l.window||{},le=l.document||{};var h=typeof process!="object"||String(process)!=="[object process]"||process.browser,E=typeof importScripts=="function",ue=typeof window<"u"&&typeof window.orientation<"u",R=typeof process<"u"&&process.version&&/v([0-9]*)/.exec(process.version),fe=R&&parseFloat(R[1])||0;function A(r,e=!0,t){let o=t||new Set;if(r){if(P(r))o.add(r);else if(P(r.buffer))o.add(r.buffer);else if(!ArrayBuffer.isView(r)){if(e&&typeof r=="object")for(let a in r)A(r[a],e,o)}}return t===void 0?Array.from(o):[]}function P(r){return r?r instanceof ArrayBuffer||typeof MessagePort<"u"&&r instanceof MessagePort||typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas:!1}async function y(){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(r){console.error(r.message)}}return parentPort}var D=new Map,f=class{static async inWorkerThread(){return typeof self<"u"||Boolean(await y())}static set onmessage(e){async function t(o){let a=await y(),{type:s,payload:i}=a?o:o.data;e(s,i)}y().then(o=>{o?(o.on("message",t),o.on("exit",()=>console.debug("Node worker closing"))):globalThis.onmessage=t})}static async addEventListener(e){let t=D.get(e);t||(t=async a=>{if(!z(a))return;let s=await y(),{type:i,payload:n}=s?a:a.data;e(i,n)}),await y()?console.error("not implemented"):globalThis.addEventListener("message",t)}static async removeEventListener(e){let t=D.get(e);D.delete(e),await y()?console.error("not implemented"):globalThis.removeEventListener("message",t)}static async postMessage(e,t){let o={source:"loaders.gl",type:e,payload:t},a=A(t),s=await y();s?s.postMessage(o,a):globalThis.postMessage(o,a)}};function z(r){let{type:e,data:t}=r;return e==="message"&&t&&typeof t.source=="string"&&t.source.startsWith("loaders.gl")}var d=j(B(),1);var _={};async function M(r,e=null,t={},o=null){return e&&(r=C(r,e,t,o)),_[r]=_[r]||U(r),await _[r]}function C(r,e,t={},o=null){if(!t.useLocalLibraries&&r.startsWith("http"))return r;o=o||r;let a=t.modules||{};return a[o]?a[o]:h?t.CDN?(T(t.CDN.startsWith("http")),`${t.CDN}/${e}@${b}/dist/libs/${o}`):E?`../src/libs/${o}`:`modules/${e}/src/libs/${o}`:`modules/${e}/dist/libs/${o}`}async function U(r){if(r.endsWith("wasm"))return await X(r);if(!h)try{return d&&void 0&&await(void 0)(r)}catch(t){return console.error(t),null}if(E)return importScripts(r);let e=await Q(r);return K(e,r)}function K(r,e){if(!h)return void 0&&(void 0)(r,e);if(E)return eval.call(globalThis,r),null;let t=document.createElement("script");t.id=e;try{t.appendChild(document.createTextNode(r))}catch{t.text=r}return document.body.appendChild(t),null}async function X(r){return h||!void 0||r.startsWith("http")?await(await fetch(r)).arrayBuffer():await(void 0)(r)}async function Q(r){return h||!void 0||r.startsWith("http")?await(await fetch(r)).text():await(void 0)(r)}var W={POSITION:"POSITION",NORMAL:"NORMAL",COLOR_0:"COLOR",TEXCOORD_0:"TEX_COORD"},H=()=>{},g=class{draco;dracoEncoder;dracoMeshBuilder;dracoMetadataBuilder;log;constructor(e){this.draco=e,this.dracoEncoder=new this.draco.Encoder,this.dracoMeshBuilder=new this.draco.MeshBuilder,this.dracoMetadataBuilder=new this.draco.MetadataBuilder}destroy(){this.destroyEncodedObject(this.dracoMeshBuilder),this.destroyEncodedObject(this.dracoEncoder),this.destroyEncodedObject(this.dracoMetadataBuilder),this.dracoMeshBuilder=null,this.dracoEncoder=null,this.draco=null}destroyEncodedObject(e){e&&this.draco.destroy(e)}encodeSync(e,t={}){return this.log=H,this._setOptions(t),t.pointcloud?this._encodePointCloud(e,t):this._encodeMesh(e,t)}_getAttributesFromMesh(e){let t={...e,...e.attributes};return e.indices&&(t.indices=e.indices),t}_encodePointCloud(e,t){let o=new this.draco.PointCloud;t.metadata&&this._addGeometryMetadata(o,t.metadata);let a=this._getAttributesFromMesh(e);this._createDracoPointCloud(o,a,t);let s=new this.draco.DracoInt8Array;try{let i=this.dracoEncoder.EncodePointCloudToDracoBuffer(o,!1,s);if(!(i>0))throw new Error("Draco encoding failed.");return this.log(`DRACO encoded ${o.num_points()} points
2
- with ${o.num_attributes()} attributes into ${i} bytes`),I(s)}finally{this.destroyEncodedObject(s),this.destroyEncodedObject(o)}}_encodeMesh(e,t){let o=new this.draco.Mesh;t.metadata&&this._addGeometryMetadata(o,t.metadata);let a=this._getAttributesFromMesh(e);this._createDracoMesh(o,a,t);let s=new this.draco.DracoInt8Array;try{let i=this.dracoEncoder.EncodeMeshToDracoBuffer(o,s);if(i<=0)throw new Error("Draco encoding failed.");return this.log(`DRACO encoded ${o.num_points()} points
3
- with ${o.num_attributes()} attributes into ${i} bytes`),I(s)}finally{this.destroyEncodedObject(s),this.destroyEncodedObject(o)}}_setOptions(e){if("speed"in e&&this.dracoEncoder.SetSpeedOptions(...e.speed),"method"in e){let t=this.draco[e.method||"MESH_SEQUENTIAL_ENCODING"];this.dracoEncoder.SetEncodingMethod(t)}if("quantization"in e)for(let t in e.quantization){let o=e.quantization[t],a=this.draco[t];this.dracoEncoder.SetAttributeQuantization(a,o)}}_createDracoMesh(e,t,o){let a=o.attributesMetadata||{};try{let s=this._getPositionAttribute(t);if(!s)throw new Error("positions");let i=s.length/3;for(let n in t){let c=t[n];n=W[n]||n;let p=this._addAttributeToMesh(e,n,c,i);p!==-1&&this._addAttributeMetadata(e,p,{name:n,...a[n]||{}})}}catch(s){throw this.destroyEncodedObject(e),s}return e}_createDracoPointCloud(e,t,o){let a=o.attributesMetadata||{};try{let s=this._getPositionAttribute(t);if(!s)throw new Error("positions");let i=s.length/3;for(let n in t){let c=t[n];n=W[n]||n;let p=this._addAttributeToMesh(e,n,c,i);p!==-1&&this._addAttributeMetadata(e,p,{name:n,...a[n]||{}})}}catch(s){throw this.destroyEncodedObject(e),s}return e}_addAttributeToMesh(e,t,o,a){if(!ArrayBuffer.isView(o))return-1;let s=this._getDracoAttributeType(t),i=o.length/a;if(s==="indices"){let p=o.length/3;return this.log(`Adding attribute ${t}, size ${p}`),this.dracoMeshBuilder.AddFacesToMesh(e,p,o),-1}this.log(`Adding attribute ${t}, size ${i}`);let n=this.dracoMeshBuilder,{buffer:c}=o;switch(o.constructor){case Int8Array:return n.AddInt8Attribute(e,s,a,i,new Int8Array(c));case Int16Array:return n.AddInt16Attribute(e,s,a,i,new Int16Array(c));case Int32Array:return n.AddInt32Attribute(e,s,a,i,new Int32Array(c));case Uint8Array:case Uint8ClampedArray:return n.AddUInt8Attribute(e,s,a,i,new Uint8Array(c));case Uint16Array:return n.AddUInt16Attribute(e,s,a,i,new Uint16Array(c));case Uint32Array:return n.AddUInt32Attribute(e,s,a,i,new Uint32Array(c));case Float32Array:default:return n.AddFloatAttribute(e,s,a,i,new Float32Array(c))}}_getDracoAttributeType(e){switch(e.toLowerCase()){case"indices":return"indices";case"position":case"positions":case"vertices":return this.draco.POSITION;case"normal":case"normals":return this.draco.NORMAL;case"color":case"colors":return this.draco.COLOR;case"texcoord":case"texcoords":return this.draco.TEX_COORD;default:return this.draco.GENERIC}}_getPositionAttribute(e){for(let t in e){let o=e[t];if(this._getDracoAttributeType(t)===this.draco.POSITION)return o}return null}_addGeometryMetadata(e,t){let o=new this.draco.Metadata;this._populateDracoMetadata(o,t),this.dracoMeshBuilder.AddMetadata(e,o)}_addAttributeMetadata(e,t,o){let a=new this.draco.Metadata;this._populateDracoMetadata(a,o),this.dracoMeshBuilder.SetMetadataForAttribute(e,t,a)}_populateDracoMetadata(e,t){for(let[o,a]of J(t))switch(typeof a){case"number":Math.trunc(a)===a?this.dracoMetadataBuilder.AddIntEntry(e,o,a):this.dracoMetadataBuilder.AddDoubleEntry(e,o,a);break;case"object":a instanceof Int32Array&&this.dracoMetadataBuilder.AddIntEntryArray(e,o,a,a.length);break;case"string":default:this.dracoMetadataBuilder.AddStringEntry(e,o,a)}}};function I(r){let e=r.size(),t=new ArrayBuffer(e),o=new Int8Array(t);for(let a=0;a<e;++a)o[a]=r.GetValue(a);return t}function J(r){return r.entries&&!r.hasOwnProperty("entries")?r.entries():Object.entries(r)}var Y="1.5.6",Z="1.4.1",w=`https://www.gstatic.com/draco/versioned/decoders/${Y}`,u={DECODER:"draco_wasm_wrapper.js",DECODER_WASM:"draco_decoder.wasm",FALLBACK_DECODER:"draco_decoder.js",ENCODER:"draco_encoder.js"},ee={[u.DECODER]:`${w}/${u.DECODER}`,[u.DECODER_WASM]:`${w}/${u.DECODER_WASM}`,[u.FALLBACK_DECODER]:`${w}/${u.FALLBACK_DECODER}`,[u.ENCODER]:`https://raw.githubusercontent.com/google/draco/${Z}/javascript/${u.ENCODER}`};var m;async function k(r){let e=r.modules||{};return e.draco3d?m=m||e.draco3d.createEncoderModule({}).then(t=>({draco:t})):m=m||te(r),await m}async function te(r){let e=await M(ee[u.ENCODER],"draco",r,u.ENCODER);return e=e||globalThis.DracoEncoderModule,new Promise(t=>{e({onModuleLoaded:o=>t({draco:o})})})}var L="4.0.2";var re={pointcloud:!1,attributeNameEntry:"name"},x={name:"DRACO",id:"draco",module:"draco",version:L,extensions:["drc"],options:{draco:re},encode:oe};async function oe(r,e={}){let{draco:t}=await k(e),o=new g(t);try{return o.encodeSync(r,e.draco)}finally{o.destroy()}}(async()=>await f.inWorkerThread()&&(f.onmessage=async(r,e)=>{switch(r){case"process":try{let{input:t,options:o}=e,a=await x.encode(t,o);f.postMessage("done",{result:a})}catch(t){let o=t instanceof Error?t.message:"";f.postMessage("error",{error:o})}break;default:}}))();})();
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
+ // src/lib/draco-builder.ts
290
+ var GLTF_TO_DRACO_ATTRIBUTE_NAME_MAP = {
291
+ POSITION: "POSITION",
292
+ NORMAL: "NORMAL",
293
+ COLOR_0: "COLOR",
294
+ TEXCOORD_0: "TEX_COORD"
295
+ };
296
+ var noop = () => {
297
+ };
298
+ var DracoBuilder = class {
299
+ draco;
300
+ dracoEncoder;
301
+ dracoMeshBuilder;
302
+ dracoMetadataBuilder;
303
+ log;
304
+ // draco - the draco decoder, either import `draco3d` or load dynamically
305
+ constructor(draco) {
306
+ this.draco = draco;
307
+ this.dracoEncoder = new this.draco.Encoder();
308
+ this.dracoMeshBuilder = new this.draco.MeshBuilder();
309
+ this.dracoMetadataBuilder = new this.draco.MetadataBuilder();
310
+ }
311
+ destroy() {
312
+ this.destroyEncodedObject(this.dracoMeshBuilder);
313
+ this.destroyEncodedObject(this.dracoEncoder);
314
+ this.destroyEncodedObject(this.dracoMetadataBuilder);
315
+ this.dracoMeshBuilder = null;
316
+ this.dracoEncoder = null;
317
+ this.draco = null;
318
+ }
319
+ // TBD - when does this need to be called?
320
+ destroyEncodedObject(object) {
321
+ if (object) {
322
+ this.draco.destroy(object);
323
+ }
324
+ }
325
+ /**
326
+ * Encode mesh or point cloud
327
+ * @param mesh =({})
328
+ * @param options
329
+ */
330
+ encodeSync(mesh, options = {}) {
331
+ this.log = noop;
332
+ this._setOptions(options);
333
+ return options.pointcloud ? this._encodePointCloud(mesh, options) : this._encodeMesh(mesh, options);
334
+ }
335
+ // PRIVATE
336
+ _getAttributesFromMesh(mesh) {
337
+ const attributes = { ...mesh, ...mesh.attributes };
338
+ if (mesh.indices) {
339
+ attributes.indices = mesh.indices;
340
+ }
341
+ return attributes;
342
+ }
343
+ _encodePointCloud(pointcloud, options) {
344
+ const dracoPointCloud = new this.draco.PointCloud();
345
+ if (options.metadata) {
346
+ this._addGeometryMetadata(dracoPointCloud, options.metadata);
347
+ }
348
+ const attributes = this._getAttributesFromMesh(pointcloud);
349
+ this._createDracoPointCloud(dracoPointCloud, attributes, options);
350
+ const dracoData = new this.draco.DracoInt8Array();
351
+ try {
352
+ const encodedLen = this.dracoEncoder.EncodePointCloudToDracoBuffer(
353
+ dracoPointCloud,
354
+ false,
355
+ dracoData
356
+ );
357
+ if (!(encodedLen > 0)) {
358
+ throw new Error("Draco encoding failed.");
359
+ }
360
+ this.log(`DRACO encoded ${dracoPointCloud.num_points()} points
361
+ with ${dracoPointCloud.num_attributes()} attributes into ${encodedLen} bytes`);
362
+ return dracoInt8ArrayToArrayBuffer(dracoData);
363
+ } finally {
364
+ this.destroyEncodedObject(dracoData);
365
+ this.destroyEncodedObject(dracoPointCloud);
366
+ }
367
+ }
368
+ _encodeMesh(mesh, options) {
369
+ const dracoMesh = new this.draco.Mesh();
370
+ if (options.metadata) {
371
+ this._addGeometryMetadata(dracoMesh, options.metadata);
372
+ }
373
+ const attributes = this._getAttributesFromMesh(mesh);
374
+ this._createDracoMesh(dracoMesh, attributes, options);
375
+ const dracoData = new this.draco.DracoInt8Array();
376
+ try {
377
+ const encodedLen = this.dracoEncoder.EncodeMeshToDracoBuffer(dracoMesh, dracoData);
378
+ if (encodedLen <= 0) {
379
+ throw new Error("Draco encoding failed.");
380
+ }
381
+ this.log(`DRACO encoded ${dracoMesh.num_points()} points
382
+ with ${dracoMesh.num_attributes()} attributes into ${encodedLen} bytes`);
383
+ return dracoInt8ArrayToArrayBuffer(dracoData);
384
+ } finally {
385
+ this.destroyEncodedObject(dracoData);
386
+ this.destroyEncodedObject(dracoMesh);
387
+ }
388
+ }
389
+ /**
390
+ * Set encoding options.
391
+ * @param {{speed?: any; method?: any; quantization?: any;}} options
392
+ */
393
+ _setOptions(options) {
394
+ if ("speed" in options) {
395
+ this.dracoEncoder.SetSpeedOptions(...options.speed);
396
+ }
397
+ if ("method" in options) {
398
+ const dracoMethod = this.draco[options.method || "MESH_SEQUENTIAL_ENCODING"];
399
+ this.dracoEncoder.SetEncodingMethod(dracoMethod);
400
+ }
401
+ if ("quantization" in options) {
402
+ for (const attribute in options.quantization) {
403
+ const bits = options.quantization[attribute];
404
+ const dracoPosition = this.draco[attribute];
405
+ this.dracoEncoder.SetAttributeQuantization(dracoPosition, bits);
406
+ }
407
+ }
408
+ }
409
+ /**
410
+ * @param {Mesh} dracoMesh
411
+ * @param {object} attributes
412
+ * @returns {Mesh}
413
+ */
414
+ _createDracoMesh(dracoMesh, attributes, options) {
415
+ const optionalMetadata = options.attributesMetadata || {};
416
+ try {
417
+ const positions = this._getPositionAttribute(attributes);
418
+ if (!positions) {
419
+ throw new Error("positions");
420
+ }
421
+ const vertexCount = positions.length / 3;
422
+ for (let attributeName in attributes) {
423
+ const attribute = attributes[attributeName];
424
+ attributeName = GLTF_TO_DRACO_ATTRIBUTE_NAME_MAP[attributeName] || attributeName;
425
+ const uniqueId = this._addAttributeToMesh(dracoMesh, attributeName, attribute, vertexCount);
426
+ if (uniqueId !== -1) {
427
+ this._addAttributeMetadata(dracoMesh, uniqueId, {
428
+ name: attributeName,
429
+ ...optionalMetadata[attributeName] || {}
430
+ });
431
+ }
432
+ }
433
+ } catch (error) {
434
+ this.destroyEncodedObject(dracoMesh);
435
+ throw error;
436
+ }
437
+ return dracoMesh;
438
+ }
439
+ /**
440
+ * @param {} dracoPointCloud
441
+ * @param {object} attributes
442
+ */
443
+ _createDracoPointCloud(dracoPointCloud, attributes, options) {
444
+ const optionalMetadata = options.attributesMetadata || {};
445
+ try {
446
+ const positions = this._getPositionAttribute(attributes);
447
+ if (!positions) {
448
+ throw new Error("positions");
449
+ }
450
+ const vertexCount = positions.length / 3;
451
+ for (let attributeName in attributes) {
452
+ const attribute = attributes[attributeName];
453
+ attributeName = GLTF_TO_DRACO_ATTRIBUTE_NAME_MAP[attributeName] || attributeName;
454
+ const uniqueId = this._addAttributeToMesh(
455
+ dracoPointCloud,
456
+ attributeName,
457
+ attribute,
458
+ vertexCount
459
+ );
460
+ if (uniqueId !== -1) {
461
+ this._addAttributeMetadata(dracoPointCloud, uniqueId, {
462
+ name: attributeName,
463
+ ...optionalMetadata[attributeName] || {}
464
+ });
465
+ }
466
+ }
467
+ } catch (error) {
468
+ this.destroyEncodedObject(dracoPointCloud);
469
+ throw error;
470
+ }
471
+ return dracoPointCloud;
472
+ }
473
+ /**
474
+ * @param mesh
475
+ * @param attributeName
476
+ * @param attribute
477
+ * @param vertexCount
478
+ */
479
+ _addAttributeToMesh(mesh, attributeName, attribute, vertexCount) {
480
+ if (!ArrayBuffer.isView(attribute)) {
481
+ return -1;
482
+ }
483
+ const type = this._getDracoAttributeType(attributeName);
484
+ const size = attribute.length / vertexCount;
485
+ if (type === "indices") {
486
+ const numFaces = attribute.length / 3;
487
+ this.log(`Adding attribute ${attributeName}, size ${numFaces}`);
488
+ this.dracoMeshBuilder.AddFacesToMesh(mesh, numFaces, attribute);
489
+ return -1;
490
+ }
491
+ this.log(`Adding attribute ${attributeName}, size ${size}`);
492
+ const builder = this.dracoMeshBuilder;
493
+ const { buffer } = attribute;
494
+ switch (attribute.constructor) {
495
+ case Int8Array:
496
+ return builder.AddInt8Attribute(mesh, type, vertexCount, size, new Int8Array(buffer));
497
+ case Int16Array:
498
+ return builder.AddInt16Attribute(mesh, type, vertexCount, size, new Int16Array(buffer));
499
+ case Int32Array:
500
+ return builder.AddInt32Attribute(mesh, type, vertexCount, size, new Int32Array(buffer));
501
+ case Uint8Array:
502
+ case Uint8ClampedArray:
503
+ return builder.AddUInt8Attribute(mesh, type, vertexCount, size, new Uint8Array(buffer));
504
+ case Uint16Array:
505
+ return builder.AddUInt16Attribute(mesh, type, vertexCount, size, new Uint16Array(buffer));
506
+ case Uint32Array:
507
+ return builder.AddUInt32Attribute(mesh, type, vertexCount, size, new Uint32Array(buffer));
508
+ case Float32Array:
509
+ default:
510
+ return builder.AddFloatAttribute(mesh, type, vertexCount, size, new Float32Array(buffer));
511
+ }
512
+ }
513
+ /**
514
+ * DRACO can compress attributes of know type better
515
+ * TODO - expose an attribute type map?
516
+ * @param attributeName
517
+ */
518
+ _getDracoAttributeType(attributeName) {
519
+ switch (attributeName.toLowerCase()) {
520
+ case "indices":
521
+ return "indices";
522
+ case "position":
523
+ case "positions":
524
+ case "vertices":
525
+ return this.draco.POSITION;
526
+ case "normal":
527
+ case "normals":
528
+ return this.draco.NORMAL;
529
+ case "color":
530
+ case "colors":
531
+ return this.draco.COLOR;
532
+ case "texcoord":
533
+ case "texcoords":
534
+ return this.draco.TEX_COORD;
535
+ default:
536
+ return this.draco.GENERIC;
537
+ }
538
+ }
539
+ _getPositionAttribute(attributes) {
540
+ for (const attributeName in attributes) {
541
+ const attribute = attributes[attributeName];
542
+ const dracoType = this._getDracoAttributeType(attributeName);
543
+ if (dracoType === this.draco.POSITION) {
544
+ return attribute;
545
+ }
546
+ }
547
+ return null;
548
+ }
549
+ /**
550
+ * Add metadata for the geometry.
551
+ * @param dracoGeometry - WASM Draco Object
552
+ * @param metadata
553
+ */
554
+ _addGeometryMetadata(dracoGeometry, metadata) {
555
+ const dracoMetadata = new this.draco.Metadata();
556
+ this._populateDracoMetadata(dracoMetadata, metadata);
557
+ this.dracoMeshBuilder.AddMetadata(dracoGeometry, dracoMetadata);
558
+ }
559
+ /**
560
+ * Add metadata for an attribute to geometry.
561
+ * @param dracoGeometry - WASM Draco Object
562
+ * @param uniqueAttributeId
563
+ * @param metadata
564
+ */
565
+ _addAttributeMetadata(dracoGeometry, uniqueAttributeId, metadata) {
566
+ const dracoAttributeMetadata = new this.draco.Metadata();
567
+ this._populateDracoMetadata(dracoAttributeMetadata, metadata);
568
+ this.dracoMeshBuilder.SetMetadataForAttribute(
569
+ dracoGeometry,
570
+ uniqueAttributeId,
571
+ dracoAttributeMetadata
572
+ );
573
+ }
574
+ /**
575
+ * Add contents of object or map to a WASM Draco Metadata Object
576
+ * @param dracoMetadata - WASM Draco Object
577
+ * @param metadata
578
+ */
579
+ _populateDracoMetadata(dracoMetadata, metadata) {
580
+ for (const [key, value] of getEntries(metadata)) {
581
+ switch (typeof value) {
582
+ case "number":
583
+ if (Math.trunc(value) === value) {
584
+ this.dracoMetadataBuilder.AddIntEntry(dracoMetadata, key, value);
585
+ } else {
586
+ this.dracoMetadataBuilder.AddDoubleEntry(dracoMetadata, key, value);
587
+ }
588
+ break;
589
+ case "object":
590
+ if (value instanceof Int32Array) {
591
+ this.dracoMetadataBuilder.AddIntEntryArray(dracoMetadata, key, value, value.length);
592
+ }
593
+ break;
594
+ case "string":
595
+ default:
596
+ this.dracoMetadataBuilder.AddStringEntry(dracoMetadata, key, value);
597
+ }
598
+ }
599
+ }
600
+ };
601
+ function dracoInt8ArrayToArrayBuffer(dracoData) {
602
+ const byteLength = dracoData.size();
603
+ const outputBuffer = new ArrayBuffer(byteLength);
604
+ const outputData = new Int8Array(outputBuffer);
605
+ for (let i = 0; i < byteLength; ++i) {
606
+ outputData[i] = dracoData.GetValue(i);
607
+ }
608
+ return outputBuffer;
609
+ }
610
+ function getEntries(container) {
611
+ const hasEntriesFunc = container.entries && !container.hasOwnProperty("entries");
612
+ return hasEntriesFunc ? container.entries() : Object.entries(container);
613
+ }
614
+
615
+ // src/lib/draco-module-loader.ts
616
+ var DRACO_DECODER_VERSION = "1.5.6";
617
+ var DRACO_ENCODER_VERSION = "1.4.1";
618
+ var STATIC_DECODER_URL = `https://www.gstatic.com/draco/versioned/decoders/${DRACO_DECODER_VERSION}`;
619
+ var DRACO_EXTERNAL_LIBRARIES = {
620
+ /** The primary Draco3D encoder, javascript wrapper part */
621
+ DECODER: "draco_wasm_wrapper.js",
622
+ /** The primary draco decoder, compiled web assembly part */
623
+ DECODER_WASM: "draco_decoder.wasm",
624
+ /** Fallback decoder for non-webassebly environments. Very big bundle, lower performance */
625
+ FALLBACK_DECODER: "draco_decoder.js",
626
+ /** Draco encoder */
627
+ ENCODER: "draco_encoder.js"
628
+ };
629
+ var DRACO_EXTERNAL_LIBRARY_URLS = {
630
+ [DRACO_EXTERNAL_LIBRARIES.DECODER]: `${STATIC_DECODER_URL}/${DRACO_EXTERNAL_LIBRARIES.DECODER}`,
631
+ [DRACO_EXTERNAL_LIBRARIES.DECODER_WASM]: `${STATIC_DECODER_URL}/${DRACO_EXTERNAL_LIBRARIES.DECODER_WASM}`,
632
+ [DRACO_EXTERNAL_LIBRARIES.FALLBACK_DECODER]: `${STATIC_DECODER_URL}/${DRACO_EXTERNAL_LIBRARIES.FALLBACK_DECODER}`,
633
+ [DRACO_EXTERNAL_LIBRARIES.ENCODER]: `https://raw.githubusercontent.com/google/draco/${DRACO_ENCODER_VERSION}/javascript/${DRACO_EXTERNAL_LIBRARIES.ENCODER}`
634
+ };
635
+ var loadEncoderPromise;
636
+ async function loadDracoEncoderModule(options) {
637
+ const modules = options.modules || {};
638
+ if (modules.draco3d) {
639
+ loadEncoderPromise = loadEncoderPromise || modules.draco3d.createEncoderModule({}).then((draco) => {
640
+ return { draco };
641
+ });
642
+ } else {
643
+ loadEncoderPromise = loadEncoderPromise || loadDracoEncoder(options);
644
+ }
645
+ return await loadEncoderPromise;
646
+ }
647
+ async function loadDracoEncoder(options) {
648
+ let DracoEncoderModule = await loadLibrary(
649
+ DRACO_EXTERNAL_LIBRARY_URLS[DRACO_EXTERNAL_LIBRARIES.ENCODER],
650
+ "draco",
651
+ options,
652
+ DRACO_EXTERNAL_LIBRARIES.ENCODER
653
+ );
654
+ DracoEncoderModule = DracoEncoderModule || globalThis.DracoEncoderModule;
655
+ return new Promise((resolve) => {
656
+ DracoEncoderModule({
657
+ onModuleLoaded: (draco) => resolve({ draco })
658
+ // Module is Promise-like. Wrap in object to avoid loop.
659
+ });
660
+ });
661
+ }
662
+
663
+ // src/lib/utils/version.ts
664
+ var VERSION2 = true ? "4.0.3" : "latest";
665
+
666
+ // src/draco-writer.ts
667
+ var DEFAULT_DRACO_WRITER_OPTIONS = {
668
+ pointcloud: false,
669
+ // Set to true if pointcloud (mode: 0, no indices)
670
+ attributeNameEntry: "name"
671
+ // Draco Compression Parameters
672
+ // method: 'MESH_EDGEBREAKER_ENCODING', // Use draco defaults
673
+ // speed: [5, 5], // Use draco defaults
674
+ // quantization: { // Use draco defaults
675
+ // POSITION: 10
676
+ // }
677
+ };
678
+ var DracoWriter = {
679
+ name: "DRACO",
680
+ id: "draco",
681
+ module: "draco",
682
+ version: VERSION2,
683
+ extensions: ["drc"],
684
+ options: {
685
+ draco: DEFAULT_DRACO_WRITER_OPTIONS
686
+ },
687
+ encode
688
+ };
689
+ async function encode(data, options = {}) {
690
+ const { draco } = await loadDracoEncoderModule(options);
691
+ const dracoBuilder = new DracoBuilder(draco);
692
+ try {
693
+ return dracoBuilder.encodeSync(data, options.draco);
694
+ } finally {
695
+ dracoBuilder.destroy();
696
+ }
697
+ }
698
+
699
+ // src/workers/draco-writer-worker.ts
700
+ (async () => {
701
+ if (!await WorkerBody.inWorkerThread()) {
702
+ return;
703
+ }
704
+ WorkerBody.onmessage = async (type, payload) => {
705
+ switch (type) {
706
+ case "process":
707
+ try {
708
+ const { input, options } = payload;
709
+ const result = await DracoWriter.encode(input, options);
710
+ WorkerBody.postMessage("done", { result });
711
+ } catch (error) {
712
+ const message = error instanceof Error ? error.message : "";
713
+ WorkerBody.postMessage("error", { error: message });
714
+ }
715
+ break;
716
+ default:
717
+ }
718
+ };
719
+ })();
720
+ })();
4
721
  //# sourceMappingURL=draco-writer-worker.js.map