@occluze/umber 0.3.0 → 0.4.1
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.
- package/README.md +93 -47
- package/THIRD-PARTY-NOTICES.md +33 -0
- package/dist/chunks/badge.js +2 -2
- package/dist/chunks/basis.js +2 -2
- package/dist/chunks/batches.js +2 -0
- package/dist/chunks/capture.js +2 -2
- package/dist/chunks/covers.js +2 -2
- package/dist/chunks/curves.js +2 -2
- package/dist/chunks/flip.js +2 -2
- package/dist/chunks/fx.js +2 -2
- package/dist/chunks/gl.js +2 -2
- package/dist/chunks/glsl.js +2 -2
- package/dist/chunks/glyphs.js +2 -0
- package/dist/chunks/inspect.js +2 -2
- package/dist/chunks/instances.js +2 -2
- package/dist/chunks/layers.js +2 -2
- package/dist/chunks/licence.js +2 -2
- package/dist/chunks/morph.js +2 -2
- package/dist/chunks/pace.js +2 -0
- package/dist/chunks/patch.js +2 -2
- package/dist/chunks/prepared.js +2 -2
- package/dist/chunks/profiler.js +2 -2
- package/dist/chunks/recheck.js +2 -0
- package/dist/chunks/resize.js +2 -0
- package/dist/chunks/restore.js +2 -2
- package/dist/chunks/shapes.js +2 -2
- package/dist/chunks/sim.js +2 -2
- package/dist/chunks/text.js +2 -2
- package/dist/chunks/video.js +2 -2
- package/dist/chunks/vocabulary.js +2 -2
- package/dist/chunks/warm.js +2 -2
- package/dist/modules/debug.js +2 -2
- package/dist/modules/debug.mjs +2 -2
- package/dist/modules/handoff.js +2 -2
- package/dist/modules/handoff.mjs +2 -2
- package/dist/modules/input.js +2 -2
- package/dist/modules/input.mjs +2 -2
- package/dist/modules/scrollfx.js +2 -2
- package/dist/modules/scrollfx.mjs +2 -2
- package/dist/modules/scrub.js +2 -2
- package/dist/modules/scrub.mjs +2 -2
- package/dist/modules/three.js +2 -2
- package/dist/modules/three.mjs +2 -2
- package/dist/node/assets.mjs +4 -2
- package/dist/node/astro.mjs +26 -18
- package/dist/node/cli.mjs +63 -10
- package/dist/node/shared-NFSQ5J4B.mjs +2116 -0
- package/dist/node/{shared-4FIU6DYP.mjs → shared-OUFNIXQ7.mjs} +106 -17
- package/dist/node/vite.mjs +7 -3
- package/dist/prepared.mjs +2 -0
- package/dist/umber.css +1 -1
- package/dist/umber.js +2 -2
- package/dist/umber.mjs +2 -2
- package/docs/AI-quick.md +43 -87
- package/docs/AI.md +1977 -1829
- package/docs/npm.md +13 -16
- package/package.json +32 -48
- package/types/assets.d.ts +109 -4
- package/types/astro.d.ts +20 -23
- package/types/debug.d.ts +1 -1
- package/types/esm.d.ts +2 -6
- package/types/input.d.ts +3 -3
- package/types/loop.d.ts +21 -9
- package/types/module.d.ts +0 -2
- package/types/scrollfx.d.ts +5 -41
- package/types/scrub.d.ts +2 -2
- package/types/three.d.ts +26 -1
- package/types/umber.d.ts +152 -155
- package/types/vite.d.ts +3 -3
- package/dist/chunks/views.js +0 -2
- package/dist/frameworks/astro.mjs +0 -2
- package/dist/frameworks/react.mjs +0 -2
- package/dist/frameworks/svelte.mjs +0 -2
- package/dist/frameworks/vue.mjs +0 -2
- package/dist/modules/router-swap.js +0 -2
- package/dist/modules/router.js +0 -2
- package/dist/modules/router.mjs +0 -2
- package/dist/modules/scroll-more.js +0 -2
- package/dist/modules/scroll-touch.js +0 -2
- package/dist/modules/scroll.js +0 -2
- package/dist/modules/scroll.mjs +0 -2
- package/dist/node/shared-3Q24RNIF.mjs +0 -602
- package/types/react.d.ts +0 -15
- package/types/router.d.ts +0 -223
- package/types/scroll.d.ts +0 -190
- package/types/svelte.d.ts +0 -16
- package/types/vue.d.ts +0 -14
package/dist/modules/scrub.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! Umber v0.
|
|
2
|
-
(()=>{async function t(t,e){let i=await fetch(t,e);if(!i.ok)throw new Error(`${t} answered ${i.status}`);return i}function e(t,e=location.href){try{return new URL(t,e)}catch{return null}}var i=()=>{};function s(t,e){let i=t.trim();if("number"===e){let t=parseFloat(i);return Number.isFinite(t)?t:void 0}return"boolean"===e?function(t){let e=t.trim().toLowerCase();return""===e||"true"===e||"1"===e||"yes"===e||"false"!==e&&"0"!==e&&"no"!==e&&void 0}(i):"list"===e?i.split(/[\s,]+/).filter(Boolean):i.replace(/^["']|["']$/g,"")}function r(t){return t.type?t.type:"number"==typeof t.default?"number":"boolean"==typeof t.default?"boolean":Array.isArray(t.default)?"list":"string"}var n=t=>t.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`);function h(t,e,i){let n={},h=i;for(let[i,o]of Object.entries(e)){let e,a=r(o);if(o.attr){let i=t.getAttribute(o.attr);null!==i&&(e=s(i,a))}if(void 0===e&&o.css){h??=getComputedStyle(t);let i=h.getPropertyValue(o.css);i&&""!==i.trim()&&(e=s(i,a))}n[i]=void 0===e?o.default:e}return n}var o=(t,e)=>t[e]??NaN,a={top:0,left:0,center:.5,middle:.5,bottom:1,right:1};function l(t,e){let i=(t??"").trim().toLowerCase();if(!i)return e;let s=function(t){let e=/^(top|left|center|middle|bottom|right|-?\d*\.?\d+(?:px|%)?)?(?:([+-])=?(\d*\.?\d+)(px|%)?)?$/.exec(t);if(!e)return null;let[,i,s,r="",n]=e;if(!i&&!s)return null;let h=0,o=0,l=void 0===i?void 0:a[i];if(void 0!==l)h=l;else if(i){let t=parseFloat(i);i.endsWith("%")?h=t/100:o=t}if(s){let t=parseFloat(r)*("-"===s?-1:1);"%"===n?h+=t/100:o+=t}return[h,o]}(i);return s?/^[+-]/.test(i)&&!/^-\d/.test(i)?[e[0]+s[0],e[1]+s[1]]:s:e}var d={cover:[[0,1,1,0]],contain:[[1,1,0,0],[0,0,1,1]],entry:[[0,1,1,1],[0,1,0,0]],exit:[[0,0,1,0],[1,1,1,0]],"entry-crossing":[[0,1,1,1]],"exit-crossing":[[0,0,1,0]]};function u(t,e){let i=function(t,e){return null==t||""===t?e:t}(t,e).trim().split(/\s+/),s=function(t,e){let[i,s]=t,r=void 0===i?void 0:d[i];if(void 0===r)return null;let[n,h]=r,o=s??(e?"100%":"0%"),a=o.endsWith("%")?0:parseFloat(o)||0,l=a?0:parseFloat(o)/100||0,u=([t,e,i,s])=>({el:t+(i-t)*l,elPx:a,vp:e+(s-e)*l,vpPx:0});return{...u(n),alt:h?u(h):void 0}}(i.map(t=>t.toLowerCase()),e.startsWith("bottom"));if(s)return s;let r=e.split(/\s+/),[n,h]=l(i[0],l(r[0],[0,0])),[o,a]=l(i[1],l(r[1],[0,0]));return{el:n,elPx:h,vp:o,vpPx:a}}var c=(t,e)=>String.fromCharCode(o(t,e),o(t,e+1),o(t,e+2),o(t,e+3));function f(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function m(t,e,i){let s=e.body+i;return s+4<=Math.min(e.end,t.length)?f(t).getUint32(s):Number.NaN}function p(t,e,i,s){let r=m(t,e,i-4);return r*s<=Math.min(e.end,t.length)-(e.body+i)?r:null}var g=2**21;function b(t,e,i=t.length){if(e+8>i)return null;let s=f(t),r=s.getUint32(e),n=c(t,e+4),h=e+8;if(1===r){if(e+16>i)return null;r=s.getUint32(e+8)*2**32+s.getUint32(e+12),h=e+16}else 0===r&&(r=1/0);return r<h-e?null:{type:n,start:e,body:h,end:e+r}}function y(t,e,i){let s=[],r=e;for(;r<i;){let e=b(t,r,i);if(!e||e.end>i||e.end<=r)break;s.push(e),r=e.end}return s}var w=(t,e,i)=>y(t,e.body,e.end).find(t=>t.type===i)??null;function v(t,e,...i){for(let s of i){if(!e)return null;e=w(t,e,s)}return e}function k(t,e,i){let s=v(t,e,"mdia","mdhd"),r=v(t,e,"mdia","minf","stbl");if(!s||!r)return null;let n=m(t,s,1===t[s.body]?20:12);if(Number.isNaN(n))return null;let h=n||1,a=function(t,e){let i=w(t,e,"stsd");if(!i)return null;let s=b(t,i.body+8,i.end);if(!s||s.end>i.end||s.body+28>s.end)return null;let r=f(t),n=s.type,h="",o=null,a=y(t,s.body+78,s.end).find(t=>"avcC"===t.type);return a&&("avc1"===n||"avc3"===n)&&(o=t.slice(a.body,a.end),h=function(t){let e=t=>t.toString(16).padStart(2,"0"),[,i,s,r]=t;return void 0===i||void 0===s||void 0===r?"":`avc1.${e(i)}${e(s)}${e(r)}`}(o)),{format:n,width:r.getUint16(s.body+24),height:r.getUint16(s.body+26),codec:h,description:o}}(t,r);if(!a)return null;let[l,d]=function(t,e){let i=w(t,e,"tkhd");if(!i)return null;let s=i.body+(1===t[i.body]?88:76);if(s+8>i.end)return null;let r=f(t),n=r.getUint32(s)/65536,h=r.getUint32(s+4)/65536;return n&&h?[Math.round(n),Math.round(h)]:null}(t,e)??[a.width,a.height],u=function(t,e){let i=i=>w(t,e,i),s=function(t,e,i){return e?function(t,e){let i=f(t),s=m(t,e,4),r=s?m(t,e,8):p(t,e,12,4);if(null===r||!(r<=g))return null;let n=new Array(r);for(let t=0;t<r;t++)n[t]=s||i.getUint32(e.body+12+4*t);return n}(t,e):i?function(t,e){let i=t[e.body+7];if(4!==i&&8!==i&&16!==i)return null;let s=p(t,e,12,i/8);if(null===s||s>g)return null;let r=f(t),n=e.body+12,h=new Array(s);for(let e=0;e<s;e++)h[e]=16===i?r.getUint16(n+2*e):8===i?o(t,n+e):o(t,n+(e>>1))>>(1&e?0:4)&15;return h}(t,i):null}(t,i("stsz"),i("stz2")),r=function(t,e,i){let s=e??i;if(!s)return null;let r=e?4:8,n=p(t,s,8,r);if(null===n)return null;let h=f(t),o=new Array(n);for(let t=0;t<n;t++){let i=s.body+8+t*r;o[t]=e?h.getUint32(i):h.getUint32(i)*2**32+h.getUint32(i+4)}return o}(t,i("stco"),i("co64")),n=i("stsc");if(!s||!r||!n)return null;let h=function(t,e,i,s){let r=i.length,n=function(t,e){let i=p(t,e,8,12);if(null===i)return null;let s=f(t),r=[];for(let t=0;t<i;t++){let i=e.body+8+12*t;r.push({first:s.getUint32(i)-1,per:s.getUint32(i+4)})}return r}(t,e);if(!n)return null;let h=new Array(r),a=0;for(let[t,e]of n.entries()){if(a>=r)break;let l=n[t+1]?.first??s.length;for(let t=e.first;t<l&&a<r;t++){let n=s[t];if(void 0===n)return null;for(let t=0;t<e.per&&a<r;t++)h[a]=n,n+=o(i,a),a++}}return a<r?null:h}(t,n,s,r),a=i("stts");if(!h||!a)return null;let l=s.length,d=function(t,e,i){let s=f(t),r=new Array(i),n=new Array(i),h=0,o=0,a=p(t,e,8,8);if(null===a)return null;for(let t=0;t<a&&o<i;t++){let a=s.getUint32(e.body+8+8*t),l=s.getUint32(e.body+12+8*t);for(let t=0;t<a&&o<i;t++)r[o]=h,n[o]=l,h+=l,o++}for(;o<i;o++)r[o]=h,n[o]=0;return{dts:r,durations:n}}(t,a,l);if(!d)return null;let{dts:u,durations:c}=d,b=function(t,e,i){let s=i.slice();if(!e)return s;let r=f(t),n=i.length,h=p(t,e,8,8);if(null===h)return null;let a=0;for(let t=0;t<h&&a<n;t++){let i=r.getUint32(e.body+8+8*t),h=r.getInt32(e.body+12+8*t);for(let t=0;t<i&&a<n;t++,a++)s[a]=o(s,a)+h}return s}(t,i("ctts"),u),y=function(t,e,i){let s=new Array(i).fill(!e);if(e){let r=f(t),n=p(t,e,8,4);if(null===n)return null;for(let t=0;t<n;t++){let n=r.getUint32(e.body+8+4*t)-1;n>=0&&n<i&&(s[n]=!0)}}return i&&(s[0]=!0),s}(t,i("stss"),l);return b&&y?s.map((t,e)=>({offset:o(h,e),size:t,dts:o(u,e),cts:o(b,e),duration:o(c,e),key:!0===y[e]})):null}(t,r);if(!u)return null;let c=function(t,e,i,s){let r=v(t,e,"edts","elst");if(!r)return null;let n=f(t),h=1===t[r.body],o=h?20:12,a=m(t,r,4),l=null;for(let t=0;t<a;t++){let e=r.body+8+t*o;if(e+o>r.end)break;let a=h?n.getUint32(e)*2**32+n.getUint32(e+4):n.getUint32(e),d=h?n.getInt32(e+8)*2**32+n.getUint32(e+12):n.getInt32(e+4);if(!(d<0)){if(l)return"cuts";l=[d,a?d+a*i/s:1/0]}}return l}(t,e,h,i||h),k="cuts"===c?null:c,M=t=>!k||t.cts+t.duration/2>=k[0]&&t.cts+t.duration/2<k[1],x=[];for(let[t,e]of u.entries())M(e)&&x.push(t);let A=u.map(t=>t.cts);x.sort((t,e)=>o(A,t)-o(A,e)||t-e);let{keyOf:S,gop:E}=function(t){let e=t.length,i=new Array(e),s=0,r=1;for(let[e,n]of t.entries())n.key&&(e&&(r=Math.max(r,e-s)),s=e),i[e]=s;return e&&(r=Math.max(r,e-s)),{keyOf:i,gop:r}}(u),[U]=x,$=x.at(-1),C=void 0===U?void 0:u[U],F=void 0===$?void 0:u[$],N=(C&&F?F.cts+F.duration-C.cts:0)/h;return{codec:a.codec,format:a.format,description:a.description,width:l,height:d,timescale:h,duration:N,fps:N>0?x.length/N:30,samples:u,order:x,keyOf:S,gop:E,cuts:"cuts"===c}}var M=class{constructor(){this.bytes=new Uint8Array(0),this.loaded=0,this.total=0,this.done=!1,this.track=null,this.late=!1,this.onTrack=null,this.onData=null,this.onError=null,this.cursor=0,this.sawMdat=!1,this.failed=!1,this.abort=null,this.reader=null}start(t){this.abort=typeof AbortController<"u"?new AbortController:null,this.run(t).catch(t=>{this.abort?.signal.aborted||this.onError?.(t)})}async run(e){let i=await t(e,{mode:"cors",credentials:"omit",signal:this.abort?.signal}),s=Number(i.headers.get("content-length"))||0;s&&!i.headers.get("content-encoding")&&(this.total=s);let r=i.body?.getReader();if(!r)return this.push(new Uint8Array(await i.arrayBuffer())),void this.finish();for(this.reader=r;;){let{done:t,value:e}=await r.read();if(this.failed)return;if(t)break;e.length&&this.push(e)}this.finish()}push(t){if(this.failed)return;let e=this.loaded+t.length;if(e>this.bytes.length){let t=Math.min(this.total,67108864),i=new Uint8Array(Math.max(e,t,2*this.bytes.length,1<<20));i.set(this.bytes.subarray(0,this.loaded)),this.bytes=i}this.bytes.set(t,this.loaded),this.loaded=e,this.scan(),this.onData?.()}finish(){this.done=!0,this.scan(),!this.track&&!this.failed&&this.onError?.(new Error("no H.264 video track found (is it an MP4?)")),this.onData?.()}fail(t){this.failed=!0,this.abort?.abort(),this.reader?.cancel().catch(()=>{}),this.onError?.(t)}scan(){for(;!this.track&&!this.failed;){let t=b(this.bytes,this.cursor,this.loaded);if(!t)return;if("moov"===t.type)return void(t.end<=this.loaded&&this.read(t));if("mdat"===t.type&&(this.sawMdat=!0),!Number.isFinite(t.end))return;this.cursor=t.end}}read(t){this.late=this.sawMdat;let e=function(t,e){let i=w(t,e,"mvhd"),s=i?m(t,i,1===t[i.body]?20:12):0;if(Number.isNaN(s))return null;for(let i of y(t,e.body,e.end)){if("trak"!==i.type)continue;let r=v(t,i,"mdia","hdlr");if(!r||"vide"!==c(t,r.body+8))continue;let n=k(t,i,s);if(n)return w(t,e,"mvex")&&(n.fragmented=!0),n}return null}(this.bytes,t);e?(this.track=e,this.onTrack?.(e)):this.fail(new Error("the MP4 has no video track"))}has(t){return t.offset+t.size<=this.loaded}data(t){return this.bytes.subarray(t.offset,t.offset+t.size)}stop(){this.abort?.abort(),this.onTrack=null,this.onData=null,this.onError=null}};function x(t){return t>0?1:t<0?-1:0}var A=class{constructor(t,e){this.track=t,this.host=e,this.target=-1,this.dir=0,this.busy=null,this.fetched=new Set,this.present=new Array(t.order.length),t.order.forEach((t,e)=>{this.present[t]=e})}get frames(){return this.track.order.length}want(t,e=0){let i=this.frames,s=i?Math.max(0,Math.min(i-1,Math.round(t))):-1;s!==this.target&&this.fetched.clear(),this.target=s,this.dir=x(e)}next(){if(this.busy||this.target<0)return null;let t=this.reachable(this.target);if(t<0)return null;let e=this.host.has(t)?this.ahead(t):t;if(e<0)return null;e!==t&&this.fetched.add(e);let i=this.track.order[e],s=void 0===i?void 0:this.track.keyOf[i];if(void 0===i||void 0===s)return null;let r=Math.max(1,Math.floor(this.host.window()/2)),n=new Set([e]);for(let e=s;e<i;e++){let i=o(this.present,e);Math.abs(i-t)<=r&&!this.host.has(i)&&n.add(i)}return this.busy={from:s,to:i,goal:e,keep:n},this.busy}forget(){this.fetched.clear()}done(){this.busy=null}ready(t){if(!(t>=0&&t<this.frames))return!1;let e=this.track.order[t],i=void 0===e?void 0:this.track.keyOf[e];return void 0!==e&&void 0!==i&&this.host.available(e)&&this.host.available(i)}reachable(t){if(this.ready(t))return t;let e=this.frames;for(let i=1;i<e;i++){if(t-i>=0&&this.ready(t-i))return t-i;if(t+i<e&&this.ready(t+i))return t+i}return-1}ahead(t){let e=this.frames,i=this.host.window(),s=Math.min(12,Math.max(1,Math.floor(i/2)-1),Math.floor((i-1)/2));for(let i=1;i<=s;i++)for(let s=0;s<(this.dir?1:2);s++){let r=t+i*(this.dir||1-2*s);if(!(r<0||r>=e)&&!this.host.has(r)&&!this.fetched.has(r)&&this.ready(r))return r}return-1}};var S="umber:scrub-decode",E={hvc1:"HEVC (hvc1)",hev1:"HEVC (hev1)",av01:"AV1",vp09:"VP9",vp08:"VP8"},U=t=>"QuotaExceededError"===$(t),$=t=>"object"==typeof t&&null!==t&&"name"in t&&"string"==typeof t.name?t.name:"",C=(t,e)=>Math.round(t/e.timescale*1e6),F=class{constructor(t,e){this.url=t,this.host=e,this.tier="decoder",this.stream=new M,this.track=null,this.schedule=null,this.decoder=null,this.config=null,this.made=null,this.accel="no-preference",this.byTime=new Map,this.running=!1,this.on=!0,this.dead=!1,this.errors=0,this.timings=[],this.keep=null,this.outputs=0}start(){let t=this.stream;t.onTrack=t=>{this.configure(t)},t.onData=()=>{this.pump()},t.onError=t=>{this.fail(`could not read the video (${t instanceof Error?t.message:String(t)})`)},t.start(this.url)}async configure(t){let e=function(t){let{codec:e,description:i}=t;return e&&i?t.fragmented&&!t.order.length?"is a fragmented MP4 (its frames are indexed in fragments), which WebCodecs scrubbing doesn't read":t.order.length?{codec:e,description:i}:"has no frames in its index":`is ${E[t.format]??(t.format||"not H.264")}, and WebCodecs scrubbing reads H.264`}(t);if("string"==typeof e)return void this.fail(e,!0);this.warnAbout(t);let i={...e,codedWidth:t.width,codedHeight:t.height,optimizeForLatency:!0},s=await this.pickConfig(i);if(!this.dead){if(!s)return void this.fail(`this browser can't decode ${e.codec} with WebCodecs`);this.begin(t)}}warnAbout(t){this.stream.late&&!this.stream.done&&this.host.log.warn('scrub video is not "faststart" (its index is at the end), so nothing shows until it fully downloads. Encode it with: npm run scrub -- input.mov'),t.cuts&&this.host.log.warn("scrub video has an edit list with several cuts, which the scrub does not follow: it shows every frame of the file. Re-encode it with: npm run scrub -- input.mov"),t.gop>10&&this.host.log.warn(`scrub video has a keyframe only every ${t.gop} frames: each step back decodes up to that many. For smooth scrubbing encode it with: npm run scrub -- input.mov`)}async pickConfig(t){let e=typeof navigator<"u"&&/Android/i.test(navigator.userAgent)?function(){try{let[t,e,...i]=(localStorage.getItem(S)??"").split(" ");return("prefer-software"===t||"prefer-hardware"===t)&&i.join(" ")===navigator.userAgent&&Date.now()-Number(e)<2592e6?t:null}catch{return null}}()??"prefer-hardware":"no-preference",i="no-preference"===e?["no-preference"]:[e,"no-preference"];for(let e of i)try{let i="no-preference"===e?t:{...t,hardwareAcceleration:e},s=await VideoDecoder.isConfigSupported(i);if(this.dead)return!1;if(s.supported){this.config=i,this.accel=e;break}}catch{}return!!this.config}begin(t){this.track=t,t.order.forEach((e,i)=>{let s=t.samples[e];s&&this.byTime.set(C(s.cts,t),i)});let e=this.host.frames;this.schedule=new A(t,{has:t=>e.has(t),available:e=>{let i=t.samples[e];return void 0!==i&&this.stream.has(i)},window:()=>Math.min(e.capacity(t.width,t.height),48)}),this.host.ready({frames:t.order.length,fps:t.fps,width:t.width,height:t.height}),this.pump()}request(t,e){this.schedule&&(this.schedule.want(t,e),this.pump())}active(t){this.on=t,t?(this.schedule?.forget(),this.pump()):this.close()}reset(){this.schedule?.forget(),this.pump()}decoderNow(t){if(this.decoder&&"closed"!==this.decoder.state&&this.made===t)return this.decoder;this.close();let e=new VideoDecoder({output:t=>{this.output(t)},error:t=>{this.onError(e,t)}});return e.configure(t),this.made=t,this.decoder=e,e}output(t){this.outputs++;let e=this.byTime.get(t.timestamp);void 0===e||this.dead||!this.keep?.has(e)||this.host.frames.ready(e)?t.close():(this.host.frames.put(e,t,!0),this.host.delivered())}onError(t,e){t===this.decoder&&(this.decoder=null),U(e)||this.host.log.info("scrub decoder error",e)}chunk(t,e,i){let s=t.samples[e];if(!s)throw new RangeError(`sample ${e} is not in the track`);return new EncodedVideoChunk({type:i||s.key?"key":"delta",timestamp:C(s.cts,t),duration:C(s.duration,t),data:this.stream.data(s)})}async pump(){let t=this.schedule;if(this.running||this.dead||!this.on||!t||!this.track||!this.config)return;let e=t.next();if(!e)return;this.running=!0;let i=this.track,s=performance.now(),r=this.errors,n=!0;try{let t=this.decoderNow(this.config);this.keep=e.keep,this.outputs=0;for(let s=e.from;s<=e.to;s++)t.decode(this.chunk(i,s,s===e.from));await t.flush(),0===this.outputs&&(n=!1,this.errors++,this.close())}catch(t){n=!1,!U(t)&&"AbortError"!==$(t)&&this.errors++,this.close()}if(this.running=!1,!this.isDestroyed()){if(t.done(),n)this.errors=0,this.time((performance.now()-s)/(e.to-e.from+1));else{if(this.errors>=3)return void this.fail("the video decoder keeps failing");this.errors>r&&t.forget()}this.pump()}}time(t){if("prefer-hardware"!==this.accel||(this.timings.push(t),1===this.timings.length))return;let e=(s=this.timings.slice(1)).length<10?null:function(t){if(!t.length)return 0;let e=t.slice().sort((t,e)=>t-e);return o(e,Math.min(e.length-1,Math.ceil(.95*e.length)-1))}(s)>25;var s;if(null===e)return;let r=e?"prefer-software":"prefer-hardware";try{localStorage.setItem(S,`${r} ${Date.now()} ${navigator.userAgent}`)}catch{}if(this.accel="no-preference",!e||!this.config)return;let n={...this.config,hardwareAcceleration:"prefer-software"};VideoDecoder.isConfigSupported(n).then(t=>{!t.supported||this.dead||(this.host.log.info("scrub: hardware decoding is slow at seeking here; using the software decoder"),this.config=n,this.accel="prefer-software",this.running||this.close())}).catch(i)}close(){let t=this.decoder;if(this.decoder=null,t&&"closed"!==t.state)try{t.close()}catch{}}isDestroyed(){return this.dead}fail(t,e){this.dead||(this.destroy(),this.host.failed(t,e))}destroy(){this.dead=!0,this.stream.stop(),this.close(),this.schedule=null}};function N(...t){for(let e of t)if(e)return e;return""}var T=class{constructor(t,e,i,s){this.video=t,this.host=e,this.fps=i,this.src=s,this.tier="video",this.frames=0,this.target=-1,this.seeking=-1,this.landed=-1,this.fastFor=-1,this.errors=0,this.on=!0,this.dead=!1,this.cors=!1,this.offs=[]}start(){let t=this.video;t.muted=!0,t.playsInline=!0,t.setAttribute("playsinline",""),t.setAttribute("webkit-playsinline",""),t.disableRemotePlayback=!0,t.pause();let s=N(t.currentSrc,t.getAttribute("src"),t.querySelector("source")?.getAttribute("src")),r=N(this.src,s),n="auto"!==t.preload;t.preload="auto";let h=r?e(r):null;var o;h&&(o=h,!(("string"==typeof o?e(o):o)?.origin===location.origin))&&!t.crossOrigin&&(t.crossOrigin="anonymous",this.cors=!0,n=!0),this.src&&this.src!==s&&(t.src=this.src,n=!0),this.listen("seeked",()=>{this.onSeeked()}),this.listen("error",e=>{let i=t.querySelectorAll("source");(e.target===t||e.target===i[i.length-1])&&this.fail(this.cors?"the video failed to load (another domain: no CORS headers?)":"the video failed to load")},!0),t.readyState>=1&&!n?this.onMeta():(this.listen("loadedmetadata",()=>{this.onMeta()}),this.meta()),n&&t.load();let a=()=>{this.dead||t.readyState>=2||t.play().then(()=>{t.pause()}).catch(i)};addEventListener("touchstart",a,{once:!0,passive:!0}),this.offs.push(()=>{removeEventListener("touchstart",a)})}listen(t,e,i=!1){this.video.addEventListener(t,e,i),this.offs.push(()=>{this.video.removeEventListener(t,e,i)})}meta(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.frames||this.dead||(1===this.video.networkState?this.meta():this.fail("the video's metadata never loaded"))},1e4)}onMeta(){if(this.frames||this.dead)return;let t=this.video;!Number.isFinite(t.duration)||t.duration<=0?this.fail("the video has no duration (a live stream?)"):(this.frames=Math.max(1,Math.round(t.duration*this.fps)),this.host.ready({frames:this.frames,fps:this.fps,width:t.videoWidth,height:t.videoHeight}),this.pump())}request(t){this.frames&&(this.target=Math.max(0,Math.min(this.frames-1,Math.round(t))),this.pump())}active(t){this.on=t,this.pump()}reset(){this.seeking=-1,this.landed=-1,this.pump()}pump(){if(this.dead||!this.on||this.target<0)return;if(this.seeking>=0){let t=this.host.frames;if(!(this.landed>=0)||!t.ready(this.landed)&&t.has(this.landed))return;this.seeking=-1,this.landed=-1}let t=this.target;if(this.host.frames.has(t))return;let e=this.video;if(e.readyState<1)return;this.seeking=t,this.landed=-1;let i=Math.min((t+.5)/this.fps,Math.max(0,e.duration-.001)),s=Math.round(e.currentTime*this.fps-.5);"function"==typeof e.fastSeek&&Math.abs(t-s)>6&&t!==this.fastFor?(this.fastFor=t,e.fastSeek(i)):e.currentTime=i,clearTimeout(this.timer),this.timer=setTimeout(()=>{this.seeking<0||this.landed>=0||(this.seeking=-1,++this.errors>=3?this.fail("seeking the video never lands"):this.pump())},4e3)}onSeeked(){if(this.dead||this.seeking<0)return;clearTimeout(this.timer),this.errors=0;let t=this.video,e=Math.max(0,Math.min(this.frames-1,Math.floor(t.currentTime*this.fps+.001)));this.landed=e,this.host.frames.put(e,t,!1),this.host.delivered()}fail(t){this.dead||(this.destroy(),this.cors&&(this.video.removeAttribute("crossorigin"),this.video.load()),this.host.failed(t))}destroy(){this.dead=!0,clearTimeout(this.timer),this.offs.forEach(t=>{t()}),this.offs=[]}},P=class{constructor(t,e,i,s){this.pattern=t,this.count=e,this.fps=i,this.host=s,this.tier="frames",this.target=-1,this.dir=0,this.loading=new Set,this.failedFrames=new Set,this.errors=0,this.known=!1,this.width=0,this.height=0,this.on=!0,this.dead=!1,this.abort=typeof AbortController<"u"?new AbortController:null}start(){this.count>0?this.load(0):this.fail('data-umber-scrub-frames needs data-umber-scrub-count="<number of frames>"')}request(t,e){this.target=Math.max(0,Math.min(this.count-1,Math.round(t))),this.dir=x(e),this.pump()}active(t){this.on=t,this.pump()}reset(){this.pump()}pump(){if(this.dead||!this.on||!this.known||this.target<0)return;let t=this.host.frames,e=this.dir>=0?1:-1,i=t.capacity(this.width,this.height)-1,s=Math.min(2,i>>2),r=Math.min(8,i-s);for(let i=0;i<=Math.max(0,r+s)&&this.loading.size<4;i++){let s=this.target+(i<=r?i:r-i)*e;s<0||s>=this.count||t.has(s)||this.loading.has(s)||this.failedFrames.has(s)||this.load(s)}}async load(e){this.loading.add(e);let i=function(t,e){return t.replace(/\{(\d+)\}/,(t,i)=>String(parseInt(i,10)+e).padStart(i.length,"0"))}(this.pattern,e);try{let s=await(await t(i,{mode:"cors",credentials:"omit",signal:this.abort?.signal})).blob(),r=await createImageBitmap(s,{premultiplyAlpha:"premultiply",colorSpaceConversion:"default"}),n=this.host.maxTexture;if(r.width>n||r.height>n){let t=n/Math.max(r.width,r.height),e=await createImageBitmap(r,{resizeWidth:Math.floor(r.width*t),resizeHeight:Math.floor(r.height*t),resizeQuality:"high"});r.close(),r=e}if(this.loading.delete(e),this.dead)return void r.close();this.errors=0,this.known||(this.known=!0,this.width=r.width,this.height=r.height,this.host.ready({frames:this.count,fps:this.fps,width:r.width,height:r.height})),this.host.frames.put(e,r,!0),this.host.delivered()}catch(t){if(this.loading.delete(e),this.dead)return;if(this.failedFrames.add(e),this.host.log.warn(`scrub frame ${i} failed to load`,t),!this.known||++this.errors>=4)return void this.fail(`the image sequence ${this.pattern} does not load`)}this.pump()}fail(t){this.dead||(this.destroy(),this.host.failed(t))}destroy(){this.dead=!0,this.abort?.abort()}},L=()=>new Promise(t=>{let e=new MessageChannel;e.port1.onmessage=t,e.port2.postMessage(0)}),V={high:128,mid:48,low:32},D=new Set,W={start:"top bottom",end:"bottom top",track:"",smooth:-1,source:"auto",src:"",srcMobile:"",frames:"",count:0,fps:0,blend:!0,cache:0,reduced:""},z={uniforms:{uScrubProgress:0,uScrubVelocity:0},fragment:{head:"uniform sampler2D uFrameNext;\nuniform float uFrameMix;\nvec4 scrubNext(vec2 uv) {\n vec2 f = fitUv(uv);\n if (uFit > 0.5 && uFit < 1.5 && (f.x < 0.0 || f.y < 0.0 || f.x > 1.0 || f.y > 1.0)) return vec4(0.0);\n vec4 c = texture(uFrameNext, f);\n return vec4(c.rgb / max(c.a, 1e-5), c.a);\n}",color:"if (uFrameMix > 0.0) color = mix(color, scrubNext(uv), uFrameMix);"}};var O={kind:"scroll"},q=t=>({kind:"manual",value:t}),R=class{constructor(t,e){this.exporter=t,this.decoded=e,this.settle=null,this.want=[],this.stuck=0}frame(t,e){e?this.stuck=0:(this.want=t,!(this.settle||this.stuck>=20)&&this.exporter.wait(new Promise(t=>{let e=i=>{this.settle===e&&(this.settle=null,i&&this.stuck++,t())};this.settle=e,this.decoded(this.want)&&L().then(()=>{e()}),new Promise(t=>{"function"==typeof AbortSignal.timeout?AbortSignal.timeout(250).onabort=()=>{t()}:setTimeout(t,250)}).then(()=>{e(!0)})})))}delivered(){this.settle&&this.decoded(this.want)&&L().then(()=>{this.settle?.()})}end(){this.settle?.()}},H=class{constructor(t){this.ctx=t,this.handlers=new Map,this.readyWith=function(){let t,e;return{promise:new Promise((i,s)=>{t=i,e=s}),resolve:t,reject:e}}(),this.cache=null,this.tier="loading",this.fileFps=0,this.source=null,this.info=null,this.started=!1,this.dead=!1,this.progress=0,this.shown=0,this.target=0,this.velocity=0,this.dir=0,this.snap=!0,this.first=!0,this.autoplay=null;let e=this.el=t.el;this.log=t.log;let i=this.o=function(t,e,i){{let s=e.replace(/^data-/,""),r=i??{},o={};for(let t in r)o[t]={attr:`data-${s}-${n(t)}`,css:`--${s}-${n(t)}`,default:r[t]};return h(t,o,void 0)}}(e,"umber-scrub",W);this.drive="manual"===(e.getAttribute("data-umber-scrub")??"").trim().toLowerCase()?q(0):O,this.start=u(i.start,W.start),this.end=u(i.end,W.end),this.video=t.media instanceof HTMLVideoElement?t.media:null;let s="high"!==t.tier&&!!i.srcMobile;this.own=s?i.srcMobile:i.src,this.src=function(t,e){return N(e,t?.currentSrc,t?.getAttribute("src"),t?.querySelector("source")?.getAttribute("src"))}(this.video,this.own),this.opts=t.options,this.tiers=function(t,e,i,s){if("decoder"===t||"video"===t||"frames"===t)return[t];let r=[];return e&&(()=>{let t=globalThis;return"function"==typeof t.VideoDecoder&&"function"==typeof t.EncodedVideoChunk})()&&r.push("decoder"),i&&e&&r.push("video"),s&&r.push("frames"),r}((i.source||"auto").toLowerCase(),this.src,this.video,i.frames);let r=function(t,e){let i=e.trim();if(!i||"self"===i)return null;if("parent"===i)return t.parentElement;try{return i.startsWith("closest ")?t.closest(i.slice(8).trim()):t.closest(i)??document.querySelector(i)}catch{return null}}(e,i.track);i.track&&!r&&"self"!==i.track.trim()&&this.log.warn(`data-umber-scrub-track="${i.track}": no such element; the video's own position drives it.`,e),this.tracker=r?t.engine.track(r):null;let o=(()=>{let t=typeof window<"u"?window.occluzeCapture:void 0;return 1===t?.version?t:null})();this.wait=o?new R(o,t=>t.every(t=>this.frames().has(t))):null,this.api=function(t){let e=()=>{t.ctx.wake()},i={get progress(){return t.progress},set progress(i){t.drive=q(Math.min(1,Math.max(0,i||0))),e()},get drive(){return t.drive.kind},set drive(i){t.drive="manual"===i?q(t.progress):O,e()},get time(){return t.info?t.shown/t.info.fps:0},set time(e){t.info&&(i.progress=e*t.info.fps/Math.max(1,t.info.frames-1))},get frame(){return t.shown},get frames(){return t.info?.frames??0},get fps(){return t.info?.fps??0},get duration(){return t.info?t.info.frames/t.info.fps:0},get tier(){return t.tier},get ready(){return t.ready},on:(e,s)=>(t.on(e,s),()=>{i.off(e,s)}),off(e,i){t.off(e,i)},destroy(){t.ctx.plane.destroy()}};return i}(this)}get ready(){return this.readyWith.promise}frames(){return this.cache||(this.cache=this.ctx.frames,this.cache.budget=this.budgetMB()*2**20),this.cache}budgetMB(){if(this.o.cache>0)return this.o.cache;let t=this.opts.cacheMB??0;return t>0?t:V[this.ctx.tier]}on(t,e){let i=this.handlers.get(t);i||(i=new Set,this.handlers.set(t,i)),i.add(e)}off(t,e){this.handlers.get(t)?.delete(e)}emit(t){let e=this.handlers.get(t);if(e)for(let i of[...e])if(e.has(i))try{i(this.api)}catch(e){this.log.error(`a scrub "${t}" handler threw:`,e)}}still(t){let e=this.video;e&&(t&&null===this.autoplay?(this.autoplay=e.autoplay,e.autoplay=!1,e.pause()):!t&&null!==this.autoplay&&(e.autoplay=this.autoplay,this.autoplay&&e.isConnected&&e.play().catch(i),this.autoplay=null))}poster(t){this.still(!1),this.tier="poster",this.source?.destroy(),this.source=null,this.info=null,this.ctx.busy(!1),this.ctx.fail(t),this.readyWith.resolve(!1),this.wait?.end(),this.emit("tier")}host(){let t=()=>this.frames();return{get frames(){return t()},log:this.log,maxTexture:this.ctx.maxTexture,ready:t=>{this.sourceReady(t)},delivered:()=>{this.delivered()},failed:(t,e)=>{this.failed(t,e)}}}sourceReady(t){this.dead||("decoder"===this.tier&&(this.fileFps=t.fps),this.info&&this.info.frames!==t.frames&&(this.shown=Math.min(this.shown,t.frames-1)),this.info=t,this.snap=!0,this.ctx.wake())}delivered(){this.dead||(this.first&&(this.first=!1,this.readyWith.resolve(!0),this.emit("ready")),this.wait?.delivered(),this.ctx.wake())}failed(t,e){if(this.dead)return;let i=e?new URL(this.src,location.href).href:"",s=e?`the video ${i} ${t}. Encode it with: npm run scrub -- input.mov`:t;if(e&&this.tiers.length&&!D.has(i)){D.add(i);let t="video"===this.tiers[0]?"by seeking the <video>, which is choppier":"from its image sequence";this.log.warn(`scrub: ${s.replace(/\. Encode/,`, so it scrubs ${t}. Encode`)}`,this.el)}else this.log.info(`scrub: ${this.tier} tier failed (${s})`,this.el);this.cache?.clear(),this.info=null,this.source=null,this.wait?.end(),this.next(s)}next(t){let e=this.tiers.shift();if(!e)return this.emit("error"),void this.poster(`scrub: ${t??"nothing to scrub (no video src and no data-umber-scrub-frames)"}; the <video> and its poster show instead.`);this.tier=e,this.still(!0);let i=this.sourceFor(e);i?(this.source=i,i.start(),this.emit("tier")):this.next('data-umber-scrub-source="video" needs a <video>')}sourceFor(t){let e=this.o;return"decoder"===t?new F(new URL(this.src,location.href).href,this.host()):"video"===t?this.video?new T(this.video,this.host(),e.fps>0?e.fps:this.fileFps||30,this.own):null:new P(e.frames,Math.round(e.count),e.fps>0?e.fps:30,this.host())}smoothing(){return this.ctx.reducedMotion?0:this.o.smooth>=0?this.o.smooth:"lenis"===this.ctx.scrollKind||this.ctx.engine.scroll||document.documentElement.classList.contains("lenis")?0:.12}binding(){let t={uniforms:z.uniforms},e=N(this.o.reduced,this.opts.reducedMotion,"poster").toLowerCase();return this.ctx.reducedMotion&&"scrub"!==e?(this.poster(),{api:this.api,source:!0,effect:t}):this.tiers.length?{api:this.api,source:!0,effect:z,near:t=>{this.near(t)},update:(t,e,i)=>this.update(t,e,i),lost:()=>{this.snap=!0},src:()=>!this.own,restored:()=>{this.source?.reset(),this.ctx.wake()},destroy:()=>{this.destroy()}}:(this.poster(`scrub: nothing to scrub here (${this.video?"the <video> has no src":"no <video> inside"} and no data-umber-scrub-frames); it shows as plain DOM.`),{api:this.api,source:!0,effect:t})}near(t){if(!this.dead&&"poster"!==this.tier){if(t&&(this.snap=!0),!this.started&&t)return this.started=!0,void this.next();this.source?.active(t),t||this.cache?.clear(!0)}}progressNow(t,e){if("manual"===this.drive.kind)return this.drive.value;let i=this.tracker?this.tracker.rect.y:o(t,1),s=this.tracker?this.tracker.rect.height:o(t,3);return s>0?function({top:t,height:e},i,s,r){let n=s=>(s.alt&&e>i&&(s=s.alt),t+e*s.el+s.elPx-(i*s.vp+s.vpPx)),h=n(s),o=h-n(r);return Math.abs(o)>1e-6?Math.min(1,Math.max(0,h/o)):h<=0?1:0}({top:i,height:s},e.height,this.start,this.end):null}update(t,e,i){let s=this.info;if(!s||!this.source||this.dead)return!1;let r=this.progressNow(e,i);if(null===r)return!1;this.progress=r;let n=s.frames;this.target=r*(n-1);let h=this.shown;return this.shown=this.snap?this.target:function(t,e,i,s){return i>0&&s>0?t+(e-t)*(1-Math.exp(-s/i)):e}(this.shown,this.target,this.smoothing(),t.dt),this.snap=!1,Math.abs(this.target-this.shown)<.01&&(this.shown=this.target),this.velocity=t.dt>0?(this.shown-h)/Math.max(1,n-1)/t.dt:0,this.dir=Math.sign(this.target-this.shown)||Math.sign(this.shown-h)||this.dir,this.ctx.busy(this.shown!==this.target),this.draw(n,e,i),this.uniforms(n,this.shown!==h)}draw(t,e,i){let s=this.frames();s.focus(Math.round(this.shown)),this.source?.request(this.shown,this.dir);let r=function(t,e,i,s){let r=t=>i.ready(t);if(e<=0)return null;let n=Math.max(0,Math.min(e-1,t)),h=Math.floor(n),o=n-h;if(s&&o>.001&&h+1<e&&r(h)&&r(h+1))return{a:h,b:h+1,mix:o};let a=Math.round(n);if(r(a))return{a:a,b:-1,mix:0};let l=-1;for(let t of i.keys())(l<0||Math.abs(t-n)<Math.abs(l-n))&&(l=t);return l<0?null:{a:l,b:-1,mix:0}}(this.shown,t,s,this.o.blend);r&&s.show(r.a,r.b,r.mix);let n=o(e,0),h=o(e,1),a=h<i.height&&h+o(e,3)>0&&n<i.width&&n+o(e,2)>0;if(!this.wait||!a)return;let l=Math.round(Math.max(0,Math.min(t-1,this.shown)));this.wait.frame([l],s.ready(l))}uniforms(t,e){let i=this.ctx.plane.uniforms;if(i.uScrubProgress&&(i.uScrubProgress.value=this.shown/Math.max(1,t-1)),!i.uScrubVelocity)return e;let s=e?this.velocity:0,r=e||i.uScrubVelocity.value!==s;return i.uScrubVelocity.value=s,r}destroy(){this.dead=!0,this.source?.destroy(),this.source=null,this.still(!1),this.tracker?.destroy(),this.handlers.clear(),this.wait?.end(),this.first&&this.readyWith.resolve(!1)}};!function(t){let e,i=window;i.Umber?.use?i.Umber.use(t,e):(i.UmberModules??=[],i.UmberModules.push(e?[t,e]:t),i.__umber?.engine?.use?.(t,e))}({name:"scrub",version:"0.3.0",attributes:["scrub"],plane:t=>function(t){return new H(t).binding()}(t)})})();
|
|
1
|
+
/*! Umber v0.4.1 | (c) Ravi Klaassens | UNLICENSED */
|
|
2
|
+
(()=>{async function t(t,e){let i=await fetch(t,e);if(!i.ok)throw new Error(`${t} answered ${i.status}`);return i}function e(t,e=location.href){try{return new URL(t,e)}catch{return null}}var i=()=>{};function s(t,e){let i=t.trim();if("number"===e){let t=parseFloat(i);return Number.isFinite(t)?t:void 0}return"boolean"===e?function(t){let e=t.trim().toLowerCase();return""===e||"true"===e||"1"===e||"yes"===e||"false"!==e&&"0"!==e&&"no"!==e&&void 0}(i):"list"===e?i.split(/[\s,]+/).filter(Boolean):i.replace(/^["']|["']$/g,"")}function r(t){return t.type?t.type:"number"==typeof t.default?"number":"boolean"==typeof t.default?"boolean":Array.isArray(t.default)?"list":"string"}var n=t=>t.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`);function h(t,e,i){let n={},h=i;for(let[i,o]of Object.entries(e)){let e,a=r(o);if(o.attr){let i=t.getAttribute(o.attr);null!==i&&(e=s(i,a))}if(void 0===e&&o.css){h??=getComputedStyle(t);let i=h.getPropertyValue(o.css);i&&""!==i.trim()&&(e=s(i,a))}n[i]=void 0===e?o.default:e}return n}var o=(t,e)=>t[e]??NaN,a={top:0,left:0,center:.5,middle:.5,bottom:1,right:1};function l(t,e){let i=(t??"").trim().toLowerCase();if(!i)return e;let s=function(t){let e=/^(top|left|center|middle|bottom|right|-?\d*\.?\d+(?:px|%)?)?(?:([+-])=?(\d*\.?\d+)(px|%)?)?$/.exec(t);if(!e)return null;let[,i,s,r="",n]=e;if(!i&&!s)return null;let h=0,o=0,l=void 0===i?void 0:a[i];if(void 0!==l)h=l;else if(i){let t=parseFloat(i);i.endsWith("%")?h=t/100:o=t}if(s){let t=parseFloat(r)*("-"===s?-1:1);"%"===n?h+=t/100:o+=t}return[h,o]}(i);return s?/^[+-]/.test(i)&&!/^-\d/.test(i)?[e[0]+s[0],e[1]+s[1]]:s:e}var d={cover:[[0,1,1,0]],contain:[[1,1,0,0],[0,0,1,1]],entry:[[0,1,1,1],[0,1,0,0]],exit:[[0,0,1,0],[1,1,1,0]],"entry-crossing":[[0,1,1,1]],"exit-crossing":[[0,0,1,0]]};function u(t,e){let i=function(t,e){return null==t||""===t?e:t}(t,e).trim().split(/\s+/),s=function(t,e){let[i,s]=t,r=void 0===i?void 0:d[i];if(void 0===r)return null;let[n,h]=r,o=s??(e?"100%":"0%"),a=o.endsWith("%")?0:parseFloat(o)||0,l=a?0:parseFloat(o)/100||0,u=([t,e,i,s])=>({el:t+(i-t)*l,elPx:a,vp:e+(s-e)*l,vpPx:0});return{...u(n),alt:h?u(h):void 0}}(i.map(t=>t.toLowerCase()),e.startsWith("bottom"));if(s)return s;let r=e.split(/\s+/),[n,h]=l(i[0],l(r[0],[0,0])),[o,a]=l(i[1],l(r[1],[0,0]));return{el:n,elPx:h,vp:o,vpPx:a}}var c=(t,e)=>String.fromCharCode(o(t,e),o(t,e+1),o(t,e+2),o(t,e+3));function f(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function m(t,e,i){let s=e.body+i;return s+4<=Math.min(e.end,t.length)?f(t).getUint32(s):Number.NaN}function p(t,e,i,s){let r=m(t,e,i-4);return r*s<=Math.min(e.end,t.length)-(e.body+i)?r:null}var g=2**21;function b(t,e,i=t.length){if(e+8>i)return null;let s=f(t),r=s.getUint32(e),n=c(t,e+4),h=e+8;if(1===r){if(e+16>i)return null;r=s.getUint32(e+8)*2**32+s.getUint32(e+12),h=e+16}else 0===r&&(r=1/0);return r<h-e?null:{type:n,start:e,body:h,end:e+r}}function y(t,e,i){let s=[],r=e;for(;r<i;){let e=b(t,r,i);if(!e||e.end>i||e.end<=r)break;s.push(e),r=e.end}return s}var w=(t,e,i)=>y(t,e.body,e.end).find(t=>t.type===i)??null;function v(t,e,...i){for(let s of i){if(!e)return null;e=w(t,e,s)}return e}function k(t,e,i){let s=v(t,e,"mdia","mdhd"),r=v(t,e,"mdia","minf","stbl");if(!s||!r)return null;let n=m(t,s,1===t[s.body]?20:12);if(Number.isNaN(n))return null;let h=n||1,a=function(t,e){let i=w(t,e,"stsd");if(!i)return null;let s=b(t,i.body+8,i.end);if(!s||s.end>i.end||s.body+28>s.end)return null;let r=f(t),n=s.type,h="",o=null,a=y(t,s.body+78,s.end).find(t=>"avcC"===t.type);return a&&("avc1"===n||"avc3"===n)&&(o=t.slice(a.body,a.end),h=function(t){let e=t=>t.toString(16).padStart(2,"0"),[,i,s,r]=t;return void 0===i||void 0===s||void 0===r?"":`avc1.${e(i)}${e(s)}${e(r)}`}(o)),{format:n,width:r.getUint16(s.body+24),height:r.getUint16(s.body+26),codec:h,description:o}}(t,r);if(!a)return null;let[l,d]=function(t,e){let i=w(t,e,"tkhd");if(!i)return null;let s=i.body+(1===t[i.body]?88:76);if(s+8>i.end)return null;let r=f(t),n=r.getUint32(s)/65536,h=r.getUint32(s+4)/65536;return n&&h?[Math.round(n),Math.round(h)]:null}(t,e)??[a.width,a.height],u=function(t,e){let i=i=>w(t,e,i),s=function(t,e,i){return e?function(t,e){let i=f(t),s=m(t,e,4),r=s?m(t,e,8):p(t,e,12,4);if(null===r||!(r<=g))return null;let n=new Array(r);for(let t=0;t<r;t++)n[t]=s||i.getUint32(e.body+12+4*t);return n}(t,e):i?function(t,e){let i=t[e.body+7];if(4!==i&&8!==i&&16!==i)return null;let s=p(t,e,12,i/8);if(null===s||s>g)return null;let r=f(t),n=e.body+12,h=new Array(s);for(let e=0;e<s;e++)h[e]=16===i?r.getUint16(n+2*e):8===i?o(t,n+e):o(t,n+(e>>1))>>(1&e?0:4)&15;return h}(t,i):null}(t,i("stsz"),i("stz2")),r=function(t,e,i){let s=e??i;if(!s)return null;let r=e?4:8,n=p(t,s,8,r);if(null===n)return null;let h=f(t),o=new Array(n);for(let t=0;t<n;t++){let i=s.body+8+t*r;o[t]=e?h.getUint32(i):h.getUint32(i)*2**32+h.getUint32(i+4)}return o}(t,i("stco"),i("co64")),n=i("stsc");if(!s||!r||!n)return null;let h=function(t,e,i,s){let r=i.length,n=function(t,e){let i=p(t,e,8,12);if(null===i)return null;let s=f(t),r=[];for(let t=0;t<i;t++){let i=e.body+8+12*t;r.push({first:s.getUint32(i)-1,per:s.getUint32(i+4)})}return r}(t,e);if(!n)return null;let h=new Array(r),a=0;for(let[t,e]of n.entries()){if(a>=r)break;let l=n[t+1]?.first??s.length;for(let t=e.first;t<l&&a<r;t++){let n=s[t];if(void 0===n)return null;for(let t=0;t<e.per&&a<r;t++)h[a]=n,n+=o(i,a),a++}}return a<r?null:h}(t,n,s,r),a=i("stts");if(!h||!a)return null;let l=s.length,d=function(t,e,i){let s=f(t),r=new Array(i),n=new Array(i),h=0,o=0,a=p(t,e,8,8);if(null===a)return null;for(let t=0;t<a&&o<i;t++){let a=s.getUint32(e.body+8+8*t),l=s.getUint32(e.body+12+8*t);for(let t=0;t<a&&o<i;t++)r[o]=h,n[o]=l,h+=l,o++}for(;o<i;o++)r[o]=h,n[o]=0;return{dts:r,durations:n}}(t,a,l);if(!d)return null;let{dts:u,durations:c}=d,b=function(t,e,i){let s=i.slice();if(!e)return s;let r=f(t),n=i.length,h=p(t,e,8,8);if(null===h)return null;let a=0;for(let t=0;t<h&&a<n;t++){let i=r.getUint32(e.body+8+8*t),h=r.getInt32(e.body+12+8*t);for(let t=0;t<i&&a<n;t++,a++)s[a]=o(s,a)+h}return s}(t,i("ctts"),u),y=function(t,e,i){let s=new Array(i).fill(!e);if(e){let r=f(t),n=p(t,e,8,4);if(null===n)return null;for(let t=0;t<n;t++){let n=r.getUint32(e.body+8+4*t)-1;n>=0&&n<i&&(s[n]=!0)}}return i&&(s[0]=!0),s}(t,i("stss"),l);return b&&y?s.map((t,e)=>({offset:o(h,e),size:t,dts:o(u,e),cts:o(b,e),duration:o(c,e),key:!0===y[e]})):null}(t,r);if(!u)return null;let c=function(t,e,i,s){let r=v(t,e,"edts","elst");if(!r)return null;let n=f(t),h=1===t[r.body],o=h?20:12,a=m(t,r,4),l=null;for(let t=0;t<a;t++){let e=r.body+8+t*o;if(e+o>r.end)break;let a=h?n.getUint32(e)*2**32+n.getUint32(e+4):n.getUint32(e),d=h?n.getInt32(e+8)*2**32+n.getUint32(e+12):n.getInt32(e+4);if(!(d<0)){if(l)return"cuts";l=[d,a?d+a*i/s:1/0]}}return l}(t,e,h,i||h),k="cuts"===c?null:c,M=t=>!k||t.cts+t.duration/2>=k[0]&&t.cts+t.duration/2<k[1],x=[];for(let[t,e]of u.entries())M(e)&&x.push(t);let A=u.map(t=>t.cts);x.sort((t,e)=>o(A,t)-o(A,e)||t-e);let{keyOf:S,gop:U}=function(t){let e=t.length,i=new Array(e),s=0,r=1;for(let[e,n]of t.entries())n.key&&(e&&(r=Math.max(r,e-s)),s=e),i[e]=s;return e&&(r=Math.max(r,e-s)),{keyOf:i,gop:r}}(u),[E]=x,$=x.at(-1),C=void 0===E?void 0:u[E],F=void 0===$?void 0:u[$],N=(C&&F?F.cts+F.duration-C.cts:0)/h;return{codec:a.codec,format:a.format,description:a.description,width:l,height:d,timescale:h,duration:N,fps:N>0?x.length/N:30,samples:u,order:x,keyOf:S,gop:U,cuts:"cuts"===c}}var M=class{constructor(){this.bytes=new Uint8Array(0),this.loaded=0,this.total=0,this.done=!1,this.track=null,this.late=!1,this.onTrack=null,this.onData=null,this.onError=null,this.cursor=0,this.sawMdat=!1,this.failed=!1,this.abort=null,this.reader=null}start(t){this.abort=typeof AbortController<"u"?new AbortController:null,this.run(t).catch(t=>{this.abort?.signal.aborted||this.onError?.(t)})}async run(e){let i=await t(e,{mode:"cors",credentials:"omit",signal:this.abort?.signal}),s=Number(i.headers.get("content-length"))||0;s&&!i.headers.get("content-encoding")&&(this.total=s);let r=i.body?.getReader();if(!r)return this.push(new Uint8Array(await i.arrayBuffer())),void this.finish();for(this.reader=r;;){let{done:t,value:e}=await r.read();if(this.failed)return;if(t)break;e.length&&this.push(e)}this.finish()}push(t){if(this.failed)return;let e=this.loaded+t.length;if(e>this.bytes.length){let t=Math.min(this.total,67108864),i=new Uint8Array(Math.max(e,t,2*this.bytes.length,1<<20));i.set(this.bytes.subarray(0,this.loaded)),this.bytes=i}this.bytes.set(t,this.loaded),this.loaded=e,this.scan(),this.onData?.()}finish(){this.done=!0,this.scan(),!this.track&&!this.failed&&this.onError?.(new Error("no H.264 video track found (is it an MP4?)")),this.onData?.()}fail(t){this.failed=!0,this.abort?.abort(),this.reader?.cancel().catch(()=>{}),this.onError?.(t)}scan(){for(;!this.track&&!this.failed;){let t=b(this.bytes,this.cursor,this.loaded);if(!t)return;if("moov"===t.type)return void(t.end<=this.loaded&&this.read(t));if("mdat"===t.type&&(this.sawMdat=!0),!Number.isFinite(t.end))return;this.cursor=t.end}}read(t){this.late=this.sawMdat;let e=function(t,e){let i=w(t,e,"mvhd"),s=i?m(t,i,1===t[i.body]?20:12):0;if(Number.isNaN(s))return null;for(let i of y(t,e.body,e.end)){if("trak"!==i.type)continue;let r=v(t,i,"mdia","hdlr");if(!r||"vide"!==c(t,r.body+8))continue;let n=k(t,i,s);if(n)return w(t,e,"mvex")&&(n.fragmented=!0),n}return null}(this.bytes,t);e?(this.track=e,this.onTrack?.(e)):this.fail(new Error("the MP4 has no video track"))}has(t){return t.offset+t.size<=this.loaded}data(t){return this.bytes.subarray(t.offset,t.offset+t.size)}stop(){this.abort?.abort(),this.onTrack=null,this.onData=null,this.onError=null}};function x(t){return t>0?1:t<0?-1:0}var A=class{constructor(t,e){this.track=t,this.host=e,this.target=-1,this.dir=0,this.busy=null,this.fetched=new Set,this.present=new Array(t.order.length),t.order.forEach((t,e)=>{this.present[t]=e})}get frames(){return this.track.order.length}want(t,e=0){let i=this.frames,s=i?Math.max(0,Math.min(i-1,Math.round(t))):-1;s!==this.target&&this.fetched.clear(),this.target=s,this.dir=x(e)}next(){if(this.busy||this.target<0)return null;let t=this.reachable(this.target);if(t<0)return null;let e=this.host.has(t)?this.ahead(t):t;if(e<0)return null;e!==t&&this.fetched.add(e);let i=this.track.order[e],s=void 0===i?void 0:this.track.keyOf[i];if(void 0===i||void 0===s)return null;let r=Math.max(1,Math.floor(this.host.window()/2)),n=new Set([e]);for(let e=s;e<i;e++){let i=o(this.present,e);Math.abs(i-t)<=r&&!this.host.has(i)&&n.add(i)}return this.busy={from:s,to:i,goal:e,keep:n},this.busy}forget(){this.fetched.clear()}done(){this.busy=null}ready(t){if(!(t>=0&&t<this.frames))return!1;let e=this.track.order[t],i=void 0===e?void 0:this.track.keyOf[e];return void 0!==e&&void 0!==i&&this.host.available(e)&&this.host.available(i)}reachable(t){if(this.ready(t))return t;let e=this.frames;for(let i=1;i<e;i++){if(t-i>=0&&this.ready(t-i))return t-i;if(t+i<e&&this.ready(t+i))return t+i}return-1}ahead(t){let e=this.frames,i=this.host.window(),s=Math.min(12,Math.max(1,Math.floor(i/2)-1),Math.floor((i-1)/2));for(let i=1;i<=s;i++)for(let s=0;s<(this.dir?1:2);s++){let r=t+i*(this.dir||1-2*s);if(!(r<0||r>=e)&&!this.host.has(r)&&!this.fetched.has(r)&&this.ready(r))return r}return-1}};var S="umber:scrub-decode",U={hvc1:"HEVC (hvc1)",hev1:"HEVC (hev1)",av01:"AV1",vp09:"VP9",vp08:"VP8"},E=t=>"QuotaExceededError"===$(t),$=t=>"object"==typeof t&&null!==t&&"name"in t&&"string"==typeof t.name?t.name:"",C=(t,e)=>Math.round(t/e.timescale*1e6),F=class{constructor(t,e){this.url=t,this.host=e,this.tier="decoder",this.stream=new M,this.track=null,this.schedule=null,this.decoder=null,this.config=null,this.made=null,this.accel="no-preference",this.byTime=new Map,this.running=!1,this.on=!0,this.dead=!1,this.errors=0,this.timings=[],this.keep=null,this.outputs=0}start(){let t=this.stream;t.onTrack=t=>{this.configure(t)},t.onData=()=>{this.pump()},t.onError=t=>{this.fail(`could not read the video (${t instanceof Error?t.message:String(t)})`)},t.start(this.url)}async configure(t){let e=function(t){let{codec:e,description:i}=t;return e&&i?t.fragmented&&!t.order.length?"is a fragmented MP4 (its frames are indexed in fragments), which WebCodecs scrubbing doesn't read":t.order.length?{codec:e,description:i}:"has no frames in its index":`is ${U[t.format]??(t.format||"not H.264")}, and WebCodecs scrubbing reads H.264`}(t);if("string"==typeof e)return void this.fail(e,!0);this.warnAbout(t);let i={...e,codedWidth:t.width,codedHeight:t.height,optimizeForLatency:!0},s=await this.pickConfig(i);if(!this.dead){if(!s)return void this.fail(`this browser can't decode ${e.codec} with WebCodecs`);this.begin(t)}}warnAbout(t){this.stream.late&&!this.stream.done&&this.host.log.warn('scrub video is not "faststart" (its index is at the end), so nothing shows until it fully downloads. Encode it with: npm run scrub -- input.mov'),t.cuts&&this.host.log.warn("scrub video has an edit list with several cuts, which the scrub does not follow: it shows every frame of the file. Re-encode it with: npm run scrub -- input.mov"),t.gop>10&&this.host.log.warn(`scrub video has a keyframe only every ${t.gop} frames: each step back decodes up to that many. For smooth scrubbing encode it with: npm run scrub -- input.mov`)}async pickConfig(t){let e=typeof navigator<"u"&&/Android/i.test(navigator.userAgent)?function(){try{let[t,e,...i]=(localStorage.getItem(S)??"").split(" ");return("prefer-software"===t||"prefer-hardware"===t)&&i.join(" ")===navigator.userAgent&&Date.now()-Number(e)<2592e6?t:null}catch{return null}}()??"prefer-hardware":"no-preference",i="no-preference"===e?["no-preference"]:[e,"no-preference"];for(let e of i)try{let i="no-preference"===e?t:{...t,hardwareAcceleration:e},s=await VideoDecoder.isConfigSupported(i);if(this.dead)return!1;if(s.supported){this.config=i,this.accel=e;break}}catch{}return!!this.config}begin(t){this.track=t,t.order.forEach((e,i)=>{let s=t.samples[e];s&&this.byTime.set(C(s.cts,t),i)});let e=this.host.frames;this.schedule=new A(t,{has:t=>e.has(t),available:e=>{let i=t.samples[e];return void 0!==i&&this.stream.has(i)},window:()=>Math.min(e.capacity(t.width,t.height),48)}),this.host.ready({frames:t.order.length,fps:t.fps,width:t.width,height:t.height}),this.pump()}request(t,e){this.schedule&&(this.schedule.want(t,e),this.pump())}active(t){this.on=t,t?(this.schedule?.forget(),this.pump()):this.close()}reset(){this.schedule?.forget(),this.pump()}decoderNow(t){if(this.decoder&&"closed"!==this.decoder.state&&this.made===t)return this.decoder;this.close();let e=new VideoDecoder({output:t=>{this.output(t)},error:t=>{this.onError(e,t)}});return e.configure(t),this.made=t,this.decoder=e,e}output(t){this.outputs++;let e=this.byTime.get(t.timestamp);void 0===e||this.dead||!this.keep?.has(e)||this.host.frames.ready(e)?t.close():(this.host.frames.put(e,t,!0),this.host.delivered())}onError(t,e){t===this.decoder&&(this.decoder=null),E(e)||this.host.log.info("scrub decoder error",e)}chunk(t,e,i){let s=t.samples[e];if(!s)throw new RangeError(`sample ${e} is not in the track`);return new EncodedVideoChunk({type:i||s.key?"key":"delta",timestamp:C(s.cts,t),duration:C(s.duration,t),data:this.stream.data(s)})}async pump(){let t=this.schedule;if(this.running||this.dead||!this.on||!t||!this.track||!this.config)return;let e=t.next();if(!e)return;this.running=!0;let i=this.track,s=performance.now(),r=this.errors,n=!0;try{let t=this.decoderNow(this.config);this.keep=e.keep,this.outputs=0;for(let s=e.from;s<=e.to;s++)t.decode(this.chunk(i,s,s===e.from));await t.flush(),0===this.outputs&&(n=!1,this.errors++,this.close())}catch(t){n=!1,!E(t)&&"AbortError"!==$(t)&&this.errors++,this.close()}if(this.running=!1,!this.isDestroyed()){if(t.done(),n)this.errors=0,this.time((performance.now()-s)/(e.to-e.from+1));else{if(this.errors>=3)return void this.fail("the video decoder keeps failing");this.errors>r&&t.forget()}this.pump()}}time(t){if("prefer-hardware"!==this.accel||(this.timings.push(t),1===this.timings.length))return;let e=(s=this.timings.slice(1)).length<10?null:function(t){if(!t.length)return 0;let e=t.slice().sort((t,e)=>t-e);return o(e,Math.min(e.length-1,Math.ceil(.95*e.length)-1))}(s)>25;var s;if(null===e)return;let r=e?"prefer-software":"prefer-hardware";try{localStorage.setItem(S,`${r} ${Date.now()} ${navigator.userAgent}`)}catch{}if(this.accel="no-preference",!e||!this.config)return;let n={...this.config,hardwareAcceleration:"prefer-software"};VideoDecoder.isConfigSupported(n).then(t=>{!t.supported||this.dead||(this.host.log.info("scrub: hardware decoding is slow at seeking here; using the software decoder"),this.config=n,this.accel="prefer-software",this.running||this.close())}).catch(i)}close(){let t=this.decoder;if(this.decoder=null,t&&"closed"!==t.state)try{t.close()}catch{}}isDestroyed(){return this.dead}fail(t,e){this.dead||(this.destroy(),this.host.failed(t,e))}destroy(){this.dead=!0,this.stream.stop(),this.close(),this.schedule=null}};function N(...t){for(let e of t)if(e)return e;return""}var T=class{constructor(t,e,i,s){this.video=t,this.host=e,this.fps=i,this.src=s,this.tier="video",this.frames=0,this.target=-1,this.seeking=-1,this.landed=-1,this.fastFor=-1,this.errors=0,this.on=!0,this.dead=!1,this.cors=!1,this.offs=[]}start(){let t=this.video;t.muted=!0,t.playsInline=!0,t.setAttribute("playsinline",""),t.setAttribute("webkit-playsinline",""),t.disableRemotePlayback=!0,t.pause();let s=N(t.currentSrc,t.getAttribute("src"),t.querySelector("source")?.getAttribute("src")),r=N(this.src,s),n="auto"!==t.preload;t.preload="auto";let h=r?e(r):null;var o;h&&(o=h,!(("string"==typeof o?e(o):o)?.origin===location.origin))&&!t.crossOrigin&&(t.crossOrigin="anonymous",this.cors=!0,n=!0),this.src&&this.src!==s&&(t.src=this.src,n=!0),this.listen("seeked",()=>{this.onSeeked()}),this.listen("error",e=>{let i=t.querySelectorAll("source");(e.target===t||e.target===i[i.length-1])&&this.fail(this.cors?"the video failed to load (another domain: no CORS headers?)":"the video failed to load")},!0),t.readyState>=1&&!n?this.onMeta():(this.listen("loadedmetadata",()=>{this.onMeta()}),this.meta()),n&&t.load();let a=()=>{this.dead||t.readyState>=2||t.play().then(()=>{t.pause()}).catch(i)};addEventListener("touchstart",a,{once:!0,passive:!0}),this.offs.push(()=>{removeEventListener("touchstart",a)})}listen(t,e,i=!1){this.video.addEventListener(t,e,i),this.offs.push(()=>{this.video.removeEventListener(t,e,i)})}meta(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.frames||this.dead||(1===this.video.networkState?this.meta():this.fail("the video's metadata never loaded"))},1e4)}onMeta(){if(this.frames||this.dead)return;let t=this.video;!Number.isFinite(t.duration)||t.duration<=0?this.fail("the video has no duration (a live stream?)"):(this.frames=Math.max(1,Math.round(t.duration*this.fps)),this.host.ready({frames:this.frames,fps:this.fps,width:t.videoWidth,height:t.videoHeight}),this.pump())}request(t){this.frames&&(this.target=Math.max(0,Math.min(this.frames-1,Math.round(t))),this.pump())}active(t){this.on=t,this.pump()}reset(){this.seeking=-1,this.landed=-1,this.pump()}pump(){if(this.dead||!this.on||this.target<0)return;if(this.seeking>=0){let t=this.host.frames;if(!(this.landed>=0)||!t.ready(this.landed)&&t.has(this.landed))return;this.seeking=-1,this.landed=-1}let t=this.target;if(this.host.frames.has(t))return;let e=this.video;if(e.readyState<1)return;this.seeking=t,this.landed=-1;let i=Math.min((t+.5)/this.fps,Math.max(0,e.duration-.001)),s=Math.round(e.currentTime*this.fps-.5);"function"==typeof e.fastSeek&&Math.abs(t-s)>6&&t!==this.fastFor?(this.fastFor=t,e.fastSeek(i)):e.currentTime=i,clearTimeout(this.timer),this.timer=setTimeout(()=>{this.seeking<0||this.landed>=0||(this.seeking=-1,++this.errors>=3?this.fail("seeking the video never lands"):this.pump())},4e3)}onSeeked(){if(this.dead||this.seeking<0)return;clearTimeout(this.timer),this.errors=0;let t=this.video,e=Math.max(0,Math.min(this.frames-1,Math.floor(t.currentTime*this.fps+.001)));this.landed=e,this.host.frames.put(e,t,!1),this.host.delivered()}fail(t){this.dead||(this.destroy(),this.cors&&(this.video.removeAttribute("crossorigin"),this.video.load()),this.host.failed(t))}destroy(){this.dead=!0,clearTimeout(this.timer),this.offs.forEach(t=>{t()}),this.offs=[]}},P=class{constructor(t,e,i,s){this.pattern=t,this.count=e,this.fps=i,this.host=s,this.tier="frames",this.target=-1,this.dir=0,this.loading=new Set,this.failedFrames=new Set,this.errors=0,this.known=!1,this.width=0,this.height=0,this.on=!0,this.dead=!1,this.abort=typeof AbortController<"u"?new AbortController:null}start(){this.count>0?this.load(0):this.fail('data-umber-scrub-frames needs data-umber-scrub-count="<number of frames>"')}request(t,e){this.target=Math.max(0,Math.min(this.count-1,Math.round(t))),this.dir=x(e),this.pump()}active(t){this.on=t,this.pump()}reset(){this.pump()}pump(){if(this.dead||!this.on||!this.known||this.target<0)return;let t=this.host.frames,e=this.dir>=0?1:-1,i=t.capacity(this.width,this.height)-1,s=Math.min(2,i>>2),r=Math.min(8,i-s);for(let i=0;i<=Math.max(0,r+s)&&this.loading.size<4;i++){let s=this.target+(i<=r?i:r-i)*e;s<0||s>=this.count||t.has(s)||this.loading.has(s)||this.failedFrames.has(s)||this.load(s)}}async load(e){this.loading.add(e);let i=function(t,e){return t.replace(/\{(\d+)\}/,(t,i)=>String(parseInt(i,10)+e).padStart(i.length,"0"))}(this.pattern,e);try{let s=await(await t(i,{mode:"cors",credentials:"omit",signal:this.abort?.signal})).blob(),r=await createImageBitmap(s,{premultiplyAlpha:"premultiply",colorSpaceConversion:"default"}),n=this.host.maxTexture;if(r.width>n||r.height>n){let t=n/Math.max(r.width,r.height),e=await createImageBitmap(r,{resizeWidth:Math.floor(r.width*t),resizeHeight:Math.floor(r.height*t),resizeQuality:"high"});r.close(),r=e}if(this.loading.delete(e),this.dead)return void r.close();this.errors=0,this.known||(this.known=!0,this.width=r.width,this.height=r.height,this.host.ready({frames:this.count,fps:this.fps,width:r.width,height:r.height})),this.host.frames.put(e,r,!0),this.host.delivered()}catch(t){if(this.loading.delete(e),this.dead)return;if(this.failedFrames.add(e),this.host.log.warn(`scrub frame ${i} failed to load`,t),!this.known||++this.errors>=4)return void this.fail(`the image sequence ${this.pattern} does not load`)}this.pump()}fail(t){this.dead||(this.destroy(),this.host.failed(t))}destroy(){this.dead=!0,this.abort?.abort()}},V=()=>new Promise(t=>{let e=new MessageChannel;e.port1.onmessage=t,e.port2.postMessage(0)}),L={high:128,mid:48,low:32},D=new Set,W={start:"top bottom",end:"bottom top",track:"",smooth:-1,source:"auto",src:"",srcMobile:"",frames:"",count:0,fps:0,blend:!0,cache:0,reduced:""},z={uniforms:{uScrubProgress:0,uScrubVelocity:0},fragment:{head:"uniform sampler2D uFrameNext;\nuniform float uFrameMix;\nvec4 scrubNext(vec2 uv) {\n vec2 f = fitUv(uv);\n if (uFit > 0.5 && uFit < 1.5 && (f.x < 0.0 || f.y < 0.0 || f.x > 1.0 || f.y > 1.0)) return vec4(0.0);\n vec4 c = texture(uFrameNext, f);\n return vec4(c.rgb / max(c.a, 1e-5), c.a);\n}",color:"if (uFrameMix > 0.0) color = mix(color, scrubNext(uv), uFrameMix);"}};var O={kind:"scroll"},q=t=>({kind:"manual",value:t}),R=class{constructor(t,e){this.exporter=t,this.decoded=e,this.settle=null,this.want=[],this.stuck=0}frame(t,e){e?this.stuck=0:(this.want=t,!(this.settle||this.stuck>=20)&&this.exporter.wait(new Promise(t=>{let e=i=>{this.settle===e&&(this.settle=null,i&&this.stuck++,t())};this.settle=e,this.decoded(this.want)&&V().then(()=>{e()}),new Promise(t=>{"function"==typeof AbortSignal.timeout?AbortSignal.timeout(250).onabort=()=>{t()}:setTimeout(t,250)}).then(()=>{e(!0)})})))}delivered(){this.settle&&this.decoded(this.want)&&V().then(()=>{this.settle?.()})}end(){this.settle?.()}},H=class{constructor(t){this.ctx=t,this.handlers=new Map,this.readyWith=function(){let t,e;return{promise:new Promise((i,s)=>{t=i,e=s}),resolve:t,reject:e}}(),this.cache=null,this.tier="loading",this.fileFps=0,this.source=null,this.info=null,this.started=!1,this.dead=!1,this.progress=0,this.shown=0,this.target=0,this.velocity=0,this.dir=0,this.snap=!0,this.first=!0,this.autoplay=null;let e=this.el=t.el;this.log=t.log;let i=this.o=function(t,e,i){{let s=e.replace(/^data-/,""),r=i??{},o={};for(let t in r)o[t]={attr:`data-${s}-${n(t)}`,css:`--${s}-${n(t)}`,default:r[t]};return h(t,o,void 0)}}(e,"umber-scrub",W);this.drive="manual"===(e.getAttribute("data-umber-scrub")??"").trim().toLowerCase()?q(0):O,this.start=u(i.start,W.start),this.end=u(i.end,W.end),this.video=t.media instanceof HTMLVideoElement?t.media:null;let s="high"!==t.tier&&!!i.srcMobile;this.own=s?i.srcMobile:i.src,this.src=function(t,e){return N(e,t?.currentSrc,t?.getAttribute("src"),t?.querySelector("source")?.getAttribute("src"))}(this.video,this.own),this.opts=t.options,this.tiers=function(t,e,i,s){if("decoder"===t||"video"===t||"frames"===t)return[t];let r=[];return e&&(()=>{let t=globalThis;return"function"==typeof t.VideoDecoder&&"function"==typeof t.EncodedVideoChunk})()&&r.push("decoder"),i&&e&&r.push("video"),s&&r.push("frames"),r}((i.source||"auto").toLowerCase(),this.src,this.video,i.frames);let r=function(t,e){let i=e.trim();if(!i||"self"===i)return null;if("parent"===i)return t.parentElement;try{return i.startsWith("closest ")?t.closest(i.slice(8).trim()):t.closest(i)??document.querySelector(i)}catch{return null}}(e,i.track);i.track&&!r&&"self"!==i.track.trim()&&this.log.warn(`data-umber-scrub-track="${i.track}": no such element; the video's own position drives it.`,e),this.tracker=r?t.engine.track(r):null;let o=(()=>{let t=typeof window<"u"?window.occluzeCapture:void 0;return 1===t?.version?t:null})();this.wait=o?new R(o,t=>t.every(t=>this.frames().has(t))):null,this.api=function(t){let e=()=>{t.ctx.wake()},i={get progress(){return t.progress},set progress(i){t.drive=q(Math.min(1,Math.max(0,i||0))),e()},get drive(){return t.drive.kind},set drive(i){t.drive="manual"===i?q(t.progress):O,e()},get time(){return t.info?t.shown/t.info.fps:0},set time(e){t.info&&(i.progress=e*t.info.fps/Math.max(1,t.info.frames-1))},get frame(){return t.shown},get frames(){return t.info?.frames??0},get fps(){return t.info?.fps??0},get duration(){return t.info?t.info.frames/t.info.fps:0},get tier(){return t.tier},get ready(){return t.ready},on:(e,s)=>(t.on(e,s),()=>{i.off(e,s)}),off(e,i){t.off(e,i)},destroy(){t.ctx.plane.destroy()}};return i}(this)}get ready(){return this.readyWith.promise}frames(){return this.cache||(this.cache=this.ctx.frames,this.cache.budget=this.budgetMB()*2**20),this.cache}budgetMB(){if(this.o.cache>0)return this.o.cache;let t=this.opts.cacheMB??0;return t>0?t:L[this.ctx.tier]}on(t,e){let i=this.handlers.get(t);i||(i=new Set,this.handlers.set(t,i)),i.add(e)}off(t,e){this.handlers.get(t)?.delete(e)}emit(t){let e=this.handlers.get(t);if(e)for(let i of[...e])if(e.has(i))try{i(this.api)}catch(e){this.log.error(`a scrub "${t}" handler threw:`,e)}}still(t){let e=this.video;e&&(t&&null===this.autoplay?(this.autoplay=e.autoplay,e.autoplay=!1,e.pause()):!t&&null!==this.autoplay&&(e.autoplay=this.autoplay,this.autoplay&&e.isConnected&&e.play().catch(i),this.autoplay=null))}poster(t){this.still(!1),this.tier="poster",this.source?.destroy(),this.source=null,this.info=null,this.ctx.busy(!1),this.ctx.fail(t),this.readyWith.resolve(!1),this.wait?.end(),this.emit("tier")}host(){let t=()=>this.frames();return{get frames(){return t()},log:this.log,maxTexture:this.ctx.maxTexture,ready:t=>{this.sourceReady(t)},delivered:()=>{this.delivered()},failed:(t,e)=>{this.failed(t,e)}}}sourceReady(t){this.dead||("decoder"===this.tier&&(this.fileFps=t.fps),this.info&&this.info.frames!==t.frames&&(this.shown=Math.min(this.shown,t.frames-1)),this.info=t,this.snap=!0,this.ctx.wake())}delivered(){this.dead||(this.first&&(this.first=!1,this.readyWith.resolve(!0),this.emit("ready")),this.wait?.delivered(),this.ctx.wake())}failed(t,e){if(this.dead)return;let i=e?new URL(this.src,location.href).href:"",s=e?`the video ${i} ${t}. Encode it with: npm run scrub -- input.mov`:t;if(e&&this.tiers.length&&!D.has(i)){D.add(i);let t="video"===this.tiers[0]?"by seeking the <video>, which is choppier":"from its image sequence";this.log.warn(`scrub: ${s.replace(/\. Encode/,`, so it scrubs ${t}. Encode`)}`,this.el)}else this.log.info(`scrub: ${this.tier} tier failed (${s})`,this.el);this.cache?.clear(),this.info=null,this.source=null,this.wait?.end(),this.next(s)}next(t){let e=this.tiers.shift();if(!e)return this.emit("error"),void this.poster(`scrub: ${t??"nothing to scrub (no video src and no data-umber-scrub-frames)"}; the <video> and its poster show instead.`);this.tier=e,this.still(!0);let i=this.sourceFor(e);i?(this.source=i,i.start(),this.emit("tier")):this.next('data-umber-scrub-source="video" needs a <video>')}sourceFor(t){let e=this.o;return"decoder"===t?new F(new URL(this.src,location.href).href,this.host()):"video"===t?this.video?new T(this.video,this.host(),e.fps>0?e.fps:this.fileFps||30,this.own):null:new P(e.frames,Math.round(e.count),e.fps>0?e.fps:30,this.host())}smoothing(){return this.ctx.reducedMotion?0:this.o.smooth>=0?this.o.smooth:.12}binding(){let t={uniforms:z.uniforms},e=N(this.o.reduced,this.opts.reducedMotion,"poster").toLowerCase();return this.ctx.reducedMotion&&"scrub"!==e?(this.poster(),{api:this.api,source:!0,effect:t}):this.tiers.length?{api:this.api,source:!0,effect:z,near:t=>{this.near(t)},update:(t,e,i)=>this.update(t,e,i),lost:()=>{this.snap=!0},src:()=>!this.own,restored:()=>{this.source?.reset(),this.ctx.wake()},destroy:()=>{this.destroy()}}:(this.poster(`scrub: nothing to scrub here (${this.video?"the <video> has no src":"no <video> inside"} and no data-umber-scrub-frames); it shows as plain DOM.`),{api:this.api,source:!0,effect:t})}near(t){if(!this.dead&&"poster"!==this.tier){if(t&&(this.snap=!0),!this.started&&t)return this.started=!0,void this.next();this.source?.active(t),t||this.cache?.clear(!0)}}progressNow(t,e){if("manual"===this.drive.kind)return this.drive.value;let i=this.tracker?this.tracker.rect.y:o(t,1),s=this.tracker?this.tracker.rect.height:o(t,3);return s>0?function({top:t,height:e},i,s,r){let n=s=>(s.alt&&e>i&&(s=s.alt),t+e*s.el+s.elPx-(i*s.vp+s.vpPx)),h=n(s),o=h-n(r);return Math.abs(o)>1e-6?Math.min(1,Math.max(0,h/o)):h<=0?1:0}({top:i,height:s},e.height,this.start,this.end):null}update(t,e,i){let s=this.info;if(!s||!this.source||this.dead)return!1;let r=this.progressNow(e,i);if(null===r)return!1;this.progress=r;let n=s.frames;this.target=r*(n-1);let h=this.shown;return this.shown=this.snap?this.target:function(t,e,i,s){return i>0&&s>0?t+(e-t)*(1-Math.exp(-s/i)):e}(this.shown,this.target,this.smoothing(),t.dt),this.snap=!1,Math.abs(this.target-this.shown)<.01&&(this.shown=this.target),this.velocity=t.dt>0?(this.shown-h)/Math.max(1,n-1)/t.dt:0,this.dir=Math.sign(this.target-this.shown)||Math.sign(this.shown-h)||this.dir,this.ctx.busy(this.shown!==this.target),this.draw(n,e,i),this.uniforms(n,this.shown!==h)}draw(t,e,i){let s=this.frames();s.focus(Math.round(this.shown)),this.source?.request(this.shown,this.dir);let r=function(t,e,i,s){let r=t=>i.ready(t);if(e<=0)return null;let n=Math.max(0,Math.min(e-1,t)),h=Math.floor(n),o=n-h;if(s&&o>.001&&h+1<e&&r(h)&&r(h+1))return{a:h,b:h+1,mix:o};let a=Math.round(n);if(r(a))return{a:a,b:-1,mix:0};let l=-1;for(let t of i.keys())(l<0||Math.abs(t-n)<Math.abs(l-n))&&(l=t);return l<0?null:{a:l,b:-1,mix:0}}(this.shown,t,s,this.o.blend);r&&s.show(r.a,r.b,r.mix);let n=o(e,0),h=o(e,1),a=h<i.height&&h+o(e,3)>0&&n<i.width&&n+o(e,2)>0;if(!this.wait||!a)return;let l=Math.round(Math.max(0,Math.min(t-1,this.shown)));this.wait.frame([l],s.ready(l))}uniforms(t,e){let i=this.ctx.plane.uniforms;if(i.uScrubProgress&&(i.uScrubProgress.value=this.shown/Math.max(1,t-1)),!i.uScrubVelocity)return e;let s=e?this.velocity:0,r=e||i.uScrubVelocity.value!==s;return i.uScrubVelocity.value=s,r}destroy(){this.dead=!0,this.source?.destroy(),this.source=null,this.still(!1),this.tracker?.destroy(),this.handlers.clear(),this.wait?.end(),this.first&&this.readyWith.resolve(!1)}};!function(t){let e,i=window;i.Umber?.use?i.Umber.use(t,e):(i.UmberModules??=[],i.UmberModules.push(e?[t,e]:t),i.__umber?.engine?.use?.(t,e))}({name:"scrub",version:"0.4.1",attributes:["scrub"],plane:t=>function(t){return new H(t).binding()}(t)})})();
|
package/dist/modules/scrub.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! Umber v0.
|
|
2
|
-
function t(t,e){let i=t.trim();if("number"===e){let t=parseFloat(i);return Number.isFinite(t)?t:void 0}return"boolean"===e?function(t){let e=t.trim().toLowerCase();return""===e||"true"===e||"1"===e||"yes"===e||"false"!==e&&"0"!==e&&"no"!==e&&void 0}(i):"list"===e?i.split(/[\s,]+/).filter(Boolean):i.replace(/^["']|["']$/g,"")}function e(t){return t.type?t.type:"number"==typeof t.default?"number":"boolean"==typeof t.default?"boolean":Array.isArray(t.default)?"list":"string"}var i=t=>t.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`);function s(i,s,r){let n={},h=r;for(let[r,o]of Object.entries(s)){let s,a=e(o);if(o.attr){let e=i.getAttribute(o.attr);null!==e&&(s=t(e,a))}if(void 0===s&&o.css){h??=getComputedStyle(i);let e=h.getPropertyValue(o.css);e&&""!==e.trim()&&(s=t(e,a))}n[r]=void 0===s?o.default:s}return n}var r=(t,e)=>t[e]??NaN,n={top:0,left:0,center:.5,middle:.5,bottom:1,right:1};function h(t,e){let i=(t??"").trim().toLowerCase();if(!i)return e;let s=function(t){let e=/^(top|left|center|middle|bottom|right|-?\d*\.?\d+(?:px|%)?)?(?:([+-])=?(\d*\.?\d+)(px|%)?)?$/.exec(t);if(!e)return null;let[,i,s,r="",h]=e;if(!i&&!s)return null;let o=0,a=0,l=void 0===i?void 0:n[i];if(void 0!==l)o=l;else if(i){let t=parseFloat(i);i.endsWith("%")?o=t/100:a=t}if(s){let t=parseFloat(r)*("-"===s?-1:1);"%"===h?o+=t/100:a+=t}return[o,a]}(i);return s?/^[+-]/.test(i)&&!/^-\d/.test(i)?[e[0]+s[0],e[1]+s[1]]:s:e}var o={cover:[[0,1,1,0]],contain:[[1,1,0,0],[0,0,1,1]],entry:[[0,1,1,1],[0,1,0,0]],exit:[[0,0,1,0],[1,1,1,0]],"entry-crossing":[[0,1,1,1]],"exit-crossing":[[0,0,1,0]]};function a(t,e){let i=function(t,e){return null==t||""===t?e:t}(t,e).trim().split(/\s+/),s=function(t,e){let[i,s]=t,r=void 0===i?void 0:o[i];if(void 0===r)return null;let[n,h]=r,a=s??(e?"100%":"0%"),l=a.endsWith("%")?0:parseFloat(a)||0,d=l?0:parseFloat(a)/100||0,u=([t,e,i,s])=>({el:t+(i-t)*d,elPx:l,vp:e+(s-e)*d,vpPx:0});return{...u(n),alt:h?u(h):void 0}}(i.map(t=>t.toLowerCase()),e.startsWith("bottom"));if(s)return s;let r=e.split(/\s+/),[n,a]=h(i[0],h(r[0],[0,0])),[l,d]=h(i[1],h(r[1],[0,0]));return{el:n,elPx:a,vp:l,vpPx:d}}var l=(t,e)=>String.fromCharCode(r(t,e),r(t,e+1),r(t,e+2),r(t,e+3));function d(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function u(t,e,i){let s=e.body+i;return s+4<=Math.min(e.end,t.length)?d(t).getUint32(s):Number.NaN}function c(t,e,i,s){let r=u(t,e,i-4);return r*s<=Math.min(e.end,t.length)-(e.body+i)?r:null}var f=2**21;function m(t,e,i=t.length){if(e+8>i)return null;let s=d(t),r=s.getUint32(e),n=l(t,e+4),h=e+8;if(1===r){if(e+16>i)return null;r=s.getUint32(e+8)*2**32+s.getUint32(e+12),h=e+16}else 0===r&&(r=1/0);return r<h-e?null:{type:n,start:e,body:h,end:e+r}}function p(t,e,i){let s=[],r=e;for(;r<i;){let e=m(t,r,i);if(!e||e.end>i||e.end<=r)break;s.push(e),r=e.end}return s}var g=(t,e,i)=>p(t,e.body,e.end).find(t=>t.type===i)??null;function b(t,e,...i){for(let s of i){if(!e)return null;e=g(t,e,s)}return e}function y(t,e,i){let s=b(t,e,"mdia","mdhd"),n=b(t,e,"mdia","minf","stbl");if(!s||!n)return null;let h=u(t,s,1===t[s.body]?20:12);if(Number.isNaN(h))return null;let o=h||1,a=function(t,e){let i=g(t,e,"stsd");if(!i)return null;let s=m(t,i.body+8,i.end);if(!s||s.end>i.end||s.body+28>s.end)return null;let r=d(t),n=s.type,h="",o=null,a=p(t,s.body+78,s.end).find(t=>"avcC"===t.type);return a&&("avc1"===n||"avc3"===n)&&(o=t.slice(a.body,a.end),h=function(t){let e=t=>t.toString(16).padStart(2,"0"),[,i,s,r]=t;return void 0===i||void 0===s||void 0===r?"":`avc1.${e(i)}${e(s)}${e(r)}`}(o)),{format:n,width:r.getUint16(s.body+24),height:r.getUint16(s.body+26),codec:h,description:o}}(t,n);if(!a)return null;let[l,y]=function(t,e){let i=g(t,e,"tkhd");if(!i)return null;let s=i.body+(1===t[i.body]?88:76);if(s+8>i.end)return null;let r=d(t),n=r.getUint32(s)/65536,h=r.getUint32(s+4)/65536;return n&&h?[Math.round(n),Math.round(h)]:null}(t,e)??[a.width,a.height],v=function(t,e){let i=i=>g(t,e,i),s=function(t,e,i){return e?function(t,e){let i=d(t),s=u(t,e,4),r=s?u(t,e,8):c(t,e,12,4);if(null===r||!(r<=f))return null;let n=new Array(r);for(let t=0;t<r;t++)n[t]=s||i.getUint32(e.body+12+4*t);return n}(t,e):i?function(t,e){let i=t[e.body+7];if(4!==i&&8!==i&&16!==i)return null;let s=c(t,e,12,i/8);if(null===s||s>f)return null;let n=d(t),h=e.body+12,o=new Array(s);for(let e=0;e<s;e++)o[e]=16===i?n.getUint16(h+2*e):8===i?r(t,h+e):r(t,h+(e>>1))>>(1&e?0:4)&15;return o}(t,i):null}(t,i("stsz"),i("stz2")),n=function(t,e,i){let s=e??i;if(!s)return null;let r=e?4:8,n=c(t,s,8,r);if(null===n)return null;let h=d(t),o=new Array(n);for(let t=0;t<n;t++){let i=s.body+8+t*r;o[t]=e?h.getUint32(i):h.getUint32(i)*2**32+h.getUint32(i+4)}return o}(t,i("stco"),i("co64")),h=i("stsc");if(!s||!n||!h)return null;let o=function(t,e,i,s){let n=i.length,h=function(t,e){let i=c(t,e,8,12);if(null===i)return null;let s=d(t),r=[];for(let t=0;t<i;t++){let i=e.body+8+12*t;r.push({first:s.getUint32(i)-1,per:s.getUint32(i+4)})}return r}(t,e);if(!h)return null;let o=new Array(n),a=0;for(let[t,e]of h.entries()){if(a>=n)break;let l=h[t+1]?.first??s.length;for(let t=e.first;t<l&&a<n;t++){let h=s[t];if(void 0===h)return null;for(let t=0;t<e.per&&a<n;t++)o[a]=h,h+=r(i,a),a++}}return a<n?null:o}(t,h,s,n),a=i("stts");if(!o||!a)return null;let l=s.length,m=function(t,e,i){let s=d(t),r=new Array(i),n=new Array(i),h=0,o=0,a=c(t,e,8,8);if(null===a)return null;for(let t=0;t<a&&o<i;t++){let a=s.getUint32(e.body+8+8*t),l=s.getUint32(e.body+12+8*t);for(let t=0;t<a&&o<i;t++)r[o]=h,n[o]=l,h+=l,o++}for(;o<i;o++)r[o]=h,n[o]=0;return{dts:r,durations:n}}(t,a,l);if(!m)return null;let{dts:p,durations:b}=m,y=function(t,e,i){let s=i.slice();if(!e)return s;let n=d(t),h=i.length,o=c(t,e,8,8);if(null===o)return null;let a=0;for(let t=0;t<o&&a<h;t++){let i=n.getUint32(e.body+8+8*t),o=n.getInt32(e.body+12+8*t);for(let t=0;t<i&&a<h;t++,a++)s[a]=r(s,a)+o}return s}(t,i("ctts"),p),v=function(t,e,i){let s=new Array(i).fill(!e);if(e){let r=d(t),n=c(t,e,8,4);if(null===n)return null;for(let t=0;t<n;t++){let n=r.getUint32(e.body+8+4*t)-1;n>=0&&n<i&&(s[n]=!0)}}return i&&(s[0]=!0),s}(t,i("stss"),l);return y&&v?s.map((t,e)=>({offset:r(o,e),size:t,dts:r(p,e),cts:r(y,e),duration:r(b,e),key:!0===v[e]})):null}(t,n);if(!v)return null;let w=function(t,e,i,s){let r=b(t,e,"edts","elst");if(!r)return null;let n=d(t),h=1===t[r.body],o=h?20:12,a=u(t,r,4),l=null;for(let t=0;t<a;t++){let e=r.body+8+t*o;if(e+o>r.end)break;let a=h?n.getUint32(e)*2**32+n.getUint32(e+4):n.getUint32(e),d=h?n.getInt32(e+8)*2**32+n.getUint32(e+12):n.getInt32(e+4);if(!(d<0)){if(l)return"cuts";l=[d,a?d+a*i/s:1/0]}}return l}(t,e,o,i||o),k="cuts"===w?null:w,M=t=>!k||t.cts+t.duration/2>=k[0]&&t.cts+t.duration/2<k[1],x=[];for(let[t,e]of v.entries())M(e)&&x.push(t);let S=v.map(t=>t.cts);x.sort((t,e)=>r(S,t)-r(S,e)||t-e);let{keyOf:A,gop:E}=function(t){let e=t.length,i=new Array(e),s=0,r=1;for(let[e,n]of t.entries())n.key&&(e&&(r=Math.max(r,e-s)),s=e),i[e]=s;return e&&(r=Math.max(r,e-s)),{keyOf:i,gop:r}}(v),[$]=x,C=x.at(-1),U=void 0===$?void 0:v[$],F=void 0===C?void 0:v[C],N=(U&&F?F.cts+F.duration-U.cts:0)/o;return{codec:a.codec,format:a.format,description:a.description,width:l,height:y,timescale:o,duration:N,fps:N>0?x.length/N:30,samples:v,order:x,keyOf:A,gop:E,cuts:"cuts"===w}}async function v(t,e){let i=await fetch(t,e);if(!i.ok)throw new Error(`${t} answered ${i.status}`);return i}function w(t,e=location.href){try{return new URL(t,e)}catch{return null}}var k=()=>{},M=class{constructor(){this.bytes=new Uint8Array(0),this.loaded=0,this.total=0,this.done=!1,this.track=null,this.late=!1,this.onTrack=null,this.onData=null,this.onError=null,this.cursor=0,this.sawMdat=!1,this.failed=!1,this.abort=null,this.reader=null}start(t){this.abort=typeof AbortController<"u"?new AbortController:null,this.run(t).catch(t=>{this.abort?.signal.aborted||this.onError?.(t)})}async run(t){let e=await v(t,{mode:"cors",credentials:"omit",signal:this.abort?.signal}),i=Number(e.headers.get("content-length"))||0;i&&!e.headers.get("content-encoding")&&(this.total=i);let s=e.body?.getReader();if(!s)return this.push(new Uint8Array(await e.arrayBuffer())),void this.finish();for(this.reader=s;;){let{done:t,value:e}=await s.read();if(this.failed)return;if(t)break;e.length&&this.push(e)}this.finish()}push(t){if(this.failed)return;let e=this.loaded+t.length;if(e>this.bytes.length){let t=Math.min(this.total,67108864),i=new Uint8Array(Math.max(e,t,2*this.bytes.length,1<<20));i.set(this.bytes.subarray(0,this.loaded)),this.bytes=i}this.bytes.set(t,this.loaded),this.loaded=e,this.scan(),this.onData?.()}finish(){this.done=!0,this.scan(),!this.track&&!this.failed&&this.onError?.(new Error("no H.264 video track found (is it an MP4?)")),this.onData?.()}fail(t){this.failed=!0,this.abort?.abort(),this.reader?.cancel().catch(()=>{}),this.onError?.(t)}scan(){for(;!this.track&&!this.failed;){let t=m(this.bytes,this.cursor,this.loaded);if(!t)return;if("moov"===t.type)return void(t.end<=this.loaded&&this.read(t));if("mdat"===t.type&&(this.sawMdat=!0),!Number.isFinite(t.end))return;this.cursor=t.end}}read(t){this.late=this.sawMdat;let e=function(t,e){let i=g(t,e,"mvhd"),s=i?u(t,i,1===t[i.body]?20:12):0;if(Number.isNaN(s))return null;for(let i of p(t,e.body,e.end)){if("trak"!==i.type)continue;let r=b(t,i,"mdia","hdlr");if(!r||"vide"!==l(t,r.body+8))continue;let n=y(t,i,s);if(n)return g(t,e,"mvex")&&(n.fragmented=!0),n}return null}(this.bytes,t);e?(this.track=e,this.onTrack?.(e)):this.fail(new Error("the MP4 has no video track"))}has(t){return t.offset+t.size<=this.loaded}data(t){return this.bytes.subarray(t.offset,t.offset+t.size)}stop(){this.abort?.abort(),this.onTrack=null,this.onData=null,this.onError=null}};function x(t){return t>0?1:t<0?-1:0}var S=class{constructor(t,e){this.track=t,this.host=e,this.target=-1,this.dir=0,this.busy=null,this.fetched=new Set,this.present=new Array(t.order.length),t.order.forEach((t,e)=>{this.present[t]=e})}get frames(){return this.track.order.length}want(t,e=0){let i=this.frames,s=i?Math.max(0,Math.min(i-1,Math.round(t))):-1;s!==this.target&&this.fetched.clear(),this.target=s,this.dir=x(e)}next(){if(this.busy||this.target<0)return null;let t=this.reachable(this.target);if(t<0)return null;let e=this.host.has(t)?this.ahead(t):t;if(e<0)return null;e!==t&&this.fetched.add(e);let i=this.track.order[e],s=void 0===i?void 0:this.track.keyOf[i];if(void 0===i||void 0===s)return null;let n=Math.max(1,Math.floor(this.host.window()/2)),h=new Set([e]);for(let e=s;e<i;e++){let i=r(this.present,e);Math.abs(i-t)<=n&&!this.host.has(i)&&h.add(i)}return this.busy={from:s,to:i,goal:e,keep:h},this.busy}forget(){this.fetched.clear()}done(){this.busy=null}ready(t){if(!(t>=0&&t<this.frames))return!1;let e=this.track.order[t],i=void 0===e?void 0:this.track.keyOf[e];return void 0!==e&&void 0!==i&&this.host.available(e)&&this.host.available(i)}reachable(t){if(this.ready(t))return t;let e=this.frames;for(let i=1;i<e;i++){if(t-i>=0&&this.ready(t-i))return t-i;if(t+i<e&&this.ready(t+i))return t+i}return-1}ahead(t){let e=this.frames,i=this.host.window(),s=Math.min(12,Math.max(1,Math.floor(i/2)-1),Math.floor((i-1)/2));for(let i=1;i<=s;i++)for(let s=0;s<(this.dir?1:2);s++){let r=t+i*(this.dir||1-2*s);if(!(r<0||r>=e)&&!this.host.has(r)&&!this.fetched.has(r)&&this.ready(r))return r}return-1}};var A="umber:scrub-decode",E={hvc1:"HEVC (hvc1)",hev1:"HEVC (hev1)",av01:"AV1",vp09:"VP9",vp08:"VP8"},$=t=>"QuotaExceededError"===C(t),C=t=>"object"==typeof t&&null!==t&&"name"in t&&"string"==typeof t.name?t.name:"",U=(t,e)=>Math.round(t/e.timescale*1e6),F=class{constructor(t,e){this.url=t,this.host=e,this.tier="decoder",this.stream=new M,this.track=null,this.schedule=null,this.decoder=null,this.config=null,this.made=null,this.accel="no-preference",this.byTime=new Map,this.running=!1,this.on=!0,this.dead=!1,this.errors=0,this.timings=[],this.keep=null,this.outputs=0}start(){let t=this.stream;t.onTrack=t=>{this.configure(t)},t.onData=()=>{this.pump()},t.onError=t=>{this.fail(`could not read the video (${t instanceof Error?t.message:String(t)})`)},t.start(this.url)}async configure(t){let e=function(t){let{codec:e,description:i}=t;return e&&i?t.fragmented&&!t.order.length?"is a fragmented MP4 (its frames are indexed in fragments), which WebCodecs scrubbing doesn't read":t.order.length?{codec:e,description:i}:"has no frames in its index":`is ${E[t.format]??(t.format||"not H.264")}, and WebCodecs scrubbing reads H.264`}(t);if("string"==typeof e)return void this.fail(e,!0);this.warnAbout(t);let i={...e,codedWidth:t.width,codedHeight:t.height,optimizeForLatency:!0},s=await this.pickConfig(i);if(!this.dead){if(!s)return void this.fail(`this browser can't decode ${e.codec} with WebCodecs`);this.begin(t)}}warnAbout(t){this.stream.late&&!this.stream.done&&this.host.log.warn('scrub video is not "faststart" (its index is at the end), so nothing shows until it fully downloads. Encode it with: npm run scrub -- input.mov'),t.cuts&&this.host.log.warn("scrub video has an edit list with several cuts, which the scrub does not follow: it shows every frame of the file. Re-encode it with: npm run scrub -- input.mov"),t.gop>10&&this.host.log.warn(`scrub video has a keyframe only every ${t.gop} frames: each step back decodes up to that many. For smooth scrubbing encode it with: npm run scrub -- input.mov`)}async pickConfig(t){let e=typeof navigator<"u"&&/Android/i.test(navigator.userAgent)?function(){try{let[t,e,...i]=(localStorage.getItem(A)??"").split(" ");return("prefer-software"===t||"prefer-hardware"===t)&&i.join(" ")===navigator.userAgent&&Date.now()-Number(e)<2592e6?t:null}catch{return null}}()??"prefer-hardware":"no-preference",i="no-preference"===e?["no-preference"]:[e,"no-preference"];for(let e of i)try{let i="no-preference"===e?t:{...t,hardwareAcceleration:e},s=await VideoDecoder.isConfigSupported(i);if(this.dead)return!1;if(s.supported){this.config=i,this.accel=e;break}}catch{}return!!this.config}begin(t){this.track=t,t.order.forEach((e,i)=>{let s=t.samples[e];s&&this.byTime.set(U(s.cts,t),i)});let e=this.host.frames;this.schedule=new S(t,{has:t=>e.has(t),available:e=>{let i=t.samples[e];return void 0!==i&&this.stream.has(i)},window:()=>Math.min(e.capacity(t.width,t.height),48)}),this.host.ready({frames:t.order.length,fps:t.fps,width:t.width,height:t.height}),this.pump()}request(t,e){this.schedule&&(this.schedule.want(t,e),this.pump())}active(t){this.on=t,t?(this.schedule?.forget(),this.pump()):this.close()}reset(){this.schedule?.forget(),this.pump()}decoderNow(t){if(this.decoder&&"closed"!==this.decoder.state&&this.made===t)return this.decoder;this.close();let e=new VideoDecoder({output:t=>{this.output(t)},error:t=>{this.onError(e,t)}});return e.configure(t),this.made=t,this.decoder=e,e}output(t){this.outputs++;let e=this.byTime.get(t.timestamp);void 0===e||this.dead||!this.keep?.has(e)||this.host.frames.ready(e)?t.close():(this.host.frames.put(e,t,!0),this.host.delivered())}onError(t,e){t===this.decoder&&(this.decoder=null),$(e)||this.host.log.info("scrub decoder error",e)}chunk(t,e,i){let s=t.samples[e];if(!s)throw new RangeError(`sample ${e} is not in the track`);return new EncodedVideoChunk({type:i||s.key?"key":"delta",timestamp:U(s.cts,t),duration:U(s.duration,t),data:this.stream.data(s)})}async pump(){let t=this.schedule;if(this.running||this.dead||!this.on||!t||!this.track||!this.config)return;let e=t.next();if(!e)return;this.running=!0;let i=this.track,s=performance.now(),r=this.errors,n=!0;try{let t=this.decoderNow(this.config);this.keep=e.keep,this.outputs=0;for(let s=e.from;s<=e.to;s++)t.decode(this.chunk(i,s,s===e.from));await t.flush(),0===this.outputs&&(n=!1,this.errors++,this.close())}catch(t){n=!1,!$(t)&&"AbortError"!==C(t)&&this.errors++,this.close()}if(this.running=!1,!this.isDestroyed()){if(t.done(),n)this.errors=0,this.time((performance.now()-s)/(e.to-e.from+1));else{if(this.errors>=3)return void this.fail("the video decoder keeps failing");this.errors>r&&t.forget()}this.pump()}}time(t){if("prefer-hardware"!==this.accel||(this.timings.push(t),1===this.timings.length))return;let e=(i=this.timings.slice(1)).length<10?null:function(t){if(!t.length)return 0;let e=t.slice().sort((t,e)=>t-e);return r(e,Math.min(e.length-1,Math.ceil(.95*e.length)-1))}(i)>25;var i;if(null===e)return;let s=e?"prefer-software":"prefer-hardware";try{localStorage.setItem(A,`${s} ${Date.now()} ${navigator.userAgent}`)}catch{}if(this.accel="no-preference",!e||!this.config)return;let n={...this.config,hardwareAcceleration:"prefer-software"};VideoDecoder.isConfigSupported(n).then(t=>{!t.supported||this.dead||(this.host.log.info("scrub: hardware decoding is slow at seeking here; using the software decoder"),this.config=n,this.accel="prefer-software",this.running||this.close())}).catch(k)}close(){let t=this.decoder;if(this.decoder=null,t&&"closed"!==t.state)try{t.close()}catch{}}isDestroyed(){return this.dead}fail(t,e){this.dead||(this.destroy(),this.host.failed(t,e))}destroy(){this.dead=!0,this.stream.stop(),this.close(),this.schedule=null}};function N(...t){for(let e of t)if(e)return e;return""}var T=class{constructor(t,e,i,s){this.video=t,this.host=e,this.fps=i,this.src=s,this.tier="video",this.frames=0,this.target=-1,this.seeking=-1,this.landed=-1,this.fastFor=-1,this.errors=0,this.on=!0,this.dead=!1,this.cors=!1,this.offs=[]}start(){let t=this.video;t.muted=!0,t.playsInline=!0,t.setAttribute("playsinline",""),t.setAttribute("webkit-playsinline",""),t.disableRemotePlayback=!0,t.pause();let e=N(t.currentSrc,t.getAttribute("src"),t.querySelector("source")?.getAttribute("src")),i=N(this.src,e),s="auto"!==t.preload;t.preload="auto";let r=i?w(i):null;var n;r&&(n=r,!(("string"==typeof n?w(n):n)?.origin===location.origin))&&!t.crossOrigin&&(t.crossOrigin="anonymous",this.cors=!0,s=!0),this.src&&this.src!==e&&(t.src=this.src,s=!0),this.listen("seeked",()=>{this.onSeeked()}),this.listen("error",e=>{let i=t.querySelectorAll("source");(e.target===t||e.target===i[i.length-1])&&this.fail(this.cors?"the video failed to load (another domain: no CORS headers?)":"the video failed to load")},!0),t.readyState>=1&&!s?this.onMeta():(this.listen("loadedmetadata",()=>{this.onMeta()}),this.meta()),s&&t.load();let h=()=>{this.dead||t.readyState>=2||t.play().then(()=>{t.pause()}).catch(k)};addEventListener("touchstart",h,{once:!0,passive:!0}),this.offs.push(()=>{removeEventListener("touchstart",h)})}listen(t,e,i=!1){this.video.addEventListener(t,e,i),this.offs.push(()=>{this.video.removeEventListener(t,e,i)})}meta(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.frames||this.dead||(1===this.video.networkState?this.meta():this.fail("the video's metadata never loaded"))},1e4)}onMeta(){if(this.frames||this.dead)return;let t=this.video;!Number.isFinite(t.duration)||t.duration<=0?this.fail("the video has no duration (a live stream?)"):(this.frames=Math.max(1,Math.round(t.duration*this.fps)),this.host.ready({frames:this.frames,fps:this.fps,width:t.videoWidth,height:t.videoHeight}),this.pump())}request(t){this.frames&&(this.target=Math.max(0,Math.min(this.frames-1,Math.round(t))),this.pump())}active(t){this.on=t,this.pump()}reset(){this.seeking=-1,this.landed=-1,this.pump()}pump(){if(this.dead||!this.on||this.target<0)return;if(this.seeking>=0){let t=this.host.frames;if(!(this.landed>=0)||!t.ready(this.landed)&&t.has(this.landed))return;this.seeking=-1,this.landed=-1}let t=this.target;if(this.host.frames.has(t))return;let e=this.video;if(e.readyState<1)return;this.seeking=t,this.landed=-1;let i=Math.min((t+.5)/this.fps,Math.max(0,e.duration-.001)),s=Math.round(e.currentTime*this.fps-.5);"function"==typeof e.fastSeek&&Math.abs(t-s)>6&&t!==this.fastFor?(this.fastFor=t,e.fastSeek(i)):e.currentTime=i,clearTimeout(this.timer),this.timer=setTimeout(()=>{this.seeking<0||this.landed>=0||(this.seeking=-1,++this.errors>=3?this.fail("seeking the video never lands"):this.pump())},4e3)}onSeeked(){if(this.dead||this.seeking<0)return;clearTimeout(this.timer),this.errors=0;let t=this.video,e=Math.max(0,Math.min(this.frames-1,Math.floor(t.currentTime*this.fps+.001)));this.landed=e,this.host.frames.put(e,t,!1),this.host.delivered()}fail(t){this.dead||(this.destroy(),this.cors&&(this.video.removeAttribute("crossorigin"),this.video.load()),this.host.failed(t))}destroy(){this.dead=!0,clearTimeout(this.timer),this.offs.forEach(t=>{t()}),this.offs=[]}},P=class{constructor(t,e,i,s){this.pattern=t,this.count=e,this.fps=i,this.host=s,this.tier="frames",this.target=-1,this.dir=0,this.loading=new Set,this.failedFrames=new Set,this.errors=0,this.known=!1,this.width=0,this.height=0,this.on=!0,this.dead=!1,this.abort=typeof AbortController<"u"?new AbortController:null}start(){this.count>0?this.load(0):this.fail('data-umber-scrub-frames needs data-umber-scrub-count="<number of frames>"')}request(t,e){this.target=Math.max(0,Math.min(this.count-1,Math.round(t))),this.dir=x(e),this.pump()}active(t){this.on=t,this.pump()}reset(){this.pump()}pump(){if(this.dead||!this.on||!this.known||this.target<0)return;let t=this.host.frames,e=this.dir>=0?1:-1,i=t.capacity(this.width,this.height)-1,s=Math.min(2,i>>2),r=Math.min(8,i-s);for(let i=0;i<=Math.max(0,r+s)&&this.loading.size<4;i++){let s=this.target+(i<=r?i:r-i)*e;s<0||s>=this.count||t.has(s)||this.loading.has(s)||this.failedFrames.has(s)||this.load(s)}}async load(t){this.loading.add(t);let e=function(t,e){return t.replace(/\{(\d+)\}/,(t,i)=>String(parseInt(i,10)+e).padStart(i.length,"0"))}(this.pattern,t);try{let i=await(await v(e,{mode:"cors",credentials:"omit",signal:this.abort?.signal})).blob(),s=await createImageBitmap(i,{premultiplyAlpha:"premultiply",colorSpaceConversion:"default"}),r=this.host.maxTexture;if(s.width>r||s.height>r){let t=r/Math.max(s.width,s.height),e=await createImageBitmap(s,{resizeWidth:Math.floor(s.width*t),resizeHeight:Math.floor(s.height*t),resizeQuality:"high"});s.close(),s=e}if(this.loading.delete(t),this.dead)return void s.close();this.errors=0,this.known||(this.known=!0,this.width=s.width,this.height=s.height,this.host.ready({frames:this.count,fps:this.fps,width:s.width,height:s.height})),this.host.frames.put(t,s,!0),this.host.delivered()}catch(i){if(this.loading.delete(t),this.dead)return;if(this.failedFrames.add(t),this.host.log.warn(`scrub frame ${e} failed to load`,i),!this.known||++this.errors>=4)return void this.fail(`the image sequence ${this.pattern} does not load`)}this.pump()}fail(t){this.dead||(this.destroy(),this.host.failed(t))}destroy(){this.dead=!0,this.abort?.abort()}},L=()=>new Promise(t=>{let e=new MessageChannel;e.port1.onmessage=t,e.port2.postMessage(0)}),V={high:128,mid:48,low:32},D=new Set,W={start:"top bottom",end:"bottom top",track:"",smooth:-1,source:"auto",src:"",srcMobile:"",frames:"",count:0,fps:0,blend:!0,cache:0,reduced:""},z={uniforms:{uScrubProgress:0,uScrubVelocity:0},fragment:{head:"uniform sampler2D uFrameNext;\nuniform float uFrameMix;\nvec4 scrubNext(vec2 uv) {\n vec2 f = fitUv(uv);\n if (uFit > 0.5 && uFit < 1.5 && (f.x < 0.0 || f.y < 0.0 || f.x > 1.0 || f.y > 1.0)) return vec4(0.0);\n vec4 c = texture(uFrameNext, f);\n return vec4(c.rgb / max(c.a, 1e-5), c.a);\n}",color:"if (uFrameMix > 0.0) color = mix(color, scrubNext(uv), uFrameMix);"}};var O={kind:"scroll"},q=t=>({kind:"manual",value:t}),R=class{constructor(t,e){this.exporter=t,this.decoded=e,this.settle=null,this.want=[],this.stuck=0}frame(t,e){e?this.stuck=0:(this.want=t,!(this.settle||this.stuck>=20)&&this.exporter.wait(new Promise(t=>{let e=i=>{this.settle===e&&(this.settle=null,i&&this.stuck++,t())};this.settle=e,this.decoded(this.want)&&L().then(()=>{e()}),new Promise(t=>{"function"==typeof AbortSignal.timeout?AbortSignal.timeout(250).onabort=()=>{t()}:setTimeout(t,250)}).then(()=>{e(!0)})})))}delivered(){this.settle&&this.decoded(this.want)&&L().then(()=>{this.settle?.()})}end(){this.settle?.()}},H=class{constructor(t){this.ctx=t,this.handlers=new Map,this.readyWith=function(){let t,e;return{promise:new Promise((i,s)=>{t=i,e=s}),resolve:t,reject:e}}(),this.cache=null,this.tier="loading",this.fileFps=0,this.source=null,this.info=null,this.started=!1,this.dead=!1,this.progress=0,this.shown=0,this.target=0,this.velocity=0,this.dir=0,this.snap=!0,this.first=!0,this.autoplay=null;let e=this.el=t.el;this.log=t.log;let r=this.o=function(t,e,r){{let n=e.replace(/^data-/,""),h=r??{},o={};for(let t in h)o[t]={attr:`data-${n}-${i(t)}`,css:`--${n}-${i(t)}`,default:h[t]};return s(t,o,void 0)}}(e,"umber-scrub",W);this.drive="manual"===(e.getAttribute("data-umber-scrub")??"").trim().toLowerCase()?q(0):O,this.start=a(r.start,W.start),this.end=a(r.end,W.end),this.video=t.media instanceof HTMLVideoElement?t.media:null;let n="high"!==t.tier&&!!r.srcMobile;this.own=n?r.srcMobile:r.src,this.src=function(t,e){return N(e,t?.currentSrc,t?.getAttribute("src"),t?.querySelector("source")?.getAttribute("src"))}(this.video,this.own),this.opts=t.options,this.tiers=function(t,e,i,s){if("decoder"===t||"video"===t||"frames"===t)return[t];let r=[];return e&&(()=>{let t=globalThis;return"function"==typeof t.VideoDecoder&&"function"==typeof t.EncodedVideoChunk})()&&r.push("decoder"),i&&e&&r.push("video"),s&&r.push("frames"),r}((r.source||"auto").toLowerCase(),this.src,this.video,r.frames);let h=function(t,e){let i=e.trim();if(!i||"self"===i)return null;if("parent"===i)return t.parentElement;try{return i.startsWith("closest ")?t.closest(i.slice(8).trim()):t.closest(i)??document.querySelector(i)}catch{return null}}(e,r.track);r.track&&!h&&"self"!==r.track.trim()&&this.log.warn(`data-umber-scrub-track="${r.track}": no such element; the video's own position drives it.`,e),this.tracker=h?t.engine.track(h):null;let o=(()=>{let t=typeof globalThis<"u"?globalThis.occluzeCapture:void 0;return 1===t?.version?t:null})();this.wait=o?new R(o,t=>t.every(t=>this.frames().has(t))):null,this.api=function(t){let e=()=>{t.ctx.wake()},i={get progress(){return t.progress},set progress(i){t.drive=q(Math.min(1,Math.max(0,i||0))),e()},get drive(){return t.drive.kind},set drive(i){t.drive="manual"===i?q(t.progress):O,e()},get time(){return t.info?t.shown/t.info.fps:0},set time(e){t.info&&(i.progress=e*t.info.fps/Math.max(1,t.info.frames-1))},get frame(){return t.shown},get frames(){return t.info?.frames??0},get fps(){return t.info?.fps??0},get duration(){return t.info?t.info.frames/t.info.fps:0},get tier(){return t.tier},get ready(){return t.ready},on:(e,s)=>(t.on(e,s),()=>{i.off(e,s)}),off(e,i){t.off(e,i)},destroy(){t.ctx.plane.destroy()}};return i}(this)}get ready(){return this.readyWith.promise}frames(){return this.cache||(this.cache=this.ctx.frames,this.cache.budget=this.budgetMB()*2**20),this.cache}budgetMB(){if(this.o.cache>0)return this.o.cache;let t=this.opts.cacheMB??0;return t>0?t:V[this.ctx.tier]}on(t,e){let i=this.handlers.get(t);i||(i=new Set,this.handlers.set(t,i)),i.add(e)}off(t,e){this.handlers.get(t)?.delete(e)}emit(t){let e=this.handlers.get(t);if(e)for(let i of[...e])if(e.has(i))try{i(this.api)}catch(e){this.log.error(`a scrub "${t}" handler threw:`,e)}}still(t){let e=this.video;e&&(t&&null===this.autoplay?(this.autoplay=e.autoplay,e.autoplay=!1,e.pause()):!t&&null!==this.autoplay&&(e.autoplay=this.autoplay,this.autoplay&&e.isConnected&&e.play().catch(k),this.autoplay=null))}poster(t){this.still(!1),this.tier="poster",this.source?.destroy(),this.source=null,this.info=null,this.ctx.busy(!1),this.ctx.fail(t),this.readyWith.resolve(!1),this.wait?.end(),this.emit("tier")}host(){let t=()=>this.frames();return{get frames(){return t()},log:this.log,maxTexture:this.ctx.maxTexture,ready:t=>{this.sourceReady(t)},delivered:()=>{this.delivered()},failed:(t,e)=>{this.failed(t,e)}}}sourceReady(t){this.dead||("decoder"===this.tier&&(this.fileFps=t.fps),this.info&&this.info.frames!==t.frames&&(this.shown=Math.min(this.shown,t.frames-1)),this.info=t,this.snap=!0,this.ctx.wake())}delivered(){this.dead||(this.first&&(this.first=!1,this.readyWith.resolve(!0),this.emit("ready")),this.wait?.delivered(),this.ctx.wake())}failed(t,e){if(this.dead)return;let i=e?new URL(this.src,location.href).href:"",s=e?`the video ${i} ${t}. Encode it with: npm run scrub -- input.mov`:t;if(e&&this.tiers.length&&!D.has(i)){D.add(i);let t="video"===this.tiers[0]?"by seeking the <video>, which is choppier":"from its image sequence";this.log.warn(`scrub: ${s.replace(/\. Encode/,`, so it scrubs ${t}. Encode`)}`,this.el)}else this.log.info(`scrub: ${this.tier} tier failed (${s})`,this.el);this.cache?.clear(),this.info=null,this.source=null,this.wait?.end(),this.next(s)}next(t){let e=this.tiers.shift();if(!e)return this.emit("error"),void this.poster(`scrub: ${t??"nothing to scrub (no video src and no data-umber-scrub-frames)"}; the <video> and its poster show instead.`);this.tier=e,this.still(!0);let i=this.sourceFor(e);i?(this.source=i,i.start(),this.emit("tier")):this.next('data-umber-scrub-source="video" needs a <video>')}sourceFor(t){let e=this.o;return"decoder"===t?new F(new URL(this.src,location.href).href,this.host()):"video"===t?this.video?new T(this.video,this.host(),e.fps>0?e.fps:this.fileFps||30,this.own):null:new P(e.frames,Math.round(e.count),e.fps>0?e.fps:30,this.host())}smoothing(){return this.ctx.reducedMotion?0:this.o.smooth>=0?this.o.smooth:"lenis"===this.ctx.scrollKind||this.ctx.engine.scroll||document.documentElement.classList.contains("lenis")?0:.12}binding(){let t={uniforms:z.uniforms},e=N(this.o.reduced,this.opts.reducedMotion,"poster").toLowerCase();return this.ctx.reducedMotion&&"scrub"!==e?(this.poster(),{api:this.api,source:!0,effect:t}):this.tiers.length?{api:this.api,source:!0,effect:z,near:t=>{this.near(t)},update:(t,e,i)=>this.update(t,e,i),lost:()=>{this.snap=!0},src:()=>!this.own,restored:()=>{this.source?.reset(),this.ctx.wake()},destroy:()=>{this.destroy()}}:(this.poster(`scrub: nothing to scrub here (${this.video?"the <video> has no src":"no <video> inside"} and no data-umber-scrub-frames); it shows as plain DOM.`),{api:this.api,source:!0,effect:t})}near(t){if(!this.dead&&"poster"!==this.tier){if(t&&(this.snap=!0),!this.started&&t)return this.started=!0,void this.next();this.source?.active(t),t||this.cache?.clear(!0)}}progressNow(t,e){if("manual"===this.drive.kind)return this.drive.value;let i=this.tracker?this.tracker.rect.y:r(t,1),s=this.tracker?this.tracker.rect.height:r(t,3);return s>0?function({top:t,height:e},i,s,r){let n=s=>(s.alt&&e>i&&(s=s.alt),t+e*s.el+s.elPx-(i*s.vp+s.vpPx)),h=n(s),o=h-n(r);return Math.abs(o)>1e-6?Math.min(1,Math.max(0,h/o)):h<=0?1:0}({top:i,height:s},e.height,this.start,this.end):null}update(t,e,i){let s=this.info;if(!s||!this.source||this.dead)return!1;let r=this.progressNow(e,i);if(null===r)return!1;this.progress=r;let n=s.frames;this.target=r*(n-1);let h=this.shown;return this.shown=this.snap?this.target:function(t,e,i,s){return i>0&&s>0?t+(e-t)*(1-Math.exp(-s/i)):e}(this.shown,this.target,this.smoothing(),t.dt),this.snap=!1,Math.abs(this.target-this.shown)<.01&&(this.shown=this.target),this.velocity=t.dt>0?(this.shown-h)/Math.max(1,n-1)/t.dt:0,this.dir=Math.sign(this.target-this.shown)||Math.sign(this.shown-h)||this.dir,this.ctx.busy(this.shown!==this.target),this.draw(n,e,i),this.uniforms(n,this.shown!==h)}draw(t,e,i){let s=this.frames();s.focus(Math.round(this.shown)),this.source?.request(this.shown,this.dir);let n=function(t,e,i,s){let r=t=>i.ready(t);if(e<=0)return null;let n=Math.max(0,Math.min(e-1,t)),h=Math.floor(n),o=n-h;if(s&&o>.001&&h+1<e&&r(h)&&r(h+1))return{a:h,b:h+1,mix:o};let a=Math.round(n);if(r(a))return{a:a,b:-1,mix:0};let l=-1;for(let t of i.keys())(l<0||Math.abs(t-n)<Math.abs(l-n))&&(l=t);return l<0?null:{a:l,b:-1,mix:0}}(this.shown,t,s,this.o.blend);n&&s.show(n.a,n.b,n.mix);let h=r(e,0),o=r(e,1),a=o<i.height&&o+r(e,3)>0&&h<i.width&&h+r(e,2)>0;if(!this.wait||!a)return;let l=Math.round(Math.max(0,Math.min(t-1,this.shown)));this.wait.frame([l],s.ready(l))}uniforms(t,e){let i=this.ctx.plane.uniforms;if(i.uScrubProgress&&(i.uScrubProgress.value=this.shown/Math.max(1,t-1)),!i.uScrubVelocity)return e;let s=e?this.velocity:0,r=e||i.uScrubVelocity.value!==s;return i.uScrubVelocity.value=s,r}destroy(){this.dead=!0,this.source?.destroy(),this.source=null,this.still(!1),this.tracker?.destroy(),this.handlers.clear(),this.wait?.end(),this.first&&this.readyWith.resolve(!1)}},I={name:"scrub",version:"0.3.0",attributes:["scrub"],plane:t=>function(t){return new H(t).binding()}(t)},B=I;export{I as Scrub,B as default};
|
|
1
|
+
/*! Umber v0.4.1 | (c) Ravi Klaassens | UNLICENSED */
|
|
2
|
+
function t(t,e){let i=t.trim();if("number"===e){let t=parseFloat(i);return Number.isFinite(t)?t:void 0}return"boolean"===e?function(t){let e=t.trim().toLowerCase();return""===e||"true"===e||"1"===e||"yes"===e||"false"!==e&&"0"!==e&&"no"!==e&&void 0}(i):"list"===e?i.split(/[\s,]+/).filter(Boolean):i.replace(/^["']|["']$/g,"")}function e(t){return t.type?t.type:"number"==typeof t.default?"number":"boolean"==typeof t.default?"boolean":Array.isArray(t.default)?"list":"string"}var i=t=>t.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`);function s(i,s,r){let n={},h=r;for(let[r,o]of Object.entries(s)){let s,a=e(o);if(o.attr){let e=i.getAttribute(o.attr);null!==e&&(s=t(e,a))}if(void 0===s&&o.css){h??=getComputedStyle(i);let e=h.getPropertyValue(o.css);e&&""!==e.trim()&&(s=t(e,a))}n[r]=void 0===s?o.default:s}return n}var r=(t,e)=>t[e]??NaN,n={top:0,left:0,center:.5,middle:.5,bottom:1,right:1};function h(t,e){let i=(t??"").trim().toLowerCase();if(!i)return e;let s=function(t){let e=/^(top|left|center|middle|bottom|right|-?\d*\.?\d+(?:px|%)?)?(?:([+-])=?(\d*\.?\d+)(px|%)?)?$/.exec(t);if(!e)return null;let[,i,s,r="",h]=e;if(!i&&!s)return null;let o=0,a=0,l=void 0===i?void 0:n[i];if(void 0!==l)o=l;else if(i){let t=parseFloat(i);i.endsWith("%")?o=t/100:a=t}if(s){let t=parseFloat(r)*("-"===s?-1:1);"%"===h?o+=t/100:a+=t}return[o,a]}(i);return s?/^[+-]/.test(i)&&!/^-\d/.test(i)?[e[0]+s[0],e[1]+s[1]]:s:e}var o={cover:[[0,1,1,0]],contain:[[1,1,0,0],[0,0,1,1]],entry:[[0,1,1,1],[0,1,0,0]],exit:[[0,0,1,0],[1,1,1,0]],"entry-crossing":[[0,1,1,1]],"exit-crossing":[[0,0,1,0]]};function a(t,e){let i=function(t,e){return null==t||""===t?e:t}(t,e).trim().split(/\s+/),s=function(t,e){let[i,s]=t,r=void 0===i?void 0:o[i];if(void 0===r)return null;let[n,h]=r,a=s??(e?"100%":"0%"),l=a.endsWith("%")?0:parseFloat(a)||0,d=l?0:parseFloat(a)/100||0,u=([t,e,i,s])=>({el:t+(i-t)*d,elPx:l,vp:e+(s-e)*d,vpPx:0});return{...u(n),alt:h?u(h):void 0}}(i.map(t=>t.toLowerCase()),e.startsWith("bottom"));if(s)return s;let r=e.split(/\s+/),[n,a]=h(i[0],h(r[0],[0,0])),[l,d]=h(i[1],h(r[1],[0,0]));return{el:n,elPx:a,vp:l,vpPx:d}}var l=(t,e)=>String.fromCharCode(r(t,e),r(t,e+1),r(t,e+2),r(t,e+3));function d(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function u(t,e,i){let s=e.body+i;return s+4<=Math.min(e.end,t.length)?d(t).getUint32(s):Number.NaN}function c(t,e,i,s){let r=u(t,e,i-4);return r*s<=Math.min(e.end,t.length)-(e.body+i)?r:null}var f=2**21;function m(t,e,i=t.length){if(e+8>i)return null;let s=d(t),r=s.getUint32(e),n=l(t,e+4),h=e+8;if(1===r){if(e+16>i)return null;r=s.getUint32(e+8)*2**32+s.getUint32(e+12),h=e+16}else 0===r&&(r=1/0);return r<h-e?null:{type:n,start:e,body:h,end:e+r}}function p(t,e,i){let s=[],r=e;for(;r<i;){let e=m(t,r,i);if(!e||e.end>i||e.end<=r)break;s.push(e),r=e.end}return s}var g=(t,e,i)=>p(t,e.body,e.end).find(t=>t.type===i)??null;function b(t,e,...i){for(let s of i){if(!e)return null;e=g(t,e,s)}return e}function y(t,e,i){let s=b(t,e,"mdia","mdhd"),n=b(t,e,"mdia","minf","stbl");if(!s||!n)return null;let h=u(t,s,1===t[s.body]?20:12);if(Number.isNaN(h))return null;let o=h||1,a=function(t,e){let i=g(t,e,"stsd");if(!i)return null;let s=m(t,i.body+8,i.end);if(!s||s.end>i.end||s.body+28>s.end)return null;let r=d(t),n=s.type,h="",o=null,a=p(t,s.body+78,s.end).find(t=>"avcC"===t.type);return a&&("avc1"===n||"avc3"===n)&&(o=t.slice(a.body,a.end),h=function(t){let e=t=>t.toString(16).padStart(2,"0"),[,i,s,r]=t;return void 0===i||void 0===s||void 0===r?"":`avc1.${e(i)}${e(s)}${e(r)}`}(o)),{format:n,width:r.getUint16(s.body+24),height:r.getUint16(s.body+26),codec:h,description:o}}(t,n);if(!a)return null;let[l,y]=function(t,e){let i=g(t,e,"tkhd");if(!i)return null;let s=i.body+(1===t[i.body]?88:76);if(s+8>i.end)return null;let r=d(t),n=r.getUint32(s)/65536,h=r.getUint32(s+4)/65536;return n&&h?[Math.round(n),Math.round(h)]:null}(t,e)??[a.width,a.height],v=function(t,e){let i=i=>g(t,e,i),s=function(t,e,i){return e?function(t,e){let i=d(t),s=u(t,e,4),r=s?u(t,e,8):c(t,e,12,4);if(null===r||!(r<=f))return null;let n=new Array(r);for(let t=0;t<r;t++)n[t]=s||i.getUint32(e.body+12+4*t);return n}(t,e):i?function(t,e){let i=t[e.body+7];if(4!==i&&8!==i&&16!==i)return null;let s=c(t,e,12,i/8);if(null===s||s>f)return null;let n=d(t),h=e.body+12,o=new Array(s);for(let e=0;e<s;e++)o[e]=16===i?n.getUint16(h+2*e):8===i?r(t,h+e):r(t,h+(e>>1))>>(1&e?0:4)&15;return o}(t,i):null}(t,i("stsz"),i("stz2")),n=function(t,e,i){let s=e??i;if(!s)return null;let r=e?4:8,n=c(t,s,8,r);if(null===n)return null;let h=d(t),o=new Array(n);for(let t=0;t<n;t++){let i=s.body+8+t*r;o[t]=e?h.getUint32(i):h.getUint32(i)*2**32+h.getUint32(i+4)}return o}(t,i("stco"),i("co64")),h=i("stsc");if(!s||!n||!h)return null;let o=function(t,e,i,s){let n=i.length,h=function(t,e){let i=c(t,e,8,12);if(null===i)return null;let s=d(t),r=[];for(let t=0;t<i;t++){let i=e.body+8+12*t;r.push({first:s.getUint32(i)-1,per:s.getUint32(i+4)})}return r}(t,e);if(!h)return null;let o=new Array(n),a=0;for(let[t,e]of h.entries()){if(a>=n)break;let l=h[t+1]?.first??s.length;for(let t=e.first;t<l&&a<n;t++){let h=s[t];if(void 0===h)return null;for(let t=0;t<e.per&&a<n;t++)o[a]=h,h+=r(i,a),a++}}return a<n?null:o}(t,h,s,n),a=i("stts");if(!o||!a)return null;let l=s.length,m=function(t,e,i){let s=d(t),r=new Array(i),n=new Array(i),h=0,o=0,a=c(t,e,8,8);if(null===a)return null;for(let t=0;t<a&&o<i;t++){let a=s.getUint32(e.body+8+8*t),l=s.getUint32(e.body+12+8*t);for(let t=0;t<a&&o<i;t++)r[o]=h,n[o]=l,h+=l,o++}for(;o<i;o++)r[o]=h,n[o]=0;return{dts:r,durations:n}}(t,a,l);if(!m)return null;let{dts:p,durations:b}=m,y=function(t,e,i){let s=i.slice();if(!e)return s;let n=d(t),h=i.length,o=c(t,e,8,8);if(null===o)return null;let a=0;for(let t=0;t<o&&a<h;t++){let i=n.getUint32(e.body+8+8*t),o=n.getInt32(e.body+12+8*t);for(let t=0;t<i&&a<h;t++,a++)s[a]=r(s,a)+o}return s}(t,i("ctts"),p),v=function(t,e,i){let s=new Array(i).fill(!e);if(e){let r=d(t),n=c(t,e,8,4);if(null===n)return null;for(let t=0;t<n;t++){let n=r.getUint32(e.body+8+4*t)-1;n>=0&&n<i&&(s[n]=!0)}}return i&&(s[0]=!0),s}(t,i("stss"),l);return y&&v?s.map((t,e)=>({offset:r(o,e),size:t,dts:r(p,e),cts:r(y,e),duration:r(b,e),key:!0===v[e]})):null}(t,n);if(!v)return null;let w=function(t,e,i,s){let r=b(t,e,"edts","elst");if(!r)return null;let n=d(t),h=1===t[r.body],o=h?20:12,a=u(t,r,4),l=null;for(let t=0;t<a;t++){let e=r.body+8+t*o;if(e+o>r.end)break;let a=h?n.getUint32(e)*2**32+n.getUint32(e+4):n.getUint32(e),d=h?n.getInt32(e+8)*2**32+n.getUint32(e+12):n.getInt32(e+4);if(!(d<0)){if(l)return"cuts";l=[d,a?d+a*i/s:1/0]}}return l}(t,e,o,i||o),k="cuts"===w?null:w,M=t=>!k||t.cts+t.duration/2>=k[0]&&t.cts+t.duration/2<k[1],x=[];for(let[t,e]of v.entries())M(e)&&x.push(t);let S=v.map(t=>t.cts);x.sort((t,e)=>r(S,t)-r(S,e)||t-e);let{keyOf:A,gop:E}=function(t){let e=t.length,i=new Array(e),s=0,r=1;for(let[e,n]of t.entries())n.key&&(e&&(r=Math.max(r,e-s)),s=e),i[e]=s;return e&&(r=Math.max(r,e-s)),{keyOf:i,gop:r}}(v),[$]=x,C=x.at(-1),U=void 0===$?void 0:v[$],F=void 0===C?void 0:v[C],N=(U&&F?F.cts+F.duration-U.cts:0)/o;return{codec:a.codec,format:a.format,description:a.description,width:l,height:y,timescale:o,duration:N,fps:N>0?x.length/N:30,samples:v,order:x,keyOf:A,gop:E,cuts:"cuts"===w}}async function v(t,e){let i=await fetch(t,e);if(!i.ok)throw new Error(`${t} answered ${i.status}`);return i}function w(t,e=location.href){try{return new URL(t,e)}catch{return null}}var k=()=>{},M=class{constructor(){this.bytes=new Uint8Array(0),this.loaded=0,this.total=0,this.done=!1,this.track=null,this.late=!1,this.onTrack=null,this.onData=null,this.onError=null,this.cursor=0,this.sawMdat=!1,this.failed=!1,this.abort=null,this.reader=null}start(t){this.abort=typeof AbortController<"u"?new AbortController:null,this.run(t).catch(t=>{this.abort?.signal.aborted||this.onError?.(t)})}async run(t){let e=await v(t,{mode:"cors",credentials:"omit",signal:this.abort?.signal}),i=Number(e.headers.get("content-length"))||0;i&&!e.headers.get("content-encoding")&&(this.total=i);let s=e.body?.getReader();if(!s)return this.push(new Uint8Array(await e.arrayBuffer())),void this.finish();for(this.reader=s;;){let{done:t,value:e}=await s.read();if(this.failed)return;if(t)break;e.length&&this.push(e)}this.finish()}push(t){if(this.failed)return;let e=this.loaded+t.length;if(e>this.bytes.length){let t=Math.min(this.total,67108864),i=new Uint8Array(Math.max(e,t,2*this.bytes.length,1<<20));i.set(this.bytes.subarray(0,this.loaded)),this.bytes=i}this.bytes.set(t,this.loaded),this.loaded=e,this.scan(),this.onData?.()}finish(){this.done=!0,this.scan(),!this.track&&!this.failed&&this.onError?.(new Error("no H.264 video track found (is it an MP4?)")),this.onData?.()}fail(t){this.failed=!0,this.abort?.abort(),this.reader?.cancel().catch(()=>{}),this.onError?.(t)}scan(){for(;!this.track&&!this.failed;){let t=m(this.bytes,this.cursor,this.loaded);if(!t)return;if("moov"===t.type)return void(t.end<=this.loaded&&this.read(t));if("mdat"===t.type&&(this.sawMdat=!0),!Number.isFinite(t.end))return;this.cursor=t.end}}read(t){this.late=this.sawMdat;let e=function(t,e){let i=g(t,e,"mvhd"),s=i?u(t,i,1===t[i.body]?20:12):0;if(Number.isNaN(s))return null;for(let i of p(t,e.body,e.end)){if("trak"!==i.type)continue;let r=b(t,i,"mdia","hdlr");if(!r||"vide"!==l(t,r.body+8))continue;let n=y(t,i,s);if(n)return g(t,e,"mvex")&&(n.fragmented=!0),n}return null}(this.bytes,t);e?(this.track=e,this.onTrack?.(e)):this.fail(new Error("the MP4 has no video track"))}has(t){return t.offset+t.size<=this.loaded}data(t){return this.bytes.subarray(t.offset,t.offset+t.size)}stop(){this.abort?.abort(),this.onTrack=null,this.onData=null,this.onError=null}};function x(t){return t>0?1:t<0?-1:0}var S=class{constructor(t,e){this.track=t,this.host=e,this.target=-1,this.dir=0,this.busy=null,this.fetched=new Set,this.present=new Array(t.order.length),t.order.forEach((t,e)=>{this.present[t]=e})}get frames(){return this.track.order.length}want(t,e=0){let i=this.frames,s=i?Math.max(0,Math.min(i-1,Math.round(t))):-1;s!==this.target&&this.fetched.clear(),this.target=s,this.dir=x(e)}next(){if(this.busy||this.target<0)return null;let t=this.reachable(this.target);if(t<0)return null;let e=this.host.has(t)?this.ahead(t):t;if(e<0)return null;e!==t&&this.fetched.add(e);let i=this.track.order[e],s=void 0===i?void 0:this.track.keyOf[i];if(void 0===i||void 0===s)return null;let n=Math.max(1,Math.floor(this.host.window()/2)),h=new Set([e]);for(let e=s;e<i;e++){let i=r(this.present,e);Math.abs(i-t)<=n&&!this.host.has(i)&&h.add(i)}return this.busy={from:s,to:i,goal:e,keep:h},this.busy}forget(){this.fetched.clear()}done(){this.busy=null}ready(t){if(!(t>=0&&t<this.frames))return!1;let e=this.track.order[t],i=void 0===e?void 0:this.track.keyOf[e];return void 0!==e&&void 0!==i&&this.host.available(e)&&this.host.available(i)}reachable(t){if(this.ready(t))return t;let e=this.frames;for(let i=1;i<e;i++){if(t-i>=0&&this.ready(t-i))return t-i;if(t+i<e&&this.ready(t+i))return t+i}return-1}ahead(t){let e=this.frames,i=this.host.window(),s=Math.min(12,Math.max(1,Math.floor(i/2)-1),Math.floor((i-1)/2));for(let i=1;i<=s;i++)for(let s=0;s<(this.dir?1:2);s++){let r=t+i*(this.dir||1-2*s);if(!(r<0||r>=e)&&!this.host.has(r)&&!this.fetched.has(r)&&this.ready(r))return r}return-1}};var A="umber:scrub-decode",E={hvc1:"HEVC (hvc1)",hev1:"HEVC (hev1)",av01:"AV1",vp09:"VP9",vp08:"VP8"},$=t=>"QuotaExceededError"===C(t),C=t=>"object"==typeof t&&null!==t&&"name"in t&&"string"==typeof t.name?t.name:"",U=(t,e)=>Math.round(t/e.timescale*1e6),F=class{constructor(t,e){this.url=t,this.host=e,this.tier="decoder",this.stream=new M,this.track=null,this.schedule=null,this.decoder=null,this.config=null,this.made=null,this.accel="no-preference",this.byTime=new Map,this.running=!1,this.on=!0,this.dead=!1,this.errors=0,this.timings=[],this.keep=null,this.outputs=0}start(){let t=this.stream;t.onTrack=t=>{this.configure(t)},t.onData=()=>{this.pump()},t.onError=t=>{this.fail(`could not read the video (${t instanceof Error?t.message:String(t)})`)},t.start(this.url)}async configure(t){let e=function(t){let{codec:e,description:i}=t;return e&&i?t.fragmented&&!t.order.length?"is a fragmented MP4 (its frames are indexed in fragments), which WebCodecs scrubbing doesn't read":t.order.length?{codec:e,description:i}:"has no frames in its index":`is ${E[t.format]??(t.format||"not H.264")}, and WebCodecs scrubbing reads H.264`}(t);if("string"==typeof e)return void this.fail(e,!0);this.warnAbout(t);let i={...e,codedWidth:t.width,codedHeight:t.height,optimizeForLatency:!0},s=await this.pickConfig(i);if(!this.dead){if(!s)return void this.fail(`this browser can't decode ${e.codec} with WebCodecs`);this.begin(t)}}warnAbout(t){this.stream.late&&!this.stream.done&&this.host.log.warn('scrub video is not "faststart" (its index is at the end), so nothing shows until it fully downloads. Encode it with: npm run scrub -- input.mov'),t.cuts&&this.host.log.warn("scrub video has an edit list with several cuts, which the scrub does not follow: it shows every frame of the file. Re-encode it with: npm run scrub -- input.mov"),t.gop>10&&this.host.log.warn(`scrub video has a keyframe only every ${t.gop} frames: each step back decodes up to that many. For smooth scrubbing encode it with: npm run scrub -- input.mov`)}async pickConfig(t){let e=typeof navigator<"u"&&/Android/i.test(navigator.userAgent)?function(){try{let[t,e,...i]=(localStorage.getItem(A)??"").split(" ");return("prefer-software"===t||"prefer-hardware"===t)&&i.join(" ")===navigator.userAgent&&Date.now()-Number(e)<2592e6?t:null}catch{return null}}()??"prefer-hardware":"no-preference",i="no-preference"===e?["no-preference"]:[e,"no-preference"];for(let e of i)try{let i="no-preference"===e?t:{...t,hardwareAcceleration:e},s=await VideoDecoder.isConfigSupported(i);if(this.dead)return!1;if(s.supported){this.config=i,this.accel=e;break}}catch{}return!!this.config}begin(t){this.track=t,t.order.forEach((e,i)=>{let s=t.samples[e];s&&this.byTime.set(U(s.cts,t),i)});let e=this.host.frames;this.schedule=new S(t,{has:t=>e.has(t),available:e=>{let i=t.samples[e];return void 0!==i&&this.stream.has(i)},window:()=>Math.min(e.capacity(t.width,t.height),48)}),this.host.ready({frames:t.order.length,fps:t.fps,width:t.width,height:t.height}),this.pump()}request(t,e){this.schedule&&(this.schedule.want(t,e),this.pump())}active(t){this.on=t,t?(this.schedule?.forget(),this.pump()):this.close()}reset(){this.schedule?.forget(),this.pump()}decoderNow(t){if(this.decoder&&"closed"!==this.decoder.state&&this.made===t)return this.decoder;this.close();let e=new VideoDecoder({output:t=>{this.output(t)},error:t=>{this.onError(e,t)}});return e.configure(t),this.made=t,this.decoder=e,e}output(t){this.outputs++;let e=this.byTime.get(t.timestamp);void 0===e||this.dead||!this.keep?.has(e)||this.host.frames.ready(e)?t.close():(this.host.frames.put(e,t,!0),this.host.delivered())}onError(t,e){t===this.decoder&&(this.decoder=null),$(e)||this.host.log.info("scrub decoder error",e)}chunk(t,e,i){let s=t.samples[e];if(!s)throw new RangeError(`sample ${e} is not in the track`);return new EncodedVideoChunk({type:i||s.key?"key":"delta",timestamp:U(s.cts,t),duration:U(s.duration,t),data:this.stream.data(s)})}async pump(){let t=this.schedule;if(this.running||this.dead||!this.on||!t||!this.track||!this.config)return;let e=t.next();if(!e)return;this.running=!0;let i=this.track,s=performance.now(),r=this.errors,n=!0;try{let t=this.decoderNow(this.config);this.keep=e.keep,this.outputs=0;for(let s=e.from;s<=e.to;s++)t.decode(this.chunk(i,s,s===e.from));await t.flush(),0===this.outputs&&(n=!1,this.errors++,this.close())}catch(t){n=!1,!$(t)&&"AbortError"!==C(t)&&this.errors++,this.close()}if(this.running=!1,!this.isDestroyed()){if(t.done(),n)this.errors=0,this.time((performance.now()-s)/(e.to-e.from+1));else{if(this.errors>=3)return void this.fail("the video decoder keeps failing");this.errors>r&&t.forget()}this.pump()}}time(t){if("prefer-hardware"!==this.accel||(this.timings.push(t),1===this.timings.length))return;let e=(i=this.timings.slice(1)).length<10?null:function(t){if(!t.length)return 0;let e=t.slice().sort((t,e)=>t-e);return r(e,Math.min(e.length-1,Math.ceil(.95*e.length)-1))}(i)>25;var i;if(null===e)return;let s=e?"prefer-software":"prefer-hardware";try{localStorage.setItem(A,`${s} ${Date.now()} ${navigator.userAgent}`)}catch{}if(this.accel="no-preference",!e||!this.config)return;let n={...this.config,hardwareAcceleration:"prefer-software"};VideoDecoder.isConfigSupported(n).then(t=>{!t.supported||this.dead||(this.host.log.info("scrub: hardware decoding is slow at seeking here; using the software decoder"),this.config=n,this.accel="prefer-software",this.running||this.close())}).catch(k)}close(){let t=this.decoder;if(this.decoder=null,t&&"closed"!==t.state)try{t.close()}catch{}}isDestroyed(){return this.dead}fail(t,e){this.dead||(this.destroy(),this.host.failed(t,e))}destroy(){this.dead=!0,this.stream.stop(),this.close(),this.schedule=null}};function N(...t){for(let e of t)if(e)return e;return""}var T=class{constructor(t,e,i,s){this.video=t,this.host=e,this.fps=i,this.src=s,this.tier="video",this.frames=0,this.target=-1,this.seeking=-1,this.landed=-1,this.fastFor=-1,this.errors=0,this.on=!0,this.dead=!1,this.cors=!1,this.offs=[]}start(){let t=this.video;t.muted=!0,t.playsInline=!0,t.setAttribute("playsinline",""),t.setAttribute("webkit-playsinline",""),t.disableRemotePlayback=!0,t.pause();let e=N(t.currentSrc,t.getAttribute("src"),t.querySelector("source")?.getAttribute("src")),i=N(this.src,e),s="auto"!==t.preload;t.preload="auto";let r=i?w(i):null;var n;r&&(n=r,!(("string"==typeof n?w(n):n)?.origin===location.origin))&&!t.crossOrigin&&(t.crossOrigin="anonymous",this.cors=!0,s=!0),this.src&&this.src!==e&&(t.src=this.src,s=!0),this.listen("seeked",()=>{this.onSeeked()}),this.listen("error",e=>{let i=t.querySelectorAll("source");(e.target===t||e.target===i[i.length-1])&&this.fail(this.cors?"the video failed to load (another domain: no CORS headers?)":"the video failed to load")},!0),t.readyState>=1&&!s?this.onMeta():(this.listen("loadedmetadata",()=>{this.onMeta()}),this.meta()),s&&t.load();let h=()=>{this.dead||t.readyState>=2||t.play().then(()=>{t.pause()}).catch(k)};addEventListener("touchstart",h,{once:!0,passive:!0}),this.offs.push(()=>{removeEventListener("touchstart",h)})}listen(t,e,i=!1){this.video.addEventListener(t,e,i),this.offs.push(()=>{this.video.removeEventListener(t,e,i)})}meta(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.frames||this.dead||(1===this.video.networkState?this.meta():this.fail("the video's metadata never loaded"))},1e4)}onMeta(){if(this.frames||this.dead)return;let t=this.video;!Number.isFinite(t.duration)||t.duration<=0?this.fail("the video has no duration (a live stream?)"):(this.frames=Math.max(1,Math.round(t.duration*this.fps)),this.host.ready({frames:this.frames,fps:this.fps,width:t.videoWidth,height:t.videoHeight}),this.pump())}request(t){this.frames&&(this.target=Math.max(0,Math.min(this.frames-1,Math.round(t))),this.pump())}active(t){this.on=t,this.pump()}reset(){this.seeking=-1,this.landed=-1,this.pump()}pump(){if(this.dead||!this.on||this.target<0)return;if(this.seeking>=0){let t=this.host.frames;if(!(this.landed>=0)||!t.ready(this.landed)&&t.has(this.landed))return;this.seeking=-1,this.landed=-1}let t=this.target;if(this.host.frames.has(t))return;let e=this.video;if(e.readyState<1)return;this.seeking=t,this.landed=-1;let i=Math.min((t+.5)/this.fps,Math.max(0,e.duration-.001)),s=Math.round(e.currentTime*this.fps-.5);"function"==typeof e.fastSeek&&Math.abs(t-s)>6&&t!==this.fastFor?(this.fastFor=t,e.fastSeek(i)):e.currentTime=i,clearTimeout(this.timer),this.timer=setTimeout(()=>{this.seeking<0||this.landed>=0||(this.seeking=-1,++this.errors>=3?this.fail("seeking the video never lands"):this.pump())},4e3)}onSeeked(){if(this.dead||this.seeking<0)return;clearTimeout(this.timer),this.errors=0;let t=this.video,e=Math.max(0,Math.min(this.frames-1,Math.floor(t.currentTime*this.fps+.001)));this.landed=e,this.host.frames.put(e,t,!1),this.host.delivered()}fail(t){this.dead||(this.destroy(),this.cors&&(this.video.removeAttribute("crossorigin"),this.video.load()),this.host.failed(t))}destroy(){this.dead=!0,clearTimeout(this.timer),this.offs.forEach(t=>{t()}),this.offs=[]}},P=class{constructor(t,e,i,s){this.pattern=t,this.count=e,this.fps=i,this.host=s,this.tier="frames",this.target=-1,this.dir=0,this.loading=new Set,this.failedFrames=new Set,this.errors=0,this.known=!1,this.width=0,this.height=0,this.on=!0,this.dead=!1,this.abort=typeof AbortController<"u"?new AbortController:null}start(){this.count>0?this.load(0):this.fail('data-umber-scrub-frames needs data-umber-scrub-count="<number of frames>"')}request(t,e){this.target=Math.max(0,Math.min(this.count-1,Math.round(t))),this.dir=x(e),this.pump()}active(t){this.on=t,this.pump()}reset(){this.pump()}pump(){if(this.dead||!this.on||!this.known||this.target<0)return;let t=this.host.frames,e=this.dir>=0?1:-1,i=t.capacity(this.width,this.height)-1,s=Math.min(2,i>>2),r=Math.min(8,i-s);for(let i=0;i<=Math.max(0,r+s)&&this.loading.size<4;i++){let s=this.target+(i<=r?i:r-i)*e;s<0||s>=this.count||t.has(s)||this.loading.has(s)||this.failedFrames.has(s)||this.load(s)}}async load(t){this.loading.add(t);let e=function(t,e){return t.replace(/\{(\d+)\}/,(t,i)=>String(parseInt(i,10)+e).padStart(i.length,"0"))}(this.pattern,t);try{let i=await(await v(e,{mode:"cors",credentials:"omit",signal:this.abort?.signal})).blob(),s=await createImageBitmap(i,{premultiplyAlpha:"premultiply",colorSpaceConversion:"default"}),r=this.host.maxTexture;if(s.width>r||s.height>r){let t=r/Math.max(s.width,s.height),e=await createImageBitmap(s,{resizeWidth:Math.floor(s.width*t),resizeHeight:Math.floor(s.height*t),resizeQuality:"high"});s.close(),s=e}if(this.loading.delete(t),this.dead)return void s.close();this.errors=0,this.known||(this.known=!0,this.width=s.width,this.height=s.height,this.host.ready({frames:this.count,fps:this.fps,width:s.width,height:s.height})),this.host.frames.put(t,s,!0),this.host.delivered()}catch(i){if(this.loading.delete(t),this.dead)return;if(this.failedFrames.add(t),this.host.log.warn(`scrub frame ${e} failed to load`,i),!this.known||++this.errors>=4)return void this.fail(`the image sequence ${this.pattern} does not load`)}this.pump()}fail(t){this.dead||(this.destroy(),this.host.failed(t))}destroy(){this.dead=!0,this.abort?.abort()}},V=()=>new Promise(t=>{let e=new MessageChannel;e.port1.onmessage=t,e.port2.postMessage(0)}),L={high:128,mid:48,low:32},D=new Set,W={start:"top bottom",end:"bottom top",track:"",smooth:-1,source:"auto",src:"",srcMobile:"",frames:"",count:0,fps:0,blend:!0,cache:0,reduced:""},z={uniforms:{uScrubProgress:0,uScrubVelocity:0},fragment:{head:"uniform sampler2D uFrameNext;\nuniform float uFrameMix;\nvec4 scrubNext(vec2 uv) {\n vec2 f = fitUv(uv);\n if (uFit > 0.5 && uFit < 1.5 && (f.x < 0.0 || f.y < 0.0 || f.x > 1.0 || f.y > 1.0)) return vec4(0.0);\n vec4 c = texture(uFrameNext, f);\n return vec4(c.rgb / max(c.a, 1e-5), c.a);\n}",color:"if (uFrameMix > 0.0) color = mix(color, scrubNext(uv), uFrameMix);"}};var O={kind:"scroll"},q=t=>({kind:"manual",value:t}),R=class{constructor(t,e){this.exporter=t,this.decoded=e,this.settle=null,this.want=[],this.stuck=0}frame(t,e){e?this.stuck=0:(this.want=t,!(this.settle||this.stuck>=20)&&this.exporter.wait(new Promise(t=>{let e=i=>{this.settle===e&&(this.settle=null,i&&this.stuck++,t())};this.settle=e,this.decoded(this.want)&&V().then(()=>{e()}),new Promise(t=>{"function"==typeof AbortSignal.timeout?AbortSignal.timeout(250).onabort=()=>{t()}:setTimeout(t,250)}).then(()=>{e(!0)})})))}delivered(){this.settle&&this.decoded(this.want)&&V().then(()=>{this.settle?.()})}end(){this.settle?.()}},H=class{constructor(t){this.ctx=t,this.handlers=new Map,this.readyWith=function(){let t,e;return{promise:new Promise((i,s)=>{t=i,e=s}),resolve:t,reject:e}}(),this.cache=null,this.tier="loading",this.fileFps=0,this.source=null,this.info=null,this.started=!1,this.dead=!1,this.progress=0,this.shown=0,this.target=0,this.velocity=0,this.dir=0,this.snap=!0,this.first=!0,this.autoplay=null;let e=this.el=t.el;this.log=t.log;let r=this.o=function(t,e,r){{let n=e.replace(/^data-/,""),h=r??{},o={};for(let t in h)o[t]={attr:`data-${n}-${i(t)}`,css:`--${n}-${i(t)}`,default:h[t]};return s(t,o,void 0)}}(e,"umber-scrub",W);this.drive="manual"===(e.getAttribute("data-umber-scrub")??"").trim().toLowerCase()?q(0):O,this.start=a(r.start,W.start),this.end=a(r.end,W.end),this.video=t.media instanceof HTMLVideoElement?t.media:null;let n="high"!==t.tier&&!!r.srcMobile;this.own=n?r.srcMobile:r.src,this.src=function(t,e){return N(e,t?.currentSrc,t?.getAttribute("src"),t?.querySelector("source")?.getAttribute("src"))}(this.video,this.own),this.opts=t.options,this.tiers=function(t,e,i,s){if("decoder"===t||"video"===t||"frames"===t)return[t];let r=[];return e&&(()=>{let t=globalThis;return"function"==typeof t.VideoDecoder&&"function"==typeof t.EncodedVideoChunk})()&&r.push("decoder"),i&&e&&r.push("video"),s&&r.push("frames"),r}((r.source||"auto").toLowerCase(),this.src,this.video,r.frames);let h=function(t,e){let i=e.trim();if(!i||"self"===i)return null;if("parent"===i)return t.parentElement;try{return i.startsWith("closest ")?t.closest(i.slice(8).trim()):t.closest(i)??document.querySelector(i)}catch{return null}}(e,r.track);r.track&&!h&&"self"!==r.track.trim()&&this.log.warn(`data-umber-scrub-track="${r.track}": no such element; the video's own position drives it.`,e),this.tracker=h?t.engine.track(h):null;let o=(()=>{let t=typeof globalThis<"u"?globalThis.occluzeCapture:void 0;return 1===t?.version?t:null})();this.wait=o?new R(o,t=>t.every(t=>this.frames().has(t))):null,this.api=function(t){let e=()=>{t.ctx.wake()},i={get progress(){return t.progress},set progress(i){t.drive=q(Math.min(1,Math.max(0,i||0))),e()},get drive(){return t.drive.kind},set drive(i){t.drive="manual"===i?q(t.progress):O,e()},get time(){return t.info?t.shown/t.info.fps:0},set time(e){t.info&&(i.progress=e*t.info.fps/Math.max(1,t.info.frames-1))},get frame(){return t.shown},get frames(){return t.info?.frames??0},get fps(){return t.info?.fps??0},get duration(){return t.info?t.info.frames/t.info.fps:0},get tier(){return t.tier},get ready(){return t.ready},on:(e,s)=>(t.on(e,s),()=>{i.off(e,s)}),off(e,i){t.off(e,i)},destroy(){t.ctx.plane.destroy()}};return i}(this)}get ready(){return this.readyWith.promise}frames(){return this.cache||(this.cache=this.ctx.frames,this.cache.budget=this.budgetMB()*2**20),this.cache}budgetMB(){if(this.o.cache>0)return this.o.cache;let t=this.opts.cacheMB??0;return t>0?t:L[this.ctx.tier]}on(t,e){let i=this.handlers.get(t);i||(i=new Set,this.handlers.set(t,i)),i.add(e)}off(t,e){this.handlers.get(t)?.delete(e)}emit(t){let e=this.handlers.get(t);if(e)for(let i of[...e])if(e.has(i))try{i(this.api)}catch(e){this.log.error(`a scrub "${t}" handler threw:`,e)}}still(t){let e=this.video;e&&(t&&null===this.autoplay?(this.autoplay=e.autoplay,e.autoplay=!1,e.pause()):!t&&null!==this.autoplay&&(e.autoplay=this.autoplay,this.autoplay&&e.isConnected&&e.play().catch(k),this.autoplay=null))}poster(t){this.still(!1),this.tier="poster",this.source?.destroy(),this.source=null,this.info=null,this.ctx.busy(!1),this.ctx.fail(t),this.readyWith.resolve(!1),this.wait?.end(),this.emit("tier")}host(){let t=()=>this.frames();return{get frames(){return t()},log:this.log,maxTexture:this.ctx.maxTexture,ready:t=>{this.sourceReady(t)},delivered:()=>{this.delivered()},failed:(t,e)=>{this.failed(t,e)}}}sourceReady(t){this.dead||("decoder"===this.tier&&(this.fileFps=t.fps),this.info&&this.info.frames!==t.frames&&(this.shown=Math.min(this.shown,t.frames-1)),this.info=t,this.snap=!0,this.ctx.wake())}delivered(){this.dead||(this.first&&(this.first=!1,this.readyWith.resolve(!0),this.emit("ready")),this.wait?.delivered(),this.ctx.wake())}failed(t,e){if(this.dead)return;let i=e?new URL(this.src,location.href).href:"",s=e?`the video ${i} ${t}. Encode it with: npm run scrub -- input.mov`:t;if(e&&this.tiers.length&&!D.has(i)){D.add(i);let t="video"===this.tiers[0]?"by seeking the <video>, which is choppier":"from its image sequence";this.log.warn(`scrub: ${s.replace(/\. Encode/,`, so it scrubs ${t}. Encode`)}`,this.el)}else this.log.info(`scrub: ${this.tier} tier failed (${s})`,this.el);this.cache?.clear(),this.info=null,this.source=null,this.wait?.end(),this.next(s)}next(t){let e=this.tiers.shift();if(!e)return this.emit("error"),void this.poster(`scrub: ${t??"nothing to scrub (no video src and no data-umber-scrub-frames)"}; the <video> and its poster show instead.`);this.tier=e,this.still(!0);let i=this.sourceFor(e);i?(this.source=i,i.start(),this.emit("tier")):this.next('data-umber-scrub-source="video" needs a <video>')}sourceFor(t){let e=this.o;return"decoder"===t?new F(new URL(this.src,location.href).href,this.host()):"video"===t?this.video?new T(this.video,this.host(),e.fps>0?e.fps:this.fileFps||30,this.own):null:new P(e.frames,Math.round(e.count),e.fps>0?e.fps:30,this.host())}smoothing(){return this.ctx.reducedMotion?0:this.o.smooth>=0?this.o.smooth:.12}binding(){let t={uniforms:z.uniforms},e=N(this.o.reduced,this.opts.reducedMotion,"poster").toLowerCase();return this.ctx.reducedMotion&&"scrub"!==e?(this.poster(),{api:this.api,source:!0,effect:t}):this.tiers.length?{api:this.api,source:!0,effect:z,near:t=>{this.near(t)},update:(t,e,i)=>this.update(t,e,i),lost:()=>{this.snap=!0},src:()=>!this.own,restored:()=>{this.source?.reset(),this.ctx.wake()},destroy:()=>{this.destroy()}}:(this.poster(`scrub: nothing to scrub here (${this.video?"the <video> has no src":"no <video> inside"} and no data-umber-scrub-frames); it shows as plain DOM.`),{api:this.api,source:!0,effect:t})}near(t){if(!this.dead&&"poster"!==this.tier){if(t&&(this.snap=!0),!this.started&&t)return this.started=!0,void this.next();this.source?.active(t),t||this.cache?.clear(!0)}}progressNow(t,e){if("manual"===this.drive.kind)return this.drive.value;let i=this.tracker?this.tracker.rect.y:r(t,1),s=this.tracker?this.tracker.rect.height:r(t,3);return s>0?function({top:t,height:e},i,s,r){let n=s=>(s.alt&&e>i&&(s=s.alt),t+e*s.el+s.elPx-(i*s.vp+s.vpPx)),h=n(s),o=h-n(r);return Math.abs(o)>1e-6?Math.min(1,Math.max(0,h/o)):h<=0?1:0}({top:i,height:s},e.height,this.start,this.end):null}update(t,e,i){let s=this.info;if(!s||!this.source||this.dead)return!1;let r=this.progressNow(e,i);if(null===r)return!1;this.progress=r;let n=s.frames;this.target=r*(n-1);let h=this.shown;return this.shown=this.snap?this.target:function(t,e,i,s){return i>0&&s>0?t+(e-t)*(1-Math.exp(-s/i)):e}(this.shown,this.target,this.smoothing(),t.dt),this.snap=!1,Math.abs(this.target-this.shown)<.01&&(this.shown=this.target),this.velocity=t.dt>0?(this.shown-h)/Math.max(1,n-1)/t.dt:0,this.dir=Math.sign(this.target-this.shown)||Math.sign(this.shown-h)||this.dir,this.ctx.busy(this.shown!==this.target),this.draw(n,e,i),this.uniforms(n,this.shown!==h)}draw(t,e,i){let s=this.frames();s.focus(Math.round(this.shown)),this.source?.request(this.shown,this.dir);let n=function(t,e,i,s){let r=t=>i.ready(t);if(e<=0)return null;let n=Math.max(0,Math.min(e-1,t)),h=Math.floor(n),o=n-h;if(s&&o>.001&&h+1<e&&r(h)&&r(h+1))return{a:h,b:h+1,mix:o};let a=Math.round(n);if(r(a))return{a:a,b:-1,mix:0};let l=-1;for(let t of i.keys())(l<0||Math.abs(t-n)<Math.abs(l-n))&&(l=t);return l<0?null:{a:l,b:-1,mix:0}}(this.shown,t,s,this.o.blend);n&&s.show(n.a,n.b,n.mix);let h=r(e,0),o=r(e,1),a=o<i.height&&o+r(e,3)>0&&h<i.width&&h+r(e,2)>0;if(!this.wait||!a)return;let l=Math.round(Math.max(0,Math.min(t-1,this.shown)));this.wait.frame([l],s.ready(l))}uniforms(t,e){let i=this.ctx.plane.uniforms;if(i.uScrubProgress&&(i.uScrubProgress.value=this.shown/Math.max(1,t-1)),!i.uScrubVelocity)return e;let s=e?this.velocity:0,r=e||i.uScrubVelocity.value!==s;return i.uScrubVelocity.value=s,r}destroy(){this.dead=!0,this.source?.destroy(),this.source=null,this.still(!1),this.tracker?.destroy(),this.handlers.clear(),this.wait?.end(),this.first&&this.readyWith.resolve(!1)}},I={name:"scrub",version:"0.4.1",attributes:["scrub"],plane:t=>function(t){return new H(t).binding()}(t)},B=I;export{I as Scrub,B as default};
|
package/dist/modules/three.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! Umber v0.
|
|
2
|
-
(()=>{var e;Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty,e=function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')},typeof require<"u"?require:typeof Proxy<"u"&&new Proxy(e,{get:(e,t)=>(typeof require<"u"?require:e)[t]});var t=()=>{},s={warn:t,error:t},i={GLTFLoader:()=>import("three/addons/loaders/GLTFLoader.js").then(e=>e.GLTFLoader),DRACOLoader:()=>import("three/addons/loaders/DRACOLoader.js").then(e=>e.DRACOLoader),KTX2Loader:()=>import("three/addons/loaders/KTX2Loader.js").then(e=>e.KTX2Loader),MeshoptDecoder:()=>import("three/addons/libs/meshopt_decoder.module.js").then(e=>e.MeshoptDecoder),RoomEnvironment:()=>import("three/addons/environments/RoomEnvironment.js").then(e=>e.RoomEnvironment),clone:()=>import("three/addons/utils/SkeletonUtils.js").then(e=>e.clone)};function r(e){let t=JSON.parse(e);return(e=>"object"==typeof e&&null!==e)(t)&&!Array.isArray(t)?t:null}var n=(e,t)=>`https://cdn.jsdelivr.net/npm/three@0.${e}.0/examples/jsm/libs/${t}/`;async function o(e,t){let s=new AbortController,i=setTimeout(()=>{s.abort()},t);try{let t=await fetch(e,{signal:s.signal});if(!t.ok)throw new Error(`${e}: HTTP ${t.status}`);return await t.arrayBuffer()}finally{clearTimeout(i)}}function h(e){e.traverse(e=>{let t=e;t.geometry?.dispose();let s=Array.isArray(t.material)?t.material:[t.material];for(let e of s)if(e&&"object"==typeof e){for(let t of Object.values(e)){let e=t;e?.isTexture&&e.dispose?.()}e.dispose?.()}})}var a=class{constructor(e){this.options=e,this.threeModule=null,this.loaded=null,this.addons=new Map,this.loader=null,this.decoders=new Map,this.files=new Map,this.workers=[]}three(){if(!this.threeModule){let e=this.options.three;this.threeModule="function"==typeof e?e():e?Promise.resolve(e):import("three"),this.threeModule.then(e=>{this.loaded=e},()=>{this.threeModule=null})}return this.threeModule}addon(e){let t=this.addons.get(e);if(!t){let s=this.options.addons?.[e];t=s?Promise.resolve(s):i[e](),this.addons.set(e,t),t.catch(()=>this.addons.delete(e))}return t}async take(e,t){let s=this.files.get(e);s||(s=this.parse(e,t),this.files.set(e,s),s.catch(()=>this.files.delete(e)));let i=await s;if(i.timer&&clearTimeout(i.timer),i.timer=0,i.users++,!i.taken)return i.taken=!0,{asset:i,root:i.gltf.scene};let r=i.needs.skinned?(await this.addon("clone"))(i.gltf.scene):i.gltf.scene.clone(!0);return{asset:i,root:r}}give(e){let{asset:t,root:s}=e;s.removeFromParent(),s===t.gltf.scene&&(t.taken=!1),!(--t.users>0)&&(t.timer=setTimeout(()=>{t.timer=0,!(t.users>0)&&(this.files.delete(t.url),h(t.gltf.scene))},this.options.keep??1e4))}async parse(e,t){let[s,i]=await Promise.all([o(e,3e4),this.gltfLoader()]),n=function(e){try{if(e.byteLength>=20){let t=new DataView(e);if(1179937895===t.getUint32(0,!0)){let s=t.getUint32(12,!0);return 1313821514!==t.getUint32(16,!0)||20+s>e.byteLength?null:r((new TextDecoder).decode(new Uint8Array(e,20,s)))}}return r((new TextDecoder).decode(e))}catch{return null}}(s);if(!n)throw new Error(`${e} is not a glTF file (.glb or .gltf)`);let h=function(e){let t=new Set([...e.extensionsUsed??[],...e.extensionsRequired??[]]);return{draco:t.has("KHR_draco_mesh_compression"),ktx2:t.has("KHR_texture_basisu"),meshopt:t.has("EXT_meshopt_compression")||t.has("KHR_meshopt_compression"),skinned:Array.isArray(e.skins)&&e.skins.length>0}}(n);return await this.decode(i,h,t),{url:e,gltf:await i.parseAsync(s,new URL(".",e).href),needs:h,users:0,taken:!1,timer:0}}gltfLoader(){return this.loader||(this.loader=this.addon("GLTFLoader").then(e=>new e),this.loader.catch(()=>{this.loader=null})),this.loader}async decode(e,t,s){let i=await this.three(),r=this.options.decoders??{},o=[];t.draco&&o.push(this.decoder("draco",async()=>{let t=new(await this.addon("DRACOLoader"));t.setDecoderPath(r.draco??n(i.REVISION,"draco/gltf")),this.workers.push(t),e.setDRACOLoader(t)})),t.ktx2&&o.push(this.decoder("ktx2",async()=>{let t=new(await this.addon("KTX2Loader"));t.setTranscoderPath(r.basis??n(i.REVISION,"basis")).detectSupport(s),this.workers.push(t),e.setKTX2Loader(t)})),t.meshopt&&o.push(this.decoder("meshopt",async()=>{e.setMeshoptDecoder(await this.addon("MeshoptDecoder"))})),await Promise.all(o)}decoder(e,t){let s=this.decoders.get(e);return s||(s=t(),this.decoders.set(e,s),s.catch(()=>this.decoders.delete(e))),s}dispose(){for(let e of this.files.values())e.then(e=>{e.timer&&clearTimeout(e.timer),h(e.gltf.scene)},()=>{});this.files.clear();for(let e of this.workers.splice(0))e.dispose()}},l=class{constructor(e,t){this.assets=e,this.wake=t,this.map=null,this.room=null,this.asked=!1}texture(e){if(this.map)return this.map;if(!this.room)return this.asked||(this.asked=!0,this.assets.addon("RoomEnvironment").then(e=>{this.room=e,this.wake()},()=>{})),null;let t=this.assets.loaded;if(!t)return null;let s=new t.PMREMGenerator(e),i=new this.room;return this.map=s.fromScene(i,.04).texture,i.dispose(),s.dispose(),this.map}apply(e,t,s){if("none"!==t){if("room"!==t)return void(e.environment=t);e.environment===this.map&&this.map||(e.environment=this.texture(s))}}restored(){this.map?.dispose(),this.map=null}dispose(){this.map?.dispose(),this.map=null}},d=e=>e*Math.PI/180,u=e=>"contain"===e||"cover"===e;function c(e,t,s,i){let r=t.margin;return i.x=e.x+e.width/2-t.width/2,i.y=t.height/2-(e.y+e.height/2),i.size="cover"===s?Math.max(e.width,e.height):Math.min(e.width,e.height),i.near=e.x+e.width>-r&&e.x<t.width+r&&e.y+e.height>-r&&e.y<t.height+r,i}function p(e,t,s){if(t<=0||s<=0)return;let i=((e,t)=>t/2/Math.tan(d(e)/2))(e.fov,s);e.aspect=t/s,e.position.set(0,0,i),e.near=i/50,e.far=50*i,e.updateProjectionMatrix()}var m=class{constructor(e,t,s){this.hub=e,this.renderer=t,this.el=function(){let e=document.createElement("div");return e.setAttribute("aria-hidden","true"),e.setAttribute("data-umber-page-scene",""),e.style.cssText="position:fixed;inset:0;pointer-events:none;margin:0;padding:0;border:0",document.body.append(e),e}(),this.environment="room",this.pins=new Set,this.hooks=new Set,this.place={x:0,y:0,size:0,near:!1},this.viewport={width:0,height:0,margin:0};let i=e.three(),r=this.scene=new i.Scene,n=this.camera=new i.PerspectiveCamera(30,1,1,1e3);this.view=e.engine.view(this.el,{scene:r,camera:n,scissor:!1,followOpacity:!1,passes:!0,resize(e){p(n,e.width,e.height)},animate:e=>this.frame(e),render:()=>{this.draw()}}),this.view.on("destroy",()=>{for(let e of[...this.pins])e.remove();this.hooks.clear(),this.el.remove(),s()})}pin(e,t,s={}){let i="string"==typeof t?document.querySelector(t):t;if(!i)return null;let r=new(this.hub.three().Group);r.add(e),this.scene.add(r);let n=this.hub.engine.track(i),o=s.fit??"none",h=this.pins,a={el:i,object:e,holder:r,tracker:n,fit:u(o)?o:"none",z:s.z??0,get progress(){return n.progress},remove(){h.delete(a)&&(l(),r.remove(e),r.removeFromParent(),n.destroy())}},l=n.on("destroy",()=>{a.remove()});return h.add(a),this.view.wake(1),a}onFrame(e){return this.hooks.add(e),this.view.wake(1),()=>{this.hooks.delete(e)}}frame(e){let t=this.viewport,s=this.place;t.width=e.width,t.height=e.height,t.margin=.5*e.height;for(let e of this.pins)c(e.tracker.rect,t,"none"===e.fit?"contain":e.fit,s),e.holder.visible=s.near,e.holder.position.set(s.x,s.y,e.z),"none"!==e.fit&&e.holder.scale.setScalar(Math.max(s.size,.001));let i=!1;for(let t of this.hooks)!0===t(e)&&(i=!0);return i}draw(){this.scene.children.some(e=>e.visible)&&(this.hub.env.apply(this.scene,this.environment,this.renderer),this.renderer.render(this.scene,this.camera))}},f=class{constructor(e,t){this.engine=e,this.models=new Map,this.shared=null,this.page=null,this.warned=!1,this.assets=new a(t),this.env=new l(this.assets,()=>{e.wake(1)})}three(){let e=this.assets.loaded;if(!e)throw new Error("three.js is not loaded yet");return e}load(){return this.assets.three().then(e=>e,e=>(this.cannotLoad(e),null))}renderer(){return this.shared??=this.load().then(e=>e?this.engine.renderer(e):null),this.shared}pageScene(){return this.page??=this.renderer().then(e=>e?((e,t)=>new m(this,t,()=>{this.page=null}))(0,e):null),this.page}cannotLoad(e){this.warned||(this.warned=!0,s.warn('three.js could not load, so 3D keeps its DOM. Map "three" and "three/addons/" in an import map, install three for your bundler, or pass it: umber.use(Three, { three: THREE }).',e))}dispose(){for(let e of[...this.models.values()])e.destroy();this.assets.dispose(),this.env.dispose()}},w={fit:"contain",fov:30,zoom:1,rotate:"",turn:0,spin:0,tilt:0,play:"",scrub:!1,environment:"room",scene:"box"},g=1e-4,y=class{constructor(e,s){this.hub=e,this.el=s,this.status="waiting",this.scene=null,this.camera=null,this.object=null,this.pivot=null,this.gltf=null,this.mixer=null,this.pin=null,this.progress=0,this.velocity=0,this.settle=t,this.hooks=new Set,this.instance=null,this.inner=null,this.box=null,this.renderer=null,this.actions=[],this.options=w,this.base=[0,0,0],this.spun=0,this.tilted=0,this.busy=!1,this.src="",this.gen=0,this.ready=this.waitReady(),this.frame={dt:0,time:0,progress:0,velocity:0,reducedMotion:!1,model:this}}waitReady(){return new Promise(e=>{this.settle=e})}onFrame(e){return this.hooks.add(e),this.wake(),()=>{this.hooks.delete(e)}}wake(){this.hub.engine.wake(1)}async setup(e){let t=++this.gen;this.status="loading",this.options=e.options;let s=await this.hub.renderer();if(!s)throw new Error("three.js or WebGL is not available");let i=this.el.getAttribute("data-umber-src")??"";if(!i)throw new Error('data-umber="model" needs data-umber-src="model.glb"');let r=await this.hub.assets.take(new URL(i,document.baseURI).href,s),n="page"===this.options.scene?await this.hub.pageScene():null;if(t!==this.gen)return void this.hub.assets.give(r);this.renderer=s,this.src=i;let o=this.place(r);if(n)this.pin=n.pin(o,this.el,{fit:this.fit()}),this.scene=n.scene,this.camera=n.camera;else{let e=this.hub.three();this.box??={scene:new e.Scene,camera:new e.PerspectiveCamera(this.options.fov,1,.01,100)},this.box.camera.fov=this.options.fov,this.box.scene.add(o),this.scene=this.box.scene,this.camera=this.box.camera}this.status="ready",this.settle(this)}fit(){return u(this.options.fit)?this.options.fit:"contain"}place(e){let t=this.hub.three(),s=e.root,i=(new t.Box3).setFromObject(s),r=i.getCenter(new t.Vector3),n=i.isEmpty()?.5:i.getSize(new t.Vector3).length()/2||.5,o=new t.Group;o.position.copy(r).negate(),o.add(s);let h=this.pivot??new t.Group;return this.inner&&h.remove(this.inner),h.add(o),h.scale.setScalar(this.options.zoom/(2*n)),function(e,t){let s=e.trim().split(/[\s,]+/);for(let e=0;e<3;e++){let i=Number.parseFloat(s[e]??"");t[e]=Number.isFinite(i)?d(i):0}}(this.options.rotate,this.base),this.pivot=h,this.inner=o,this.instance=e,this.object=s,this.gltf=e.asset.gltf,this.animations(t,s),h}animations(e,t){this.mixer?.stopAllAction(),this.actions=[];let s=this.gltf?.animations??[];this.mixer=s.length?new e.AnimationMixer(t):null;let{play:i,scrub:r}=this.options;if(this.mixer&&(i||r))for(let e of s){if(i&&"all"!==i&&e.name!==i)continue;let t=this.mixer.clipAction(e);t.play(),t.paused=r,this.actions.push(t)}}resize(e){let t=this.camera;if(!t||this.pin||e.rect.height<=0)return;t.aspect=e.rect.width/e.rect.height;let s=function(e,t,s,i="contain"){let r=d(t),n=2*Math.atan(Math.tan(r/2)*Math.max(s,1e-6)),o="cover"===i?Math.max(r,n):Math.min(r,n);return e/Math.sin(o/2)}(.5,t.fov,t.aspect,this.fit());t.position.set(0,0,s),t.near=s/100,t.far=100*s,t.updateProjectionMatrix()}render(e){let t=this.renderer,s=this.scene,i=this.camera;!t||!s||!i||"ready"!==this.status||((this.el.getAttribute("data-umber-src")??"")!==this.src&&this.reload(e),this.step(e),!this.pin&&(e.three(t),this.hub.env.apply(s,"none"===this.options.environment?"none":"room",t),t.render(s,i)))}step(e){let t=this.pivot;if(!t)return;let s=e.reducedMotion,i=s?0:e.frame?.dt??0;this.progress=function(e,t){let s=t+e.height;return s>0?Math.min(1,Math.max(0,(t-e.y)/s)):0}(e.rect,e.viewport.height),this.velocity=e.scrollVelocity;let r=this.turn(t,i,s);this.animate(i,s)&&(r=!0),this.hooked(e,i,s)&&(r=!0),r!==this.busy&&(this.busy=r,e.busy(r))}turn(e,t,s){let{turn:i,spin:r,tilt:n}=this.options,o=s?0:Math.max(-1,Math.min(1,this.velocity/1e3*n));this.tilted=s?0:((e,t,s,i)=>t+(e-t)*Math.exp(-6*Math.max(0,i)))(this.tilted,o,0,t),this.spun=(this.spun+r*t)%1;let[h,a,l]=this.base;return e.rotation.set(h+this.tilted,a+(i*this.progress+this.spun)*Math.PI*2,l),0!==r&&!s||Math.abs(this.tilted-o)>g||Math.abs(this.tilted)>g}animate(e,t){let s=this.mixer;if(!s||!this.actions.length)return!1;if(this.options.scrub){for(let e of this.actions)e.time=this.progress*e.getClip().duration;return s.update(0),!1}return!t&&(s.update(e),!0)}hooked(e,t,s){let i=!1,r=this.frame;r.dt=t,r.time=e.time,r.progress=this.progress,r.velocity=this.velocity,r.reducedMotion=s;for(let e of this.hooks)!0===e(r)&&(i=!0);return i}reload(e){let t=this.renderer,i=this.el.getAttribute("data-umber-src")??"";if(this.src=i,!t||!i)return;let r=this.gen;this.hub.assets.take(new URL(i,document.baseURI).href,t).then(t=>{if(r!==this.gen||i!==this.src)return void this.hub.assets.give(t);let s=this.instance;this.place(t),s&&this.hub.assets.give(s),e.wake(1)},e=>{s.warn(`data-umber-src="${i}" could not load; the model before it stays.`,e)})}teardown(){this.gen++,this.mixer?.stopAllAction(),this.pin?.remove(),this.pivot?.removeFromParent(),this.instance&&this.hub.assets.give(this.instance),this.instance=null,this.inner=null,this.pivot=null,this.object=null,this.mixer=null,this.pin=null,this.busy=!1,this.renderer=null,this.el.isConnected?(this.status="waiting",this.ready=this.waitReady()):this.destroy()}destroy(){"destroyed"!==this.status&&(this.instance&&this.teardown(),this.status="destroyed",this.scene=null,this.camera=null,this.box=null,this.hooks.clear(),this.hub.models.delete(this.el),this.settle(null),this.ready=Promise.resolve(null))}failed(){this.status="error",this.settle(null)}};function v(e,t){let s=e.models.get(t);return s||(s=new y(e,t),e.models.set(t,s)),s}var b=e=>"string"==typeof e?document.querySelector(e):e;var x={name:"three",version:"0.3.0",attributes:[],install:(...e)=>{let[t,i,r,n,o]=e;(function(e){e&&(s=e)})(o),(({engine:e,options:t})=>{!function(e,t={}){let s=new f(e,t);e.layer("model",function(e){return{options:w,async setup(t){let s=v(e,t.el);t.state.model=s;try{await s.setup(t)}catch(e){throw s.failed(),e}return()=>{s.teardown()}},render(e){e.state.model.render(e)},resize(e){e.state.model.resize(e)},animate:!1,passes:!0}}(s));let i={load:()=>s.load(),renderer:()=>s.renderer(),model(e){let t=b(e);return t?v(s,t):null},async scene(e,t={}){let i=b(e);if(!(i instanceof HTMLElement))return null;let r=await s.renderer();return r?function(e,t,s,i){let r=e.three(),n=i.scene??new r.Scene,o=!i.camera,a=i.camera??new r.PerspectiveCamera(i.fov??30,1,1,1e3),l=i.dispose??!i.scene,d={el:s,scene:n,camera:a,environment:i.environment??"room",view:null};return d.view=e.engine.view(s,{scene:n,camera:a,scissor:i.scissor,followOpacity:i.followOpacity,dpr:i.dpr,passes:i.passes??!0,animate:i.animate,resize(e){o&&p(a,e.width,e.height)},render(){e.env.apply(n,d.environment,t),t.render(n,a)}}),l&&d.view.on("destroy",()=>{h(n)}),d}(s,r,i,t):null},page:()=>s.pageScene(),lights(e,t=1){let i=s.assets.loaded;if(!i)return null;let r=new i.Group,n=new i.DirectionalLight(16777215,2.2*t);n.position.set(3,4,5);let o=new i.DirectionalLight(16777215,.8*t);return o.position.set(-4,1,2),r.add(n,o,new i.HemisphereLight(16777215,4210752,.9*t)),e.add(r),r}};e.three=i,e.on("restored",()=>{s.env.restored()}),e.on("destroy",()=>{s.dispose(),e.three===i&&(e.three=void 0)})}(e,t)})({engine:t,options:i,keep:r,root:n})}};!function(e){let t,s=window;s.Umber?.use?s.Umber.use(e,t):(s.UmberModules??=[],s.UmberModules.push(t?[e,t]:e),s.__umber?.engine?.use?.(e,t))}(x)})();
|
|
1
|
+
/*! Umber v0.4.1 | (c) Ravi Klaassens | UNLICENSED */
|
|
2
|
+
(()=>{var e;Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty,e=function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')},typeof require<"u"?require:typeof Proxy<"u"&&new Proxy(e,{get:(e,t)=>(typeof require<"u"?require:e)[t]});var t=()=>{},s={warn:t,error:t},i=(e,t)=>e[t]??NaN,r=e=>e.left??e.x??0,n=e=>e.top??e.y??0;function o(){return{left:0,top:0,width:"number"==typeof innerWidth?innerWidth:1,height:"number"==typeof innerHeight?innerHeight:1}}function a(e,t){let[s,r,n]=t,o=i(e,3)*s+i(e,7)*r+i(e,11)*n+i(e,15)||1;return t[0]=(i(e,0)*s+i(e,4)*r+i(e,8)*n+i(e,12))/o,t[1]=(i(e,1)*s+i(e,5)*r+i(e,9)*n+i(e,13))/o,t[2]=(i(e,2)*s+i(e,6)*r+i(e,10)*n+i(e,14))/o,o}var h=[0,0,0],l=[0,0,0];function d(e,[t,s],i,r){h[0]=t,h[1]=s,h[2]=-1,a(e.projectionMatrixInverse.elements,h),a(e.matrixWorld.elements,h),l[0]=t,l[1]=s,l[2]=1,a(e.projectionMatrixInverse.elements,l),a(e.matrixWorld.elements,l);let n=l[2]-h[2],o=Math.abs(n)<1e-12?0:(i-h[2])/n;return r[0]=h[0]+(l[0]-h[0])*o,r[1]=h[1]+(l[1]-h[1])*o,r[2]=i,r}function u(e,t,s){let r=s??o().height,n=e.zoom&&Number.isFinite(e.zoom)?e.zoom:1;if(e.isOrthographicCamera)return r*n/Math.max(1e-9,(e.top??1)-(e.bottom??-1));let a=Math.abs(t??function(e){return e.updateMatrixWorld?.(),i(e.matrixWorld.elements,14)}(e)),h=(e.fov??50)*Math.PI/180;return r*n/Math.max(1e-9,2*a*Math.tan(h/2))}function c(e,t,s=1){let i=Math.max(1e-6,t.width)/s,r=Math.max(1e-6,t.height)/s;if(e.isOrthographicCamera)e.left=-i/2,e.right=i/2,e.top=r/2,e.bottom=-r/2,e.zoom=1;else{let t=(e.fov??50)*Math.PI/180,s=r/2/Math.tan(t/2);e.aspect=i/r,e.zoom=1,e.position&&(e.position.z=s),"number"==typeof e.far&&e.far<2*s&&(e.far=2*s)}return e.updateProjectionMatrix?.(),e.updateMatrixWorld?.(!0),e}var p=[0,0,0],m=[0,0,0],f=[0,0,0];function w(e,t,s,i={}){let a=i.frame??o(),h=i.z??0;t.updateMatrixWorld?.();let l=Math.max(a.width,1e-6),u=Math.max(a.height,1e-6),c=(e,t)=>[(e-r(a))/l*2-1,1-(t-n(a))/u*2],w=r(e),g=n(e);d(t,c(w,g),h,p),d(t,c(w+e.width,g+e.height),h,m),d(t,c(w+e.width/2,g+e.height/2),h,f);let y={x:f[0],y:f[1],z:h,width:Math.abs(m[0]-p[0]),height:Math.abs(p[1]-m[1])};return s&&(s.x=y.x,s.y=y.y,s.z=y.z),y}function g(e,t,s=o()){t.updateMatrixWorld?.(),l[0]=e.x,l[1]=e.y,l[2]=e.z,a(t.matrixWorldInverse.elements,l);let i=a(t.projectionMatrix.elements,l),h=!!t.isOrthographicCamera||i>0;return{x:r(s)+(l[0]+1)/2*s.width,y:n(s)+(1-l[1])/2*s.height,visible:h&&Math.abs(l[0])<=1&&Math.abs(l[1])<=1&&l[2]>=-1&&l[2]<=1}}var y={GLTFLoader:()=>import("three/addons/loaders/GLTFLoader.js").then(e=>e.GLTFLoader),DRACOLoader:()=>import("three/addons/loaders/DRACOLoader.js").then(e=>e.DRACOLoader),KTX2Loader:()=>import("three/addons/loaders/KTX2Loader.js").then(e=>e.KTX2Loader),MeshoptDecoder:()=>import("three/addons/libs/meshopt_decoder.module.js").then(e=>e.MeshoptDecoder),RoomEnvironment:()=>import("three/addons/environments/RoomEnvironment.js").then(e=>e.RoomEnvironment),clone:()=>import("three/addons/utils/SkeletonUtils.js").then(e=>e.clone)};function b(e){let t=JSON.parse(e);return(e=>"object"==typeof e&&null!==e)(t)&&!Array.isArray(t)?t:null}var v=(e,t)=>`https://cdn.jsdelivr.net/npm/three@0.${e}.0/examples/jsm/libs/${t}/`;async function x(e,t){let s=new AbortController,i=setTimeout(()=>{s.abort()},t);try{let t=await fetch(e,{signal:s.signal});if(!t.ok)throw new Error(`${e}: HTTP ${t.status}`);return await t.arrayBuffer()}finally{clearTimeout(i)}}function M(e){e.traverse(e=>{let t=e;t.geometry?.dispose();let s=Array.isArray(t.material)?t.material:[t.material];for(let e of s)if(e&&"object"==typeof e){for(let t of Object.values(e)){let e=t;e?.isTexture&&e.dispose?.()}e.dispose?.()}})}var k=class{constructor(e){this.options=e,this.threeModule=null,this.loaded=null,this.addons=new Map,this.loader=null,this.decoders=new Map,this.files=new Map,this.workers=[]}three(){if(!this.threeModule){let e=this.options.three;this.threeModule="function"==typeof e?e():e?Promise.resolve(e):import("three"),this.threeModule.then(e=>{this.loaded=e},()=>{this.threeModule=null})}return this.threeModule}addon(e){let t=this.addons.get(e);if(!t){let s=this.options.addons?.[e];t=s?Promise.resolve(s):y[e](),this.addons.set(e,t),t.catch(()=>this.addons.delete(e))}return t}async take(e,t){let s=this.files.get(e);s||(s=this.parse(e,t),this.files.set(e,s),s.catch(()=>this.files.delete(e)));let i=await s;if(i.timer&&clearTimeout(i.timer),i.timer=0,i.users++,!i.taken)return i.taken=!0,{asset:i,root:i.gltf.scene};let r=i.needs.skinned?(await this.addon("clone"))(i.gltf.scene):i.gltf.scene.clone(!0);return{asset:i,root:r}}give(e){let{asset:t,root:s}=e;s.removeFromParent(),s===t.gltf.scene&&(t.taken=!1),!(--t.users>0)&&(t.timer=setTimeout(()=>{t.timer=0,!(t.users>0)&&(this.files.delete(t.url),M(t.gltf.scene))},this.options.keep??1e4))}async parse(e,t){let[s,i]=await Promise.all([x(e,3e4),this.gltfLoader()]),r=function(e){try{if(e.byteLength>=20){let t=new DataView(e);if(1179937895===t.getUint32(0,!0)){let s=t.getUint32(12,!0);return 1313821514!==t.getUint32(16,!0)||20+s>e.byteLength?null:b((new TextDecoder).decode(new Uint8Array(e,20,s)))}}return b((new TextDecoder).decode(e))}catch{return null}}(s);if(!r)throw new Error(`${e} is not a glTF file (.glb or .gltf)`);let n=function(e){let t=new Set([...e.extensionsUsed??[],...e.extensionsRequired??[]]);return{draco:t.has("KHR_draco_mesh_compression"),ktx2:t.has("KHR_texture_basisu"),meshopt:t.has("EXT_meshopt_compression")||t.has("KHR_meshopt_compression"),skinned:Array.isArray(e.skins)&&e.skins.length>0}}(r);return await this.decode(i,n,t),{url:e,gltf:await i.parseAsync(s,new URL(".",e).href),needs:n,users:0,taken:!1,timer:0}}gltfLoader(){return this.loader||(this.loader=this.addon("GLTFLoader").then(e=>new e),this.loader.catch(()=>{this.loader=null})),this.loader}async decode(e,t,s){let i=await this.three(),r=this.options.decoders??{},n=[];t.draco&&n.push(this.decoder("draco",async()=>{let t=new(await this.addon("DRACOLoader"));t.setDecoderPath(r.draco??v(i.REVISION,"draco/gltf")),this.workers.push(t),e.setDRACOLoader(t)})),t.ktx2&&n.push(this.decoder("ktx2",async()=>{let t=new(await this.addon("KTX2Loader"));t.setTranscoderPath(r.basis??v(i.REVISION,"basis")).detectSupport(s),this.workers.push(t),e.setKTX2Loader(t)})),t.meshopt&&n.push(this.decoder("meshopt",async()=>{e.setMeshoptDecoder(await this.addon("MeshoptDecoder"))})),await Promise.all(n)}decoder(e,t){let s=this.decoders.get(e);return s||(s=t(),this.decoders.set(e,s),s.catch(()=>this.decoders.delete(e))),s}dispose(){for(let e of this.files.values())e.then(e=>{e.timer&&clearTimeout(e.timer),M(e.gltf.scene)},()=>{});this.files.clear();for(let e of this.workers.splice(0))e.dispose()}},L=class{constructor(e,t){this.assets=e,this.wake=t,this.map=null,this.room=null,this.asked=null,this.linking=null}load(){return this.asked??=this.assets.addon("RoomEnvironment").then(e=>{this.room=e,this.wake()},t),this.asked}texture(e){if(this.map)return this.map;if(!this.room)return this.load(),null;let t=this.assets.loaded;if(!t)return null;let s=this.linking??=this.link(t,new this.room,e);return s.linked?(this.map=s.pmrem.fromScene(s.room,.04).texture,this.drop(),this.map):null}async ready(e){this.texture(e),await(this.linking?.ready)}link(e,t,s){let i=new e.PMREMGenerator(s),r=[],n=[],o=s.render;s.render=(t,i)=>{let{material:o,geometry:a}=t;if(o&&!Array.isArray(o)){let s=o.clone();r.push(s),t=new e.Mesh(a,s)}n.push(s.compileAsync(t,i))};try{i.fromScene(t,.04).dispose()}finally{s.render=o}let a={pmrem:i,room:t,kept:r,ready:Promise.allSettled(n).then(()=>{a.linked=!0,this.wake()})};return a}drop(){let e=this.linking;this.linking=null,e?.ready.then(()=>{e.room.dispose(),e.pmrem.dispose();for(let t of e.kept)t.dispose()})}apply(e,t,s){if("none"!==t){if("room"!==t)return void(e.environment=t);e.environment===this.map&&this.map||(e.environment=this.texture(s))}}dispose(){this.map?.dispose(),this.map=null,this.drop()}},P=e=>e*Math.PI/180,j=e=>"contain"===e||"cover"===e;function A(e,t,s,i){let r=t.margin;return i.x=e.x+e.width/2-t.width/2,i.y=t.height/2-(e.y+e.height/2),i.size="cover"===s?Math.max(e.width,e.height):Math.min(e.width,e.height),i.near=e.x+e.width>-r&&e.x<t.width+r&&e.y+e.height>-r&&e.y<t.height+r,i}function T(e,t,s){if(t<=0||s<=0)return;let i=((e,t)=>t/2/Math.tan(P(e)/2))(e.fov,s);e.aspect=t/s,e.position.set(0,0,i),e.near=i/50,e.far=50*i,e.updateProjectionMatrix()}var O=class{constructor(e,t,s){this.hub=e,this.renderer=t,this.el=function(){let e=document.createElement("div");return e.setAttribute("aria-hidden","true"),e.setAttribute("data-umber-page-scene",""),e.style.cssText="position:fixed;inset:0;pointer-events:none;margin:0;padding:0;border:0",document.body.append(e),e}(),this.environment="room",this.pins=new Set,this.hooks=new Set,this.place={x:0,y:0,size:0,near:!1},this.viewport={width:0,height:0,margin:0};let i=e.three(),r=this.scene=new i.Scene,n=this.camera=new i.PerspectiveCamera(30,1,1,1e3);this.view=e.engine.view(this.el,{scene:r,camera:n,scissor:!1,followOpacity:!1,passes:!0,resize(e){T(n,e.width,e.height)},animate:e=>this.frame(e),render:()=>{this.draw()}}),this.view.on("destroy",()=>{for(let e of[...this.pins])e.remove();this.hooks.clear(),this.el.remove(),s()})}pin(e,t,s={}){let i="string"==typeof t?document.querySelector(t):t;if(!i)return null;let r=new(this.hub.three().Group);r.add(e),this.scene.add(r);let n=this.hub.engine.track(i),o=s.fit??"none",a=this.pins,h={el:i,object:e,holder:r,tracker:n,fit:j(o)?o:"none",z:s.z??0,get progress(){return n.progress},remove(){a.delete(h)&&(l(),r.remove(e),r.removeFromParent(),n.destroy())}},l=n.on("destroy",()=>{h.remove()});return a.add(h),this.view.wake(1),h}onFrame(e){return this.hooks.add(e),this.view.wake(1),()=>{this.hooks.delete(e)}}frame(e){let t=this.viewport,s=this.place;t.width=e.width,t.height=e.height,t.margin=.5*e.height;for(let e of this.pins)A(e.tracker.rect,t,"none"===e.fit?"contain":e.fit,s),e.holder.visible=s.near,e.holder.position.set(s.x,s.y,e.z),"none"!==e.fit&&e.holder.scale.setScalar(Math.max(s.size,.001));let i=!1;for(let t of this.hooks)!0===t(e)&&(i=!0);return i}draw(){this.scene.children.some(e=>e.visible)&&(this.hub.env.apply(this.scene,this.environment,this.renderer),this.renderer.render(this.scene,this.camera))}},R=class{constructor(e,t){this.engine=e,this.models=new Map,this.shared=null,this.page=null,this.warned=!1,this.assets=new k(t),this.env=new L(this.assets,()=>{e.wake(1)})}three(){let e=this.assets.loaded;if(!e)throw new Error("three.js is not loaded yet");return e}load(){return this.assets.three().then(e=>e,e=>(this.cannotLoad(e),null))}renderer(){return this.shared??=this.load().then(e=>e?this.engine.renderer(e):null),this.shared}pageScene(){return this.page??=this.renderer().then(e=>e?((e,t)=>new O(this,t,()=>{this.page=null}))(0,e):null),this.page}cannotLoad(e){this.warned||(this.warned=!0,s.warn('three.js could not load, so 3D keeps its DOM. Map "three" and "three/addons/" in an import map, install three for your bundler, or pass it: umber.use(Three, { three: THREE }).',e))}dispose(){for(let e of[...this.models.values()])e.destroy();this.assets.dispose(),this.env.dispose()}},z={fit:"contain",fov:30,zoom:1,rotate:"",turn:0,spin:0,tilt:0,play:"",scrub:!1,environment:"room",scene:"box"},S=1e-4,D=class{constructor(e,s){this.hub=e,this.el=s,this.status="waiting",this.scene=null,this.camera=null,this.object=null,this.pivot=null,this.gltf=null,this.mixer=null,this.pin=null,this.progress=0,this.velocity=0,this.settle=t,this.hooks=new Set,this.instance=null,this.inner=null,this.box=null,this.renderer=null,this.actions=[],this.options=z,this.base=[0,0,0],this.spun=0,this.tilted=0,this.busy=!1,this.src="",this.gen=0,this.ready=this.waitReady(),this.frame={dt:0,time:0,progress:0,velocity:0,reducedMotion:!1,model:this}}waitReady(){return new Promise(e=>{this.settle=e})}onFrame(e){return this.hooks.add(e),this.wake(),()=>{this.hooks.delete(e)}}wake(){this.hub.engine.wake(1)}async setup(e){let t=++this.gen;this.status="loading",this.options=e.options;let s=await this.hub.renderer();if(!s)throw new Error("three.js or WebGL is not available");let i=this.el.getAttribute("data-umber-src")??"";if(!i)throw new Error('data-umber="model" needs data-umber-src="model.glb"');let r="none"!==this.options.environment&&this.hub.env.load(),n=await this.hub.assets.take(new URL(i,document.baseURI).href,s),o="page"===this.options.scene?await this.hub.pageScene():null;if(t!==this.gen)return void this.hub.assets.give(n);this.renderer=s,this.src=i;let a=this.place(n);if(o)this.pin=o.pin(a,this.el,{fit:this.fit()}),this.scene=o.scene,this.camera=o.camera;else{let e=this.hub.three();if(this.box??={scene:new e.Scene,camera:new e.PerspectiveCamera(this.options.fov,1,.01,100)},this.box.camera.fov=this.options.fov,this.box.scene.add(a),this.scene=this.box.scene,this.camera=this.box.camera,r){if(await r,s.resetState(),await this.hub.env.ready(s),t!==this.gen)return;s.resetState(),this.hub.env.apply(this.scene,"room",s)}if(await s.compileAsync(this.scene,this.camera),t!==this.gen)return}this.status="ready",this.settle(this)}fit(){return j(this.options.fit)?this.options.fit:"contain"}place(e){let t=this.hub.three(),s=e.root,i=(new t.Box3).setFromObject(s),r=i.getCenter(new t.Vector3),n=i.isEmpty()?.5:i.getSize(new t.Vector3).length()/2||.5,o=new t.Group;o.position.copy(r).negate(),o.add(s);let a=this.pivot??new t.Group;return this.inner&&a.remove(this.inner),a.add(o),a.scale.setScalar(this.options.zoom/(2*n)),function(e,t){let s=e.trim().split(/[\s,]+/);for(let e=0;e<3;e++){let i=Number.parseFloat(s[e]??"");t[e]=Number.isFinite(i)?P(i):0}}(this.options.rotate,this.base),this.pivot=a,this.inner=o,this.instance=e,this.object=s,this.gltf=e.asset.gltf,this.animations(t,s),a}animations(e,t){this.mixer?.stopAllAction(),this.actions=[];let s=this.gltf?.animations??[];this.mixer=s.length?new e.AnimationMixer(t):null;let{play:i,scrub:r}=this.options;if(this.mixer&&(i||r))for(let e of s){if(i&&"all"!==i&&e.name!==i)continue;let t=this.mixer.clipAction(e);t.play(),t.paused=r,this.actions.push(t)}}resize(e){let t=this.camera;if(!t||this.pin||e.rect.height<=0)return;t.aspect=e.rect.width/e.rect.height;let s=function(e,t,s,i="contain"){let r=P(t),n=2*Math.atan(Math.tan(r/2)*Math.max(s,1e-6)),o="cover"===i?Math.max(r,n):Math.min(r,n);return e/Math.sin(o/2)}(.5,t.fov,t.aspect,this.fit());t.position.set(0,0,s),t.near=s/100,t.far=100*s,t.updateProjectionMatrix()}render(e){let t=this.renderer,s=this.scene,i=this.camera;!t||!s||!i||"ready"!==this.status||((this.el.getAttribute("data-umber-src")??"")!==this.src&&this.reload(e),this.step(e),!this.pin&&(e.three(t),this.hub.env.apply(s,"none"===this.options.environment?"none":"room",t),t.render(s,i)))}step(e){let t=this.pivot;if(!t)return;let s=e.reducedMotion,i=s?0:e.frame?.dt??0;this.progress=function(e,t){let s=t+e.height;return s>0?Math.min(1,Math.max(0,(t-e.y)/s)):0}(e.rect,e.viewport.height),this.velocity=e.scrollVelocity;let r=this.turn(t,i,s);this.animate(i,s)&&(r=!0),this.hooked(e,i,s)&&(r=!0),r!==this.busy&&(this.busy=r,e.busy(r))}turn(e,t,s){let{turn:i,spin:r,tilt:n}=this.options,o=s?0:Math.max(-1,Math.min(1,this.velocity/1e3*n));this.tilted=s?0:((e,t,s,i)=>t+(e-t)*Math.exp(-6*Math.max(0,i)))(this.tilted,o,0,t),this.spun=(this.spun+r*t)%1;let[a,h,l]=this.base;return e.rotation.set(a+this.tilted,h+(i*this.progress+this.spun)*Math.PI*2,l),0!==r&&!s||Math.abs(this.tilted-o)>S||Math.abs(this.tilted)>S}animate(e,t){let s=this.mixer;if(!s||!this.actions.length)return!1;if(this.options.scrub){for(let e of this.actions)e.time=this.progress*e.getClip().duration;return s.update(0),!1}return!t&&(s.update(e),!0)}hooked(e,t,s){let i=!1,r=this.frame;r.dt=t,r.time=e.time,r.progress=this.progress,r.velocity=this.velocity,r.reducedMotion=s;for(let e of this.hooks)!0===e(r)&&(i=!0);return i}reload(e){let t=this.renderer,i=this.el.getAttribute("data-umber-src")??"";if(this.src=i,!t||!i)return;let r=this.gen;this.hub.assets.take(new URL(i,document.baseURI).href,t).then(t=>{if(r!==this.gen||i!==this.src)return void this.hub.assets.give(t);let s=this.instance;this.place(t),s&&this.hub.assets.give(s),e.wake(1)},e=>{s.warn(`data-umber-src="${i}" could not load; the model before it stays.`,e)})}teardown(){this.gen++,this.mixer?.stopAllAction(),this.pin?.remove(),this.pivot?.removeFromParent(),this.instance&&this.hub.assets.give(this.instance),this.instance=null,this.inner=null,this.pivot=null,this.object=null,this.mixer=null,this.pin=null,this.busy=!1,this.renderer=null,this.el.isConnected?(this.status="waiting",this.ready=this.waitReady()):this.destroy()}destroy(){"destroyed"!==this.status&&(this.instance&&this.teardown(),this.status="destroyed",this.scene=null,this.camera=null,this.box=null,this.hooks.clear(),this.hub.models.delete(this.el),this.settle(null),this.ready=Promise.resolve(null))}failed(){this.status="error",this.settle(null)}};function E(e,t){let s=e.models.get(t);return s||(s=new D(e,t),e.models.set(t,s)),s}var C=e=>"string"==typeof e?document.querySelector(e):e;var U={name:"three",version:"0.4.1",attributes:[],install:(...e)=>{let[t,i,r,n,o]=e;(function(e){e&&(s=e)})(o),(({engine:e,options:t})=>{!function(e,t={}){let s=new R(e,t);e.layer("model",function(e){return{options:z,async setup(t){let s=E(e,t.el);t.state.model=s;try{await s.setup(t)}catch(e){throw s.failed(),e}return()=>{s.teardown()}},render(e){e.state.model.render(e)},resize(e){e.state.model.resize(e)},animate:!1,passes:!0}}(s));let i={load:()=>s.load(),renderer:()=>s.renderer(),model(e){let t=C(e);return t?E(s,t):null},async scene(e,t={}){let i=C(e);if(!(i instanceof HTMLElement))return null;let r=await s.renderer();return r?function(e,t,s,i){let r=e.three(),n=i.scene??new r.Scene,o=!i.camera,a=i.camera??new r.PerspectiveCamera(i.fov??30,1,1,1e3),h=i.dispose??!i.scene,l={el:s,scene:n,camera:a,environment:i.environment??"room",view:null};return l.view=e.engine.view(s,{scene:n,camera:a,scissor:i.scissor,followOpacity:i.followOpacity,dpr:i.dpr,passes:i.passes??!0,animate:i.animate,resize(e){o&&T(a,e.width,e.height)},render(){e.env.apply(n,l.environment,t),t.render(n,a)}}),h&&l.view.on("destroy",()=>{M(n)}),l}(s,r,i,t):null},page:()=>s.pageScene(),lights(e,t=1){let i=s.assets.loaded;if(!i)return null;let r=new i.Group,n=new i.DirectionalLight(16777215,2.2*t);n.position.set(3,4,5);let o=new i.DirectionalLight(16777215,.8*t);return o.position.set(-4,1,2),r.add(n,o,new i.HemisphereLight(16777215,4210752,.9*t)),e.add(r),r},pxPerWorld:u,fitCamera:c,rectToWorld:w,worldToRect:g};e.three=i,e.on("restored",()=>{s.env.dispose()}),e.on("destroy",()=>{s.dispose(),e.three===i&&(e.three=void 0)})}(e,t)})({engine:t,options:i,keep:r,root:n})}};!function(e){let t,s=window;s.Umber?.use?s.Umber.use(e,t):(s.UmberModules??=[],s.UmberModules.push(t?[e,t]:e),s.__umber?.engine?.use?.(e,t))}(U)})();
|
package/dist/modules/three.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! Umber v0.
|
|
2
|
-
var e=()=>{},t={warn:e,error:e},s={GLTFLoader:()=>import("three/addons/loaders/GLTFLoader.js").then(e=>e.GLTFLoader),DRACOLoader:()=>import("three/addons/loaders/DRACOLoader.js").then(e=>e.DRACOLoader),KTX2Loader:()=>import("three/addons/loaders/KTX2Loader.js").then(e=>e.KTX2Loader),MeshoptDecoder:()=>import("three/addons/libs/meshopt_decoder.module.js").then(e=>e.MeshoptDecoder),RoomEnvironment:()=>import("three/addons/environments/RoomEnvironment.js").then(e=>e.RoomEnvironment),clone:()=>import("three/addons/utils/SkeletonUtils.js").then(e=>e.clone)};function i(e){let t=JSON.parse(e);return(e=>"object"==typeof e&&null!==e)(t)&&!Array.isArray(t)?t:null}var r=(e,t)=>`https://cdn.jsdelivr.net/npm/three@0.${e}.0/examples/jsm/libs/${t}/`;async function n(e,t){let s=new AbortController,i=setTimeout(()=>{s.abort()},t);try{let t=await fetch(e,{signal:s.signal});if(!t.ok)throw new Error(`${e}: HTTP ${t.status}`);return await t.arrayBuffer()}finally{clearTimeout(i)}}function o(e){e.traverse(e=>{let t=e;t.geometry?.dispose();let s=Array.isArray(t.material)?t.material:[t.material];for(let e of s)if(e&&"object"==typeof e){for(let t of Object.values(e)){let e=t;e?.isTexture&&e.dispose?.()}e.dispose?.()}})}var h=class{constructor(e){this.options=e,this.threeModule=null,this.loaded=null,this.addons=new Map,this.loader=null,this.decoders=new Map,this.files=new Map,this.workers=[]}three(){if(!this.threeModule){let e=this.options.three;this.threeModule="function"==typeof e?e():e?Promise.resolve(e):import("three"),this.threeModule.then(e=>{this.loaded=e},()=>{this.threeModule=null})}return this.threeModule}addon(e){let t=this.addons.get(e);if(!t){let i=this.options.addons?.[e];t=i?Promise.resolve(i):s[e](),this.addons.set(e,t),t.catch(()=>this.addons.delete(e))}return t}async take(e,t){let s=this.files.get(e);s||(s=this.parse(e,t),this.files.set(e,s),s.catch(()=>this.files.delete(e)));let i=await s;if(i.timer&&clearTimeout(i.timer),i.timer=0,i.users++,!i.taken)return i.taken=!0,{asset:i,root:i.gltf.scene};let r=i.needs.skinned?(await this.addon("clone"))(i.gltf.scene):i.gltf.scene.clone(!0);return{asset:i,root:r}}give(e){let{asset:t,root:s}=e;s.removeFromParent(),s===t.gltf.scene&&(t.taken=!1),!(--t.users>0)&&(t.timer=setTimeout(()=>{t.timer=0,!(t.users>0)&&(this.files.delete(t.url),o(t.gltf.scene))},this.options.keep??1e4))}async parse(e,t){let[s,r]=await Promise.all([n(e,3e4),this.gltfLoader()]),o=function(e){try{if(e.byteLength>=20){let t=new DataView(e);if(1179937895===t.getUint32(0,!0)){let s=t.getUint32(12,!0);return 1313821514!==t.getUint32(16,!0)||20+s>e.byteLength?null:i((new TextDecoder).decode(new Uint8Array(e,20,s)))}}return i((new TextDecoder).decode(e))}catch{return null}}(s);if(!o)throw new Error(`${e} is not a glTF file (.glb or .gltf)`);let h=function(e){let t=new Set([...e.extensionsUsed??[],...e.extensionsRequired??[]]);return{draco:t.has("KHR_draco_mesh_compression"),ktx2:t.has("KHR_texture_basisu"),meshopt:t.has("EXT_meshopt_compression")||t.has("KHR_meshopt_compression"),skinned:Array.isArray(e.skins)&&e.skins.length>0}}(o);return await this.decode(r,h,t),{url:e,gltf:await r.parseAsync(s,new URL(".",e).href),needs:h,users:0,taken:!1,timer:0}}gltfLoader(){return this.loader||(this.loader=this.addon("GLTFLoader").then(e=>new e),this.loader.catch(()=>{this.loader=null})),this.loader}async decode(e,t,s){let i=await this.three(),n=this.options.decoders??{},o=[];t.draco&&o.push(this.decoder("draco",async()=>{let t=new(await this.addon("DRACOLoader"));t.setDecoderPath(n.draco??r(i.REVISION,"draco/gltf")),this.workers.push(t),e.setDRACOLoader(t)})),t.ktx2&&o.push(this.decoder("ktx2",async()=>{let t=new(await this.addon("KTX2Loader"));t.setTranscoderPath(n.basis??r(i.REVISION,"basis")).detectSupport(s),this.workers.push(t),e.setKTX2Loader(t)})),t.meshopt&&o.push(this.decoder("meshopt",async()=>{e.setMeshoptDecoder(await this.addon("MeshoptDecoder"))})),await Promise.all(o)}decoder(e,t){let s=this.decoders.get(e);return s||(s=t(),this.decoders.set(e,s),s.catch(()=>this.decoders.delete(e))),s}dispose(){for(let e of this.files.values())e.then(e=>{e.timer&&clearTimeout(e.timer),o(e.gltf.scene)},()=>{});this.files.clear();for(let e of this.workers.splice(0))e.dispose()}},a=class{constructor(e,t){this.assets=e,this.wake=t,this.map=null,this.room=null,this.asked=!1}texture(e){if(this.map)return this.map;if(!this.room)return this.asked||(this.asked=!0,this.assets.addon("RoomEnvironment").then(e=>{this.room=e,this.wake()},()=>{})),null;let t=this.assets.loaded;if(!t)return null;let s=new t.PMREMGenerator(e),i=new this.room;return this.map=s.fromScene(i,.04).texture,i.dispose(),s.dispose(),this.map}apply(e,t,s){if("none"!==t){if("room"!==t)return void(e.environment=t);e.environment===this.map&&this.map||(e.environment=this.texture(s))}}restored(){this.map?.dispose(),this.map=null}dispose(){this.map?.dispose(),this.map=null}},l=e=>e*Math.PI/180,d=e=>"contain"===e||"cover"===e;function c(e,t,s,i){let r=t.margin;return i.x=e.x+e.width/2-t.width/2,i.y=t.height/2-(e.y+e.height/2),i.size="cover"===s?Math.max(e.width,e.height):Math.min(e.width,e.height),i.near=e.x+e.width>-r&&e.x<t.width+r&&e.y+e.height>-r&&e.y<t.height+r,i}function u(e,t,s){if(t<=0||s<=0)return;let i=((e,t)=>t/2/Math.tan(l(e)/2))(e.fov,s);e.aspect=t/s,e.position.set(0,0,i),e.near=i/50,e.far=50*i,e.updateProjectionMatrix()}var p=class{constructor(e,t,s){this.hub=e,this.renderer=t,this.el=function(){let e=document.createElement("div");return e.setAttribute("aria-hidden","true"),e.setAttribute("data-umber-page-scene",""),e.style.cssText="position:fixed;inset:0;pointer-events:none;margin:0;padding:0;border:0",document.body.append(e),e}(),this.environment="room",this.pins=new Set,this.hooks=new Set,this.place={x:0,y:0,size:0,near:!1},this.viewport={width:0,height:0,margin:0};let i=e.three(),r=this.scene=new i.Scene,n=this.camera=new i.PerspectiveCamera(30,1,1,1e3);this.view=e.engine.view(this.el,{scene:r,camera:n,scissor:!1,followOpacity:!1,passes:!0,resize(e){u(n,e.width,e.height)},animate:e=>this.frame(e),render:()=>{this.draw()}}),this.view.on("destroy",()=>{for(let e of[...this.pins])e.remove();this.hooks.clear(),this.el.remove(),s()})}pin(e,t,s={}){let i="string"==typeof t?document.querySelector(t):t;if(!i)return null;let r=new(this.hub.three().Group);r.add(e),this.scene.add(r);let n=this.hub.engine.track(i),o=s.fit??"none",h=this.pins,a={el:i,object:e,holder:r,tracker:n,fit:d(o)?o:"none",z:s.z??0,get progress(){return n.progress},remove(){h.delete(a)&&(l(),r.remove(e),r.removeFromParent(),n.destroy())}},l=n.on("destroy",()=>{a.remove()});return h.add(a),this.view.wake(1),a}onFrame(e){return this.hooks.add(e),this.view.wake(1),()=>{this.hooks.delete(e)}}frame(e){let t=this.viewport,s=this.place;t.width=e.width,t.height=e.height,t.margin=.5*e.height;for(let e of this.pins)c(e.tracker.rect,t,"none"===e.fit?"contain":e.fit,s),e.holder.visible=s.near,e.holder.position.set(s.x,s.y,e.z),"none"!==e.fit&&e.holder.scale.setScalar(Math.max(s.size,.001));let i=!1;for(let t of this.hooks)!0===t(e)&&(i=!0);return i}draw(){this.scene.children.some(e=>e.visible)&&(this.hub.env.apply(this.scene,this.environment,this.renderer),this.renderer.render(this.scene,this.camera))}},m=class{constructor(e,t){this.engine=e,this.models=new Map,this.shared=null,this.page=null,this.warned=!1,this.assets=new h(t),this.env=new a(this.assets,()=>{e.wake(1)})}three(){let e=this.assets.loaded;if(!e)throw new Error("three.js is not loaded yet");return e}load(){return this.assets.three().then(e=>e,e=>(this.cannotLoad(e),null))}renderer(){return this.shared??=this.load().then(e=>e?this.engine.renderer(e):null),this.shared}pageScene(){return this.page??=this.renderer().then(e=>e?((e,t)=>new p(this,t,()=>{this.page=null}))(0,e):null),this.page}cannotLoad(e){this.warned||(this.warned=!0,t.warn('three.js could not load, so 3D keeps its DOM. Map "three" and "three/addons/" in an import map, install three for your bundler, or pass it: umber.use(Three, { three: THREE }).',e))}dispose(){for(let e of[...this.models.values()])e.destroy();this.assets.dispose(),this.env.dispose()}},f={fit:"contain",fov:30,zoom:1,rotate:"",turn:0,spin:0,tilt:0,play:"",scrub:!1,environment:"room",scene:"box"},w=1e-4,g=class{constructor(t,s){this.hub=t,this.el=s,this.status="waiting",this.scene=null,this.camera=null,this.object=null,this.pivot=null,this.gltf=null,this.mixer=null,this.pin=null,this.progress=0,this.velocity=0,this.settle=e,this.hooks=new Set,this.instance=null,this.inner=null,this.box=null,this.renderer=null,this.actions=[],this.options=f,this.base=[0,0,0],this.spun=0,this.tilted=0,this.busy=!1,this.src="",this.gen=0,this.ready=this.waitReady(),this.frame={dt:0,time:0,progress:0,velocity:0,reducedMotion:!1,model:this}}waitReady(){return new Promise(e=>{this.settle=e})}onFrame(e){return this.hooks.add(e),this.wake(),()=>{this.hooks.delete(e)}}wake(){this.hub.engine.wake(1)}async setup(e){let t=++this.gen;this.status="loading",this.options=e.options;let s=await this.hub.renderer();if(!s)throw new Error("three.js or WebGL is not available");let i=this.el.getAttribute("data-umber-src")??"";if(!i)throw new Error('data-umber="model" needs data-umber-src="model.glb"');let r=await this.hub.assets.take(new URL(i,document.baseURI).href,s),n="page"===this.options.scene?await this.hub.pageScene():null;if(t!==this.gen)return void this.hub.assets.give(r);this.renderer=s,this.src=i;let o=this.place(r);if(n)this.pin=n.pin(o,this.el,{fit:this.fit()}),this.scene=n.scene,this.camera=n.camera;else{let e=this.hub.three();this.box??={scene:new e.Scene,camera:new e.PerspectiveCamera(this.options.fov,1,.01,100)},this.box.camera.fov=this.options.fov,this.box.scene.add(o),this.scene=this.box.scene,this.camera=this.box.camera}this.status="ready",this.settle(this)}fit(){return d(this.options.fit)?this.options.fit:"contain"}place(e){let t=this.hub.three(),s=e.root,i=(new t.Box3).setFromObject(s),r=i.getCenter(new t.Vector3),n=i.isEmpty()?.5:i.getSize(new t.Vector3).length()/2||.5,o=new t.Group;o.position.copy(r).negate(),o.add(s);let h=this.pivot??new t.Group;return this.inner&&h.remove(this.inner),h.add(o),h.scale.setScalar(this.options.zoom/(2*n)),function(e,t){let s=e.trim().split(/[\s,]+/);for(let e=0;e<3;e++){let i=Number.parseFloat(s[e]??"");t[e]=Number.isFinite(i)?l(i):0}}(this.options.rotate,this.base),this.pivot=h,this.inner=o,this.instance=e,this.object=s,this.gltf=e.asset.gltf,this.animations(t,s),h}animations(e,t){this.mixer?.stopAllAction(),this.actions=[];let s=this.gltf?.animations??[];this.mixer=s.length?new e.AnimationMixer(t):null;let{play:i,scrub:r}=this.options;if(this.mixer&&(i||r))for(let e of s){if(i&&"all"!==i&&e.name!==i)continue;let t=this.mixer.clipAction(e);t.play(),t.paused=r,this.actions.push(t)}}resize(e){let t=this.camera;if(!t||this.pin||e.rect.height<=0)return;t.aspect=e.rect.width/e.rect.height;let s=function(e,t,s,i="contain"){let r=l(t),n=2*Math.atan(Math.tan(r/2)*Math.max(s,1e-6)),o="cover"===i?Math.max(r,n):Math.min(r,n);return e/Math.sin(o/2)}(.5,t.fov,t.aspect,this.fit());t.position.set(0,0,s),t.near=s/100,t.far=100*s,t.updateProjectionMatrix()}render(e){let t=this.renderer,s=this.scene,i=this.camera;!t||!s||!i||"ready"!==this.status||((this.el.getAttribute("data-umber-src")??"")!==this.src&&this.reload(e),this.step(e),!this.pin&&(e.three(t),this.hub.env.apply(s,"none"===this.options.environment?"none":"room",t),t.render(s,i)))}step(e){let t=this.pivot;if(!t)return;let s=e.reducedMotion,i=s?0:e.frame?.dt??0;this.progress=function(e,t){let s=t+e.height;return s>0?Math.min(1,Math.max(0,(t-e.y)/s)):0}(e.rect,e.viewport.height),this.velocity=e.scrollVelocity;let r=this.turn(t,i,s);this.animate(i,s)&&(r=!0),this.hooked(e,i,s)&&(r=!0),r!==this.busy&&(this.busy=r,e.busy(r))}turn(e,t,s){let{turn:i,spin:r,tilt:n}=this.options,o=s?0:Math.max(-1,Math.min(1,this.velocity/1e3*n));this.tilted=s?0:((e,t,s,i)=>t+(e-t)*Math.exp(-6*Math.max(0,i)))(this.tilted,o,0,t),this.spun=(this.spun+r*t)%1;let[h,a,l]=this.base;return e.rotation.set(h+this.tilted,a+(i*this.progress+this.spun)*Math.PI*2,l),0!==r&&!s||Math.abs(this.tilted-o)>w||Math.abs(this.tilted)>w}animate(e,t){let s=this.mixer;if(!s||!this.actions.length)return!1;if(this.options.scrub){for(let e of this.actions)e.time=this.progress*e.getClip().duration;return s.update(0),!1}return!t&&(s.update(e),!0)}hooked(e,t,s){let i=!1,r=this.frame;r.dt=t,r.time=e.time,r.progress=this.progress,r.velocity=this.velocity,r.reducedMotion=s;for(let e of this.hooks)!0===e(r)&&(i=!0);return i}reload(e){let s=this.renderer,i=this.el.getAttribute("data-umber-src")??"";if(this.src=i,!s||!i)return;let r=this.gen;this.hub.assets.take(new URL(i,document.baseURI).href,s).then(t=>{if(r!==this.gen||i!==this.src)return void this.hub.assets.give(t);let s=this.instance;this.place(t),s&&this.hub.assets.give(s),e.wake(1)},e=>{t.warn(`data-umber-src="${i}" could not load; the model before it stays.`,e)})}teardown(){this.gen++,this.mixer?.stopAllAction(),this.pin?.remove(),this.pivot?.removeFromParent(),this.instance&&this.hub.assets.give(this.instance),this.instance=null,this.inner=null,this.pivot=null,this.object=null,this.mixer=null,this.pin=null,this.busy=!1,this.renderer=null,this.el.isConnected?(this.status="waiting",this.ready=this.waitReady()):this.destroy()}destroy(){"destroyed"!==this.status&&(this.instance&&this.teardown(),this.status="destroyed",this.scene=null,this.camera=null,this.box=null,this.hooks.clear(),this.hub.models.delete(this.el),this.settle(null),this.ready=Promise.resolve(null))}failed(){this.status="error",this.settle(null)}};function v(e,t){let s=e.models.get(t);return s||(s=new g(e,t),e.models.set(t,s)),s}var y=e=>"string"==typeof e?document.querySelector(e):e;function b(e,t={}){let s=new m(e,t);e.layer("model",function(e){return{options:f,async setup(t){let s=v(e,t.el);t.state.model=s;try{await s.setup(t)}catch(e){throw s.failed(),e}return()=>{s.teardown()}},render(e){e.state.model.render(e)},resize(e){e.state.model.resize(e)},animate:!1,passes:!0}}(s));let i={load:()=>s.load(),renderer:()=>s.renderer(),model(e){let t=y(e);return t?v(s,t):null},async scene(e,t={}){let i=y(e);if(!(i instanceof HTMLElement))return null;let r=await s.renderer();return r?function(e,t,s,i){let r=e.three(),n=i.scene??new r.Scene,h=!i.camera,a=i.camera??new r.PerspectiveCamera(i.fov??30,1,1,1e3),l=i.dispose??!i.scene,d={el:s,scene:n,camera:a,environment:i.environment??"room",view:null};return d.view=e.engine.view(s,{scene:n,camera:a,scissor:i.scissor,followOpacity:i.followOpacity,dpr:i.dpr,passes:i.passes??!0,animate:i.animate,resize(e){h&&u(a,e.width,e.height)},render(){e.env.apply(n,d.environment,t),t.render(n,a)}}),l&&d.view.on("destroy",()=>{o(n)}),d}(s,r,i,t):null},page:()=>s.pageScene(),lights(e,t=1){let i=s.assets.loaded;if(!i)return null;let r=new i.Group,n=new i.DirectionalLight(16777215,2.2*t);n.position.set(3,4,5);let o=new i.DirectionalLight(16777215,.8*t);return o.position.set(-4,1,2),r.add(n,o,new i.HemisphereLight(16777215,4210752,.9*t)),e.add(r),r}};return e.three=i,e.on("restored",()=>{s.env.restored()}),e.on("destroy",()=>{s.dispose(),e.three===i&&(e.three=void 0)}),i}var k,x={name:"three",version:"0.3.0",attributes:[],install:(k=({engine:e,options:t})=>{b(e,t)},(...e)=>{let[s,i,r,n,o]=e;(function(e){e&&(t=e)})(o),k({engine:s,options:i,keep:r,root:n})})},M=x;export{f as MODEL_OPTIONS,x as Three,b as addThree,M as default};
|
|
1
|
+
/*! Umber v0.4.1 | (c) Ravi Klaassens | UNLICENSED */
|
|
2
|
+
var e=()=>{},t={warn:e,error:e},s=(e,t)=>e[t]??NaN,i=e=>e.left??e.x??0,r=e=>e.top??e.y??0;function n(){return{left:0,top:0,width:"number"==typeof innerWidth?innerWidth:1,height:"number"==typeof innerHeight?innerHeight:1}}function o(e,t){let[i,r,n]=t,o=s(e,3)*i+s(e,7)*r+s(e,11)*n+s(e,15)||1;return t[0]=(s(e,0)*i+s(e,4)*r+s(e,8)*n+s(e,12))/o,t[1]=(s(e,1)*i+s(e,5)*r+s(e,9)*n+s(e,13))/o,t[2]=(s(e,2)*i+s(e,6)*r+s(e,10)*n+s(e,14))/o,o}var a=[0,0,0],h=[0,0,0];function l(e,[t,s],i,r){a[0]=t,a[1]=s,a[2]=-1,o(e.projectionMatrixInverse.elements,a),o(e.matrixWorld.elements,a),h[0]=t,h[1]=s,h[2]=1,o(e.projectionMatrixInverse.elements,h),o(e.matrixWorld.elements,h);let n=h[2]-a[2],l=Math.abs(n)<1e-12?0:(i-a[2])/n;return r[0]=a[0]+(h[0]-a[0])*l,r[1]=a[1]+(h[1]-a[1])*l,r[2]=i,r}function d(e,t,i){let r=i??n().height,o=e.zoom&&Number.isFinite(e.zoom)?e.zoom:1;if(e.isOrthographicCamera)return r*o/Math.max(1e-9,(e.top??1)-(e.bottom??-1));let a=Math.abs(t??function(e){return e.updateMatrixWorld?.(),s(e.matrixWorld.elements,14)}(e)),h=(e.fov??50)*Math.PI/180;return r*o/Math.max(1e-9,2*a*Math.tan(h/2))}function u(e,t,s=1){let i=Math.max(1e-6,t.width)/s,r=Math.max(1e-6,t.height)/s;if(e.isOrthographicCamera)e.left=-i/2,e.right=i/2,e.top=r/2,e.bottom=-r/2,e.zoom=1;else{let t=(e.fov??50)*Math.PI/180,s=r/2/Math.tan(t/2);e.aspect=i/r,e.zoom=1,e.position&&(e.position.z=s),"number"==typeof e.far&&e.far<2*s&&(e.far=2*s)}return e.updateProjectionMatrix?.(),e.updateMatrixWorld?.(!0),e}var c=[0,0,0],m=[0,0,0],p=[0,0,0];function f(e,t,s,o={}){let a=o.frame??n(),h=o.z??0;t.updateMatrixWorld?.();let d=Math.max(a.width,1e-6),u=Math.max(a.height,1e-6),f=(e,t)=>[(e-i(a))/d*2-1,1-(t-r(a))/u*2],w=i(e),g=r(e);l(t,f(w,g),h,c),l(t,f(w+e.width,g+e.height),h,m),l(t,f(w+e.width/2,g+e.height/2),h,p);let y={x:p[0],y:p[1],z:h,width:Math.abs(m[0]-c[0]),height:Math.abs(c[1]-m[1])};return s&&(s.x=y.x,s.y=y.y,s.z=y.z),y}function w(e,t,s=n()){t.updateMatrixWorld?.(),h[0]=e.x,h[1]=e.y,h[2]=e.z,o(t.matrixWorldInverse.elements,h);let a=o(t.projectionMatrix.elements,h),l=!!t.isOrthographicCamera||a>0;return{x:i(s)+(h[0]+1)/2*s.width,y:r(s)+(1-h[1])/2*s.height,visible:l&&Math.abs(h[0])<=1&&Math.abs(h[1])<=1&&h[2]>=-1&&h[2]<=1}}var g={GLTFLoader:()=>import("three/addons/loaders/GLTFLoader.js").then(e=>e.GLTFLoader),DRACOLoader:()=>import("three/addons/loaders/DRACOLoader.js").then(e=>e.DRACOLoader),KTX2Loader:()=>import("three/addons/loaders/KTX2Loader.js").then(e=>e.KTX2Loader),MeshoptDecoder:()=>import("three/addons/libs/meshopt_decoder.module.js").then(e=>e.MeshoptDecoder),RoomEnvironment:()=>import("three/addons/environments/RoomEnvironment.js").then(e=>e.RoomEnvironment),clone:()=>import("three/addons/utils/SkeletonUtils.js").then(e=>e.clone)};function y(e){let t=JSON.parse(e);return(e=>"object"==typeof e&&null!==e)(t)&&!Array.isArray(t)?t:null}var v=(e,t)=>`https://cdn.jsdelivr.net/npm/three@0.${e}.0/examples/jsm/libs/${t}/`;async function b(e,t){let s=new AbortController,i=setTimeout(()=>{s.abort()},t);try{let t=await fetch(e,{signal:s.signal});if(!t.ok)throw new Error(`${e}: HTTP ${t.status}`);return await t.arrayBuffer()}finally{clearTimeout(i)}}function x(e){e.traverse(e=>{let t=e;t.geometry?.dispose();let s=Array.isArray(t.material)?t.material:[t.material];for(let e of s)if(e&&"object"==typeof e){for(let t of Object.values(e)){let e=t;e?.isTexture&&e.dispose?.()}e.dispose?.()}})}var M=class{constructor(e){this.options=e,this.threeModule=null,this.loaded=null,this.addons=new Map,this.loader=null,this.decoders=new Map,this.files=new Map,this.workers=[]}three(){if(!this.threeModule){let e=this.options.three;this.threeModule="function"==typeof e?e():e?Promise.resolve(e):import("three"),this.threeModule.then(e=>{this.loaded=e},()=>{this.threeModule=null})}return this.threeModule}addon(e){let t=this.addons.get(e);if(!t){let s=this.options.addons?.[e];t=s?Promise.resolve(s):g[e](),this.addons.set(e,t),t.catch(()=>this.addons.delete(e))}return t}async take(e,t){let s=this.files.get(e);s||(s=this.parse(e,t),this.files.set(e,s),s.catch(()=>this.files.delete(e)));let i=await s;if(i.timer&&clearTimeout(i.timer),i.timer=0,i.users++,!i.taken)return i.taken=!0,{asset:i,root:i.gltf.scene};let r=i.needs.skinned?(await this.addon("clone"))(i.gltf.scene):i.gltf.scene.clone(!0);return{asset:i,root:r}}give(e){let{asset:t,root:s}=e;s.removeFromParent(),s===t.gltf.scene&&(t.taken=!1),!(--t.users>0)&&(t.timer=setTimeout(()=>{t.timer=0,!(t.users>0)&&(this.files.delete(t.url),x(t.gltf.scene))},this.options.keep??1e4))}async parse(e,t){let[s,i]=await Promise.all([b(e,3e4),this.gltfLoader()]),r=function(e){try{if(e.byteLength>=20){let t=new DataView(e);if(1179937895===t.getUint32(0,!0)){let s=t.getUint32(12,!0);return 1313821514!==t.getUint32(16,!0)||20+s>e.byteLength?null:y((new TextDecoder).decode(new Uint8Array(e,20,s)))}}return y((new TextDecoder).decode(e))}catch{return null}}(s);if(!r)throw new Error(`${e} is not a glTF file (.glb or .gltf)`);let n=function(e){let t=new Set([...e.extensionsUsed??[],...e.extensionsRequired??[]]);return{draco:t.has("KHR_draco_mesh_compression"),ktx2:t.has("KHR_texture_basisu"),meshopt:t.has("EXT_meshopt_compression")||t.has("KHR_meshopt_compression"),skinned:Array.isArray(e.skins)&&e.skins.length>0}}(r);return await this.decode(i,n,t),{url:e,gltf:await i.parseAsync(s,new URL(".",e).href),needs:n,users:0,taken:!1,timer:0}}gltfLoader(){return this.loader||(this.loader=this.addon("GLTFLoader").then(e=>new e),this.loader.catch(()=>{this.loader=null})),this.loader}async decode(e,t,s){let i=await this.three(),r=this.options.decoders??{},n=[];t.draco&&n.push(this.decoder("draco",async()=>{let t=new(await this.addon("DRACOLoader"));t.setDecoderPath(r.draco??v(i.REVISION,"draco/gltf")),this.workers.push(t),e.setDRACOLoader(t)})),t.ktx2&&n.push(this.decoder("ktx2",async()=>{let t=new(await this.addon("KTX2Loader"));t.setTranscoderPath(r.basis??v(i.REVISION,"basis")).detectSupport(s),this.workers.push(t),e.setKTX2Loader(t)})),t.meshopt&&n.push(this.decoder("meshopt",async()=>{e.setMeshoptDecoder(await this.addon("MeshoptDecoder"))})),await Promise.all(n)}decoder(e,t){let s=this.decoders.get(e);return s||(s=t(),this.decoders.set(e,s),s.catch(()=>this.decoders.delete(e))),s}dispose(){for(let e of this.files.values())e.then(e=>{e.timer&&clearTimeout(e.timer),x(e.gltf.scene)},()=>{});this.files.clear();for(let e of this.workers.splice(0))e.dispose()}},k=class{constructor(e,t){this.assets=e,this.wake=t,this.map=null,this.room=null,this.asked=null,this.linking=null}load(){return this.asked??=this.assets.addon("RoomEnvironment").then(e=>{this.room=e,this.wake()},e),this.asked}texture(e){if(this.map)return this.map;if(!this.room)return this.load(),null;let t=this.assets.loaded;if(!t)return null;let s=this.linking??=this.link(t,new this.room,e);return s.linked?(this.map=s.pmrem.fromScene(s.room,.04).texture,this.drop(),this.map):null}async ready(e){this.texture(e),await(this.linking?.ready)}link(e,t,s){let i=new e.PMREMGenerator(s),r=[],n=[],o=s.render;s.render=(t,i)=>{let{material:o,geometry:a}=t;if(o&&!Array.isArray(o)){let s=o.clone();r.push(s),t=new e.Mesh(a,s)}n.push(s.compileAsync(t,i))};try{i.fromScene(t,.04).dispose()}finally{s.render=o}let a={pmrem:i,room:t,kept:r,ready:Promise.allSettled(n).then(()=>{a.linked=!0,this.wake()})};return a}drop(){let e=this.linking;this.linking=null,e?.ready.then(()=>{e.room.dispose(),e.pmrem.dispose();for(let t of e.kept)t.dispose()})}apply(e,t,s){if("none"!==t){if("room"!==t)return void(e.environment=t);e.environment===this.map&&this.map||(e.environment=this.texture(s))}}dispose(){this.map?.dispose(),this.map=null,this.drop()}},L=e=>e*Math.PI/180,T=e=>"contain"===e||"cover"===e;function A(e,t,s,i){let r=t.margin;return i.x=e.x+e.width/2-t.width/2,i.y=t.height/2-(e.y+e.height/2),i.size="cover"===s?Math.max(e.width,e.height):Math.min(e.width,e.height),i.near=e.x+e.width>-r&&e.x<t.width+r&&e.y+e.height>-r&&e.y<t.height+r,i}function P(e,t,s){if(t<=0||s<=0)return;let i=((e,t)=>t/2/Math.tan(L(e)/2))(e.fov,s);e.aspect=t/s,e.position.set(0,0,i),e.near=i/50,e.far=50*i,e.updateProjectionMatrix()}var R=class{constructor(e,t,s){this.hub=e,this.renderer=t,this.el=function(){let e=document.createElement("div");return e.setAttribute("aria-hidden","true"),e.setAttribute("data-umber-page-scene",""),e.style.cssText="position:fixed;inset:0;pointer-events:none;margin:0;padding:0;border:0",document.body.append(e),e}(),this.environment="room",this.pins=new Set,this.hooks=new Set,this.place={x:0,y:0,size:0,near:!1},this.viewport={width:0,height:0,margin:0};let i=e.three(),r=this.scene=new i.Scene,n=this.camera=new i.PerspectiveCamera(30,1,1,1e3);this.view=e.engine.view(this.el,{scene:r,camera:n,scissor:!1,followOpacity:!1,passes:!0,resize(e){P(n,e.width,e.height)},animate:e=>this.frame(e),render:()=>{this.draw()}}),this.view.on("destroy",()=>{for(let e of[...this.pins])e.remove();this.hooks.clear(),this.el.remove(),s()})}pin(e,t,s={}){let i="string"==typeof t?document.querySelector(t):t;if(!i)return null;let r=new(this.hub.three().Group);r.add(e),this.scene.add(r);let n=this.hub.engine.track(i),o=s.fit??"none",a=this.pins,h={el:i,object:e,holder:r,tracker:n,fit:T(o)?o:"none",z:s.z??0,get progress(){return n.progress},remove(){a.delete(h)&&(l(),r.remove(e),r.removeFromParent(),n.destroy())}},l=n.on("destroy",()=>{h.remove()});return a.add(h),this.view.wake(1),h}onFrame(e){return this.hooks.add(e),this.view.wake(1),()=>{this.hooks.delete(e)}}frame(e){let t=this.viewport,s=this.place;t.width=e.width,t.height=e.height,t.margin=.5*e.height;for(let e of this.pins)A(e.tracker.rect,t,"none"===e.fit?"contain":e.fit,s),e.holder.visible=s.near,e.holder.position.set(s.x,s.y,e.z),"none"!==e.fit&&e.holder.scale.setScalar(Math.max(s.size,.001));let i=!1;for(let t of this.hooks)!0===t(e)&&(i=!0);return i}draw(){this.scene.children.some(e=>e.visible)&&(this.hub.env.apply(this.scene,this.environment,this.renderer),this.renderer.render(this.scene,this.camera))}},S=class{constructor(e,t){this.engine=e,this.models=new Map,this.shared=null,this.page=null,this.warned=!1,this.assets=new M(t),this.env=new k(this.assets,()=>{e.wake(1)})}three(){let e=this.assets.loaded;if(!e)throw new Error("three.js is not loaded yet");return e}load(){return this.assets.three().then(e=>e,e=>(this.cannotLoad(e),null))}renderer(){return this.shared??=this.load().then(e=>e?this.engine.renderer(e):null),this.shared}pageScene(){return this.page??=this.renderer().then(e=>e?((e,t)=>new R(this,t,()=>{this.page=null}))(0,e):null),this.page}cannotLoad(e){this.warned||(this.warned=!0,t.warn('three.js could not load, so 3D keeps its DOM. Map "three" and "three/addons/" in an import map, install three for your bundler, or pass it: umber.use(Three, { three: THREE }).',e))}dispose(){for(let e of[...this.models.values()])e.destroy();this.assets.dispose(),this.env.dispose()}},j={fit:"contain",fov:30,zoom:1,rotate:"",turn:0,spin:0,tilt:0,play:"",scrub:!1,environment:"room",scene:"box"},z=1e-4,O=class{constructor(t,s){this.hub=t,this.el=s,this.status="waiting",this.scene=null,this.camera=null,this.object=null,this.pivot=null,this.gltf=null,this.mixer=null,this.pin=null,this.progress=0,this.velocity=0,this.settle=e,this.hooks=new Set,this.instance=null,this.inner=null,this.box=null,this.renderer=null,this.actions=[],this.options=j,this.base=[0,0,0],this.spun=0,this.tilted=0,this.busy=!1,this.src="",this.gen=0,this.ready=this.waitReady(),this.frame={dt:0,time:0,progress:0,velocity:0,reducedMotion:!1,model:this}}waitReady(){return new Promise(e=>{this.settle=e})}onFrame(e){return this.hooks.add(e),this.wake(),()=>{this.hooks.delete(e)}}wake(){this.hub.engine.wake(1)}async setup(e){let t=++this.gen;this.status="loading",this.options=e.options;let s=await this.hub.renderer();if(!s)throw new Error("three.js or WebGL is not available");let i=this.el.getAttribute("data-umber-src")??"";if(!i)throw new Error('data-umber="model" needs data-umber-src="model.glb"');let r="none"!==this.options.environment&&this.hub.env.load(),n=await this.hub.assets.take(new URL(i,document.baseURI).href,s),o="page"===this.options.scene?await this.hub.pageScene():null;if(t!==this.gen)return void this.hub.assets.give(n);this.renderer=s,this.src=i;let a=this.place(n);if(o)this.pin=o.pin(a,this.el,{fit:this.fit()}),this.scene=o.scene,this.camera=o.camera;else{let e=this.hub.three();if(this.box??={scene:new e.Scene,camera:new e.PerspectiveCamera(this.options.fov,1,.01,100)},this.box.camera.fov=this.options.fov,this.box.scene.add(a),this.scene=this.box.scene,this.camera=this.box.camera,r){if(await r,s.resetState(),await this.hub.env.ready(s),t!==this.gen)return;s.resetState(),this.hub.env.apply(this.scene,"room",s)}if(await s.compileAsync(this.scene,this.camera),t!==this.gen)return}this.status="ready",this.settle(this)}fit(){return T(this.options.fit)?this.options.fit:"contain"}place(e){let t=this.hub.three(),s=e.root,i=(new t.Box3).setFromObject(s),r=i.getCenter(new t.Vector3),n=i.isEmpty()?.5:i.getSize(new t.Vector3).length()/2||.5,o=new t.Group;o.position.copy(r).negate(),o.add(s);let a=this.pivot??new t.Group;return this.inner&&a.remove(this.inner),a.add(o),a.scale.setScalar(this.options.zoom/(2*n)),function(e,t){let s=e.trim().split(/[\s,]+/);for(let e=0;e<3;e++){let i=Number.parseFloat(s[e]??"");t[e]=Number.isFinite(i)?L(i):0}}(this.options.rotate,this.base),this.pivot=a,this.inner=o,this.instance=e,this.object=s,this.gltf=e.asset.gltf,this.animations(t,s),a}animations(e,t){this.mixer?.stopAllAction(),this.actions=[];let s=this.gltf?.animations??[];this.mixer=s.length?new e.AnimationMixer(t):null;let{play:i,scrub:r}=this.options;if(this.mixer&&(i||r))for(let e of s){if(i&&"all"!==i&&e.name!==i)continue;let t=this.mixer.clipAction(e);t.play(),t.paused=r,this.actions.push(t)}}resize(e){let t=this.camera;if(!t||this.pin||e.rect.height<=0)return;t.aspect=e.rect.width/e.rect.height;let s=function(e,t,s,i="contain"){let r=L(t),n=2*Math.atan(Math.tan(r/2)*Math.max(s,1e-6)),o="cover"===i?Math.max(r,n):Math.min(r,n);return e/Math.sin(o/2)}(.5,t.fov,t.aspect,this.fit());t.position.set(0,0,s),t.near=s/100,t.far=100*s,t.updateProjectionMatrix()}render(e){let t=this.renderer,s=this.scene,i=this.camera;!t||!s||!i||"ready"!==this.status||((this.el.getAttribute("data-umber-src")??"")!==this.src&&this.reload(e),this.step(e),!this.pin&&(e.three(t),this.hub.env.apply(s,"none"===this.options.environment?"none":"room",t),t.render(s,i)))}step(e){let t=this.pivot;if(!t)return;let s=e.reducedMotion,i=s?0:e.frame?.dt??0;this.progress=function(e,t){let s=t+e.height;return s>0?Math.min(1,Math.max(0,(t-e.y)/s)):0}(e.rect,e.viewport.height),this.velocity=e.scrollVelocity;let r=this.turn(t,i,s);this.animate(i,s)&&(r=!0),this.hooked(e,i,s)&&(r=!0),r!==this.busy&&(this.busy=r,e.busy(r))}turn(e,t,s){let{turn:i,spin:r,tilt:n}=this.options,o=s?0:Math.max(-1,Math.min(1,this.velocity/1e3*n));this.tilted=s?0:((e,t,s,i)=>t+(e-t)*Math.exp(-6*Math.max(0,i)))(this.tilted,o,0,t),this.spun=(this.spun+r*t)%1;let[a,h,l]=this.base;return e.rotation.set(a+this.tilted,h+(i*this.progress+this.spun)*Math.PI*2,l),0!==r&&!s||Math.abs(this.tilted-o)>z||Math.abs(this.tilted)>z}animate(e,t){let s=this.mixer;if(!s||!this.actions.length)return!1;if(this.options.scrub){for(let e of this.actions)e.time=this.progress*e.getClip().duration;return s.update(0),!1}return!t&&(s.update(e),!0)}hooked(e,t,s){let i=!1,r=this.frame;r.dt=t,r.time=e.time,r.progress=this.progress,r.velocity=this.velocity,r.reducedMotion=s;for(let e of this.hooks)!0===e(r)&&(i=!0);return i}reload(e){let s=this.renderer,i=this.el.getAttribute("data-umber-src")??"";if(this.src=i,!s||!i)return;let r=this.gen;this.hub.assets.take(new URL(i,document.baseURI).href,s).then(t=>{if(r!==this.gen||i!==this.src)return void this.hub.assets.give(t);let s=this.instance;this.place(t),s&&this.hub.assets.give(s),e.wake(1)},e=>{t.warn(`data-umber-src="${i}" could not load; the model before it stays.`,e)})}teardown(){this.gen++,this.mixer?.stopAllAction(),this.pin?.remove(),this.pivot?.removeFromParent(),this.instance&&this.hub.assets.give(this.instance),this.instance=null,this.inner=null,this.pivot=null,this.object=null,this.mixer=null,this.pin=null,this.busy=!1,this.renderer=null,this.el.isConnected?(this.status="waiting",this.ready=this.waitReady()):this.destroy()}destroy(){"destroyed"!==this.status&&(this.instance&&this.teardown(),this.status="destroyed",this.scene=null,this.camera=null,this.box=null,this.hooks.clear(),this.hub.models.delete(this.el),this.settle(null),this.ready=Promise.resolve(null))}failed(){this.status="error",this.settle(null)}};function E(e,t){let s=e.models.get(t);return s||(s=new O(e,t),e.models.set(t,s)),s}var D=e=>"string"==typeof e?document.querySelector(e):e;function C(e,t={}){let s=new S(e,t);e.layer("model",function(e){return{options:j,async setup(t){let s=E(e,t.el);t.state.model=s;try{await s.setup(t)}catch(e){throw s.failed(),e}return()=>{s.teardown()}},render(e){e.state.model.render(e)},resize(e){e.state.model.resize(e)},animate:!1,passes:!0}}(s));let i={load:()=>s.load(),renderer:()=>s.renderer(),model(e){let t=D(e);return t?E(s,t):null},async scene(e,t={}){let i=D(e);if(!(i instanceof HTMLElement))return null;let r=await s.renderer();return r?function(e,t,s,i){let r=e.three(),n=i.scene??new r.Scene,o=!i.camera,a=i.camera??new r.PerspectiveCamera(i.fov??30,1,1,1e3),h=i.dispose??!i.scene,l={el:s,scene:n,camera:a,environment:i.environment??"room",view:null};return l.view=e.engine.view(s,{scene:n,camera:a,scissor:i.scissor,followOpacity:i.followOpacity,dpr:i.dpr,passes:i.passes??!0,animate:i.animate,resize(e){o&&P(a,e.width,e.height)},render(){e.env.apply(n,l.environment,t),t.render(n,a)}}),h&&l.view.on("destroy",()=>{x(n)}),l}(s,r,i,t):null},page:()=>s.pageScene(),lights(e,t=1){let i=s.assets.loaded;if(!i)return null;let r=new i.Group,n=new i.DirectionalLight(16777215,2.2*t);n.position.set(3,4,5);let o=new i.DirectionalLight(16777215,.8*t);return o.position.set(-4,1,2),r.add(n,o,new i.HemisphereLight(16777215,4210752,.9*t)),e.add(r),r},pxPerWorld:d,fitCamera:u,rectToWorld:f,worldToRect:w};return e.three=i,e.on("restored",()=>{s.env.dispose()}),e.on("destroy",()=>{s.dispose(),e.three===i&&(e.three=void 0)}),i}var F,I={name:"three",version:"0.4.1",attributes:[],install:(F=({engine:e,options:t})=>{C(e,t)},(...e)=>{let[s,i,r,n,o]=e;(function(e){e&&(t=e)})(o),F({engine:s,options:i,keep:r,root:n})})},W=I;export{j as MODEL_OPTIONS,I as Three,C as addThree,W as default};
|
package/dist/node/assets.mjs
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
/*! Umber v0.
|
|
1
|
+
/*! Umber v0.4.1 asset tool | (c) Ravi Klaassens | UNLICENSED */
|
|
2
2
|
import {
|
|
3
3
|
loadNative,
|
|
4
|
+
pageWriter,
|
|
4
5
|
prepareSite
|
|
5
|
-
} from "./shared-
|
|
6
|
+
} from "./shared-NFSQ5J4B.mjs";
|
|
6
7
|
export {
|
|
7
8
|
loadNative,
|
|
9
|
+
pageWriter,
|
|
8
10
|
prepareSite
|
|
9
11
|
};
|