@margoengine/animation 0.1.0 → 1.0.0

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/dist/lod.js CHANGED
@@ -1,4 +1,4 @@
1
- // @margo/core-built 0.1.0
1
+ // @margo/core-built 1.0.0
2
2
  import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
3
 
4
- import{o as e}from"./sampling-DjDWYqt2.js";import{MargoError as t}from"@margoengine/math/errors";var n=Object.freeze([Object.freeze({distance:0,interval:1}),Object.freeze({distance:15,interval:2}),Object.freeze({distance:40,interval:4,depth:4})]);function r(e,t){if(!Number.isFinite(e?.distance)||e.distance<0||!Number.isInteger(e.interval)||e.interval<1||e.depth!==void 0&&!(Number.isInteger(e.depth)&&e.depth>=0))throw RangeError(`${t} is invalid; use a distance >= 0, an integer interval >= 1 and an integer depth >= 0`)}function i(e){let t=e.model.asset.doc.nodes??[],n=new Int32Array(t.length),r=e=>t[e]?.children??[],i=new Uint8Array(t.length);for(let e=0;e<t.length;e++)for(let t of r(e))i[t]=1;let a=[];for(let e=0;e<t.length;e++)i[e]||a.push(e);for(;a.length;){let e=a.pop();for(let t of r(e))n[t]=n[e]+1,a.push(t)}return n}var a=0,o=class o{coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);get time(){return this.elapsed}static attach(e,t){__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));let n=new o(t);return e.use(n),n}constructor({tiers:e=n,hidden:t={distance:0,interval:16,depth:1}}={}){if(this.name=`animation-lod:`+a++,this.stats={updated:0,skipped:0,hidden:0},this.members=/* @__PURE__ */ new Map,this.quaternion=[0,0,0,1],this.frame=0,this.next=0,this.disposed=!1,this.elapsed=0,!Array.isArray(e)||!e.length)throw TypeError(`AnimationLOD tiers must be a non-empty array`);e.forEach((t,n)=>{if(r(t,`AnimationLOD tier ${n}`),n?t.distance<=e[n-1].distance:t.distance!==0)throw RangeError(`AnimationLOD tiers must start at distance 0 and increase`)}),r(t,`AnimationLOD hidden tier`),this.tiers=e,this.hidden=t}get count(){return this.members.size}add(e,{radius:n=2}={}){if(this.disposed)throw new t(`disposed`,`AnimationLOD is disposed; create a new one`);if(!Number.isFinite(n)||n<0)throw RangeError(`AnimationLOD radius must be a finite number >= 0`);let r=this.members.get(e);return r?(r.radius=n,this):(this.members.set(e,{animation:e,radius:n,phase:this.next++,owed:0,due:!1,time:e.time,playing:e.playing,tier:this.tiers[0],levels:i(e)}),e.playing=!1,this)}remove(e){let t=this.members.get(e);return t?(this.members.delete(e),!e.disposed&&!e.model.disposed&&(e.seek(t.time+t.owed*(e.options.speed??1)),e.playing=t.playing),!0):!1}tierOf(e){return this.members.get(e)?.tier}setup(e){if(this.disposed)throw new t(`disposed`,`AnimationLOD is disposed; create a new controller before attaching`);this.engine=e}onPreUpdate(e){this.update(e)}update(e){this.advanceTime(e);for(let e of this.members.values())e.due&&(e.due=!1,this.pose(e,e.tier))}advanceTime(e){if(this.disposed)return;if(!Number.isFinite(e)||e<0)throw RangeError(`Invalid animation delta; pass a finite delta >= 0 seconds`);this.elapsed+=e;let t=this.engine?.camera,n=this.stats,r=this.frame++;n.updated=n.skipped=n.hidden=0;for(let i of this.members.values()){let{animation:a}=i;if(a.disposed||a.model.disposed){this.members.delete(a);continue}let o=a.model.root.matrix,s=o[12],c=o[13],l=o[14],u=this.tiers[0],d=!0;if(t){let e=t.position,n=Math.hypot(s-e[0],c-e[1],l-e[2]),r=t.planes;for(let e of this.tiers)n>=e.distance&&(u=e);for(let e=0;d&&e<24;e+=4)d=r[e]*s+r[e+1]*c+r[e+2]*l+r[e+3]>=-i.radius}d||(u=this.hidden,n.hidden++),i.tier=u,i.owed+=e,(r+i.phase)%u.interval?n.skipped++:(i.time+=i.owed*(a.options.speed??1),i.owed=0,i.due=!0,n.updated++)}}pose({animation:t,time:n,levels:r},i){if(i.depth===void 0){t.seek(n);return}let a=t.clips[t.clip];if(!a)return;let o=(t.options.loop??!0)&&a.duration>0?n%a.duration:Math.min(n,a.duration),s=t.model.nodes;t.time=n;for(let n of a.tracks){if(n.path!==`weights`&&r[n.node]>i.depth)continue;let a=e(n.times,n.values,n.width,o,n.interpolation,n.path===`rotation`,n.sample),c=s[n.node];if(n.path===`translation`)c.setPosition(a);else if(n.path===`scale`)c.setScale(a);else if(n.path===`rotation`){for(let e=0;e<4;e++)this.quaternion[e]=a[e];c.setQuaternion(this.quaternion)}else for(let e of t.model.primitives)e.nodeIndex===n.node&&e.weights.set(a)}}dispose(){if(!this.disposed){this.disposed=!0;for(let e of[...this.members.keys()])this.remove(e);this.engine?.sceneOf(this)?.removePlugin(this.name)}}[Symbol.dispose??Symbol()](){this.dispose()}};export{o as AnimationLOD,n as defaultLODTiers};
4
+ import{o as e}from"./sampling-DjDWYqt2.js";import{MargoError as t}from"@margoengine/math/errors";var n=Object.freeze([Object.freeze({distance:0,interval:1}),Object.freeze({distance:15,interval:2}),Object.freeze({distance:40,interval:4,depth:4})]);function r(e,t){if(!Number.isFinite(e?.distance)||e.distance<0||!Number.isInteger(e.interval)||e.interval<1||e.depth!==void 0&&!(Number.isInteger(e.depth)&&e.depth>=0))throw RangeError(`${t} is invalid; use a distance >= 0, an integer interval >= 1 and an integer depth >= 0`)}function i(e){let t=e.model.asset.doc.nodes??[],n=new Int32Array(t.length),r=e=>t[e]?.children??[],i=new Uint8Array(t.length);for(let e=0;e<t.length;e++)for(let t of r(e))i[t]=1;let a=[];for(let e=0;e<t.length;e++)i[e]||a.push(e);for(;a.length;){let e=a.pop();for(let t of r(e))n[t]=n[e]+1,a.push(t)}return n}var a=0,o=class o{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);get time(){return this.elapsed}static attach(e,t){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));let n=new o(t);return e.use(n),n}constructor({tiers:e=n,hidden:t={distance:0,interval:16,depth:1}}={}){if(this.name=`animation-lod:`+a++,this.stats={updated:0,skipped:0,hidden:0},this.members=/* @__PURE__ */ new Map,this.quaternion=[0,0,0,1],this.frame=0,this.next=0,this.disposed=!1,this.elapsed=0,!Array.isArray(e)||!e.length)throw TypeError(`AnimationLOD tiers must be a non-empty array`);e.forEach((t,n)=>{if(r(t,`AnimationLOD tier ${n}`),n?t.distance<=e[n-1].distance:t.distance!==0)throw RangeError(`AnimationLOD tiers must start at distance 0 and increase`)}),r(t,`AnimationLOD hidden tier`),this.tiers=e,this.hidden=t}get count(){return this.members.size}add(e,{radius:n=2}={}){if(this.disposed)throw new t(`disposed`,`AnimationLOD is disposed; create a new one`);if(!Number.isFinite(n)||n<0)throw RangeError(`AnimationLOD radius must be a finite number >= 0`);let r=this.members.get(e);return r?(r.radius=n,this):(this.members.set(e,{animation:e,radius:n,phase:this.next++,owed:0,due:!1,time:e.time,playing:e.playing,tier:this.tiers[0],levels:i(e)}),e.playing=!1,this)}remove(e){let t=this.members.get(e);return t?(this.members.delete(e),!e.disposed&&!e.model.disposed&&(e.seek(t.time+t.owed*(e.options.speed??1)),e.playing=t.playing),!0):!1}tierOf(e){return this.members.get(e)?.tier}setup(e){if(this.disposed)throw new t(`disposed`,`AnimationLOD is disposed; create a new controller before attaching`);this.engine=e}onPreUpdate(e){this.update(e)}update(e){this.advanceTime(e);for(let e of this.members.values())e.due&&(e.due=!1,this.pose(e,e.tier))}advanceTime(e){if(this.disposed)return;if(!Number.isFinite(e)||e<0)throw RangeError(`Invalid animation delta; pass a finite delta >= 0 seconds`);this.elapsed+=e;let t=this.engine?.camera,n=this.stats,r=this.frame++;n.updated=n.skipped=n.hidden=0;for(let i of this.members.values()){let{animation:a}=i;if(a.disposed||a.model.disposed){this.members.delete(a);continue}let o=a.model.root.matrix,s=o[12],c=o[13],l=o[14],u=this.tiers[0],d=!0;if(t){let e=t.position,n=Math.hypot(s-e[0],c-e[1],l-e[2]),r=t.planes;for(let e of this.tiers)n>=e.distance&&(u=e);for(let e=0;d&&e<24;e+=4)d=r[e]*s+r[e+1]*c+r[e+2]*l+r[e+3]>=-i.radius}d||(u=this.hidden,n.hidden++),i.tier=u,i.owed+=e,(r+i.phase)%u.interval?n.skipped++:(i.time+=i.owed*(a.options.speed??1),i.owed=0,i.due=!0,n.updated++)}}pose({animation:t,time:n,levels:r},i){if(i.depth===void 0){t.seek(n);return}let a=t.clips[t.clip];if(!a)return;let o=(t.options.loop??!0)&&a.duration>0?n%a.duration:Math.min(n,a.duration),s=t.model.nodes;t.time=n;for(let n of a.tracks){if(n.path!==`weights`&&r[n.node]>i.depth)continue;let a=e(n.times,n.values,n.width,o,n.interpolation,n.path===`rotation`,n.sample),c=s[n.node];if(n.path===`translation`)c.setPosition(a);else if(n.path===`scale`)c.setScale(a);else if(n.path===`rotation`){for(let e=0;e<4;e++)this.quaternion[e]=a[e];c.setQuaternion(this.quaternion)}else for(let e of t.model.primitives)e.nodeIndex===n.node&&e.weights.set(a)}}dispose(){if(!this.disposed){this.disposed=!0;for(let e of[...this.members.keys()])this.remove(e);this.engine?.sceneOf(this)?.removePlugin(this.name)}}[Symbol.dispose??Symbol()](){this.dispose()}};export{o as AnimationLOD,n as defaultLODTiers};
package/dist/mixer.js CHANGED
@@ -1,4 +1,4 @@
1
- // @margo/core-built 0.1.0
1
+ // @margo/core-built 1.0.0
2
2
  import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
3
 
4
- import{n as e}from"./errors-t1ewumJS.js";import{MargoError as t}from"@margoengine/math/errors";import{Animation as n,Skeleton as r,sampleKeyframes as i}from"@margoengine/animation";import{sampleTrackInto as a}from"@margoengine/animation/sampling";var o=t=>Object.assign(e(t,`arguments`),{code:`arguments`}),s=2200,c=2201,l=2202,u=2500,d=2501,f=e=>`kind`in e&&e.kind===`discrete`,p=(e,t,n=-1/0)=>{if(!Number.isFinite(e)||e<n)throw o(`Invalid ${t}; pass a finite number >= ${n}`);return e},m=(e,t)=>e.from+(e.to-e.from)*Math.max(0,Math.min(1,(t-e.start)/e.duration));function h(e,t,n,r){let i=0;for(let n=0;n<4;n++)i+=e[n]*t[n];let a=i<0?-1:1;i=Math.min(1,Math.abs(i));let o=1-n,s=n;if(i<.9995){let e=Math.acos(i),t=Math.sin(e);o=Math.sin((1-n)*e)/t,s=Math.sin(n*e)/t}for(let n=0;n<4;n++)r[n]=e[n]*o+t[n]*s*a;let c=Math.hypot(...r);for(let e=0;e<4;e++)r[e]/=c}var g=class{constructor(e,t,n,r=u,i=[],a=[]){this.mixer=e,this.clip=t,this.root=n,this.blendMode=r,this.channels=i,this.discrete=a,this.time=0,this.timeScale=1,this.weight=1,this.enabled=!0,this.paused=!1,this.clampWhenFinished=!1,this.loop=c,this.repetitions=1/0,this.scheduled=!1,this.loops=0,this.sampled=0,this.contribution=0}play(){return this.mixer.assertLive(),this.mixer.assertRootLive(this.root),this.scheduled||this.mixer.activate(this.channels.map(e=>e.binding)),this.scheduled||this.mixer.activateDiscrete(this.discrete.map(e=>e.binding)),this.scheduled=!0,this}stop(){return this.scheduled=!1,this.mixer.deactivate(this.channels.map(e=>e.binding)),this.mixer.deactivateDiscrete(this.discrete.map(e=>e.binding)),this.reset()}reset(){return this.time=this.loops=0,this.enabled=!0,this.paused=!1,this.fade=this.speed=void 0,this.start=void 0,this}startAt(e){return this.start=p(e,`start time`),this}isScheduled(){return this.scheduled}isRunning(){return this.scheduled&&this.enabled&&!this.paused&&this.timeScale!==0&&(this.start===void 0||this.mixer.time>=this.start)}getClip(){return this.clip}getMixer(){return this.mixer}getRoot(){return this.root}getEffectiveWeight(){return this.enabled?this.weight*this.fadeFactor():0}getEffectiveTimeScale(){return this.paused?0:this.rate()}fadeFactor(){let e=this.fade;return e?e.duration?m(e,this.mixer.time):e.to:1}rate(){let e=this.speed;return e?e.duration?m(e,this.mixer.time):e.to:this.timeScale}setEffectiveWeight(e){return this.weight=p(e,`weight`,0),this.fade=void 0,this}setEffectiveTimeScale(e){return this.timeScale=p(e,`timeScale`),this.speed=void 0,this}setDuration(e){if(!(p(e,`duration`,0)>0))throw o(`Duration must be positive; pass seconds > 0`);return this.setEffectiveTimeScale(this.clip.duration/e)}syncWith(e){return this.time=e.time,this.setEffectiveTimeScale(e.timeScale)}setLoop(e,t=1/0){if(![2200,2201,2202].includes(e)||t!==1/0&&(!Number.isSafeInteger(t)||t<1))throw o(`Invalid action loop; pass a loop mode and a positive integer count or Infinity`);return this.loop=e,this.repetitions=t,this}envelope(e,t,n){return p(n,`fade/warp duration`,0),{from:e,to:t,duration:n,start:this.mixer.time}}fadeIn(e){return this.fade=this.envelope(0,1,e),this}fadeOut(e){return this.fade=this.envelope(1,0,e),this}stopFading(){return this.fade=void 0,this}warp(e,t,n){return this.speed=this.envelope(p(e,`warp start`),p(t,`warp end`),n),this}halt(e){return this.warp(this.getEffectiveTimeScale(),0,e)}stopWarping(){return this.speed=void 0,this}crossFadeTo(e,t,n=!1){if(e.mixer!==this.mixer||e===this)throw o(`Crossfade needs a different action from this mixer; use mixer.clipAction`);if(p(t,`crossfade duration`,0),n&&(!(this.clip.duration>0)||!(e.clip.duration>0)))throw o(`Warp needs positive clip durations; omit warp for static clips`);if(this.fadeOut(t),e.fadeIn(t),n){let n=this.clip.duration/e.clip.duration;this.warp(1,n,t),e.warp(1/n,1,t)}return this}crossFadeFrom(e,t,n=!1){return e.crossFadeTo(this,t,n),this}step(e){if(this.contribution=0,!this.scheduled||!this.enabled)return;if(p(this.time,`action time`),p(this.timeScale,`timeScale`),p(this.weight,`weight`,0),this.start!==void 0){if(this.mixer.time<this.start)return;e=Math.min(e,this.mixer.time-this.start),this.start=void 0}let t=this.rate();if(this.speed){let e=this.speed;this.mixer.time>=e.start+e.duration&&(this.timeScale=t,this.speed=void 0,t===0&&(this.paused=!0))}let n=this.fadeFactor();if(this.fade){let e=this.fade;this.mixer.time>=e.start+e.duration&&(this.fade=void 0,e.to===0&&(this.enabled=!1))}let r=this.enabled?this.weight*n:0,i=this.clip.duration,a=this.time;if(!this.paused&&e*t!==0){let n=p(this.time+e*t,`advanced action time`);if(this.loop===2200||i===0)this.time=Math.max(0,Math.min(i,n)),(n>=i||n<0)&&(i>0||this.loop===2200||this.repetitions!==1/0)&&this.finish();else{let e=Math.floor(n/i);this.loops+Math.abs(e)>=this.repetitions?(this.time=n<0?0:i,this.loops=this.repetitions-1,this.finish()):(this.time=(n%i+i)%i,this.loops+=Math.abs(e))}a=this.time}this.loop===2202&&this.loops%2&&(a=i-a),this.enabled||(r=0),this.sampled=a,this.contribution=r}contribute(){let e=this.sampled,t=this.contribution;if(t>0){for(let n of this.channels)this.mixer.accumulate(n.binding,n.sample(e),t,this.blendMode);for(let n of this.discrete)this.mixer.accumulateDiscrete(n.binding,n.sample(e),t)}}uses(e){return this.channels.some(t=>t.binding===e)}usesDiscrete(e){return this.discrete.some(t=>t.binding===e)}rewind(){this.time=this.loops=0}finish(){this.clampWhenFinished?this.paused=!0:this.enabled=!1}},_=class e{coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);static attach(t,n){__margoAssertCore(t,__margoCoreRequirement("0.1.0",import.meta.url));let r=new e(n);try{return t.use(r),r}catch(e){throw r.dispose(),e}}constructor(e){this.root=e,this.time=0,this.timeScale=1,this.actions=[],this.players=/* @__PURE__ */ new Map,this.owned=/* @__PURE__ */ new Set,this.bindings=/* @__PURE__ */ new Map,this.discreteBindings=/* @__PURE__ */ new Map,this.disposed=!1,this.additive=/* @__PURE__ */ new Map,this.name=`animation-mixer:`+v++,this.player(e)}assertLive(){if(this.disposed)throw new t(`disposed`,`AnimationMixer is disposed; create a new mixer; see https://margoengine.com/errors#disposed`)}assertRootLive(e){let r=this.players.get(e);if(r instanceof n){if(r.model.disposed)throw new t(`disposed`,`Mixer root is disposed; use a live model; see https://margoengine.com/errors#disposed`);r.captureState()}}rootAlive(e){let t=this.players.get(e);return!(t instanceof n)||!t.model.disposed}activate(e){for(let t of e)this.actions.some(e=>e.isScheduled()&&e.uses(t))||t.base.set(Array.from(t.read()))}deactivate(e){for(let t of e)t.applied&&!this.actions.some(e=>e.isScheduled()&&e.uses(t))&&(this.actions.some(e=>e.uses(t)&&this.rootAlive(e.getRoot()))&&t.write(t.base),t.applied=!1)}activateDiscrete(e){for(let t of e)this.actions.some(e=>e.isScheduled()&&e.usesDiscrete(t))||(t.base=t.channel.read())}deactivateDiscrete(e){for(let t of e)t.applied&&!this.actions.some(e=>e.isScheduled()&&e.usesDiscrete(t))&&(this.actions.some(e=>e.usesDiscrete(t)&&this.rootAlive(e.getRoot()))&&t.channel.write(t.base),t.applied=!1)}player(e){if(this.players.has(e))return this.players.get(e);let i=this.players.get(e);if(!i){if(!e||typeof e!=`object`)throw o(`Invalid mixer root; pass an object, model, Skeleton or Animation`);if(e instanceof r||e instanceof n)i=e;else if(Array.isArray(e.nodes)&&e.root?.scene){let r=e;if(r.disposed)throw new t(`disposed`,`Mixer root is disposed; use a live model; see https://margoengine.com/errors#disposed`);i=new n(r),r.root.scene.use(i)}i instanceof n&&(i.playing=!1,i!==e&&this.owned.add(i)),this.players.set(e,i)}return i}resolve(e,t){let r=this.player(t),i=typeof e==`object`?e:r instanceof n?typeof e==`number`?r.clips[e]:r.clips.find(t=>t.name===e):void 0;if(!i||!Number.isFinite(i.duration)||i.duration<0||!Array.isArray(i.tracks))throw o(`Unknown mixer clip; use an Animation clip or createKeyframeClip`);return i}clipAction(e,t=this.root,n=u){if(this.assertLive(),![2500,2501].includes(n))throw o(`Invalid blend mode; choose NormalAnimationBlendMode or AdditiveAnimationBlendMode`);let r=this.resolve(e,t);if(this.assertRootLive(t),f(r)&&n===2501)throw o(`Categorical tracks have no additive arithmetic; use NormalAnimationBlendMode`);let i=this.actions.find(e=>e.getClip()===r&&e.getRoot()===t&&e.blendMode===n);return i||(i=new g(this,r,t,n,this.bind(r,t),this.bindDiscrete(r)),this.actions.push(i)),i}existingAction(e,t=this.root){let r=this.players.get(t),i=typeof e==`object`?e:r instanceof n?typeof e==`number`?r.clips[e]:r.clips.find(t=>t.name===e):void 0;return i?this.actions.find(e=>e.getClip()===i&&e.getRoot()===t)??null:null}getRoot(){return this.root}update(e){return this.advanceTime(e),this.blend(),this}advanceTime(e){this.assertLive(),p(e,`mixer delta`),p(this.timeScale,`mixer timeScale`);let t=e*this.timeScale;p(this.time+t,`mixer time`),this.time+=t;let r=this.actions.filter(e=>{let t=this.players.get(e.getRoot());return t instanceof n&&t.model.disposed});for(let e of r)this.actions.splice(this.actions.indexOf(e),1);for(let[e,t]of this.bindings){for(let[e,n]of t)r.some(e=>e.uses(n))&&!this.actions.some(e=>e.uses(n))&&t.delete(e);t.size||this.bindings.delete(e)}for(let[e,t]of this.discreteBindings){for(let[e,n]of t)r.some(e=>e.usesDiscrete(n))&&!this.actions.some(e=>e.usesDiscrete(n))&&t.delete(e);t.size||this.discreteBindings.delete(e)}for(let e of this.actions)e.step(t)}blend(){this.additive.clear();for(let e of this.discreteBindings.values())for(let t of e.values())t.total=0,t.winner=-1/0,t.value=t.base;for(let e of this.bindings.values())for(let t of e.values())t.total=0,t.value.fill(0);for(let e of this.actions)e.contribute();for(let e of this.bindings.values())for(let t of e.values()){let e=t.total>0||this.additive.has(t);if(e||t.applied){if(t.total===0)t.value.set(t.base);else if(t.quaternion)t.total<1&&h(t.base,t.value,t.total,t.value);else for(let e=0;e<t.value.length;e++)t.value[e]=t.value[e]/Math.max(1,t.total)+t.base[e]*Math.max(0,1-t.total);for(let e of this.additive.get(t)??[])if(t.quaternion){let n=/* @__PURE__ */ new Float64Array(4);h([0,0,0,1],e.value,e.weight,n);let[r,i,a,o]=t.value,[s,c,l,u]=n;t.value.set([o*s+r*u+i*l-a*c,o*c-r*l+i*u+a*s,o*l+r*c-i*s+a*u,o*u-r*s-i*c-a*l])}else for(let n=0;n<t.value.length;n++)t.value[n]=t.scale?t.value[n]*(1+(e.value[n]-1)*e.weight):t.value[n]+e.value[n]*e.weight;t.write(t.value),t.applied=e}}for(let e of this.discreteBindings.values())for(let t of e.values()){let e=t.total>0;(e||t.applied)&&(t.channel.write(!e||Math.max(0,1-t.total)>t.winner?t.base:t.value),t.applied=e)}}setTime(e){p(e,`mixer seek`),this.time=0;for(let e of this.actions)e.rewind();return this.update(e)}stopAllAction(){for(let e of this.actions)e.stop();return this.update(0)}uncacheAction(e,t=this.root){let n=this.resolve(e,t);for(let e=this.actions.length-1;e>=0;e--)this.actions[e].getClip()===n&&this.actions[e].getRoot()===t&&(this.actions[e].stop(),this.actions.splice(e,1));this.update(0);for(let[e,t]of this.bindings){for(let[e,n]of t)this.actions.some(e=>e.uses(n))||t.delete(e);t.size||this.bindings.delete(e)}for(let[e,t]of this.discreteBindings){for(let[e,n]of t)this.actions.some(e=>e.usesDiscrete(n))||t.delete(e);t.size||this.discreteBindings.delete(e)}}uncacheClip(e){for(let t of this.players.keys())this.uncacheAction(e,t)}uncacheRoot(e){for(let t of[...this.actions])t.getRoot()===e&&this.uncacheAction(t.getClip(),e);this.update(0);let t=this.players.get(e);t instanceof n&&this.owned.delete(t)&&t.dispose(),this.players.delete(e)}setup(e){this.assertLive(),this.engine=e}onPreUpdate(e){this.update(e)}dispose(){if(!this.disposed){this.stopAllAction(),this.disposed=!0,this.engine?.sceneOf(this)?.removePlugin(this.name);for(let e of this.owned)e.dispose();this.owned.clear(),this.actions.length=0,this.players.clear(),this.bindings.clear(),this.discreteBindings.clear(),this.engine=void 0}}[Symbol.dispose??Symbol()](){this.dispose()}accumulate(e,t,n,r){if(r===2501){let r=this.additive.get(e);r||this.additive.set(e,r=[]),r.push({value:Float64Array.from(t),weight:n});return}let i=e.total+n;if(e.quaternion)e.total===0?e.value.set(Array.from(t)):h(e.value,t,n/i,e.value);else for(let r=0;r<e.value.length;r++)e.value[r]+=t[r]*n;e.total=i}binding(e,t,n,r,i=!1,a=!1,o=()=>n){let s=this.bindings.get(e);s||this.bindings.set(e,s=/* @__PURE__ */ new Map);let c=s.get(t);return c||(c={base:Float64Array.from(n),value:new Float64Array(n.length),total:0,write:r,quaternion:i,scale:a,applied:!1,read:o},s.set(t,c)),c}bind(e,t){if(f(e))return[];let s=this.player(t),c=[],l=e.tracks[0]&&`target`in e.tracks[0]||`properties`in e;for(let t of e.tracks){let e=t.path,l;if(s instanceof r){if(!(`target`in t)||e===`weights`)continue;let n=s.index(t.target);if(n<0)continue;let r=s.getPose(n),i=e;l=this.binding(s,n+`:`+e,r[i],e=>s.setPose(n,{[i]:e}),e===`rotation`,e===`scale`,()=>s.getPose(n)[i])}else if(s instanceof n){let n=`node`in t?t.node:s.model.nodes.findIndex(e=>e.name===t.target);if(n<0)continue;let r=s.model.nodes[n];if(e===`weights`){let t=s.model.primitives.find(e=>e.nodeIndex===n);if(!t)continue;l=this.binding(r,e,t.weights,e=>{for(let t=0;t<e.length;t++)s.setMorph(n,t,e[t])})}else{let t=r.engine.store.transforms,n=r.id,i=e===`translation`?[t.x[n],t.y[n],t.z[n]]:e===`scale`?[t.sx[n],t.sy[n],t.sz[n]]:[t.qx[n],t.qy[n],t.qz[n],t.qw[n]];l=this.binding(r,e,i,t=>{e===`translation`?r.setPosition(t):e===`scale`?r.setScale(t):r.setQuaternion(Array.from(t))},e===`rotation`,e===`scale`,()=>e===`translation`?[t.x[n],t.y[n],t.z[n]]:e===`scale`?[t.sx[n],t.sy[n],t.sz[n]]:[t.qx[n],t.qy[n],t.qz[n],t.qw[n]])}}else throw o(`Transform tracks need a Skeleton or Animation root; use bound property tracks on plain objects`);if(`node`in t){let n=new Float32Array(t.width);c.push({binding:l,sample:r=>a(t.times,t.values,t.width,r,t.interpolation,e===`rotation`,n)})}else{let e=new Float64Array(t.values.length/t.times.length);c.push({binding:l,sample:n=>i(t,n,e)})}}let u=l?e.properties:`bind`in e&&e.bind?(e.bound??=e.bind()).properties:void 0;for(let e of u??[])this.property(e,c);return c}property(e,t){let n=this.binding(e.target,`property:`+(e.property??e.name),e.read(),t=>e.write(t),e.type===`quaternion`,!1,()=>e.read()),r=new Float64Array(e.size);t.push({binding:n,sample:t=>i(e,t,r)})}bindDiscrete(e){return f(e)?e.tracks.map(e=>{let t=this.discreteBindings.get(e.target);t||this.discreteBindings.set(e.target,t=/* @__PURE__ */ new Map);let n=t.get(e.property);if(!n){let r=e.read();n={base:r,value:r,total:0,winner:-1/0,applied:!1,channel:e},t.set(e.property,n)}else if(typeof n.base!=typeof e.read())throw o(`Categorical binding types disagree; use the same value type for one property`);return{binding:n,sample:t=>e.sample(t)}}):[]}accumulateDiscrete(e,t,n){if(typeof t!=`boolean`&&typeof t!=`string`||typeof t!=typeof e.base)throw o(`Categorical channel changed value type; return the original boolean or string type`);e.total+=n,n>=e.winner&&(e.winner=n,e.value=t)}},v=0;export{d as AdditiveAnimationBlendMode,g as AnimationAction,_ as AnimationMixer,s as LoopOnce,l as LoopPingPong,c as LoopRepeat,u as NormalAnimationBlendMode};
4
+ import{n as e}from"./errors-t1ewumJS.js";import{MargoError as t}from"@margoengine/math/errors";import{Animation as n,Skeleton as r,sampleKeyframes as i}from"@margoengine/animation";import{sampleTrackInto as a}from"@margoengine/animation/sampling";var o=t=>Object.assign(e(t,`arguments`),{code:`arguments`}),s=2200,c=2201,l=2202,u=2500,d=2501,f=e=>`kind`in e&&e.kind===`discrete`,p=(e,t,n=-1/0)=>{if(!Number.isFinite(e)||e<n)throw o(`Invalid ${t}; pass a finite number >= ${n}`);return e},m=(e,t)=>e.from+(e.to-e.from)*Math.max(0,Math.min(1,(t-e.start)/e.duration));function h(e,t,n,r){let i=0;for(let n=0;n<4;n++)i+=e[n]*t[n];let a=i<0?-1:1;i=Math.min(1,Math.abs(i));let o=1-n,s=n;if(i<.9995){let e=Math.acos(i),t=Math.sin(e);o=Math.sin((1-n)*e)/t,s=Math.sin(n*e)/t}for(let n=0;n<4;n++)r[n]=e[n]*o+t[n]*s*a;let c=Math.hypot(...r);for(let e=0;e<4;e++)r[e]/=c}var g=class{constructor(e,t,n,r=u,i=[],a=[]){this.mixer=e,this.clip=t,this.root=n,this.blendMode=r,this.channels=i,this.discrete=a,this.time=0,this.timeScale=1,this.weight=1,this.enabled=!0,this.paused=!1,this.clampWhenFinished=!1,this.loop=c,this.repetitions=1/0,this.scheduled=!1,this.loops=0,this.sampled=0,this.contribution=0}play(){return this.mixer.assertLive(),this.mixer.assertRootLive(this.root),this.scheduled||this.mixer.activate(this.channels.map(e=>e.binding)),this.scheduled||this.mixer.activateDiscrete(this.discrete.map(e=>e.binding)),this.scheduled=!0,this}stop(){return this.scheduled=!1,this.mixer.deactivate(this.channels.map(e=>e.binding)),this.mixer.deactivateDiscrete(this.discrete.map(e=>e.binding)),this.reset()}reset(){return this.time=this.loops=0,this.enabled=!0,this.paused=!1,this.fade=this.speed=void 0,this.start=void 0,this}startAt(e){return this.start=p(e,`start time`),this}isScheduled(){return this.scheduled}isRunning(){return this.scheduled&&this.enabled&&!this.paused&&this.timeScale!==0&&(this.start===void 0||this.mixer.time>=this.start)}getClip(){return this.clip}getMixer(){return this.mixer}getRoot(){return this.root}getEffectiveWeight(){return this.enabled?this.weight*this.fadeFactor():0}getEffectiveTimeScale(){return this.paused?0:this.rate()}fadeFactor(){let e=this.fade;return e?e.duration?m(e,this.mixer.time):e.to:1}rate(){let e=this.speed;return e?e.duration?m(e,this.mixer.time):e.to:this.timeScale}setEffectiveWeight(e){return this.weight=p(e,`weight`,0),this.fade=void 0,this}setEffectiveTimeScale(e){return this.timeScale=p(e,`timeScale`),this.speed=void 0,this}setDuration(e){if(!(p(e,`duration`,0)>0))throw o(`Duration must be positive; pass seconds > 0`);return this.setEffectiveTimeScale(this.clip.duration/e)}syncWith(e){return this.time=e.time,this.setEffectiveTimeScale(e.timeScale)}setLoop(e,t=1/0){if(![2200,2201,2202].includes(e)||t!==1/0&&(!Number.isSafeInteger(t)||t<1))throw o(`Invalid action loop; pass a loop mode and a positive integer count or Infinity`);return this.loop=e,this.repetitions=t,this}envelope(e,t,n){return p(n,`fade/warp duration`,0),{from:e,to:t,duration:n,start:this.mixer.time}}fadeIn(e){return this.fade=this.envelope(0,1,e),this}fadeOut(e){return this.fade=this.envelope(1,0,e),this}stopFading(){return this.fade=void 0,this}warp(e,t,n){return this.speed=this.envelope(p(e,`warp start`),p(t,`warp end`),n),this}halt(e){return this.warp(this.getEffectiveTimeScale(),0,e)}stopWarping(){return this.speed=void 0,this}crossFadeTo(e,t,n=!1){if(e.mixer!==this.mixer||e===this)throw o(`Crossfade needs a different action from this mixer; use mixer.clipAction`);if(p(t,`crossfade duration`,0),n&&(!(this.clip.duration>0)||!(e.clip.duration>0)))throw o(`Warp needs positive clip durations; omit warp for static clips`);if(this.fadeOut(t),e.fadeIn(t),n){let n=this.clip.duration/e.clip.duration;this.warp(1,n,t),e.warp(1/n,1,t)}return this}crossFadeFrom(e,t,n=!1){return e.crossFadeTo(this,t,n),this}step(e){if(this.contribution=0,!this.scheduled||!this.enabled)return;if(p(this.time,`action time`),p(this.timeScale,`timeScale`),p(this.weight,`weight`,0),this.start!==void 0){if(this.mixer.time<this.start)return;e=Math.min(e,this.mixer.time-this.start),this.start=void 0}let t=this.rate();if(this.speed){let e=this.speed;this.mixer.time>=e.start+e.duration&&(this.timeScale=t,this.speed=void 0,t===0&&(this.paused=!0))}let n=this.fadeFactor();if(this.fade){let e=this.fade;this.mixer.time>=e.start+e.duration&&(this.fade=void 0,e.to===0&&(this.enabled=!1))}let r=this.enabled?this.weight*n:0,i=this.clip.duration,a=this.time;if(!this.paused&&e*t!==0){let n=p(this.time+e*t,`advanced action time`);if(this.loop===2200||i===0)this.time=Math.max(0,Math.min(i,n)),(n>=i||n<0)&&(i>0||this.loop===2200||this.repetitions!==1/0)&&this.finish();else{let e=Math.floor(n/i);this.loops+Math.abs(e)>=this.repetitions?(this.time=n<0?0:i,this.loops=this.repetitions-1,this.finish()):(this.time=(n%i+i)%i,this.loops+=Math.abs(e))}a=this.time}this.loop===2202&&this.loops%2&&(a=i-a),this.enabled||(r=0),this.sampled=a,this.contribution=r}contribute(){let e=this.sampled,t=this.contribution;if(t>0){for(let n of this.channels)this.mixer.accumulate(n.binding,n.sample(e),t,this.blendMode);for(let n of this.discrete)this.mixer.accumulateDiscrete(n.binding,n.sample(e),t)}}uses(e){return this.channels.some(t=>t.binding===e)}usesDiscrete(e){return this.discrete.some(t=>t.binding===e)}rewind(){this.time=this.loops=0}finish(){this.clampWhenFinished?this.paused=!0:this.enabled=!1}},_=class e{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static attach(t,n){__margoAssertCore(t,__margoCoreRequirement("1.0.0",import.meta.url));let r=new e(n);try{return t.use(r),r}catch(e){throw r.dispose(),e}}constructor(e){this.root=e,this.time=0,this.timeScale=1,this.actions=[],this.players=/* @__PURE__ */ new Map,this.owned=/* @__PURE__ */ new Set,this.bindings=/* @__PURE__ */ new Map,this.discreteBindings=/* @__PURE__ */ new Map,this.disposed=!1,this.additive=/* @__PURE__ */ new Map,this.name=`animation-mixer:`+v++,this.player(e)}assertLive(){if(this.disposed)throw new t(`disposed`,`AnimationMixer is disposed; create a new mixer; see https://margoengine.com/errors#disposed`)}assertRootLive(e){let r=this.players.get(e);if(r instanceof n){if(r.model.disposed)throw new t(`disposed`,`Mixer root is disposed; use a live model; see https://margoengine.com/errors#disposed`);r.captureState()}}rootAlive(e){let t=this.players.get(e);return!(t instanceof n)||!t.model.disposed}activate(e){for(let t of e)this.actions.some(e=>e.isScheduled()&&e.uses(t))||t.base.set(Array.from(t.read()))}deactivate(e){for(let t of e)t.applied&&!this.actions.some(e=>e.isScheduled()&&e.uses(t))&&(this.actions.some(e=>e.uses(t)&&this.rootAlive(e.getRoot()))&&t.write(t.base),t.applied=!1)}activateDiscrete(e){for(let t of e)this.actions.some(e=>e.isScheduled()&&e.usesDiscrete(t))||(t.base=t.channel.read())}deactivateDiscrete(e){for(let t of e)t.applied&&!this.actions.some(e=>e.isScheduled()&&e.usesDiscrete(t))&&(this.actions.some(e=>e.usesDiscrete(t)&&this.rootAlive(e.getRoot()))&&t.channel.write(t.base),t.applied=!1)}player(e){if(this.players.has(e))return this.players.get(e);let i=this.players.get(e);if(!i){if(!e||typeof e!=`object`)throw o(`Invalid mixer root; pass an object, model, Skeleton or Animation`);if(e instanceof r||e instanceof n)i=e;else if(Array.isArray(e.nodes)&&e.root?.scene){let r=e;if(r.disposed)throw new t(`disposed`,`Mixer root is disposed; use a live model; see https://margoengine.com/errors#disposed`);i=new n(r),r.root.scene.use(i)}i instanceof n&&(i.playing=!1,i!==e&&this.owned.add(i)),this.players.set(e,i)}return i}resolve(e,t){let r=this.player(t),i=typeof e==`object`?e:r instanceof n?typeof e==`number`?r.clips[e]:r.clips.find(t=>t.name===e):void 0;if(!i||!Number.isFinite(i.duration)||i.duration<0||!Array.isArray(i.tracks))throw o(`Unknown mixer clip; use an Animation clip or createKeyframeClip`);return i}clipAction(e,t=this.root,n=u){if(this.assertLive(),![2500,2501].includes(n))throw o(`Invalid blend mode; choose NormalAnimationBlendMode or AdditiveAnimationBlendMode`);let r=this.resolve(e,t);if(this.assertRootLive(t),f(r)&&n===2501)throw o(`Categorical tracks have no additive arithmetic; use NormalAnimationBlendMode`);let i=this.actions.find(e=>e.getClip()===r&&e.getRoot()===t&&e.blendMode===n);return i||(i=new g(this,r,t,n,this.bind(r,t),this.bindDiscrete(r)),this.actions.push(i)),i}existingAction(e,t=this.root){let r=this.players.get(t),i=typeof e==`object`?e:r instanceof n?typeof e==`number`?r.clips[e]:r.clips.find(t=>t.name===e):void 0;return i?this.actions.find(e=>e.getClip()===i&&e.getRoot()===t)??null:null}getRoot(){return this.root}update(e){return this.advanceTime(e),this.blend(),this}advanceTime(e){this.assertLive(),p(e,`mixer delta`),p(this.timeScale,`mixer timeScale`);let t=e*this.timeScale;p(this.time+t,`mixer time`),this.time+=t;let r=this.actions.filter(e=>{let t=this.players.get(e.getRoot());return t instanceof n&&t.model.disposed});for(let e of r)this.actions.splice(this.actions.indexOf(e),1);for(let[e,t]of this.bindings){for(let[e,n]of t)r.some(e=>e.uses(n))&&!this.actions.some(e=>e.uses(n))&&t.delete(e);t.size||this.bindings.delete(e)}for(let[e,t]of this.discreteBindings){for(let[e,n]of t)r.some(e=>e.usesDiscrete(n))&&!this.actions.some(e=>e.usesDiscrete(n))&&t.delete(e);t.size||this.discreteBindings.delete(e)}for(let e of this.actions)e.step(t)}blend(){this.additive.clear();for(let e of this.discreteBindings.values())for(let t of e.values())t.total=0,t.winner=-1/0,t.value=t.base;for(let e of this.bindings.values())for(let t of e.values())t.total=0,t.value.fill(0);for(let e of this.actions)e.contribute();for(let e of this.bindings.values())for(let t of e.values()){let e=t.total>0||this.additive.has(t);if(e||t.applied){if(t.total===0)t.value.set(t.base);else if(t.quaternion)t.total<1&&h(t.base,t.value,t.total,t.value);else for(let e=0;e<t.value.length;e++)t.value[e]=t.value[e]/Math.max(1,t.total)+t.base[e]*Math.max(0,1-t.total);for(let e of this.additive.get(t)??[])if(t.quaternion){let n=/* @__PURE__ */ new Float64Array(4);h([0,0,0,1],e.value,e.weight,n);let[r,i,a,o]=t.value,[s,c,l,u]=n;t.value.set([o*s+r*u+i*l-a*c,o*c-r*l+i*u+a*s,o*l+r*c-i*s+a*u,o*u-r*s-i*c-a*l])}else for(let n=0;n<t.value.length;n++)t.value[n]=t.scale?t.value[n]*(1+(e.value[n]-1)*e.weight):t.value[n]+e.value[n]*e.weight;t.write(t.value),t.applied=e}}for(let e of this.discreteBindings.values())for(let t of e.values()){let e=t.total>0;(e||t.applied)&&(t.channel.write(!e||Math.max(0,1-t.total)>t.winner?t.base:t.value),t.applied=e)}}setTime(e){p(e,`mixer seek`),this.time=0;for(let e of this.actions)e.rewind();return this.update(e)}stopAllAction(){for(let e of this.actions)e.stop();return this.update(0)}uncacheAction(e,t=this.root){let n=this.resolve(e,t);for(let e=this.actions.length-1;e>=0;e--)this.actions[e].getClip()===n&&this.actions[e].getRoot()===t&&(this.actions[e].stop(),this.actions.splice(e,1));this.update(0);for(let[e,t]of this.bindings){for(let[e,n]of t)this.actions.some(e=>e.uses(n))||t.delete(e);t.size||this.bindings.delete(e)}for(let[e,t]of this.discreteBindings){for(let[e,n]of t)this.actions.some(e=>e.usesDiscrete(n))||t.delete(e);t.size||this.discreteBindings.delete(e)}}uncacheClip(e){for(let t of this.players.keys())this.uncacheAction(e,t)}uncacheRoot(e){for(let t of[...this.actions])t.getRoot()===e&&this.uncacheAction(t.getClip(),e);this.update(0);let t=this.players.get(e);t instanceof n&&this.owned.delete(t)&&t.dispose(),this.players.delete(e)}setup(e){this.assertLive(),this.engine=e}onPreUpdate(e){this.update(e)}dispose(){if(!this.disposed){this.stopAllAction(),this.disposed=!0,this.engine?.sceneOf(this)?.removePlugin(this.name);for(let e of this.owned)e.dispose();this.owned.clear(),this.actions.length=0,this.players.clear(),this.bindings.clear(),this.discreteBindings.clear(),this.engine=void 0}}[Symbol.dispose??Symbol()](){this.dispose()}accumulate(e,t,n,r){if(r===2501){let r=this.additive.get(e);r||this.additive.set(e,r=[]),r.push({value:Float64Array.from(t),weight:n});return}let i=e.total+n;if(e.quaternion)e.total===0?e.value.set(Array.from(t)):h(e.value,t,n/i,e.value);else for(let r=0;r<e.value.length;r++)e.value[r]+=t[r]*n;e.total=i}binding(e,t,n,r,i=!1,a=!1,o=()=>n){let s=this.bindings.get(e);s||this.bindings.set(e,s=/* @__PURE__ */ new Map);let c=s.get(t);return c||(c={base:Float64Array.from(n),value:new Float64Array(n.length),total:0,write:r,quaternion:i,scale:a,applied:!1,read:o},s.set(t,c)),c}bind(e,t){if(f(e))return[];let s=this.player(t),c=[],l=e.tracks[0]&&`target`in e.tracks[0]||`properties`in e;for(let t of e.tracks){let e=t.path,l;if(s instanceof r){if(!(`target`in t)||e===`weights`)continue;let n=s.index(t.target);if(n<0)continue;let r=s.getPose(n),i=e;l=this.binding(s,n+`:`+e,r[i],e=>s.setPose(n,{[i]:e}),e===`rotation`,e===`scale`,()=>s.getPose(n)[i])}else if(s instanceof n){let n=`node`in t?t.node:s.model.nodes.findIndex(e=>e.name===t.target);if(n<0)continue;let r=s.model.nodes[n];if(e===`weights`){let t=s.model.primitives.find(e=>e.nodeIndex===n);if(!t)continue;l=this.binding(r,e,t.weights,e=>{for(let t=0;t<e.length;t++)s.setMorph(n,t,e[t])})}else{let t=r.engine.store.transforms,n=r.id,i=e===`translation`?[t.x[n],t.y[n],t.z[n]]:e===`scale`?[t.sx[n],t.sy[n],t.sz[n]]:[t.qx[n],t.qy[n],t.qz[n],t.qw[n]];l=this.binding(r,e,i,t=>{e===`translation`?r.setPosition(t):e===`scale`?r.setScale(t):r.setQuaternion(Array.from(t))},e===`rotation`,e===`scale`,()=>e===`translation`?[t.x[n],t.y[n],t.z[n]]:e===`scale`?[t.sx[n],t.sy[n],t.sz[n]]:[t.qx[n],t.qy[n],t.qz[n],t.qw[n]])}}else throw o(`Transform tracks need a Skeleton or Animation root; use bound property tracks on plain objects`);if(`node`in t){let n=new Float32Array(t.width);c.push({binding:l,sample:r=>a(t.times,t.values,t.width,r,t.interpolation,e===`rotation`,n)})}else{let e=new Float64Array(t.values.length/t.times.length);c.push({binding:l,sample:n=>i(t,n,e)})}}let u=l?e.properties:`bind`in e&&e.bind?(e.bound??=e.bind()).properties:void 0;for(let e of u??[])this.property(e,c);return c}property(e,t){let n=this.binding(e.target,`property:`+(e.property??e.name),e.read(),t=>e.write(t),e.type===`quaternion`,!1,()=>e.read()),r=new Float64Array(e.size);t.push({binding:n,sample:t=>i(e,t,r)})}bindDiscrete(e){return f(e)?e.tracks.map(e=>{let t=this.discreteBindings.get(e.target);t||this.discreteBindings.set(e.target,t=/* @__PURE__ */ new Map);let n=t.get(e.property);if(!n){let r=e.read();n={base:r,value:r,total:0,winner:-1/0,applied:!1,channel:e},t.set(e.property,n)}else if(typeof n.base!=typeof e.read())throw o(`Categorical binding types disagree; use the same value type for one property`);return{binding:n,sample:t=>e.sample(t)}}):[]}accumulateDiscrete(e,t,n){if(typeof t!=`boolean`&&typeof t!=`string`||typeof t!=typeof e.base)throw o(`Categorical channel changed value type; return the original boolean or string type`);e.total+=n,n>=e.winner&&(e.winner=n,e.value=t)}},v=0;export{d as AdditiveAnimationBlendMode,g as AnimationAction,_ as AnimationMixer,s as LoopOnce,l as LoopPingPong,c as LoopRepeat,u as NormalAnimationBlendMode};
@@ -1,5 +1,6 @@
1
1
  import type { EngineKernel } from '@margoengine/core';
2
2
  import type { Engine, EnginePlugin, FrameGraph } from '@margoengine/core/extension';
3
+ import type { PBRPrimitive } from '@margoengine/gltf/pbr';
3
4
  import type { Animation } from './index.js';
4
5
  /** Options for {@link MorphWeightPlayer}. */
5
6
  export interface MorphWeightOptions {
@@ -14,12 +15,14 @@ export interface MorphWeightMember {
14
15
  speed?: number;
15
16
  }
16
17
  /** Weight tracks sampled per thread; the arithmetic is `sampleTrackInto`'s, term for term. */
17
- export declare const morphWeightShader = "\nstruct Track {times:u32,keys:u32,values:u32,width:u32,mode:u32,pad0:u32,pad1:u32,pad2:u32}\nstruct Item {weight:u32,track:u32,component:u32,member:u32}\nstruct Params {time:f32,duration:f32,loops:u32,pad:u32}\n@group(0) @binding(0) var<uniform> p:Params;\n@group(0) @binding(1) var<storage,read> tracks:array<Track>;\n@group(0) @binding(2) var<storage,read> times:array<f32>;\n@group(0) @binding(3) var<storage,read> values:array<f32>;\n@group(0) @binding(4) var<storage,read> items:array<Item>;\n@group(0) @binding(5) var<storage,read> members:array<vec2f>;\n@group(0) @binding(6) var<storage,read_write> weights:array<f32>;\n@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id:vec3u,@builtin(num_workgroups) groups:vec3u) {\n let i=id.y*groups.x*64u+id.x;\n if(i>=arrayLength(&items)){return;}\n let item=items[i];let member=members[item.member];let track=tracks[item.track];\n var at=p.time*member.y+member.x;\n if(p.loops>0u&&p.duration>0.0) {\n\n at=at-floor(at/p.duration)*p.duration;\n if(at<0.0){at+=p.duration;}\n if(at>=p.duration){at-=p.duration;}\n } else {at=clamp(at,0.0,p.duration);}\n var lo=0u;var hi=track.keys-1u;\n while(lo<hi) {\n let mid=(lo+hi+1u)/2u;\n if(times[track.times+mid]<=at){lo=mid;}else{hi=mid-1u;}\n }\n let a=lo;let b=min(a+1u,track.keys-1u);\n let span=times[track.times+b]-times[track.times+a];\n var t=0.0;\n if(span>0.0){t=clamp((at-times[track.times+a])/span,0.0,1.0);}\n let w=track.width;let c=item.component;let cubic=track.mode==2u;\n let ai=track.values+(a*select(1u,3u,cubic)+select(0u,1u,cubic))*w+c;\n let bi=track.values+(b*select(1u,3u,cubic)+select(0u,1u,cubic))*w+c;\n var out=values[ai];\n if(track.mode!=0u&&a!=b) {\n if(cubic) {\n let t2=t*t;let t3=t2*t;\n out=(2.0*t3-3.0*t2+1.0)*values[ai]+(t3-2.0*t2+t)*span*values[track.values+(a*3u+2u)*w+c]\n +(-2.0*t3+3.0*t2)*values[bi]+(t3-t2)*span*values[track.values+b*3u*w+c];\n } else {out=values[ai]*(1.0-t)+values[bi]*t;}\n }\n weights[item.weight]=out;\n}\n";
18
+ export declare const morphWeightShader = "\nstruct Track {times:u32,keys:u32,values:u32,width:u32,mode:u32,pad0:u32,pad1:u32,pad2:u32}\nstruct Item {weight:u32,track:u32,component:u32,member:u32}\nstruct Params {time:f32,duration:f32,loops:u32,pad:u32}\n@group(0) @binding(0) var<uniform> p:Params;\n@group(0) @binding(1) var<storage,read> tracks:array<Track>;\n@group(0) @binding(2) var<storage,read> times:array<f32>;\n@group(0) @binding(3) var<storage,read> values:array<f32>;\n@group(0) @binding(4) var<storage,read> items:array<Item>;\n@group(0) @binding(5) var<storage,read> members:array<vec2f>;\n@group(0) @binding(6) var<storage,read_write> weights:array<f32>;\n@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id:vec3u,@builtin(num_workgroups) groups:vec3u) {\n let i=id.y*groups.x*64u+id.x;\n if(i>=arrayLength(&items)){return;}\n let item=items[i];let member=members[item.member];let track=tracks[item.track];\n var at=p.time*member.y+member.x;\n if(p.loops>0u&&p.duration>0.0) {\n\n at=at-floor(at/p.duration)*p.duration;\n if(at<0.0){at+=p.duration;}\n if(at>=p.duration){at-=p.duration;}\n } else {at=clamp(at,0.0,p.duration);}\n\n\n let last=max(track.keys,1u)-1u;var lo=0u;var hi=last;\n while(lo<hi) {\n let mid=lo+(hi-lo+1u)/2u;\n if(times[track.times+mid]<=at){lo=mid;}else{hi=mid-1u;}\n }\n let a=lo;let b=min(a+1u,last);\n let span=times[track.times+b]-times[track.times+a];\n var t=0.0;\n if(span>0.0){t=clamp((at-times[track.times+a])/span,0.0,1.0);}\n let w=track.width;let c=item.component;let cubic=track.mode==2u;\n let ai=track.values+(a*select(1u,3u,cubic)+select(0u,1u,cubic))*w+c;\n let bi=track.values+(b*select(1u,3u,cubic)+select(0u,1u,cubic))*w+c;\n var out=values[ai];\n if(track.mode!=0u&&a!=b) {\n if(cubic) {\n let t2=t*t;let t3=t2*t;\n out=(2.0*t3-3.0*t2+1.0)*values[ai]+(t3-2.0*t2+t)*span*values[track.values+(a*3u+2u)*w+c]\n +(-2.0*t3+3.0*t2)*values[bi]+(t3-t2)*span*values[track.values+b*3u*w+c];\n } else {out=values[ai]*(1.0-t)+values[bi]*t;}\n }\n weights[item.weight]=out;\n}\n";
18
19
  /**
19
20
  * Plays the morph weight tracks of one glTF clip on many copies of a model with no per-copy CPU work: the tracks upload
20
21
  * once, and each frame one compute dispatch per deformation buffer page samples every copy's weights from the player's
21
22
  * time and that copy's offset and speed. Only weights are driven: a copy's `Animation` keeps playing its own clip for
22
- * the body, and weights the player drives are overwritten each frame, so `setMorph` on them has no effect.
23
+ * the body, and weights the player drives are overwritten each frame, so `setMorph` on them has no effect. A
24
+ * synchronous raycast (`@margoengine/bvh`) hits a copy at the weights the player draws, sampled on the CPU on demand
25
+ * with the shader's arithmetic; `remove` writes the weights last drawn into the copy's `primitive.weights`.
23
26
  *
24
27
  * @example
25
28
  * ```ts
@@ -35,7 +38,9 @@ export declare class MorphWeightPlayer implements EnginePlugin {
35
38
  /** Rate multiplier for every copy, finite and >= 0. Default 1. */
36
39
  speed: number;
37
40
  playing: boolean;
41
+ /** Each copy's offset and speed, and the player time its weights were last drawn at (unset before a dispatch). */
38
42
  private readonly members;
43
+ private sample;
39
44
  private readonly loop;
40
45
  private engine?;
41
46
  private gpu?;
@@ -53,8 +58,21 @@ export declare class MorphWeightPlayer implements EnginePlugin {
53
58
  private tracksOf;
54
59
  /** Adds a copy, or changes its offset and speed. Every copy must come from one asset: they share the tracks. */
55
60
  add(animation: Animation, { offset, speed }?: MorphWeightMember): this;
56
- /** Stops driving a copy; its weights stay at the last value the GPU wrote until something else writes them. */
61
+ /**
62
+ * Stops driving a copy. Its weights on the GPU stay at the last value the player wrote until something else writes
63
+ * them, and that value goes into the copy's `primitive.weights`, so they say what is drawn.
64
+ */
57
65
  remove(animation: Animation): boolean;
66
+ /** Gives a copy's weights back to its `primitive.weights`: the samples last drawn, if any were. */
67
+ private handBack;
68
+ /** The weights this player's dispatch writes this frame for `primitive` of a copy, into `out` (Animation's CPU pose). */
69
+ weightsInto(animation: Animation, primitive: PBRPrimitive, out: Float32Array): void;
70
+ /**
71
+ * `morphWeightShader` on the CPU at player time `time`: the copy's float32 time, wrapped as `time % duration` (the
72
+ * shader's corrected f32 wrap lands there), then every track of the primitive's node sampled by `sampleTrackInto`,
73
+ * whose arithmetic the shader repeats term for term. Weights no track drives keep their value in `out`.
74
+ */
75
+ private sampleInto;
58
76
  setup(engine: Engine): void;
59
77
  onPreUpdate(delta: number): void;
60
78
  /** Moves `time` by `delta` seconds times `speed` when playing; the weights pass samples it, so a seek replays it. */
package/dist/morph-gpu.js CHANGED
@@ -1,7 +1,7 @@
1
- // @margo/core-built 0.1.0
1
+ // @margo/core-built 1.0.0
2
2
  import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
3
 
4
- import{t as e}from"./require-webgpu-Jrqt3Xy4.js";import{MargoError as t}from"@margoengine/math/errors";var n=`
4
+ import{o as e}from"./sampling-DjDWYqt2.js";import{t}from"./require-webgpu-Jrqt3Xy4.js";import{MargoError as n}from"@margoengine/math/errors";var r=`
5
5
  struct Track {times:u32,keys:u32,values:u32,width:u32,mode:u32,pad0:u32,pad1:u32,pad2:u32}
6
6
  struct Item {weight:u32,track:u32,component:u32,member:u32}
7
7
  struct Params {time:f32,duration:f32,loops:u32,pad:u32}
@@ -23,12 +23,14 @@ struct Params {time:f32,duration:f32,loops:u32,pad:u32}
23
23
  if(at<0.0){at+=p.duration;}
24
24
  if(at>=p.duration){at-=p.duration;}
25
25
  } else {at=clamp(at,0.0,p.duration);}
26
- var lo=0u;var hi=track.keys-1u;
26
+
27
+
28
+ let last=max(track.keys,1u)-1u;var lo=0u;var hi=last;
27
29
  while(lo<hi) {
28
- let mid=(lo+hi+1u)/2u;
30
+ let mid=lo+(hi-lo+1u)/2u;
29
31
  if(times[track.times+mid]<=at){lo=mid;}else{hi=mid-1u;}
30
32
  }
31
- let a=lo;let b=min(a+1u,track.keys-1u);
33
+ let a=lo;let b=min(a+1u,last);
32
34
  let span=times[track.times+b]-times[track.times+a];
33
35
  var t=0.0;
34
36
  if(span>0.0){t=clamp((at-times[track.times+a])/span,0.0,1.0);}
@@ -45,4 +47,4 @@ struct Params {time:f32,duration:f32,loops:u32,pad:u32}
45
47
  }
46
48
  weights[item.weight]=out;
47
49
  }
48
- `,r={STEP:0,LINEAR:1,CUBICSPLINE:2},i=8,a=0,o=class o{coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);static attach(e,t=0,n){__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));let r=new o(t,n);return e.use(r),r}constructor(e=0,{loop:t=!0}={}){if(this.clip=e,this.name=`morph-gpu:`+a++,this.time=0,this.speed=1,this.playing=!0,this.members=/* @__PURE__ */ new Map,this.dirty=!0,this.disposed=!1,this.params=/* @__PURE__ */ new ArrayBuffer(16),this.paramFloats=new Float32Array(this.params),this.paramWords=new Uint32Array(this.params),typeof t!=`boolean`)throw TypeError(`MorphWeightPlayer loop must be a boolean`);if(typeof e!=`string`&&!(Number.isInteger(e)&&e>=0))throw RangeError(`MorphWeightPlayer clip must be a clip name or an index from animation.clips`);this.loop=t}get count(){return this.members.size}tracksOf(e){let t=e.clips,n=t[typeof this.clip==`string`?t.findIndex(e=>e.name===this.clip):this.clip];if(!n)throw RangeError(`Unknown animation clip; pass a clip name or an index from animation.clips`);let r=n.tracks.filter(e=>e.path===`weights`);if(!r.length)throw RangeError(`Clip ${n.name} has no morph weight tracks; pick a clip that has them`);return{duration:n.duration,tracks:r}}add(e,{offset:n=0,speed:r=1}={}){if(this.disposed)throw new t(`disposed`,`MorphWeightPlayer is disposed; create a new one`);if(!Number.isFinite(n)||!Number.isFinite(r)||r<0)throw RangeError(`Invalid morph member; offset must be finite and speed a finite number >= 0`);let i=this.members.keys().next().value;if(i&&i!==e&&i.model.asset!==e.model.asset)throw TypeError(`MorphWeightPlayer copies must share one asset; clone them with cloneModel`);return this.tracksOf(e),e.gpuWeights=!0,this.members.set(e,{offset:n,speed:r}),this.dirty=!0,this}remove(e){let t=this.members.delete(e);return this.dirty||=t,t}setup(n){if(this.disposed)throw new t(`disposed`,`MorphWeightPlayer is disposed; create a new player before attaching`);e(n,`MorphWeightPlayer`),this.engine=n}onPreUpdate(e){this.advanceTime(e)}advanceTime(e){if(!Number.isFinite(e)||e<0)throw RangeError(`Invalid animation delta; pass a finite delta >= 0 seconds`);if(!Number.isFinite(this.speed)||this.speed<0)throw RangeError(`Invalid morph player speed; use a finite number >= 0`);this.playing&&!this.disposed&&(this.time+=e*this.speed)}registerPasses(e){e.add({name:this.name,order:-11,execute:e=>this.evaluate(e)})}live(){for(let e of this.members.keys())(e.disposed||e.model.disposed)&&(this.members.delete(e),this.dirty=!0);return[...this.members.keys()]}upload(e,t){let n=e.createBuffer({size:Math.max(16,Math.ceil(t.byteLength/4)*4),usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});return e.queue.writeBuffer(n,0,t),n}prepare(e,t){let{tracks:a}=this.tracksOf(t),o=new Uint32Array(a.length*i),s=0,c=0;a.forEach((e,t)=>{o.set([s,e.times.length,c,e.width,r[e.interpolation]],t*i),s+=e.times.length,c+=e.values.length});let l=new Float32Array(s),u=new Float32Array(c);return a.forEach((e,t)=>{l.set(e.times,o[t*i]),u.set(e.values,o[t*i+2])}),{device:e,pipeline:e.createComputePipeline({layout:`auto`,compute:{module:e.createShaderModule({code:n}),entryPoint:`main`}}),params:e.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),tracks:this.upload(e,o),times:this.upload(e,l),values:this.upload(e,u),pages:[],version:-1}}dropPages(e){for(let t of e.pages)t.items.destroy();e.pages=[],e.members?.destroy(),e.members=void 0}build(e,t,n){this.dropPages(e);let{tracks:r}=this.tracksOf(t[0]),i=/* @__PURE__ */ new Map,a=new Float32Array(t.length*2);t.forEach((e,t)=>{let n=this.members.get(e);a[t*2]=n.offset,a[t*2+1]=n.speed;for(let n of e.resources){let e=n.weights,a=i.get(e)??[];i.set(e,a),r.forEach((e,r)=>{if(e.node===n.primitive.nodeIndex)for(let i=0;i<e.width;i++)a.push(n.slot.weights.offset+i,r,i,t)})}}),e.members=this.upload(e.device,a);let o=e.device.limits.maxComputeWorkgroupsPerDimension??65535;for(let[t,n]of i){if(!n.length)continue;let r=this.upload(e.device,Uint32Array.from(n)),i=Math.ceil(n.length/4/64),a=Math.min(i,o);e.pages.push({items:r,x:a,y:Math.ceil(i/a),group:e.device.createBindGroup({layout:e.pipeline.getBindGroupLayout(0),entries:[e.params,e.tracks,e.times,e.values,r,e.members,t].map((e,t)=>({binding:t,resource:{buffer:e}}))})})}e.version=n,this.dirty=!1}evaluate(e){if(e.backend!==`webgpu`)return;let t=this.live(),n=t[0]?.arena;if(!n)return;this.gpu&&this.gpu.device!==e.device&&this.release();let r=this.gpu??=this.prepare(e.device,t[0]);if((this.dirty||r.version!==n.version)&&this.build(r,t,n.version),!r.pages.length)return;this.paramFloats[0]=this.time,this.paramFloats[1]=this.tracksOf(t[0]).duration,this.paramWords[2]=+this.loop,e.device.queue.writeBuffer(r.params,0,this.params);let i=e.encoder.beginComputePass();try{i.setPipeline(r.pipeline);for(let e of r.pages)i.setBindGroup(0,e.group),i.dispatchWorkgroups(e.x,e.y)}finally{i.end()}}release(){let e=this.gpu;if(e){this.dropPages(e);for(let t of[e.params,e.tracks,e.times,e.values])t.destroy();this.gpu=void 0,this.dirty=!0}}onDeviceRestored(){this.gpu=void 0,this.dirty=!0}dispose(){this.disposed||(this.disposed=!0,this.engine?.sceneOf(this)?.removePlugin(this.name),this.release(),this.members.clear())}[Symbol.dispose??Symbol()](){this.dispose()}};export{o as MorphWeightPlayer,n as morphWeightShader};
50
+ `,i={STEP:0,LINEAR:1,CUBICSPLINE:2},a=8,o=0,s=class s{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static attach(e,t=0,n){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));let r=new s(t,n);return e.use(r),r}constructor(e=0,{loop:t=!0}={}){if(this.clip=e,this.name=`morph-gpu:`+o++,this.time=0,this.speed=1,this.playing=!0,this.members=/* @__PURE__ */ new Map,this.sample=/* @__PURE__ */ new Float32Array,this.dirty=!0,this.disposed=!1,this.params=/* @__PURE__ */ new ArrayBuffer(16),this.paramFloats=new Float32Array(this.params),this.paramWords=new Uint32Array(this.params),typeof t!=`boolean`)throw TypeError(`MorphWeightPlayer loop must be a boolean`);if(typeof e!=`string`&&!(Number.isInteger(e)&&e>=0))throw RangeError(`MorphWeightPlayer clip must be a clip name or an index from animation.clips`);this.loop=t}get count(){return this.members.size}tracksOf(e){let t=e.clips,n=t[typeof this.clip==`string`?t.findIndex(e=>e.name===this.clip):this.clip];if(!n)throw RangeError(`Unknown animation clip; pass a clip name or an index from animation.clips`);let r=n.tracks.filter(e=>e.path===`weights`);if(!r.length)throw RangeError(`Clip ${n.name} has no morph weight tracks; pick a clip that has them`);return{duration:n.duration,tracks:r}}add(e,{offset:t=0,speed:r=1}={}){if(this.disposed)throw new n(`disposed`,`MorphWeightPlayer is disposed; create a new one`);if(!Number.isFinite(t)||!Number.isFinite(r)||r<0)throw RangeError(`Invalid morph member; offset must be finite and speed a finite number >= 0`);let i=this.members.keys().next().value;if(i&&i!==e&&i.model.asset!==e.model.asset)throw TypeError(`MorphWeightPlayer copies must share one asset; clone them with cloneModel`);return this.tracksOf(e),e.weightSource=this,this.members.set(e,{offset:t,speed:r,drawn:this.members.get(e)?.drawn}),this.dirty=!0,this}remove(e){let t=this.members.get(e);return t?(this.handBack(e,t),this.members.delete(e),this.dirty=!0,!0):!1}handBack(e,t){if(t.drawn!==void 0)for(let n of e.resources)this.sampleInto(e,t,n.primitive,n.primitive.weights,t.drawn);e.weightSource===this&&(e.weightSource=void 0)}weightsInto(e,t,n){let r=this.members.get(e);r&&this.sampleInto(e,r,t,n,this.time)}sampleInto(t,n,r,i,a){let{duration:o,tracks:s}=this.tracksOf(t),c=Math.fround,l=c(o),u=c(c(c(a)*c(n.speed))+c(n.offset)),d=this.loop&&l>0?(u%l+l)%l:Math.min(Math.max(u,0),l);for(let t of s)t.node===r.nodeIndex&&(this.sample.length!==t.width&&(this.sample=new Float32Array(t.width)),e(t.times,t.values,t.width,d,t.interpolation,!1,this.sample),i.set(this.sample.subarray(0,Math.min(t.width,i.length))))}setup(e){if(this.disposed)throw new n(`disposed`,`MorphWeightPlayer is disposed; create a new player before attaching`);t(e,`MorphWeightPlayer`),this.engine=e}onPreUpdate(e){this.advanceTime(e)}advanceTime(e){if(!Number.isFinite(e)||e<0)throw RangeError(`Invalid animation delta; pass a finite delta >= 0 seconds`);if(!Number.isFinite(this.speed)||this.speed<0)throw RangeError(`Invalid morph player speed; use a finite number >= 0`);this.playing&&!this.disposed&&(this.time+=e*this.speed)}registerPasses(e){e.add({name:this.name,order:-11,execute:e=>this.evaluate(e)})}live(){for(let e of this.members.keys())(e.disposed||e.model.disposed)&&(this.members.delete(e),this.dirty=!0);return[...this.members.keys()]}upload(e,t){let n=e.createBuffer({size:Math.max(16,Math.ceil(t.byteLength/4)*4),usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});return e.queue.writeBuffer(n,0,t),n}prepare(e,t){let{tracks:n}=this.tracksOf(t),o=new Uint32Array(n.length*a),s=0,c=0;n.forEach((e,t)=>{o.set([s,e.times.length,c,e.width,i[e.interpolation]],t*a),s+=e.times.length,c+=e.values.length});let l=new Float32Array(s),u=new Float32Array(c);return n.forEach((e,t)=>{l.set(e.times,o[t*a]),u.set(e.values,o[t*a+2])}),{device:e,pipeline:e.createComputePipeline({layout:`auto`,compute:{module:e.createShaderModule({code:r}),entryPoint:`main`}}),params:e.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),tracks:this.upload(e,o),times:this.upload(e,l),values:this.upload(e,u),pages:[],version:-1}}dropPages(e){for(let t of e.pages)t.items.destroy();e.pages=[],e.members?.destroy(),e.members=void 0}build(e,t,n){this.dropPages(e);let{tracks:r}=this.tracksOf(t[0]),i=/* @__PURE__ */ new Map,a=new Float32Array(t.length*2);t.forEach((e,t)=>{let n=this.members.get(e);a[t*2]=n.offset,a[t*2+1]=n.speed;for(let n of e.resources){let e=n.weights,a=i.get(e)??[];i.set(e,a),r.forEach((e,r)=>{if(e.node===n.primitive.nodeIndex)for(let i=0;i<e.width;i++)a.push(n.slot.weights.offset+i,r,i,t)})}}),e.members=this.upload(e.device,a);let o=e.device.limits.maxComputeWorkgroupsPerDimension??65535;for(let[t,n]of i){if(!n.length)continue;let r=this.upload(e.device,Uint32Array.from(n)),i=Math.ceil(n.length/4/64),a=Math.min(i,o);e.pages.push({items:r,x:a,y:Math.ceil(i/a),group:e.device.createBindGroup({layout:e.pipeline.getBindGroupLayout(0),entries:[e.params,e.tracks,e.times,e.values,r,e.members,t].map((e,t)=>({binding:t,resource:{buffer:e}}))})})}e.version=n,this.dirty=!1}evaluate(e){if(e.backend!==`webgpu`)return;let t=this.live(),n=t[0]?.arena;if(!n)return;this.gpu&&this.gpu.device!==e.device&&this.release();let r=this.gpu??=this.prepare(e.device,t[0]);if((this.dirty||r.version!==n.version)&&this.build(r,t,n.version),!r.pages.length)return;this.paramFloats[0]=this.time,this.paramFloats[1]=this.tracksOf(t[0]).duration,this.paramWords[2]=+this.loop,e.device.queue.writeBuffer(r.params,0,this.params);let i=e.encoder.beginComputePass();try{i.setPipeline(r.pipeline);for(let e of r.pages)i.setBindGroup(0,e.group),i.dispatchWorkgroups(e.x,e.y)}finally{i.end()}for(let e of this.members.values())e.drawn=this.time}release(){let e=this.gpu;if(e){this.dropPages(e);for(let t of[e.params,e.tracks,e.times,e.values])t.destroy();this.gpu=void 0,this.dirty=!0}}onDeviceRestored(){this.gpu=void 0,this.dirty=!0}dispose(){if(!this.disposed){this.disposed=!0,this.engine?.sceneOf(this)?.removePlugin(this.name),this.release();for(let[e,t]of this.members)this.handBack(e,t);this.members.clear()}}[Symbol.dispose??Symbol()](){this.dispose()}};export{s as MorphWeightPlayer,r as morphWeightShader};
@@ -0,0 +1,29 @@
1
+ /** One morph attribute's moved rows (ascending file vertices) and their deltas, three floats each. */
2
+ export interface MorphRows {
3
+ readonly rows: Uint32Array;
4
+ readonly values: Float32Array;
5
+ }
6
+ /**
7
+ * The table, in the 32-bit words the deformation shader reads. Words 0 to `count` are each vertex's first entry, then
8
+ * the end (row pointers); the entries start at word `header`, a multiple of 4. An entry is `stride` words: the
9
+ * position delta and the target's index (bits, word 3), the normal delta and a zero, and with `stride` 12 the tangent
10
+ * delta and a zero. Float words are Float32 bits.
11
+ */
12
+ export interface MorphTable {
13
+ readonly count: number;
14
+ readonly targets: number;
15
+ /** Words per entry: 8 (position and normal) or 12 (with the tangent). */
16
+ readonly stride: 8 | 12;
17
+ readonly header: number;
18
+ readonly words: Uint32Array;
19
+ /** `words` read as floats. */
20
+ readonly floats: Float32Array;
21
+ }
22
+ /** Words before the entries: one row pointer per vertex and the end, rounded up to a vec4. */
23
+ export declare const morphHeader: (count: number) => number;
24
+ /**
25
+ * Builds the table of `count` vertices from each target's attributes (position, normal, tangent; undefined where the
26
+ * target has none) as `@margoengine/gltf` `sparseAccessor` reads them, rows in the file's vertices. With `vertexMap`
27
+ * (a part of a split primitive) vertex k of the table is the file's vertex `vertexMap[k]`.
28
+ */
29
+ export declare function morphTable(attributes: readonly (readonly (MorphRows | undefined)[])[], count: number, sourceCount: number, stride: 8 | 12, vertexMap?: Uint32Array): MorphTable;
package/dist/playback.js CHANGED
@@ -1,4 +1,4 @@
1
- // @margo/core-built 0.1.0
1
+ // @margo/core-built 1.0.0
2
2
  import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
3
 
4
- import{n as e}from"./errors-t1ewumJS.js";import{LoopOnce as t,LoopPingPong as n,LoopRepeat as r}from"./mixer.js";import{Animation as i}from"@margoengine/animation";var a=class extends Event{constructor(e,t,n,r){super(e),this.animation=t,this.loopDelta=n,this.direction=r}},o=t=>Object.assign(e(t,`arguments`),{code:`arguments`}),s=(e,t)=>{if(!Number.isFinite(e))throw o(`Invalid playback ${t}; pass finite seconds or a rate`);return e},c=()=>new DOMException(`Animation playback cancelled; start another play or wait on a live player`,`AbortError`),l=class e extends i{constructor(e,t={}){super(e,t),this.cursor=0,this.completed=0,this.settled=!1,this.started=!1,this.terminal=!1,this.released=!1,this.events=new EventTarget,this.abort=()=>this.dispose(),this.loopMode=t.loopMode??(t.loop===!1?2200:2201),this.repetitions=t.repetitions??1/0,this.timeScale=t.timeScale??1,this.validatePlayback(),this.newPromise(),this.signal=t.signal,t.signal?.addEventListener(`abort`,this.abort,{once:!0}),t.signal?.aborted&&this.dispose()}static attach(t,n={}){__margoAssertCore(t,__margoCoreRequirement("0.1.0",import.meta.url));let r=new e(t,n);if(!n.signal?.aborted)try{t.root.scene.use(r)}catch(e){throw r.dispose(),e}return r}get finished(){return this.promise}newPromise(){this.settled=!1,this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t}),this.promise.catch(()=>{})}validatePlayback(){if(![2200,2201,2202].includes(this.loopMode)||this.repetitions!==1/0&&(!Number.isSafeInteger(this.repetitions)||this.repetitions<1))throw o(`Invalid playback loop; choose a loop mode and a positive integer traversal count or Infinity`);s(this.timeScale,`timeScale`)}play(e=0){return super.play(e),this.started&&(this.settled||this.reject(c()),this.newPromise()),this.started=!0,this.completed=0,this.terminal=!1,this.cursor=this.timeScale<0?this.clips[this.clip].duration:0,this.pose(this.cursor,1,this.timeScale<0),this}setLoop(e,n=1/0){let r=this.loopMode,i=this.repetitions;this.loopMode=e,this.repetitions=n;try{this.validatePlayback()}catch(e){throw this.loopMode=r,this.repetitions=i,e}return this.options.loop=e!==t,this}seek(e){if(s(e,`seek`)<0)throw o(`Playback seek must be nonnegative; pass total clip seconds >= 0`);return this.cursor=e,this.completed=0,this.terminal=!1,this.pose(e,this.timeScale<0?-1:1,!1),this}mode(){return this.loopMode===2201&&this.options.loop===!1?t:this.loopMode}pose(e,t,n){let r=this.clips[this.clip]?.duration??0,i=this.mode(),a=0;if(r>0){if(i===2200)a=Math.max(0,Math.min(r,e));else if(i===2202){let t=2*r,n=(e%t+t)%t;a=n<=r?n:t-n}else a=n?t>0?r:0:(e%r+r)%r}let o=this.options.loop;this.options.loop=!1;try{super.seek(a)}finally{this.options.loop=o}}onPreUpdate(e){if(this.model.disposed){this.dispose();return}this.validatePlayback();let t=this.playing;this.playing=!1;try{super.onPreUpdate(0)}finally{this.playing=t}let n=this.stepClock(e),r=this.owed;if(r&&(this.owed=void 0,this.pose(r[0],r[1],r[2])),!n)return;let[i,o,s]=n;s?this.events.dispatchEvent(s):i&&this.events.dispatchEvent(new a(`loop`,this,i*o,o))}advanceTime(e){this.validatePlayback(),this.stepClock(e)}stepClock(e){if(!this.playing||this.terminal||this.disposed)return;if(s(e,`delta`),e<0)throw o(`Playback delta must be nonnegative; reverse with timeScale`);let t=s(e*(this.options.speed??1)*this.timeScale,`advance`);if(t===0&&(this.clips[this.clip]?.duration??0)>0)return;let n=this.clips[this.clip]?.duration??0,r=t<0?-1:1,i=this.mode(),c=s(this.cursor+t,`clock`),l=0,u=!1;if(n===0)c=0,u=!0;else if(i===2200)u=r>0?c>=n:c<=0,c=Math.max(0,Math.min(n,c));else{if(l=r>0?Math.floor(c/n)-Math.floor(this.cursor/n):Math.ceil(this.cursor/n)-Math.ceil(c/n),!Number.isSafeInteger(l))throw o(`Playback crossed too many loops to count exactly; use a smaller delta or rate`);let e=this.repetitions-this.completed;l>=e&&(c=(r>0?Math.floor(this.cursor/n)+e:Math.ceil(this.cursor/n)-e)*n,l=e,u=!0)}if(this.started=!0,this.cursor=c,this.completed+=l,this.owed=[c,r,u],!u)return[l,r,void 0];this.terminal=!0,this.playing=!1,this.settled=!0;let d=new a(`finished`,this,0,r);return this.resolve(d),[l,r,d]}on(e,t,n={}){return this.events.addEventListener(e,t,n),()=>this.events.removeEventListener(e,t)}addEventListener(e,t,n){this.events.addEventListener(e,t,n)}removeEventListener(e,t,n){this.events.removeEventListener(e,t,n)}waitForFinished({signal:e}={}){return e?e.aborted?Promise.reject(e.reason??c()):new Promise((t,n)=>{let r=()=>{e.removeEventListener(`abort`,r),n(e.reason??c())};e.addEventListener(`abort`,r,{once:!0}),this.finished.then(n=>{e.removeEventListener(`abort`,r),t(n)},t=>{e.removeEventListener(`abort`,r),n(t)})}):this.finished}dispose(){this.released||(this.released=!0,this.playing=!1,this.signal?.removeEventListener(`abort`,this.abort),this.signal=void 0,this.settled||(this.settled=!0,this.reject(c())),super.dispose())}};export{l as Animation,l as PlaybackAnimation,t as LoopOnce,n as LoopPingPong,r as LoopRepeat,a as PlaybackEvent};
4
+ import{n as e}from"./errors-t1ewumJS.js";import{LoopOnce as t,LoopPingPong as n,LoopRepeat as r}from"./mixer.js";import{Animation as i}from"@margoengine/animation";var a=class extends Event{constructor(e,t,n,r){super(e),this.animation=t,this.loopDelta=n,this.direction=r}},o=t=>Object.assign(e(t,`arguments`),{code:`arguments`}),s=(e,t)=>{if(!Number.isFinite(e))throw o(`Invalid playback ${t}; pass finite seconds or a rate`);return e},c=()=>new DOMException(`Animation playback cancelled; start another play or wait on a live player`,`AbortError`),l=class e extends i{constructor(e,t={}){super(e,t),this.cursor=0,this.completed=0,this.settled=!1,this.started=!1,this.terminal=!1,this.released=!1,this.events=new EventTarget,this.abort=()=>this.dispose(),this.loopMode=t.loopMode??(t.loop===!1?2200:2201),this.repetitions=t.repetitions??1/0,this.timeScale=t.timeScale??1,this.validatePlayback(),this.newPromise(),this.signal=t.signal,t.signal?.addEventListener(`abort`,this.abort,{once:!0}),t.signal?.aborted&&this.dispose()}static attach(t,n={}){__margoAssertCore(t,__margoCoreRequirement("1.0.0",import.meta.url));let r=new e(t,n);if(!n.signal?.aborted)try{t.root.scene.use(r)}catch(e){throw r.dispose(),e}return r}get finished(){return this.promise}newPromise(){this.settled=!1,this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t}),this.promise.catch(()=>{})}validatePlayback(){if(![2200,2201,2202].includes(this.loopMode)||this.repetitions!==1/0&&(!Number.isSafeInteger(this.repetitions)||this.repetitions<1))throw o(`Invalid playback loop; choose a loop mode and a positive integer traversal count or Infinity`);s(this.timeScale,`timeScale`)}play(e=0){return super.play(e),this.started&&(this.settled||this.reject(c()),this.newPromise()),this.started=!0,this.completed=0,this.terminal=!1,this.cursor=this.timeScale<0?this.clips[this.clip].duration:0,this.pose(this.cursor,1,this.timeScale<0),this}setLoop(e,n=1/0){let r=this.loopMode,i=this.repetitions;this.loopMode=e,this.repetitions=n;try{this.validatePlayback()}catch(e){throw this.loopMode=r,this.repetitions=i,e}return this.options.loop=e!==t,this}seek(e){if(s(e,`seek`)<0)throw o(`Playback seek must be nonnegative; pass total clip seconds >= 0`);return this.cursor=e,this.completed=0,this.terminal=!1,this.pose(e,this.timeScale<0?-1:1,!1),this}mode(){return this.loopMode===2201&&this.options.loop===!1?t:this.loopMode}pose(e,t,n){let r=this.clips[this.clip]?.duration??0,i=this.mode(),a=0;if(r>0){if(i===2200)a=Math.max(0,Math.min(r,e));else if(i===2202){let t=2*r,n=(e%t+t)%t;a=n<=r?n:t-n}else a=n?t>0?r:0:(e%r+r)%r}let o=this.options.loop;this.options.loop=!1;try{super.seek(a)}finally{this.options.loop=o}}onPreUpdate(e){if(this.model.disposed){this.dispose();return}this.validatePlayback();let t=this.playing;this.playing=!1;try{super.onPreUpdate(0)}finally{this.playing=t}let n=this.stepClock(e),r=this.owed;if(r&&(this.owed=void 0,this.pose(r[0],r[1],r[2])),!n)return;let[i,o,s]=n;s?this.events.dispatchEvent(s):i&&this.events.dispatchEvent(new a(`loop`,this,i*o,o))}advanceTime(e){this.validatePlayback(),this.stepClock(e)}stepClock(e){if(!this.playing||this.terminal||this.disposed)return;if(s(e,`delta`),e<0)throw o(`Playback delta must be nonnegative; reverse with timeScale`);let t=s(e*(this.options.speed??1)*this.timeScale,`advance`);if(t===0&&(this.clips[this.clip]?.duration??0)>0)return;let n=this.clips[this.clip]?.duration??0,r=t<0?-1:1,i=this.mode(),c=s(this.cursor+t,`clock`),l=0,u=!1;if(n===0)c=0,u=!0;else if(i===2200)u=r>0?c>=n:c<=0,c=Math.max(0,Math.min(n,c));else{if(l=r>0?Math.floor(c/n)-Math.floor(this.cursor/n):Math.ceil(this.cursor/n)-Math.ceil(c/n),!Number.isSafeInteger(l))throw o(`Playback crossed too many loops to count exactly; use a smaller delta or rate`);let e=this.repetitions-this.completed;l>=e&&(c=(r>0?Math.floor(this.cursor/n)+e:Math.ceil(this.cursor/n)-e)*n,l=e,u=!0)}if(this.started=!0,this.cursor=c,this.completed+=l,this.owed=[c,r,u],!u)return[l,r,void 0];this.terminal=!0,this.playing=!1,this.settled=!0;let d=new a(`finished`,this,0,r);return this.resolve(d),[l,r,d]}on(e,t,n={}){return this.events.addEventListener(e,t,n),()=>this.events.removeEventListener(e,t)}addEventListener(e,t,n){this.events.addEventListener(e,t,n)}removeEventListener(e,t,n){this.events.removeEventListener(e,t,n)}waitForFinished({signal:e}={}){return e?e.aborted?Promise.reject(e.reason??c()):new Promise((t,n)=>{let r=()=>{e.removeEventListener(`abort`,r),n(e.reason??c())};e.addEventListener(`abort`,r,{once:!0}),this.finished.then(n=>{e.removeEventListener(`abort`,r),t(n)},t=>{e.removeEventListener(`abort`,r),n(t)})}):this.finished}dispose(){this.released||(this.released=!0,this.playing=!1,this.signal?.removeEventListener(`abort`,this.abort),this.signal=void 0,this.settled||(this.settled=!0,this.reject(c())),super.dispose())}};export{l as Animation,l as PlaybackAnimation,t as LoopOnce,n as LoopPingPong,r as LoopRepeat,a as PlaybackEvent};
@@ -1 +1 @@
1
- import{i as e}from"./keyframes-BO50xipp.js";import{a as t,l as n,o as r}from"./gltf-C2HVNxzB.js";import{textureCoordinates as i,textureTransform as a}from"@margoengine/gltf/pbr-model";function o(e,t){return e===1?1:e**t}var s={SCALAR:1,VEC2:2,VEC3:3,VEC4:4},c=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:void 0,l=e=>Array.isArray(e)?e:[],u=(e,t)=>t.split(`/`).reduce((e,t)=>c(e)?.[t],e),d={"pbrMetallicRoughness/baseColorTexture":0,"pbrMetallicRoughness/metallicRoughnessTexture":1,normalTexture:2,occlusionTexture:3,emissiveTexture:4,"extensions/KHR_materials_clearcoat/clearcoatTexture":5,"extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture":6,"extensions/KHR_materials_clearcoat/clearcoatNormalTexture":7,"extensions/KHR_materials_transmission/transmissionTexture":8,"extensions/KHR_materials_sheen/sheenColorTexture":9,"extensions/KHR_materials_sheen/sheenRoughnessTexture":10,"extensions/KHR_materials_specular/specularTexture":11,"extensions/KHR_materials_specular/specularColorTexture":12},f={"pbrMetallicRoughness/baseColorFactor":[`VEC4`,`base`,0],"pbrMetallicRoughness/roughnessFactor":[`SCALAR`,`factors`,0],"pbrMetallicRoughness/metallicFactor":[`SCALAR`,`factors`,1],"normalTexture/scale":[`SCALAR`,`factors`,2,`normalTexture`],"occlusionTexture/strength":[`SCALAR`,`factors`,3,`occlusionTexture`],emissiveFactor:[`VEC3`,`emissive`,0],alphaCutoff:[`SCALAR`,`settings`,1],"extensions/KHR_materials_emissive_strength/emissiveStrength":[`SCALAR`,`strength`,0,`extensions/KHR_materials_emissive_strength`],"extensions/KHR_materials_dispersion/dispersion":[`SCALAR`,`dispersion`,0,`extensions/KHR_materials_dispersion`],"extensions/KHR_materials_clearcoat/clearcoatFactor":[`SCALAR`,`physical`,0],"extensions/KHR_materials_clearcoat/clearcoatRoughnessFactor":[`SCALAR`,`physical`,1],"extensions/KHR_materials_clearcoat/clearcoatNormalTexture/scale":[`SCALAR`,`physical`,2,`extensions/KHR_materials_clearcoat/clearcoatNormalTexture`],"extensions/KHR_materials_transmission/transmissionFactor":[`SCALAR`,`physical`,3],"extensions/KHR_materials_specular/specularColorFactor":[`VEC3`,`physical`,4],"extensions/KHR_materials_specular/specularFactor":[`SCALAR`,`physical`,7],"extensions/KHR_materials_sheen/sheenColorFactor":[`VEC3`,`physical`,8],"extensions/KHR_materials_sheen/sheenRoughnessFactor":[`SCALAR`,`physical`,11],"extensions/KHR_materials_ior/ior":[`SCALAR`,`ext`,1],"extensions/KHR_materials_volume/thicknessFactor":[`SCALAR`,`volume`,0],"extensions/KHR_materials_volume/attenuationColor":[`VEC3`,`volume`,1],"extensions/KHR_materials_volume/attenuationDistance":[`SCALAR`,`volume`,4,`extensions/KHR_materials_volume/attenuationDistance`]},p={color:`VEC3`,intensity:`SCALAR`,range:`SCALAR`,"spot/innerConeAngle":`SCALAR`,"spot/outerConeAngle":`SCALAR`},m={perspective:[`yfov`,`aspectRatio`,`znear`,`zfar`],orthographic:[`xmag`,`ymag`,`znear`,`zfar`]},h=/^\/materials\/\d+\/extensions\/KHR_materials_ior\/ior$/,g=/* @__PURE__ */ new Set([`pbrMetallicRoughness/baseColorFactor`,`emissiveFactor`,`color`]),_=class{constructor(e){this.reason=e}},v=/* @__PURE__ */ new WeakMap,y=e=>{throw new _(e)},b=(i,a,o)=>{let s=i.asset.doc,u=[],d=[],f=[],p=/* @__PURE__ */ new Set,m=[],g=[],y=/* @__PURE__ */ new Set,b=0;a.channels.forEach((e,v)=>{let x=c(e),S=c(x?.target),w=c(S?.extensions),T=c(w?.KHR_animation_pointer)?.pointer;if(S?.path!==`pointer`&&w?.KHR_animation_pointer===void 0){S?.path===`weights`&&typeof S.node==`number`&&p.add(S.node),u.push(e);return}let E=`Animation ${o} channel ${v}`;if(S?.path!==`pointer`||Object.hasOwn(S,`node`)||typeof T!=`string`)throw TypeError(`${E} KHR_animation_pointer needs path 'pointer', no target node and a pointer string; fix the channel target`);if(y.has(T))throw TypeError(`${E} repeats pointer ${T}; use one channel per property`);y.add(T);let D=n(a.samplers[t(x.sampler,a.samplers.length,`sampler`)]),O=r(D.interpolation),k=i.asset.accessor(D.input,`SCALAR`);if(k.some((e,t)=>e<0||t>0&&e<=k[t-1]))throw RangeError(`${E} key times must be nonnegative and strictly increasing; fix the sampler input`);if(b=Math.max(b,k[k.length-1]),h.test(T)){let e=i.asset.accessor(D.output,`SCALAR`),t=O===`CUBICSPLINE`?3:1;for(let n=0;n<k.length;n++)if(e[n*t+(t>>1)]<1)throw RangeError(`${E} pointer ${T} keys an IOR of ${e[n*t+(t>>1)]}; KHR_materials_ior allows animated IORs of 1 or more only`)}let A;try{A=C(i,s,T,E)}catch(e){if(!(e instanceof _))throw e;g.push(`${E}: pointer ${T} ${e.reason}; skipped`);return}if(`path`in A){A.mesh||p.add(A.nodes[0]);for(let e of A.nodes)(A.mesh?f:d).push({node:e,path:A.path,sampler:x.sampler});A.nodes.length||g.push(`${E}: pointer ${T} has no node using the mesh; skipped`);return}let{accessor:j,size:M,bool:N}=A,P=c(l(s.accessors)[D.output]);if(N&&(O!==`STEP`||P?.componentType!==5121||P.normalized))throw TypeError(`${E} pointer ${T} is a boolean; use STEP and an unsigned byte SCALAR accessor`);let F=i.asset.accessor(D.output,j),I=O===`CUBICSPLINE`,L=M*(I?3:1);if(F.length!==k.length*L)throw RangeError(`${E} pointer ${T} has ${F.length/M} output values for ${k.length} keys; key one ${j} per time${I?` with in and out tangents`:``}`);let R=Array.from(k,(e,t)=>{let n=t*L+(I?M:0),r={time:e,value:Array.from(F.subarray(n,n+M)),interpolation:I?`cubicSpline`:O===`STEP`?`discrete`:`linear`};return I&&(r.inTangent=Array.from(F.subarray(n-M,n)),r.outTangent=Array.from(F.subarray(n+M,n+2*M))),r});m.push({target:A,keys:R,pointer:T})});for(let e of f)p.has(e.node)||d.unshift(e);return{ordinary:u,nodes:d,duration:b,warnings:g,...m.length?{bind:()=>{let t=v.get(i);return t||v.set(i,t=/* @__PURE__ */ new Map),e({name:o,tracks:m.map(({target:e,keys:n,pointer:r})=>({target:i,name:r,type:e.type,set:e.make(t),keys:n}))})}}:{}}};function x(e,t){let n=/^\/nodes\/(\d+)\/weights\/(\d+)$/.exec(t);if(n)return t=>{for(let r of e.primitives)r.nodeIndex===+n[1]&&(r.weights[+n[2]]=t[0])};let r;try{r=C(e,e.asset.doc,t,`Behaviour graph`)}catch(e){if(e instanceof _)return;throw e}if(!(`path`in r)){let t=v.get(e);t||v.set(e,t=/* @__PURE__ */ new Map);let n=r.make(t);return e=>n(Float64Array.from(e))}let i=e.nodes[r.nodes[0]],{path:a}=r;if(i&&a!==`weights`)return e=>{a===`rotation`?i.setQuaternion(Array.from(e)):a===`scale`?i.setScale(Array.from(e)):i.setPosition(Array.from(e))}}function S(e,t,n,r,i){if(e===void 0||!/^(0|[1-9]\d*)$/.test(e)||Number(e)>=t)throw TypeError(`${r} pointer ${i} names no ${n} ${e??``}; point at an existing index`);return Number(e)}function C(e,t,n,r){if(!n.startsWith(`/`))throw TypeError(`${r} pointer ${n} is not a JSON pointer; start it with '/'`);let i=n.slice(1).split(`/`).map(e=>e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`)),a=()=>{throw TypeError(`${r} pointer ${n} is not an animatable glTF property; point at a property animations may change`)},o=e=>e.split(`/`).some(e=>e===`extras`||e===`extensions`);i.includes(`extras`)&&y(`targets application-defined extras`);let[d,f,...h]=i,_=h.join(`/`);if(d===`nodes`){let i=S(f,l(t.nodes).length,`node`,r,n);if([`translation`,`rotation`,`scale`,`weights`].includes(_))return{nodes:[i],path:_,mesh:!1};if(_===`extensions/KHR_node_visibility/visible`){c(u(l(t.nodes)[i],`extensions/KHR_node_visibility`))||y(`targets a node without KHR_node_visibility`);let n=e.nodes[i];return{accessor:`SCALAR`,size:1,type:`number`,bool:!0,make:()=>e=>{n.visible=e[0]!==0}}}return o(_)&&y(`targets a node extension this player does not drive`),a()}if(d===`meshes`){let e=S(f,l(t.meshes).length,`mesh`,r,n);return _===`weights`?{nodes:l(t.nodes).flatMap((t,n)=>c(t)?.mesh===e?[n]:[]),path:`weights`,mesh:!0}:(o(_)&&y(`targets a mesh extension this player does not drive`),a())}if(d===`materials`)return w(e,t,S(f,l(t.materials).length,`material`,r,n),_,a);if(d===`cameras`){let i=S(f,l(t.cameras).length,`camera`,r,n),o=c(l(t.cameras)[i]),[s,u,d]=h;if(!m[s]?.includes(u)||d!==void 0)return a();(o.type!==s||!c(o[s]))&&y(`targets ${s} values of a ${String(o.type)} camera`),c(o[s])[u]===void 0&&y(`targets ${u}, which the camera does not define`);let p=e.cameras.filter(e=>c(l(t.nodes)[e.nodeIndex])?.camera===i);return p.length||y(`targets a camera no scene node uses`),{accessor:`SCALAR`,size:1,type:`number`,make:e=>{let t=`camera ${i}`,n=e.get(t)??p.map(e=>{let t={...e[s]};return e[s]=t,t});return e.set(t,n),e=>{for(let t of n)t[u]=e[0]}}}}if(d===`extensions`&&f===`KHR_lights_punctual`&&h[0]===`lights`){let i=l(c(c(t.extensions)?.KHR_lights_punctual)?.lights),o=S(h[1],i.length,`light`,r,n),d=h.slice(2).join(`/`),f=c(i[o]),m=p[d];if(!m)return a();d.startsWith(`spot/`)&&f.type!==`spot`&&y(`targets spot cones of a ${String(f.type)} light`),d===`range`&&f.range===void 0&&y(`targets range, which the light does not define`);let _=e.lights.filter(e=>c(u(l(t.nodes)[e.nodeIndex],`extensions/KHR_lights_punctual`))?.light===o);_.length||y(`targets a light no scene node uses`);let v=d.startsWith(`spot/`)?d.slice(5):d;return{accessor:m,size:s[m],type:g.has(d)?`color`:`number`,make:e=>{if(d===`color`){if(!e.has(`light ${o}`))for(let e of _)e.color=e.color.slice();return e.set(`light ${o}`,!0),e=>{for(let t of _)for(let n=0;n<3;n++)t.color[n]=e[n]}}return e=>{for(let t of _)t[v]=e[0]}}}}return d===`extensions`&&y(`targets ${f}, which this player does not drive`),a()}function w(e,t,n,r,i){let o=c(l(t.materials)[n]),p=[...new Set([...e.primitives,...e.pointsAndLines].filter(e=>e.definition.material===n).map(e=>e.material))],m=/^(.+)\/extensions\/KHR_texture_transform\/(offset|scale|rotation|texCoord)$/.exec(r);if(m){let e=d[m[1]],t=m[2];e===void 0&&y(`targets a texture this player does not map to a live UV transform`),t===`texCoord`&&y(`targets texCoord, an integer UV set this player does not switch`),c(u(o,m[1]))||y(`targets a texture the material does not define`),p.length||y(`targets a material no primitive draws`),p.some(t=>t.maps[e])||y(`targets a texture no drawn primitive samples`);let r=t===`rotation`?`SCALAR`:`VEC2`;return{accessor:r,size:s[r],type:t===`rotation`?`number`:`vector`,make:r=>{let i=`texture ${n} ${e}`,o=r.get(i)??T(p,e);return r.set(i,o),n=>{for(let{m:r,own:i,texCoord:s}of o){if(t===`rotation`)i.rotation=n[0];else{let e=i[t];e[0]=n[0],e[1]=n[1]}let o=a(i,s);if(r.uvt&&r.uvt.length>=e*8+8)for(let t=0;t<8;t++)r.uvt[e*8+t]=o[t]}}}}}let h=f[r];if(!h)return(r.startsWith(`extensions/`)||r.includes(`/extensions/`))&&y(`targets a material extension property this player does not drive`),i();let[_,v,b,x]=h,S=r.startsWith(`extensions/`)?r.split(`/`).slice(0,2).join(`/`):void 0;x&&u(o,x)===void 0&&y(`targets ${x.split(`/`).pop()}, which the material does not define`),S&&!c(u(o,S))&&y(`targets ${S.slice(11)}, which the material does not use`),r===`extensions/KHR_materials_ior/ior`&&u(o,r)===0&&y(`targets an IOR of 0, a mode KHR_materials_ior keeps for good (updates are ignored)`),p.length||y(`targets a material no primitive draws`),(v===`physical`||v===`ext`||v===`volume`)&&(p.some(e=>!e.physical)&&y(`targets a physical material factor gltf/pbr did not load (pass decoders.materials)`),(v===`volume`||b===3)&&p.some(e=>!e.tint&&!e.attenuation)&&y(`targets transmission or volume of a material loaded without transmission`));let C=s[_];return{accessor:_,size:C,type:g.has(r)?`color`:C===1?`number`:`vector`,make:e=>{let t=`material ${n}`,r=e.get(t)??E(o,p);if(e.set(t,r),v===`base`)for(let e of p)e.base=e.base.slice();return e=>{if(v===`emissive`||v===`strength`){if(v===`strength`)r.strength=e[0];else for(let t=0;t<3;t++)r.emissive[t]=e[t];for(let e of p)for(let t=0;t<3;t++)e.emission[t]=r.emissive[t]*r.strength}else{if(v===`volume`){if(b===0)r.thickness=e[0];else if(b===4)r.distance=e[0];else for(let t=0;t<3;t++)r.atten[t]=e[t]}else if(v===`dispersion`)for(let t of p)t.dispersion=e[0];else if(v===`ext`&&b===1)for(let t of p)t.ext[1]=Math.max(1,e[0]);else for(let t of p)for(let n=0;n<C;n++)t[v][b+n]=e[n];(v===`base`||v===`volume`||v===`physical`&&b===3)&&D(r)}}}}}function T(e,t){return e.flatMap(e=>{let n=e.maps[t];if(!n)return[];let r=n.extensions?.KHR_texture_transform??{},a=i(n).texCoord,o={...r,offset:[...r.offset??[0,0]],scale:[...r.scale??[1,1]],rotation:r.rotation??0},s=e.maps.slice();return s[t]={...n,texCoord:a,extensions:{...n.extensions,KHR_texture_transform:o}},e.maps=s,[{m:e,own:o,texCoord:a}]})}function E(e,t){let n=c(u(e,`extensions/KHR_materials_volume`)),r=n?.attenuationDistance;return{mats:t,emissive:[...e.emissiveFactor??[0,0,0]],strength:u(e,`extensions/KHR_materials_emissive_strength/emissiveStrength`)??1,atten:[...n?.attenuationColor??[1,1,1]],thickness:n?.thicknessFactor??0,distance:typeof r==`number`?r:1/0}}function D({mats:e,atten:t,thickness:n,distance:r}){let i=n/r;for(let a of e)if((a.tint||a.attenuation)&&a.physical){if(a.physical[3]>0){let e=a.tint??=[0,0,0];for(let n=0;n<3;n++)e[n]=a.base[n]*a.physical[3]*o(t[n],i)}else a.tint=void 0;if(a.attenuation){for(let e=0;e<3;e++)a.attenuation[e]=o(t[e],i);let e=a.opticalDepth??=[0,0,0];for(let n=0;n<3;n++)e[n]=t[n]===1||i===0?0:-Math.log(t[n])*i}if(a.volume){a.volume[0]=n;for(let e=0;e<3;e++)a.volume[1+e]=o(t[e],1/r)}}}export{x as n,b as t};
1
+ import{i as e}from"./keyframes-YpidiYS4.js";import{a as t,l as n,o as r}from"./gltf-C2HVNxzB.js";import{textureCoordinates as i,textureTransform as a}from"@margoengine/gltf/pbr-model";function o(e,t){return e===1?1:e**t}var s={SCALAR:1,VEC2:2,VEC3:3,VEC4:4},c=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:void 0,l=e=>Array.isArray(e)?e:[],u=(e,t)=>t.split(`/`).reduce((e,t)=>c(e)?.[t],e),d={"pbrMetallicRoughness/baseColorTexture":0,"pbrMetallicRoughness/metallicRoughnessTexture":1,normalTexture:2,occlusionTexture:3,emissiveTexture:4,"extensions/KHR_materials_clearcoat/clearcoatTexture":5,"extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture":6,"extensions/KHR_materials_clearcoat/clearcoatNormalTexture":7,"extensions/KHR_materials_transmission/transmissionTexture":8,"extensions/KHR_materials_sheen/sheenColorTexture":9,"extensions/KHR_materials_sheen/sheenRoughnessTexture":10,"extensions/KHR_materials_specular/specularTexture":11,"extensions/KHR_materials_specular/specularColorTexture":12},f={"pbrMetallicRoughness/baseColorFactor":[`VEC4`,`base`,0],"pbrMetallicRoughness/roughnessFactor":[`SCALAR`,`factors`,0],"pbrMetallicRoughness/metallicFactor":[`SCALAR`,`factors`,1],"normalTexture/scale":[`SCALAR`,`factors`,2,`normalTexture`],"occlusionTexture/strength":[`SCALAR`,`factors`,3,`occlusionTexture`],emissiveFactor:[`VEC3`,`emissive`,0],alphaCutoff:[`SCALAR`,`settings`,1],"extensions/KHR_materials_emissive_strength/emissiveStrength":[`SCALAR`,`strength`,0,`extensions/KHR_materials_emissive_strength`],"extensions/KHR_materials_dispersion/dispersion":[`SCALAR`,`dispersion`,0,`extensions/KHR_materials_dispersion`],"extensions/KHR_materials_clearcoat/clearcoatFactor":[`SCALAR`,`physical`,0],"extensions/KHR_materials_clearcoat/clearcoatRoughnessFactor":[`SCALAR`,`physical`,1],"extensions/KHR_materials_clearcoat/clearcoatNormalTexture/scale":[`SCALAR`,`physical`,2,`extensions/KHR_materials_clearcoat/clearcoatNormalTexture`],"extensions/KHR_materials_transmission/transmissionFactor":[`SCALAR`,`physical`,3],"extensions/KHR_materials_specular/specularColorFactor":[`VEC3`,`physical`,4],"extensions/KHR_materials_specular/specularFactor":[`SCALAR`,`physical`,7],"extensions/KHR_materials_sheen/sheenColorFactor":[`VEC3`,`physical`,8],"extensions/KHR_materials_sheen/sheenRoughnessFactor":[`SCALAR`,`physical`,11],"extensions/KHR_materials_ior/ior":[`SCALAR`,`ext`,1],"extensions/KHR_materials_volume/thicknessFactor":[`SCALAR`,`volume`,0],"extensions/KHR_materials_volume/attenuationColor":[`VEC3`,`volume`,1],"extensions/KHR_materials_volume/attenuationDistance":[`SCALAR`,`volume`,4,`extensions/KHR_materials_volume/attenuationDistance`]},p={color:`VEC3`,intensity:`SCALAR`,range:`SCALAR`,"spot/innerConeAngle":`SCALAR`,"spot/outerConeAngle":`SCALAR`},m={perspective:[`yfov`,`aspectRatio`,`znear`,`zfar`],orthographic:[`xmag`,`ymag`,`znear`,`zfar`]},h=/^\/materials\/\d+\/extensions\/KHR_materials_ior\/ior$/,g=/* @__PURE__ */ new Set([`pbrMetallicRoughness/baseColorFactor`,`emissiveFactor`,`color`]),_=class{constructor(e){this.reason=e}},v=/* @__PURE__ */ new WeakMap,y=e=>{throw new _(e)},b=(i,a,o)=>{let s=i.asset.doc,u=[],d=[],f=[],p=/* @__PURE__ */ new Set,m=[],g=[],y=/* @__PURE__ */ new Set,b=0;a.channels.forEach((e,v)=>{let x=c(e),S=c(x?.target),w=c(S?.extensions),T=c(w?.KHR_animation_pointer)?.pointer;if(S?.path!==`pointer`&&w?.KHR_animation_pointer===void 0){S?.path===`weights`&&typeof S.node==`number`&&p.add(S.node),u.push(e);return}let E=`Animation ${o} channel ${v}`;if(S?.path!==`pointer`||Object.hasOwn(S,`node`)||typeof T!=`string`)throw TypeError(`${E} KHR_animation_pointer needs path 'pointer', no target node and a pointer string; fix the channel target`);if(y.has(T))throw TypeError(`${E} repeats pointer ${T}; use one channel per property`);y.add(T);let D=n(a.samplers[t(x.sampler,a.samplers.length,`sampler`)]),O=r(D.interpolation),k=i.asset.accessor(D.input,`SCALAR`);if(k.some((e,t)=>e<0||t>0&&e<=k[t-1]))throw RangeError(`${E} key times must be nonnegative and strictly increasing; fix the sampler input`);if(b=Math.max(b,k[k.length-1]),h.test(T)){let e=i.asset.accessor(D.output,`SCALAR`),t=O===`CUBICSPLINE`?3:1;for(let n=0;n<k.length;n++)if(e[n*t+(t>>1)]<1)throw RangeError(`${E} pointer ${T} keys an IOR of ${e[n*t+(t>>1)]}; KHR_materials_ior allows animated IORs of 1 or more only`)}let A;try{A=C(i,s,T,E)}catch(e){if(!(e instanceof _))throw e;g.push(`${E}: pointer ${T} ${e.reason}; skipped`);return}if(`path`in A){A.mesh||p.add(A.nodes[0]);for(let e of A.nodes)(A.mesh?f:d).push({node:e,path:A.path,sampler:x.sampler});A.nodes.length||g.push(`${E}: pointer ${T} has no node using the mesh; skipped`);return}let{accessor:j,size:M,bool:N}=A,P=c(l(s.accessors)[D.output]);if(N&&(O!==`STEP`||P?.componentType!==5121||P.normalized))throw TypeError(`${E} pointer ${T} is a boolean; use STEP and an unsigned byte SCALAR accessor`);let F=i.asset.accessor(D.output,j),I=O===`CUBICSPLINE`,L=M*(I?3:1);if(F.length!==k.length*L)throw RangeError(`${E} pointer ${T} has ${F.length/M} output values for ${k.length} keys; key one ${j} per time${I?` with in and out tangents`:``}`);let R=Array.from(k,(e,t)=>{let n=t*L+(I?M:0),r={time:e,value:Array.from(F.subarray(n,n+M)),interpolation:I?`cubicSpline`:O===`STEP`?`discrete`:`linear`};return I&&(r.inTangent=Array.from(F.subarray(n-M,n)),r.outTangent=Array.from(F.subarray(n+M,n+2*M))),r});m.push({target:A,keys:R,pointer:T})});for(let e of f)p.has(e.node)||d.unshift(e);return{ordinary:u,nodes:d,duration:b,warnings:g,...m.length?{bind:()=>{let t=v.get(i);return t||v.set(i,t=/* @__PURE__ */ new Map),e({name:o,tracks:m.map(({target:e,keys:n,pointer:r})=>({target:i,name:r,type:e.type,set:e.make(t),keys:n}))})}}:{}}};function x(e,t){let n=/^\/nodes\/(\d+)\/weights\/(\d+)$/.exec(t);if(n)return t=>{for(let r of e.primitives)r.nodeIndex===+n[1]&&(r.weights[+n[2]]=t[0])};let r;try{r=C(e,e.asset.doc,t,`Behaviour graph`)}catch(e){if(e instanceof _)return;throw e}if(!(`path`in r)){let t=v.get(e);t||v.set(e,t=/* @__PURE__ */ new Map);let n=r.make(t);return e=>n(Float64Array.from(e))}let i=e.nodes[r.nodes[0]],{path:a}=r;if(i&&a!==`weights`)return e=>{a===`rotation`?i.setQuaternion(Array.from(e)):a===`scale`?i.setScale(Array.from(e)):i.setPosition(Array.from(e))}}function S(e,t,n,r,i){if(e===void 0||!/^(0|[1-9]\d*)$/.test(e)||Number(e)>=t)throw TypeError(`${r} pointer ${i} names no ${n} ${e??``}; point at an existing index`);return Number(e)}function C(e,t,n,r){if(!n.startsWith(`/`))throw TypeError(`${r} pointer ${n} is not a JSON pointer; start it with '/'`);let i=n.slice(1).split(`/`).map(e=>e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`)),a=()=>{throw TypeError(`${r} pointer ${n} is not an animatable glTF property; point at a property animations may change`)},o=e=>e.split(`/`).some(e=>e===`extras`||e===`extensions`);i.includes(`extras`)&&y(`targets application-defined extras`);let[d,f,...h]=i,_=h.join(`/`);if(d===`nodes`){let i=S(f,l(t.nodes).length,`node`,r,n);if([`translation`,`rotation`,`scale`,`weights`].includes(_))return{nodes:[i],path:_,mesh:!1};if(_===`extensions/KHR_node_visibility/visible`){c(u(l(t.nodes)[i],`extensions/KHR_node_visibility`))||y(`targets a node without KHR_node_visibility`);let n=e.nodes[i];return{accessor:`SCALAR`,size:1,type:`number`,bool:!0,make:()=>e=>{n.visible=e[0]!==0}}}return o(_)&&y(`targets a node extension this player does not drive`),a()}if(d===`meshes`){let e=S(f,l(t.meshes).length,`mesh`,r,n);return _===`weights`?{nodes:l(t.nodes).flatMap((t,n)=>c(t)?.mesh===e?[n]:[]),path:`weights`,mesh:!0}:(o(_)&&y(`targets a mesh extension this player does not drive`),a())}if(d===`materials`)return w(e,t,S(f,l(t.materials).length,`material`,r,n),_,a);if(d===`cameras`){let i=S(f,l(t.cameras).length,`camera`,r,n),o=c(l(t.cameras)[i]),[s,u,d]=h;if(!m[s]?.includes(u)||d!==void 0)return a();(o.type!==s||!c(o[s]))&&y(`targets ${s} values of a ${String(o.type)} camera`),c(o[s])[u]===void 0&&y(`targets ${u}, which the camera does not define`);let p=e.cameras.filter(e=>c(l(t.nodes)[e.nodeIndex])?.camera===i);return p.length||y(`targets a camera no scene node uses`),{accessor:`SCALAR`,size:1,type:`number`,make:e=>{let t=`camera ${i}`,n=e.get(t)??p.map(e=>{let t={...e[s]};return e[s]=t,t});return e.set(t,n),e=>{for(let t of n)t[u]=e[0]}}}}if(d===`extensions`&&f===`KHR_lights_punctual`&&h[0]===`lights`){let i=l(c(c(t.extensions)?.KHR_lights_punctual)?.lights),o=S(h[1],i.length,`light`,r,n),d=h.slice(2).join(`/`),f=c(i[o]),m=p[d];if(!m)return a();d.startsWith(`spot/`)&&f.type!==`spot`&&y(`targets spot cones of a ${String(f.type)} light`),d===`range`&&f.range===void 0&&y(`targets range, which the light does not define`);let _=e.lights.filter(e=>c(u(l(t.nodes)[e.nodeIndex],`extensions/KHR_lights_punctual`))?.light===o);_.length||y(`targets a light no scene node uses`);let v=d.startsWith(`spot/`)?d.slice(5):d;return{accessor:m,size:s[m],type:g.has(d)?`color`:`number`,make:e=>{if(d===`color`){if(!e.has(`light ${o}`))for(let e of _)e.color=e.color.slice();return e.set(`light ${o}`,!0),e=>{for(let t of _)for(let n=0;n<3;n++)t.color[n]=e[n]}}return e=>{for(let t of _)t[v]=e[0]}}}}return d===`extensions`&&y(`targets ${f}, which this player does not drive`),a()}function w(e,t,n,r,i){let o=c(l(t.materials)[n]),p=[...new Set([...e.primitives,...e.pointsAndLines].filter(e=>e.definition.material===n).map(e=>e.material))],m=/^(.+)\/extensions\/KHR_texture_transform\/(offset|scale|rotation|texCoord)$/.exec(r);if(m){let e=d[m[1]],t=m[2];e===void 0&&y(`targets a texture this player does not map to a live UV transform`),t===`texCoord`&&y(`targets texCoord, an integer UV set this player does not switch`),c(u(o,m[1]))||y(`targets a texture the material does not define`),p.length||y(`targets a material no primitive draws`),p.some(t=>t.maps[e])||y(`targets a texture no drawn primitive samples`);let r=t===`rotation`?`SCALAR`:`VEC2`;return{accessor:r,size:s[r],type:t===`rotation`?`number`:`vector`,make:r=>{let i=`texture ${n} ${e}`,o=r.get(i)??T(p,e);return r.set(i,o),n=>{for(let{m:r,own:i,texCoord:s}of o){if(t===`rotation`)i.rotation=n[0];else{let e=i[t];e[0]=n[0],e[1]=n[1]}let o=a(i,s);if(r.uvt&&r.uvt.length>=e*8+8)for(let t=0;t<8;t++)r.uvt[e*8+t]=o[t]}}}}}let h=f[r];if(!h)return(r.startsWith(`extensions/`)||r.includes(`/extensions/`))&&y(`targets a material extension property this player does not drive`),i();let[_,v,b,x]=h,S=r.startsWith(`extensions/`)?r.split(`/`).slice(0,2).join(`/`):void 0;x&&u(o,x)===void 0&&y(`targets ${x.split(`/`).pop()}, which the material does not define`),S&&!c(u(o,S))&&y(`targets ${S.slice(11)}, which the material does not use`),r===`extensions/KHR_materials_ior/ior`&&u(o,r)===0&&y(`targets an IOR of 0, a mode KHR_materials_ior keeps for good (updates are ignored)`),p.length||y(`targets a material no primitive draws`),(v===`physical`||v===`ext`||v===`volume`)&&(p.some(e=>!e.physical)&&y(`targets a physical material factor gltf/pbr did not load (pass decoders.materials)`),(v===`volume`||b===3)&&p.some(e=>!e.tint&&!e.attenuation)&&y(`targets transmission or volume of a material loaded without transmission`));let C=s[_];return{accessor:_,size:C,type:g.has(r)?`color`:C===1?`number`:`vector`,make:e=>{let t=`material ${n}`,r=e.get(t)??E(o,p);if(e.set(t,r),v===`base`)for(let e of p)e.base=e.base.slice();return e=>{if(v===`emissive`||v===`strength`){if(v===`strength`)r.strength=e[0];else for(let t=0;t<3;t++)r.emissive[t]=e[t];for(let e of p)for(let t=0;t<3;t++)e.emission[t]=r.emissive[t]*r.strength}else{if(v===`volume`){if(b===0)r.thickness=e[0];else if(b===4)r.distance=e[0];else for(let t=0;t<3;t++)r.atten[t]=e[t]}else if(v===`dispersion`)for(let t of p)t.dispersion=e[0];else if(v===`ext`&&b===1)for(let t of p)t.ext[1]=Math.max(1,e[0]);else for(let t of p)for(let n=0;n<C;n++)t[v][b+n]=e[n];(v===`base`||v===`volume`||v===`physical`&&b===3)&&D(r)}}}}}function T(e,t){return e.flatMap(e=>{let n=e.maps[t];if(!n)return[];let r=n.extensions?.KHR_texture_transform??{},a=i(n).texCoord,o={...r,offset:[...r.offset??[0,0]],scale:[...r.scale??[1,1]],rotation:r.rotation??0},s=e.maps.slice();return s[t]={...n,texCoord:a,extensions:{...n.extensions,KHR_texture_transform:o}},e.maps=s,[{m:e,own:o,texCoord:a}]})}function E(e,t){let n=c(u(e,`extensions/KHR_materials_volume`)),r=n?.attenuationDistance;return{mats:t,emissive:[...e.emissiveFactor??[0,0,0]],strength:u(e,`extensions/KHR_materials_emissive_strength/emissiveStrength`)??1,atten:[...n?.attenuationColor??[1,1,1]],thickness:n?.thicknessFactor??0,distance:typeof r==`number`?r:1/0}}function D({mats:e,atten:t,thickness:n,distance:r}){let i=n/r;for(let a of e)if((a.tint||a.attenuation)&&a.physical){if(a.physical[3]>0){let e=a.tint??=[0,0,0];for(let n=0;n<3;n++)e[n]=a.base[n]*a.physical[3]*o(t[n],i)}else a.tint=void 0;if(a.attenuation){for(let e=0;e<3;e++)a.attenuation[e]=o(t[e],i);let e=a.opticalDepth??=[0,0,0];for(let n=0;n<3;n++)e[n]=t[n]===1||i===0?0:-Math.log(t[n])*i}if(a.volume){a.volume[0]=n;for(let e=0;e<3;e++)a.volume[1+e]=o(t[e],1/r)}}}export{x as n,b as t};
package/dist/pointer.js CHANGED
@@ -1 +1 @@
1
- export{t as pointerChannels,n as pointerWriter}from"./pointer-BOFnz0gk.js";
1
+ export{t as pointerChannels,n as pointerWriter}from"./pointer-DyWpFsQi.js";
package/dist/pose.d.ts CHANGED
@@ -1,7 +1,12 @@
1
+ import type { SkinningMode } from './shader.js';
2
+ import type { MorphTable } from './morph-table.js';
1
3
  /**
2
- * Writes the pose of `bind` (20 floats per vertex) into `out`. Morph targets are added first: `deltas` holds 12 floats
3
- * per vertex and target (position at 0, normal at 4) and `weights` one value per target. Then comes the weighted blend
4
+ * Writes the pose of `bind` (20 floats per vertex) into `out`. Morph targets are added first: `deltas` is the primitive's sparse
5
+ * table (morph-table.ts), walked in target order as the shader walks it, and `weights` holds one value per target. Then comes the weighted blend
4
6
  * of `palette` (16 floats per bone) by `influences`: `words` per vertex, four joint indices then four float weights,
5
- * twice for eight influences. Everything but position and normal is copied from `bind`.
7
+ * twice for eight influences. Everything but position and normal is copied from `bind`. With a skinning `mode`, its
8
+ * `blend` moves each vertex instead, with `palette` encoded for it; a mode with `share` reads each vertex's share from
9
+ * the upper 16 bits of its first joint index, as the mode's shader does; a mode with `vertexData` reads the last four
10
+ * of each vertex's `words` as its data.
6
11
  */
7
- export declare function poseVertices(bind: Float32Array, out: Float32Array, deltas: Float32Array, weights: ArrayLike<number>, influences: Uint32Array, words: number, palette: Float32Array): void;
12
+ export declare function poseVertices(bind: Float32Array, out: Float32Array, deltas: MorphTable, weights: ArrayLike<number>, influences: Uint32Array, words: number, palette: Float32Array, mode?: SkinningMode): void;
@@ -27,6 +27,12 @@ export interface RetargetOptions {
27
27
  * the source hip's, or 1 when either is not above 0.
28
28
  */
29
29
  hipScale?: number;
30
+ /**
31
+ * Unmapped target bones held at the target rig's rest rotation: {@link Retarget.apply} writes it and
32
+ * {@link Retarget.clip} keys it, for a rig whose rest differs from the pose the target holds now (an aligned rig
33
+ * from `@margoengine/rigging`'s prepareRetarget lists the bones it re-aimed). Default: none; mapped bones are ignored.
34
+ */
35
+ hold?: readonly string[];
30
36
  }
31
37
  /** A glTF PBR model's player, such as an `Animation`, whose clip {@link Retarget.clip} can sample. */
32
38
  export interface RetargetPlayer {
@@ -66,6 +72,8 @@ export declare class Retarget {
66
72
  readonly sourceHip: number;
67
73
  /** Scale applied to the hip's movement. */
68
74
  readonly hipScale: number;
75
+ /** 1 per unmapped target bone held at its rig rest rotation (see {@link RetargetOptions.hold}), else 0. */
76
+ readonly held: Uint8Array;
69
77
  private readonly sourceOrder;
70
78
  private readonly targetOrder;
71
79
  private readonly sourceRest;
@@ -86,13 +94,13 @@ export declare class Retarget {
86
94
  pose(source: Float64Array, out?: Float64Array): Float64Array;
87
95
  /**
88
96
  * Poses `target` the way `source` is posed now: each must be the Skeleton or model its rig was made from. Writes
89
- * only the mapped bones' rotations and the hip's position; other target bones keep what they have (the retarget
90
- * assumes them at rest).
97
+ * the mapped bones' rotations, the held bones' rest rotations ({@link RetargetOptions.hold}) and the hip's position;
98
+ * other target bones keep what they have (the retarget assumes them at rest).
91
99
  */
92
100
  apply(source: Skeleton | PBRModel, target: Skeleton | PBRModel): void;
93
101
  /**
94
102
  * A code-authored clip for the target rig from a source clip, sampled at `fps` (default 30) from 0 to the clip's
95
- * duration: a rotation track per mapped target bone and a translation track for the hip, linear keys. The source
103
+ * duration: a rotation track per mapped or held target bone and a translation track for the hip, linear keys. The source
96
104
  * is a `KeyframeClip` whose tracks name source bones (sampled over the source rig's rest pose; weights tracks are
97
105
  * not carried over), or a glTF clip played by the source model's `Animation` (`{animation, clip}`; its clip, time and
98
106
  * playing state are restored afterwards). Play the result with `applyKeyframeClip` or an `AnimationGroup`.
@@ -34,13 +34,14 @@ struct Influence {joints:vec4u,weights:vec4f}
34
34
  let normalMatrix=mat3x3f(cross(skin[1].xyz,skin[2].xyz),cross(skin[2].xyz,skin[0].xyz),cross(skin[0].xyz,skin[1].xyz));
35
35
  let handedness=select(-1.0,1.0,dot(skin[0].xyz,cross(skin[1].xyz,skin[2].xyz))>=0.0);let bent=normalMatrix*v.normal.xyz*handedness;
36
36
  v.normal=vec4f(select(vec3f(0,1,0),bent,dot(bent,bent)>0.0),0);
37
- v.tangent=vec4f((skin*vec4f(v.tangent.xyz,0)).xyz,v.tangent.w*handedness);`,i=e=>e?n(`weightsExtra`,r(!1),r(!0)):r(!1);function a(e,t={functions:``,blend:i(e)}){return`
37
+ v.tangent=vec4f((skin*vec4f(v.tangent.xyz,0)).xyz,v.tangent.w*handedness);`,i=e=>e?n(`weightsExtra`,r(!1),r(!0)):r(!1);function a(e,t={functions:``,blend:i(e)},n=!1){return`
38
38
  struct Vertex {position:vec4f,normal:vec4f,tangent:vec4f,uv:vec4f,color:vec4f}
39
- struct Morph {position:vec4f,normal:vec4f,tangent:vec4f}
40
- struct Slot {source:u32,output:u32,count:u32,targets:u32,morphs:u32,weights:u32,bones:u32,joints:u32,influences:u32,pad0:u32,pad1:u32,pad2:u32}
39
+ struct Slot {source:u32,output:u32,count:u32,targets:u32,morphs:u32,weights:u32,bones:u32,joints:u32,influences:u32,entry:u32,pad1:u32,pad2:u32}
41
40
  @group(0) @binding(0) var<storage,read> source:array<Vertex>;
42
41
  @group(0) @binding(1) var<storage,read_write> output:array<Vertex>;
43
- @group(0) @binding(2) var<storage,read> morphs:array<Morph>;
42
+
43
+
44
+ @group(0) @binding(2) var<storage,read> morphs:array<vec4u>;
44
45
  @group(0) @binding(3) var<storage,read> weights:array<f32>;
45
46
  @group(0) @binding(4) var<storage,read> boneMatrices:array<mat4x4f>;
46
47
  @group(0) @binding(5) var<storage,read> influences:array<vec4u>;
@@ -53,12 +54,18 @@ ${t.functions}
53
54
  let entry=work[item+1u];let s=slots[entry.x];let i=entry.y+lane;
54
55
  if(i>=s.count){return;}
55
56
  var v=source[s.source+i];
56
- for(var morphIndex=0u;morphIndex<s.targets;morphIndex++) {
57
- let m=morphs[s.morphs+morphIndex*s.count+i];let w=weights[s.weights+morphIndex];
58
- v.position+=vec4f(m.position.xyz*w,0);v.normal+=vec4f(m.normal.xyz*w,0);v.tangent+=vec4f(m.tangent.xyz*w,0);
57
+ if(s.targets>0u) {
58
+
59
+
60
+ let entries=s.morphs+(s.count+4u)/4u;let first=morphs[s.morphs+i/4u][i%4u];let end=morphs[s.morphs+(i+1u)/4u][(i+1u)%4u];
61
+ for(var e=first;e<end;e++) {
62
+ let at=entries+e*s.entry;let p=morphs[at];let w=weights[s.weights+p.w];
63
+ v.position+=vec4f(bitcast<vec3f>(p.xyz)*w,0);v.normal+=vec4f(bitcast<vec3f>(morphs[at+1u].xyz)*w,0);
64
+ if(s.entry>2u){v.tangent+=vec4f(bitcast<vec3f>(morphs[at+2u].xyz)*w,0);}
65
+ }
59
66
  }
60
67
  if(s.joints>0u) {
61
- let at=s.influences+i*${e?4:2}u;let joints=influences[at];let jointWeights=bitcast<vec4f>(influences[at+1u]);${e?`let jointsExtra=influences[at+2u];let weightsExtra=bitcast<vec4f>(influences[at+3u]);`:``}
68
+ let at=s.influences+i*${(e?4:2)+ +!!n}u;let joints=influences[at];let jointWeights=bitcast<vec4f>(influences[at+1u]);${e?`let jointsExtra=influences[at+2u];let weightsExtra=bitcast<vec4f>(influences[at+3u]);`:``}${n?`let vertexData=bitcast<vec4f>(influences[at+${e?4:2}u]);`:``}
62
69
  ${t.blend}
63
70
  }
64
71
  v.normal=vec4f(normalize(v.normal.xyz),0);output[s.output+i]=v;
package/dist/shader.d.ts CHANGED
@@ -14,6 +14,37 @@ export interface SkinningMode {
14
14
  * packs it into the upper 16 bits of each vertex's first joint index, so only a mode that masks the index reads it.
15
15
  */
16
16
  share?(extras: unknown): ArrayLike<number> | undefined;
17
+ /**
18
+ * The mode's blend on the CPU: where one vertex goes, the shader's steps in double precision. `palette` is the
19
+ * encoded palette (after `encode`), `joints` and `weights` the vertex's influences in the shader's order (weights
20
+ * summing to 1), `position` and `normal` its bind values after the morph targets, and `share` its share from
21
+ * {@link SkinningMode.share} (1 for a mode without one, or a node without shares). Returns the position and the unit
22
+ * normal. `Animation` poses synchronous queries (`@margoengine/bvh` raycasts) with it; a mode without it has no CPU
23
+ * pose, so those queries throw MargoError `unsupported` rather than test the bind pose.
24
+ */
25
+ blend?(palette: Float32Array, joints: ArrayLike<number>, weights: ArrayLike<number>, position: ArrayLike<number>, normal: ArrayLike<number>, share: number, data?: ArrayLike<number>): {
26
+ position: ArrayLike<number>;
27
+ normal: ArrayLike<number>;
28
+ };
29
+ /**
30
+ * Four numbers per vertex the mode's shader reads as `vertexData` (and `blend` as `data`), made once per skinned mesh
31
+ * from all of its primitives in the file's bind pose: one array of `4 * vertices` numbers per part, in order.
32
+ * `Animation` keeps them per mode, asset and mesh, so copies and clones of a model make them once.
33
+ */
34
+ vertexData?(parts: readonly SkinMeshPart[]): Float32Array[];
35
+ }
36
+ /** One primitive of a skinned mesh as the file has it, for {@link SkinningMode.vertexData}. */
37
+ export interface SkinMeshPart {
38
+ /** Bind-pose positions, three numbers per vertex. */
39
+ readonly positions: ArrayLike<number>;
40
+ /** Triangle corners (three per triangle), or null for a primitive that draws no triangles. */
41
+ readonly triangles: ArrayLike<number> | null;
42
+ /** Joint indices into the skin's joints, `influences` per vertex. */
43
+ readonly joints: ArrayLike<number>;
44
+ /** Weights parallel to `joints`. */
45
+ readonly weights: ArrayLike<number>;
46
+ /** Influences per vertex: 4, or 8 with JOINTS_1. */
47
+ readonly influences: number;
17
48
  }
18
49
  /** Text a skinning mode puts into the batched shader: module-scope `functions`, and the `blend` that moves `v`. */
19
50
  export interface SkinningShader {
@@ -25,6 +56,7 @@ export interface SkinningShader {
25
56
  * named by the work list (`work[0].x` workgroups, then a slot index and first vertex per workgroup); each slot record
26
57
  * gives where its vertices, deltas, weights, bones and influences start in the shared buffers. The per-vertex
27
58
  * arithmetic is the per-primitive shader's, term for term, so the output is the same bits. `extra`: eight influences.
28
- * `skin` replaces that arithmetic for a skinning mode.
59
+ * `skin` replaces that arithmetic for a skinning mode. `data`: each vertex's influences end with one more vec4, the
60
+ * mode's `vertexData`, which the blend reads as `vertexData`.
29
61
  */
30
- export declare function batchedDeformationShader(extra: boolean, skin?: SkinningShader): string;
62
+ export declare function batchedDeformationShader(extra: boolean, skin?: SkinningShader, data?: boolean): string;
@@ -1,4 +1,4 @@
1
- // @margo/core-built 0.1.0
1
+ // @margo/core-built 1.0.0
2
2
  import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
3
 
4
- import{a as e,i as t,s as n}from"./keyframes-BO50xipp.js";import{MargoError as r}from"@margoengine/math/errors";import{normalizeQuaternion as i}from"@margoengine/math/quat";import{PBRModel as a,closeImages as o}from"@margoengine/gltf/pbr-model";var s=0,c=(e,t)=>{let n=t+s++;for(;e.plugins?.has(n);)n+=`:`;return n};function l(e,t){return{scene:t,run(n){if(!t)return n();let r,i={coreRequirement:/*@__PURE__*/__margoCoreRequirement("0.1.0",import.meta.url),name:c(e,`scene-scope:`),setup(){r=n()}};return t.use(i),t.removePlugin(i.name),r}}}var u=[0,0,0,1];async function d(e){if(!(e instanceof a))throw TypeError(`cloneModel needs a glTF PBR PBRModel; pass a loaded model`);if(e.disposed)throw new r(`disposed`,`cloneModel source is disposed; clone a live model`);let t=e.shareImages(),n=e.asset.doc,i=e.root.engine,s;if(!n.buffers?.length){let t=/* @__PURE__ */ new Map;for(let n of[...e.primitives,...e.pointsAndLines])t.set(n.definition,n.topology?{vertices:n.vertices,indices:n.indices,topology:n.topology}:n);s=(n.meshes??[]).map(e=>(e.primitives??[]).map(e=>t.get(e)))}return l(i,i.sceneOf(e)).run(()=>{let n;try{n=new a(i,e.asset,t,s);let r=i.store.transforms,o=(e,t)=>{let n=e.id,i=r.x[n],a=r.y[n],o=r.z[n],s=r.sx[n],c=r.sy[n],l=r.sz[n];Number.isFinite(i+a+o)?t.position.set(i,a,o):t.setPosition([i,a,o]),Number.isFinite(s+c+l)?t.scale.set(s,c,l):t.setScale([s,c,l]),u[0]=r.qx[n],u[1]=r.qy[n],u[2]=r.qz[n],u[3]=r.qw[n],t.setQuaternion(u),t.visible=e.visible};return o(e.root,n.root),e.nodes.forEach((e,t)=>o(e,n.nodes[t])),e.primitives.forEach((e,t)=>n.primitives[t]?.weights.set(e.weights)),n.adoptStaticBatches(e),i.plugins.get(e.name)===e&&i.use(n),n}catch(e){throw n?n.dispose():o(t),e}})}var f=[0,0,0,0],p=e=>({rotation:new Float64Array(e.names.length*4),position:new Float64Array(e.names.length*3),scale:new Float64Array(e.names.length*3)});function m(e,t){let{names:n,parents:r,rest:i}=e??{},a=n?.length;if(!Array.isArray(n)||!Array.isArray(r)||r.length!==a||!(i instanceof Float64Array))throw TypeError(`Retarget ${t} needs a rig with names, parents and rest; make it with retargetRig`);if(i.length!==a*10||!i.every(Number.isFinite))throw RangeError(`Retarget ${t} rest pose needs 10 finite numbers per bone`);let o=r.map(()=>[]),s=[];r.forEach((e,n)=>{if(!Number.isInteger(e)||e<-1||e>=a||e===n)throw RangeError(`Retarget ${t} bone ${n} parent ${e} is invalid; use -1 or another bone's index`);e>=0&&o[e].push(n)});for(let e=r.flatMap((e,t)=>e<0?[t]:[]);e.length;){let t=e.pop();s.push(t),e.push(...o[t])}if(s.length!==a)throw RangeError(`Retarget ${t} parents form a cycle; every chain must reach a top bone`);return s}function h(e,t,n,r,i,a){let o=n[r],s=n[r+1],c=n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];e[t]=l*u+o*p+s*f-c*d,e[t+1]=l*d-o*f+s*p+c*u,e[t+2]=l*f+o*d-s*u+c*p,e[t+3]=l*p-o*u-s*d-c*f}function g(e,t,n,r,i,a){let o=-n[r],s=-n[r+1],c=-n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];e[t]=l*u+o*p+s*f-c*d,e[t+1]=l*d-o*f+s*p+c*u,e[t+2]=l*f+o*d-s*u+c*p,e[t+3]=l*p-o*u-s*d-c*f}function _(e,t,n,r,i,a,o,s=!1){let c=s?-1:1,l=n[r]*c,u=n[r+1]*c,d=n[r+2]*c,f=n[r+3],p=2*(u*o-d*a),m=2*(d*i-l*o),h=2*(l*a-u*i);e[t]=i+f*p+u*h-d*m,e[t+1]=a+f*m+d*p-l*h,e[t+2]=o+f*h+l*m-u*p}function v(e,t,n,r,i,a){for(let o=0;o<e.length;o++){let s=e[o],c=t[s],l=s*10;if(c<0){for(let e=0;e<3;e++)i[s*3+e]=n[l+e],a[s*3+e]=n[l+7+e];for(let e=0;e<4;e++)r[s*4+e]=n[l+3+e]}else{h(r,s*4,r,c*4,n,l+3),_(i,s*3,r,c*4,a[c*3]*n[l],a[c*3+1]*n[l+1],a[c*3+2]*n[l+2]);for(let e=0;e<3;e++)i[s*3+e]+=i[c*3+e],a[s*3+e]=a[c*3+e]*n[l+7+e]}}}function y(e,t,r,i){if(e instanceof n){if(e.count!==t)throw RangeError(`Retarget ${r} has ${e.count} bones but its rig has ${t}; use a source with the rig's bone count`);for(let n=0;n<t;n++){let{translation:t,rotation:r,scale:a}=e.getPose(n);i.set(t,n*10),i.set(r,n*10+3),i.set(a,n*10+7)}return}if(!(e instanceof a))throw TypeError(`Retarget ${r} must be a Skeleton or a glTF PBR model`);if(e.nodes.length!==t)throw RangeError(`Retarget ${r} has ${e.nodes.length} nodes but its rig ${t}; use its own rig`);let o=e.root.engine.store.transforms;for(let n=0;n<t;n++){let t=e.nodes[n].id,r=n*10;i[r]=o.x[t],i[r+1]=o.y[t],i[r+2]=o.z[t],i[r+3]=o.qx[t],i[r+4]=o.qy[t],i[r+5]=o.qz[t],i[r+6]=o.qw[t],i[r+7]=o.sx[t],i[r+8]=o.sy[t],i[r+9]=o.sz[t]}}function b(e){if(e instanceof n){let t=new Float64Array(e.count*10);return y(e,e.count,`skeleton`,t),{names:e.names,parents:e.parents,rest:t}}if(!(e instanceof a))throw TypeError(`retargetRig needs a Skeleton or a glTF PBR model`);let t=new Map(e.nodes.map((e,t)=>[e.id,t])),r=e.root.engine.store.parents,i=new Float64Array(e.nodes.length*10);return y(e,e.nodes.length,`model`,i),{names:e.nodes.map(e=>e.name),parents:e.nodes.map(e=>t.get(r[e.id])??-1),rest:i}}var x=class{constructor(e,t,n={}){this.source=e,this.target=t,this.delta=/* @__PURE__ */ new Float64Array(4),this.quaternion=[0,0,0,1],this.vector=[0,0,0],this.sourceOrder=m(e,`source`),this.targetOrder=m(t,`target`);let r=n.names??{};if(typeof r!=`object`)throw TypeError(`Retarget names must map target bone names to source bone names`);for(let[t,n]of Object.entries(r))if(typeof n!=`string`||n&&!e.names.includes(n))throw RangeError(`Retarget maps ${t} to ${n}, which the source does not have; fix the names map`);let i=e=>Object.hasOwn(r,e)?r[e]:e;if(this.map=Int32Array.from(t.names,t=>i(t)?e.names.indexOf(i(t)):-1),!this.map.some(e=>e>=0))throw RangeError(`Retarget maps no bones; pass a names map or use rigs with matching bone names`);this.sourceNow=p(e),this.targetNow=p(t);let a=this.sourceRest=p(e),o=this.targetRest=p(t);if(v(this.sourceOrder,e.parents,e.rest,a.rotation,a.position,a.scale),v(this.targetOrder,t.parents,t.rest,o.rotation,o.position,o.scale),this.hip=n.hip===void 0?-1:t.names.indexOf(n.hip),n.hip!==void 0&&this.hip<0)throw RangeError(`Retarget hip ${n.hip} is not a target bone; pass the target's hip bone name`);if(this.sourceHip=this.hip<0?-1:this.map[this.hip],this.hip>=0&&this.sourceHip<0)throw RangeError(`Retarget hip ${n.hip} has no source bone; map it in names`);let s=this.sourceHip<0?0:a.position[this.sourceHip*3+1],c=this.hip<0?0:o.position[this.hip*3+1],l=n.hipScale??(s>0&&c>0?c/s:1);if(typeof l!=`number`||!Number.isFinite(l)||l<=0)throw RangeError(`Retarget hipScale ${l} is invalid; pass a finite number > 0`);this.hipScale=l,this.input=new Float64Array(e.names.length*10),this.output=new Float64Array(t.names.length*10),this.poses=t.names.map((e,t)=>({rotation:this.output.subarray(t*10+3,t*10+7),...t===this.hip?{translation:this.output.subarray(t*10,t*10+3)}:{}}))}pose(e,t=new Float64Array(this.target.names.length*10)){if(!(e instanceof Float64Array)||e.length!==this.source.names.length*10)throw TypeError(`Retarget pose needs a Float64Array of ${this.source.names.length*10} numbers`);if(!(t instanceof Float64Array)||t.length!==this.target.names.length*10)throw TypeError(`Retarget output needs a Float64Array of ${this.target.names.length*10} numbers`);let n=this.sourceNow,r=this.targetNow,{parents:a,rest:o}=this.target,s=this.delta;v(this.sourceOrder,this.source.parents,e,n.rotation,n.position,n.scale),t.set(o);for(let e=0;e<this.targetOrder.length;e++){let o=this.targetOrder[e],c=a[o],l=this.map[o],u=o*10;if(l>=0){if(g(s,0,this.sourceRest.rotation,l*4,this.targetRest.rotation,o*4),h(r.rotation,o*4,n.rotation,l*4,s,0),c<0)for(let e=0;e<4;e++)t[u+3+e]=r.rotation[o*4+e];else g(t,u+3,r.rotation,c*4,r.rotation,o*4);for(let e=0;e<4;e++)f[e]=t[u+3+e];t.set(i(f,f),u+3)}if(o===this.hip){let e=this.hipScale,i=this.sourceHip*3,a=this.targetRest.position[o*3]+e*(n.position[i]-this.sourceRest.position[i]),s=this.targetRest.position[o*3+1]+e*(n.position[i+1]-this.sourceRest.position[i+1]),l=this.targetRest.position[o*3+2]+e*(n.position[i+2]-this.sourceRest.position[i+2]);if(c<0)t[u]=a,t[u+1]=s,t[u+2]=l;else{_(t,u,r.rotation,c*4,a-r.position[c*3],s-r.position[c*3+1],l-r.position[c*3+2],!0);for(let e=0;e<3;e++)t[u+e]/=r.scale[c*3+e]}}if(c<0){for(let e=0;e<3;e++)r.position[o*3+e]=t[u+e],r.scale[o*3+e]=t[u+7+e];for(let e=0;e<4;e++)r.rotation[o*4+e]=t[u+3+e]}else{h(r.rotation,o*4,r.rotation,c*4,t,u+3),_(r.position,o*3,r.rotation,c*4,r.scale[c*3]*t[u],r.scale[c*3+1]*t[u+1],r.scale[c*3+2]*t[u+2]);for(let e=0;e<3;e++)r.position[o*3+e]+=r.position[c*3+e],r.scale[o*3+e]=r.scale[c*3+e]*t[u+7+e]}}return t}apply(e,t){y(e,this.source.names.length,`source`,this.input);let r=this.pose(this.input,this.output);if(t instanceof n){if(t.count!==this.target.names.length)throw RangeError(`Retarget target has ${t.count} bones but its rig has ${this.target.names.length}; pass a target with the rig's bone count`);for(let e=0;e<this.map.length;e++)(this.map[e]>=0||e===this.hip)&&t.setPose(e,this.poses[e]);return}if(!(t instanceof a))throw TypeError(`Retarget target must be a Skeleton or a glTF PBR model`);if(t.nodes.length!==this.target.names.length)throw RangeError(`Retarget target has ${t.nodes.length} nodes but its rig has ${this.target.names.length}; pass a model with the rig's node count`);let i=this.quaternion,o=this.vector;for(let e=0;e<this.map.length;e++){if(this.map[e]>=0){for(let t=0;t<4;t++)i[t]=r[e*10+3+t];t.nodes[e].setQuaternion(i)}if(e===this.hip){for(let t=0;t<3;t++)o[t]=r[e*10+t];t.nodes[e].setPosition(o)}}}clip(n,{fps:r=30,name:i}={}){if(typeof r!=`number`||!Number.isFinite(r)||r<=0||r>1e3)throw RangeError(`Retarget clip fps ${r} is invalid; pass frames per second from 0 to 1000`);let o=this.input,s=this.source.names.length,c,l,u,d=()=>{};if(`tracks`in n&&Array.isArray(n.tracks)){let t=n,r=t.tracks.filter(e=>e.path!==`weights`&&this.source.names.includes(e.target)),i=r.map(e=>this.source.names.indexOf(e.target)*10),a=/* @__PURE__ */ new Float64Array(4);c=t.duration,l=t.name,u=t=>{o.set(this.source.rest),r.forEach((n,r)=>{let s=e(n,t,a),c=i[r]+(n.path===`translation`?0:n.path===`rotation`?3:7);for(let e=0;e<(n.path===`rotation`?4:3);e++)o[c+e]=s[e]})}}else{let{animation:e,clip:t}=n,r=e?.model;if(!(r instanceof a)||!Array.isArray(e.clips)||typeof e.seek!=`function`)throw TypeError(`Retarget clip needs a KeyframeClip or {animation, clip} with an Animation`);let i=typeof t==`string`?e.clips.findIndex(e=>e.name===t):t;if(!Number.isInteger(i)||i<0||i>=e.clips.length)throw RangeError(`Retarget clip ${t} is not one of the source model's clips; pass a name or index it has`);let f={clip:e.clip,time:e.time,playing:e.playing};c=e.clips[i].duration,l=e.clips[i].name,e.play(i),u=t=>{e.seek(t),y(r,s,`source`,o)},d=()=>{e.play(f.clip),e.seek(f.time),e.playing=f.playing}}let f=Math.max(1,Math.ceil(c*r)),p=Array.from(this.map.keys()).filter(e=>this.map[e]>=0),m=p.map(()=>[]),h=[],g=this.output;try{for(let e=0;e<=f;e++){let t=c*e/f;if(u(t),this.pose(o,g),p.forEach((e,n)=>m[n].push({time:t,value:Array.from(g.subarray(e*10+3,e*10+7))})),this.hip>=0&&h.push({time:t,value:Array.from(g.subarray(this.hip*10,this.hip*10+3))}),c===0)break}}finally{d()}let _=p.map((e,t)=>({target:this.target.names[e],path:`rotation`,keys:m[t]}));this.hip>=0&&_.push({target:this.target.names[this.hip],path:`translation`,keys:h});let v=/* @__PURE__ */ new Set;for(let e of _)if(v.has(e.target+e.path))throw RangeError(`Retarget target rig repeats bone name ${e.target}; give target bones unique names`);else v.add(e.target+e.path);return t({name:i??l,tracks:_})}};export{x as Retarget,d as cloneModel,b as retargetRig};
4
+ import{a as e,i as t,s as n}from"./keyframes-YpidiYS4.js";import{MargoError as r}from"@margoengine/math/errors";import{normalizeQuaternion as i}from"@margoengine/math/quat";import{PBRModel as a,closeImages as o}from"@margoengine/gltf/pbr-model";var s=0,c=(e,t)=>{let n=t+s++;for(;e.plugins?.has(n);)n+=`:`;return n};function l(e,t){return{scene:t,run(n){if(!t)return n();let r,i={coreRequirement:/*@__PURE__*/__margoCoreRequirement("1.0.0",import.meta.url),name:c(e,`scene-scope:`),setup(){r=n()}};return t.use(i),t.removePlugin(i.name),r}}}var u=[0,0,0,1];async function d(e){if(!(e instanceof a))throw TypeError(`cloneModel needs a glTF PBR PBRModel; pass a loaded model`);if(e.disposed)throw new r(`disposed`,`cloneModel source is disposed; clone a live model`);let t=e.shareImages(),n=e.asset.doc,i=e.root.engine,s;if(!n.buffers?.length){let t=/* @__PURE__ */ new Map;for(let n of[...e.primitives,...e.pointsAndLines])t.set(n.definition,n.topology?{vertices:n.vertices,indices:n.indices,topology:n.topology}:n);s=(n.meshes??[]).map(e=>(e.primitives??[]).map(e=>t.get(e)))}let c=l(i,i.sceneOf(e)),d=c.run(()=>{let n;try{n=new a(i,e.asset,t,s);let r=i.store.transforms,o=(e,t)=>{let n=e.id,i=r.x[n],a=r.y[n],o=r.z[n],s=r.sx[n],c=r.sy[n],l=r.sz[n];Number.isFinite(i+a+o)?t.position.set(i,a,o):t.setPosition([i,a,o]),Number.isFinite(s+c+l)?t.scale.set(s,c,l):t.setScale([s,c,l]),u[0]=r.qx[n],u[1]=r.qy[n],u[2]=r.qz[n],u[3]=r.qw[n],t.setQuaternion(u),t.visible=e.visible};return o(e.root,n.root),e.nodes.forEach((e,t)=>o(e,n.nodes[t])),e.primitives.forEach((e,t)=>n.primitives[t]?.weights.set(e.weights)),n.adoptStaticBatches(e),i.plugins.get(e.name)===e&&i.use(n),n}catch(e){throw n?n.dispose():o(t),e}});try{await c.run(()=>d.attachStrokes())}catch(e){throw d.dispose(),e}return d}var f=[0,0,0,0],p=e=>({rotation:new Float64Array(e.names.length*4),position:new Float64Array(e.names.length*3),scale:new Float64Array(e.names.length*3)});function m(e,t){let{names:n,parents:r,rest:i}=e??{},a=n?.length;if(!Array.isArray(n)||!Array.isArray(r)||r.length!==a||!(i instanceof Float64Array))throw TypeError(`Retarget ${t} needs a rig with names, parents and rest; make it with retargetRig`);if(i.length!==a*10||!i.every(Number.isFinite))throw RangeError(`Retarget ${t} rest pose needs 10 finite numbers per bone`);let o=r.map(()=>[]),s=[];r.forEach((e,n)=>{if(!Number.isInteger(e)||e<-1||e>=a||e===n)throw RangeError(`Retarget ${t} bone ${n} parent ${e} is invalid; use -1 or another bone's index`);e>=0&&o[e].push(n)});for(let e=r.flatMap((e,t)=>e<0?[t]:[]);e.length;){let t=e.pop();s.push(t),e.push(...o[t])}if(s.length!==a)throw RangeError(`Retarget ${t} parents form a cycle; every chain must reach a top bone`);return s}function h(e,t,n,r,i,a){let o=n[r],s=n[r+1],c=n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];e[t]=l*u+o*p+s*f-c*d,e[t+1]=l*d-o*f+s*p+c*u,e[t+2]=l*f+o*d-s*u+c*p,e[t+3]=l*p-o*u-s*d-c*f}function g(e,t,n,r,i,a){let o=-n[r],s=-n[r+1],c=-n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];e[t]=l*u+o*p+s*f-c*d,e[t+1]=l*d-o*f+s*p+c*u,e[t+2]=l*f+o*d-s*u+c*p,e[t+3]=l*p-o*u-s*d-c*f}function _(e,t,n,r,i,a,o,s=!1){let c=s?-1:1,l=n[r]*c,u=n[r+1]*c,d=n[r+2]*c,f=n[r+3],p=2*(u*o-d*a),m=2*(d*i-l*o),h=2*(l*a-u*i);e[t]=i+f*p+u*h-d*m,e[t+1]=a+f*m+d*p-l*h,e[t+2]=o+f*h+l*m-u*p}function v(e,t,n,r,i,a){for(let o=0;o<e.length;o++){let s=e[o],c=t[s],l=s*10;if(c<0){for(let e=0;e<3;e++)i[s*3+e]=n[l+e],a[s*3+e]=n[l+7+e];for(let e=0;e<4;e++)r[s*4+e]=n[l+3+e]}else{h(r,s*4,r,c*4,n,l+3),_(i,s*3,r,c*4,a[c*3]*n[l],a[c*3+1]*n[l+1],a[c*3+2]*n[l+2]);for(let e=0;e<3;e++)i[s*3+e]+=i[c*3+e],a[s*3+e]=a[c*3+e]*n[l+7+e]}}}function y(e,t,r,i){if(e instanceof n){if(e.count!==t)throw RangeError(`Retarget ${r} has ${e.count} bones but its rig has ${t}; use a source with the rig's bone count`);for(let n=0;n<t;n++){let{translation:t,rotation:r,scale:a}=e.getPose(n);i.set(t,n*10),i.set(r,n*10+3),i.set(a,n*10+7)}return}if(!(e instanceof a))throw TypeError(`Retarget ${r} must be a Skeleton or a glTF PBR model`);if(e.nodes.length!==t)throw RangeError(`Retarget ${r} has ${e.nodes.length} nodes but its rig ${t}; use its own rig`);let o=e.root.engine.store.transforms;for(let n=0;n<t;n++){let t=e.nodes[n].id,r=n*10;i[r]=o.x[t],i[r+1]=o.y[t],i[r+2]=o.z[t],i[r+3]=o.qx[t],i[r+4]=o.qy[t],i[r+5]=o.qz[t],i[r+6]=o.qw[t],i[r+7]=o.sx[t],i[r+8]=o.sy[t],i[r+9]=o.sz[t]}}function b(e){if(e instanceof n){let t=new Float64Array(e.count*10);return y(e,e.count,`skeleton`,t),{names:e.names,parents:e.parents,rest:t}}if(!(e instanceof a))throw TypeError(`retargetRig needs a Skeleton or a glTF PBR model`);let t=new Map(e.nodes.map((e,t)=>[e.id,t])),r=e.root.engine.store.parents,i=new Float64Array(e.nodes.length*10);return y(e,e.nodes.length,`model`,i),{names:e.nodes.map(e=>e.name),parents:e.nodes.map(e=>t.get(r[e.id])??-1),rest:i}}var x=class{constructor(e,t,n={}){this.source=e,this.target=t,this.delta=/* @__PURE__ */ new Float64Array(4),this.quaternion=[0,0,0,1],this.vector=[0,0,0],this.sourceOrder=m(e,`source`),this.targetOrder=m(t,`target`);let r=n.names??{};if(typeof r!=`object`)throw TypeError(`Retarget names must map target bone names to source bone names`);for(let[t,n]of Object.entries(r))if(typeof n!=`string`||n&&!e.names.includes(n))throw RangeError(`Retarget maps ${t} to ${n}, which the source does not have; fix the names map`);let i=e=>Object.hasOwn(r,e)?r[e]:e;if(this.map=Int32Array.from(t.names,t=>i(t)?e.names.indexOf(i(t)):-1),!this.map.some(e=>e>=0))throw RangeError(`Retarget maps no bones; pass a names map or use rigs with matching bone names`);let a=n.hold??[];if(!Array.isArray(a))throw TypeError(`Retarget hold must be an array of target bone names`);this.held=new Uint8Array(t.names.length);for(let e of a){let n=typeof e==`string`?t.names.indexOf(e):-1;if(n<0)throw RangeError(`Retarget holds ${String(e)}, which the target does not have; fix the hold list`);this.map[n]<0&&(this.held[n]=1)}this.sourceNow=p(e),this.targetNow=p(t);let o=this.sourceRest=p(e),s=this.targetRest=p(t);if(v(this.sourceOrder,e.parents,e.rest,o.rotation,o.position,o.scale),v(this.targetOrder,t.parents,t.rest,s.rotation,s.position,s.scale),this.hip=n.hip===void 0?-1:t.names.indexOf(n.hip),n.hip!==void 0&&this.hip<0)throw RangeError(`Retarget hip ${n.hip} is not a target bone; pass the target's hip bone name`);if(this.sourceHip=this.hip<0?-1:this.map[this.hip],this.hip>=0&&this.sourceHip<0)throw RangeError(`Retarget hip ${n.hip} has no source bone; map it in names`);let c=this.sourceHip<0?0:o.position[this.sourceHip*3+1],l=this.hip<0?0:s.position[this.hip*3+1],u=n.hipScale??(c>0&&l>0?l/c:1);if(typeof u!=`number`||!Number.isFinite(u)||u<=0)throw RangeError(`Retarget hipScale ${u} is invalid; pass a finite number > 0`);this.hipScale=u,this.input=new Float64Array(e.names.length*10),this.output=new Float64Array(t.names.length*10),this.poses=t.names.map((e,t)=>({rotation:this.output.subarray(t*10+3,t*10+7),...t===this.hip?{translation:this.output.subarray(t*10,t*10+3)}:{}}))}pose(e,t=new Float64Array(this.target.names.length*10)){if(!(e instanceof Float64Array)||e.length!==this.source.names.length*10)throw TypeError(`Retarget pose needs a Float64Array of ${this.source.names.length*10} numbers`);if(!(t instanceof Float64Array)||t.length!==this.target.names.length*10)throw TypeError(`Retarget output needs a Float64Array of ${this.target.names.length*10} numbers`);let n=this.sourceNow,r=this.targetNow,{parents:a,rest:o}=this.target,s=this.delta;v(this.sourceOrder,this.source.parents,e,n.rotation,n.position,n.scale),t.set(o);for(let e=0;e<this.targetOrder.length;e++){let o=this.targetOrder[e],c=a[o],l=this.map[o],u=o*10;if(l>=0){if(g(s,0,this.sourceRest.rotation,l*4,this.targetRest.rotation,o*4),h(r.rotation,o*4,n.rotation,l*4,s,0),c<0)for(let e=0;e<4;e++)t[u+3+e]=r.rotation[o*4+e];else g(t,u+3,r.rotation,c*4,r.rotation,o*4);for(let e=0;e<4;e++)f[e]=t[u+3+e];t.set(i(f,f),u+3)}if(o===this.hip){let e=this.hipScale,i=this.sourceHip*3,a=this.targetRest.position[o*3]+e*(n.position[i]-this.sourceRest.position[i]),s=this.targetRest.position[o*3+1]+e*(n.position[i+1]-this.sourceRest.position[i+1]),l=this.targetRest.position[o*3+2]+e*(n.position[i+2]-this.sourceRest.position[i+2]);if(c<0)t[u]=a,t[u+1]=s,t[u+2]=l;else{_(t,u,r.rotation,c*4,a-r.position[c*3],s-r.position[c*3+1],l-r.position[c*3+2],!0);for(let e=0;e<3;e++)t[u+e]/=r.scale[c*3+e]}}if(c<0){for(let e=0;e<3;e++)r.position[o*3+e]=t[u+e],r.scale[o*3+e]=t[u+7+e];for(let e=0;e<4;e++)r.rotation[o*4+e]=t[u+3+e]}else{h(r.rotation,o*4,r.rotation,c*4,t,u+3),_(r.position,o*3,r.rotation,c*4,r.scale[c*3]*t[u],r.scale[c*3+1]*t[u+1],r.scale[c*3+2]*t[u+2]);for(let e=0;e<3;e++)r.position[o*3+e]+=r.position[c*3+e],r.scale[o*3+e]=r.scale[c*3+e]*t[u+7+e]}}return t}apply(e,t){y(e,this.source.names.length,`source`,this.input);let r=this.pose(this.input,this.output);if(t instanceof n){if(t.count!==this.target.names.length)throw RangeError(`Retarget target has ${t.count} bones but its rig has ${this.target.names.length}; pass a target with the rig's bone count`);for(let e=0;e<this.map.length;e++)(this.map[e]>=0||this.held[e]||e===this.hip)&&t.setPose(e,this.poses[e]);return}if(!(t instanceof a))throw TypeError(`Retarget target must be a Skeleton or a glTF PBR model`);if(t.nodes.length!==this.target.names.length)throw RangeError(`Retarget target has ${t.nodes.length} nodes but its rig has ${this.target.names.length}; pass a model with the rig's node count`);let i=this.quaternion,o=this.vector;for(let e=0;e<this.map.length;e++){if(this.map[e]>=0||this.held[e]){for(let t=0;t<4;t++)i[t]=r[e*10+3+t];t.nodes[e].setQuaternion(i)}if(e===this.hip){for(let t=0;t<3;t++)o[t]=r[e*10+t];t.nodes[e].setPosition(o)}}}clip(n,{fps:r=30,name:i}={}){if(typeof r!=`number`||!Number.isFinite(r)||r<=0||r>1e3)throw RangeError(`Retarget clip fps ${r} is invalid; pass frames per second from 0 to 1000`);let o=this.input,s=this.source.names.length,c,l,u,d=()=>{};if(`tracks`in n&&Array.isArray(n.tracks)){let t=n,r=t.tracks.filter(e=>e.path!==`weights`&&this.source.names.includes(e.target)),i=r.map(e=>this.source.names.indexOf(e.target)*10),a=/* @__PURE__ */ new Float64Array(4);c=t.duration,l=t.name,u=t=>{o.set(this.source.rest),r.forEach((n,r)=>{let s=e(n,t,a),c=i[r]+(n.path===`translation`?0:n.path===`rotation`?3:7);for(let e=0;e<(n.path===`rotation`?4:3);e++)o[c+e]=s[e]})}}else{let{animation:e,clip:t}=n,r=e?.model;if(!(r instanceof a)||!Array.isArray(e.clips)||typeof e.seek!=`function`)throw TypeError(`Retarget clip needs a KeyframeClip or {animation, clip} with an Animation`);let i=typeof t==`string`?e.clips.findIndex(e=>e.name===t):t;if(!Number.isInteger(i)||i<0||i>=e.clips.length)throw RangeError(`Retarget clip ${t} is not one of the source model's clips; pass a name or index it has`);let f={clip:e.clip,time:e.time,playing:e.playing};c=e.clips[i].duration,l=e.clips[i].name,e.play(i),u=t=>{e.seek(t),y(r,s,`source`,o)},d=()=>{e.play(f.clip),e.seek(f.time),e.playing=f.playing}}let f=Math.max(1,Math.ceil(c*r)),p=Array.from(this.map.keys()).filter(e=>this.map[e]>=0||this.held[e]),m=p.map(()=>[]),h=[],g=this.output;try{for(let e=0;e<=f;e++){let t=c*e/f;if(u(t),this.pose(o,g),p.forEach((e,n)=>m[n].push({time:t,value:Array.from(g.subarray(e*10+3,e*10+7))})),this.hip>=0&&h.push({time:t,value:Array.from(g.subarray(this.hip*10,this.hip*10+3))}),c===0)break}}finally{d()}let _=p.map((e,t)=>({target:this.target.names[e],path:`rotation`,keys:m[t]}));this.hip>=0&&_.push({target:this.target.names[this.hip],path:`translation`,keys:h});let v=/* @__PURE__ */ new Set;for(let e of _)if(v.has(e.target+e.path))throw RangeError(`Retarget target rig repeats bone name ${e.target}; give target bones unique names`);else v.add(e.target+e.path);return t({name:i??l,tracks:_})}};export{x as Retarget,d as cloneModel,b as retargetRig};