@maptalks/gl
Version:
WebGL infrastrcture for maptalks
585 lines (510 loc) • 1.4 MB
JavaScript
/*!
* @maptalks/gl v0.108.4
* LICENSE : UNLICENSED
* (c) 2016-2025 maptalks.com
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('maptalks')) :
typeof define === 'function' && define.amd ? define(['exports', 'maptalks'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.maptalks = global.maptalks || {}, global.maptalks));
})(this, (function (exports, t$1) { 'use strict';
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var t__namespace = /*#__PURE__*/_interopNamespaceDefault(t$1);
const getGlobal = function () {
if (typeof globalThis !== 'undefined') { return globalThis; }
if (typeof self !== 'undefined') { return self; }
if (typeof window !== 'undefined') { return window; }
if (typeof global !== 'undefined') { return global; }
throw new Error('unable to locate global object');
};
const globals = getGlobal();
const transcoders = globals['gl_trans__coders'] = globals['gl_trans__coders'] || {};
function inject(chunk) {
// 奇怪的变量名是为了避免与worker源代码中的变量名冲突
const fnString = chunk.toString();
const prefixIndex = fnString.indexOf('{') + 1;
const prefix = fnString.substring(0, prefixIndex);
const transcoders = globals['gl_trans__coders'] = globals['gl_trans__coders'] || {};
let injected = `${prefix}
const _____getGlobal = ${getGlobal.toString()};
const g___lobals = _____getGlobal()
const tran_____scoders = g___lobals['gl_trans__coders'] = g___lobals['gl_trans__coders'] || {};`;
for (const p in transcoders) {
if (p === 'inject' || p === 'getTranscoder' || p === 'registerTranscoder') {
continue;
}
injected += 'tran_____scoders["' + p + '"] =' + transcoders[p].toString() + '\n;';
}
const gltfBundle = getGlobal()['maptalks_gltf_loader_bundle'];
injected += '\n(' + gltfBundle.toString() + ')({});\n';
injected += '\n' + fnString.substring(prefix.length);
return injected;
}
transcoders['inject'] = inject;
function getTranscoder(name/*, options*/) {
return transcoders[name];
}
function registerTranscoder(name, fn) {
transcoders[name] = fn;
}
function registerGLTFLoaderBundle(fn) {
getGlobal()['maptalks_gltf_loader_bundle'] = fn;
}
transcoders.registerTranscoder = registerTranscoder;
transcoders.getTranscoder = getTranscoder;
function gltfLoaderExport(t){var e=function(){return "undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:void 0};if(e().maptalks_gltf_loader)return;
/*!
* @maptalks/gltf-loader v0.102.8
* LICENSE : UNLICENSED
* (c) 2016-2025 maptalks.org
*/var n="undefined"!=typeof Float32Array?Float32Array:Array;function s(t,e,n){var s=e[0],r=e[1],i=e[2],o=e[3],h=e[4],u=e[5],c=e[6],a=e[7],f=e[8],l=e[9],d=e[10],m=e[11],p=e[12],w=e[13],y=e[14],g=e[15],b=n[0],_=n[1],A=n[2],x=n[3];return t[0]=b*s+_*h+A*f+x*p,t[1]=b*r+_*u+A*l+x*w,t[2]=b*i+_*c+A*d+x*y,t[3]=b*o+_*a+A*m+x*g,b=n[4],_=n[5],A=n[6],x=n[7],t[4]=b*s+_*h+A*f+x*p,t[5]=b*r+_*u+A*l+x*w,t[6]=b*i+_*c+A*d+x*y,t[7]=b*o+_*a+A*m+x*g,b=n[8],_=n[9],A=n[10],x=n[11],t[8]=b*s+_*h+A*f+x*p,t[9]=b*r+_*u+A*l+x*w,t[10]=b*i+_*c+A*d+x*y,t[11]=b*o+_*a+A*m+x*g,b=n[12],_=n[13],A=n[14],x=n[15],t[12]=b*s+_*h+A*f+x*p,t[13]=b*r+_*u+A*l+x*w,t[14]=b*i+_*c+A*d+x*y,t[15]=b*o+_*a+A*m+x*g,t}function r(){var t=new n(3);return n!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t}function i(t,e,s){var r=new n(3);return r[0]=t,r[1]=e,r[2]=s,r}function o(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function h(t,e,n,s){return t[0]=e,t[1]=n,t[2]=s,t}function u(t,e,n){return t[0]=e[0]+n[0],t[1]=e[1]+n[1],t[2]=e[2]+n[2],t}function c(t,e,n){return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t}function a(t,e,n,s,r){return t[0]=e,t[1]=n,t[2]=s,t[3]=r,t}function f(t,e,n){var s=e[0],r=e[1],i=e[2],o=e[3];return t[0]=n[0]*s+n[4]*r+n[8]*i+n[12]*o,t[1]=n[1]*s+n[5]*r+n[9]*i+n[13]*o,t[2]=n[2]*s+n[6]*r+n[10]*i+n[14]*o,t[3]=n[3]*s+n[7]*r+n[11]*i+n[15]*o,t}function l(){var t=new n(4);return n!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t[3]=1,t}Math.hypot||(Math.hypot=function(){for(var t=0,e=arguments.length;e--;)t+=arguments[e]*arguments[e];return Math.sqrt(t)}),r(),function(){var t;t=new n(4),n!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[3]=0);}();var d,m=function(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t};r(),i(1,0,0),i(0,1,0),l(),l(),d=new n(9),n!=Float32Array&&(d[1]=0,d[2]=0,d[3]=0,d[5]=0,d[6]=0,d[7]=0),d[0]=1,d[4]=1,d[8]=1;let p=0;function w(t){return null==t}function y(t){return !w(t)}function g(t){return !w(t)&&("string"==typeof t||null!==t.constructor&&t.constructor===String)}function b(t){for(let e=1;e<arguments.length;e++){const n=arguments[e];for(const e in n)t[e]=n[e];}return t}function _(t){switch(t){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5124:return Int32Array;case 5125:return Uint32Array;case 5126:return Float32Array}throw new Error("unsupported bufferView's component type: "+t)}function A(t){return 0===t.indexOf("data:")&&t.indexOf("base64,")>0}function x(t){const e=function(t){return "undefined"!=typeof self?self.atob(t):window.atob(t)}(t.substring(t.indexOf(",")+1)),n=e.length,s=new Uint8Array(n);for(let t=0;t<n;t++)s[t]=e.charCodeAt(t);return s.buffer}const T=[],M=[],I=[],E=[0,0,0],v=function(t){return t[0]=0,t[1]=0,t[2]=0,t[3]=1,t}([]),P=[1,1,1];function O(t,e,n,s,r,i,o){const h=_(o),u=h.BYTES_PER_ELEMENT;if((0===r||r===s*u)&&i%u==0){const r=new h(e,i,n*s);return t.set(r),t}0===r&&(r=s*u);const c=new Uint8Array(s*u);for(let o=0;o<n;o++){let n=null;const a=new Uint8Array(e,r*o+i,s*u);c.set(a),n=new h(c.buffer,0,s);for(let e=0;e<s;e++)t[o*s+e]=n[e];}return t}const N="undefined"!=typeof TextDecoder?new TextDecoder("utf-8"):null;function S(t,e,n){const s=new Uint8Array(t,e,n);return N.decode(s)}const B={get:function(t,e={},n){e||(e={});const s=new AbortController,r=s.signal,i=b({},e);i.signal=r,i.method||(i.method="GET"),i.referrerPolicy=i.referrerPolicy||"origin","undefined"==typeof window||i.referrer||(i.referrer=window.location.href),n&&(t=n(t));const o=fetch(t,i).then((t=>{const n=this.t(t,e.responseType);return n.message?n:n.then((n=>"arraybuffer"===e.responseType?{data:n,cacheControl:t.headers.get("Cache-Control"),expires:t.headers.get("Expires"),contentType:t.headers.get("Content-Type")}:n)).catch((t=>{if(!t.code||t.code!==DOMException.ABORT_ERR)throw t}))})).catch((t=>{if(!t.code||t.code!==DOMException.ABORT_ERR)throw t}));return o.xhr=s,o},t:(t,e)=>200!==t.status?{status:t.status,statusText:t.statusText,message:`incorrect http request with status code(${t.status}): ${t.statusText}`}:"arraybuffer"===e?t.arrayBuffer():"json"===e?t.json():t.text(),getArrayBuffer:(t,e={},n)=>(e||(e={}),e.responseType="arraybuffer",B.get(t,e,n)),getJSON:function(t,e={},n){return e&&e.jsonp?B.jsonp(t):((e=e||{}).responseType="json",B.get(t,e,n))},jsonp:function(t){const e="_maptalks_jsonp_"+p++;t.match(/\?/)?t+="&callback="+e:t+="?callback="+e;let n=document.createElement("script");return n.type="text/javascript",n.src=t,new Promise((t=>{window[e]=function(s){document.getElementsByTagName("head")[0].removeChild(n),n=null,delete window[e],t(s);},document.getElementsByTagName("head")[0].appendChild(n);}))}};class R{constructor(t,e,n,s,r){this.i=t,this.decoders=e,this.o=n,this.images={},this.h={},this.u=s||{},this.l=r;}requestImageFromBufferURI(t,e,n){if(this.buffers[t.id]){const s=this.buffers[t.id],r=this.m(e,s);return this.getImageByBuffer(r,n)}if(this.h[t.id])return this.h[t.id].then((()=>{const s=this.buffers[t.id],r=this.m(e,s);return this.getImageByBuffer(r,n)}));if(A(t.uri)){const s=this.buffers[t.id]=x(t.uri),r=this.m(e,s);return this.getImageByBuffer(r,n)}let s;const r=t.uri.indexOf("blob:")>=0;return s=t.uri.indexOf("://")>0||r?t.uri:this.rootPath+"/"+t.uri,this.h[t.id]=B.getArrayBuffer(s,this.u,this.l).then((s=>{const r=this.buffers[t.id]=s.data,i=this.m(e,r);return this.getImageByBuffer(i,n)}))}getImageByBuffer(t,e){if(this.images[e.id])return Promise.resolve(this.images[e.id]);const n=this.decoders;if(n[e.mimeType])return n[e.mimeType](t,{supportedFormats:this.o});if("image/crn"===e.mimeType||"image/ktx2"===e.mimeType||"image/cttf"===e.mimeType)throw new Error("missing transcoder for "+e.mimeType,"");return this.p(e.id,t)}requestExternalImage(t){if(this.images[t.id])return Promise.resolve(this.images[t.id]);const e=0===t.uri.indexOf("data:image/")?t.uri:this.rootPath+"/"+t.uri;return this.h[t.id]?this.h[t.id].then((()=>this.images[t.id])):this.h[t.id]=this.p(t.id,e)}p(t,e){return new Promise(((n,s)=>{let r=e;this.l&&(r=this.l(e)),this.i(r,this.u,((r,i)=>{r?s(r):(URL.revokeObjectURL(e),this.images[t]=i,n(this.images[t]));}));}))}}const C=["SCALAR",1,"VEC2",2,"VEC3",3,"VEC4",4,"MAT2",4,"MAT3",9,"MAT4",16],U=[];class k{constructor(t,e,n,s,r){this.rootPath=t,this.gltf=e,this._=!1,this.glbBuffer=n,this.buffers={},this.requests={},this.accessors={},this.A(),this.u=s,this.l=r;}T(t,e){const n=this.gltf,s=n.accessors[e];if(void 0===s.bufferView)return this.accessors[s.id]=this.M(t,e,null,0),Promise.resolve(this.accessors[s.id]);if(s&&this.accessors[s.id])return Promise.resolve(this.accessors[s.id]);const r=n.bufferViews[s.bufferView];return this.I(r).then((n=>{const{buffer:r,byteOffset:i}=n;return this.accessors[s.id]=this.M(t,e,r,i)}))}I(t){const e=this.gltf.buffers[t.buffer];if(this.buffers[e.id]){const t=this.buffers[e.id];return Promise.resolve({buffer:t,byteOffset:0})}if(this.requests[e.id])return this.requests[e.id].then((()=>{const t=this.buffers[e.id];return Promise.resolve({buffer:t,byteOffset:0})}));if("binary_glTF"!==t.buffer&&"KHR_binary_glTF"!==t.buffer&&e.uri){if(A(e.uri)){const t=this.buffers[e.id]=x(e.uri);return Promise.resolve({buffer:t,byteOffset:0})}let t;const n=e.uri.indexOf("blob:")>=0;return t=e.uri.indexOf("://")>0||n?e.uri:this.rootPath+"/"+e.uri,this.requests[e.id]=B.getArrayBuffer(t,this.u,!n&&this.l).then((s=>(n&&URL.revokeObjectURL(t),{buffer:this.buffers[e.id]=s.data,byteOffset:0})))}return Promise.resolve({buffer:this.glbBuffer.buffer,byteOffset:this.glbBuffer.byteOffset})}M(t,e,n,s=0){const r=this.gltf,i=r.accessors[e],o=void 0!==i.bufferView?r.bufferViews[i.bufferView]:{},h=(o.byteOffset||0)+s,u=this.v(i.type),c=_(i.componentType),a=o.byteStride||0,l={array:void 0,name:t,accessorName:e,byteLength:i.count*u*c.BYTES_PER_ELEMENT,componentType:i.componentType,count:i.count,type:i.type,itemSize:u,max:i.max,min:i.min,extensions:i.extensions};if(i.min&&(l.min=i.min),i.max&&(l.max=i.max),n)if(this._)l.byteStride=a,l.byteOffset=h+(i.byteOffset||0),!a||a===u*c.BYTES_PER_ELEMENT||"indices"===t||"input"===t||"output"===t||t.indexOf("morph")>=0?(l.array=this.P(n,i.count,u,h+(i.byteOffset||0),c),l.array.buffer.byteLength===l.byteLength&&(l.byteOffset=0)):l.array=new Uint8Array(n,h,o.byteLength);else if(i.interleaved){l.byteStride=0,l.byteOffset=0;const t=new c(i.count*u);if(l.array=O(t,n,i.count,u,a,h+(i.byteOffset||0),i.componentType),l.extensions&&l.extensions.WEB3D_quantized_attributes&&u>2){const t=new Float32Array(l.array.length),{decodeMatrix:e}=l.extensions.WEB3D_quantized_attributes;for(let n=0;n<l.array.length;n+=u){U[0]=l.array[n],U[1]=l.array[n+1],U[2]=l.array[n+2],U[3]=1;const s=f(U,U,e);t[n]=s[0],t[n+1]=s[1],t[n+2]=s[2];}l.componentType=5126,l.array=t;}}else l.byteStride=0,l.array=this.P(n,i.count,u,h+(i.byteOffset||0),c),l.byteOffset=l.array.byteOffset;else {l.array=new c(i.count);const t=l.min||l.max;t&&(l.array[0]=t[0],l.array[1]=t[1],l.array[2]=t[2]);}return l}A(){const t=this.gltf.accessors;if(Array.isArray(t))for(let e=0;e<t.length;e++)for(let n=0;n<t.length;n++)e!==n&&t[e].bufferView===t[n].bufferView&&(t[e].interleaved=t[n].interleaved=!0);else for(const e in t)for(const n in t)e!==n&&t[e].bufferView===t[n].bufferView&&(t[e].interleaved=t[n].interleaved=!0);}P(t,e,n,s,r){return s%r.BYTES_PER_ELEMENT!=0&&(t=t.slice(s,s+e*n*r.BYTES_PER_ELEMENT),s=0),new r(t,s,n*e)}v(t){const e=C.indexOf(t);return C[e+1]}requestKHRTechniquesWebgl(t){const{shaders:e}=t,n=e.map((t=>{if(void 0!==t.bufferView){const e=this.gltf.bufferViews[t.bufferView],{byteLength:n}=e;return this.I(e).then((s=>{const{buffer:r,byteOffset:i}=s,o=S(r,i+(e.byteOffset||0),n);return t.content=o,t}))}if(t.uri){if(A(t.uri)){const e=x(t.uri),n=S(e,0,e.byteLength);return t.content=n,Promise.resolve(t)}{const e=this.rootPath+"/"+t.uri;return B.get(e,this.u,this.l).then((e=>(t.content=e,t)))}}return Promise.resolve(t)}));return Promise.all(n).then((()=>t))}}class L extends R{constructor(t,e,n,s,r,i,o,h){super(s,r,i,o,h),this.rootPath=t,this.gltf=e,this.requests={},this.buffers={},this.glbBuffer=n,this.accessor=new k(t,e,n,o,h);}iterate(t,e){const n=this.gltf[e];if(!n)return;let s=0;for(const e in n)t(e,n[e],s++);}createNode(t){const e={};if(y(t.name)&&(e.name=t.name),y(t.children)&&(e.children=t.children),y(t.jointName)&&(e.jointName=t.jointName),y(t.matrix)&&(e.matrix=t.matrix),y(t.rotation)&&(e.rotation=t.rotation),y(t.scale)&&(e.scale=t.scale),y(t.translation)&&(e.translation=t.translation),y(t.extras)&&(e.extras=t.extras),y(t.meshes)&&(e.mesh=t.meshes[0]),e.translation||e.rotation||e.scale){const t=function(t,e){if(e.matrix)return e.matrix;if(e.translation||e.scale||e.rotation){const n=function(t,e){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=e[0],t[13]=e[1],t[14]=e[2],t[15]=1,t}(T,e.translation||E),r=function(t,e){var n=e[0],s=e[1],r=e[2],i=e[3],o=n+n,h=s+s,u=r+r,c=n*o,a=s*o,f=s*h,l=r*o,d=r*h,m=r*u,p=i*o,w=i*h,y=i*u;return t[0]=1-f-m,t[1]=a+y,t[2]=l-w,t[3]=0,t[4]=a-y,t[5]=1-c-m,t[6]=d+p,t[7]=0,t[8]=l+w,t[9]=d-p,t[10]=1-c-f,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}(M,e.rotation||v),i=function(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e[1],t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=e[2],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}(I,e.scale||P);return s(i,r,i),s(t,n,i)}return function(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}(t)}([],e);delete e.translation,delete e.rotation,delete e.scale,e.matrix=t;}return e}O(t){const e={};for(const n in t){const s=t[n];let r,i;s.instanceTechnique&&s.instanceTechnique.values?(r=s.instanceTechnique,i=r.values.diffuse):(r=s,i=r.values.tex||r.values.diffuseTex||r.values.diffuse);const o={baseColorTexture:{index:i}};s.name&&(o.name=s.name),s.extensions&&(o.extensions=s.extensions),s.extras&&(o.extras=s.extras),e[n]=o;}return e}N(t){if(t.bufferView||t.extensions&&(t.extensions.KHR_binary_glTF||t.extensions.binary_glTF)){const e=t.bufferView?t:t.extensions.KHR_binary_glTF||t.extensions.binary_glTF;t.extensions&&(t.mimeType=e.mimeType,t.width=e.width,t.height=e.height);const n=this.gltf.bufferViews[e.bufferView],s=(n.byteOffset||0)+this.glbBuffer.byteOffset,r=n.byteLength,i=this.buffers[e.bufferView]=new Uint8Array(this.glbBuffer.buffer,s,r);return this.getImageByBuffer(i,t)}return this.requestExternalImage(t)}S(t){const e=this.gltf.textures[t];if(!e)return null;const n=this.gltf.images[e.source];return this.N(n).then((t=>{const s=this.gltf.samplers[e.sampler];return {image:{array:t.data,width:t.width,height:t.height,index:e.source,mimeType:n.mimeType,name:n.name,extras:n.extras},sampler:s}}))}getBaseColorTexture(t){const e=this.gltf.materials[t];let n,s;if(e.instanceTechnique&&e.instanceTechnique.values?(n=e.instanceTechnique,s=n.values.diffuse):(n=e,s=n.values.tex||n.values.diffuseTex||n.values.diffuse),void 0===s||void 0===this.gltf.textures)return null;const r=this.gltf.textures[s];if(!r)return null;const i=this.gltf.samplers[r.sampler];return {format:r.format||6408,internalFormat:r.internalFormat||6408,type:r.type||5121,sampler:i,source:this.gltf.images[r.source]}}getMaterial(){return null}getAnimations(){return null}}const q=9729;class F extends R{constructor(t,e,n,s,r,i,o,h){super(s,r,i,o,h),this.rootPath=t,this.gltf=e,this.glbBuffer=n,this.buffers={},this.requests={},this.accessor=new k(t,e,n,o,h);}iterate(t,e){const n=this.gltf[e];if(n)for(let e=0;e<n.length;e++)t(e,n[e],e);}createNode(t){const e={};return b(e,t),!y(t.weights)&&this.gltf.meshes&&y(e.mesh)?e.weights=this.gltf.meshes[e.mesh].weights:t.weights&&(e.weights=t.weights),e}S(t){const e=this.gltf.textures[t];if(!e)return null;let n=e.source;if(e.extensions&&e.extensions.EXT_texture_webp?n=e.extensions.EXT_texture_webp.source:e.extensions&&e.extensions.KHR_texture_basisu&&(n=e.extensions.KHR_texture_basisu.source),!y(n))return null;const s=this.gltf.images[n];return this.N(s).then((t=>{if(!t)return null;const n={image:{array:t.data,mipmap:t.mipmap,width:t.width,height:t.height,index:e.source,mimeType:s.mimeType,name:s.name,extensions:s.extensions,extras:s.extras}};b(n,e);const r=y(e.sampler)?this.gltf.samplers[e.sampler]:void 0;if(r&&(n.sampler=r,n.sampler.magFilter=r.magFilter||q,n.sampler.minFilter=r.minFilter||9987,n.sampler.wrapS=r.wrapS||10497,n.sampler.wrapT=r.wrapT||10497),"image/ktx2"===n.image.mimeType&&!n.image.mipmap&&n.sampler&&n.sampler.minFilter!==q&&9728!==n.sampler.minFilter){const t=n.sampler.minFilter;n.sampler.minFilter=9984===t||9986===t?9728:q;}return t.format&&(n.format=t.format),n}))}N(t){if(!y(t.bufferView))return this.requestExternalImage(t);{const e=this.gltf.bufferViews[t.bufferView],n=this.gltf.buffers[e.buffer];if(n.uri)return this.requestImageFromBufferURI(n,e,t);if(this.glbBuffer)return this.B(e,t)}return null}B(t,e){const n=this.m(t,this.glbBuffer.buffer,this.glbBuffer.byteOffset);return this.getImageByBuffer(n,e)}m(t,e,n){n=n||0;const s=(t.byteOffset||0)+n,r=t.byteLength;return new Uint8Array(e,s,r)}R(t,e){const n=new Array(t.byteLength);for(let e=0;e<t.byteLength;e++)n[e]=String.fromCharCode(t[e]);n.join("");const s="data:"+(e=e||"image/png")+";base64,"+function(t){return "undefined"!=typeof self?self.btoa(t):window.btoa(t)}(unescape(encodeURIComponent(n)));return s}getAnimations(t){const e=[];return t.forEach((t=>{e.push(this.getSamplers(t.samplers));})),Promise.all(e).then((e=>{for(let n=0;n<e.length;n++)t[n].samplers=e[n];return t}))}getSamplers(t){const e=[];for(let n=0;n<t.length;n++)(y(t[n].input)||y(t[n].output))&&(e.push(this.accessor.T("input",t[n].input)),e.push(this.accessor.T("output",t[n].output)));return Promise.all(e).then((e=>{for(let n=0;n<e.length/2;n++)t[n].input=e[2*n],t[n].output=e[2*n+1],t[n].interpolation||(t[n].interpolation="LINEAR");return t}))}}const D="undefined"!=typeof TextDecoder?new TextDecoder("utf-8"):null;class V{static read(t,e=0,n=0){n||(n=t.byteLength);const s=new DataView(t,e,n),r=s.getUint32(4,!0);if(1===r)return V.readV1(s,e);if(2===r)return V.readV2(t,e);throw new Error("Unsupported glb version : "+r)}static readV1(t,e){const n=t.getUint32(8,!0),s=t.getUint32(12,!0);if(n!==t.byteLength)throw new Error("Length in GLB header is inconsistent with glb's byte length.");const r=j(t.buffer,20+e,s);return {json:JSON.parse(r),glbBuffer:{byteOffset:20+e+s,buffer:t.buffer,byteLength:n}}}static readV2(t,e){let n,s,r;const i=new DataView(t,e+12);let o=0;for(;o+8<i.byteLength;){const h=i.getUint32(o,!0);o+=4;const u=i.getUint32(o,!0);if(o+=4,1313821514===u)n=j(t,e+12+o,h);else if(5130562===u){r=e+12+o,s=h;break}o+=h;}return {json:JSON.parse(n),glbBuffer:{byteOffset:r,buffer:t,byteLength:s}}}}function j(t,e,n){if(D){const s=new Uint8Array(t,e,n);return D.decode(s)}return function(t){const e=t.length;let n="";for(let s=0;s<e;){let r=t[s++];if(128&r){let n=K[r>>3&7];if(!(64&r)||!n||s+n>e)return null;for(r&=63>>n;n>0;n-=1){const e=t[s++];if(128!=(192&e))return null;r=r<<6|63&e;}}n+=String.fromCharCode(r);}return n}(new Uint8Array(t,e,n))}const K=[1,1,1,1,2,2,3,0],H=[0,0,0],X=[0,0,0,1],$=[1,1,1],z={TRANSLATION:[0,0,0],ROTATION:[0,0,0,1],SCALE:[1,1,1]},G={PREVIOUS:null,NEXT:null,PREINDEX:null,NEXTINDEX:null,INTERPOLATION:null},J={C(t,e,n,s,r,i,h,u){const c=y(t)?e.animations:[e.animations[0]],a={};for(let e=0;e<c.length;e++){const f=c[e],l=f.name||e;if(y(t)&&l!==t)continue;const d=f.channelsMap[n];if(d)for(let t=0;t<d.length;t++){const e=d[t];"translation"===e.target.path?(this.U(r,f.samplers[e.sampler],s,1),a.translation=o(H,r)):"rotation"===e.target.path?(this.k(i,f.samplers[e.sampler],s,1),a.rotation=m(X,i)):"scale"===e.target.path?(this.U(h,f.samplers[e.sampler],s,1),a.scale=o($,h)):"weights"===e.target.path&&u&&(this.U(u,f.samplers[e.sampler],s,u.length),a.weights=u);}}return a},U(t,e,n,s){switch(e.interpolation){case"LINEAR":{const r=this.L(G,e,n,1*s);r&&(t=function(t,e,n,s){for(let r=0;r<t.length;r++)t[r]=e[r]+s*(n[r]-e[r]);return t}(t,r.PREVIOUS,r.NEXT,r.INTERPOLATION));break}case"STEP":{const r=this.L(G,e,n,1*s);r&&(t=function(t,e){for(let n=0;n<t.length;n++)t[n]=e[n];return t}(t,...r.PREVIOUS));break}case"CUBICSPLINE":{const r=this.L(G,e,n,3*s);r&&(t=this.q(t,r,e.input.array,3*s));break}}return t},k(t,e,n){switch(e.interpolation){case"LINEAR":{const s=this.L(G,e,n,1);s&&function(t,e,n,s){var r,i,o,h,u,c=e[0],a=e[1],f=e[2],l=e[3],d=n[0],m=n[1],p=n[2],w=n[3];(i=c*d+a*m+f*p+l*w)<0&&(i=-i,d=-d,m=-m,p=-p,w=-w),1-i>1e-6?(r=Math.acos(i),o=Math.sin(r),h=Math.sin((1-s)*r)/o,u=Math.sin(s*r)/o):(h=1-s,u=s),t[0]=h*c+u*d,t[1]=h*a+u*m,t[2]=h*f+u*p,t[3]=h*l+u*w;}(t,s.PREVIOUS,s.NEXT,s.INTERPOLATION);break}case"STEP":{const s=this.L(G,e,n,1);s&&(t=a(t,...s.PREVIOUS));break}case"CUBICSPLINE":{const s=this.L(G,e,n,3);if(s){for(let t=0;t<s.PREVIOUS.length;t++)s.PREVIOUS[t]=Math.acos(s.PREVIOUS[t]),s.NEXT[t]=Math.acos(s.NEXT[t]);t=this.q(t,s,e.input.array,3);for(let e=0;e<t.length;e++)t[e]=Math.cos(t[e]);}break}}return t},F(t,e){const n=t.length;let s,r,i,o=0,h=n-1,u=Math.floor((o+h)/2);for(;o<=n-1&&h>=0;){if(o===h)return null;if(t[u]<=e&&e<=t[u+1]){const n=t[u];return s=u,r=u+1,i=(e-n)/(t[u+1]-n),{preIndx:s,nextIndex:r,interpolation:i}}e<t[u]?(h=u,u=Math.floor((o+h)/2)):t[u+1]<e&&(o=u,u=Math.floor((o+h)/2));}return null},L(t,e,n,s){const r=e.input.array,i=e.output.array,o=e.output.itemSize;(n<r[0]||n>r[r.length-1])&&(n=Math.max(r[0],Math.min(r[r.length-1],n))),n===r[r.length-1]&&(n=r[0]);const h=this.F(r,n);if(!h||!h.nextIndex)return null;const{preIndx:u,nextIndex:c,interpolation:a}=h;t.PREINDEX=u,t.NEXTINDEX=c,t.INTERPOLATION=a;const f=o*s;return t.PREVIOUS=i.subarray(t.PREINDEX*f,(t.PREINDEX+1)*f),t.NEXT=i.subarray(t.NEXTINDEX*f,(t.NEXTINDEX+1)*f),t},q(t,e,n,s){const r=e.INTERPOLATION,i=n[e.PREINDEX],o=n[e.NEXTINDEX];for(let n=0;n<3;n++){const h=e.PREVIOUS[s+n],u=(o-i)*e.PREVIOUS[2*s+n],c=e.NEXT[3+n],a=(o-i)*e.NEXT[n],f=(2*Math.pow(r,3)-3*Math.pow(r,2)+1)*h+(Math.pow(r,3)-2*Math.pow(r,2)+r)*u+(2*-Math.pow(r,3)+3*Math.pow(r,2))*c+(Math.pow(r,3)-Math.pow(r,2))*a;t[n]=f;}return t},getAnimationClip(t,e,n,s){const r=t.nodes[e]&&t.nodes[e].weights;return h(H,...z.TRANSLATION),a(X,...z.ROTATION),h($,...z.SCALE),this.C(s,t,e,n,H,X,$,r)},getTimeSpan(t){if(!t.animations)return null;if(t.timeSpan)return t.timeSpan;const e=t.animations;return t.timeSpan={},e.forEach(((e,n)=>{let s=-1/0,r=1/0;const i=e.channels;for(let t=0;t<i.length;t++){const n=i[t],o=e.samplers[n.sampler].input.array;o[o.length-1]>s&&(s=o[o.length-1]),o[0]<r&&(r=o[0]);}const o=e.name||n;t.timeSpan[o]={max:s,min:r};})),t.timeSpan},getTimeSpanByName(t,e){const n=this.getTimeSpan(t);return n?y(e)?n[e]:n[Object.keys(n)[0]]:null}};let W=!1;if("undefined"!=typeof OffscreenCanvas){let t;try{t=new OffscreenCanvas(2,2).getContext("2d");}catch(n){}t&&"undefined"!=typeof createImageBitmap&&(W=!0);}const Q="undefined"==typeof document?null:document.createElement("canvas");function Y(t,e,n){const s=new Image;s.crossOrigin="",s.onload=()=>{if(!Q)return void n(new Error("There is no canvas to draw image!"));Q.width=s.width,Q.height=s.height;const t=Q.getContext("2d",{willReadFrequently:!0});t.drawImage(s,0,0,s.width,s.height);const e=t.getImageData(0,0,s.width,s.height),r={width:s.width,height:s.height,data:new Uint8Array(e.data)};n(null,r);},s.onerror=function(t){n(t);},s.src=t;}const Z=[],tt=[],et=30;let nt,st;function rt(t,e,n){nt||(nt=new OffscreenCanvas(2,2),st=nt.getContext("2d",{willReadFrequently:!0}));let s=null;if(g(t))this.options.urlModifier&&(t=this.options.urlModifier(t)),Z.push([t,e,n,this]),it();else {const e=new Blob([t]);s=createImageBitmap(e),s.then(ot.bind(this)).then((t=>{n(null,t);})).catch((t=>{console.warn(t),n(t);}));}}function it(){if(!Z.length||tt.length>et)return;const t=Z.shift(),[e,n,s,r]=t;tt.push(t),fetch(e,n).then((t=>t.arrayBuffer())).then((t=>{const e=new Blob([new Uint8Array(t)]);return createImageBitmap(e)})).then(ot.bind(r)).then((e=>{s.call(r,null,e);const n=tt.indexOf(t);tt.splice(n,1),it();})).catch((e=>{console.warn(e),s.call(r,e);const n=tt.indexOf(t);tt.splice(n,1),it();}));}function ot(t){let{width:e,height:n}=t;ht(e)||(e=ut(e)),ht(n)||(n=ut(n));const s=this.options.maxTextureSize;s&&(e=Math.min(s,e),n=Math.min(s,n)),nt.width=e,nt.height=n,st.drawImage(t,0,0,e,n),t.close();const r=st.getImageData(0,0,e,n);return {width:e,height:n,data:new Uint8Array(r.data)}}function ht(t){return !(t&t-1)&&0!==t}function ut(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))}function ct(t,e){for(const n in t)if(t[n]===e)return n;return e}t.Ajax=B,t.GLTFLoader=class{constructor(t,e,n){if(this.options=n||{},this.options.decoders||(this.options.decoders={}),this.u=this.options.fetchOptions||{},e.buffer instanceof ArrayBuffer){const{json:n,glbBuffer:s}=V.read(e.buffer,e.byteOffset,e.byteLength);this.D(t,n,s);}else this.D(t,e);this.V=new k(this.rootPath,this.gltf,this.glbBuffer,this.u,this.options.urlModifier),this.j();}j(){const t=this.gltf.extensionsRequired;if(t){if(t.indexOf("KHR_draco_mesh_compression")>=0&&!this.options.decoders.draco)throw new Error("KHR_draco_mesh_compression is required but @maptalks/transcoders.draco is not loaded");if(t.indexOf("KHR_texture_basisu")>=0&&!this.options.decoders["image/ktx2"])throw new Error("KHR_texture_basisu is required but @maptalks/transcoders.ktx2 is not loaded");if(t.indexOf("EXT_meshopt_compression")>=0)throw new Error("EXT_meshopt_compression extension is not supported yet.")}}K(){const t=this.gltf.extensions;return t&&t.KHR_techniques_webgl?this.V.requestKHRTechniquesWebgl(t.KHR_techniques_webgl).then((e=>(t.KHR_techniques_webgl=e,t))):Promise.resolve(t)}H(){if(!Array.isArray(this.gltf.programs))return;const t=this.gltf.materials;for(let e=0;e<t.length;e++)t[e]&&t[e].extensions&&t[e].extensions.KHR_technique_webgl&&(t[e].extensions.KHR_techniques_webgl=t[e].extensions.KHR_technique_webgl,delete t[e].extensions.KHR_technique_webgl);const e=this.gltf.extensions||{},n=this.gltf.techniques;e.KHR_techniques_webgl={programs:this.gltf.programs,shaders:this.gltf.shaders,techniques:n};for(let e=0;e<t.length;e++){const r=(s=t[e])&&s.extensions&&s.extensions.KHR_techniques_webgl;if(r){const{values:t,technique:e}=r,s=n[e];if(!s||!t)continue;const{uniforms:i,parameters:o}=s,h={};for(const e in t){const n=ct(i,e);h[n]=t[e],o[e]&&35678===o[e].type&&(h[n]={index:t[e]});}r.values=h;}}var s;for(let t=0;t<n.length;t++){const e=n[t];if(!e)continue;const{attributes:s,uniforms:r,parameters:i}=e;if(s)for(const t in s){const e=s[t];s[t]=i[e];}if(r)for(const t in r){const e=r[t];r[t]=i[e];}delete e.parameters;}return delete this.gltf.programs,delete this.gltf.shaders,delete this.gltf.techniques,this.gltf.extensions=e,e}load(t){t=t||{},this.H();const e=this.X(t),n=this.$(),s=this.G(),r=this.K();return Promise.all([e,n,s,r]).then((t=>(t[0].animations=t[1],t[0].textures=t[2],t[0].extensions=t[3],t[0].transferables=this.transferables||[],this.createChannelsMap(t[0]),t[0])))}createChannelsMap(t){const e=t.animations;if(e)for(let t=0;t<e.length;t++){const n=e[t];n.channelsMap={};for(let t=0;t<n.channels.length;t++){const e=n.channels[t];n.channelsMap[e.target.node]||(n.channelsMap[e.target.node]=[]),n.channelsMap[e.target.node].push(e);}}}getExternalResources(){const t=[];if(this.gltf){const{buffers:e,images:n}=this.gltf;for(let n=0;n<e.length;n++)e[n].uri&&e[n].uri.indexOf("data:application/octet-stream;base64")<0&&t.push({type:"buffer",uri:e[n].uri});for(let e=0;e<n.length;e++)n[e].uri&&n[e].uri.indexOf("data:image/")<0&&t.push({type:"image",uri:n[e].uri});}return t}static getAnimationClip(t,e,n,s){return J.getAnimationClip(t,e,n,s)}static getAnimationTimeSpan(t,e){return J.getTimeSpanByName(t,e)}static getTypedArrayCtor(t){return _(t)}static readInterleavedArray(t,e,n,s,r,i,o){return O(t,e,n,s,r,i,o)}D(t,e,n){this.gltf=e,this.glbBuffer=n,this.version=e.asset?+e.asset.version:1,this.rootPath=t,this.buffers={},this.requests={},this.options.requestImage=W?rt.bind(this):this.options.requestImage||Y,this.options.transferable&&(this.transferables=[]),2===this.version?(this.adapter=new F(t,e,n,this.options.requestImage,this.options.decoders||{},this.options.supportedFormats||{},this.u,this.options.urlModifier),this.adapter.iterate(((t,e,n)=>{e.id="buffer_"+n;}),"buffers"),this.adapter.iterate(((t,e,n)=>{e.id="image_"+n;}),"images"),this.adapter.iterate(((t,e,n)=>{e.id="accessor_"+n;}),"accessors")):(this.adapter=new L(t,e,n,this.options.requestImage,this.options.decoders||{},this.options.supportedFormats||{},this.u,this.options.urlModifier),this.adapter.iterate(((t,e,n)=>{e.id="accessor_"+n;}),"accessors"),this.adapter.iterate(((t,e,n)=>{e.id="image_"+n;}),"images"));}J(t,e){if(t.children&&t.children.length>0){if(!("number"==typeof(n=t.children[0])&&isFinite(n)||g(t.children[0])))return t;const s=t.children.map((t=>{const n=e[t];return n.nodeIndex=t,this.J(n,e)}));t.children=s;}var n;return t}X(t){return this.W(t).then((t=>{const e=this.scenes=[];let n;for(const e in t)t[e]=this.J(t[e],t),t[e].nodeIndex=Number(e)?Number(e):e;this.adapter.iterate(((s,r,i)=>{const o={};r.name&&(o.name=r.name),r.nodes&&(o.nodes=r.nodes.map((e=>t[e]))),this.gltf.scene===s&&(n=i),e.push(o);}),"scenes");const s={textures:this.gltf.textures,asset:this.gltf.asset,scene:n,scenes:e,nodes:t,meshes:this.meshes,materials:this.gltf.materials,skins:this.skins,extensionsRequired:this.gltf.extensionsRequired,extensionsUsed:this.gltf.extensionsUsed};if(this.gltf.extensions&&(s.extensions=this.gltf.extensions),1===this.version){const t=this.adapter.O(this.gltf.materials);s.materials=t;}return delete this.gltf.buffers,s.json=this.gltf,s}))}W(t){return this.Y(t).then((()=>{const t=this.nodes={};return this.adapter.iterate(((e,n)=>{const s=this.adapter.createNode(n,this.meshes,this.skins);t[e]=s;}),"nodes"),t}))}Z(){this.skins=[];const t=[];return this.adapter.iterate(((e,n,s)=>{t.push(this.tt(n).then((t=>{t.index=s,this.skins.push(t);})));}),"skins"),t}tt(t){const e=t.inverseBindMatrices;return this.adapter.accessor.T("inverseBindMatrices",e).then((e=>(t.inverseBindMatrices=e,e&&e.buffer&&this.transferables&&this.transferables.indexOf(e.buffer)<0&&this.transferables.push(e.buffer),t)))}$(){const t=this.gltf.animations;return y(t)?this.adapter.getAnimations(t):null}Y(t){this.meshes={};let e=[];return this.adapter.iterate(((n,s,r)=>{e.push(this.et(s,t).then((t=>{t.index=r,this.meshes[n]=t;})));}),"meshes"),e=e.concat(this.Z()),Promise.all(e)}et(t,e){const n=t.primitives.map((t=>this.nt(t,e))).filter((t=>!!t));return Promise.all(n).then((e=>{const n={};return b(n,t),n.primitives=e,n}))}G(){const t=this.gltf.textures;if(!t)return null;const e=[];for(const n in t)e.push(this.adapter.S(n));return Promise.all(e).then((e=>{if(this.transferables)for(let t=0;t<e.length;t++){const n=e[t]&&e[t].image.array;if(n){let t;t=n instanceof ImageBitmap?n:n.buffer,t&&this.transferables.indexOf(t)<0&&this.transferables.push(t);}}if(!Array.isArray(t)){const n={},s=Object.keys(t);for(let t=0;t<e.length;t++)e[t]&&(n[s[t]]=e[t]);return n}return e}))}nt(t,e){let n;const s=[],r=t.extensions;if(y(t.targets))for(let e=0;e<t.targets.length;e++){const n=t.targets[e];for(const t in n){const r=this.adapter.accessor.T(`morphTargets_${t}_${e}`,n[t]);r&&s.push(r);}}if(r&&r.KHR_draco_mesh_compression){if(!this.options.decoders.draco&&(!this.gltf.extensionsRequired||!this.gltf.extensionsRequired.indexOf("KHR_draco_mesh_compression")<0))return null;const t=this.options.decoders.draco,{bufferView:i,attributes:o}=r.KHR_draco_mesh_compression,h=this.gltf.bufferViews[i],u=this.V.I(h).then((n=>{const{buffer:s,byteOffset:r}=n;let{byteOffset:i}=h;const u=h.byteLength;i||(i=0);const c=new DataView(s,r+i,u),a={attributes:o,useUniqueIDs:!1,skipAttributeTransform:e.skipAttributeTransform};return t(c,a).then((t=>{const e=Object.values(t.attributes);return t.indices&&e.push(t.indices),e}))}));s.push(u),n=Promise.all(s);}else {const e=t.attributes;for(const t in e){const n=this.adapter.accessor.T(t,e[t]);n&&s.push(n);}if(y(t.indices)){const e=this.adapter.accessor.T("indices",t.indices);e&&s.push(e);}n=Promise.all(s);}return n.then((e=>{if(r&&r.KHR_draco_mesh_compression){const n=t.targets?t.targets.length:0;e[n]=e[n].concat(e.slice(0,n)),e=e[n];}let n,s;const i={attributes:e.reduce(((t,e)=>{if("indices"===e.name)n=e;else if(e.name.indexOf("morphTargets_")>-1)s=s||{},s[e.name.slice(13)]=e;else {if(!("POSITION"!==e.name||e.min&&e.max)){const t=[1/0,1/0,1/0],n=[-1/0,-1/0,-1/0],{itemSize:s,array:r}=e,i=r.length/s;for(let e=0;e<i;e++)for(let i=0;i<s;i++){const o=e*s+i;r[o]<t[i]&&(t[i]=r[o]),r[o]>n[i]&&(n[i]=r[o]);}if(e.quantization){const s=e.quantization,r=s.range/(1<<s.quantizationBits),i=s.minValues;c(t,t,r),u(t,t,i),c(n,n,r),u(n,n,i);}e.min=t,e.max=n;}t[e.name]=e;}return this.transferables&&e.array.buffer&&this.transferables.indexOf(e.array.buffer)<0&&this.transferables.push(e.array.buffer),t}),{}),material:t.material};return n&&(i.indices=n),s&&(i.morphTargets=s),i.mode=y(t.mode)?t.mode:4,y(t.extras)&&(i.extras=t.extras),i}))}},e().maptalks_gltf_loader=t;}gltfLoaderExport({});
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var regl = {exports: {}};
(function (module, exports) {
(function (global, factory) {
module.exports = factory() ;
}(commonjsGlobal, (function () {
var isTypedArray = function (x) {
return (
x instanceof Uint8Array ||
x instanceof Uint16Array ||
x instanceof Uint32Array ||
x instanceof Int8Array ||
x instanceof Int16Array ||
x instanceof Int32Array ||
x instanceof Float32Array ||
x instanceof Float64Array ||
x instanceof Uint8ClampedArray
)
};
var extend = function (base, opts) {
var keys = Object.keys(opts);
for (var i = 0; i < keys.length; ++i) {
base[keys[i]] = opts[keys[i]];
}
return base
};
// Error checking and parameter validation.
//
// Statements for the form `check.someProcedure(...)` get removed by
// a browserify transform for optimized/minified bundles.
//
/* globals atob */
var endl = '\n';
// only used for extracting shader names. if atob not present, then errors
// will be slightly crappier
function decodeB64 (str) {
if (typeof atob !== 'undefined') {
return atob(str)
}
return 'base64:' + str
}
function raise (message) {
var error = new Error('(regl) ' + message);
console.error(error);
throw error
}
function check (pred, message) {
if (!pred) {
raise(message);
}
}
function encolon (message) {
if (message) {
return ': ' + message
}
return ''
}
function checkParameter (param, possibilities, message) {
if (!(param in possibilities)) {
raise('unknown parameter (' + param + ')' + encolon(message) +
'. possible values: ' + Object.keys(possibilities).join());
}
}
function checkIsTypedArray (data, message) {
if (!isTypedArray(data)) {
raise(
'invalid parameter type' + encolon(message) +
'. must be a typed array');
}
}
function standardTypeEh (value, type) {
switch (type) {
case 'number': return typeof value === 'number'
case 'object': return typeof value === 'object'
case 'string': return typeof value === 'string'
case 'boolean': return typeof value === 'boolean'
case 'function': return typeof value === 'function'
case 'undefined': return typeof value === 'undefined'
case 'symbol': return typeof value === 'symbol'
}
}
function checkTypeOf (value, type, message) {
if (!standardTypeEh(value, type)) {
raise(
'invalid parameter type' + encolon(message) +
'. expected ' + type + ', got ' + (typeof value));
}
}
function checkNonNegativeInt (value, message) {
if (!((value >= 0) &&
((value | 0) === value))) {
raise('invalid parameter type, (' + value + ')' + encolon(message) +
'. must be a nonnegative integer');
}
}
function checkOneOf (value, list, message) {
if (list.indexOf(value) < 0) {
raise('invalid value' + encolon(message) + '. must be one of: ' + list);
}
}
var constructorKeys = [
'gl',
'canvas',
'container',
'attributes',
'pixelRatio',
'extensions',
'optionalExtensions',
'profile',
'onDone'
];
function checkConstructor (obj) {
Object.keys(obj).forEach(function (key) {
if (constructorKeys.indexOf(key) < 0) {
raise('invalid regl constructor argument "' + key + '". must be one of ' + constructorKeys);
}
});
}
function leftPad (str, n) {
str = str + '';
while (str.length < n) {
str = ' ' + str;
}
return str
}
function ShaderFile () {
this.name = 'unknown';
this.lines = [];
this.index = {};
this.hasErrors = false;
}
function ShaderLine (number, line) {
this.number = number;
this.line = line;
this.errors = [];
}
function ShaderError (fileNumber, lineNumber, message) {
this.file = fileNumber;
this.line = lineNumber;
this.message = message;
}
function guessCommand () {
var error = new Error();
var stack = (error.stack || error).toString();
var pat = /compileProcedure.*\n\s*at.*\((.*)\)/.exec(stack);
if (pat) {
return pat[1]
}
var pat2 = /compileProcedure.*\n\s*at\s+(.*)(\n|$)/.exec(stack);
if (pat2) {
return pat2[1]
}
return 'unknown'
}
function guessCallSite () {
var error = new Error();
var stack = (error.stack || error).toString();
var pat = /at REGLCommand.*\n\s+at.*\((.*)\)/.exec(stack);
if (pat) {
return pat[1]
}
var pat2 = /at REGLCommand.*\n\s+at\s+(.*)\n/.exec(stack);
if (pat2) {
return pat2[1]
}
return 'unknown'
}
function parseSource (source, command) {
var lines = source.split('\n');
var lineNumber = 1;
var fileNumber = 0;
var files = {
unknown: new ShaderFile(),
0: new ShaderFile()
};
files.unknown.name = files[0].name = command || guessCommand();
files.unknown.lines.push(new ShaderLine(0, ''));
for (var i = 0; i < lines.length; ++i) {
var line = lines[i];
var parts = /^\s*#\s*(\w+)\s+(.+)\s*$/.exec(line);
if (parts) {
switch (parts[1]) {
case 'line':
var lineNumberInfo = /(\d+)(\s+\d+)?/.exec(parts[2]);
if (lineNumberInfo) {
lineNumber = lineNumberInfo[1] | 0;
if (lineNumberInfo[2]) {
fileNumber = lineNumberInfo[2] | 0;
if (!(fileNumber in files)) {
files[fileNumber] = new ShaderFile();
}
}
}
break
case 'define':
var nameInfo = /SHADER_NAME(_B64)?\s+(.*)$/.exec(parts[2]);
if (nameInfo) {
files[fileNumber].name = (nameInfo[1]
? decodeB64(nameInfo[2])
: nameInfo[2]);
}
break
}
}
files[fileNumber].lines.push(new ShaderLine(lineNumber++, line));
}
Object.keys(files).forEach(function (fileNumber) {
var file = files[fileNumber];
file.lines.forEach(function (line) {
file.index[line.number] = line;
});
});
return files
}
function parseErrorLog (errLog) {
var result = [];
errLog.split('\n').forEach(function (errMsg) {
if (errMsg.length < 5) {
return
}
var parts = /^ERROR:\s+(\d+):(\d+):\s*(.*)$/.exec(errMsg);
if (parts) {
result.push(new ShaderError(
parts[1] | 0,
parts[2] | 0,
parts[3].trim()));
} else if (errMsg.length > 0) {
result.push(new ShaderError('unknown', 0, errMsg));
}
});
return result
}
function annotateFiles (files, errors) {
errors.forEach(function (error) {
var file = files[error.file];
if (file) {
var line = file.index[error.line];
if (line) {
line.errors.push(error);
file.hasErrors = true;
return
}
}
files.unknown.hasErrors = true;
files.unknown.lines[0].errors.push(error);
});
}
function checkShaderError (gl, shader, source, type, command) {
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
var errLog = gl.getShaderInfoLog(shader);
var typeName = type === gl.FRAGMENT_SHADER ? 'fragment' : 'vertex';
checkCommandType(source, 'string', typeName + ' shader source must be a string', command);
var files = parseSource(source, command);
var errors = parseErrorLog(errLog);
annotateFiles(files, errors);
Object.keys(files).forEach(function (fileNumber) {
var file = files[fileNumber];
if (!file.hasErrors) {
return
}
var strings = [''];
var styles = [''];
function push (str, style) {
strings.push(str);
styles.push(style || '');
}
push('file number ' + fileNumber + ': ' + file.name + '\n', 'color:red;text-decoration:underline;font-weight:bold');
file.lines.forEach(function (line) {
if (line.errors.length > 0) {
push(leftPad(line.number, 4) + '| ', 'background-color:yellow; font-weight:bold');
push(line.line + endl, 'color:red; background-color:yellow; font-weight:bold');
// try to guess token
var offset = 0;
line.errors.forEach(function (error) {
var message = error.message;
var token = /^\s*'(.*)'\s*:\s*(.*)$/.exec(message);
if (token) {
var tokenPat = token[1];
message = token[2];
switch (tokenPat) {
case 'assign':
tokenPat = '=';
break
}
offset = Math.max(line.line.indexOf(tokenPat, offset), 0);
} else {
offset = 0;
}
push(leftPad('| ', 6));
push(leftPad('^^^', offset + 3) + endl, 'font-weight:bold');
push(leftPad('| ', 6));
push(message + endl, 'font-weight:bold');
});
push(leftPad('| ', 6) + endl);
} else {
push(leftPad(line.number, 4) + '| ');
push(line.line + endl, 'color:red');
}
});
if (typeof document !== 'undefined' && !window.chrome) {
styles[0] = strings.join('%c');
console.log.apply(console, styles);
} else {
console.log(strings.join(''));
}
});
check.raise('Error compiling ' + typeName + ' shader, ' + files[0].name);
}
}
function checkLinkError (gl, program, fragShader, vertShader, command) {
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
var errLog = gl.getProgramInfoLog(program);
var fragParse = parseSource(fragShader, command);
var vertParse = parseSource(vertShader, command);
var header = 'Error linking program with vertex shader, "' +
vertParse[0].name + '", and fragment shader "' + fragParse[0].name + '"';
if (typeof document !== 'undefined') {
console.log('%c' + header + endl + '%c' + errLog,
'color:red;text-decoration:underline;font-weight:bold',
'color:red');
} else {
console.log(header + endl + errLog);
}
check.raise(header);
}
}
function saveCommandRef (object) {
object._commandRef = guessCommand();
}
function saveDrawCommandInfo (opts, uniforms, attributes, stringStore) {
saveCommandRef(opts);
function id (str) {
if (str) {
return stringStore.id(str)
}
return 0
}
opts._fragId = id(opts.static.frag);
opts._vertId = id(opts.static.vert);
function addProps (dict, set) {
Object.keys(set).forEach(function (u) {
dict[stringStore.id(u)] = true;
});
}
var uniformSet = opts._uniformSet = {};
addProps(uniformSet, uniforms.static);
addProps(uniformSet, uniforms.dynamic);
var attributeSet = opts._attributeSet = {};
addProps(attributeSet, attributes.static);
addProps(attributeSet, attributes.dynamic);
opts._hasCount = (
'count' in opts.static ||
'count' in opts.dynamic ||
'elements' in opts.static ||
'elements' in opts.dynamic);
}
function commandRaise (message, command) {
var callSite = guessCallSite();
raise(message +
' in command ' + (command || guessCommand()) +
(callSite === 'unknown' ? '' : ' called from ' + callSite));
}
function checkCommand (pred, message, command) {
if (!pred) {
commandRaise(message, command || guessCommand());
}
}
function checkParameterCommand (param, possibilities, message, command) {
if (!(param in possibilities)) {
commandRaise(
'unknown parameter (' + param + ')' + encolon(message) +
'. possible values: ' + Object.keys(possibilities).join(),
command || guessCommand());
}
}
function checkCommandType (value, type, message, command) {
if (!standardTypeEh(value, type)) {
commandRaise(
'invalid parameter type' + encolon(message) +
'. expected ' + type + ', got ' + (typeof value),
command || guessCommand());
}
}
function checkOptional (block) {
block();
}
function checkFramebufferFormat (attachment, texFormats, rbFormats) {
if (attachment.texture) {
checkOneOf(
attachment.texture._texture.internalformat,
texFormats,
'unsupported texture format for attachment');
} else {
checkOneOf(
attachment.renderbuffer._renderbuffer.format,
rbFormats,
'unsupported renderbuffer format for attachment');
}
}
var GL_CLAMP_TO_EDGE = 0x812F;
var GL_NEAREST = 0x2600;
var GL_NEAREST_MIPMAP_NEAREST = 0x2700;
var GL_LINEAR_MIPMAP_NEAREST = 0x2701;
var GL_NEAREST_MIPMAP_LINEAR = 0x2702;
var GL_LINEAR_MIPMAP_LINEAR = 0x2703;
var GL_BYTE = 5120;
var GL_UNSIGNED_BYTE = 5121;
var GL_SHORT = 5122;
var GL_UNSIGNED_SHORT = 5123;
var GL_INT = 5124;
var GL_UNSIGNED_INT = 5125;
var GL_FLOAT = 5126;
var GL_UNSIGNED_SHORT_4_4_4_4 = 0x8033;
var GL_UNSIGNED_SHORT_5_5_5_1 = 0x8034;
var GL_UNSIGNED_SHORT_5_6_5 = 0x8363;
var GL_UNSIGNED_INT_24_8_WEBGL = 0x84FA;
var GL_HALF_FLOAT_OES = 0x8D61;
var TYPE_SIZE = {};
TYPE_SIZE[GL_BYTE] =
TYPE_SIZE[GL_UNSIGNED_BYTE] = 1;
TYPE_SIZE[GL_SHORT] =
TYPE_SIZE[GL_UNSIGNED_SHORT] =
TYPE_SIZE[GL_HALF_FLOAT_OES] =
TYPE_SIZE[GL_UNSIGNED_SHORT_5_6_5] =
TYPE_SIZE[GL_UNSIGNED_SHORT_4_4_4_4] =
TYPE_SIZE[GL_UNSIGNED_SHORT_5_5_5_1] = 2;
TYPE_SIZE[GL_INT] =
TYPE_SIZE[GL_UNSIGNED_INT] =
TYPE_SIZE[GL_FLOAT] =
TYPE_SIZE[GL_UNSIGNED_INT_24_8_WEBGL] = 4;
function pixelSize (type, channels) {
if (type === GL_UNSIGN