@margoengine/animation 0.0.0-stage → 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 -0
- package/NOTICE +4 -0
- package/README.md +1172 -2
- package/dist/batch.d.ts +162 -0
- package/dist/clip-utils.d.ts +50 -0
- package/dist/clip-utils.js +1 -0
- package/dist/clone.d.ts +15 -0
- package/dist/cor.d.ts +52 -0
- package/dist/cor.js +17 -0
- package/dist/deform-readers-DmYAkvBK.js +1 -0
- package/dist/deform-readers.d.ts +5 -0
- package/dist/deformed-points.d.ts +87 -0
- package/dist/deformed-points.js +17 -0
- package/dist/discrete-tracks.d.ts +102 -0
- package/dist/discrete-tracks.js +1 -0
- package/dist/dqs.d.ts +42 -0
- package/dist/dqs.js +29 -0
- package/dist/errors-t1ewumJS.js +1 -0
- package/dist/geometry-cache.d.ts +208 -0
- package/dist/geometry-cache.js +4 -0
- package/dist/gltf-C2HVNxzB.js +1 -0
- package/dist/gltf.d.ts +63 -0
- package/dist/group.d.ts +97 -0
- package/dist/hdr-format-cmvLFubB.js +1 -0
- package/dist/index.d.ts +203 -0
- package/dist/index.js +1 -0
- package/dist/instanced-morph.d.ts +82 -0
- package/dist/instanced-morph.js +13 -0
- package/dist/instanced-skin.d.ts +82 -0
- package/dist/instanced-skin.js +43 -0
- package/dist/interactivity.d.ts +71 -0
- package/dist/interactivity.js +4 -0
- package/dist/key-cursor.d.ts +23 -0
- package/dist/keyframes-YpidiYS4.js +4 -0
- package/dist/keyframes.d.ts +204 -0
- package/dist/lod.d.ts +87 -0
- package/dist/lod.js +4 -0
- package/dist/material-animation.d.ts +29 -0
- package/dist/mixer.d.ts +226 -0
- package/dist/mixer.js +4 -0
- package/dist/morph-gpu.d.ts +94 -0
- package/dist/morph-gpu.js +50 -0
- package/dist/morph-table.d.ts +29 -0
- package/dist/playback.d.ts +94 -0
- package/dist/playback.js +4 -0
- package/dist/point-cache.d.ts +28 -0
- package/dist/point-cache.js +1 -0
- package/dist/pointer-DyWpFsQi.js +1 -0
- package/dist/pointer.d.ts +43 -0
- package/dist/pointer.js +1 -0
- package/dist/pose-source-MuCl8VDd.js +1 -0
- package/dist/pose.d.ts +12 -0
- package/dist/require-webgpu-Jrqt3Xy4.js +1 -0
- package/dist/retarget.d.ts +115 -0
- package/dist/rigid.d.ts +42 -0
- package/dist/sampling-DjDWYqt2.js +1 -0
- package/dist/sampling.d.ts +112 -0
- package/dist/sampling.js +1 -0
- package/dist/shader-DuGkHFKx.js +73 -0
- package/dist/shader.d.ts +62 -0
- package/dist/skeleton-utils.d.ts +2 -0
- package/dist/skeleton-utils.js +4 -0
- package/dist/skin.d.ts +163 -0
- package/dist/src-fuuIJ3rU.js +4 -0
- package/dist/vat-SpfL7y9U.js +53 -0
- package/dist/vat.d.ts +194 -0
- package/dist/vat.js +1 -0
- package/dist/vertex-map-BC_WH7ER.js +1 -0
- package/dist/weight-buffer.d.ts +1 -0
- package/package.json +139 -4
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { EngineKernel } from '@margoengine/core';
|
|
2
|
+
import type { Engine, EnginePlugin, FrameGraph } from '@margoengine/core/extension';
|
|
3
|
+
import type { PBRPrimitive } from '@margoengine/gltf/pbr';
|
|
4
|
+
import type { Animation } from './index.js';
|
|
5
|
+
/** Options for {@link MorphWeightPlayer}. */
|
|
6
|
+
export interface MorphWeightOptions {
|
|
7
|
+
/** Wrap time at the end of the clip. Default true; false holds the first and last keys. */
|
|
8
|
+
loop?: boolean;
|
|
9
|
+
}
|
|
10
|
+
/** One copy's place in the crowd, for {@link MorphWeightPlayer.add}. */
|
|
11
|
+
export interface MorphWeightMember {
|
|
12
|
+
/** Seconds added to the player's time, so copies do not move in step. Default 0. */
|
|
13
|
+
offset?: number;
|
|
14
|
+
/** This copy's rate multiplier, finite and >= 0. Default 1. */
|
|
15
|
+
speed?: number;
|
|
16
|
+
}
|
|
17
|
+
/** Weight tracks sampled per thread; the arithmetic is `sampleTrackInto`'s, term for term. */
|
|
18
|
+
export declare const morphWeightShader = "\nstruct Track {times:u32,keys:u32,values:u32,width:u32,mode:u32,pad0:u32,pad1:u32,pad2:u32}\nstruct Item {weight:u32,track:u32,component:u32,member:u32}\nstruct Params {time:f32,duration:f32,loops:u32,pad:u32}\n@group(0) @binding(0) var<uniform> p:Params;\n@group(0) @binding(1) var<storage,read> tracks:array<Track>;\n@group(0) @binding(2) var<storage,read> times:array<f32>;\n@group(0) @binding(3) var<storage,read> values:array<f32>;\n@group(0) @binding(4) var<storage,read> items:array<Item>;\n@group(0) @binding(5) var<storage,read> members:array<vec2f>;\n@group(0) @binding(6) var<storage,read_write> weights:array<f32>;\n@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id:vec3u,@builtin(num_workgroups) groups:vec3u) {\n let i=id.y*groups.x*64u+id.x;\n if(i>=arrayLength(&items)){return;}\n let item=items[i];let member=members[item.member];let track=tracks[item.track];\n var at=p.time*member.y+member.x;\n if(p.loops>0u&&p.duration>0.0) {\n\n at=at-floor(at/p.duration)*p.duration;\n if(at<0.0){at+=p.duration;}\n if(at>=p.duration){at-=p.duration;}\n } else {at=clamp(at,0.0,p.duration);}\n\n\n let last=max(track.keys,1u)-1u;var lo=0u;var hi=last;\n while(lo<hi) {\n let mid=lo+(hi-lo+1u)/2u;\n if(times[track.times+mid]<=at){lo=mid;}else{hi=mid-1u;}\n }\n let a=lo;let b=min(a+1u,last);\n let span=times[track.times+b]-times[track.times+a];\n var t=0.0;\n if(span>0.0){t=clamp((at-times[track.times+a])/span,0.0,1.0);}\n let w=track.width;let c=item.component;let cubic=track.mode==2u;\n let ai=track.values+(a*select(1u,3u,cubic)+select(0u,1u,cubic))*w+c;\n let bi=track.values+(b*select(1u,3u,cubic)+select(0u,1u,cubic))*w+c;\n var out=values[ai];\n if(track.mode!=0u&&a!=b) {\n if(cubic) {\n let t2=t*t;let t3=t2*t;\n out=(2.0*t3-3.0*t2+1.0)*values[ai]+(t3-2.0*t2+t)*span*values[track.values+(a*3u+2u)*w+c]\n +(-2.0*t3+3.0*t2)*values[bi]+(t3-t2)*span*values[track.values+b*3u*w+c];\n } else {out=values[ai]*(1.0-t)+values[bi]*t;}\n }\n weights[item.weight]=out;\n}\n";
|
|
19
|
+
/**
|
|
20
|
+
* Plays the morph weight tracks of one glTF clip on many copies of a model with no per-copy CPU work: the tracks upload
|
|
21
|
+
* once, and each frame one compute dispatch per deformation buffer page samples every copy's weights from the player's
|
|
22
|
+
* time and that copy's offset and speed. Only weights are driven: a copy's `Animation` keeps playing its own clip for
|
|
23
|
+
* the body, and weights the player drives are overwritten each frame, so `setMorph` on them has no effect. A
|
|
24
|
+
* synchronous raycast (`@margoengine/bvh`) hits a copy at the weights the player draws, sampled on the CPU on demand
|
|
25
|
+
* with the shader's arithmetic; `remove` writes the weights last drawn into the copy's `primitive.weights`.
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* ```ts
|
|
29
|
+
* const talk = MorphWeightPlayer.attach(stage.engine, 'Talk');
|
|
30
|
+
* for (const [i, animation] of faces.entries()) talk.add(animation, {offset: i * 0.13});
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
export declare class MorphWeightPlayer implements EnginePlugin {
|
|
34
|
+
readonly clip: string | number;
|
|
35
|
+
readonly name: string;
|
|
36
|
+
/** Seconds played; a copy samples `time * speed + offset`. */
|
|
37
|
+
time: number;
|
|
38
|
+
/** Rate multiplier for every copy, finite and >= 0. Default 1. */
|
|
39
|
+
speed: number;
|
|
40
|
+
playing: boolean;
|
|
41
|
+
/** Each copy's offset and speed, and the player time its weights were last drawn at (unset before a dispatch). */
|
|
42
|
+
private readonly members;
|
|
43
|
+
private sample;
|
|
44
|
+
private readonly loop;
|
|
45
|
+
private engine?;
|
|
46
|
+
private gpu?;
|
|
47
|
+
private dirty;
|
|
48
|
+
private disposed;
|
|
49
|
+
private readonly params;
|
|
50
|
+
private readonly paramFloats;
|
|
51
|
+
private readonly paramWords;
|
|
52
|
+
/** Same as `engine.use(new MorphWeightPlayer(...))`; returns the player. */
|
|
53
|
+
static attach(engine: EngineKernel, clip?: string | number, options?: MorphWeightOptions): MorphWeightPlayer;
|
|
54
|
+
/** `clip` is a name or index every added copy's model has. */
|
|
55
|
+
constructor(clip?: string | number, { loop }?: MorphWeightOptions);
|
|
56
|
+
/** Copies playing. */
|
|
57
|
+
get count(): number;
|
|
58
|
+
private tracksOf;
|
|
59
|
+
/** Adds a copy, or changes its offset and speed. Every copy must come from one asset: they share the tracks. */
|
|
60
|
+
add(animation: Animation, { offset, speed }?: MorphWeightMember): this;
|
|
61
|
+
/**
|
|
62
|
+
* Stops driving a copy. Its weights on the GPU stay at the last value the player wrote until something else writes
|
|
63
|
+
* them, and that value goes into the copy's `primitive.weights`, so they say what is drawn.
|
|
64
|
+
*/
|
|
65
|
+
remove(animation: Animation): boolean;
|
|
66
|
+
/** Gives a copy's weights back to its `primitive.weights`: the samples last drawn, if any were. */
|
|
67
|
+
private handBack;
|
|
68
|
+
/** The weights this player's dispatch writes this frame for `primitive` of a copy, into `out` (Animation's CPU pose). */
|
|
69
|
+
weightsInto(animation: Animation, primitive: PBRPrimitive, out: Float32Array): void;
|
|
70
|
+
/**
|
|
71
|
+
* `morphWeightShader` on the CPU at player time `time`: the copy's float32 time, wrapped as `time % duration` (the
|
|
72
|
+
* shader's corrected f32 wrap lands there), then every track of the primitive's node sampled by `sampleTrackInto`,
|
|
73
|
+
* whose arithmetic the shader repeats term for term. Weights no track drives keep their value in `out`.
|
|
74
|
+
*/
|
|
75
|
+
private sampleInto;
|
|
76
|
+
setup(engine: Engine): void;
|
|
77
|
+
onPreUpdate(delta: number): void;
|
|
78
|
+
/** Moves `time` by `delta` seconds times `speed` when playing; the weights pass samples it, so a seek replays it. */
|
|
79
|
+
advanceTime(delta: number): void;
|
|
80
|
+
registerPasses(graph: FrameGraph): void;
|
|
81
|
+
/** The live copies, in order; a disposed copy leaves by itself. */
|
|
82
|
+
private live;
|
|
83
|
+
private upload;
|
|
84
|
+
/** Uploads the tracks once per device and asset. */
|
|
85
|
+
private prepare;
|
|
86
|
+
private dropPages;
|
|
87
|
+
/** One item per copy, primitive and target, grouped by the buffer page the weights live in. */
|
|
88
|
+
private build;
|
|
89
|
+
private evaluate;
|
|
90
|
+
private release;
|
|
91
|
+
onDeviceRestored(): void;
|
|
92
|
+
dispose(): void;
|
|
93
|
+
[Symbol.dispose]: () => void;
|
|
94
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// @margo/core-built 1.0.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
|
|
4
|
+
import{o as e}from"./sampling-DjDWYqt2.js";import{t}from"./require-webgpu-Jrqt3Xy4.js";import{MargoError as n}from"@margoengine/math/errors";var r=`
|
|
5
|
+
struct Track {times:u32,keys:u32,values:u32,width:u32,mode:u32,pad0:u32,pad1:u32,pad2:u32}
|
|
6
|
+
struct Item {weight:u32,track:u32,component:u32,member:u32}
|
|
7
|
+
struct Params {time:f32,duration:f32,loops:u32,pad:u32}
|
|
8
|
+
@group(0) @binding(0) var<uniform> p:Params;
|
|
9
|
+
@group(0) @binding(1) var<storage,read> tracks:array<Track>;
|
|
10
|
+
@group(0) @binding(2) var<storage,read> times:array<f32>;
|
|
11
|
+
@group(0) @binding(3) var<storage,read> values:array<f32>;
|
|
12
|
+
@group(0) @binding(4) var<storage,read> items:array<Item>;
|
|
13
|
+
@group(0) @binding(5) var<storage,read> members:array<vec2f>;
|
|
14
|
+
@group(0) @binding(6) var<storage,read_write> weights:array<f32>;
|
|
15
|
+
@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id:vec3u,@builtin(num_workgroups) groups:vec3u) {
|
|
16
|
+
let i=id.y*groups.x*64u+id.x;
|
|
17
|
+
if(i>=arrayLength(&items)){return;}
|
|
18
|
+
let item=items[i];let member=members[item.member];let track=tracks[item.track];
|
|
19
|
+
var at=p.time*member.y+member.x;
|
|
20
|
+
if(p.loops>0u&&p.duration>0.0) {
|
|
21
|
+
|
|
22
|
+
at=at-floor(at/p.duration)*p.duration;
|
|
23
|
+
if(at<0.0){at+=p.duration;}
|
|
24
|
+
if(at>=p.duration){at-=p.duration;}
|
|
25
|
+
} else {at=clamp(at,0.0,p.duration);}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
let last=max(track.keys,1u)-1u;var lo=0u;var hi=last;
|
|
29
|
+
while(lo<hi) {
|
|
30
|
+
let mid=lo+(hi-lo+1u)/2u;
|
|
31
|
+
if(times[track.times+mid]<=at){lo=mid;}else{hi=mid-1u;}
|
|
32
|
+
}
|
|
33
|
+
let a=lo;let b=min(a+1u,last);
|
|
34
|
+
let span=times[track.times+b]-times[track.times+a];
|
|
35
|
+
var t=0.0;
|
|
36
|
+
if(span>0.0){t=clamp((at-times[track.times+a])/span,0.0,1.0);}
|
|
37
|
+
let w=track.width;let c=item.component;let cubic=track.mode==2u;
|
|
38
|
+
let ai=track.values+(a*select(1u,3u,cubic)+select(0u,1u,cubic))*w+c;
|
|
39
|
+
let bi=track.values+(b*select(1u,3u,cubic)+select(0u,1u,cubic))*w+c;
|
|
40
|
+
var out=values[ai];
|
|
41
|
+
if(track.mode!=0u&&a!=b) {
|
|
42
|
+
if(cubic) {
|
|
43
|
+
let t2=t*t;let t3=t2*t;
|
|
44
|
+
out=(2.0*t3-3.0*t2+1.0)*values[ai]+(t3-2.0*t2+t)*span*values[track.values+(a*3u+2u)*w+c]
|
|
45
|
+
+(-2.0*t3+3.0*t2)*values[bi]+(t3-t2)*span*values[track.values+b*3u*w+c];
|
|
46
|
+
} else {out=values[ai]*(1.0-t)+values[bi]*t;}
|
|
47
|
+
}
|
|
48
|
+
weights[item.weight]=out;
|
|
49
|
+
}
|
|
50
|
+
`,i={STEP:0,LINEAR:1,CUBICSPLINE:2},a=8,o=0,s=class s{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static attach(e,t=0,n){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));let r=new s(t,n);return e.use(r),r}constructor(e=0,{loop:t=!0}={}){if(this.clip=e,this.name=`morph-gpu:`+o++,this.time=0,this.speed=1,this.playing=!0,this.members=/* @__PURE__ */ new Map,this.sample=/* @__PURE__ */ new Float32Array,this.dirty=!0,this.disposed=!1,this.params=/* @__PURE__ */ new ArrayBuffer(16),this.paramFloats=new Float32Array(this.params),this.paramWords=new Uint32Array(this.params),typeof t!=`boolean`)throw TypeError(`MorphWeightPlayer loop must be a boolean`);if(typeof e!=`string`&&!(Number.isInteger(e)&&e>=0))throw RangeError(`MorphWeightPlayer clip must be a clip name or an index from animation.clips`);this.loop=t}get count(){return this.members.size}tracksOf(e){let t=e.clips,n=t[typeof this.clip==`string`?t.findIndex(e=>e.name===this.clip):this.clip];if(!n)throw RangeError(`Unknown animation clip; pass a clip name or an index from animation.clips`);let r=n.tracks.filter(e=>e.path===`weights`);if(!r.length)throw RangeError(`Clip ${n.name} has no morph weight tracks; pick a clip that has them`);return{duration:n.duration,tracks:r}}add(e,{offset:t=0,speed:r=1}={}){if(this.disposed)throw new n(`disposed`,`MorphWeightPlayer is disposed; create a new one`);if(!Number.isFinite(t)||!Number.isFinite(r)||r<0)throw RangeError(`Invalid morph member; offset must be finite and speed a finite number >= 0`);let i=this.members.keys().next().value;if(i&&i!==e&&i.model.asset!==e.model.asset)throw TypeError(`MorphWeightPlayer copies must share one asset; clone them with cloneModel`);return this.tracksOf(e),e.weightSource=this,this.members.set(e,{offset:t,speed:r,drawn:this.members.get(e)?.drawn}),this.dirty=!0,this}remove(e){let t=this.members.get(e);return t?(this.handBack(e,t),this.members.delete(e),this.dirty=!0,!0):!1}handBack(e,t){if(t.drawn!==void 0)for(let n of e.resources)this.sampleInto(e,t,n.primitive,n.primitive.weights,t.drawn);e.weightSource===this&&(e.weightSource=void 0)}weightsInto(e,t,n){let r=this.members.get(e);r&&this.sampleInto(e,r,t,n,this.time)}sampleInto(t,n,r,i,a){let{duration:o,tracks:s}=this.tracksOf(t),c=Math.fround,l=c(o),u=c(c(c(a)*c(n.speed))+c(n.offset)),d=this.loop&&l>0?(u%l+l)%l:Math.min(Math.max(u,0),l);for(let t of s)t.node===r.nodeIndex&&(this.sample.length!==t.width&&(this.sample=new Float32Array(t.width)),e(t.times,t.values,t.width,d,t.interpolation,!1,this.sample),i.set(this.sample.subarray(0,Math.min(t.width,i.length))))}setup(e){if(this.disposed)throw new n(`disposed`,`MorphWeightPlayer is disposed; create a new player before attaching`);t(e,`MorphWeightPlayer`),this.engine=e}onPreUpdate(e){this.advanceTime(e)}advanceTime(e){if(!Number.isFinite(e)||e<0)throw RangeError(`Invalid animation delta; pass a finite delta >= 0 seconds`);if(!Number.isFinite(this.speed)||this.speed<0)throw RangeError(`Invalid morph player speed; use a finite number >= 0`);this.playing&&!this.disposed&&(this.time+=e*this.speed)}registerPasses(e){e.add({name:this.name,order:-11,execute:e=>this.evaluate(e)})}live(){for(let e of this.members.keys())(e.disposed||e.model.disposed)&&(this.members.delete(e),this.dirty=!0);return[...this.members.keys()]}upload(e,t){let n=e.createBuffer({size:Math.max(16,Math.ceil(t.byteLength/4)*4),usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});return e.queue.writeBuffer(n,0,t),n}prepare(e,t){let{tracks:n}=this.tracksOf(t),o=new Uint32Array(n.length*a),s=0,c=0;n.forEach((e,t)=>{o.set([s,e.times.length,c,e.width,i[e.interpolation]],t*a),s+=e.times.length,c+=e.values.length});let l=new Float32Array(s),u=new Float32Array(c);return n.forEach((e,t)=>{l.set(e.times,o[t*a]),u.set(e.values,o[t*a+2])}),{device:e,pipeline:e.createComputePipeline({layout:`auto`,compute:{module:e.createShaderModule({code:r}),entryPoint:`main`}}),params:e.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),tracks:this.upload(e,o),times:this.upload(e,l),values:this.upload(e,u),pages:[],version:-1}}dropPages(e){for(let t of e.pages)t.items.destroy();e.pages=[],e.members?.destroy(),e.members=void 0}build(e,t,n){this.dropPages(e);let{tracks:r}=this.tracksOf(t[0]),i=/* @__PURE__ */ new Map,a=new Float32Array(t.length*2);t.forEach((e,t)=>{let n=this.members.get(e);a[t*2]=n.offset,a[t*2+1]=n.speed;for(let n of e.resources){let e=n.weights,a=i.get(e)??[];i.set(e,a),r.forEach((e,r)=>{if(e.node===n.primitive.nodeIndex)for(let i=0;i<e.width;i++)a.push(n.slot.weights.offset+i,r,i,t)})}}),e.members=this.upload(e.device,a);let o=e.device.limits.maxComputeWorkgroupsPerDimension??65535;for(let[t,n]of i){if(!n.length)continue;let r=this.upload(e.device,Uint32Array.from(n)),i=Math.ceil(n.length/4/64),a=Math.min(i,o);e.pages.push({items:r,x:a,y:Math.ceil(i/a),group:e.device.createBindGroup({layout:e.pipeline.getBindGroupLayout(0),entries:[e.params,e.tracks,e.times,e.values,r,e.members,t].map((e,t)=>({binding:t,resource:{buffer:e}}))})})}e.version=n,this.dirty=!1}evaluate(e){if(e.backend!==`webgpu`)return;let t=this.live(),n=t[0]?.arena;if(!n)return;this.gpu&&this.gpu.device!==e.device&&this.release();let r=this.gpu??=this.prepare(e.device,t[0]);if((this.dirty||r.version!==n.version)&&this.build(r,t,n.version),!r.pages.length)return;this.paramFloats[0]=this.time,this.paramFloats[1]=this.tracksOf(t[0]).duration,this.paramWords[2]=+this.loop,e.device.queue.writeBuffer(r.params,0,this.params);let i=e.encoder.beginComputePass();try{i.setPipeline(r.pipeline);for(let e of r.pages)i.setBindGroup(0,e.group),i.dispatchWorkgroups(e.x,e.y)}finally{i.end()}for(let e of this.members.values())e.drawn=this.time}release(){let e=this.gpu;if(e){this.dropPages(e);for(let t of[e.params,e.tracks,e.times,e.values])t.destroy();this.gpu=void 0,this.dirty=!0}}onDeviceRestored(){this.gpu=void 0,this.dirty=!0}dispose(){if(!this.disposed){this.disposed=!0,this.engine?.sceneOf(this)?.removePlugin(this.name),this.release();for(let[e,t]of this.members)this.handBack(e,t);this.members.clear()}}[Symbol.dispose??Symbol()](){this.dispose()}};export{s as MorphWeightPlayer,r as morphWeightShader};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** One morph attribute's moved rows (ascending file vertices) and their deltas, three floats each. */
|
|
2
|
+
export interface MorphRows {
|
|
3
|
+
readonly rows: Uint32Array;
|
|
4
|
+
readonly values: Float32Array;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* The table, in the 32-bit words the deformation shader reads. Words 0 to `count` are each vertex's first entry, then
|
|
8
|
+
* the end (row pointers); the entries start at word `header`, a multiple of 4. An entry is `stride` words: the
|
|
9
|
+
* position delta and the target's index (bits, word 3), the normal delta and a zero, and with `stride` 12 the tangent
|
|
10
|
+
* delta and a zero. Float words are Float32 bits.
|
|
11
|
+
*/
|
|
12
|
+
export interface MorphTable {
|
|
13
|
+
readonly count: number;
|
|
14
|
+
readonly targets: number;
|
|
15
|
+
/** Words per entry: 8 (position and normal) or 12 (with the tangent). */
|
|
16
|
+
readonly stride: 8 | 12;
|
|
17
|
+
readonly header: number;
|
|
18
|
+
readonly words: Uint32Array;
|
|
19
|
+
/** `words` read as floats. */
|
|
20
|
+
readonly floats: Float32Array;
|
|
21
|
+
}
|
|
22
|
+
/** Words before the entries: one row pointer per vertex and the end, rounded up to a vec4. */
|
|
23
|
+
export declare const morphHeader: (count: number) => number;
|
|
24
|
+
/**
|
|
25
|
+
* Builds the table of `count` vertices from each target's attributes (position, normal, tangent; undefined where the
|
|
26
|
+
* target has none) as `@margoengine/gltf` `sparseAccessor` reads them, rows in the file's vertices. With `vertexMap`
|
|
27
|
+
* (a part of a split primitive) vertex k of the table is the file's vertex `vertexMap[k]`.
|
|
28
|
+
*/
|
|
29
|
+
export declare function morphTable(attributes: readonly (readonly (MorphRows | undefined)[])[], count: number, sourceCount: number, stride: 8 | 12, vertexMap?: Uint32Array): MorphTable;
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/// <reference lib="esnext.disposable" preserve="true" />
|
|
2
|
+
import { Animation as BaseAnimation, type AnimationOptions } from '@margoengine/animation';
|
|
3
|
+
import type { PBRModel } from '@margoengine/gltf/pbr';
|
|
4
|
+
import { type ActionLoop } from './mixer.js';
|
|
5
|
+
export { LoopOnce, LoopRepeat, LoopPingPong } from './mixer.js';
|
|
6
|
+
/** Optional plain-player event and iteration controls. */
|
|
7
|
+
export interface PlaybackOptions extends AnimationOptions {
|
|
8
|
+
/** Default LoopRepeat, or LoopOnce when loop=false. */
|
|
9
|
+
loopMode?: ActionLoop;
|
|
10
|
+
/** Total traversals, positive integer or Infinity. Default Infinity; LoopOnce always uses one. */
|
|
11
|
+
repetitions?: number;
|
|
12
|
+
/** Signed multiplier on speed. Default 1. */
|
|
13
|
+
timeScale?: number;
|
|
14
|
+
/** Abort disposes this player and rejects its pending finished promise. */
|
|
15
|
+
signal?: AbortSignal;
|
|
16
|
+
}
|
|
17
|
+
/** Loop or completion notification, delivered after the sampled pose is applied. */
|
|
18
|
+
export declare class PlaybackEvent extends Event {
|
|
19
|
+
readonly animation: PlaybackAnimation;
|
|
20
|
+
readonly loopDelta: number;
|
|
21
|
+
readonly direction: 1 | -1;
|
|
22
|
+
/** @internal Constructed by PlaybackAnimation. */
|
|
23
|
+
constructor(type: 'loop' | 'finished', animation: PlaybackAnimation, loopDelta: number, direction: 1 | -1);
|
|
24
|
+
}
|
|
25
|
+
/** Event payloads for on/addEventListener. */
|
|
26
|
+
export interface PlaybackEventMap {
|
|
27
|
+
loop: PlaybackEvent;
|
|
28
|
+
finished: PlaybackEvent;
|
|
29
|
+
}
|
|
30
|
+
/** Plain Animation playback with repeat counts, ping-pong, events and an abortable completion promise. */
|
|
31
|
+
export declare class PlaybackAnimation extends BaseAnimation {
|
|
32
|
+
/** Directed looping. Default LoopRepeat (LoopOnce when constructed with loop=false). */
|
|
33
|
+
loopMode: ActionLoop;
|
|
34
|
+
/** Total traversals. Default Infinity. */
|
|
35
|
+
repetitions: number;
|
|
36
|
+
/** Signed multiplier on Animation.options.speed. Default 1. */
|
|
37
|
+
timeScale: number;
|
|
38
|
+
private cursor;
|
|
39
|
+
private completed;
|
|
40
|
+
private settled;
|
|
41
|
+
private started;
|
|
42
|
+
private terminal;
|
|
43
|
+
private released;
|
|
44
|
+
private readonly events;
|
|
45
|
+
private promise;
|
|
46
|
+
private resolve;
|
|
47
|
+
private reject;
|
|
48
|
+
private signal?;
|
|
49
|
+
private readonly abort;
|
|
50
|
+
/** Construct like Animation, adding loopMode, repetitions, timeScale and signal. */
|
|
51
|
+
constructor(model: PBRModel, options?: PlaybackOptions);
|
|
52
|
+
/** Create and register in the model's scene; an already-aborted signal never registers. */
|
|
53
|
+
static attach(model: PBRModel, options?: PlaybackOptions): PlaybackAnimation;
|
|
54
|
+
/** Current run's completion, renewed by play; rejects with AbortError on replacement/disposal. */
|
|
55
|
+
get finished(): Promise<PlaybackEvent>;
|
|
56
|
+
private newPromise;
|
|
57
|
+
private validatePlayback;
|
|
58
|
+
/** Start a clip from its beginning (negative rates start at its end); renew completion on a replacement run. */
|
|
59
|
+
play(clip?: string | number): this;
|
|
60
|
+
/** Choose a loop mode and total traversal count, without restarting the run. */
|
|
61
|
+
setLoop(mode: ActionLoop, repetitions?: number): this;
|
|
62
|
+
/** Seek total clip seconds without emitting playback events; restarts traversal counting. */
|
|
63
|
+
seek(time: number): this;
|
|
64
|
+
private mode;
|
|
65
|
+
private pose;
|
|
66
|
+
/** Advance plain playback before world-matrix/deformation updates. */
|
|
67
|
+
onPreUpdate(delta: number): void;
|
|
68
|
+
/**
|
|
69
|
+
* Moves the playback cursor by `delta` seconds times `speed` and `timeScale`, counting loops and the end of the run:
|
|
70
|
+
* the CPU part of the frame update, which a seek from `@margoengine/cutscene/seek` replays. It poses nothing and
|
|
71
|
+
* sends no `loop` or `finished` event (a replayed end still settles `finished`); the next update poses the place
|
|
72
|
+
* reached.
|
|
73
|
+
*/
|
|
74
|
+
advanceTime(delta: number): void;
|
|
75
|
+
/** The pose a step owes the next update: cursor, direction, at an endpoint. */
|
|
76
|
+
private owed?;
|
|
77
|
+
/** One step of the cursor: loops crossed, direction and, at the end of the run, its `finished` event. */
|
|
78
|
+
private stepClock;
|
|
79
|
+
/** Subscribe with optional AbortSignal; returns an unsubscribe function. */
|
|
80
|
+
on<K extends keyof PlaybackEventMap>(type: K, listener: (event: PlaybackEventMap[K]) => void, options?: {
|
|
81
|
+
signal?: AbortSignal;
|
|
82
|
+
}): () => void;
|
|
83
|
+
/** Familiar EventTarget listener API. */
|
|
84
|
+
addEventListener(type: 'loop' | 'finished', listener: (event: PlaybackEvent) => void, options?: AddEventListenerOptions | boolean): void;
|
|
85
|
+
/** Remove a previously added listener. */
|
|
86
|
+
removeEventListener(type: 'loop' | 'finished', listener: (event: PlaybackEvent) => void, options?: EventListenerOptions | boolean): void;
|
|
87
|
+
/** Await this run with independent cancellation, without stopping playback. */
|
|
88
|
+
waitForFinished({ signal }?: {
|
|
89
|
+
signal?: AbortSignal;
|
|
90
|
+
}): Promise<PlaybackEvent>;
|
|
91
|
+
/** Reject pending completion, remove abort subscription and release Animation resources. Idempotent. */
|
|
92
|
+
dispose(): void;
|
|
93
|
+
}
|
|
94
|
+
export { PlaybackAnimation as Animation };
|
package/dist/playback.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @margo/core-built 1.0.0
|
|
2
|
+
import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
|
|
3
|
+
|
|
4
|
+
import{n as e}from"./errors-t1ewumJS.js";import{LoopOnce as t,LoopPingPong as n,LoopRepeat as r}from"./mixer.js";import{Animation as i}from"@margoengine/animation";var a=class extends Event{constructor(e,t,n,r){super(e),this.animation=t,this.loopDelta=n,this.direction=r}},o=t=>Object.assign(e(t,`arguments`),{code:`arguments`}),s=(e,t)=>{if(!Number.isFinite(e))throw o(`Invalid playback ${t}; pass finite seconds or a rate`);return e},c=()=>new DOMException(`Animation playback cancelled; start another play or wait on a live player`,`AbortError`),l=class e extends i{constructor(e,t={}){super(e,t),this.cursor=0,this.completed=0,this.settled=!1,this.started=!1,this.terminal=!1,this.released=!1,this.events=new EventTarget,this.abort=()=>this.dispose(),this.loopMode=t.loopMode??(t.loop===!1?2200:2201),this.repetitions=t.repetitions??1/0,this.timeScale=t.timeScale??1,this.validatePlayback(),this.newPromise(),this.signal=t.signal,t.signal?.addEventListener(`abort`,this.abort,{once:!0}),t.signal?.aborted&&this.dispose()}static attach(t,n={}){__margoAssertCore(t,__margoCoreRequirement("1.0.0",import.meta.url));let r=new e(t,n);if(!n.signal?.aborted)try{t.root.scene.use(r)}catch(e){throw r.dispose(),e}return r}get finished(){return this.promise}newPromise(){this.settled=!1,this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t}),this.promise.catch(()=>{})}validatePlayback(){if(![2200,2201,2202].includes(this.loopMode)||this.repetitions!==1/0&&(!Number.isSafeInteger(this.repetitions)||this.repetitions<1))throw o(`Invalid playback loop; choose a loop mode and a positive integer traversal count or Infinity`);s(this.timeScale,`timeScale`)}play(e=0){return super.play(e),this.started&&(this.settled||this.reject(c()),this.newPromise()),this.started=!0,this.completed=0,this.terminal=!1,this.cursor=this.timeScale<0?this.clips[this.clip].duration:0,this.pose(this.cursor,1,this.timeScale<0),this}setLoop(e,n=1/0){let r=this.loopMode,i=this.repetitions;this.loopMode=e,this.repetitions=n;try{this.validatePlayback()}catch(e){throw this.loopMode=r,this.repetitions=i,e}return this.options.loop=e!==t,this}seek(e){if(s(e,`seek`)<0)throw o(`Playback seek must be nonnegative; pass total clip seconds >= 0`);return this.cursor=e,this.completed=0,this.terminal=!1,this.pose(e,this.timeScale<0?-1:1,!1),this}mode(){return this.loopMode===2201&&this.options.loop===!1?t:this.loopMode}pose(e,t,n){let r=this.clips[this.clip]?.duration??0,i=this.mode(),a=0;if(r>0){if(i===2200)a=Math.max(0,Math.min(r,e));else if(i===2202){let t=2*r,n=(e%t+t)%t;a=n<=r?n:t-n}else a=n?t>0?r:0:(e%r+r)%r}let o=this.options.loop;this.options.loop=!1;try{super.seek(a)}finally{this.options.loop=o}}onPreUpdate(e){if(this.model.disposed){this.dispose();return}this.validatePlayback();let t=this.playing;this.playing=!1;try{super.onPreUpdate(0)}finally{this.playing=t}let n=this.stepClock(e),r=this.owed;if(r&&(this.owed=void 0,this.pose(r[0],r[1],r[2])),!n)return;let[i,o,s]=n;s?this.events.dispatchEvent(s):i&&this.events.dispatchEvent(new a(`loop`,this,i*o,o))}advanceTime(e){this.validatePlayback(),this.stepClock(e)}stepClock(e){if(!this.playing||this.terminal||this.disposed)return;if(s(e,`delta`),e<0)throw o(`Playback delta must be nonnegative; reverse with timeScale`);let t=s(e*(this.options.speed??1)*this.timeScale,`advance`);if(t===0&&(this.clips[this.clip]?.duration??0)>0)return;let n=this.clips[this.clip]?.duration??0,r=t<0?-1:1,i=this.mode(),c=s(this.cursor+t,`clock`),l=0,u=!1;if(n===0)c=0,u=!0;else if(i===2200)u=r>0?c>=n:c<=0,c=Math.max(0,Math.min(n,c));else{if(l=r>0?Math.floor(c/n)-Math.floor(this.cursor/n):Math.ceil(this.cursor/n)-Math.ceil(c/n),!Number.isSafeInteger(l))throw o(`Playback crossed too many loops to count exactly; use a smaller delta or rate`);let e=this.repetitions-this.completed;l>=e&&(c=(r>0?Math.floor(this.cursor/n)+e:Math.ceil(this.cursor/n)-e)*n,l=e,u=!0)}if(this.started=!0,this.cursor=c,this.completed+=l,this.owed=[c,r,u],!u)return[l,r,void 0];this.terminal=!0,this.playing=!1,this.settled=!0;let d=new a(`finished`,this,0,r);return this.resolve(d),[l,r,d]}on(e,t,n={}){return this.events.addEventListener(e,t,n),()=>this.events.removeEventListener(e,t)}addEventListener(e,t,n){this.events.addEventListener(e,t,n)}removeEventListener(e,t,n){this.events.removeEventListener(e,t,n)}waitForFinished({signal:e}={}){return e?e.aborted?Promise.reject(e.reason??c()):new Promise((t,n)=>{let r=()=>{e.removeEventListener(`abort`,r),n(e.reason??c())};e.addEventListener(`abort`,r,{once:!0}),this.finished.then(n=>{e.removeEventListener(`abort`,r),t(n)},t=>{e.removeEventListener(`abort`,r),n(t)})}):this.finished}dispose(){this.released||(this.released=!0,this.playing=!1,this.signal?.removeEventListener(`abort`,this.abort),this.signal=void 0,this.settled||(this.settled=!0,this.reject(c())),super.dispose())}};export{l as Animation,l as PlaybackAnimation,t as LoopOnce,n as LoopPingPong,r as LoopRepeat,a as PlaybackEvent};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** Options of {@link parsePointCache}. */
|
|
2
|
+
export interface PointCacheOptions {
|
|
3
|
+
/** Frames per second for a PC2 file, which does not say. Default 24. An MDD file's own times win. */
|
|
4
|
+
fps?: number;
|
|
5
|
+
/** Turn a Z-up file to Y-up, as `(x, z, -y)`. Default false: the file's axes as written. */
|
|
6
|
+
zUp?: boolean;
|
|
7
|
+
/** Refuses a file holding more floats than this. Default 1 GiB of them. */
|
|
8
|
+
maxFloats?: number;
|
|
9
|
+
}
|
|
10
|
+
/** A point cache read whole. `frameCount` and `positions` fit a chunk of `encodeGeometryCache`. */
|
|
11
|
+
export interface PointCache {
|
|
12
|
+
format: 'pc2' | 'mdd';
|
|
13
|
+
/** Frames per second. */
|
|
14
|
+
rate: number;
|
|
15
|
+
frameCount: number;
|
|
16
|
+
vertexCount: number;
|
|
17
|
+
/** Seconds of each frame: the file's for MDD, from its start frame and `fps` for PC2. */
|
|
18
|
+
times: Float32Array;
|
|
19
|
+
/** `frameCount` frames of `vertexCount` vertices, three floats each. */
|
|
20
|
+
positions: Float32Array;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Reads a PC2 (Point Cache 2, little endian) or MDD (big endian) file. To play one, give it the triangles of its mesh:
|
|
24
|
+
* `encodeGeometryCache(cache.rate, [{ frameCount: cache.frameCount, positions: cache.positions, indices }])`.
|
|
25
|
+
*
|
|
26
|
+
* @throws MargoError code `failed` for a cut or empty file or one over `maxFloats`, `unsupported` for another PC2 version.
|
|
27
|
+
*/
|
|
28
|
+
export declare function parsePointCache(bytes: Uint8Array, options?: PointCacheOptions): PointCache;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{MargoError as e}from"@margoengine/math/errors";var t=`POINTCACHE2\0`,n=32,r=8,i=t=>new e(`failed`,`Point cache ${t}; export the file again`);function a(e,t,n,r){let i=new Float32Array(n);for(let a=0;a<n;a++)i[a]=e.getFloat32(t+a*4,r);return i}function o(t,n,r,a){if(!Number.isInteger(t)||!Number.isInteger(n)||t<1||n<1)throw i(`has no frames or no vertices`);let o=t*n*3;if(o*4>a)throw i(`is cut off or is not a PC2 or MDD file: its header asks for ${t} frames of ${n} vertices, more than it holds`);if(o>r)throw new e(`failed`,`Point cache holds ${o} floats, over maxFloats ${r}; raise maxFloats or export fewer frames`);return o}function s(t,r,s){if(t.byteLength<n)throw i(`stops inside its header`);let c=t.getInt32(12,!0),l=t.getInt32(16,!0),u=t.getFloat32(20,!0),d=t.getFloat32(24,!0),f=t.getInt32(28,!0);if(c!==1)throw new e(`unsupported`,`PC2 version ${c} is not read; export version 1`);let p=o(f,l,s,t.byteLength-n);if(!(d>0))throw i(`has a sample rate of 0 or less`);let m=new Float32Array(f);for(let e=0;e<f;e++)m[e]=(u+e*d)/r;return{format:`pc2`,rate:r/d,frameCount:f,vertexCount:l,times:m,positions:a(t,n,p,!0)}}function c(e,t,n){if(e.byteLength<r)throw i(`stops inside its header`);let s=e.getInt32(0,!1),c=e.getInt32(4,!1),l=r+s*4,u=o(s,c,n,e.byteLength-l),d=a(e,r,s,!1),f=d[s-1]-d[0];for(let e=1;e<s;e++)if(!(d[e]>d[e-1]))throw i(`has times that do not rise`);return{format:`mdd`,rate:f>0?(s-1)/f:t,frameCount:s,vertexCount:c,times:d,positions:a(e,l,u,!1)}}function l(e,n={}){let{fps:r=24,zUp:i=!1,maxFloats:a=2**28}=n;if(!(r>0&&Number.isFinite(r)))throw RangeError(`Invalid fps; pass a frame rate above 0`);let o=new DataView(e.buffer,e.byteOffset,e.byteLength),l=String.fromCharCode(...e.subarray(0,12))===t?s(o,r,a):c(o,r,a);if(i){let e=l.positions;for(let t=0;t<e.length;t+=3){let n=e[t+1];e[t+1]=e[t+2],e[t+2]=-n}}return l}export{l as parsePointCache};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as e}from"./keyframes-YpidiYS4.js";import{a as t,l as n,o as r}from"./gltf-C2HVNxzB.js";import{textureCoordinates as i,textureTransform as a}from"@margoengine/gltf/pbr-model";function o(e,t){return e===1?1:e**t}var s={SCALAR:1,VEC2:2,VEC3:3,VEC4:4},c=e=>e&&typeof e==`object`&&!Array.isArray(e)?e:void 0,l=e=>Array.isArray(e)?e:[],u=(e,t)=>t.split(`/`).reduce((e,t)=>c(e)?.[t],e),d={"pbrMetallicRoughness/baseColorTexture":0,"pbrMetallicRoughness/metallicRoughnessTexture":1,normalTexture:2,occlusionTexture:3,emissiveTexture:4,"extensions/KHR_materials_clearcoat/clearcoatTexture":5,"extensions/KHR_materials_clearcoat/clearcoatRoughnessTexture":6,"extensions/KHR_materials_clearcoat/clearcoatNormalTexture":7,"extensions/KHR_materials_transmission/transmissionTexture":8,"extensions/KHR_materials_sheen/sheenColorTexture":9,"extensions/KHR_materials_sheen/sheenRoughnessTexture":10,"extensions/KHR_materials_specular/specularTexture":11,"extensions/KHR_materials_specular/specularColorTexture":12},f={"pbrMetallicRoughness/baseColorFactor":[`VEC4`,`base`,0],"pbrMetallicRoughness/roughnessFactor":[`SCALAR`,`factors`,0],"pbrMetallicRoughness/metallicFactor":[`SCALAR`,`factors`,1],"normalTexture/scale":[`SCALAR`,`factors`,2,`normalTexture`],"occlusionTexture/strength":[`SCALAR`,`factors`,3,`occlusionTexture`],emissiveFactor:[`VEC3`,`emissive`,0],alphaCutoff:[`SCALAR`,`settings`,1],"extensions/KHR_materials_emissive_strength/emissiveStrength":[`SCALAR`,`strength`,0,`extensions/KHR_materials_emissive_strength`],"extensions/KHR_materials_dispersion/dispersion":[`SCALAR`,`dispersion`,0,`extensions/KHR_materials_dispersion`],"extensions/KHR_materials_clearcoat/clearcoatFactor":[`SCALAR`,`physical`,0],"extensions/KHR_materials_clearcoat/clearcoatRoughnessFactor":[`SCALAR`,`physical`,1],"extensions/KHR_materials_clearcoat/clearcoatNormalTexture/scale":[`SCALAR`,`physical`,2,`extensions/KHR_materials_clearcoat/clearcoatNormalTexture`],"extensions/KHR_materials_transmission/transmissionFactor":[`SCALAR`,`physical`,3],"extensions/KHR_materials_specular/specularColorFactor":[`VEC3`,`physical`,4],"extensions/KHR_materials_specular/specularFactor":[`SCALAR`,`physical`,7],"extensions/KHR_materials_sheen/sheenColorFactor":[`VEC3`,`physical`,8],"extensions/KHR_materials_sheen/sheenRoughnessFactor":[`SCALAR`,`physical`,11],"extensions/KHR_materials_ior/ior":[`SCALAR`,`ext`,1],"extensions/KHR_materials_volume/thicknessFactor":[`SCALAR`,`volume`,0],"extensions/KHR_materials_volume/attenuationColor":[`VEC3`,`volume`,1],"extensions/KHR_materials_volume/attenuationDistance":[`SCALAR`,`volume`,4,`extensions/KHR_materials_volume/attenuationDistance`]},p={color:`VEC3`,intensity:`SCALAR`,range:`SCALAR`,"spot/innerConeAngle":`SCALAR`,"spot/outerConeAngle":`SCALAR`},m={perspective:[`yfov`,`aspectRatio`,`znear`,`zfar`],orthographic:[`xmag`,`ymag`,`znear`,`zfar`]},h=/^\/materials\/\d+\/extensions\/KHR_materials_ior\/ior$/,g=/* @__PURE__ */ new Set([`pbrMetallicRoughness/baseColorFactor`,`emissiveFactor`,`color`]),_=class{constructor(e){this.reason=e}},v=/* @__PURE__ */ new WeakMap,y=e=>{throw new _(e)},b=(i,a,o)=>{let s=i.asset.doc,u=[],d=[],f=[],p=/* @__PURE__ */ new Set,m=[],g=[],y=/* @__PURE__ */ new Set,b=0;a.channels.forEach((e,v)=>{let x=c(e),S=c(x?.target),w=c(S?.extensions),T=c(w?.KHR_animation_pointer)?.pointer;if(S?.path!==`pointer`&&w?.KHR_animation_pointer===void 0){S?.path===`weights`&&typeof S.node==`number`&&p.add(S.node),u.push(e);return}let E=`Animation ${o} channel ${v}`;if(S?.path!==`pointer`||Object.hasOwn(S,`node`)||typeof T!=`string`)throw TypeError(`${E} KHR_animation_pointer needs path 'pointer', no target node and a pointer string; fix the channel target`);if(y.has(T))throw TypeError(`${E} repeats pointer ${T}; use one channel per property`);y.add(T);let D=n(a.samplers[t(x.sampler,a.samplers.length,`sampler`)]),O=r(D.interpolation),k=i.asset.accessor(D.input,`SCALAR`);if(k.some((e,t)=>e<0||t>0&&e<=k[t-1]))throw RangeError(`${E} key times must be nonnegative and strictly increasing; fix the sampler input`);if(b=Math.max(b,k[k.length-1]),h.test(T)){let e=i.asset.accessor(D.output,`SCALAR`),t=O===`CUBICSPLINE`?3:1;for(let n=0;n<k.length;n++)if(e[n*t+(t>>1)]<1)throw RangeError(`${E} pointer ${T} keys an IOR of ${e[n*t+(t>>1)]}; KHR_materials_ior allows animated IORs of 1 or more only`)}let A;try{A=C(i,s,T,E)}catch(e){if(!(e instanceof _))throw e;g.push(`${E}: pointer ${T} ${e.reason}; skipped`);return}if(`path`in A){A.mesh||p.add(A.nodes[0]);for(let e of A.nodes)(A.mesh?f:d).push({node:e,path:A.path,sampler:x.sampler});A.nodes.length||g.push(`${E}: pointer ${T} has no node using the mesh; skipped`);return}let{accessor:j,size:M,bool:N}=A,P=c(l(s.accessors)[D.output]);if(N&&(O!==`STEP`||P?.componentType!==5121||P.normalized))throw TypeError(`${E} pointer ${T} is a boolean; use STEP and an unsigned byte SCALAR accessor`);let F=i.asset.accessor(D.output,j),I=O===`CUBICSPLINE`,L=M*(I?3:1);if(F.length!==k.length*L)throw RangeError(`${E} pointer ${T} has ${F.length/M} output values for ${k.length} keys; key one ${j} per time${I?` with in and out tangents`:``}`);let R=Array.from(k,(e,t)=>{let n=t*L+(I?M:0),r={time:e,value:Array.from(F.subarray(n,n+M)),interpolation:I?`cubicSpline`:O===`STEP`?`discrete`:`linear`};return I&&(r.inTangent=Array.from(F.subarray(n-M,n)),r.outTangent=Array.from(F.subarray(n+M,n+2*M))),r});m.push({target:A,keys:R,pointer:T})});for(let e of f)p.has(e.node)||d.unshift(e);return{ordinary:u,nodes:d,duration:b,warnings:g,...m.length?{bind:()=>{let t=v.get(i);return t||v.set(i,t=/* @__PURE__ */ new Map),e({name:o,tracks:m.map(({target:e,keys:n,pointer:r})=>({target:i,name:r,type:e.type,set:e.make(t),keys:n}))})}}:{}}};function x(e,t){let n=/^\/nodes\/(\d+)\/weights\/(\d+)$/.exec(t);if(n)return t=>{for(let r of e.primitives)r.nodeIndex===+n[1]&&(r.weights[+n[2]]=t[0])};let r;try{r=C(e,e.asset.doc,t,`Behaviour graph`)}catch(e){if(e instanceof _)return;throw e}if(!(`path`in r)){let t=v.get(e);t||v.set(e,t=/* @__PURE__ */ new Map);let n=r.make(t);return e=>n(Float64Array.from(e))}let i=e.nodes[r.nodes[0]],{path:a}=r;if(i&&a!==`weights`)return e=>{a===`rotation`?i.setQuaternion(Array.from(e)):a===`scale`?i.setScale(Array.from(e)):i.setPosition(Array.from(e))}}function S(e,t,n,r,i){if(e===void 0||!/^(0|[1-9]\d*)$/.test(e)||Number(e)>=t)throw TypeError(`${r} pointer ${i} names no ${n} ${e??``}; point at an existing index`);return Number(e)}function C(e,t,n,r){if(!n.startsWith(`/`))throw TypeError(`${r} pointer ${n} is not a JSON pointer; start it with '/'`);let i=n.slice(1).split(`/`).map(e=>e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`)),a=()=>{throw TypeError(`${r} pointer ${n} is not an animatable glTF property; point at a property animations may change`)},o=e=>e.split(`/`).some(e=>e===`extras`||e===`extensions`);i.includes(`extras`)&&y(`targets application-defined extras`);let[d,f,...h]=i,_=h.join(`/`);if(d===`nodes`){let i=S(f,l(t.nodes).length,`node`,r,n);if([`translation`,`rotation`,`scale`,`weights`].includes(_))return{nodes:[i],path:_,mesh:!1};if(_===`extensions/KHR_node_visibility/visible`){c(u(l(t.nodes)[i],`extensions/KHR_node_visibility`))||y(`targets a node without KHR_node_visibility`);let n=e.nodes[i];return{accessor:`SCALAR`,size:1,type:`number`,bool:!0,make:()=>e=>{n.visible=e[0]!==0}}}return o(_)&&y(`targets a node extension this player does not drive`),a()}if(d===`meshes`){let e=S(f,l(t.meshes).length,`mesh`,r,n);return _===`weights`?{nodes:l(t.nodes).flatMap((t,n)=>c(t)?.mesh===e?[n]:[]),path:`weights`,mesh:!0}:(o(_)&&y(`targets a mesh extension this player does not drive`),a())}if(d===`materials`)return w(e,t,S(f,l(t.materials).length,`material`,r,n),_,a);if(d===`cameras`){let i=S(f,l(t.cameras).length,`camera`,r,n),o=c(l(t.cameras)[i]),[s,u,d]=h;if(!m[s]?.includes(u)||d!==void 0)return a();(o.type!==s||!c(o[s]))&&y(`targets ${s} values of a ${String(o.type)} camera`),c(o[s])[u]===void 0&&y(`targets ${u}, which the camera does not define`);let p=e.cameras.filter(e=>c(l(t.nodes)[e.nodeIndex])?.camera===i);return p.length||y(`targets a camera no scene node uses`),{accessor:`SCALAR`,size:1,type:`number`,make:e=>{let t=`camera ${i}`,n=e.get(t)??p.map(e=>{let t={...e[s]};return e[s]=t,t});return e.set(t,n),e=>{for(let t of n)t[u]=e[0]}}}}if(d===`extensions`&&f===`KHR_lights_punctual`&&h[0]===`lights`){let i=l(c(c(t.extensions)?.KHR_lights_punctual)?.lights),o=S(h[1],i.length,`light`,r,n),d=h.slice(2).join(`/`),f=c(i[o]),m=p[d];if(!m)return a();d.startsWith(`spot/`)&&f.type!==`spot`&&y(`targets spot cones of a ${String(f.type)} light`),d===`range`&&f.range===void 0&&y(`targets range, which the light does not define`);let _=e.lights.filter(e=>c(u(l(t.nodes)[e.nodeIndex],`extensions/KHR_lights_punctual`))?.light===o);_.length||y(`targets a light no scene node uses`);let v=d.startsWith(`spot/`)?d.slice(5):d;return{accessor:m,size:s[m],type:g.has(d)?`color`:`number`,make:e=>{if(d===`color`){if(!e.has(`light ${o}`))for(let e of _)e.color=e.color.slice();return e.set(`light ${o}`,!0),e=>{for(let t of _)for(let n=0;n<3;n++)t.color[n]=e[n]}}return e=>{for(let t of _)t[v]=e[0]}}}}return d===`extensions`&&y(`targets ${f}, which this player does not drive`),a()}function w(e,t,n,r,i){let o=c(l(t.materials)[n]),p=[...new Set([...e.primitives,...e.pointsAndLines].filter(e=>e.definition.material===n).map(e=>e.material))],m=/^(.+)\/extensions\/KHR_texture_transform\/(offset|scale|rotation|texCoord)$/.exec(r);if(m){let e=d[m[1]],t=m[2];e===void 0&&y(`targets a texture this player does not map to a live UV transform`),t===`texCoord`&&y(`targets texCoord, an integer UV set this player does not switch`),c(u(o,m[1]))||y(`targets a texture the material does not define`),p.length||y(`targets a material no primitive draws`),p.some(t=>t.maps[e])||y(`targets a texture no drawn primitive samples`);let r=t===`rotation`?`SCALAR`:`VEC2`;return{accessor:r,size:s[r],type:t===`rotation`?`number`:`vector`,make:r=>{let i=`texture ${n} ${e}`,o=r.get(i)??T(p,e);return r.set(i,o),n=>{for(let{m:r,own:i,texCoord:s}of o){if(t===`rotation`)i.rotation=n[0];else{let e=i[t];e[0]=n[0],e[1]=n[1]}let o=a(i,s);if(r.uvt&&r.uvt.length>=e*8+8)for(let t=0;t<8;t++)r.uvt[e*8+t]=o[t]}}}}}let h=f[r];if(!h)return(r.startsWith(`extensions/`)||r.includes(`/extensions/`))&&y(`targets a material extension property this player does not drive`),i();let[_,v,b,x]=h,S=r.startsWith(`extensions/`)?r.split(`/`).slice(0,2).join(`/`):void 0;x&&u(o,x)===void 0&&y(`targets ${x.split(`/`).pop()}, which the material does not define`),S&&!c(u(o,S))&&y(`targets ${S.slice(11)}, which the material does not use`),r===`extensions/KHR_materials_ior/ior`&&u(o,r)===0&&y(`targets an IOR of 0, a mode KHR_materials_ior keeps for good (updates are ignored)`),p.length||y(`targets a material no primitive draws`),(v===`physical`||v===`ext`||v===`volume`)&&(p.some(e=>!e.physical)&&y(`targets a physical material factor gltf/pbr did not load (pass decoders.materials)`),(v===`volume`||b===3)&&p.some(e=>!e.tint&&!e.attenuation)&&y(`targets transmission or volume of a material loaded without transmission`));let C=s[_];return{accessor:_,size:C,type:g.has(r)?`color`:C===1?`number`:`vector`,make:e=>{let t=`material ${n}`,r=e.get(t)??E(o,p);if(e.set(t,r),v===`base`)for(let e of p)e.base=e.base.slice();return e=>{if(v===`emissive`||v===`strength`){if(v===`strength`)r.strength=e[0];else for(let t=0;t<3;t++)r.emissive[t]=e[t];for(let e of p)for(let t=0;t<3;t++)e.emission[t]=r.emissive[t]*r.strength}else{if(v===`volume`){if(b===0)r.thickness=e[0];else if(b===4)r.distance=e[0];else for(let t=0;t<3;t++)r.atten[t]=e[t]}else if(v===`dispersion`)for(let t of p)t.dispersion=e[0];else if(v===`ext`&&b===1)for(let t of p)t.ext[1]=Math.max(1,e[0]);else for(let t of p)for(let n=0;n<C;n++)t[v][b+n]=e[n];(v===`base`||v===`volume`||v===`physical`&&b===3)&&D(r)}}}}}function T(e,t){return e.flatMap(e=>{let n=e.maps[t];if(!n)return[];let r=n.extensions?.KHR_texture_transform??{},a=i(n).texCoord,o={...r,offset:[...r.offset??[0,0]],scale:[...r.scale??[1,1]],rotation:r.rotation??0},s=e.maps.slice();return s[t]={...n,texCoord:a,extensions:{...n.extensions,KHR_texture_transform:o}},e.maps=s,[{m:e,own:o,texCoord:a}]})}function E(e,t){let n=c(u(e,`extensions/KHR_materials_volume`)),r=n?.attenuationDistance;return{mats:t,emissive:[...e.emissiveFactor??[0,0,0]],strength:u(e,`extensions/KHR_materials_emissive_strength/emissiveStrength`)??1,atten:[...n?.attenuationColor??[1,1,1]],thickness:n?.thicknessFactor??0,distance:typeof r==`number`?r:1/0}}function D({mats:e,atten:t,thickness:n,distance:r}){let i=n/r;for(let a of e)if((a.tint||a.attenuation)&&a.physical){if(a.physical[3]>0){let e=a.tint??=[0,0,0];for(let n=0;n<3;n++)e[n]=a.base[n]*a.physical[3]*o(t[n],i)}else a.tint=void 0;if(a.attenuation){for(let e=0;e<3;e++)a.attenuation[e]=o(t[e],i);let e=a.opticalDepth??=[0,0,0];for(let n=0;n<3;n++)e[n]=t[n]===1||i===0?0:-Math.log(t[n])*i}if(a.volume){a.volume[0]=n;for(let e=0;e<3;e++)a.volume[1+e]=o(t[e],1/r)}}}export{x as n,b as t};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { PBRModel } from '@margoengine/gltf/pbr';
|
|
2
|
+
import { type KeyframeClip } from './keyframes.js';
|
|
3
|
+
import { type AnimationDefinition } from './gltf.js';
|
|
4
|
+
import type { AnimationPath } from './gltf.js';
|
|
5
|
+
/** A pointer channel that drives a node's TRS or morph weights: played as an ordinary node track. */
|
|
6
|
+
export interface PointerNodeChannel {
|
|
7
|
+
node: number;
|
|
8
|
+
path: AnimationPath;
|
|
9
|
+
sampler: unknown;
|
|
10
|
+
}
|
|
11
|
+
/** What {@link PointerChannels} found in one glTF clip. */
|
|
12
|
+
export interface PointerPlan {
|
|
13
|
+
/** Channels without KHR_animation_pointer, for the ordinary node track parser. */
|
|
14
|
+
ordinary: unknown[];
|
|
15
|
+
/** Node TRS and weights pointers, mesh weights expanded to every node using the mesh. */
|
|
16
|
+
nodes: PointerNodeChannel[];
|
|
17
|
+
/** Binds the material, light, camera and visibility pointers to live values; undefined when there are none. */
|
|
18
|
+
bind?: () => KeyframeClip;
|
|
19
|
+
/** The last key time of every pointer channel, skipped ones included. */
|
|
20
|
+
duration: number;
|
|
21
|
+
/** One line per skipped pointer channel. */
|
|
22
|
+
warnings: string[];
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The shape of {@link pointerChannels}, the opt-in KHR_animation_pointer support `Animation` takes as its `pointers`
|
|
26
|
+
* option: sorts one glTF clip's channels (`def`, labelled `clip` in messages) for `model`.
|
|
27
|
+
*/
|
|
28
|
+
export type PointerChannels = (model: PBRModel, def: AnimationDefinition, clip: string) => PointerPlan;
|
|
29
|
+
/**
|
|
30
|
+
* KHR_animation_pointer playback for `Animation`: pass it as the `pointers` option
|
|
31
|
+
* (`Animation.attach(model, {pointers: pointerChannels})`). For each glTF clip it sorts the channels into ordinary
|
|
32
|
+
* channels, pointer channels that drive node TRS and weights (played as node tracks) and property pointers bound on the
|
|
33
|
+
* clip's first playback to the model's live material factors, texture transforms, lights, cameras and node
|
|
34
|
+
* visibility. Malformed pointers, pointers to properties glTF does not let animations change and mismatched accessors
|
|
35
|
+
* throw TypeError or RangeError; valid pointers it cannot drive are skipped and listed in `animation.warnings`.
|
|
36
|
+
* `Animation` calls it; apps only pass it along.
|
|
37
|
+
*/
|
|
38
|
+
export declare const pointerChannels: PointerChannels;
|
|
39
|
+
/**
|
|
40
|
+
* A writer of one object model property of the live model, for a value that does not come from a clip: `value` holds its
|
|
41
|
+
* components. Undefined for a property the model has no live value for. Shares its state with playing clips.
|
|
42
|
+
*/
|
|
43
|
+
export declare function pointerWriter(model: PBRModel, pointer: string): ((value: ArrayLike<number>) => void) | undefined;
|
package/dist/pointer.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{t as pointerChannels,n as pointerWriter}from"./pointer-DyWpFsQi.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=Symbol.for(`margoengine.pose-sources.v1`),t=globalThis[e]??/* @__PURE__ */ new WeakMap;globalThis[e]||Object.defineProperty(globalThis,e,{value:t});function n(e,n){t.set(e,n)}function r(e,n){t.get(e)===n&&t.delete(e)}export{n,r as t};
|
package/dist/pose.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { SkinningMode } from './shader.js';
|
|
2
|
+
import type { MorphTable } from './morph-table.js';
|
|
3
|
+
/**
|
|
4
|
+
* Writes the pose of `bind` (20 floats per vertex) into `out`. Morph targets are added first: `deltas` is the primitive's sparse
|
|
5
|
+
* table (morph-table.ts), walked in target order as the shader walks it, and `weights` holds one value per target. Then comes the weighted blend
|
|
6
|
+
* of `palette` (16 floats per bone) by `influences`: `words` per vertex, four joint indices then four float weights,
|
|
7
|
+
* twice for eight influences. Everything but position and normal is copied from `bind`. With a skinning `mode`, its
|
|
8
|
+
* `blend` moves each vertex instead, with `palette` encoded for it; a mode with `share` reads each vertex's share from
|
|
9
|
+
* the upper 16 bits of its first joint index, as the mode's shader does; a mode with `vertexData` reads the last four
|
|
10
|
+
* of each vertex's `words` as its data.
|
|
11
|
+
*/
|
|
12
|
+
export declare function poseVertices(bind: Float32Array, out: Float32Array, deltas: MorphTable, weights: ArrayLike<number>, influences: Uint32Array, words: number, palette: Float32Array, mode?: SkinningMode): void;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{MargoError as e}from"@margoengine/math/errors";function t(t,n){if(t.backend===`webgl2`||!t.gpu)throw new e(`unsupported`,`${n} needs WebGPU; see https://margoengine.com/errors#webgpu`)}export{t};
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { PBRModel } from '@margoengine/gltf/pbr-model';
|
|
2
|
+
import { type KeyframeClip } from './keyframes.js';
|
|
3
|
+
import { Skeleton } from './skin.js';
|
|
4
|
+
/**
|
|
5
|
+
* A bone hierarchy and its rest pose, as {@link Retarget} reads it. Make one with {@link retargetRig} from a
|
|
6
|
+
* `Skeleton` (bones) or a glTF PBR model (every node, so armature and mesh nodes count toward bone orientations).
|
|
7
|
+
*/
|
|
8
|
+
export interface RetargetRig {
|
|
9
|
+
/** Bone names; a bone's index is its position here (a model's node index). */
|
|
10
|
+
readonly names: readonly string[];
|
|
11
|
+
/** Parent bone per bone, -1 at the top. */
|
|
12
|
+
readonly parents: readonly number[];
|
|
13
|
+
/** Rest local pose, 10 numbers per bone: translation xyz, rotation quaternion xyzw, scale xyz. */
|
|
14
|
+
readonly rest: Float64Array;
|
|
15
|
+
}
|
|
16
|
+
/** Options for {@link Retarget}. */
|
|
17
|
+
export interface RetargetOptions {
|
|
18
|
+
/**
|
|
19
|
+
* Target bone name to source bone name. A target bone that is not listed follows the source bone of the same name,
|
|
20
|
+
* when there is one. Map a target bone to `''` to leave it at rest.
|
|
21
|
+
*/
|
|
22
|
+
names?: Readonly<Record<string, string>>;
|
|
23
|
+
/** The target bone whose position follows the source's (the hips). Default: none, every bone keeps its rest position. */
|
|
24
|
+
hip?: string;
|
|
25
|
+
/**
|
|
26
|
+
* Scale on the hip's movement from rest. Default: the target hip's rest height (y in model or skeleton space) over
|
|
27
|
+
* the source hip's, or 1 when either is not above 0.
|
|
28
|
+
*/
|
|
29
|
+
hipScale?: number;
|
|
30
|
+
/**
|
|
31
|
+
* Unmapped target bones held at the target rig's rest rotation: {@link Retarget.apply} writes it and
|
|
32
|
+
* {@link Retarget.clip} keys it, for a rig whose rest differs from the pose the target holds now (an aligned rig
|
|
33
|
+
* from `@margoengine/rigging`'s prepareRetarget lists the bones it re-aimed). Default: none; mapped bones are ignored.
|
|
34
|
+
*/
|
|
35
|
+
hold?: readonly string[];
|
|
36
|
+
}
|
|
37
|
+
/** A glTF PBR model's player, such as an `Animation`, whose clip {@link Retarget.clip} can sample. */
|
|
38
|
+
export interface RetargetPlayer {
|
|
39
|
+
readonly model: PBRModel;
|
|
40
|
+
readonly clips: readonly {
|
|
41
|
+
readonly name: string;
|
|
42
|
+
readonly duration: number;
|
|
43
|
+
}[];
|
|
44
|
+
clip: number;
|
|
45
|
+
time: number;
|
|
46
|
+
playing: boolean;
|
|
47
|
+
play(clip: number): unknown;
|
|
48
|
+
seek(time: number): unknown;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The bones and current local pose of a `Skeleton`, or of every node of a glTF PBR model (names, parents and the
|
|
52
|
+
* nodes' local transforms), as a {@link RetargetRig}. The current pose becomes the rig's rest pose, the reference both
|
|
53
|
+
* rigs are compared in, so pose both characters the same way (both in T-pose, say) before making their rigs.
|
|
54
|
+
*/
|
|
55
|
+
export declare function retargetRig(from: Skeleton | PBRModel): RetargetRig;
|
|
56
|
+
/**
|
|
57
|
+
* Retargeting: moves one skeleton the way another moves, bone by bone. Each
|
|
58
|
+
* mapped target bone turns in model space by the same rotation its source bone has turned from rest, which absorbs
|
|
59
|
+
* different bone axes and rest orientations: target world rotation = source world rotation x inverse(source rest
|
|
60
|
+
* world rotation) x target rest world rotation. Unmapped target bones keep their rest local rotation, every bone keeps
|
|
61
|
+
* its rest length and scale, and the `hip` bone's position follows the source hip's movement from rest times
|
|
62
|
+
* `hipScale`. Both rigs' model spaces are assumed to face the same way.
|
|
63
|
+
*/
|
|
64
|
+
export declare class Retarget {
|
|
65
|
+
readonly source: RetargetRig;
|
|
66
|
+
readonly target: RetargetRig;
|
|
67
|
+
/** Source bone per target bone, -1 where the target bone is not mapped. */
|
|
68
|
+
readonly map: Int32Array;
|
|
69
|
+
/** Target hip bone index, or -1. */
|
|
70
|
+
readonly hip: number;
|
|
71
|
+
/** Source bone the hip follows, or -1. */
|
|
72
|
+
readonly sourceHip: number;
|
|
73
|
+
/** Scale applied to the hip's movement. */
|
|
74
|
+
readonly hipScale: number;
|
|
75
|
+
/** 1 per unmapped target bone held at its rig rest rotation (see {@link RetargetOptions.hold}), else 0. */
|
|
76
|
+
readonly held: Uint8Array;
|
|
77
|
+
private readonly sourceOrder;
|
|
78
|
+
private readonly targetOrder;
|
|
79
|
+
private readonly sourceRest;
|
|
80
|
+
private readonly targetRest;
|
|
81
|
+
private readonly sourceNow;
|
|
82
|
+
private readonly targetNow;
|
|
83
|
+
private readonly delta;
|
|
84
|
+
private readonly input;
|
|
85
|
+
private readonly output;
|
|
86
|
+
private readonly poses;
|
|
87
|
+
private readonly quaternion;
|
|
88
|
+
private readonly vector;
|
|
89
|
+
constructor(source: RetargetRig, target: RetargetRig, options?: RetargetOptions);
|
|
90
|
+
/**
|
|
91
|
+
* The target's local pose (10 numbers per target bone, as in {@link RetargetRig.rest}) for a source local pose
|
|
92
|
+
* (10 per source bone). Unmapped target bones get their rest pose.
|
|
93
|
+
*/
|
|
94
|
+
pose(source: Float64Array, out?: Float64Array): Float64Array;
|
|
95
|
+
/**
|
|
96
|
+
* Poses `target` the way `source` is posed now: each must be the Skeleton or model its rig was made from. Writes
|
|
97
|
+
* the mapped bones' rotations, the held bones' rest rotations ({@link RetargetOptions.hold}) and the hip's position;
|
|
98
|
+
* other target bones keep what they have (the retarget assumes them at rest).
|
|
99
|
+
*/
|
|
100
|
+
apply(source: Skeleton | PBRModel, target: Skeleton | PBRModel): void;
|
|
101
|
+
/**
|
|
102
|
+
* A code-authored clip for the target rig from a source clip, sampled at `fps` (default 30) from 0 to the clip's
|
|
103
|
+
* duration: a rotation track per mapped or held target bone and a translation track for the hip, linear keys. The source
|
|
104
|
+
* is a `KeyframeClip` whose tracks name source bones (sampled over the source rig's rest pose; weights tracks are
|
|
105
|
+
* not carried over), or a glTF clip played by the source model's `Animation` (`{animation, clip}`; its clip, time and
|
|
106
|
+
* playing state are restored afterwards). Play the result with `applyKeyframeClip` or an `AnimationGroup`.
|
|
107
|
+
*/
|
|
108
|
+
clip(source: KeyframeClip | {
|
|
109
|
+
readonly animation: RetargetPlayer;
|
|
110
|
+
readonly clip: string | number;
|
|
111
|
+
}, { fps, name }?: {
|
|
112
|
+
fps?: number;
|
|
113
|
+
name?: string;
|
|
114
|
+
}): KeyframeClip;
|
|
115
|
+
}
|
package/dist/rigid.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { type KeyframeClip } from './keyframes.js';
|
|
2
|
+
/** A bone of a rigid rig: its id (the track target) and its rest translation. */
|
|
3
|
+
export interface RigidBone {
|
|
4
|
+
id: string;
|
|
5
|
+
translation: readonly [number, number, number];
|
|
6
|
+
}
|
|
7
|
+
/** A mesh rigidly bound to a bone, with the rest pose its keys are measured from. */
|
|
8
|
+
export interface RigidBinding {
|
|
9
|
+
/** The mesh's id, as named by its keys. */
|
|
10
|
+
object: string;
|
|
11
|
+
/** The bone that carries it. One bone may carry several meshes. */
|
|
12
|
+
bone: string;
|
|
13
|
+
/** Rest position. */
|
|
14
|
+
position: readonly [number, number, number];
|
|
15
|
+
/** Rest rotation as a quaternion `[x, y, z, w]`. */
|
|
16
|
+
rotation: readonly [number, number, number, number];
|
|
17
|
+
}
|
|
18
|
+
/** A keyed pose of a bound mesh. */
|
|
19
|
+
export interface RigidKey {
|
|
20
|
+
object: string;
|
|
21
|
+
/** Seconds, >= 0. Keys need not be sorted; among equal times the later key wins. */
|
|
22
|
+
time: number;
|
|
23
|
+
position: readonly [number, number, number];
|
|
24
|
+
rotation: readonly [number, number, number, number];
|
|
25
|
+
}
|
|
26
|
+
/** Options for {@link compileRigidClip}. */
|
|
27
|
+
export interface RigidClipOptions {
|
|
28
|
+
/** Clip name. */
|
|
29
|
+
name?: string;
|
|
30
|
+
/** Seconds; when past the last key, the last pose is held until then. */
|
|
31
|
+
duration?: number;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Compiles keys of rigidly bound meshes into stepped bone translation and rotation tracks. Each bone follows one of
|
|
35
|
+
* its meshes: the first in binding order that has been keyed so far. A key moves the bone by the mesh's offset from
|
|
36
|
+
* its rest position (`bone.translation + key.position - rest.position`) and rotates it by
|
|
37
|
+
* `key.rotation * inverse(rest.rotation)`. A bone whose first key is after 0 starts at rest; bones without keyed
|
|
38
|
+
* meshes get no tracks. Keys of unbound meshes are ignored.
|
|
39
|
+
* @throws TypeError for malformed bones, bindings or keys, or a binding to an unknown bone or a mesh bound twice;
|
|
40
|
+
* RangeError for a non-finite or negative time or value.
|
|
41
|
+
*/
|
|
42
|
+
export declare function compileRigidClip(bones: readonly RigidBone[], bindings: readonly RigidBinding[], keys: readonly RigidKey[], options?: RigidClipOptions): KeyframeClip;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{normalizeQuaternion as e}from"@margoengine/math/quat";function t(t,n,r,i,a,o,s,c,l,u){let d=c===`CUBICSPLINE`?3:1,f=o-a,p=f?Math.max(0,Math.min(1,(s-a)/f)):0,m=(r*d+ +(d===3))*n,h=(i*d+ +(d===3))*n;if(c===`STEP`||r===i)for(let e=0;e<n;e++)u[e]=t[m+e];else if(c===`CUBICSPLINE`){let e=p*p,a=e*p;for(let o=0;o<n;o++)u[o]=(2*a-3*e+1)*t[m+o]+(a-2*e+p)*f*t[(r*3+2)*n+o]+(-2*a+3*e)*t[h+o]+(a-e)*f*t[i*3*n+o]}else if(l){let e=0;for(let n=0;n<4;n++)e+=t[m+n]*t[h+n];let n=e<0?-1:1;e=Math.abs(e);let r=1-p,i=p;if(e<.9995){let t=Math.acos(Math.min(1,e)),n=Math.sin(t);r=Math.sin((1-p)*t)/n,i=Math.sin(p*t)/n}for(let e=0;e<4;e++)u[e]=t[m+e]*r+t[h+e]*i*n}else for(let e=0;e<n;e++)u[e]=t[m+e]*(1-p)+t[h+e]*p;if(l){if(!(u[0]||u[1]||u[2]||u[3]))throw RangeError(`Zero animation quaternion; rotation keys must be non-zero quaternions`);e(u,u)}for(let e=0;e<n;e++)if(!Number.isFinite(u[e]))throw RangeError(`Animation sample overflow; use finite keyframe values`);return u}var n=()=>/* @__PURE__ */ TypeError(`Invalid animation track; pass times and values arrays, an integer width >= 1, a finite time and STEP, LINEAR or CUBICSPLINE`);function r(e,r,i,a){let o=e.times,s=o.length;if(!s||!Number.isFinite(r))throw n();let c=e.cursor<s?e.cursor:0,l=o[c],u=c,d=l;if(c===0||l<=r){for(;c+1<s;){let e=o[c+1];if(e<=r)c++,l=e;else{u=c+1,d=e;break}}u<c&&(u=c,d=l)}else{let e=0,t=s-1;for(;e<t;){let n=Math.ceil((e+t)/2);o[n]<=r?e=n:t=n-1}c=e,u=Math.min(c+1,s-1),l=o[c],d=o[u]}return e.cursor=c,t(e.values,e.width,c,u,l,d,r,e.interpolation,i,a)}function i(e,t,n,r,i,o=!1,s){if(s!==void 0&&(!(s instanceof Float32Array)||s.length!==n||s.buffer===e.buffer||s.buffer===t.buffer))throw TypeError(`Invalid animation sample target; pass a Float32Array of the track width that does not share the times or values buffer`);return a(e,t,n,r,i,o,s)}function a(e,r,i,a,o,s=!1,c){if(!e.length||!Number.isInteger(i)||i<1||!Number.isFinite(a)||o!==`STEP`&&o!==`LINEAR`&&o!==`CUBICSPLINE`)throw n();let l=o===`CUBICSPLINE`?3:1;if(r.length!==e.length*i*l)throw RangeError(`Animation output count mismatch; values needs times.length * width numbers (three times that for CUBICSPLINE)`);let u=0,d=e.length-1;for(;u<d;){let t=Math.ceil((u+d)/2);e[t]<=a?u=t:d=t-1}let f=u,p=Math.min(f+1,e.length-1);return c=c?.length===i&&(!s||i===4)?c:new Float32Array(i),t(r,i,f,p,e[f],e[p],a,o,s,c)}function o(e){if(!Array.isArray(e))throw TypeError(`Clip markers must be an array of {time, name}`);for(let t of e){if(typeof t?.name!=`string`||!t.name)throw TypeError(`Clip marker needs a nonempty string name`);if(!Number.isFinite(t.time)||t.time<0)throw RangeError(`Clip marker time must be a finite number >= 0`)}return Object.freeze(e.map(e=>Object.freeze({...e})).sort((e,t)=>e.time-t.time))}var s=class{constructor(e,t,n=!0){if(this.at=0,this.fresh=!0,!(t>0)||!Number.isFinite(t))throw RangeError(`Clip duration must be a finite number > 0 seconds`);if(this.markers=o(e),this.duration=t,this.loop=n,this.markers.some(e=>e.time>t))throw RangeError(`Clip marker time is past the clip duration; move it inside the clip`)}get time(){return this.loop?this.at%this.duration:this.at}advance(e,t=[]){if(!Number.isFinite(e))throw RangeError(`Clip advance needs a finite delta in seconds`);return this.move(this.at+e,t)}seek(e,t=!1,n=[]){if(!Number.isFinite(e)||e<0)throw RangeError(`Clip seek needs a finite time >= 0 seconds`);let r=this.move(e,n);return t||(r.length=0),r}move(e,t){let{duration:n,loop:r}=this;t.length=0,e=r?Math.max(e,0):Math.min(Math.max(e,0),n);let i=this.at,a=e>=i,o=a?i:e,s=a?e:i,c=r?Math.floor(o/n):0,l=r?Math.floor(s/n):0,u=[];if((l-c+1)*this.markers.length>65536)throw RangeError(`Clip step spans too many laps; use smaller deltas`);for(let e=c;e<=l;e++)for(let t of this.markers){let r=t.time+e*n;r<=s&&(r>o||this.fresh&&a&&r===o)&&u.push([r,t])}u.sort((e,t)=>a?e[0]-t[0]:t[0]-e[0]);for(let e of u)t.push(e[1]);return this.at=e,this.fresh=!1,t}},c=(e,t,n)=>{let r=0,i=0;if(n)for(let n=0;n<4;n++)r+=e[n]*t[n];let a=r<0?-1:1;for(let n=0;n<e.length;n++)i=Math.max(i,Math.abs(e[n]-a*t[n]));return i},l=(t,n,r)=>{for(let e=0;e<t.width;e++)r[e]=t.values[n*t.width+e];return t.quaternion?e(r,r):r};function u(e,t){let{times:n,values:r,width:i,interpolation:o,quaternion:s}=e,u=n.length;if(!(t>=0)||!Number.isFinite(t))throw RangeError(`Compression tolerance must be a finite number >= 0`);if(o!==`LINEAR`&&o!==`STEP`)throw TypeError(`Only LINEAR and STEP tracks compress; pass interpolation LINEAR or STEP`);if(u<1||r.length!==u*i)throw RangeError(`Track needs times and width numbers per key; values.length must be times.length * width`);let d=new Uint8Array(u),f=new Float32Array(i),p=new Float32Array(i),m={times:/* @__PURE__ */ new Float32Array(2),values:new Float32Array(2*i),width:i,interpolation:o,quaternion:s};if(d[0]=d[u-1]=1,o===`STEP`)for(let n=1,r=0;n<u-1;n++)c(l(e,n,f),l(e,r,p),s)>t&&(d[r=n]=1);else{let o=[0,u-1];for(;o.length;){let u=o.pop(),h=o.pop(),g=-1,_=t;m.times[0]=n[h],m.times[1]=n[u],m.values.set(r.subarray(h*i,h*i+i),0),m.values.set(r.subarray(u*i,u*i+i),i);for(let t=h+1;t<u;t++){let r=c(a(m.times,m.values,i,n[t],`LINEAR`,s,f),l(e,t,p),s);r>_&&(_=r,g=t)}g>=0&&(d[g]=1,o.push(h,g,g,u))}}let h=d.reduce((e,t)=>e+t,0),g={times:new Float32Array(h),values:new Float32Array(h*i),width:i,interpolation:o,...s?{quaternion:s}:{},error:0};for(let e=0,t=0;e<u;e++)d[e]&&(g.times[t]=n[e],g.values.set(r.subarray(e*i,e*i+i),t++*i));for(let t=0;t<u;t++)g.error=Math.max(g.error,c(a(g.times,g.values,i,n[t],o,s,f),l(e,t,p),s));return g}function d(e){let{values:t,width:n}=e,r=new Float32Array(n).fill(1/0),i=new Float32Array(n).fill(-1/0),a=new Float32Array(n),o=new Uint16Array(t.length);if(!t.length||t.length!==e.times.length*n)throw RangeError(`Track needs times and width numbers per key; values.length must be times.length * width`);for(let e=0;e<t.length;e++){let a=t[e],o=e%n;if(!Number.isFinite(a))throw RangeError(`Track values must be finite to quantise`);a<r[o]&&(r[o]=a),a>i[o]&&(i[o]=a)}for(let e=0;e<n;e++)a[e]=(i[e]-r[e])/65535;for(let e=0;e<t.length;e++){let i=e%n;o[e]=a[i]?Math.round((t[e]-r[i])/a[i]):0}let{values:s,...c}=e;return{...c,data:o,min:r,step:a}}function f(e){let{data:t,min:n,step:r,...i}=e,a=new Float32Array(t.length);for(let i=0;i<t.length;i++)a[i]=n[i%e.width]+t[i]*r[i%e.width];return{...i,values:a}}export{i as a,r as c,d as i,u as n,a as o,f as r,o as s,s as t};
|