@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/LICENSE +201 -201
- package/NOTICE +4 -4
- package/README.md +1173 -1054
- package/dist/batch.d.ts +8 -1
- package/dist/clip-utils.js +1 -1
- package/dist/cor.d.ts +52 -0
- package/dist/cor.js +17 -0
- package/dist/deformed-points.d.ts +1 -1
- package/dist/deformed-points.js +2 -2
- package/dist/dqs.d.ts +2 -1
- package/dist/dqs.js +3 -3
- package/dist/geometry-cache.js +2 -2
- package/dist/index.d.ts +5 -3
- package/dist/index.js +1 -1
- package/dist/instanced-morph.js +3 -3
- package/dist/instanced-skin.js +3 -3
- package/dist/interactivity.js +2 -2
- package/dist/{keyframes-BO50xipp.js → keyframes-YpidiYS4.js} +2 -2
- package/dist/lod.js +2 -2
- package/dist/mixer.js +2 -2
- package/dist/morph-gpu.d.ts +21 -3
- package/dist/morph-gpu.js +8 -6
- package/dist/morph-table.d.ts +29 -0
- package/dist/playback.js +2 -2
- package/dist/{pointer-BOFnz0gk.js → pointer-DyWpFsQi.js} +1 -1
- package/dist/pointer.js +1 -1
- package/dist/pose.d.ts +9 -4
- package/dist/retarget.d.ts +11 -3
- package/dist/{shader-CgAVFeOl.js → shader-DuGkHFKx.js} +15 -8
- package/dist/shader.d.ts +34 -2
- package/dist/skeleton-utils.js +2 -2
- package/dist/src-fuuIJ3rU.js +4 -0
- package/dist/{vat-mWaj5B5R.js → vat-SpfL7y9U.js} +5 -2
- package/dist/vat.d.ts +19 -3
- package/dist/vat.js +1 -1
- package/package.json +141 -133
- package/dist/src-WGCsukxV.js +0 -4
package/dist/batch.d.ts
CHANGED
|
@@ -39,6 +39,10 @@ export interface SlotSpec {
|
|
|
39
39
|
count: number;
|
|
40
40
|
/** Morph targets. */
|
|
41
41
|
targets: number;
|
|
42
|
+
/** 32-bit words of the morph table (morph-table.ts), a multiple of 4; 0 without targets. */
|
|
43
|
+
morphWords: number;
|
|
44
|
+
/** Words per morph table entry: 8, or 12 with tangents. */
|
|
45
|
+
morphStride: number;
|
|
42
46
|
/** Skin joints; 0 for a morph-only primitive. */
|
|
43
47
|
joints: number;
|
|
44
48
|
/** Eight influences per vertex (JOINTS_1/WEIGHTS_1) rather than four. */
|
|
@@ -49,7 +53,8 @@ export interface SlotSpec {
|
|
|
49
53
|
asset: object;
|
|
50
54
|
definition: object;
|
|
51
55
|
skin: number | undefined;
|
|
52
|
-
|
|
56
|
+
/** The morph table's words; read once, when the first copy of the primitive is placed on a page. */
|
|
57
|
+
deltas(): Uint32Array;
|
|
53
58
|
influences(): Uint32Array;
|
|
54
59
|
}
|
|
55
60
|
/** A placed primitive: where its inputs and its deformed output live. */
|
|
@@ -58,6 +63,8 @@ export interface Slot {
|
|
|
58
63
|
readonly primitive: PBRPrimitive;
|
|
59
64
|
readonly count: number;
|
|
60
65
|
readonly targets: number;
|
|
66
|
+
/** Words per morph table entry. */
|
|
67
|
+
readonly morphStride: number;
|
|
61
68
|
readonly joints: number;
|
|
62
69
|
readonly extra: boolean;
|
|
63
70
|
readonly mode?: SkinningMode;
|
package/dist/clip-utils.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,i as t}from"./keyframes-
|
|
1
|
+
import{a as e,i as t}from"./keyframes-YpidiYS4.js";import{interpolateQuaternions as n,multiplyQuaternions as r}from"@margoengine/math/quat";var i=e=>e.values.length/e.times.length,a=e=>e!==`linear`&&e!==`discrete`;function o(t,n,r,o){let{times:s,values:c,interpolations:l,tangents:u}=t,d=i(t),f=s.length-1,p=[],m=(r,i)=>p.push({time:r-n,value:Array.from(e(t,r).subarray(0,d)),interpolation:i}),h=(e,t=l[e])=>{let r={time:s[e]-n,value:Array.from(c.subarray(e*d,(e+1)*d)),interpolation:t};if(u){let t=e*d*2;r.inTangent=Array.from(u.subarray(t,t+d)),r.outTangent=Array.from(u.subarray(t+d,t+d*2))}p.push(r)},g=-1;for(;g<f&&s[g+1]<=n;)g++;let _=n;for(;_<r;){let e=g<f?s[g+1]:1/0,t=Math.min(e,r),n=g>=0&&s[g]===_,i=g>=0?l[g]:`linear`;if(g>=0&&g<f&&a(i)&&!(n&&e<=r)){n?h(g,`linear`):m(_,`linear`);let e=Math.max(1,Math.ceil((t-_)*o));for(let n=1;n<e;n++)m(_+(t-_)*n/e,`linear`)}else n?h(g):m(_,a(i)?`linear`:i);_=t,_===e&&g++}return g>=0&&s[g]===r?h(g):m(r,`linear`),p}function s(e,n,r,{name:i=e.name,fps:a=60}={}){if(!Number.isFinite(n)||!Number.isFinite(r)||n<0||r<=n||r>e.duration)throw RangeError(`Subclip range ${n} to ${r} is invalid; use 0 <= start < end <= ${e.duration}`);if(!Number.isFinite(a)||a<=0)throw RangeError(`Subclip fps must be a finite number > 0`);let s=e.tracks.map(e=>({target:e.target,path:e.path,keys:o(e,n,r,a),...e.blend?{blend:e.blend}:{}}));for(let t of e.properties??[])s.push({target:t.target,type:t.type,name:t.name,keys:o(t,n,r,a),...t.blend?{blend:t.blend}:{},...t.property===void 0?{get:()=>t.read(),set:e=>t.write(e)}:{property:t.property}});return t({name:i,tracks:s,markers:(e.markers??[]).filter(e=>e.time>=n&&e.time<=r).map(e=>({...e,time:e.time-n}))})}function c(e,t,n,r=30,i){if(!Number.isInteger(t)||!Number.isInteger(n)||!Number.isFinite(r)||r<=0)throw RangeError(`Subclip frames must be integers and the frame rate a finite number > 0`);return s(e,t/r,n/r,i)}function l(n,a={}){let{clip:o=n,time:s=0,name:c=n.name+` (additive)`}=a;if(!Number.isFinite(s)||s<0)throw RangeError(`Additive reference time must be finite and >= 0`);let l=n.tracks.map(t=>{let n=o.tracks.find(e=>e.target===t.target&&e.path===t.path);if(!n)throw RangeError(`Additive reference has no ${t.path} track for ${t.target}; use a reference clip that animates it`);let a=e(n,s),c=i(t),l=t.path===`rotation`?[-a[0],-a[1],-a[2],a[3]]:void 0;if(t.path===`weights`&&a.length!==c)throw RangeError(`Additive reference for ${t.target} has a different morph target count; use a reference clip of the same model`);let u=(e,n)=>l?Array.from(r(l,e)):Array.from(e,(e,r)=>t.path===`scale`?a[r]===0?+!n:e/a[r]:n?e:e-a[r]),d=Array.from(t.times,(e,n)=>{let r={time:e,value:u(t.values.subarray(n*c,(n+1)*c),!1),interpolation:t.interpolations[n]};if(t.tangents){let e=n*c*2;r.inTangent=u(t.tangents.subarray(e,e+c),!0),r.outTangent=u(t.tangents.subarray(e+c,e+c*2),!0)}return r});return{target:t.target,path:t.path,keys:d,...t.blend?{blend:t.blend}:{}}});return t({name:c,tracks:l,markers:n.markers??[]})}function u(t,i,a,o=1){if(!Number.isFinite(o)||o<0)throw RangeError(`Additive weight must be finite and >= 0`);for(let s of t.tracks){if(s.path===`weights`||!i.names.includes(s.target))continue;let t=i.index(s.target),c=i.getPose(t),l=e(s,a);if(s.path===`translation`)i.setPose(t,{translation:c.translation.map((e,t)=>e+l[t]*o)});else if(s.path===`scale`)i.setPose(t,{scale:c.scale.map((e,t)=>e*(1+(l[t]-1)*o))});else{let e=n([0,0,0,1],l,o,.9995);i.setPose(t,{rotation:Array.from(r(c.rotation,e))})}}}export{u as applyAdditiveClip,l as makeAdditive,s as subclip,c as subclipFrames};
|
package/dist/cor.d.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type SkinMeshPart, type SkinningMode } from './shader.js';
|
|
2
|
+
import { type SkinnedVertex } from './dqs.js';
|
|
3
|
+
/** Options of {@link rotationCentres}. */
|
|
4
|
+
export interface RotationCentreOptions {
|
|
5
|
+
/** Width of the weight similarity kernel (the paper's sigma). Default 0.1. */
|
|
6
|
+
sigma?: number;
|
|
7
|
+
/**
|
|
8
|
+
* Triangles whose weights agree to within `1 / steps` per bone are summed together before the vertices read them, so
|
|
9
|
+
* the work grows with the variety of weights, not the triangle count. Vertex weights are used exactly. Default 16.
|
|
10
|
+
*/
|
|
11
|
+
steps?: number;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Every vertex's centre of rotation (Le and Hodgins 2016), for all primitives of one skinned mesh in their bind pose:
|
|
15
|
+
* one `Float32Array` per part, four numbers per vertex, the centre then 1, or the vertex's own position then 0 where
|
|
16
|
+
* no triangle shares two of its bones (a vertex on one bone, whose skin is rigid wherever its centre is).
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```ts
|
|
20
|
+
* import { rotationCentres } from '@margoengine/animation/cor';
|
|
21
|
+
* // Two triangles along x, the left one on bone 0, the right one half and half on bones 0 and 1.
|
|
22
|
+
* const [centres] = rotationCentres([{
|
|
23
|
+
* positions: [0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0],
|
|
24
|
+
* triangles: [0, 1, 2, 1, 3, 2],
|
|
25
|
+
* joints: [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0],
|
|
26
|
+
* weights: [1, 0, 0, 0, 0.5, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0.5, 0.5, 0, 0],
|
|
27
|
+
* influences: 4,
|
|
28
|
+
* }]);
|
|
29
|
+
* console.log(centres.length); // 16: four numbers for each of the four vertices
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
export declare function rotationCentres(parts: readonly SkinMeshPart[], options?: RotationCentreOptions): Float32Array[];
|
|
33
|
+
/**
|
|
34
|
+
* One vertex under bones encoded by `encodeDualQuaternions` (`@margoengine/animation/dqs`), about its centre of
|
|
35
|
+
* rotation `centre` (from {@link rotationCentres}): the shader's steps in double precision, for checks and CPU picking.
|
|
36
|
+
* `joints` and `weights` are parallel, weights summing to 1; the normal comes back unit length.
|
|
37
|
+
*/
|
|
38
|
+
export declare function skinCenterOfRotation(slots: Float32Array, joints: ArrayLike<number>, weights: ArrayLike<number>, position: ArrayLike<number>, normal?: ArrayLike<number>, centre?: ArrayLike<number>): SkinnedVertex;
|
|
39
|
+
/**
|
|
40
|
+
* The `skinning` option of `Animation` for skinning with optimized centres of rotation (Le and Hodgins 2016): no
|
|
41
|
+
* collapse at a bent or twisted joint and no bulge on the outside of a bend. Each skinned mesh's centres are computed
|
|
42
|
+
* once, from all of its primitives in the bind pose ({@link rotationCentres}); its `blend` gives the same pose on the
|
|
43
|
+
* CPU for synchronous raycasts. `@margoengine/humans` `addPerson` uses it by default.
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* ```ts
|
|
47
|
+
* import { Animation } from '@margoengine/animation';
|
|
48
|
+
* import { centerOfRotationSkinning } from '@margoengine/animation/cor';
|
|
49
|
+
* const animation = Animation.attach(model, { skinning: centerOfRotationSkinning });
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
52
|
+
export declare const centerOfRotationSkinning: SkinningMode;
|
package/dist/cor.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{t as e}from"./shader-DuGkHFKx.js";import{encodeDualQuaternions as t}from"./dqs.js";var n=16;function r(e,t,n,r){n.length=r.length=0;let i=0;for(let a=0;a<e.influences;a++){let o=e.weights[t*e.influences+a];if(!(o>0))continue;let s=e.joints[t*e.influences+a],c=n.indexOf(s);c>=0?r[c]+=o:(n.push(s),r.push(o)),i+=o}for(let e=1;e<n.length;e++)for(let t=e;t>0&&n[t-1]>n[t];t--)[n[t-1],n[t]]=[n[t],n[t-1]],[r[t-1],r[t]]=[r[t],r[t-1]];for(let e=0;e<r.length;e++)r[e]/=i}function i(e,t={}){let n=t.sigma??.1,i=t.steps??16;if(!(n>0)||!Number.isFinite(n))throw RangeError(`rotationCentres sigma must be a positive number`);if(!(i>=1)||!Number.isInteger(i))throw RangeError(`rotationCentres steps must be a whole number >= 1`);for(let t of e){let e=t.positions.length/3;if(!Number.isInteger(e)||t.joints.length!==e*t.influences||t.weights.length!==e*t.influences)throw RangeError("rotationCentres parts need three positions and `influences` joints and weights per vertex");if(t.triangles&&t.triangles.length%3)throw RangeError(`rotationCentres triangles must come in threes`)}let a=n*n,o=/* @__PURE__ */ new Map,s=[],c=[],l=/* @__PURE__ */ new Map;for(let t of e){let e=t.triangles,n=t.positions,a=n.length/3;if(e)for(let u=0;u<e.length;u+=3){let d=e[u],f=e[u+1],p=e[u+2];if(d>=a||f>=a||p>=a)throw RangeError(`rotationCentres triangle corner out of range`);let m=n[f*3]-n[d*3],h=n[f*3+1]-n[d*3+1],g=n[f*3+2]-n[d*3+2],_=n[p*3]-n[d*3],v=n[p*3+1]-n[d*3+1],y=n[p*3+2]-n[d*3+2],b=.5*Math.hypot(h*y-g*v,g*_-m*y,m*v-h*_);if(!(b>0))continue;l.clear();for(let e of[d,f,p]){r(t,e,s,c);for(let e=0;e<s.length;e++)l.set(s[e],(l.get(s[e])??0)+c[e]/3)}if(l.size<2)continue;let x=[...l.keys()].sort((e,t)=>e-t),S=``;for(let e of x)S+=e+`:`+Math.round(l.get(e)*i)+`,`;let C=o.get(S);C||o.set(S,C={bones:x,weights:new Float64Array(x.length),area:0,x:0,y:0,z:0});for(let e=0;e<x.length;e++)C.weights[e]+=l.get(x[e])*b;C.area+=b,C.x+=b*(n[d*3]+n[f*3]+n[p*3])/3,C.y+=b*(n[d*3+1]+n[f*3+1]+n[p*3+1])/3,C.z+=b*(n[d*3+2]+n[f*3+2]+n[p*3+2])/3}}let u=[...o.values()],d=0;for(let e of u){for(let t=0;t<e.weights.length;t++)e.weights[t]/=e.area;d=Math.max(d,e.bones[e.bones.length-1])}for(let t of e)for(let e=0;e<t.joints.length;e++)d=Math.max(d,t.joints[e]);let f=d+1,p=/* @__PURE__ */ new Map;u.forEach((e,t)=>{let n=e.bones;for(let e=0;e<n.length;e++)for(let r=e+1;r<n.length;r++){let i=n[e]*f+n[r],a=p.get(i);a||p.set(i,a=[]),a.push(t)}});let m=new Int32Array(u.length).fill(-1),h=new Float64Array(f),g=/* @__PURE__ */ new Map,_=[],v=0;for(let t of e){let e=t.positions,n=e.length/3,i=new Float32Array(n*4);for(let o=0;o<n;o++){if(i[o*4]=e[o*3],i[o*4+1]=e[o*3+1],i[o*4+2]=e[o*3+2],r(t,o,s,c),s.length<2)continue;let n=``;for(let e=0;e<s.length;e++)n+=s[e]+`:`+Math.round(c[e]*4096)+`,`;let l=g.get(n);if(l===void 0){v++;for(let e=0;e<s.length;e++)h[s[e]]=c[e];let e=0,t=0,r=0,i=0;for(let n=0;n<s.length;n++)for(let o=n+1;o<s.length;o++)for(let c of p.get(s[n]*f+s[o])??[]){if(m[c]===v)continue;m[c]=v;let n=u[c],o=n.bones,s=n.weights,l=0;for(let e=0;e<o.length;e++){let t=h[o[e]];if(!t)continue;let n=s[e];for(let r=e+1;r<o.length;r++){let e=h[o[r]];if(!e)continue;let i=s[r],c=t*i-e*n;l+=t*e*n*i*Math.exp(-(c*c)/a)}}l&&(i+=l*n.area,e+=l*n.x,t+=l*n.y,r+=l*n.z)}for(let e=0;e<s.length;e++)h[s[e]]=0;l=i>0?Float64Array.of(e/i,t/i,r/i):null,g.set(n,l)}l&&(i[o*4]=l[0],i[o*4+1]=l[1],i[o*4+2]=l[2],i[o*4+3]=1)}_.push(i)}return _}var a=(e,t,n,r)=>{let i=e[1]*r-e[2]*n+e[3]*t,a=e[2]*t-e[0]*r+e[3]*n,o=e[0]*n-e[1]*t+e[3]*r;return[t+2*(e[1]*o-e[2]*a),n+2*(e[2]*i-e[0]*o),r+2*(e[0]*a-e[1]*i)]};function o(e,t,r,i,o=[0,0,1],s=i){if(t.length!==r.length||!t.length)throw RangeError(`Invalid influences; pass as many joints as weights, at least one`);let c=t[0],l=r[0];for(let e=1;e<t.length;e++)r[e]>l&&(l=r[e],c=t[e]);let u=c*n,d=[0,0,0,0],f=[0,0,0,0,0,0],p=[0,0,0],m=s[0],h=s[1],g=s[2];for(let i=0;i<t.length;i++){let o=t[i]*n,s=r[i],c=0;for(let t=0;t<4;t++)c+=e[o+t]*e[u+t];let l=c<0?-s:s;for(let t=0;t<4;t++)d[t]+=e[o+t]*l;for(let t=0;t<6;t++)f[t]+=e[o+8+t]*s;let _=e.subarray(o,o+4),v=e.subarray(o+4,o+8),y=a(_,e[o+8]*m+e[o+11]*h+e[o+12]*g,e[o+11]*m+e[o+9]*h+e[o+13]*g,e[o+12]*m+e[o+13]*h+e[o+10]*g);p[0]+=s*(y[0]+2*(_[3]*v[0]-v[3]*_[0]+_[1]*v[2]-_[2]*v[1])),p[1]+=s*(y[1]+2*(_[3]*v[1]-v[3]*_[1]+_[2]*v[0]-_[0]*v[2])),p[2]+=s*(y[2]+2*(_[3]*v[2]-v[3]*_[2]+_[0]*v[1]-_[1]*v[0]))}let _=Math.hypot(...d),v=d.map(e=>e/_),y=i[0]-m,b=i[1]-h,x=i[2]-g,S=a(v,f[0]*y+f[3]*b+f[4]*x,f[3]*y+f[1]*b+f[5]*x,f[4]*y+f[5]*b+f[2]*x),C=f[1]*f[2]-f[5]*f[5],w=f[4]*f[5]-f[3]*f[2],T=f[3]*f[5]-f[4]*f[1],E=f[0]*f[2]-f[4]*f[4],D=f[3]*f[4]-f[0]*f[5],O=f[0]*f[1]-f[3]*f[3],k=f[0]*C+f[3]*w+f[4]*T>=0?1:-1,A=k*(C*o[0]+w*o[1]+T*o[2]),j=k*(w*o[0]+E*o[1]+D*o[2]),M=k*(T*o[0]+D*o[1]+O*o[2]),N=A*A+j*j+M*M>0,P=a(v,N?A:0,N?j:1,N?M:0),F=Math.hypot(P[0],P[1],P[2])||1;return{position:[S[0]+p[0],S[1]+p[1],S[2]+p[2]],normal:[P[0]/F,P[1]/F,P[2]/F]}}var s=e=>{let t=[`x`,`y`,`z`,`w`].map(e=>[`joints.${e}`,`jointWeights.${e}`]);if(e)for(let e of[`x`,`y`,`z`,`w`])t.push([`jointsExtra.${e}`,`weightsExtra.${e}`]);return`var pivot=${t[0][0]};var heaviest=${t[0][1]};
|
|
2
|
+
${t.slice(1).map(([e,t])=>`if(${t}>heaviest){heaviest=${t};pivot=${e};}`).join(``)}
|
|
3
|
+
let near=boneMatrices[s.bones+pivot][0];let centre=vertexData.xyz;
|
|
4
|
+
var real=vec4f(0);var stretchA=vec4f(0);var stretchB=vec4f(0);var moved=vec3f(0);
|
|
5
|
+
${t.map(([e,t])=>`{let b=boneMatrices[s.bones+${e}];let k=select(${t},-${t},dot(b[0],near)<0);real+=b[0]*k;stretchA+=b[2]*${t};stretchB+=b[3]*${t};moved+=placed(b,centre)*${t};}`).join(`
|
|
6
|
+
`)}
|
|
7
|
+
let turn=real/length(real);
|
|
8
|
+
let stretch=mat3x3f(stretchA.x,stretchA.w,stretchB.x,stretchA.w,stretchA.y,stretchB.y,stretchB.x,stretchB.y,stretchA.z);
|
|
9
|
+
v.position=vec4f(rotated(turn,stretch*(v.position.xyz-centre))+moved,1);
|
|
10
|
+
let normalMatrix=mat3x3f(cross(stretch[1],stretch[2]),cross(stretch[2],stretch[0]),cross(stretch[0],stretch[1]));
|
|
11
|
+
let handedness=select(-1.0,1.0,dot(stretch[0],cross(stretch[1],stretch[2]))>=0.0);let bent=normalMatrix*v.normal.xyz*handedness;
|
|
12
|
+
v.normal=vec4f(rotated(turn,select(vec3f(0,1,0),bent,dot(bent,bent)>0.0)),0);
|
|
13
|
+
v.tangent=vec4f(rotated(turn,stretch*v.tangent.xyz),v.tangent.w*handedness);`},c=`fn rotated(q:vec4f,x:vec3f)->vec3f {return x+2*cross(q.xyz,cross(q.xyz,x)+q.w*x);}
|
|
14
|
+
fn placed(b:mat4x4f,p:vec3f)->vec3f {
|
|
15
|
+
let st=mat3x3f(b[2].x,b[2].w,b[3].x,b[2].w,b[2].y,b[3].y,b[3].x,b[3].y,b[2].z);
|
|
16
|
+
return rotated(b[0],st*p)+2*(b[0].w*b[1].xyz-b[1].w*b[0].xyz+cross(b[0].xyz,b[1].xyz));
|
|
17
|
+
}`,l={name:`center-of-rotation`,shader:t=>e(t,{functions:c,blend:s(t)},!0),encode:e=>{t(e)},blend:(e,t,n,r,i,a,s)=>o(e,t,n,r,i,s??r),vertexData:e=>i(e)};export{l as centerOfRotationSkinning,i as rotationCentres,o as skinCenterOfRotation};
|
|
@@ -4,7 +4,7 @@ import type { Engine, EnginePlugin, FrameGraph } from '@margoengine/core/extensi
|
|
|
4
4
|
import { type ColorInput } from '@margoengine/math/color';
|
|
5
5
|
/** Options for {@link DeformedPoints}; every one is also a live field of the same name. */
|
|
6
6
|
export interface DeformedPointsOptions {
|
|
7
|
-
/** Point diameter: pixels
|
|
7
|
+
/** Point diameter: CSS pixels, or world units when `sizeUnits` is 'world'. Finite, 0 or more. Default 4. */
|
|
8
8
|
size?: number;
|
|
9
9
|
/** 'pixels' keeps a constant screen size; 'world' shrinks with distance. Default 'pixels'. */
|
|
10
10
|
sizeUnits?: 'pixels' | 'world';
|
package/dist/deformed-points.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// @margo/core-built
|
|
1
|
+
// @margo/core-built 1.0.0
|
|
2
2
|
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
3
|
|
|
4
4
|
import{t as e}from"./deform-readers-DmYAkvBK.js";import{t}from"./require-webgpu-Jrqt3Xy4.js";import{n,r,t as i}from"./hdr-format-cmvLFubB.js";import{MargoError as a}from"@margoengine/math/errors";import{parseColor as o}from"@margoengine/math/color";function s(e,t,n,r,i,a=/* @__PURE__ */ new Float32Array(3)){if(!(t>=0&&Number.isFinite(t))||n!==`pixels`&&n!==`world`||!(r>0&&i>0))throw RangeError(`Invalid point size; pass a finite size >= 0, sizeUnits 'pixels' or 'world' and a view of at least 1 pixel`);if(n===`pixels`)return a[0]=t/r,a[1]=t/i,a[2]=1,a;let o=e[3],s=e[7],c=e[11],l=o*o+s*s+c*c;for(let n=0;n<2;n++){let r=e[n],i=e[4+n],u=e[8+n],d=l>0?(r*o+i*s+u*c)/l:0;a[n]=t/2*Math.hypot(r-d*o,i-d*s,u-d*c)}return a[2]=0,a}var c=`
|
|
@@ -14,4 +14,4 @@ struct Out {@builtin(position) clip:vec4f,@location(0) color:vec4f,@location(1)
|
|
|
14
14
|
let x=clamp(i.color.rgb,vec3f(0.0),vec3f(1.0));
|
|
15
15
|
return vec4f(select(select(x*12.92,1.055*pow(x,vec3f(1.0/2.4))-0.055,x>=vec3f(0.0031308)),i.color.rgb,f.flags.y>0.5),i.color.a);
|
|
16
16
|
}
|
|
17
|
-
`,l=0,u=class u{coreRequirement=__margoCoreRequirement("
|
|
17
|
+
`,l=0,u=class u{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static attach(e,t){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));let n=new u(e,t);return e.root.engine.use(n),n}constructor(e,t={}){if(this.model=e,this.name=`deformed-points:`+l++,this.size=4,this.sizeUnits=`pixels`,this.color=new Float32Array([1,1,1]),this.opacity=1,this.shape=`square`,this.vertexColors=!0,this.visible=!0,this.disposed=!1,this.key=``,this.groups=[],this.own=/* @__PURE__ */ new Map,this.values=/* @__PURE__ */ new Float32Array(44),this.scale=/* @__PURE__ */ new Float32Array(3),this.reading=!1,!Array.isArray(e?.primitives)||!e.root)throw TypeError(`DeformedPoints needs a gltf/pbr model; pass a loaded model or a createMesh mesh`);this.set(t)}set({size:e,sizeUnits:t,color:n,opacity:r,shape:i,vertexColors:a}){let s={size:e??this.size,sizeUnits:t??this.sizeUnits,opacity:r??this.opacity,shape:i??this.shape,vertexColors:a??this.vertexColors};return d(s),n!==void 0&&o(n,this.color),Object.assign(this,s),this}get count(){let e=0;for(let t of this.model.primitives)e+=t.vertices.length/20;return e}setup(e){if(this.disposed)throw new a(`disposed`,`DeformedPoints is disposed; create new points before attaching`);if(this.model.disposed)throw new a(`disposed`,`DeformedPoints model is disposed; attach the points to a live model`);t(e,`DeformedPoints`),this.engine=e,this.unsubscribe??=this.model.onDispose(()=>this.dispose()),this.read(!0)}read(t){if(this.reading===t)return;this.reading=t;let n=(e.get(this.model)??0)+(t?1:-1);n>0?e.set(this.model,n):e.delete(this.model)}registerPasses(e){e.add({name:this.name,order:1,execute:e=>{e.backend===`webgpu`&&this.draw(e)}})}draw(e){let t=this.engine,a=this.model.primitives;if(!t||!this.visible||this.model.disposed||!a.length)return;d(this);let o=e.device;this.device!==o&&(this.release(),this.device=o);let l=e.descriptor.multisample?.count??1,u=e.descriptor.depthStencil.format,f=this.opacity<1,p=e.format+l+u+f;if(this.key!==p){let t=o.createShaderModule({code:c});this.key=p,this.groups=[],this.pipeline=o.createRenderPipeline({layout:`auto`,vertex:{module:t,entryPoint:`vertex`,buffers:[{arrayStride:80,stepMode:`instance`,attributes:[{shaderLocation:0,offset:0,format:`float32x3`},{shaderLocation:1,offset:64,format:`float32x4`}]}]},fragment:{module:t,entryPoint:`fragment`,targets:[f?{format:e.format,blend:{color:{srcFactor:`src-alpha`,dstFactor:`one-minus-src-alpha`},alpha:{srcFactor:`one`,dstFactor:`one-minus-src-alpha`}}}:{format:e.format}]},primitive:{topology:`triangle-strip`},depthStencil:{format:u,depthWriteEnabled:!0,depthCompare:`greater-equal`},multisample:{count:l}})}(!this.frames||this.frames.size<a.length*256)&&(this.frames?.destroy(),this.frames=o.createBuffer({size:a.length*256,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.groups=[]);let m=t.canvas?.clientWidth,h=this.sizeUnits===`pixels`&&m?this.size*(e.width/m):this.size,[g,_]=r(e),v=s(e.camera.matrix,h,this.sizeUnits,g,_,this.scale),y=this.values;y.set(e.camera.matrix),y.set(this.color,32),y[35]=this.opacity,y.set(v,36),y[39]=+(this.shape===`round`),y[40]=+this.vertexColors,y[41]=+i(e.format);let b=e.encoder.beginRenderPass({colorAttachments:[{view:e.color,loadOp:`load`,storeOp:`store`}],depthStencilAttachment:{view:e.depth,depthLoadOp:`load`,depthStoreOp:`store`,stencilReadOnly:!0}});try{n(b,e),b.setPipeline(this.pipeline),a.forEach((e,n)=>{let r=e.vertices.length/20;r&&(y.set(e.node.matrix,16),o.queue.writeBuffer(this.frames,n*256,y),b.setBindGroup(0,this.groups[n]??=o.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.frames,offset:n*256,size:176}}]})),e.deformed?b.setVertexBuffer(0,e.deformed,e.deformedOffset??0,r*80):b.setVertexBuffer(0,this.bind(o,e)),b.draw(4,r),t.stats.drawCalls++)})}finally{b.end()}}bind(e,t){let n=this.own.get(t);return n?.source!==t.vertices&&(n?.buffer.destroy(),n={source:t.vertices,buffer:e.createBuffer({size:t.vertices.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST})},e.queue.writeBuffer(n.buffer,0,t.vertices),this.own.set(t,n)),n.buffer}release(){this.frames?.destroy();for(let{buffer:e}of this.own.values())e.destroy();this.own.clear(),this.frames=this.pipeline=this.device=void 0,this.groups=[],this.key=``}onDeviceRestored(){this.release()}dispose(){this.disposed||(this.disposed=!0,this.read(!1),this.unsubscribe?.(),this.unsubscribe=void 0,this.engine?.sceneOf(this)?.removePlugin(this.name),this.release(),this.engine=void 0)}[Symbol.dispose??Symbol()](){this.dispose()}};function d({size:e,sizeUnits:t,opacity:n,shape:r,vertexColors:i}){if(!(e>=0&&Number.isFinite(e))||t!==`pixels`&&t!==`world`||!(n>=0&&n<=1)||r!==`square`&&r!==`round`)throw RangeError(`Invalid point options; use a finite size >= 0, sizeUnits 'pixels' or 'world', opacity in 0..1 and shape 'square' or 'round'`);if(typeof i!=`boolean`)throw TypeError(`DeformedPoints vertexColors must be true or false`)}export{u as DeformedPoints,c as deformedPointsShader,s as pointScale};
|
package/dist/dqs.d.ts
CHANGED
|
@@ -19,7 +19,8 @@ export declare const dualQuaternionSkinning: SkinningMode;
|
|
|
19
19
|
* does (Autodesk's FbxSkin::eBlend: each control point has its own share of dual quaternion). The share of each vertex
|
|
20
20
|
* comes from the node's `extras.fbxSkinning.blendWeights`, which `@margoengine/fbx/deformers` writes, one number in
|
|
21
21
|
* [0, 1] per vertex of the node's primitive (0 is linear, 1 is all dual quaternion). A node without it is all dual
|
|
22
|
-
* quaternion. Position, normal and tangent blend between the two skins with that share.
|
|
22
|
+
* quaternion. Position, normal and tangent blend between the two skins with that share. Its `blend` gives the same pose
|
|
23
|
+
* on the CPU for synchronous raycasts.
|
|
23
24
|
*
|
|
24
25
|
* @example
|
|
25
26
|
* ```ts
|
package/dist/dqs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{t as e}from"./shader-
|
|
1
|
+
import{t as e}from"./shader-DuGkHFKx.js";var t=16;function n(e,t){t.fill(0),t[0]=t[4]=t[8]=1;for(let n=0;n<12;n++){if(e[1]*e[1]+e[2]*e[2]+e[5]*e[5]<=1e-32*(e[0]*e[0]+e[4]*e[4]+e[8]*e[8]))return;for(let n=0;n<2;n++)for(let r=n+1;r<3;r++){let i=e[n*3+r];if(!i)continue;let a=(e[r*3+r]-e[n*3+n])/(2*i),o=Math.sign(a||1)/(Math.abs(a)+Math.sqrt(a*a+1)),s=1/Math.sqrt(o*o+1),c=o*s;for(let t=0;t<3;t++){let i=e[t*3+n],a=e[t*3+r];e[t*3+n]=s*i-c*a,e[t*3+r]=c*i+s*a}for(let t=0;t<3;t++){let i=e[n*3+t],a=e[r*3+t];e[n*3+t]=s*i-c*a,e[r*3+t]=c*i+s*a}for(let e=0;e<3;e++){let i=t[e*3+n],a=t[e*3+r];t[e*3+n]=s*i-c*a,t[e*3+r]=c*i+s*a}}}}var r=/* @__PURE__ */ new Float64Array(9),i=/* @__PURE__ */ new Float64Array(9),a=/* @__PURE__ */ new Float64Array(9),o=/* @__PURE__ */ new Float64Array(9),s=[0,1,2],c=e=>e[0]*(e[4]*e[8]-e[5]*e[7])-e[1]*(e[3]*e[8]-e[5]*e[6])+e[2]*(e[3]*e[7]-e[4]*e[6]);function l(e,t,l,u){for(let n=0;n<3;n++)for(let i=0;i<3;i++)r[n*3+i]=e[t+n*4]*e[t+i*4]+e[t+n*4+1]*e[t+i*4+1]+e[t+n*4+2]*e[t+i*4+2];n(r,i),s.sort((e,t)=>r[t*4]-r[e*4]);let d=s.map(e=>Math.sqrt(Math.max(r[e*4],0))),f=d[0]*1e-7,p=0;for(let n=0;n<3;n++){let r=s[n];if(!(d[n]<=f||!d[n])){p++;for(let o=0;o<3;o++)a[o*3+n]=(e[t+o]*i[r]+e[t+4+o]*i[3+r]+e[t+8+o]*i[6+r])/d[n]}}if(p===0)for(let e=0;e<3;e++)for(let t=0;t<3;t++)a[t*3+e]=i[t*3+s[e]];else if(p===1){let e=a[0],t=a[3],n=a[6],r=+(Math.abs(e)<.6),i=+!r,o=r*e+i*t,s=r-o*e,c=i-o*t,l=-o*n,u=Math.hypot(s,c,l);a[1]=s/u,a[4]=c/u,a[7]=l/u}p&&p<3&&(a[2]=a[3]*a[7]-a[6]*a[4],a[5]=a[6]*a[1]-a[0]*a[7],a[8]=a[0]*a[4]-a[3]*a[1]);for(let e=0;e<3;e++)for(let t=0;t<3;t++){let n=0;for(let r=0;r<3;r++)n+=a[e*3+r]*i[t*3+s[r]];o[e*3+t]=n}let m=1;if(c(o)<0){if(p===3){m=-1;for(let e=0;e<9;e++)o[e]=-o[e]}else for(let e=0;e<3;e++){let t=s[2];for(let n=0;n<3;n++)o[e*3+n]-=2*a[e*3+2]*i[n*3+t]}}let h=(e,t)=>{let n=0;for(let r=0;r<3;r++)n+=d[r]*i[e*3+s[r]]*i[t*3+s[r]];return m*n};l[u]=h(0,0),l[u+1]=h(1,1),l[u+2]=h(2,2),l[u+3]=h(0,1),l[u+4]=h(0,2),l[u+5]=h(1,2),l[u+6]=l[u+7]=0}function u(e){let t=o,n=t[0]+t[4]+t[8],r,i,a,s;if(n>0){let e=2*Math.sqrt(n+1);s=e/4,r=(t[7]-t[5])/e,i=(t[2]-t[6])/e,a=(t[3]-t[1])/e}else if(t[0]>=t[4]&&t[0]>=t[8]){let e=2*Math.sqrt(Math.max(1+t[0]-t[4]-t[8],0));s=(t[7]-t[5])/e,r=e/4,i=(t[1]+t[3])/e,a=(t[2]+t[6])/e}else if(t[4]>=t[8]){let e=2*Math.sqrt(Math.max(1+t[4]-t[0]-t[8],0));s=(t[2]-t[6])/e,r=(t[1]+t[3])/e,i=e/4,a=(t[5]+t[7])/e}else{let e=2*Math.sqrt(Math.max(1+t[8]-t[0]-t[4],0));s=(t[3]-t[1])/e,r=(t[2]+t[6])/e,i=(t[5]+t[7])/e,a=e/4}let c=Math.hypot(r,i,a,s);e[0]=r/c,e[1]=i/c,e[2]=a/c,e[3]=s/c}var d=/* @__PURE__ */ new Float64Array(4);function f(e,n=e){if(e.length%t||n.length<e.length)throw RangeError(`Invalid bone palette; pass 16 floats per bone and an output at least as long`);for(let r=0;r<e.length;r+=t){let t=e[r+12],i=e[r+13],a=e[r+14];l(e,r,n,r+8),u(d);let[o,s,c,f]=d;n[r]=o,n[r+1]=s,n[r+2]=c,n[r+3]=f,n[r+4]=.5*(t*f+i*c-a*s),n[r+5]=.5*(-t*c+i*f+a*o),n[r+6]=.5*(t*s-i*o+a*f),n[r+7]=-.5*(t*o+i*s+a*c)}return n}var p=(e,t=!1)=>{let n=[`x`,`y`,`z`,`w`].map(e=>[t?`ids.${e}`:`joints.${e}`,`jointWeights.${e}`]);if(e)for(let e of[`x`,`y`,`z`,`w`])n.push([`jointsExtra.${e}`,`weightsExtra.${e}`]);return`var pivot=${n[0][0]};var heaviest=${n[0][1]};
|
|
2
2
|
${n.slice(1).map(([e,t])=>`if(${t}>heaviest){heaviest=${t};pivot=${e};}`).join(``)}
|
|
3
3
|
let near=boneMatrices[s.bones+pivot][0];
|
|
4
4
|
var real=vec4f(0);var dual=vec4f(0);var stretchA=vec4f(0);var stretchB=vec4f(0);
|
|
@@ -11,7 +11,7 @@ import{t as e}from"./shader-CgAVFeOl.js";var t=16;function n(e,t){t.fill(0),t[0]
|
|
|
11
11
|
let normalMatrix=mat3x3f(cross(stretch[1],stretch[2]),cross(stretch[2],stretch[0]),cross(stretch[0],stretch[1]));
|
|
12
12
|
let handedness=select(-1.0,1.0,dot(stretch[0],cross(stretch[1],stretch[2]))>=0.0);let bent=normalMatrix*v.normal.xyz*handedness;
|
|
13
13
|
v.normal=vec4f(rotated(turn,select(vec3f(0,1,0),bent,dot(bent,bent)>0.0)),0);
|
|
14
|
-
v.tangent=vec4f(rotated(turn,stretch*v.tangent.xyz),v.tangent.w*handedness);`},m={name:`dual-quaternion`,shader:t=>e(t,{functions:`fn rotated(q:vec4f,x:vec3f)->vec3f {return x+2*cross(q.xyz,cross(q.xyz,x)+q.w*x);}`,blend:p(t)}),encode:e=>{f(e)}},h=`fn boneMatrix(b:mat4x4f)->mat4x4f {
|
|
14
|
+
v.tangent=vec4f(rotated(turn,stretch*v.tangent.xyz),v.tangent.w*handedness);`},m={name:`dual-quaternion`,shader:t=>e(t,{functions:`fn rotated(q:vec4f,x:vec3f)->vec3f {return x+2*cross(q.xyz,cross(q.xyz,x)+q.w*x);}`,blend:p(t)}),encode:e=>{f(e)},blend:(e,t,n,r,i)=>y(e,t,n,r,i)},h=`fn boneMatrix(b:mat4x4f)->mat4x4f {
|
|
15
15
|
let st=mat3x3f(b[2].x,b[2].w,b[3].x,b[2].w,b[2].y,b[3].y,b[3].x,b[3].y,b[2].z);
|
|
16
16
|
let shift=2*(b[0].w*b[1].xyz-b[1].w*b[0].xyz+cross(b[0].xyz,b[1].xyz));
|
|
17
17
|
return mat4x4f(vec4f(rotated(b[0],st[0]),0),vec4f(rotated(b[0],st[1]),0),vec4f(rotated(b[0],st[2]),0),vec4f(shift,1));
|
|
@@ -26,4 +26,4 @@ import{t as e}from"./shader-CgAVFeOl.js";var t=16;function n(e,t){t.fill(0),t[0]
|
|
|
26
26
|
v.normal=vec4f(mix(ln,dnu,share),0);
|
|
27
27
|
v.tangent=vec4f(mix(lt,v.tangent.xyz,share),select(t0.w*hd,v.tangent.w,share>=0.5));}`},_={name:`dual-quaternion-blend`,shader:t=>e(t,{functions:`fn rotated(q:vec4f,x:vec3f)->vec3f {return x+2*cross(q.xyz,cross(q.xyz,x)+q.w*x);}\n${h}`,blend:`let ids=vec4u(joints.x&65535u,joints.y,joints.z,joints.w);let share=f32(joints.x>>16u)/65535.0;
|
|
28
28
|
let p0=v.position;let n0=v.normal;let t0=v.tangent;
|
|
29
|
-
${p(t,!0)}${g(t)}`}),encode:m.encode,share:e=>{let t=e?.fbxSkinning?.blendWeights;return Array.isArray(t)||ArrayBuffer.isView(t)?t:void 0}},v=(e,t,n,r)=>{let i=e[1]*r-e[2]*n+e[3]*t,a=e[2]*t-e[0]*r+e[3]*n,o=e[0]*n-e[1]*t+e[3]*r;return[t+2*(e[1]*o-e[2]*a),n+2*(e[2]*i-e[0]*o),r+2*(e[0]*a-e[1]*i)]};function y(e,n,r,i,a=[0,0,1],o=1){if(n.length!==r.length||!n.length)throw RangeError(`Invalid influences; pass as many joints as weights, at least one`);let s=n[0],c=r[0];for(let e=1;e<n.length;e++)r[e]>c&&(c=r[e],s=n[e]);let l=s*t,u=[0,0,0,0],d=[0,0,0,0],f=[0,0,0,0,0,0];for(let i=0;i<n.length;i++){let a=n[i]*t,o=r[i],s=0;for(let t=0;t<4;t++)s+=e[a+t]*e[l+t];let c=s<0?-o:o;for(let t=0;t<4;t++)u[t]+=e[a+t]*c,d[t]+=e[a+4+t]*c;for(let t=0;t<6;t++)f[t]+=e[a+8+t]*o}let p=Math.hypot(...u),m=u.map(e=>e/p),h=d.map(e=>e/p),g=i[0],_=i[1],y=i[2],x=v(m,f[0]*g+f[3]*_+f[4]*y,f[3]*g+f[1]*_+f[5]*y,f[4]*g+f[5]*_+f[2]*y),S=[2*(m[3]*h[0]-h[3]*m[0]+m[1]*h[2]-m[2]*h[1]),2*(m[3]*h[1]-h[3]*m[1]+m[2]*h[0]-m[0]*h[2]),2*(m[3]*h[2]-h[3]*m[2]+m[0]*h[1]-m[1]*h[0])],C=f[1]*f[2]-f[5]*f[5],w=f[4]*f[5]-f[3]*f[2],T=f[3]*f[5]-f[4]*f[1],E=f[0]*f[2]-f[4]*f[4],D=f[3]*f[4]-f[0]*f[5],O=f[0]*f[1]-f[3]*f[3],k=Math.sign(f[0]*C+f[3]*w+f[4]*T),A=v(m,k*(C*a[0]+w*a[1]+T*a[2]),k*(w*a[0]+E*a[1]+D*a[2]),k*(T*a[0]+D*a[1]+O*a[2])),j=Math.hypot(A[0],A[1],A[2])||1,M={position:[x[0]+S[0],x[1]+S[1],x[2]+S[2]],normal:[A[0]/j,A[1]/j,A[2]/j]};return o>=1?M:b(e,n,r,i,a,o,M)}function b(e,n,r,i,a,o,s){let c=[0,0,0,0,0,0,0,0,0],l=[0,0,0];for(let i=0;i<n.length;i++){let a=n[i]*t,o=r[i],s=[e[a],e[a+1],e[a+2],e[a+3]],u=[e[a+4],e[a+5],e[a+6],e[a+7]],d=[[e[a+8],e[a+11],e[a+12]],[e[a+11],e[a+9],e[a+13]],[e[a+12],e[a+13],e[a+10]]];for(let e=0;e<3;e++){let t=v(s,d[e][0],d[e][1],d[e][2]);for(let n=0;n<3;n++)c[e*3+n]+=t[n]*o}l[0]+=o*2*(s[3]*u[0]-u[3]*s[0]+s[1]*u[2]-s[2]*u[1]),l[1]+=o*2*(s[3]*u[1]-u[3]*s[1]+s[2]*u[0]-s[0]*u[2]),l[2]+=o*2*(s[3]*u[2]-u[3]*s[2]+s[0]*u[1]-s[1]*u[0])}let[u,d,f]=[c.slice(0,3),c.slice(3,6),c.slice(6,9)],p=(e,t)=>[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]],m=[p(d,f),p(f,u),p(u,d)],h=Math.sign(u[0]*m[0][0]+u[1]*m[0][1]+u[2]*m[0][2])||1,g=(e,t)=>[e[0][0]*t[0]+e[1][0]*t[1]+e[2][0]*t[2],e[0][1]*t[0]+e[1][1]*t[1]+e[2][1]*t[2],e[0][2]*t[0]+e[1][2]*t[1]+e[2][2]*t[2]],_=g([u,d,f],i).map((e,t)=>e+l[t]),y=g(m,a).map(e=>e*h),b=Math.hypot(y[0],y[1],y[2]),x=b>0?y.map(e=>e/b):[0,1,0],S=(e,t)=>e+(t-e)*o,C=[S(x[0],s.normal[0]),S(x[1],s.normal[1]),S(x[2],s.normal[2])],w=Math.hypot(C[0],C[1],C[2])||1;return{position:[S(_[0],s.position[0]),S(_[1],s.position[1]),S(_[2],s.position[2])],normal:[C[0]/w,C[1]/w,C[2]/w]}}export{_ as blendSkinning,m as dualQuaternionSkinning,f as encodeDualQuaternions,y as skinDualQuaternion};
|
|
29
|
+
${p(t,!0)}${g(t)}`}),encode:m.encode,blend:(e,t,n,r,i,a)=>y(e,t,n,r,i,a),share:e=>{let t=e?.fbxSkinning?.blendWeights;return Array.isArray(t)||ArrayBuffer.isView(t)?t:void 0}},v=(e,t,n,r)=>{let i=e[1]*r-e[2]*n+e[3]*t,a=e[2]*t-e[0]*r+e[3]*n,o=e[0]*n-e[1]*t+e[3]*r;return[t+2*(e[1]*o-e[2]*a),n+2*(e[2]*i-e[0]*o),r+2*(e[0]*a-e[1]*i)]};function y(e,n,r,i,a=[0,0,1],o=1){if(n.length!==r.length||!n.length)throw RangeError(`Invalid influences; pass as many joints as weights, at least one`);let s=n[0],c=r[0];for(let e=1;e<n.length;e++)r[e]>c&&(c=r[e],s=n[e]);let l=s*t,u=[0,0,0,0],d=[0,0,0,0],f=[0,0,0,0,0,0];for(let i=0;i<n.length;i++){let a=n[i]*t,o=r[i],s=0;for(let t=0;t<4;t++)s+=e[a+t]*e[l+t];let c=s<0?-o:o;for(let t=0;t<4;t++)u[t]+=e[a+t]*c,d[t]+=e[a+4+t]*c;for(let t=0;t<6;t++)f[t]+=e[a+8+t]*o}let p=Math.hypot(...u),m=u.map(e=>e/p),h=d.map(e=>e/p),g=i[0],_=i[1],y=i[2],x=v(m,f[0]*g+f[3]*_+f[4]*y,f[3]*g+f[1]*_+f[5]*y,f[4]*g+f[5]*_+f[2]*y),S=[2*(m[3]*h[0]-h[3]*m[0]+m[1]*h[2]-m[2]*h[1]),2*(m[3]*h[1]-h[3]*m[1]+m[2]*h[0]-m[0]*h[2]),2*(m[3]*h[2]-h[3]*m[2]+m[0]*h[1]-m[1]*h[0])],C=f[1]*f[2]-f[5]*f[5],w=f[4]*f[5]-f[3]*f[2],T=f[3]*f[5]-f[4]*f[1],E=f[0]*f[2]-f[4]*f[4],D=f[3]*f[4]-f[0]*f[5],O=f[0]*f[1]-f[3]*f[3],k=Math.sign(f[0]*C+f[3]*w+f[4]*T),A=v(m,k*(C*a[0]+w*a[1]+T*a[2]),k*(w*a[0]+E*a[1]+D*a[2]),k*(T*a[0]+D*a[1]+O*a[2])),j=Math.hypot(A[0],A[1],A[2])||1,M={position:[x[0]+S[0],x[1]+S[1],x[2]+S[2]],normal:[A[0]/j,A[1]/j,A[2]/j]};return o>=1?M:b(e,n,r,i,a,o,M)}function b(e,n,r,i,a,o,s){let c=[0,0,0,0,0,0,0,0,0],l=[0,0,0];for(let i=0;i<n.length;i++){let a=n[i]*t,o=r[i],s=[e[a],e[a+1],e[a+2],e[a+3]],u=[e[a+4],e[a+5],e[a+6],e[a+7]],d=[[e[a+8],e[a+11],e[a+12]],[e[a+11],e[a+9],e[a+13]],[e[a+12],e[a+13],e[a+10]]];for(let e=0;e<3;e++){let t=v(s,d[e][0],d[e][1],d[e][2]);for(let n=0;n<3;n++)c[e*3+n]+=t[n]*o}l[0]+=o*2*(s[3]*u[0]-u[3]*s[0]+s[1]*u[2]-s[2]*u[1]),l[1]+=o*2*(s[3]*u[1]-u[3]*s[1]+s[2]*u[0]-s[0]*u[2]),l[2]+=o*2*(s[3]*u[2]-u[3]*s[2]+s[0]*u[1]-s[1]*u[0])}let[u,d,f]=[c.slice(0,3),c.slice(3,6),c.slice(6,9)],p=(e,t)=>[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]],m=[p(d,f),p(f,u),p(u,d)],h=Math.sign(u[0]*m[0][0]+u[1]*m[0][1]+u[2]*m[0][2])||1,g=(e,t)=>[e[0][0]*t[0]+e[1][0]*t[1]+e[2][0]*t[2],e[0][1]*t[0]+e[1][1]*t[1]+e[2][1]*t[2],e[0][2]*t[0]+e[1][2]*t[1]+e[2][2]*t[2]],_=g([u,d,f],i).map((e,t)=>e+l[t]),y=g(m,a).map(e=>e*h),b=Math.hypot(y[0],y[1],y[2]),x=b>0?y.map(e=>e/b):[0,1,0],S=(e,t)=>e+(t-e)*o,C=[S(x[0],s.normal[0]),S(x[1],s.normal[1]),S(x[2],s.normal[2])],w=Math.hypot(C[0],C[1],C[2])||1;return{position:[S(_[0],s.position[0]),S(_[1],s.position[1]),S(_[2],s.position[2])],normal:[C[0]/w,C[1]/w,C[2]/w]}}export{_ as blendSkinning,m as dualQuaternionSkinning,f as encodeDualQuaternions,y as skinDualQuaternion};
|
package/dist/geometry-cache.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// @margo/core-built
|
|
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"./pose-source-MuCl8VDd.js";import{MargoError as t}from"@margoengine/math/errors";import{GLTFAsset as n,PBRModel as r}from"@margoengine/gltf/pbr-model";var i=16,a=64,o=1212368717,s=1263421507,c=1,l=1,u=2,d=20,f=e=>new t(`failed`,`Geometry cache ${e}; export the file again`);async function*p(e,t){if(e instanceof Uint8Array)yield e;else{if(`getReader`in e){let n=e.getReader(),r=()=>void n.cancel(t?.reason).catch(()=>{});t?.addEventListener(`abort`,r,{once:!0});try{for(;;){let{done:e,value:t}=await n.read();if(e)return;yield t}}finally{t?.removeEventListener(`abort`,r),n.cancel().catch(()=>{}),n.releaseLock()}}yield*e}}var m=class{constructor(){this.parts=[],this.head=0,this.size=0}push(e){this.parts.push(e),this.size+=e.length}take(e){let t=new Uint8Array(e);for(let n=0;n<e;){let r=this.parts[0],i=Math.min(r.length-this.head,e-n);t.set(r.subarray(this.head,this.head+i),n),n+=i,this.head+=i,this.head===r.length&&(this.parts.shift(),this.head=0)}return this.size-=e,t}};function h(e){let{positions:t,indices:n,vertexCount:r,frameCount:i}=e,a=new Float32Array(t.length);for(let e=0;e<i;e++){let i=e*r*3;for(let e=0;e+2<n.length;e+=3){let r=i+n[e]*3,o=i+n[e+1]*3,s=i+n[e+2]*3,c=t[o]-t[r],l=t[o+1]-t[r+1],u=t[o+2]-t[r+2],d=t[s]-t[r],f=t[s+1]-t[r+1],p=t[s+2]-t[r+2],m=l*p-u*f,h=u*d-c*p,g=c*f-l*d;for(let e of[r,o,s])a[e]+=m,a[e+1]+=h,a[e+2]+=g}}for(let e=0;e<a.length;e+=3){let t=Math.hypot(a[e],a[e+1],a[e+2]);t>0?(a[e]/=t,a[e+1]/=t,a[e+2]/=t):a[e+2]=1}return a}async function*g(e,{signal:t,maxChunkBytes:n=2**30}={}){let r=new m,d=0,g=0,_=0,v,y,b=(e,t)=>{let n=t.getUint32(12,!0),r=t.getUint32(16,!0),i=t.getUint32(20,!0),a=t.getUint32(24,!0),o=e.buffer,s=0,c=e=>{let t=new Float32Array(o,s,e);return s+=e*4,t},p=i?new Uint32Array(o,0,i):y?.indices;if(s=i*4,!p)throw f(`starts with a chunk that has no indices`);for(let e=0;e<p.length;e++)if(p[e]>=r)throw f(`has an index past its vertices`);let m=a&u?c(r*2):y?.uvs.length===r*2?y.uvs:new Float32Array(r*2),_=c(n*r*3),v={rate:d,totalFrames:g,firstFrame:t.getUint32(8,!0),frameCount:n,vertexCount:r,indices:p,uvs:m,positions:_,normals:_,bounds:/* @__PURE__ */ new Float32Array(6)};for(let e=0;e<6;e++)v.bounds[e]=t.getFloat32(32+e*4,!0);v.normals=a&l?c(n*r*3):h(v);for(let e of[_,v.normals])for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t]))throw f(`holds a non-finite vertex`);return v};for await(let m of p(e,t))for(t?.throwIfAborted(),r.push(m);;){if(!d){if(r.size<i)break;let e=r.take(i),t=new DataView(e.buffer);if(t.getUint32(0,!0)!==o)throw f(`has the wrong magic number`);if(t.getUint32(4,!0)!==c)throw f(`has unknown version ${t.getUint32(4,!0)}`);if(d=t.getFloat32(8,!0),g=t.getUint32(12,!0),!(d>0&&Number.isFinite(d)))throw f(`has no frame rate`)}if(!v){if(r.size<a)break;let e=new DataView(r.take(a).buffer),t=e.getUint32(12,!0),i=e.getUint32(16,!0),o=e.getUint32(20,!0),c=e.getUint32(24,!0),d=o*4+(c&u?i*8:0)+t*i*(c&l?24:12);if(e.getUint32(0,!0)!==s)throw f(`has a damaged chunk header`);if(!t||i<3||i>1e6||o%3)throw f(`has a chunk with no frames, a broken triangle list, or not 3 to 1,000,000 vertices`);if(e.getUint32(8,!0)!==_)throw f(`skips from frame ${_} to ${e.getUint32(8,!0)}`);if(e.getUint32(4,!0)!==d)throw f(`has a chunk of the wrong size`);if(d>n)throw RangeError(`Geometry chunk of ${d} bytes is over maxChunkBytes; raise it or export smaller chunks`);v=e}let e=v.getUint32(4,!0);if(r.size<e)break;let p=b(r.take(e),v);v=void 0,y=p,_+=p.frameCount,yield p,t?.throwIfAborted()}if(!d||v||r.size)throw f(`ends inside a chunk`);if(g&&_!==g)throw f(`ends at frame ${_} of ${g}`)}function _(e,t){if(!(e>0&&Number.isFinite(e))||!t.length)throw RangeError(`Invalid geometry cache; pass a frame rate above 0 and at least one chunk`);let n=[],r=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(i)),d=0;r.setUint32(0,o,!0),r.setUint32(4,c,!0),r.setFloat32(8,e,!0),n.push(new Uint8Array(r.buffer));for(let{frameCount:e,positions:r,indices:i,normals:o,uvs:c}of t){let t=r.length/3/e;if(!Number.isInteger(e)||e<1||!Number.isInteger(t)||t<1||o&&o.length!==r.length||c&&c.length!==t*2||i&&i.length%3)throw RangeError(`Invalid geometry chunk; give positions and normals frameCount frames of 3 floats per vertex, 2 UV floats per vertex and whole triangles`);let f=[i,c,r,o].filter(e=>e!==void 0),p=f.reduce((e,t)=>e+t.byteLength,0),m=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(a)),h=[1/0,1/0,1/0],g=[-1/0,-1/0,-1/0];for(let e=0;e<r.length;e++)h[e%3]=Math.min(h[e%3],r[e]),g[e%3]=Math.max(g[e%3],r[e]);m.setUint32(0,s,!0),m.setUint32(4,p,!0),m.setUint32(8,d,!0),m.setUint32(12,e,!0),m.setUint32(16,t,!0),m.setUint32(20,i?.length??0,!0),m.setUint32(24,(o?l:0)|(c?u:0),!0),[...h,...g].forEach((e,t)=>m.setFloat32(32+t*4,e,!0)),n.push(new Uint8Array(m.buffer));for(let e of f)n.push(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));d+=e}r.setUint32(12,d,!0);let f=new Uint8Array(n.reduce((e,t)=>e+t.length,0)),p=0;for(let e of n)f.set(e,p),p+=e.length;return f}var v=(e,t)=>e===t||!!e&&!!t&&e.length===t.length&&e.every((e,n)=>Object.is(e,t[n]));async function*y(e,t,n){if(!(e>0&&Number.isFinite(e)))throw RangeError(`Invalid mesh sequence rate; pass frames a second above 0`);let r=n?.maxChunkFrames??Math.max(1,Math.round(e));if(!Number.isInteger(r)||r<1||r>65536)throw RangeError(`Invalid maxChunkFrames; pass a whole number from 1 to 65536`);let a=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(i));a.setUint32(0,o,!0),a.setUint32(4,c,!0),a.setFloat32(8,e,!0),yield new Uint8Array(a.buffer);let s=[],l=0,u,d,f=()=>{let t=s[0],n=t.positions.length,r=e=>{let t=new Float32Array(n*s.length);return s.forEach((r,i)=>t.set(e(r),i*n)),t},a=_(e,[{frameCount:s.length,positions:r(e=>e.positions),normals:t.normals?r(e=>e.normals):void 0,indices:u&&C(u,t.indices)?void 0:t.indices,uvs:t.uvs&&!v(d,t.uvs)?t.uvs:void 0}]).subarray(i);return new DataView(a.buffer,a.byteOffset).setUint32(8,l,!0),l+=s.length,u=t.indices,t.uvs&&(d=t.uvs),s=[],a},p=0;for await(let e of t){let{positions:t,indices:n,normals:i,uvs:a}=e??{},o=t?.length/3;if(!(t instanceof Float32Array)||!(n instanceof Uint32Array)||!Number.isInteger(o)||o<3||o>1e6||n.length%3||n.some(e=>e>=o)||i!==void 0&&(!(i instanceof Float32Array)||i.length!==t.length)||a!==void 0&&(!(a instanceof Float32Array)||a.length!==o*2)||!t.every(Number.isFinite))throw RangeError(`Invalid mesh sequence frame ${p}; pass 3 to 1,000,000 finite vertices, whole triangles into them, and normals and UVs sized to the vertices`);let c=s[0];c&&(s.length>=r||c.positions.length!==t.length||!C(c.indices,n)||!c.normals!=!i||!v(c.uvs,a))&&(yield f()),s.push(e),p++}if(!s.length)throw RangeError(`Empty mesh sequence; pass at least one frame`);return yield f(),l}async function*b(e,t,n={}){yield*y(e,t,n)}async function x(e,t,n={}){let r=[],i=y(e,t,n),a=await i.next();for(;!a.done;)r.push(a.value),a=await i.next();let o=new Uint8Array(r.reduce((e,t)=>e+t.length,0)),s=0;for(let e of r)o.set(e,s),s+=e.length;return new DataView(o.buffer).setUint32(12,a.value,!0),o}var S=0,C=(e,t)=>e===t||e.length===t.length&&e.every((e,n)=>e===t[n]),w=class i{coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);static async attach(e,n,r={}){__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));let{ahead:a=2,speed:o=1,signal:s,maxChunkBytes:c}=r;if(!Number.isInteger(a)||a<1||!Number.isFinite(o)||o<0)throw RangeError(`Invalid geometry cache options; ahead must be a whole number >= 1 and speed a finite number >= 0`);if(!e.gpu)throw new t(`unsupported`,`GeometryCachePlayer needs WebGPU; create the engine with the webgpu backend`);let l=new AbortController,u=()=>l.abort(s.reason),d=e,p,m={coreRequirement:/*@__PURE__*/__margoCoreRequirement("0.1.0",import.meta.url),name:`geometry-cache:load:`+S++,setup(){p=d.sceneOf(m)}};for(;d.plugins.has(m.name);)m.name+=`:`;d.use(m),p.removePlugin(m.name);let h=()=>s?.removeEventListener(`abort`,u);s?.aborted?u():s?.addEventListener(`abort`,u,{once:!0});let _=()=>g(T(n,l.signal),{signal:l.signal,maxChunkBytes:c}),v=_();try{let e=await v.next();if(e.done)throw f(`holds no chunks`);let t=typeof n==`string`||typeof n==`function`||n instanceof URL||n instanceof Uint8Array,a,o={coreRequirement:/*@__PURE__*/__margoCoreRequirement("0.1.0",import.meta.url),name:m.name,setup(){a=new i(d,e.value,v,_,l,r,t,h)}};try{p.use(o)}finally{p.plugins.get(o.name)===o&&p.removePlugin(o.name)}return a}catch(e){throw h(),l.abort(e),await v.return(),e}}constructor(e,t,i,a,o,{ahead:s=2,speed:c=1,loop:l=!0,material:u},f,p){this.open=a,this.abort=o,this.rewinds=f,this.unlisten=p,this.name=`geometry-cache:`+S++,this.time=0,this.playing=!0,this.stats={uploads:0,stalls:0,chunks:0,swaps:0},this.disposed=!1,this.capacity=0,this.readTo=0,this.frames=1/0,this.shown=``,this.reader=0,this.at=0,this.wrapped=!1,this.packs=0,this.pose=()=>this.buffer&&this.model.primitives[0].deformed===this.buffer?{vertices:this.scratch,revision:this.packs}:void 0,this.ahead=s,this.speed=c,this.loop=l,this.chunks=[t],this.installed=t,this.stats.chunks=1,this.readTo=t.frameCount,t.totalFrames&&(this.frames=t.totalFrames),this.scratch=new Float32Array(t.vertexCount*d),this.pack(t),this.model=new r(e,new n({asset:{version:`2.0`},materials:[u??{}],meshes:[{primitives:[{attributes:{POSITION:0},material:0}]}],nodes:[{mesh:0}]},[]),[],[[{vertices:this.scratch.slice(),indices:t.indices}]]),this.done=new Promise((e,t)=>{this.settle=n=>n===void 0?e():t(n)}),this.done.catch(()=>{});try{e.use(this.model),e.use(this),this.pump(i,this.reader)}catch(e){throw this.dispose(),e}}setup(e){this.engine=e,this.bind(e.gpu)}get duration(){return this.frames/this.installed.rate}get bounds(){return this.installed.bounds}advanceTime(e){if(this.disposed)return;if(!Number.isFinite(e)||e<0)throw RangeError(`Invalid geometry cache delta; pass finite seconds >= 0`);let t=this.installed.rate;this.playing&&(this.time+=e*this.speed);let n=this.time*t,r=!1;n>=this.frames&&(this.loop?(n%=this.frames,this.time=n/t,r=!0):(n=this.frames-1,this.time=this.frames/t,this.playing=!1)),this.at=n,this.wrapped=r}seek(e){if(!Number.isFinite(e)||e<0)throw RangeError(`Invalid geometry cache time; pass finite seconds >= 0`);return this.time=e,this}onPreUpdate(e){if(this.disposed)return;let t=this.time;this.advanceTime(e);let n=this.at,r=this.wrapped,i=Math.floor(n),a=this.find(i);r&&this.failure===void 0&&this.rewinds&&!this.holdsAll()&&this.restart(),a?(this.show(a,i,n-i),this.drop(i),this.wake?.()):(this.time=t,this.failure===void 0&&(this.stats.stalls++,this.rewinds&&i<this.readTo&&this.restart()),this.wake?.())}onDeviceRestored(e){this.buffer=void 0,this.capacity=0,this.shown=``,this.bind(e.gpu)}dispose(){this.disposed||(this.disposed=!0,this.unlisten(),this.reader++,this.abort.abort(new t(`disposed`,`GeometryCachePlayer is disposed; attach the cache again`)),this.wake?.(),this.settle(),this.engine?.sceneOf(this)?.removePlugin(this.name),this.model.primitives[0].deformed=void 0,this.buffer?.destroy(),this.buffer=void 0,this.model.dispose(),this.chunks=[])}[Symbol.dispose??Symbol()](){this.dispose()}find(e){return this.chunks.find(t=>e>=t.firstFrame&&e<t.firstFrame+t.frameCount)}holdsAll(){return this.chunks.reduce((e,t)=>e+t.frameCount,0)>=this.frames}pinned(e){return this.loop&&e.firstFrame===0}drop(e){this.rewinds&&(this.chunks=this.chunks.filter(t=>t.firstFrame+t.frameCount>e||t===this.installed||this.pinned(t)))}behind(){let e=Math.floor(this.time*this.installed.rate),t=-1;this.find(e)||(t=0);for(let n=this.find(e);n;n=this.find(e))e=n.firstFrame+n.frameCount,t++;return t}async pump(e,t){try{for(;;){for(;t===this.reader&&this.behind()>=this.ahead;)await new Promise(e=>this.wake=e);if(t!==this.reader)break;let{done:n,value:r}=await e.next();if(t!==this.reader)break;if(n){this.frames=this.readTo,this.settle();return}this.stats.chunks++,this.readTo=r.firstFrame+r.frameCount,(!this.rewinds||r.firstFrame+r.frameCount>Math.floor(this.time*this.installed.rate))&&!this.chunks.some(e=>e.firstFrame===r.firstFrame)&&(this.chunks.push(r),this.chunks.sort((e,t)=>e.firstFrame-t.firstFrame))}e.return()}catch(e){if(t!==this.reader)return;this.failure=e,this.settle(e)}}restart(){this.reader++,this.readTo=0,this.wake?.(),this.chunks=this.chunks.filter(e=>this.pinned(e)),this.pump(this.open(),this.reader)}pack(e,t=0,n=e,r=0,i=0){this.packs++;let a=this.scratch,o=e.vertexCount,s=t*o*3,c=r*o*3,l=e.positions,u=n.positions,f=e.normals,p=n.normals;for(let t=0;t<o;t++){let n=t*d,r=s+t*3,o=c+t*3,m=f[r]+(p[o]-f[r])*i,h=f[r+1]+(p[o+1]-f[r+1])*i,g=f[r+2]+(p[o+2]-f[r+2])*i,_=Math.hypot(m,h,g);_>0?(m/=_,h/=_,g/=_):g=1,a[n]=l[r]+(u[o]-l[r])*i,a[n+1]=l[r+1]+(u[o+1]-l[r+1])*i,a[n+2]=l[r+2]+(u[o+2]-l[r+2])*i,a[n+3]=1,a[n+4]=m,a[n+5]=h,a[n+6]=g,a[n+12]=e.uvs[t*2],a[n+13]=e.uvs[t*2+1],a[n+16]=a[n+17]=a[n+18]=a[n+19]=1}}show(e,t,n){let r=t-e.firstFrame,i=e.firstFrame+`:`+r+`:`+n;if(i===this.shown)return;let a=e,o=r+1;if(o===e.frameCount){let t=this.find(e.firstFrame+e.frameCount);t&&t.vertexCount===e.vertexCount&&C(t.indices,e.indices)?(a=t,o=0):o=r}(this.installed.vertexCount!==e.vertexCount||!C(this.installed.indices,e.indices))&&this.swap(e),this.installed=e,this.pack(e,r,a,o,n),this.engine.gpu.queue.writeBuffer(this.buffer,0,this.scratch),this.shown=i,this.stats.uploads++}swap(e){let t=this.model.primitives[0];this.scratch=new Float32Array(e.vertexCount*d),this.pack(e),t.deformed=void 0,this.model.writeGeometry([{vertices:this.scratch.slice(),indices:e.indices}]),this.bind(this.engine.gpu),this.stats.swaps++}bind(t){let n=this.model.primitives[0];this.scratch.byteLength>this.capacity&&(this.buffer?.destroy(),this.capacity=this.scratch.byteLength,this.buffer=t.createBuffer({size:this.capacity,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST})),n.deformed=this.buffer,n.deformedOffset=0,e(n,this.pose),t.queue.writeBuffer(this.buffer,0,this.scratch)}};function T(e,n){return typeof e==`function`?e(n):typeof e!=`string`&&!(e instanceof URL)?e:(async function*(){let r=await fetch(e,{signal:n});if(!r.ok||!r.body)throw new t(`failed`,`Geometry cache request failed with status ${r.status}; check the URL`);yield*p(r.body,n)})()}export{w as GeometryCachePlayer,_ as encodeGeometryCache,x as encodeMeshSequence,g as readGeometryCache,b as streamMeshSequence};
|
|
4
|
+
import{n as e}from"./pose-source-MuCl8VDd.js";import{MargoError as t}from"@margoengine/math/errors";import{GLTFAsset as n,PBRModel as r}from"@margoengine/gltf/pbr-model";var i=16,a=64,o=1212368717,s=1263421507,c=1,l=1,u=2,d=20,f=e=>new t(`failed`,`Geometry cache ${e}; export the file again`);async function*p(e,t){if(e instanceof Uint8Array)yield e;else{if(`getReader`in e){let n=e.getReader(),r=()=>void n.cancel(t?.reason).catch(()=>{});t?.addEventListener(`abort`,r,{once:!0});try{for(;;){let{done:e,value:t}=await n.read();if(e)return;yield t}}finally{t?.removeEventListener(`abort`,r),n.cancel().catch(()=>{}),n.releaseLock()}}yield*e}}var m=class{constructor(){this.parts=[],this.head=0,this.size=0}push(e){this.parts.push(e),this.size+=e.length}take(e){let t=new Uint8Array(e);for(let n=0;n<e;){let r=this.parts[0],i=Math.min(r.length-this.head,e-n);t.set(r.subarray(this.head,this.head+i),n),n+=i,this.head+=i,this.head===r.length&&(this.parts.shift(),this.head=0)}return this.size-=e,t}};function h(e){let{positions:t,indices:n,vertexCount:r,frameCount:i}=e,a=new Float32Array(t.length);for(let e=0;e<i;e++){let i=e*r*3;for(let e=0;e+2<n.length;e+=3){let r=i+n[e]*3,o=i+n[e+1]*3,s=i+n[e+2]*3,c=t[o]-t[r],l=t[o+1]-t[r+1],u=t[o+2]-t[r+2],d=t[s]-t[r],f=t[s+1]-t[r+1],p=t[s+2]-t[r+2],m=l*p-u*f,h=u*d-c*p,g=c*f-l*d;for(let e of[r,o,s])a[e]+=m,a[e+1]+=h,a[e+2]+=g}}for(let e=0;e<a.length;e+=3){let t=Math.hypot(a[e],a[e+1],a[e+2]);t>0?(a[e]/=t,a[e+1]/=t,a[e+2]/=t):a[e+2]=1}return a}async function*g(e,{signal:t,maxChunkBytes:n=2**30}={}){let r=new m,d=0,g=0,_=0,v,y,b=(e,t)=>{let n=t.getUint32(12,!0),r=t.getUint32(16,!0),i=t.getUint32(20,!0),a=t.getUint32(24,!0),o=e.buffer,s=0,c=e=>{let t=new Float32Array(o,s,e);return s+=e*4,t},p=i?new Uint32Array(o,0,i):y?.indices;if(s=i*4,!p)throw f(`starts with a chunk that has no indices`);for(let e=0;e<p.length;e++)if(p[e]>=r)throw f(`has an index past its vertices`);let m=a&u?c(r*2):y?.uvs.length===r*2?y.uvs:new Float32Array(r*2),_=c(n*r*3),v={rate:d,totalFrames:g,firstFrame:t.getUint32(8,!0),frameCount:n,vertexCount:r,indices:p,uvs:m,positions:_,normals:_,bounds:/* @__PURE__ */ new Float32Array(6)};for(let e=0;e<6;e++)v.bounds[e]=t.getFloat32(32+e*4,!0);v.normals=a&l?c(n*r*3):h(v);for(let e of[_,v.normals])for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t]))throw f(`holds a non-finite vertex`);return v};for await(let m of p(e,t))for(t?.throwIfAborted(),r.push(m);;){if(!d){if(r.size<i)break;let e=r.take(i),t=new DataView(e.buffer);if(t.getUint32(0,!0)!==o)throw f(`has the wrong magic number`);if(t.getUint32(4,!0)!==c)throw f(`has unknown version ${t.getUint32(4,!0)}`);if(d=t.getFloat32(8,!0),g=t.getUint32(12,!0),!(d>0&&Number.isFinite(d)))throw f(`has no frame rate`)}if(!v){if(r.size<a)break;let e=new DataView(r.take(a).buffer),t=e.getUint32(12,!0),i=e.getUint32(16,!0),o=e.getUint32(20,!0),c=e.getUint32(24,!0),d=o*4+(c&u?i*8:0)+t*i*(c&l?24:12);if(e.getUint32(0,!0)!==s)throw f(`has a damaged chunk header`);if(!t||i<3||i>1e6||o%3)throw f(`has a chunk with no frames, a broken triangle list, or not 3 to 1,000,000 vertices`);if(e.getUint32(8,!0)!==_)throw f(`skips from frame ${_} to ${e.getUint32(8,!0)}`);if(e.getUint32(4,!0)!==d)throw f(`has a chunk of the wrong size`);if(d>n)throw RangeError(`Geometry chunk of ${d} bytes is over maxChunkBytes; raise it or export smaller chunks`);v=e}let e=v.getUint32(4,!0);if(r.size<e)break;let p=b(r.take(e),v);v=void 0,y=p,_+=p.frameCount,yield p,t?.throwIfAborted()}if(!d||v||r.size)throw f(`ends inside a chunk`);if(g&&_!==g)throw f(`ends at frame ${_} of ${g}`)}function _(e,t){if(!(e>0&&Number.isFinite(e))||!t.length)throw RangeError(`Invalid geometry cache; pass a frame rate above 0 and at least one chunk`);let n=[],r=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(i)),d=0;r.setUint32(0,o,!0),r.setUint32(4,c,!0),r.setFloat32(8,e,!0),n.push(new Uint8Array(r.buffer));for(let{frameCount:e,positions:r,indices:i,normals:o,uvs:c}of t){let t=r.length/3/e;if(!Number.isInteger(e)||e<1||!Number.isInteger(t)||t<1||o&&o.length!==r.length||c&&c.length!==t*2||i&&i.length%3)throw RangeError(`Invalid geometry chunk; give positions and normals frameCount frames of 3 floats per vertex, 2 UV floats per vertex and whole triangles`);let f=[i,c,r,o].filter(e=>e!==void 0),p=f.reduce((e,t)=>e+t.byteLength,0),m=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(a)),h=[1/0,1/0,1/0],g=[-1/0,-1/0,-1/0];for(let e=0;e<r.length;e++)h[e%3]=Math.min(h[e%3],r[e]),g[e%3]=Math.max(g[e%3],r[e]);m.setUint32(0,s,!0),m.setUint32(4,p,!0),m.setUint32(8,d,!0),m.setUint32(12,e,!0),m.setUint32(16,t,!0),m.setUint32(20,i?.length??0,!0),m.setUint32(24,(o?l:0)|(c?u:0),!0),[...h,...g].forEach((e,t)=>m.setFloat32(32+t*4,e,!0)),n.push(new Uint8Array(m.buffer));for(let e of f)n.push(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));d+=e}r.setUint32(12,d,!0);let f=new Uint8Array(n.reduce((e,t)=>e+t.length,0)),p=0;for(let e of n)f.set(e,p),p+=e.length;return f}var v=(e,t)=>e===t||!!e&&!!t&&e.length===t.length&&e.every((e,n)=>Object.is(e,t[n]));async function*y(e,t,n){if(!(e>0&&Number.isFinite(e)))throw RangeError(`Invalid mesh sequence rate; pass frames a second above 0`);let r=n?.maxChunkFrames??Math.max(1,Math.round(e));if(!Number.isInteger(r)||r<1||r>65536)throw RangeError(`Invalid maxChunkFrames; pass a whole number from 1 to 65536`);let a=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(i));a.setUint32(0,o,!0),a.setUint32(4,c,!0),a.setFloat32(8,e,!0),yield new Uint8Array(a.buffer);let s=[],l=0,u,d,f=()=>{let t=s[0],n=t.positions.length,r=e=>{let t=new Float32Array(n*s.length);return s.forEach((r,i)=>t.set(e(r),i*n)),t},a=_(e,[{frameCount:s.length,positions:r(e=>e.positions),normals:t.normals?r(e=>e.normals):void 0,indices:u&&C(u,t.indices)?void 0:t.indices,uvs:t.uvs&&!v(d,t.uvs)?t.uvs:void 0}]).subarray(i);return new DataView(a.buffer,a.byteOffset).setUint32(8,l,!0),l+=s.length,u=t.indices,t.uvs&&(d=t.uvs),s=[],a},p=0;for await(let e of t){let{positions:t,indices:n,normals:i,uvs:a}=e??{},o=t?.length/3;if(!(t instanceof Float32Array)||!(n instanceof Uint32Array)||!Number.isInteger(o)||o<3||o>1e6||n.length%3||n.some(e=>e>=o)||i!==void 0&&(!(i instanceof Float32Array)||i.length!==t.length)||a!==void 0&&(!(a instanceof Float32Array)||a.length!==o*2)||!t.every(Number.isFinite))throw RangeError(`Invalid mesh sequence frame ${p}; pass 3 to 1,000,000 finite vertices, whole triangles into them, and normals and UVs sized to the vertices`);let c=s[0];c&&(s.length>=r||c.positions.length!==t.length||!C(c.indices,n)||!c.normals!=!i||!v(c.uvs,a))&&(yield f()),s.push(e),p++}if(!s.length)throw RangeError(`Empty mesh sequence; pass at least one frame`);return yield f(),l}async function*b(e,t,n={}){yield*y(e,t,n)}async function x(e,t,n={}){let r=[],i=y(e,t,n),a=await i.next();for(;!a.done;)r.push(a.value),a=await i.next();let o=new Uint8Array(r.reduce((e,t)=>e+t.length,0)),s=0;for(let e of r)o.set(e,s),s+=e.length;return new DataView(o.buffer).setUint32(12,a.value,!0),o}var S=0,C=(e,t)=>e===t||e.length===t.length&&e.every((e,n)=>e===t[n]),w=class i{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static async attach(e,n,r={}){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));let{ahead:a=2,speed:o=1,signal:s,maxChunkBytes:c}=r;if(!Number.isInteger(a)||a<1||!Number.isFinite(o)||o<0)throw RangeError(`Invalid geometry cache options; ahead must be a whole number >= 1 and speed a finite number >= 0`);if(!e.gpu)throw new t(`unsupported`,`GeometryCachePlayer needs WebGPU; create the engine with the webgpu backend`);let l=new AbortController,u=()=>l.abort(s.reason),d=e,p,m={coreRequirement:/*@__PURE__*/__margoCoreRequirement("1.0.0",import.meta.url),name:`geometry-cache:load:`+S++,setup(){p=d.sceneOf(m)}};for(;d.plugins.has(m.name);)m.name+=`:`;d.use(m),p.removePlugin(m.name);let h=()=>s?.removeEventListener(`abort`,u);s?.aborted?u():s?.addEventListener(`abort`,u,{once:!0});let _=()=>g(T(n,l.signal),{signal:l.signal,maxChunkBytes:c}),v=_();try{let e=await v.next();if(e.done)throw f(`holds no chunks`);let t=typeof n==`string`||typeof n==`function`||n instanceof URL||n instanceof Uint8Array,a,o={coreRequirement:/*@__PURE__*/__margoCoreRequirement("1.0.0",import.meta.url),name:m.name,setup(){a=new i(d,e.value,v,_,l,r,t,h)}};try{p.use(o)}finally{p.plugins.get(o.name)===o&&p.removePlugin(o.name)}return a}catch(e){throw h(),l.abort(e),await v.return(),e}}constructor(e,t,i,a,o,{ahead:s=2,speed:c=1,loop:l=!0,material:u},f,p){this.open=a,this.abort=o,this.rewinds=f,this.unlisten=p,this.name=`geometry-cache:`+S++,this.time=0,this.playing=!0,this.stats={uploads:0,stalls:0,chunks:0,swaps:0},this.disposed=!1,this.capacity=0,this.readTo=0,this.frames=1/0,this.shown=``,this.reader=0,this.at=0,this.wrapped=!1,this.packs=0,this.pose=()=>this.buffer&&this.model.primitives[0].deformed===this.buffer?{vertices:this.scratch,revision:this.packs}:void 0,this.ahead=s,this.speed=c,this.loop=l,this.chunks=[t],this.installed=t,this.stats.chunks=1,this.readTo=t.frameCount,t.totalFrames&&(this.frames=t.totalFrames),this.scratch=new Float32Array(t.vertexCount*d),this.pack(t),this.model=new r(e,new n({asset:{version:`2.0`},materials:[u??{}],meshes:[{primitives:[{attributes:{POSITION:0},material:0}]}],nodes:[{mesh:0}]},[]),[],[[{vertices:this.scratch.slice(),indices:t.indices}]]),this.done=new Promise((e,t)=>{this.settle=n=>n===void 0?e():t(n)}),this.done.catch(()=>{});try{e.use(this.model),e.use(this),this.pump(i,this.reader)}catch(e){throw this.dispose(),e}}setup(e){this.engine=e,this.bind(e.gpu)}get duration(){return this.frames/this.installed.rate}get bounds(){return this.installed.bounds}advanceTime(e){if(this.disposed)return;if(!Number.isFinite(e)||e<0)throw RangeError(`Invalid geometry cache delta; pass finite seconds >= 0`);let t=this.installed.rate;this.playing&&(this.time+=e*this.speed);let n=this.time*t,r=!1;n>=this.frames&&(this.loop?(n%=this.frames,this.time=n/t,r=!0):(n=this.frames-1,this.time=this.frames/t,this.playing=!1)),this.at=n,this.wrapped=r}seek(e){if(!Number.isFinite(e)||e<0)throw RangeError(`Invalid geometry cache time; pass finite seconds >= 0`);return this.time=e,this}onPreUpdate(e){if(this.disposed)return;let t=this.time;this.advanceTime(e);let n=this.at,r=this.wrapped,i=Math.floor(n),a=this.find(i);r&&this.failure===void 0&&this.rewinds&&!this.holdsAll()&&this.restart(),a?(this.show(a,i,n-i),this.drop(i),this.wake?.()):(this.time=t,this.failure===void 0&&(this.stats.stalls++,this.rewinds&&i<this.readTo&&this.restart()),this.wake?.())}onDeviceRestored(e){this.buffer=void 0,this.capacity=0,this.shown=``,this.bind(e.gpu)}dispose(){this.disposed||(this.disposed=!0,this.unlisten(),this.reader++,this.abort.abort(new t(`disposed`,`GeometryCachePlayer is disposed; attach the cache again`)),this.wake?.(),this.settle(),this.engine?.sceneOf(this)?.removePlugin(this.name),this.model.primitives[0].deformed=void 0,this.buffer?.destroy(),this.buffer=void 0,this.model.dispose(),this.chunks=[])}[Symbol.dispose??Symbol()](){this.dispose()}find(e){return this.chunks.find(t=>e>=t.firstFrame&&e<t.firstFrame+t.frameCount)}holdsAll(){return this.chunks.reduce((e,t)=>e+t.frameCount,0)>=this.frames}pinned(e){return this.loop&&e.firstFrame===0}drop(e){this.rewinds&&(this.chunks=this.chunks.filter(t=>t.firstFrame+t.frameCount>e||t===this.installed||this.pinned(t)))}behind(){let e=Math.floor(this.time*this.installed.rate),t=-1;this.find(e)||(t=0);for(let n=this.find(e);n;n=this.find(e))e=n.firstFrame+n.frameCount,t++;return t}async pump(e,t){try{for(;;){for(;t===this.reader&&this.behind()>=this.ahead;)await new Promise(e=>this.wake=e);if(t!==this.reader)break;let{done:n,value:r}=await e.next();if(t!==this.reader)break;if(n){this.frames=this.readTo,this.settle();return}this.stats.chunks++,this.readTo=r.firstFrame+r.frameCount,(!this.rewinds||r.firstFrame+r.frameCount>Math.floor(this.time*this.installed.rate))&&!this.chunks.some(e=>e.firstFrame===r.firstFrame)&&(this.chunks.push(r),this.chunks.sort((e,t)=>e.firstFrame-t.firstFrame))}e.return()}catch(e){if(t!==this.reader)return;this.failure=e,this.settle(e)}}restart(){this.reader++,this.readTo=0,this.wake?.(),this.chunks=this.chunks.filter(e=>this.pinned(e)),this.pump(this.open(),this.reader)}pack(e,t=0,n=e,r=0,i=0){this.packs++;let a=this.scratch,o=e.vertexCount,s=t*o*3,c=r*o*3,l=e.positions,u=n.positions,f=e.normals,p=n.normals;for(let t=0;t<o;t++){let n=t*d,r=s+t*3,o=c+t*3,m=f[r]+(p[o]-f[r])*i,h=f[r+1]+(p[o+1]-f[r+1])*i,g=f[r+2]+(p[o+2]-f[r+2])*i,_=Math.hypot(m,h,g);_>0?(m/=_,h/=_,g/=_):g=1,a[n]=l[r]+(u[o]-l[r])*i,a[n+1]=l[r+1]+(u[o+1]-l[r+1])*i,a[n+2]=l[r+2]+(u[o+2]-l[r+2])*i,a[n+3]=1,a[n+4]=m,a[n+5]=h,a[n+6]=g,a[n+12]=e.uvs[t*2],a[n+13]=e.uvs[t*2+1],a[n+16]=a[n+17]=a[n+18]=a[n+19]=1}}show(e,t,n){let r=t-e.firstFrame,i=e.firstFrame+`:`+r+`:`+n;if(i===this.shown)return;let a=e,o=r+1;if(o===e.frameCount){let t=this.find(e.firstFrame+e.frameCount);t&&t.vertexCount===e.vertexCount&&C(t.indices,e.indices)?(a=t,o=0):o=r}(this.installed.vertexCount!==e.vertexCount||!C(this.installed.indices,e.indices))&&this.swap(e),this.installed=e,this.pack(e,r,a,o,n),this.engine.gpu.queue.writeBuffer(this.buffer,0,this.scratch),this.shown=i,this.stats.uploads++}swap(e){let t=this.model.primitives[0];this.scratch=new Float32Array(e.vertexCount*d),this.pack(e),t.deformed=void 0,this.model.writeGeometry([{vertices:this.scratch.slice(),indices:e.indices}]),this.bind(this.engine.gpu),this.stats.swaps++}bind(t){let n=this.model.primitives[0];this.scratch.byteLength>this.capacity&&(this.buffer?.destroy(),this.capacity=this.scratch.byteLength,this.buffer=t.createBuffer({size:this.capacity,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST})),n.deformed=this.buffer,n.deformedOffset=0,e(n,this.pose),t.queue.writeBuffer(this.buffer,0,this.scratch)}};function T(e,n){return typeof e==`function`?e(n):typeof e!=`string`&&!(e instanceof URL)?e:(async function*(){let r=await fetch(e,{signal:n});if(!r.ok||!r.body)throw new t(`failed`,`Geometry cache request failed with status ${r.status}; check the URL`);yield*p(r.body,n)})()}export{w as GeometryCachePlayer,_ as encodeGeometryCache,x as encodeMeshSequence,g as readGeometryCache,b as streamMeshSequence};
|
package/dist/index.d.ts
CHANGED
|
@@ -124,10 +124,12 @@ export declare class Animation implements EnginePlugin {
|
|
|
124
124
|
/** The model whose nodes are the joints: this one, or `options.skeleton`. */
|
|
125
125
|
private readonly joints;
|
|
126
126
|
/**
|
|
127
|
-
* Set by `MorphWeightPlayer` (morph-gpu.ts)
|
|
128
|
-
* `primitive.weights`
|
|
127
|
+
* Set by `MorphWeightPlayer` (morph-gpu.ts) while it writes this Animation's morph weights on the GPU: then
|
|
128
|
+
* `primitive.weights` does not say what is drawn, so the CPU pose takes the player's samples, its shader's arithmetic
|
|
129
|
+
* on the CPU (KB-BVH-SYNCPOSE-MORPHGPU1). At `remove` the player writes the weights last drawn back into
|
|
130
|
+
* `primitive.weights` and clears this.
|
|
129
131
|
*/
|
|
130
|
-
private
|
|
132
|
+
private weightSource?;
|
|
131
133
|
private readonly prepareDeformation;
|
|
132
134
|
/** The deformation group of the frame graph this Animation's pass is in. */
|
|
133
135
|
private group?;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e,n as t,r as n,t as r}from"./src-
|
|
1
|
+
import{i as e,n as t,r as n,t as r}from"./src-fuuIJ3rU.js";import{a as i,o as a}from"./sampling-DjDWYqt2.js";import{a as o,c as s,i as c,n as l,o as u,r as d,s as f,t as p}from"./keyframes-YpidiYS4.js";export{r as Animation,t as AnimationGroup,f as Skeleton,s as Skin,p as applyKeyframeClip,l as bakeKeyframeClip,d as bakeKeyframeTrack,n as compileRigidClip,c as createKeyframeClip,e as createMaterialAnimation,o as sampleKeyframes,i as sampleTrack,a as sampleTrackInto,u as segmentTime};
|
package/dist/instanced-morph.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
// @margo/core-built
|
|
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"./vertex-map-BC_WH7ER.js";import{r as t}from"./vat-
|
|
4
|
+
import{t as e}from"./vertex-map-BC_WH7ER.js";import{r as t}from"./vat-SpfL7y9U.js";import{SkinnedCrowd as n,bakeBones as r,poseBones as i,skinnedCrowdLayout as a,skinnedCrowdVertex as o}from"./instanced-skin.js";var s=64;function c(n,i={}){let a=n.model,o=a.asset,s=[],c=a.primitives.map(e=>{let t=e.definition.targets??[],n=t.map((t,n)=>e.targetNames[n]??`Target `+n);for(let e of n)s.includes(e)||s.push(e);return{p:e,targets:t,names:n,count:e.vertices.length/20}}),l=(i.morphs??s).map(e=>typeof e==`string`?e:s[e]);if(!s.length)throw RangeError(`The model has no morph targets; bake it with bakeBones`);if(!l.length||l.some((e,t)=>!s.includes(e)||l.indexOf(e)!==t))throw RangeError(`Unknown or repeated morph target; pass target names, or indices below the number of targets, once each`);if(l.length>64)throw RangeError(`${l.length} live morph targets exceed 64; name the ones members set in the morphs option`);let u=new Float32Array(l.length),d=c.map(({p:e})=>e.weights.slice()),f=/* @__PURE__ */ new Set,p;try{for(let{p:e,names:t}of c)t.forEach((t,n)=>{let r=l.indexOf(t);r<0||(f.has(r)||(u[r]=e.weights[n]),f.add(r),e.weights[n]=0)});p=r(n,i)}finally{c.forEach(({p:e},t)=>e.weights.set(d[t]))}let m=c.map(e=>e.names.map(e=>l.indexOf(e)).filter(e=>e>=0).length),h=m.reduce((e,t)=>e+t,0),g=p.rows*p.bones*3,_=g+h+c.reduce((e,t,n)=>e+m[n]*t.count*2,0),v=Math.ceil(_/t);if(v>8192)throw RangeError(`Morph data exceeds 8192 texture rows; keep fewer targets live, or bake fewer clips`);let y=new Float32Array(t*v*4),b=new Uint32Array(p.vertexCount*4);y.set(p.texels.subarray(0,g*4));let x=g,S=g+h,C=0;return c.forEach(({p:t,targets:n,names:r,count:i},a)=>{for(let e=0;e<i;e++)b.set([x,m[a],e,0],(C+e)*4);C+=i,n.forEach((n,a)=>{let s=l.indexOf(r[a]);s<0||(y[x*4]=S,y[x++*4+1]=s,[n.POSITION,n.NORMAL].forEach((n,r)=>{if(n===void 0)return;let a=e(o.accessor(n,`VEC3`),3,t.part?.vertexMap);for(let e=0;e<i;e++)y.set(a.subarray(e*3,e*3+3),(S+e*2+r)*4)}),S+=i*2)})}),{...p,texels:y,morphs:{names:l,weights:u,vertices:b,blocks:h}}}var l=`fn morphTexel(i:u32)->vec4f {let w=u32(f.vat.y);return textureLoad(vat,vec2u(i%w,i/w),0);}
|
|
5
5
|
fn morphed(s:Instance,position:vec3f,normal:vec3f,morph:vec4u)->SkinnedVertex {
|
|
6
6
|
var p=position;var n=normal;
|
|
7
7
|
for(var i=0u;i<morph.y;i++) {
|
|
@@ -10,4 +10,4 @@ fn morphed(s:Instance,position:vec3f,normal:vec3f,morph:vec4u)->SkinnedVertex {
|
|
|
10
10
|
}
|
|
11
11
|
return SkinnedVertex(p,n);
|
|
12
12
|
}
|
|
13
|
-
`;function u(e){return o.replace(`q:vec4f}`,`q:vec4f,w:array<vec4f,${e}>}`).replace(`@vertex fn vertex(`,l+`@vertex fn vertex(`).replace(`@location(6) w1:vec4f,`,`@location(6) w1:vec4f,@location(7) morph:vec4u,`).replace(`let k=skinned(s,position,normal,`,`let b=morphed(s,position,normal,morph);let k=skinned(s,b.position,b.normal,`)}function d(e,t){let n=typeof t==`string`?e.morphs.names.indexOf(t):t;if(!(Number.isInteger(n)&&n>=0&&n<e.morphs.names.length))throw RangeError(`Unknown morph target ${t}; use a name from bake.morphs.names or an index below ${e.morphs.names.length}`);return n}function f(e,t,n,r){let i=ArrayBuffer.isView(t)||Array.isArray(t)?Array.from(t,(e,t)=>[t,e]):Object.entries(t),a=i.map(([t])=>d(e,t));if(i.some(([,e])=>typeof e!=`number`||!Number.isFinite(e)))throw RangeError(`Invalid morph weight; pass finite numbers`);a.forEach((e,t)=>n[r+e]=i[t][1])}function p(e,t=e.morphs.weights,n=new Float32Array(e.vertices.length)){let r=e.morphs.weights.slice(),{vertices:i,texels:a}={vertices:e.morphs.vertices,texels:e.texels};if(f(e,t,r,0),n.length<e.vertices.length)throw RangeError(`Morph output needs 6 floats per vertex`);n.set(e.vertices);for(let t=0;t<e.vertexCount;t++)for(let e=0;e<i[t*4+1];e++){let o=(i[t*4]+e)*4,s=r[a[o+1]],c=(a[o]+i[t*4+2]*2)*4;if(s)for(let e=0;e<3;e++)n[t*6+e]+=a[c+e]*s,n[t*6+3+e]+=a[c+4+e]*s}return n}function m(e,t,n,r){return i({...e,vertices:p(e,t.morphs??e.morphs.weights)},t,n,r)}var h=class e extends n{static attach(t,n,r){__margoAssertCore(t,__margoCoreRequirement("
|
|
13
|
+
`;function u(e){return o.replace(`q:vec4f}`,`q:vec4f,w:array<vec4f,${e}>}`).replace(`@vertex fn vertex(`,l+`@vertex fn vertex(`).replace(`@location(6) w1:vec4f,`,`@location(6) w1:vec4f,@location(7) morph:vec4u,`).replace(`let k=skinned(s,position,normal,`,`let b=morphed(s,position,normal,morph);let k=skinned(s,b.position,b.normal,`)}function d(e,t){let n=typeof t==`string`?e.morphs.names.indexOf(t):t;if(!(Number.isInteger(n)&&n>=0&&n<e.morphs.names.length))throw RangeError(`Unknown morph target ${t}; use a name from bake.morphs.names or an index below ${e.morphs.names.length}`);return n}function f(e,t,n,r){let i=ArrayBuffer.isView(t)||Array.isArray(t)?Array.from(t,(e,t)=>[t,e]):Object.entries(t),a=i.map(([t])=>d(e,t));if(i.some(([,e])=>typeof e!=`number`||!Number.isFinite(e)))throw RangeError(`Invalid morph weight; pass finite numbers`);a.forEach((e,t)=>n[r+e]=i[t][1])}function p(e,t=e.morphs.weights,n=new Float32Array(e.vertices.length)){let r=e.morphs.weights.slice(),{vertices:i,texels:a}={vertices:e.morphs.vertices,texels:e.texels};if(f(e,t,r,0),n.length<e.vertices.length)throw RangeError(`Morph output needs 6 floats per vertex`);n.set(e.vertices);for(let t=0;t<e.vertexCount;t++)for(let e=0;e<i[t*4+1];e++){let o=(i[t*4]+e)*4,s=r[a[o+1]],c=(a[o]+i[t*4+2]*2)*4;if(s)for(let e=0;e<3;e++)n[t*6+e]+=a[c+e]*s,n[t*6+3+e]+=a[c+4+e]*s}return n}function m(e,t,n,r){return i({...e,vertices:p(e,t.morphs??e.morphs.weights)},t,n,r)}var h=class e extends n{static attach(t,n,r){__margoAssertCore(t,__margoCoreRequirement("1.0.0",import.meta.url));let i=new e(n,r);return t.use(i),i}constructor(e,t){let n=e?.morphs?.names?.length;if(!(e?.morphs?.vertices instanceof Uint32Array)||!(n>=1&&n<=64))throw TypeError(`Invalid morphed crowd; pass the result of bakeMorphBones`);let r=Math.ceil(n/4),i=a(e);super(e,t,{...i,vertex:u(r),stride:28+r*4,vertices:[...i.vertices,e.morphs.vertices],attributes:[...i.attributes,{arrayStride:16,attributes:[{shaderLocation:7,offset:0,format:`uint32x4`}]}]})}add(e={}){let t=this.bake.morphs.weights.slice();return e.morphs!==void 0&&f(this.bake,e.morphs,t,0),super.add({...e,morphs:t})}set(e,t){let{morphs:n}=t,r=new Float32Array(this.bake.morphs.names.length);return n!==void 0&&f(this.bake,n,r,0),super.set(e,t),n!==void 0&&f(this.bake,n,this.rows,e*this.stride+28),this}setMorph(e,t,n){return this.set(e,{morphs:{[this.bake.morphs.names[d(this.bake,t)]]:n}})}getMorph(e,t){let n=d(this.bake,t);if(!(Number.isInteger(e)&&e>=0&&e<this.count))throw RangeError(`Invalid crowd member; use an index below the member count`);return this.rows[e*this.stride+28+n]}};export{s as MORPH_TARGET_LIMIT,h as MorphedCrowd,c as bakeMorphBones,p as morphVertices,u as morphedCrowdVertex,m as poseMorphedBones};
|
package/dist/instanced-skin.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
// @margo/core-built
|
|
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"./vertex-map-BC_WH7ER.js";import{r as t,t as n}from"./vat-
|
|
4
|
+
import{t as e}from"./vertex-map-BC_WH7ER.js";import{r as t,t as n}from"./vat-SpfL7y9U.js";import{invertMatrixStable as r,multiplyMatrices as i}from"@margoengine/math/mat4";var a=28;function o(e,n,r,i,a=t){let o=(e*i+n)*3+r;return[o%a,Math.floor(o/a)]}function s(n,{fps:a=30,clips:o}={}){let s=n.model,c=s.asset.doc,l=s.asset,u=s.root.engine.store,d=(o??n.clips.map((e,t)=>t)).map(e=>typeof e==`string`?n.clips.findIndex(t=>t.name===e):e);if(!(a>0&&a<=1e3)||!d.length||d.some(e=>!n.clips[e]))throw RangeError(`Invalid bone bake fps or clips; pass fps in (0, 1000] and clip indices that exist in animation.clips`);let f=[],p=/* @__PURE__ */ new Map,m=s.primitives.reduce((e,t)=>e+t.vertices.length/20,0),h=new Float32Array(m*6),g=new Uint32Array(m*8),_=new Float32Array(m*8),v=new Float32Array(m*2),y=[],b=0;for(let t of s.primitives){let n=t.definition,r=t.vertices.length/20,i=c.nodes[t.nodeIndex].skin,a=i===void 0?void 0:c.skins[i],o=t.vertices,s=t.part?.vertexMap,u=(n.targets??[]).map(t=>[t.POSITION,t.NORMAL].map(t=>t===void 0?null:e(l.accessor(t,`VEC3`),3,s))),d=i===void 0?void 0:p.get(i);if(d===void 0){if(d=f.length,a){p.set(i,d);let e=a.inverseBindMatrices===void 0?void 0:l.accessor(a.inverseBindMatrices,`MAT4`);a.joints.forEach((t,n)=>f.push({node:t,bind:e?.subarray(n*16,n*16+16)}))}else f.push({node:t.nodeIndex,part:t})}let m=a?[[n.attributes.JOINTS_0,n.attributes.WEIGHTS_0],[n.attributes.JOINTS_1,n.attributes.WEIGHTS_1]].filter(([e,t])=>e!==void 0&&t!==void 0).map(([t,n])=>[e(l.accessor(t,`VEC4`),4,s),e(l.accessor(n,`VEC4`),4,s)]):[];for(let e=0;e<r;e++){let n=b+e,r=o[e*20],i=o[e*20+1],s=o[e*20+2],c=o[e*20+4],l=o[e*20+5],f=o[e*20+6];if(u.forEach(([n,a],o)=>{let u=t.weights[o];n&&(r+=n[e*3]*u,i+=n[e*3+1]*u,s+=n[e*3+2]*u),a&&(c+=a[e*3]*u,l+=a[e*3+1]*u,f+=a[e*3+2]*u)}),h.set([r,i,s,c,l,f],n*6),v[n*2]=o[e*20+12],v[n*2+1]=1-o[e*20+13],!a){g[n*8]=d,_[n*8]=1;continue}let p=0;for(let[,t]of m)for(let n=0;n<4;n++)p+=t[e*4+n];if(!(p>0))throw RangeError(`Skin weights must have a positive sum; give every vertex a joint`);m.forEach(([t,r],i)=>{for(let a=0;a<4;a++)g[n*8+i*4+a]=d+t[e*4+a],_[n*8+i*4+a]=r[e*4+a]/p})}for(let e of t.indices)y.push(b+e);b+=r}let x=d.map(e=>Math.max(1,Math.ceil(n.clips[e].duration*a))),S=x.reduce((e,t)=>e+t+1,0),C=Math.ceil(S*f.length*3/t);if(C>8192)throw RangeError(`Bone data exceeds 8192 texture rows; bake fewer clips, a lower fps or fewer bones`);let w={clip:n.clip,time:n.time,playing:n.playing},T=new Float32Array(t*C*4),E=/* @__PURE__ */ new Float32Array(16),D=/* @__PURE__ */ new Float32Array(16),O=/* @__PURE__ */ new Float32Array(16),k=/* @__PURE__ */ new Float64Array(52),A=0;try{d.forEach((e,t)=>{let a=n.clips[e].duration;n.play(e);for(let e=0;e<=x[t];e++,A++){if(n.seek(a*e/x[t]),u.tick(!1),!r(s.root.matrix,E,k))throw RangeError(`Singular model root; give the model root a non-zero scale before baking`);f.forEach(({node:e,bind:t,part:n},r)=>{let a=n?n.node.matrix:s.nodes[e].matrix;t?i(a,t,D):D.set(a),i(E,D,O);let o=(A*f.length+r)*12;for(let e=0;e<3;e++)for(let t=0;t<4;t++){let n=O[t*4+e];if(!Number.isFinite(n))throw RangeError(`Bone bake produced non-finite matrices; use finite joints and inverse binds`);T[o+e*4+t]=n}})}})}finally{n.play(w.clip),n.seek(w.time),n.playing=w.playing,u.tick(!1)}let j=0;return{bones:f.length,rows:S,width:t,texels:T,vertexCount:m,vertices:h,joints:g,weights:_,indices:Uint32Array.from(y),uvs:v,clips:d.map((e,t)=>{let r={name:n.clips[e].name,start:j,frames:x[t],duration:n.clips[e].duration,loop:n.options.loop??!0};return j+=x[t]+1,r})}}var c=`
|
|
5
5
|
struct Frame {camera:mat4x4f,eye:vec4f,light:vec4f,radiance:vec4f,base:vec4f,options:vec4f,vat:vec4f}
|
|
6
6
|
struct Instance {m:mat4x4f,p:vec4f,uv:vec4f,q:vec4f}
|
|
7
7
|
@group(0) @binding(0) var<uniform> f:Frame;
|
|
@@ -40,4 +40,4 @@ fn skinned(s:Instance,position:vec3f,normal:vec3f,j0:vec4u,j1:vec4u,w0:vec4f,w1:
|
|
|
40
40
|
let m=s.m;let c0=cross(m[1].xyz,m[2].xyz);let world=m*vec4f(k.position,1.0);
|
|
41
41
|
var o:Out;o.clip=f.camera*world;o.position=world.xyz;let n=mat3x3f(c0,cross(m[2].xyz,m[0].xyz),cross(m[0].xyz,m[1].xyz))*k.normal*select(-1.0,1.0,dot(m[0].xyz,c0)>=0.0);o.normal=select(vec3f(0,1,0),n,dot(n,n)>0.0);o.uv=s.uv.xy+uv*s.uv.zw;return o;
|
|
42
42
|
}
|
|
43
|
-
`,l=e=>({vertex:c,stride:28,rowSize:e.bones,vertices:[e.vertices,e.joints,e.weights],attributes:[{arrayStride:24,attributes:[{shaderLocation:1,offset:0,format:`float32x3`},{shaderLocation:2,offset:12,format:`float32x3`}]},{arrayStride:32,attributes:[{shaderLocation:3,offset:0,format:`uint32x4`},{shaderLocation:4,offset:16,format:`uint32x4`}]},{arrayStride:32,attributes:[{shaderLocation:5,offset:0,format:`float32x4`},{shaderLocation:6,offset:16,format:`float32x4`}]}]}),u=class e extends n{static attach(t,n,r){__margoAssertCore(t,__margoCoreRequirement("
|
|
43
|
+
`,l=e=>({vertex:c,stride:28,rowSize:e.bones,vertices:[e.vertices,e.joints,e.weights],attributes:[{arrayStride:24,attributes:[{shaderLocation:1,offset:0,format:`float32x3`},{shaderLocation:2,offset:12,format:`float32x3`}]},{arrayStride:32,attributes:[{shaderLocation:3,offset:0,format:`uint32x4`},{shaderLocation:4,offset:16,format:`uint32x4`}]},{arrayStride:32,attributes:[{shaderLocation:5,offset:0,format:`float32x4`},{shaderLocation:6,offset:16,format:`float32x4`}]}]}),u=class e extends n{static attach(t,n,r){__margoAssertCore(t,__margoCoreRequirement("1.0.0",import.meta.url));let i=new e(n,r);return t.use(i),i}constructor(e,t,n){if(!(e?.vertices instanceof Float32Array)||!(e.bones>0))throw TypeError(`Invalid skinned crowd; pass the result of bakeBones`);let r=n??l(e);super(e,t,r),this.bake=e,this.stride=r.stride}add(e={}){return super.add(e)}set(e,t){let{blendClip:n,blendOffset:r,blendSpeed:i,blend:a}=t;if(n!==void 0&&!(Number.isInteger(n)&&n>=0&&n<this.bake.clips.length)||r!==void 0&&!Number.isFinite(r)||i!==void 0&&!Number.isFinite(i)||a!==void 0&&!(a>=0&&a<=1))throw RangeError(`Invalid crowd blend; use a blendClip from bake.clips, a finite blendOffset and blendSpeed, and a blend in 0..1`);super.set(e,t);let o=e*this.stride,s=this.rows;return a!==void 0&&(s[o+19]=a),n!==void 0&&(s[o+24]=n),r!==void 0&&(s[o+25]=r),i!==void 0&&(s[o+26]=i),this}},d=(e,t,n)=>e+(t-e)*n;function f(e,t){let n=t/Math.max(e.duration,1e-6);n=e.loop?n-Math.floor(n):Math.min(1,Math.max(0,n));let r=n*e.frames,i=Math.min(Math.floor(r),e.frames-1);return[e.start+i,r-i]}function p(e,{clip:t=0,offset:n=0,speed:r=1,blendClip:i=0,blendOffset:a=0,blendSpeed:s=1,blend:c=0},l,u,p=/* @__PURE__ */ new Float32Array(12)){if(!e.clips[t]||!e.clips[i]||!(Number.isInteger(l)&&l>=0&&l<e.bones)||p.length<12)throw RangeError(`Invalid bone pose; use clips from bake.clips, a bone below bake.bones and an output of 12 floats`);let m=f(e.clips[t],u*r+n),h=f(e.clips[i],u*s+a),g=(t,n,r)=>{let[i,a]=o(t,l,n,e.bones,e.width);return e.texels[(a*e.width+i)*4+r]},_=(e,t,n)=>d(g(e[0],t,n),g(e[0]+1,t,n),e[1]);for(let e=0;e<3;e++)for(let t=0;t<4;t++)p[e*4+t]=d(_(m,e,t),_(h,e,t),c);return p}function m(e,{clip:t=0,offset:n=0,speed:r=1,blendClip:i=0,blendOffset:a=0,blendSpeed:s=1,blend:c=0},l,u=new Float32Array(e.vertexCount*3)){if(!e.clips[t]||!e.clips[i]||u.length<e.vertexCount*3)throw RangeError(`Invalid pose; use clips from bake.clips and an output of 3 floats per vertex`);let p=f(e.clips[t],l*r+n),m=f(e.clips[i],l*s+a),h=(t,n,r,i)=>{let[a,s]=o(t,n,r,e.bones,e.width);return e.texels[(s*e.width+a)*4+i]},g=(e,t,n,r)=>d(h(e[0],t,n,r),h(e[0]+1,t,n,r),e[1]);for(let t=0;t<e.vertexCount;t++){let[n,r,i]=e.vertices.subarray(t*6,t*6+3);for(let a=0;a<3;a++){let o=0;for(let s=0;s<8;s++){let l=e.weights[t*8+s];if(!l)continue;let u=e.joints[t*8+s],f=e=>d(g(p,u,a,e),g(m,u,a,e),c);o+=l*(f(0)*n+f(1)*r+f(2)*i+f(3))}u[t*3+a]=o}}return u}export{a as SKINNED_CROWD_STRIDE,u as SkinnedCrowd,s as bakeBones,o as boneTexel,p as poseBone,m as poseBones,l as skinnedCrowdLayout,c as skinnedCrowdVertex};
|
package/dist/interactivity.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// @margo/core-built
|
|
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"./src-
|
|
4
|
+
import{t as e}from"./src-fuuIJ3rU.js";import{o as t}from"./sampling-DjDWYqt2.js";import{n,t as r}from"./pointer-DyWpFsQi.js";import{MargoError as i}from"@margoengine/math/errors";import{rotationToQuaternion as a}from"@margoengine/math/quat";import{screenToWorld as o}from"@margoengine/math/project";import{Ray as s}from"@margoengine/math/ray";import{Vector3 as c}from"@margoengine/math/vector3";import{loadBehaviorGraph as l}from"@margoengine/gltf/interactivity";function u(e,n){let{times:r,values:i,width:a,interpolation:o}=e;return Array.from(t(r,i,a,n,o,a===4&&o!==`STEP`))}var d=(e,t)=>Math.hypot(e.x-t.x,e.y-t.y,e.z-t.z);function f(e,t,n){let r=e[t*20],i=e[t*20+1],a=e[t*20+2];return{x:n[0]*r+n[4]*i+n[8]*a+n[12],y:n[1]*r+n[5]*i+n[9]*a+n[13],z:n[2]*r+n[6]*i+n[10]*a+n[14]}}var p=0,m=/\/extensions\/KHR_node_(selectability|hoverability)\//,h=/KHR_physics_rigid_bodies/,g=class t{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static attach(e,n={}){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));let r=new t(e,n);return e.root.engine.use(r),r}constructor(e,t={}){this.name=`gltf-interactivity:`+p++,this.notes=[],this.writers=/* @__PURE__ */ new Map,this.nodeOf=/* @__PURE__ */ new Map,this.removers=[],this.picking=!1,this.disposed=!1,this.model=e,this.options=t;let{physics:n}=t,r=l(e.asset,{...t,sample:u,physics:n&&_(n),live:(e,t)=>this.write(e,t),camera:()=>t.shareCamera===!1?void 0:this.camera()});this.graph=r.graph,this.rejected=r.rejected,e.nodes.forEach((e,t)=>this.nodeOf.set(e,t))}setup(t){if(this.disposed)throw new i(`disposed`,`GLTFInteractivity is disposed; create a new graph before attaching`);this.engine=t;let{graph:n}=this,a=this.model.asset.doc;n&&((a.skins?.length||a.meshes?.some(e=>e.primitives?.some(e=>e.targets?.length)))&&(e.attach(this.model,{pointers:r,loop:!1}).playing=!1),this.options.physics&&this.removers.push(this.options.physics.onTrigger(({entered:e,nodeIndex:t,colliderNodeIndex:r,motionNodeIndex:i})=>n.trigger(e?`event/rigid_body_triggerEntered`:`event/rigid_body_triggerExited`,t,r,i))),this.options.pointer!==!1&&this.listen(t,n))}listen(e,t){let{canvas:n}=e,r=t.handles(`event/onSelect`),a=t.handles(`event/onHoverIn`)||t.handles(`event/onHoverOut`);(r||a)&&![...e.plugins.values()].some(e=>e.onPick)&&(this.picker=import(`@margoengine/selection`).then(({Picking:t})=>t.forEngine(e)??t.attach(e,{capture:!1}),()=>{throw new i(`unsupported`,`Clicks on a behaviour graph need @margoengine/selection; install it, or pass pointer: false`)}));let o=e=>{let t=n.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}},s=(e,t)=>{n.addEventListener(e,t),this.removers.push(()=>n.removeEventListener(e,t))};r&&(s(`pointerdown`,e=>this.press=o(e)),s(`pointerup`,e=>{let t=o(e),n=this.press;this.press=void 0,n&&Math.hypot(t.x-n.x,t.y-n.y)<=4&&this.select(t)})),a&&(s(`pointermove`,e=>this.moved=o(e)),s(`pointerleave`,()=>{this.moved=void 0,t.hover(void 0)}))}async nodeAt({x:e,y:t}){await this.picker;let n=await this.engine.pick(e,t);return n?this.nodeOf.get(n):void 0}async trace({x:e,y:t}){let{camera:n,canvas:r}=this.engine,i=r.clientWidth||r.width,a=r.clientHeight||r.height,l=r=>o(e,t,r,n,i,a,new c),[u,p,m]=n.position,h={x:u,y:p,z:m},[g,_]=[l(.25),l(.75)].sort((e,t)=>d(e,h)-d(t,h)),v=new s(g,_.clone().sub(g).normalize()),y=new c,b=[];for(let{vertices:e,indices:t,matrix:n,nodeIndex:r}of await this.model.readPickingGeometry()){if(r===void 0)continue;let i=1/0,a=[];for(let r=0;r+2<t.length;r+=3){let o=f(e,t[r],n),s=f(e,t[r+1],n),c=f(e,t[r+2],n);if(!v.intersectTriangle(o,s,c,!1,y))continue;let l=d(y,g);l<i&&(i=l,a=[y.x,y.y,y.z])}i<1/0&&b.push({node:r,distance:i,point:a})}return b.sort((e,t)=>e.distance-t.distance)}async select(e){let t=await this.nodeAt(e);if(t===void 0||this.model.disposed)return;let n=[...this.engine.camera.position],r=await this.trace(e);if(!this.model.disposed){for(let e of r)if(this.graph?.select(e.node,{point:e.point,origin:n}))return;r.length||this.graph?.select(t,{origin:n})}}async hover(e){this.picking=!0;let t=await this.nodeAt(e);this.picking=!1,this.model.disposed||this.graph?.hover(t)}onPreUpdate(e){if(this.model.disposed)this.dispose();else{if(this.moved&&!this.picking){let e=this.moved;this.moved=void 0,this.hover(e)}this.graph?.tick(e)}}write(e,t){if(m.test(e))return;let r=typeof t==`boolean`?[+!!t]:typeof t==`number`?[t]:t;if(h.test(e))this.options.physics?.setPointer(e,r.length===1?r[0]:r);else{if(!this.writers.has(e)){let t=n(this.model,e);this.writers.set(e,t),t||this.notes.push(`${e} has no effect on the rendered model`)}this.writers.get(e)?.(r)}}camera(){let e=this.engine;if(!e)return;let{position:t,target:n,up:r,fov:i,near:o,far:s}=e.camera,c=e=>{let t=Math.hypot(...e);return e.map(e=>e/t)},l=(e,t)=>[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]],u=c(t.map((e,t)=>e-n[t])),d=c(l([...r],u)),f=l(u,d);return{position:[...t],rotation:a([...d,0,...f,0,...u],[0,0,0,0]),perspective:{aspectRatio:e.canvas.width/e.canvas.height,yfov:i*Math.PI/180,znear:o,zfar:s}}}dispose(){if(!this.disposed){this.disposed=!0;for(let e of this.removers.splice(0))e();this.engine?.sceneOf(this)?.removePlugin(this.name)}}[Symbol.dispose](){this.dispose()}};function _(e){let t=e=>e;return{applyImpulse(n,r,i){e.bodyOf(n)?.applyImpulse(t(r)).applyTorqueImpulse(t(i))},applyPointImpulse(n,r,i){e.bodyOf(n)?.applyImpulse(t(r),t(i))},rayCast(t,n){let r=n.map((e,n)=>e-t[n]),i=Math.hypot(...r);if(!i)return;let a=e.physics.raycast(t,r,{maxDistance:i});if(a)return{nodeIndex:[...e.bodies].find(([,e])=>e===a.body)?.[0]??-1,fraction:a.distance/i,normal:[...a.normal]}}}}export{g as GLTFInteractivity,u as sampleChannel};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// @margo/core-built
|
|
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,t}from"./pose-source-MuCl8VDd.js";import{s as n}from"./sampling-DjDWYqt2.js";import{n as r}from"./shader-CgAVFeOl.js";import{MargoError as i}from"@margoengine/math/errors";import{composeMatrix as a,invertMatrixStable as o,multiplyMatrices as s}from"@margoengine/math/mat4";import{normalizeQuaternion as c}from"@margoengine/math/quat";function l(e,t,n){let r=e;if(!r||typeof r!=`object`||r.length!==t)throw TypeError(`${n} needs ${t} numbers; pass an array of length ${t}`);for(let e=0;e<t;e++)if(typeof r[e]!=`number`||!Number.isFinite(r[e]))throw RangeError(`${n} has a non-finite value; pass finite numbers`);return r}var u=/* @__PURE__ */ new Float64Array(4);function d(e,t){let n=e;if(!n||typeof n!=`object`||n.length!==t)return!1;for(let e=0;e<t;e++)if(typeof n[e]!=`number`||!Number.isFinite(n[e]))return!1;return!0}function f(e,t,n,r){let i=n.translation,a=n.scale,o=n.rotation;if(i!==void 0&&!d(i,3)&&l(i,3,`Skeleton bone ${r} translation`),a!==void 0&&!d(a,3)&&l(a,3,`Skeleton bone ${r} scale`),o!==void 0&&!d(o,4)&&l(o,4,`Skeleton bone ${r} rotation`),o&&!(o[0]||o[1]||o[2]||o[3]))throw RangeError(`Skeleton bone ${r} rotation is a zero quaternion; pass a unit quaternion`);i&&e.set(i,t),a&&e.set(a,t+7),o&&e.set(c(o,u),t+3)}var p=class{constructor(e,t){if(this.revision=0,this.order=[],this.local=/* @__PURE__ */ new Float64Array(16),this.workspace=/* @__PURE__ */ new Float64Array(52),this.dirty=!0,!Array.isArray(e)||!e.length)throw TypeError(`Skeleton bones must be a nonempty array; pass at least a root bone`);let n=e.length,r=e.map((e,t)=>{if(!e||typeof e!=`object`)throw TypeError(`Skeleton bone ${t} must be an object`);if(typeof e.name!=`string`||!e.name)throw TypeError(`Skeleton bone ${t} needs a nonempty string name`);return e.name});if(this.byName=new Map(r.map((e,t)=>[e,t])),this.byName.size!==n)throw TypeError(`Skeleton bone names repeat; give every bone a unique name`);let i=e.map(({parent:e},t)=>{if(!Number.isInteger(e)||e<-1||e>=n||e===t)throw RangeError(`Skeleton bone ${t} parent ${e} is invalid; use -1 or another bone's index`);return e}),a=i.filter(e=>e===-1).length;if(a!==1)throw RangeError(`Skeleton has ${a} root bones; give exactly one bone parent -1`);this.names=Object.freeze(r),this.parents=Object.freeze(i),this.root=i.indexOf(-1);let o=i.map(()=>[]);i.forEach((e,t)=>e>=0&&o[e].push(t));for(let e=[this.root];e.length;){let t=e.pop();this.order.push(t),e.push(...o[t])}if(this.order.length!==n)throw RangeError(`Skeleton bone parents form a cycle; every parent chain must end at the root`);this.base=new Float64Array(n*10),e.forEach((e,t)=>{this.base.set([0,0,0,0,0,0,1,1,1,1],t*10),f(this.base,t*10,e,t)}),this.pose=this.base.slice(),this.world=new Float64Array(n*16),this.skin=new Float64Array(n*16),this.inverse=new Float64Array(n*16),t===void 0?this.bind():this.inverse.set(l(t,n*16,`Skeleton inverse bind matrices`))}get count(){return this.names.length}index(e){return this.byName.get(e)??-1}bone(e){if(!Number.isInteger(e)||e<0||e>=this.count)throw RangeError(`Skeleton bone ${e} does not exist; pass an index below ${this.count}`);return e}setPose(e,t){return f(this.pose,this.bone(e)*10,t??{},e),this.changed()}getPose(e){let t=this.pose,n=this.bone(e)*10;return{translation:[t[n],t[n+1],t[n+2]],rotation:[t[n+3],t[n+4],t[n+5],t[n+6]],scale:[t[n+7],t[n+8],t[n+9]]}}restorePose(e,t=!1){if(e===void 0)this.pose.set(this.base);else{let n=new Uint8Array(this.count);n[this.bone(e)]=1;for(let e of this.order)t&&this.parents[e]>=0&&n[this.parents[e]]&&(n[e]=1),n[e]&&this.pose.set(this.base.subarray(e*10,e*10+10),e*10)}return this.changed()}setBindPose(){return this.bind(),this.base.set(this.pose),this.changed()}bind(){let e=this.matrices,t=this.inverse.slice();for(let n=0;n<this.count;n++)if(!o(e.subarray(n*16,n*16+16),t.subarray(n*16,n*16+16),this.workspace))throw RangeError(`Skeleton bone ${n} bind pose is singular; give it a non-zero scale`);this.inverse.set(t),this.dirty=!0}changed(){return this.dirty=!0,this.revision++,this}update(){if(!this.dirty)return;let{pose:e,world:t,local:n}=this;for(let r of this.order){a(e.subarray(r*10,r*10+3),e.subarray(r*10+3,r*10+7),e.subarray(r*10+7,r*10+10),n);let i=this.parents[r],o=t.subarray(r*16,r*16+16);i<0?o.set(n):s(t.subarray(i*16,i*16+16),n,o),s(o,this.inverse.subarray(r*16,r*16+16),this.skin.subarray(r*16,r*16+16))}this.dirty=!1}get matrices(){return this.update(),this.world}get inverseBindMatrices(){return this.inverse}get skinMatrices(){return this.update(),this.skin}worldMatrix(e,t,n=/* @__PURE__ */ new Float32Array(16)){let r=this.bone(e)*16,i=this.matrices.subarray(r,r+16);return t===void 0?n.set(i):s(l(t,16,`Skeleton parent matrix`),i,n),n}},m=/* @__PURE__ */ new WeakMap,h=0,g=class n{coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);constructor(e,t,n){if(this.skeleton=e,this.name=`skin:`+h++,this.edits=0,this.dirtyFrom=0,this.uploaded=-1,this.disposed=!1,this.prepare=e=>this.deform(e),this.scenePose=()=>{let e=this.mesh;if(!this.gpu||!e||e.primitives[0].deformed!==this.gpu.output)return;let t=this.picking.posePickingGeometry()[0].vertices,n=this.scenePosed??={vertices:new Float32Array(t.length),revision:0};return n.from!==t&&(n.vertices.length!==t.length&&(n.vertices=new Float32Array(t.length)),n.vertices.set(t),n.from=t,n.revision++),n},!(e instanceof p))throw TypeError(`Skin needs a Skeleton; pass new Skeleton(bones)`);let r=t?.length/4;if(!Number.isInteger(r)||r<1)throw RangeError(`Skin joints need four bone indices per vertex for at least one vertex`);this.count=this.dirtyTo=r;let i=/* @__PURE__ */ new ArrayBuffer(r*32);this.ids=new Uint32Array(i),this.weights=new Float32Array(i),this.setInfluences(0,t,n)}setInfluences(e,t,n){let r=t?.length/4,i=this.skeleton.count;if(!Number.isInteger(e)||e<0||!Number.isInteger(r)||e+r>this.count)throw RangeError(`Skin influences for vertices ${e}+ exceed the ${this.count} vertices; pass 4 joints each`);if(n?.length!==t.length)throw RangeError(`Skin weights need one weight per joint index; pass 4 weights per vertex`);for(let r=0;r<t.length;r++){let a=t[r],o=n[r];if(!Number.isInteger(a)||a<0||a>=i)throw RangeError(`Skin joint ${a} at vertex ${e+(r>>2)} is not a bone; use 0 to ${i-1}`);if(typeof o!=`number`||!Number.isFinite(o)||o<0)throw RangeError(`Skin weight ${o} at vertex ${e+(r>>2)} is invalid; use a finite number >= 0`)}for(let i=0;i<r;i++){let r=(e+i)*8,a=n[i*4]+n[i*4+1]+n[i*4+2]+n[i*4+3];for(let e=0;e<4;e++)this.ids[r+e]=a>0?t[i*4+e]:this.skeleton.root,this.weights[r+4+e]=a>0?n[i*4+e]/a:+(e===0)}return this.edits++,this.dirtyFrom=Math.min(this.dirtyFrom,e),this.dirtyTo=Math.max(this.dirtyTo,e+r),this}pose(e,t){let n=l(e,this.count*3,`Skin positions`),r=t===void 0?void 0:l(t,this.count*3,`Skin normals`),i=this.skeleton.skinMatrices,a=/* @__PURE__ */ new Float64Array(16),o=new Float32Array(this.count*3),s=r&&new Float32Array(this.count*3);for(let e=0,t=0;e<this.count;e++,t+=3){a.fill(0);for(let t=0;t<4;t++){let n=this.weights[e*8+4+t],r=this.ids[e*8+t]*16;if(n)for(let e=0;e<16;e++)a[e]+=n*i[r+e]}for(let e=0;e<3;e++)o[t+e]=a[e]*n[t]+a[4+e]*n[t+1]+a[8+e]*n[t+2]+a[12+e];if(!r||!s)continue;let c=[a[5]*a[10]-a[6]*a[9],a[6]*a[8]-a[4]*a[10],a[4]*a[9]-a[5]*a[8]],l=[a[9]*a[2]-a[10]*a[1],a[10]*a[0]-a[8]*a[2],a[8]*a[1]-a[9]*a[0]],u=[a[1]*a[6]-a[2]*a[5],a[2]*a[4]-a[0]*a[6],a[0]*a[5]-a[1]*a[4]],d=a[0]*c[0]+a[1]*c[1]+a[2]*c[2]<0?-1:1,f=(c[0]*r[t]+l[0]*r[t+1]+u[0]*r[t+2])*d,p=(c[1]*r[t]+l[1]*r[t+1]+u[1]*r[t+2])*d,m=(c[2]*r[t]+l[2]*r[t+1]+u[2]*r[t+2])*d,h=Math.hypot(f,p,m);s[t]=h>0?f/h:0,s[t+1]=h>0?p/h:1,s[t+2]=h>0?m/h:0}return s?{positions:o,normals:s}:{positions:o}}get picking(){let e=this;return this.pickingSource??={get root(){return e.requireMesh().root},get disposed(){return e.disposed||!e.mesh||e.mesh.disposed},posePickingGeometry:()=>{let e=this.requireMesh(),t=this.skeleton.revision+`:`+this.edits;if(this.posed?.key===t&&this.posed.mesh===e){for(let e of this.posed.list)e.matrix.set(e.node.matrix);return this.posed.list}let n=e.primitives[0].vertices,r=new Float32Array(this.count*3),i=new Float32Array(this.count*3);for(let e=0;e<this.count;e++)for(let t=0;t<3;t++)r[e*3+t]=n[e*20+t],i[e*3+t]=n[e*20+4+t];let a=this.pose(r,i),o=n.slice();for(let e=0;e<this.count;e++)for(let t=0;t<3;t++)o[e*20+t]=a.positions[e*3+t],o[e*20+4+t]=a.normals[e*3+t];let s=e.primitives.map((e,t)=>{let n=e.material,r=n.side??(n.settings[2]===2?`back`:n.settings[2]>=.5?`double`:`front`);return{node:e.node,vertices:o,indices:e.indices instanceof Uint32Array?e.indices:Uint32Array.from(e.indices),doubleSided:r===`double`,side:r,matrix:new Float32Array(e.node.matrix),primitiveIndex:t}});return this.posed={key:t,mesh:e,list:s},s}}}requireMesh(){if(!this.mesh)throw new i(`state`,`Skin is not attached; create it with Skin.attach(mesh, skeleton, joints, weights)`);return this.mesh}static attach(e,t,r,a){__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));let o=new n(t,r,a),s=e?.primitives?.[0]?.vertices;if(!s||e.primitives.some(e=>e.vertices!==s))throw TypeError(`Skin needs a mesh whose primitives share one vertex array; use createMesh`);if(s.length/20!==o.count)throw RangeError(`Skin has ${o.count} vertices but the mesh has ${s.length/20}; match them`);if(e.disposed)throw new i(`disposed`,`Skin mesh is disposed; attach the skin to a live mesh`);if(e.primitives.some(e=>e.deformed))throw new i(`attached`,`Mesh is already deformed by another plugin; dispose that one first`);return o.mesh=e,e.root.engine.use(o),o}setup(t){let n=this.mesh;if(!n||this.disposed)throw new i(`state`,`Skin is not attached; create it with Skin.attach(mesh, skeleton, joints, weights)`);if(n.disposed)throw new i(`disposed`,`Skin mesh is disposed; attach the skin to a live mesh`);let a=t.gpu;if(!a)throw new i(`unsupported`,`Skin needs WebGPU; create the engine with the webgpu backend; see https://margoengine.com/errors#webgpu`);let o=m.get(a)??a.createComputePipeline({layout:`auto`,compute:{module:a.createShaderModule({code:r}),entryPoint:`main`}});m.set(a,o);let s=[],c=n.primitives[0].vertices,l=(e,t=GPUBufferUsage.STORAGE)=>{let n=a.createBuffer({size:Math.max(16,e),usage:t|GPUBufferUsage.COPY_DST});return s.push(n),n};if(Math.max(c.byteLength,this.count*32,this.skeleton.count*64)>Math.min(a.limits.maxStorageBufferBindingSize,a.limits.maxBufferSize))throw RangeError(`Skin buffers exceed the device storage limit; use fewer vertices or bones`);this.unsubscribe??=n.onDispose(()=>this.dispose());let u=l(c.byteLength),d=l(c.byteLength,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC),f=l(this.skeleton.count*64),p=l(this.count*32),h=l(16,GPUBufferUsage.UNIFORM),g=[u,d,l(48),l(16),f,p,h];a.queue.writeBuffer(h,0,new Uint32Array([this.count,0,this.skeleton.count,0])),this.gpu={buffers:s,source:u,output:d,bones:f,influences:p,pipeline:o,vertices:void 0,palette:new Float32Array(this.skeleton.count*16),group:a.createBindGroup({layout:o.getBindGroupLayout(0),entries:g.map((e,t)=>({binding:t,resource:{buffer:e}}))})},this.uploaded=-1,this.dirtyFrom=0,this.dirtyTo=this.count;for(let t of n.primitives)t.deformed=d,e(t,this.scenePose);n.prepareDeformation=this.prepare}registerPasses(e){e.add({name:this.name,order:-10,execute:e=>this.deform(e)})}deform(e){let t=this.gpu,n=this.mesh;if(e.backend!==`webgpu`||!t||!n||n.disposed)return;let r=e.device.queue,a=n.primitives[0].vertices,o=!1;if(t.vertices!==a){if(a.length!==this.count*20)throw new i(`state`,`Skin mesh vertex count changed; create a new Skin for the new geometry`);r.writeBuffer(t.source,0,a),t.vertices=a,o=!0}if(this.uploaded!==this.skeleton.revision&&(t.palette.set(this.skeleton.skinMatrices),r.writeBuffer(t.bones,0,t.palette),this.uploaded=this.skeleton.revision,o=!0),this.dirtyFrom<this.dirtyTo&&(r.writeBuffer(t.influences,this.dirtyFrom*32,this.ids.subarray(this.dirtyFrom*8,this.dirtyTo*8)),this.dirtyFrom=this.count,this.dirtyTo=0,o=!0),!o)return;let s=e.encoder.beginComputePass();try{s.setPipeline(t.pipeline),s.setBindGroup(0,t.group),s.dispatchWorkgroups(Math.ceil(this.count/64))}finally{s.end()}}release(){let e=this.mesh,n=this.gpu;if(e&&n){e.prepareDeformation===this.prepare&&(e.prepareDeformation=void 0);for(let r of e.primitives)r.deformed===n.output&&(r.deformed=void 0),t(r,this.scenePose);for(let e of n.buffers)e.destroy();this.gpu=void 0}}onDeviceRestored(e){this.release(),this.setup(e)}dispose(){this.disposed||(this.disposed=!0,this.release(),this.unsubscribe?.(),this.unsubscribe=void 0,this.mesh?.root.engine.sceneOf(this)?.removePlugin(this.name))}[Symbol.dispose??Symbol()](){this.dispose()}},_=/* @__PURE__ */ new Float64Array(4),v=[`discrete`,`linear`,`easeIn`,`easeOut`,`easeInOut`,`cubicSpline`],y=(e,t)=>e===`discrete`?0:e===`easeIn`?t*t*t:e===`easeOut`?1-(1-t)**3:e===`easeInOut`?t<.5?4*t*t*t:1-(2-2*t)**3/2:t;function b(e,t,n,r){let i=new Float64Array(t.length),a=new Float64Array(t.length*n),o=t.some(e=>e?.interpolation===`cubicSpline`)?new Float64Array(t.length*n*2):void 0,s=t.map((t,s)=>{let u=t?.time,d=t?.interpolation??`linear`;if(typeof u!=`number`||!Number.isFinite(u)||u<0||s>0&&u<=i[s-1])throw RangeError(`${e} key ${s} time ${u} is invalid; use increasing seconds >= 0`);if(!v.includes(d))throw TypeError(`${e} key ${s} interpolation ${d} is invalid; use one of ${v.join(`, `)}`);let f=l(t.value,n,`${e} key ${s} value`);if(!r)a.set(f,s*n);else if(f[0]||f[1]||f[2]||f[3])a.set(c(f,_),s*n);else throw RangeError(`${e} key ${s} is a zero quaternion; pass a unit quaternion`);return o&&(t.inTangent!==void 0&&o.set(l(t.inTangent,n,`${e} key ${s} inTangent`),s*n*2),t.outTangent!==void 0&&o.set(l(t.outTangent,n,`${e} key ${s} outTangent`),s*n*2+n)),i[s]=u,d});return o?{times:i,values:a,interpolations:s,tangents:o}:{times:i,values:a,interpolations:s}}var x=[`x`,`y`,`z`,`w`],S=[`r`,`g`,`b`,`a`],C=e=>Array.isArray(e)||ArrayBuffer.isView(e)&&!(e instanceof DataView);function w(e,t,n,r){let i=t.split(`.`);if(i.some(e=>!e))throw TypeError(`${r} property path '${t}' has an empty segment; use names joined by dots`);let a=e;for(let e=0;e<i.length-1;e++){let n=a[i[e]];if(!n||typeof n!=`object`)throw RangeError(`${r} property path '${t}' stops at '${i.slice(0,e+1).join(`.`)}', which is ${n===null?`null`:typeof n}; check the path names an object`);a=n}let o=i[i.length-1];if(!(o in a))throw RangeError(`${r} property path '${t}' has no '${o}' on its object; check the spelling`);let s=a[o],c=e=>/* @__PURE__ */ TypeError(`${r} property '${t}' ${e}, which ${n} number${n>1?`s`:``} per key cannot drive; key a matching size or pass set`);if(typeof s==`number`||typeof s==`boolean`){if(n!==1)throw c(`is a ${typeof s}`);return typeof s==`number`?e=>a[o]=e[0]:e=>a[o]=e[0]>=.5}if(C(s)){if(s.length<n)throw c(`holds ${s.length} numbers`);if(a[o]!==s){let e=Array(n).fill(0);return t=>{for(let r=0;r<n;r++)e[r]=t[r];a[o]=e}}let e=s;return t=>{for(let r=0;r<n;r++)e[r]=t[r]}}if(s&&typeof s==`object`){let e=s,t=typeof e.r==`number`?S:x;for(let r=0;r<n;r++)if(typeof e[t[r]]!=`number`)throw c(`has no number field '${t[r]}'`);if(n===3&&t===x&&typeof e.set==`function`){let t=e.set;return n=>t.call(e,n[0],n[1],n[2])}return r=>{for(let i=0;i<n;i++)e[t[i]]=r[i]}}throw c(`is ${s===null?`null`:typeof s}, not a number, array or vector object`)}function T(e,t,n){if(typeof e==`number`||typeof e==`boolean`)n[0]=+e;else if(C(e))for(let r=0;r<t;r++)n[r]=e[r];else{let r=e,i=typeof r?.r==`number`?S:x;for(let e=0;e<t;e++)n[e]=r?.[i[e]]}return n}var E=[1,2,3,4].map(e=>new Float64Array(e)),D={number:[1],vector:[2,3,4],color:[3,4],quaternion:[4]};function O(e,t){let{target:n,property:r,get:i,set:a,keys:o,blend:s}=e;if(r===void 0==(a===void 0))throw TypeError(`${t} needs either a property path or a set accessor; pass exactly one`);if(r!==void 0&&(typeof r!=`string`||!r))throw TypeError(`${t} property must be a nonempty dot path such as 'material.roughness'`);if(a!==void 0&&typeof a!=`function`)throw TypeError(`${t} set must be a function`);if(i!==void 0&&typeof i!=`function`)throw TypeError(`${t} get must be a function`);if(e.name!==void 0&&typeof e.name!=`string`)throw TypeError(`${t} name must be a string`);if(s!==void 0&&s!==`delta`&&s!==`weighted`)throw TypeError(`${t} blend ${s} is invalid; use delta or weighted`);if(!Array.isArray(o)||!o.length)throw TypeError(`${t} needs a nonempty keys array`);let c=Number(o[0]?.value?.length),l=e.type??(c===1?`number`:`vector`),u=D[l];if(!u)throw TypeError(`${t} type ${l} is invalid; use number, vector, color or quaternion`);if(!u.includes(c))throw RangeError(`${t} ${l} keys need ${u.join(` or `)} numbers each; pass that many in every key`);let d=e.name??r??`set`,f=b(t,o,c,l===`quaternion`),p=E[c-1],m=a?e=>{for(let t=0;t<c;t++)p[t]=e[t];a(p)}:w(n,r,c,t),h=(e=new Float64Array(c))=>{if(i)return T(i(),c,e);if(r===void 0)throw TypeError(`Property track ${d} has no get accessor; pass get to read it`);let t=n;for(let e of r.split(`.`))t=t[e];return T(t,c,e)};return{target:n,...r===void 0?{}:{property:r},name:d,type:l,size:c,...f,...s===void 0?{}:{blend:s},write:m,read:h}}function k(e){if(!e||!Array.isArray(e.tracks))throw TypeError(`Keyframe clip needs a tracks array`);if(e.name!==void 0&&typeof e.name!=`string`)throw TypeError(`Keyframe clip name must be a string`);let t=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Map,i=[],a=[];e.tracks.forEach((e,n)=>{let o=`Keyframe track ${n}`,s=e?.target;if(s!==null&&(typeof s==`object`||typeof s==`function`)){let t=e,n=O(t,o),i=t.set??t.property,c=r.get(s)??/* @__PURE__ */ new Set;if(c.has(i))throw TypeError(`${o} repeats property ${n.name}; merge the keys`);r.set(s,c.add(i)),a.push(n);return}if(typeof s!=`string`||!s)throw TypeError(`${o} needs a nonempty string target, or an object target with a property`);let{path:c,keys:l,blend:u}=e;if(c!==`translation`&&c!==`rotation`&&c!==`scale`&&c!==`weights`)throw TypeError(`${o} path ${c} is invalid; use translation, rotation, scale or weights`);if(u!==void 0&&u!==`delta`&&u!==`weighted`)throw TypeError(`${o} blend ${u} is invalid; use delta or weighted`);if(t.has(s+`:`+c))throw TypeError(`${o} repeats ${s} ${c}; merge the keys`);if(t.add(s+`:`+c),!Array.isArray(l)||!l.length)throw TypeError(`${o} needs a nonempty keys array`);let d=c===`rotation`?4:c===`weights`?Number(l[0]?.value?.length):3;if(!(Number.isInteger(d)&&d>0))throw TypeError(`${o} weights keys need one number per morph target; pass a nonempty array`);let f=b(o,l,d,c===`rotation`);i.push({target:s,path:c,...f,...u===void 0?{}:{blend:u}})});let o=Math.max(0,...[...i,...a].map(e=>e.times[e.times.length-1])),s=n(e.markers??[]);if(s.some(e=>e.time>o))throw RangeError(`Keyframe clip marker is past the last key; move it inside the clip or add a key there`);return{name:e.name??``,duration:o,tracks:i,properties:a,markers:s}}function A(e,t,n){if(typeof t!=`number`||!Number.isFinite(t))throw RangeError(`Keyframe sample time ${t} is invalid; pass finite seconds`);let{times:r,values:i}=e,a=`path`in e?e.path!==`rotation`:e.type!==`quaternion`,o=a?i.length/r.length:4,s=r.length-1;if(n!==void 0&&!(n instanceof Float64Array&&n.length>=o))throw TypeError(`Keyframe sample target must be a Float64Array of at least ${o} numbers`);n??=new Float64Array(o);let l=0;if(t>=r[s])l=s;else if(t>r[0])for(let e=s;l+1<e;){let n=l+e>>1;r[n]<=t?l=n:e=n}let u=l===s||t<=r[l]?0:y(e.interpolations[l],(t-r[l])/(r[l+1]-r[l])),d=l*o,f=Math.min(l+1,s)*o;if(u>0&&u<1&&e.interpolations[l]===`cubicSpline`){let t=r[l+1]-r[l],s=u,p=s*s,m=p*s,h=e.tangents,g=l*o*2+o,_=(l+1)*o*2;for(let e=0;e<o;e++)n[e]=(2*m-3*p+1)*i[d+e]+(m-2*p+s)*t*h[g+e]+(-2*m+3*p)*i[f+e]+(m-p)*t*h[_+e];return a?n:(n[0]||n[1]||n[2]||n[3]||n.set(i.subarray(d,d+4)),c(n,n))}if(e.blend===`weighted`){if(u===0||u===1)return n.set(i.subarray(u?f:d,(u?f:d)+o)),n;if(a){for(let e=0;e<o;e++){let t=i[d+e],r=i[f+e],a=(1-u)*t+u*r;n[e]=Number.isFinite(a)?a:a>0?Math.max(t,r):Math.min(t,r)}return n}}else if(a||u===0||u===1){for(let e=0;e<o;e++)n[e]=u===1?i[f+e]:i[d+e]+(i[f+e]-i[d+e])*u;return n}let p=0;for(let e=0;e<4;e++)p+=i[d+e]*i[f+e];let m=p<0?-1:1,h=Math.acos(Math.min(1,Math.abs(p))),g=Math.sin(h),_=g>1e-6?Math.sin((1-u)*h)/g:1-u,v=(g>1e-6?Math.sin(u*h)/g:u)*m;for(let e=0;e<4;e++)n[e]=i[d+e]*_+i[f+e]*v;return c(n,n)}var j=/* @__PURE__ */ new Float64Array(4),M=(e,t)=>{let n=new Float64Array(t);return{value:n,pose:{[e]:n}}},N={translation:M(`translation`,3),rotation:M(`rotation`,4),scale:M(`scale`,3)},P=/* @__PURE__ */ new WeakMap;function F(e,t){let n=e.tracks,r=P.get(n);r||P.set(n,r=/* @__PURE__ */ new WeakMap);let i=r.get(t);return(!i||i.length!==n.length)&&(i=Int32Array.from(n,e=>e.path===`weights`?-1:t.index(e.target)),r.set(t,i)),i}function I(e,t,n){let r=typeof t==`number`?void 0:t,i=typeof t==`number`?t:n;if(r!==void 0&&!(r instanceof p)&&(!r||typeof r.setMorph!=`function`||!Array.isArray(r.model?.nodes)))throw TypeError(`applyKeyframeClip needs a Skeleton or an Animation; pass a skeleton or Animation.attach(model)`);let a=e?.properties??[];for(let e=0;e<a.length;e++)a[e].write(A(a[e],i,j));if(r===void 0){if(typeof i!=`number`||!Number.isFinite(i))throw RangeError(`Keyframe clip time ${i} is invalid; pass finite seconds`);return}if(r instanceof p){let t=e.tracks,n=F(e,r);for(let e=0;e<t.length;e++){let a=n[e],o=t[e];if(a<0)continue;let s=N[o.path];A(o,i,s.value),r.setPose(a,s.pose)}return}let{nodes:o,primitives:s}=r.model,c=/* @__PURE__ */ new Map;for(let e=o.length-1;e>=0;e--)typeof o[e].name==`string`&&c.set(o[e].name,e);for(let t of e.tracks){let e=c.get(t.target)??-1;if(e<0)continue;let n=A(t,i),a=o[e];if(t.path===`weights`){let i=s.find(t=>t.nodeIndex===e)?.weights.length??0;if(i!==n.length)throw RangeError(`Keyframe track ${t.target} weights has ${n.length} values but the node has ${i} morph targets; key one weight per target`);for(let t=0;t<i;t++)r.setMorph(e,t,n[t])}else t.path===`translation`?a.setPosition(n):t.path===`scale`?a.setScale(n):a.setQuaternion(n)}}function L(e,t,{loop:n=!1,timeScale:r=1}={}){if(![e,t,r].every(Number.isFinite)||e<0||t<0)throw RangeError(`Segment time needs finite elapsed and duration >= 0 and a finite timeScale`);let i=e*Math.abs(r),a=n&&t>0?i%t:Math.min(i,t);return r<0?t-a:a}function R(e){let t=new Float32Array([e]);return new Uint32Array(t.buffer)[0]--,t[0]}var z=e=>{if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw RangeError(`Keyframe bake fps ${e} is invalid; pass frames per second > 0`)};function B(e,t){z(t);let{times:n,interpolations:r}=e,i=new Set(r.slice(0,-1)),a=i.size===0||i.size===1&&(i.has(`discrete`)||i.has(`linear`)),o=[],s=[],c=(t,n=t)=>{let r=Math.fround(t);return o.length&&r<=o[o.length-1]?!1:(o.push(r),s.push(...A(e,n)),!0)};for(let i=0;i<n.length;i++){if(!c(n[i]))throw RangeError(`Keyframe track ${`path`in e?e.target+` `+e.path:e.name} keys are closer than Float32 time precision; space keys further apart`);if(a||i===n.length-1||r[i]===`linear`)continue;let o=Math.fround(n[i+1]);if(r[i]===`discrete`)c(R(o),n[i]);else for(let e=Math.floor(n[i]*t)+1;e/t<n[i+1];e++)Math.fround(e/t)<o&&c(e/t,Math.fround(e/t))}if(`path`in e?e.path===`rotation`:e.type===`quaternion`){for(let e=4;e<s.length;e+=4)if(s[e]*s[e-4]+s[e+1]*s[e-3]+s[e+2]*s[e-2]+s[e+3]*s[e-1]<0)for(let t=0;t<4;t++)s[e+t]=-s[e+t]}return{interpolation:a&&i.has(`discrete`)?`STEP`:`LINEAR`,times:Float32Array.from(o),values:Float32Array.from(s)}}function V(e,t,n){if(z(t),typeof n!=`function`)throw TypeError(`Keyframe bake needs a resolve(target) function`);let r=[];for(let i of e.tracks){let e=n(i.target);e!==void 0&&r.push({node:e,path:i.path,...B(i,t)})}return{name:e.name,channels:r}}export{A as a,g as c,k as i,V as n,L as o,B as r,p as s,I as t};
|
|
4
|
+
import{n as e,t}from"./pose-source-MuCl8VDd.js";import{s as n}from"./sampling-DjDWYqt2.js";import{n as r}from"./shader-DuGkHFKx.js";import{MargoError as i}from"@margoengine/math/errors";import{composeMatrix as a,invertMatrixStable as o,multiplyMatrices as s}from"@margoengine/math/mat4";import{normalizeQuaternion as c}from"@margoengine/math/quat";function l(e,t,n){let r=e;if(!r||typeof r!=`object`||r.length!==t)throw TypeError(`${n} needs ${t} numbers; pass an array of length ${t}`);for(let e=0;e<t;e++)if(typeof r[e]!=`number`||!Number.isFinite(r[e]))throw RangeError(`${n} has a non-finite value; pass finite numbers`);return r}var u=/* @__PURE__ */ new Float64Array(4);function d(e,t){let n=e;if(!n||typeof n!=`object`||n.length!==t)return!1;for(let e=0;e<t;e++)if(typeof n[e]!=`number`||!Number.isFinite(n[e]))return!1;return!0}function f(e,t,n,r){let i=n.translation,a=n.scale,o=n.rotation;if(i!==void 0&&!d(i,3)&&l(i,3,`Skeleton bone ${r} translation`),a!==void 0&&!d(a,3)&&l(a,3,`Skeleton bone ${r} scale`),o!==void 0&&!d(o,4)&&l(o,4,`Skeleton bone ${r} rotation`),o&&!(o[0]||o[1]||o[2]||o[3]))throw RangeError(`Skeleton bone ${r} rotation is a zero quaternion; pass a unit quaternion`);i&&e.set(i,t),a&&e.set(a,t+7),o&&e.set(c(o,u),t+3)}var p=class{constructor(e,t){if(this.revision=0,this.order=[],this.local=/* @__PURE__ */ new Float64Array(16),this.workspace=/* @__PURE__ */ new Float64Array(52),this.dirty=!0,!Array.isArray(e)||!e.length)throw TypeError(`Skeleton bones must be a nonempty array; pass at least a root bone`);let n=e.length,r=e.map((e,t)=>{if(!e||typeof e!=`object`)throw TypeError(`Skeleton bone ${t} must be an object`);if(typeof e.name!=`string`||!e.name)throw TypeError(`Skeleton bone ${t} needs a nonempty string name`);return e.name});if(this.byName=new Map(r.map((e,t)=>[e,t])),this.byName.size!==n)throw TypeError(`Skeleton bone names repeat; give every bone a unique name`);let i=e.map(({parent:e},t)=>{if(!Number.isInteger(e)||e<-1||e>=n||e===t)throw RangeError(`Skeleton bone ${t} parent ${e} is invalid; use -1 or another bone's index`);return e}),a=i.filter(e=>e===-1).length;if(a!==1)throw RangeError(`Skeleton has ${a} root bones; give exactly one bone parent -1`);this.names=Object.freeze(r),this.parents=Object.freeze(i),this.root=i.indexOf(-1);let o=i.map(()=>[]);i.forEach((e,t)=>e>=0&&o[e].push(t));for(let e=[this.root];e.length;){let t=e.pop();this.order.push(t),e.push(...o[t])}if(this.order.length!==n)throw RangeError(`Skeleton bone parents form a cycle; every parent chain must end at the root`);this.base=new Float64Array(n*10),e.forEach((e,t)=>{this.base.set([0,0,0,0,0,0,1,1,1,1],t*10),f(this.base,t*10,e,t)}),this.pose=this.base.slice(),this.world=new Float64Array(n*16),this.skin=new Float64Array(n*16),this.inverse=new Float64Array(n*16),t===void 0?this.bind():this.inverse.set(l(t,n*16,`Skeleton inverse bind matrices`))}get count(){return this.names.length}index(e){return this.byName.get(e)??-1}bone(e){if(!Number.isInteger(e)||e<0||e>=this.count)throw RangeError(`Skeleton bone ${e} does not exist; pass an index below ${this.count}`);return e}setPose(e,t){return f(this.pose,this.bone(e)*10,t??{},e),this.changed()}getPose(e){let t=this.pose,n=this.bone(e)*10;return{translation:[t[n],t[n+1],t[n+2]],rotation:[t[n+3],t[n+4],t[n+5],t[n+6]],scale:[t[n+7],t[n+8],t[n+9]]}}restorePose(e,t=!1){if(e===void 0)this.pose.set(this.base);else{let n=new Uint8Array(this.count);n[this.bone(e)]=1;for(let e of this.order)t&&this.parents[e]>=0&&n[this.parents[e]]&&(n[e]=1),n[e]&&this.pose.set(this.base.subarray(e*10,e*10+10),e*10)}return this.changed()}setBindPose(){return this.bind(),this.base.set(this.pose),this.changed()}bind(){let e=this.matrices,t=this.inverse.slice();for(let n=0;n<this.count;n++)if(!o(e.subarray(n*16,n*16+16),t.subarray(n*16,n*16+16),this.workspace))throw RangeError(`Skeleton bone ${n} bind pose is singular; give it a non-zero scale`);this.inverse.set(t),this.dirty=!0}changed(){return this.dirty=!0,this.revision++,this}update(){if(!this.dirty)return;let{pose:e,world:t,local:n}=this;for(let r of this.order){a(e.subarray(r*10,r*10+3),e.subarray(r*10+3,r*10+7),e.subarray(r*10+7,r*10+10),n);let i=this.parents[r],o=t.subarray(r*16,r*16+16);i<0?o.set(n):s(t.subarray(i*16,i*16+16),n,o),s(o,this.inverse.subarray(r*16,r*16+16),this.skin.subarray(r*16,r*16+16))}this.dirty=!1}get matrices(){return this.update(),this.world}get inverseBindMatrices(){return this.inverse}get skinMatrices(){return this.update(),this.skin}worldMatrix(e,t,n=/* @__PURE__ */ new Float32Array(16)){let r=this.bone(e)*16,i=this.matrices.subarray(r,r+16);return t===void 0?n.set(i):s(l(t,16,`Skeleton parent matrix`),i,n),n}},m=/* @__PURE__ */ new WeakMap,h=0,g=class n{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);constructor(e,t,n){if(this.skeleton=e,this.name=`skin:`+h++,this.edits=0,this.dirtyFrom=0,this.uploaded=-1,this.disposed=!1,this.prepare=e=>this.deform(e),this.scenePose=()=>{let e=this.mesh;if(!this.gpu||!e||e.primitives[0].deformed!==this.gpu.output)return;let t=this.picking.posePickingGeometry()[0].vertices,n=this.scenePosed??={vertices:new Float32Array(t.length),revision:0};return n.from!==t&&(n.vertices.length!==t.length&&(n.vertices=new Float32Array(t.length)),n.vertices.set(t),n.from=t,n.revision++),n},!(e instanceof p))throw TypeError(`Skin needs a Skeleton; pass new Skeleton(bones)`);let r=t?.length/4;if(!Number.isInteger(r)||r<1)throw RangeError(`Skin joints need four bone indices per vertex for at least one vertex`);this.count=this.dirtyTo=r;let i=/* @__PURE__ */ new ArrayBuffer(r*32);this.ids=new Uint32Array(i),this.weights=new Float32Array(i),this.setInfluences(0,t,n)}setInfluences(e,t,n){let r=t?.length/4,i=this.skeleton.count;if(!Number.isInteger(e)||e<0||!Number.isInteger(r)||e+r>this.count)throw RangeError(`Skin influences for vertices ${e}+ exceed the ${this.count} vertices; pass 4 joints each`);if(n?.length!==t.length)throw RangeError(`Skin weights need one weight per joint index; pass 4 weights per vertex`);for(let r=0;r<t.length;r++){let a=t[r],o=n[r];if(!Number.isInteger(a)||a<0||a>=i)throw RangeError(`Skin joint ${a} at vertex ${e+(r>>2)} is not a bone; use 0 to ${i-1}`);if(typeof o!=`number`||!Number.isFinite(o)||o<0)throw RangeError(`Skin weight ${o} at vertex ${e+(r>>2)} is invalid; use a finite number >= 0`)}for(let i=0;i<r;i++){let r=(e+i)*8,a=n[i*4]+n[i*4+1]+n[i*4+2]+n[i*4+3];for(let e=0;e<4;e++)this.ids[r+e]=a>0?t[i*4+e]:this.skeleton.root,this.weights[r+4+e]=a>0?n[i*4+e]/a:+(e===0)}return this.edits++,this.dirtyFrom=Math.min(this.dirtyFrom,e),this.dirtyTo=Math.max(this.dirtyTo,e+r),this}pose(e,t){let n=l(e,this.count*3,`Skin positions`),r=t===void 0?void 0:l(t,this.count*3,`Skin normals`),i=this.skeleton.skinMatrices,a=/* @__PURE__ */ new Float64Array(16),o=new Float32Array(this.count*3),s=r&&new Float32Array(this.count*3);for(let e=0,t=0;e<this.count;e++,t+=3){a.fill(0);for(let t=0;t<4;t++){let n=this.weights[e*8+4+t],r=this.ids[e*8+t]*16;if(n)for(let e=0;e<16;e++)a[e]+=n*i[r+e]}for(let e=0;e<3;e++)o[t+e]=a[e]*n[t]+a[4+e]*n[t+1]+a[8+e]*n[t+2]+a[12+e];if(!r||!s)continue;let c=[a[5]*a[10]-a[6]*a[9],a[6]*a[8]-a[4]*a[10],a[4]*a[9]-a[5]*a[8]],l=[a[9]*a[2]-a[10]*a[1],a[10]*a[0]-a[8]*a[2],a[8]*a[1]-a[9]*a[0]],u=[a[1]*a[6]-a[2]*a[5],a[2]*a[4]-a[0]*a[6],a[0]*a[5]-a[1]*a[4]],d=a[0]*c[0]+a[1]*c[1]+a[2]*c[2]<0?-1:1,f=(c[0]*r[t]+l[0]*r[t+1]+u[0]*r[t+2])*d,p=(c[1]*r[t]+l[1]*r[t+1]+u[1]*r[t+2])*d,m=(c[2]*r[t]+l[2]*r[t+1]+u[2]*r[t+2])*d,h=Math.hypot(f,p,m);s[t]=h>0?f/h:0,s[t+1]=h>0?p/h:1,s[t+2]=h>0?m/h:0}return s?{positions:o,normals:s}:{positions:o}}get picking(){let e=this;return this.pickingSource??={get root(){return e.requireMesh().root},get disposed(){return e.disposed||!e.mesh||e.mesh.disposed},posePickingGeometry:()=>{let e=this.requireMesh(),t=this.skeleton.revision+`:`+this.edits;if(this.posed?.key===t&&this.posed.mesh===e){for(let e of this.posed.list)e.matrix.set(e.node.matrix);return this.posed.list}let n=e.primitives[0].vertices,r=new Float32Array(this.count*3),i=new Float32Array(this.count*3);for(let e=0;e<this.count;e++)for(let t=0;t<3;t++)r[e*3+t]=n[e*20+t],i[e*3+t]=n[e*20+4+t];let a=this.pose(r,i),o=n.slice();for(let e=0;e<this.count;e++)for(let t=0;t<3;t++)o[e*20+t]=a.positions[e*3+t],o[e*20+4+t]=a.normals[e*3+t];let s=e.primitives.map((e,t)=>{let n=e.material,r=n.side??(n.settings[2]===2?`back`:n.settings[2]>=.5?`double`:`front`);return{node:e.node,vertices:o,indices:e.indices instanceof Uint32Array?e.indices:Uint32Array.from(e.indices),doubleSided:r===`double`,side:r,matrix:new Float32Array(e.node.matrix),primitiveIndex:t}});return this.posed={key:t,mesh:e,list:s},s}}}requireMesh(){if(!this.mesh)throw new i(`state`,`Skin is not attached; create it with Skin.attach(mesh, skeleton, joints, weights)`);return this.mesh}static attach(e,t,r,a){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));let o=new n(t,r,a),s=e?.primitives?.[0]?.vertices;if(!s||e.primitives.some(e=>e.vertices!==s))throw TypeError(`Skin needs a mesh whose primitives share one vertex array; use createMesh`);if(s.length/20!==o.count)throw RangeError(`Skin has ${o.count} vertices but the mesh has ${s.length/20}; match them`);if(e.disposed)throw new i(`disposed`,`Skin mesh is disposed; attach the skin to a live mesh`);if(e.primitives.some(e=>e.deformed))throw new i(`attached`,`Mesh is already deformed by another plugin; dispose that one first`);return o.mesh=e,e.root.engine.use(o),o}setup(t){let n=this.mesh;if(!n||this.disposed)throw new i(`state`,`Skin is not attached; create it with Skin.attach(mesh, skeleton, joints, weights)`);if(n.disposed)throw new i(`disposed`,`Skin mesh is disposed; attach the skin to a live mesh`);let a=t.gpu;if(!a)throw new i(`unsupported`,`Skin needs WebGPU; create the engine with the webgpu backend; see https://margoengine.com/errors#webgpu`);let o=m.get(a)??a.createComputePipeline({layout:`auto`,compute:{module:a.createShaderModule({code:r}),entryPoint:`main`}});m.set(a,o);let s=[],c=n.primitives[0].vertices,l=(e,t=GPUBufferUsage.STORAGE)=>{let n=a.createBuffer({size:Math.max(16,e),usage:t|GPUBufferUsage.COPY_DST});return s.push(n),n};if(Math.max(c.byteLength,this.count*32,this.skeleton.count*64)>Math.min(a.limits.maxStorageBufferBindingSize,a.limits.maxBufferSize))throw RangeError(`Skin buffers exceed the device storage limit; use fewer vertices or bones`);this.unsubscribe??=n.onDispose(()=>this.dispose());let u=l(c.byteLength),d=l(c.byteLength,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC),f=l(this.skeleton.count*64),p=l(this.count*32),h=l(16,GPUBufferUsage.UNIFORM),g=[u,d,l(48),l(16),f,p,h];a.queue.writeBuffer(h,0,new Uint32Array([this.count,0,this.skeleton.count,0])),this.gpu={buffers:s,source:u,output:d,bones:f,influences:p,pipeline:o,vertices:void 0,palette:new Float32Array(this.skeleton.count*16),group:a.createBindGroup({layout:o.getBindGroupLayout(0),entries:g.map((e,t)=>({binding:t,resource:{buffer:e}}))})},this.uploaded=-1,this.dirtyFrom=0,this.dirtyTo=this.count;for(let t of n.primitives)t.deformed=d,e(t,this.scenePose);n.prepareDeformation=this.prepare}registerPasses(e){e.add({name:this.name,order:-10,execute:e=>this.deform(e)})}deform(e){let t=this.gpu,n=this.mesh;if(e.backend!==`webgpu`||!t||!n||n.disposed)return;let r=e.device.queue,a=n.primitives[0].vertices,o=!1;if(t.vertices!==a){if(a.length!==this.count*20)throw new i(`state`,`Skin mesh vertex count changed; create a new Skin for the new geometry`);r.writeBuffer(t.source,0,a),t.vertices=a,o=!0}if(this.uploaded!==this.skeleton.revision&&(t.palette.set(this.skeleton.skinMatrices),r.writeBuffer(t.bones,0,t.palette),this.uploaded=this.skeleton.revision,o=!0),this.dirtyFrom<this.dirtyTo&&(r.writeBuffer(t.influences,this.dirtyFrom*32,this.ids.subarray(this.dirtyFrom*8,this.dirtyTo*8)),this.dirtyFrom=this.count,this.dirtyTo=0,o=!0),!o)return;let s=e.encoder.beginComputePass();try{s.setPipeline(t.pipeline),s.setBindGroup(0,t.group),s.dispatchWorkgroups(Math.ceil(this.count/64))}finally{s.end()}}release(){let e=this.mesh,n=this.gpu;if(e&&n){e.prepareDeformation===this.prepare&&(e.prepareDeformation=void 0);for(let r of e.primitives)r.deformed===n.output&&(r.deformed=void 0),t(r,this.scenePose);for(let e of n.buffers)e.destroy();this.gpu=void 0}}onDeviceRestored(e){this.release(),this.setup(e)}dispose(){this.disposed||(this.disposed=!0,this.release(),this.unsubscribe?.(),this.unsubscribe=void 0,this.mesh?.root.engine.sceneOf(this)?.removePlugin(this.name))}[Symbol.dispose??Symbol()](){this.dispose()}},_=/* @__PURE__ */ new Float64Array(4),v=[`discrete`,`linear`,`easeIn`,`easeOut`,`easeInOut`,`cubicSpline`],y=(e,t)=>e===`discrete`?0:e===`easeIn`?t*t*t:e===`easeOut`?1-(1-t)**3:e===`easeInOut`?t<.5?4*t*t*t:1-(2-2*t)**3/2:t;function b(e,t,n,r){let i=new Float64Array(t.length),a=new Float64Array(t.length*n),o=t.some(e=>e?.interpolation===`cubicSpline`)?new Float64Array(t.length*n*2):void 0,s=t.map((t,s)=>{let u=t?.time,d=t?.interpolation??`linear`;if(typeof u!=`number`||!Number.isFinite(u)||u<0||s>0&&u<=i[s-1])throw RangeError(`${e} key ${s} time ${u} is invalid; use increasing seconds >= 0`);if(!v.includes(d))throw TypeError(`${e} key ${s} interpolation ${d} is invalid; use one of ${v.join(`, `)}`);let f=l(t.value,n,`${e} key ${s} value`);if(!r)a.set(f,s*n);else if(f[0]||f[1]||f[2]||f[3])a.set(c(f,_),s*n);else throw RangeError(`${e} key ${s} is a zero quaternion; pass a unit quaternion`);return o&&(t.inTangent!==void 0&&o.set(l(t.inTangent,n,`${e} key ${s} inTangent`),s*n*2),t.outTangent!==void 0&&o.set(l(t.outTangent,n,`${e} key ${s} outTangent`),s*n*2+n)),i[s]=u,d});return o?{times:i,values:a,interpolations:s,tangents:o}:{times:i,values:a,interpolations:s}}var x=[`x`,`y`,`z`,`w`],S=[`r`,`g`,`b`,`a`],C=e=>Array.isArray(e)||ArrayBuffer.isView(e)&&!(e instanceof DataView);function w(e,t,n,r){let i=t.split(`.`);if(i.some(e=>!e))throw TypeError(`${r} property path '${t}' has an empty segment; use names joined by dots`);let a=e;for(let e=0;e<i.length-1;e++){let n=a[i[e]];if(!n||typeof n!=`object`)throw RangeError(`${r} property path '${t}' stops at '${i.slice(0,e+1).join(`.`)}', which is ${n===null?`null`:typeof n}; check the path names an object`);a=n}let o=i[i.length-1];if(!(o in a))throw RangeError(`${r} property path '${t}' has no '${o}' on its object; check the spelling`);let s=a[o],c=e=>/* @__PURE__ */ TypeError(`${r} property '${t}' ${e}, which ${n} number${n>1?`s`:``} per key cannot drive; key a matching size or pass set`);if(typeof s==`number`||typeof s==`boolean`){if(n!==1)throw c(`is a ${typeof s}`);return typeof s==`number`?e=>a[o]=e[0]:e=>a[o]=e[0]>=.5}if(C(s)){if(s.length<n)throw c(`holds ${s.length} numbers`);if(a[o]!==s){let e=Array(n).fill(0);return t=>{for(let r=0;r<n;r++)e[r]=t[r];a[o]=e}}let e=s;return t=>{for(let r=0;r<n;r++)e[r]=t[r]}}if(s&&typeof s==`object`){let e=s,t=typeof e.r==`number`?S:x;for(let r=0;r<n;r++)if(typeof e[t[r]]!=`number`)throw c(`has no number field '${t[r]}'`);if(n===3&&t===x&&typeof e.set==`function`){let t=e.set;return n=>t.call(e,n[0],n[1],n[2])}return r=>{for(let i=0;i<n;i++)e[t[i]]=r[i]}}throw c(`is ${s===null?`null`:typeof s}, not a number, array or vector object`)}function T(e,t,n){if(typeof e==`number`||typeof e==`boolean`)n[0]=+e;else if(C(e))for(let r=0;r<t;r++)n[r]=e[r];else{let r=e,i=typeof r?.r==`number`?S:x;for(let e=0;e<t;e++)n[e]=r?.[i[e]]}return n}var E=[1,2,3,4].map(e=>new Float64Array(e)),D={number:[1],vector:[2,3,4],color:[3,4],quaternion:[4]};function O(e,t){let{target:n,property:r,get:i,set:a,keys:o,blend:s}=e;if(r===void 0==(a===void 0))throw TypeError(`${t} needs either a property path or a set accessor; pass exactly one`);if(r!==void 0&&(typeof r!=`string`||!r))throw TypeError(`${t} property must be a nonempty dot path such as 'material.roughness'`);if(a!==void 0&&typeof a!=`function`)throw TypeError(`${t} set must be a function`);if(i!==void 0&&typeof i!=`function`)throw TypeError(`${t} get must be a function`);if(e.name!==void 0&&typeof e.name!=`string`)throw TypeError(`${t} name must be a string`);if(s!==void 0&&s!==`delta`&&s!==`weighted`)throw TypeError(`${t} blend ${s} is invalid; use delta or weighted`);if(!Array.isArray(o)||!o.length)throw TypeError(`${t} needs a nonempty keys array`);let c=Number(o[0]?.value?.length),l=e.type??(c===1?`number`:`vector`),u=D[l];if(!u)throw TypeError(`${t} type ${l} is invalid; use number, vector, color or quaternion`);if(!u.includes(c))throw RangeError(`${t} ${l} keys need ${u.join(` or `)} numbers each; pass that many in every key`);let d=e.name??r??`set`,f=b(t,o,c,l===`quaternion`),p=E[c-1],m=a?e=>{for(let t=0;t<c;t++)p[t]=e[t];a(p)}:w(n,r,c,t),h=(e=new Float64Array(c))=>{if(i)return T(i(),c,e);if(r===void 0)throw TypeError(`Property track ${d} has no get accessor; pass get to read it`);let t=n;for(let e of r.split(`.`))t=t[e];return T(t,c,e)};return{target:n,...r===void 0?{}:{property:r},name:d,type:l,size:c,...f,...s===void 0?{}:{blend:s},write:m,read:h}}function k(e){if(!e||!Array.isArray(e.tracks))throw TypeError(`Keyframe clip needs a tracks array`);if(e.name!==void 0&&typeof e.name!=`string`)throw TypeError(`Keyframe clip name must be a string`);let t=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Map,i=[],a=[];e.tracks.forEach((e,n)=>{let o=`Keyframe track ${n}`,s=e?.target;if(s!==null&&(typeof s==`object`||typeof s==`function`)){let t=e,n=O(t,o),i=t.set??t.property,c=r.get(s)??/* @__PURE__ */ new Set;if(c.has(i))throw TypeError(`${o} repeats property ${n.name}; merge the keys`);r.set(s,c.add(i)),a.push(n);return}if(typeof s!=`string`||!s)throw TypeError(`${o} needs a nonempty string target, or an object target with a property`);let{path:c,keys:l,blend:u}=e;if(c!==`translation`&&c!==`rotation`&&c!==`scale`&&c!==`weights`)throw TypeError(`${o} path ${c} is invalid; use translation, rotation, scale or weights`);if(u!==void 0&&u!==`delta`&&u!==`weighted`)throw TypeError(`${o} blend ${u} is invalid; use delta or weighted`);if(t.has(s+`:`+c))throw TypeError(`${o} repeats ${s} ${c}; merge the keys`);if(t.add(s+`:`+c),!Array.isArray(l)||!l.length)throw TypeError(`${o} needs a nonempty keys array`);let d=c===`rotation`?4:c===`weights`?Number(l[0]?.value?.length):3;if(!(Number.isInteger(d)&&d>0))throw TypeError(`${o} weights keys need one number per morph target; pass a nonempty array`);let f=b(o,l,d,c===`rotation`);i.push({target:s,path:c,...f,...u===void 0?{}:{blend:u}})});let o=Math.max(0,...[...i,...a].map(e=>e.times[e.times.length-1])),s=n(e.markers??[]);if(s.some(e=>e.time>o))throw RangeError(`Keyframe clip marker is past the last key; move it inside the clip or add a key there`);return{name:e.name??``,duration:o,tracks:i,properties:a,markers:s}}function A(e,t,n){if(typeof t!=`number`||!Number.isFinite(t))throw RangeError(`Keyframe sample time ${t} is invalid; pass finite seconds`);let{times:r,values:i}=e,a=`path`in e?e.path!==`rotation`:e.type!==`quaternion`,o=a?i.length/r.length:4,s=r.length-1;if(n!==void 0&&!(n instanceof Float64Array&&n.length>=o))throw TypeError(`Keyframe sample target must be a Float64Array of at least ${o} numbers`);n??=new Float64Array(o);let l=0;if(t>=r[s])l=s;else if(t>r[0])for(let e=s;l+1<e;){let n=l+e>>1;r[n]<=t?l=n:e=n}let u=l===s||t<=r[l]?0:y(e.interpolations[l],(t-r[l])/(r[l+1]-r[l])),d=l*o,f=Math.min(l+1,s)*o;if(u>0&&u<1&&e.interpolations[l]===`cubicSpline`){let t=r[l+1]-r[l],s=u,p=s*s,m=p*s,h=e.tangents,g=l*o*2+o,_=(l+1)*o*2;for(let e=0;e<o;e++)n[e]=(2*m-3*p+1)*i[d+e]+(m-2*p+s)*t*h[g+e]+(-2*m+3*p)*i[f+e]+(m-p)*t*h[_+e];return a?n:(n[0]||n[1]||n[2]||n[3]||n.set(i.subarray(d,d+4)),c(n,n))}if(e.blend===`weighted`){if(u===0||u===1)return n.set(i.subarray(u?f:d,(u?f:d)+o)),n;if(a){for(let e=0;e<o;e++){let t=i[d+e],r=i[f+e],a=(1-u)*t+u*r;n[e]=Number.isFinite(a)?a:a>0?Math.max(t,r):Math.min(t,r)}return n}}else if(a||u===0||u===1){for(let e=0;e<o;e++)n[e]=u===1?i[f+e]:i[d+e]+(i[f+e]-i[d+e])*u;return n}let p=0;for(let e=0;e<4;e++)p+=i[d+e]*i[f+e];let m=p<0?-1:1,h=Math.acos(Math.min(1,Math.abs(p))),g=Math.sin(h),_=g>1e-6?Math.sin((1-u)*h)/g:1-u,v=(g>1e-6?Math.sin(u*h)/g:u)*m;for(let e=0;e<4;e++)n[e]=i[d+e]*_+i[f+e]*v;return c(n,n)}var j=/* @__PURE__ */ new Float64Array(4),M=(e,t)=>{let n=new Float64Array(t);return{value:n,pose:{[e]:n}}},N={translation:M(`translation`,3),rotation:M(`rotation`,4),scale:M(`scale`,3)},P=/* @__PURE__ */ new WeakMap;function F(e,t){let n=e.tracks,r=P.get(n);r||P.set(n,r=/* @__PURE__ */ new WeakMap);let i=r.get(t);return(!i||i.length!==n.length)&&(i=Int32Array.from(n,e=>e.path===`weights`?-1:t.index(e.target)),r.set(t,i)),i}function I(e,t,n){let r=typeof t==`number`?void 0:t,i=typeof t==`number`?t:n;if(r!==void 0&&!(r instanceof p)&&(!r||typeof r.setMorph!=`function`||!Array.isArray(r.model?.nodes)))throw TypeError(`applyKeyframeClip needs a Skeleton or an Animation; pass a skeleton or Animation.attach(model)`);let a=e?.properties??[];for(let e=0;e<a.length;e++)a[e].write(A(a[e],i,j));if(r===void 0){if(typeof i!=`number`||!Number.isFinite(i))throw RangeError(`Keyframe clip time ${i} is invalid; pass finite seconds`);return}if(r instanceof p){let t=e.tracks,n=F(e,r);for(let e=0;e<t.length;e++){let a=n[e],o=t[e];if(a<0)continue;let s=N[o.path];A(o,i,s.value),r.setPose(a,s.pose)}return}let{nodes:o,primitives:s}=r.model,c=/* @__PURE__ */ new Map;for(let e=o.length-1;e>=0;e--)typeof o[e].name==`string`&&c.set(o[e].name,e);for(let t of e.tracks){let e=c.get(t.target)??-1;if(e<0)continue;let n=A(t,i),a=o[e];if(t.path===`weights`){let i=s.find(t=>t.nodeIndex===e)?.weights.length??0;if(i!==n.length)throw RangeError(`Keyframe track ${t.target} weights has ${n.length} values but the node has ${i} morph targets; key one weight per target`);for(let t=0;t<i;t++)r.setMorph(e,t,n[t])}else t.path===`translation`?a.setPosition(n):t.path===`scale`?a.setScale(n):a.setQuaternion(n)}}function L(e,t,{loop:n=!1,timeScale:r=1}={}){if(![e,t,r].every(Number.isFinite)||e<0||t<0)throw RangeError(`Segment time needs finite elapsed and duration >= 0 and a finite timeScale`);let i=e*Math.abs(r),a=n&&t>0?i%t:Math.min(i,t);return r<0?t-a:a}function R(e){let t=new Float32Array([e]);return new Uint32Array(t.buffer)[0]--,t[0]}var z=e=>{if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw RangeError(`Keyframe bake fps ${e} is invalid; pass frames per second > 0`)};function B(e,t){z(t);let{times:n,interpolations:r}=e,i=new Set(r.slice(0,-1)),a=i.size===0||i.size===1&&(i.has(`discrete`)||i.has(`linear`)),o=[],s=[],c=(t,n=t)=>{let r=Math.fround(t);return o.length&&r<=o[o.length-1]?!1:(o.push(r),s.push(...A(e,n)),!0)};for(let i=0;i<n.length;i++){if(!c(n[i]))throw RangeError(`Keyframe track ${`path`in e?e.target+` `+e.path:e.name} keys are closer than Float32 time precision; space keys further apart`);if(a||i===n.length-1||r[i]===`linear`)continue;let o=Math.fround(n[i+1]);if(r[i]===`discrete`)c(R(o),n[i]);else for(let e=Math.floor(n[i]*t)+1;e/t<n[i+1];e++)Math.fround(e/t)<o&&c(e/t,Math.fround(e/t))}if(`path`in e?e.path===`rotation`:e.type===`quaternion`){for(let e=4;e<s.length;e+=4)if(s[e]*s[e-4]+s[e+1]*s[e-3]+s[e+2]*s[e-2]+s[e+3]*s[e-1]<0)for(let t=0;t<4;t++)s[e+t]=-s[e+t]}return{interpolation:a&&i.has(`discrete`)?`STEP`:`LINEAR`,times:Float32Array.from(o),values:Float32Array.from(s)}}function V(e,t,n){if(z(t),typeof n!=`function`)throw TypeError(`Keyframe bake needs a resolve(target) function`);let r=[];for(let i of e.tracks){let e=n(i.target);e!==void 0&&r.push({node:e,path:i.path,...B(i,t)})}return{name:e.name,channels:r}}export{A as a,g as c,k as i,V as n,L as o,B as r,p as s,I as t};
|