@algorisys/tinyfly 0.118.0 → 0.119.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -6
- package/docs/editor-guide.md +1 -1
- package/docs/examples.md +1 -1
- package/docs/getting-started.md +1 -1
- package/docs/gsap-compat.md +1 -1
- package/docs/llm-guide.md +3 -1
- package/docs/maps.md +2 -2
- package/docs/math.md +46 -7
- package/docs/teaching.md +1 -1
- package/lib/addons/characters.js +1851 -1844
- package/lib/addons/math.js +2002 -1478
- package/lib/browser/tinyfly-math.iife.js +4 -4
- package/lib/browser/tinyfly.iife.js +1 -1
- package/lib/browser/tinyfly.js +8 -1
- package/lib/browser/tinyfly.umd.js +1 -1
- package/lib/types/math/figure/display-list.d.ts +2 -0
- package/lib/types/math/figure/figure-spec.d.ts +101 -1
- package/lib/types/math/figure/items/ml.d.ts +47 -0
- package/lib/types/math/index.d.ts +7 -0
- package/lib/types/math/ml/classify.d.ts +30 -0
- package/lib/types/math/ml/colormap.d.ts +14 -0
- package/lib/types/math/ml/contours.d.ts +15 -0
- package/lib/types/math/ml/descent.d.ts +11 -0
- package/lib/types/math/ml/kmeans.d.ts +11 -0
- package/lib/types/math/ml/network.d.ts +19 -0
- package/lib/types/math/presets/ml.d.ts +50 -0
- package/llms-full.txt +64 -16
- package/llms.txt +31 -31
- package/package.json +1 -1
- package/skills/tinyfly/SKILL.md +2 -1
|
@@ -59,7 +59,7 @@ ${s.map(i=>` ${i.beat>=0?`beat ${i.beat}: `:""}${i.message}`).join(`
|
|
|
59
59
|
${i.map(d=>` ${d.beat>=0?`beat ${d.beat}: `:""}${d.message}`).join(`
|
|
60
60
|
`)}`);const r=n.map(d=>Hm(d,e)),o=Ro(t,r,s),a=bx(r,o.beats,s),l=s.ground??0,c=d=>s.ride===!1?d:Object.values(e).reduce((f,p)=>p.ride(f,t,{ground:l}),d);n.forEach((d,f)=>{for(const p of mx(d)){const g=w=>new Error(`surfaceScript: beat ${f} (${d.do}), ${p.edit} on ${p.surface}: ${w}`),m=(w,T)=>{const A=typeof w=="object"?w.beat:f,M=(typeof w=="object"?w.at:w)??T??"start",x=a[A][M];if(x===void 0){const S=Es.filter(E=>a[A][E]!==void 0).join(", ");throw g(`beat ${A} (${n[A].do}) has no ${M} (it has ${S})`)}return x},y=e[p.surface],v=m(p.at??(a[f].contact!==void 0?"contact":"start")),k=p.until===void 0?void 0:m(p.until,"end");if(k!==void 0&&k<v)throw g(`it ends (${k} ms) before it starts (${v} ms)`);try{if(p.edit==="carry"){const T=y.piece(p.anchor),A=hh(t,c(o.tracks),{x:s.from??0,y:l,style:s.figureStyle??(s.height?{height:s.height}:void 0),cast:s,start:v,end:k});y.follow(T,A);continue}const w=Object.fromEntries(Object.entries(p).filter(([T])=>!gx.includes(T)));y.edit(p.edit,p.anchor,{...w,at:v,...k!==void 0?{duration:k-v}:{}})}catch(w){throw g(w.message)}}});const h=c(o.tracks),u=Object.entries(e).flatMap(([d,f])=>f.tracks(d));return{...o,tracks:[...h,...u],figureTracks:h}}function _m(t,e,n={}){if(!Array.isArray(t))return Bi(t,n);const s=[],i=Object.keys(e),r=(c,h,u)=>{const d=typeof h=="string"?e[h]:void 0;return d||s.push({level:"error",beat:c,message:`${u}: ${ft("surface",h,i)}`}),d},o=(c,h,u,d)=>{if(typeof u!="string"){s.push({level:"error",beat:c,message:`${d}: \`anchor\` is a place name such as ${Object.keys(h.about.anchors).join(", ")} (got ${JSON.stringify(u)}).`});return}try{h.anchor(u,0)}catch(f){s.push({level:"error",beat:c,message:`${d}: ${f.message}`})}},a=(c,h,u)=>{const d=typeof h=="object"&&h!==null?h.at:h;if(typeof h=="object"&&h!==null){const f=h.beat;if((typeof f!="number"||!Number.isInteger(f)||f<c||f>=t.length)&&s.push({level:"error",beat:c,message:`${u}: \`beat\` is the index of this beat or a later one, ${c} to ${t.length-1} (got ${JSON.stringify(f)}).`}),d===void 0)return}typeof d=="number"?s.push({level:"error",beat:c,message:`${u}: a cue starts at a moment of its beat (${Es.join(", ")}), not at ms; set the beat's own \`at\` to move it.`}):(typeof d!="string"||!Es.includes(d))&&s.push({level:"error",beat:c,message:`${u}: ${ft("moment",d,Es)}`})};t.forEach((c,h)=>{if(!c||typeof c!="object"||Array.isArray(c))return;const u=c;for(const f of["target","to","onto"]){if(!Fo(u[f]))continue;const p=u[f],g=r(h,p.surface,`\`${f}\``);g&&o(h,g,p.anchor,`\`${f}\``)}if(u.then===void 0)return;(Array.isArray(u.then)?u.then:[u.then]).forEach(f=>{if(!f||typeof f!="object"||Array.isArray(f)){s.push({level:"error",beat:h,message:"`then` is a cue, { surface, edit, anchor, at?, until? }, or a list of them."});return}const p=f,g=r(h,p.surface,"`then`");if(!g)return;const m=`\`then\` (${String(p.edit)} on ${String(p.surface)})`,y=[...Object.keys(g.about.edits),...px];if(typeof p.edit!="string"||!y.includes(p.edit)){s.push({level:"error",beat:h,message:`\`then\`: ${ft("edit",p.edit,y)}`});return}for(const v of Array.isArray(p.anchor)?p.anchor:[p.anchor])o(h,g,v,m);p.edit==="carry"&&typeof p.anchor!="string"&&s.push({level:"error",beat:h,message:`${m}: \`carry\` takes one anchor, the piece it carries.`}),p.edit==="carry"&&p.until===void 0&&s.push({level:"error",beat:h,message:`${m}: \`carry\` needs \`until\` (when it lets go, such as { beat: ${h+1}, at: 'release' }).`}),p.at!==void 0&&a(h,p.at,`${m} \`at\``),p.until!==void 0&&a(h,p.until,`${m} \`until\``),p.until!==void 0&&p.duration!==void 0&&s.push({level:"error",beat:h,message:`${m}: give \`until\` or \`duration\`, not both.`})})});const l=t.map(c=>c&&typeof c=="object"&&!Array.isArray(c)?Hm(c,e,!0):c);return[...Bi(l,n),...s]}function Hm(t,e,n=!1){const{then:s,...i}=t,r=a=>{try{return e[a.surface].anchor(a.anchor,0)}catch(l){if(n)return{x:0,y:0,left:0,right:0,top:0,bottom:0,width:0,height:0};throw l}},o={...i};return Fo(t.target)&&(o.target=r(t.target)),Fo(t.to)&&(o.to=r(t.to).x),Fo(t.onto)&&(o.onto=r(t.onto).top),o}function bx(t,e,n){let s=0;return t.map(i=>{const r=_o([i],n.actions).length,o=e.slice(s,s+r);s+=r;const a=o.find(c=>c.contact!==void 0)?.contact,l=[...o].reverse().find(c=>c.release!==void 0)?.release;return{start:o[0]?.start,end:o[o.length-1]?.end,...a!==void 0?{contact:a}:{},...l!==void 0?{release:l}:{}}})}function wx(t){const e={actions:t.actions,gaits:t.gaits},n=Qc(e);if(n.length>0)throw new Error(`persona "${t.name}": ${n.join(" ")}`);const s=[...Object.keys(Xt),...Object.keys(t.gaits??{})],i=t.gait??"walk";if(!s.includes(i))throw new Error(`persona "${t.name}": ${ft("gait",i,s)}`);if(t.mood&&!(t.mood in vt))throw new Error(`persona "${t.name}": ${ft("mood",t.mood,Object.keys(vt))}`);const r=t.acting??"snappy";if(typeof r=="string"&&!(r in Fn))throw new Error(`persona "${t.name}": ${ft("acting style",r,Object.keys(Fn))}`);if(typeof t.stance=="string"&&!(t.stance in ae))throw new Error(`persona "${t.name}": ${ft("stance",t.stance,Object.keys(ae))}`);const o=t.height??120,a=typeof t.stance=="string"?ae[t.stance]:Dt(t.stance??{}),l=t.mood?Je(a,t.mood):a,c={...t.look,height:o},h=t.summary??`${t.name}, a stick figure`;return{name:t.name,summary:h,cast:e,rest:l,height:o,figure:u=>Ml({x:u.x,y:u.y,pose:l,style:{...c,...u.facing?{facing:u.facing}:{}},cast:e}),script:(u,d,f={})=>Ro(u,d,{...e,from:f.from,ground:f.ground,facing:f.facing,height:o,style:r,gait:i,start:l,rest:l,energy:t.energy}),check:u=>Bi(u,e),handPath:(u,d,f)=>hh(u,d,{...f,style:c,cast:e}),describe:()=>({name:t.name,summary:h,habits:{height:o,acting:typeof r=="string"?r:"custom",gait:i,...t.mood?{mood:t.mood}:{},stance:typeof t.stance=="string"?t.stance:t.stance?"custom":"rest"},actions:th(e),own:{actions:Object.keys(t.actions??{}),gaits:Object.keys(t.gaits??{})}})}}const kx=new Set(["x","y","walking","gait"]),Rm=.215+.205;function Fm(t,e,n=1){const{points:s}=fe(t,lt),i=s["hip.left"],r=s["knee.left"],o=s["ankle.left"],a=i&&r&&o?Math.hypot(r.x-i.x,r.y-i.y)+Math.hypot(o.x-r.x,o.y-r.y):Rm*t.height;return io(e,a/Rm,n)}function vx(t,e,n,s={}){const i=Ro(t,n,{...s,height:e.height,reach:s.reach??Lm(e)}),r=i.tracks.find(y=>y.property==="facing")?.keyframes??[],o=y=>{let v=s.facing??1;for(const k of r)k.time<=y&&(v=k.value);return v},a=_r(i.keys),l=i.keys.map((y,v)=>{const k=ip(a[v]);return{time:y.time,pose:o(y.time)<0?kf(k):k,...y.easing?{easing:y.easing}:{},...y.act===!1?{act:!1}:{}}}),{rest:c,start:h,...u}=s;xx(l,a,n,i,e,o,s);const d=dm(t,l,u),f=ko(t,d,i.lines,{energy:s.energy}),p=i.tracks.filter(y=>kx.has(y.property)),g=i.tracks.find(y=>y.property==="walk");return{tracks:g?[...f,...p,Ix(t,g,i.tracks,e,s)]:[...f,...p],duration:i.duration,lines:i.lines,keys:l,beats:i.beats,effects:i.effects}}function Lm(t){const e=kt({"arm.left.spread":90,"arm.left.elbow":0,"arm.left.bend":0,"leg.left.knee":0}),n=fe(t,e).points,s=Math.hypot(n["hand.left"].x-n["shoulder.left"].x,n["hand.left"].y-n["shoulder.left"].y),i=Math.hypot(n["toe.left"].x-n["hip.left"].x,n["toe.left"].y-n["hip.left"].y),r=ye({...ut,rightShoulder:90,rightElbow:0,rightWrist:0},{height:t.height,facing:1}),o=ye({...ut,rightHip:90,rightKnee:0},{height:t.height,facing:1}),a={x:(r.hands.right.x+r.fingertips.right.x)/2,y:(r.hands.right.y+r.fingertips.right.y)/2},l=Math.hypot(a.x-r.shoulders.right.x,a.y-r.shoulders.right.y),c=Math.hypot(o.feet.right.x-o.hip.x,o.feet.right.y-o.hip.y);return{arm:l>0?s/l:1,leg:c>0?i/c:1}}const Mx={point:"arm",grab:"arm",put:"arm",write:"arm",swipe:"arm",push:"arm",kick:"leg"},Sx=new Set(["point","grab","put","kick"]);function xx(t,e,n,s,i,r,o){const a=s.beats;if(n.length!==a.length)return;const l=new Ht({id:"placed",tracks:s.tracks.filter(h=>h.property==="x"||h.property==="y")}),c=h=>{const u=l.getStateAtTime(h).values.get(s.tracks[0]?.target??"");return{x:(o.from??0)+Number(u?.get("x")??0),y:(o.ground??0)+Number(u?.get("y")??0)}};n.forEach((h,u)=>{const d=Mx[h.do],f=a[u];if(!d||f.contact===void 0||h.do!=="swipe"&&!h.target)return;const p=f.contact,g=f.release??f.contact;t.forEach((m,y)=>{if(m.time<p-1||m.time>g+1)return;const v=r(m.time),k=ye(e[y],{height:i.height,facing:v<0?-1:1}),w=c(m.time),T=Sx.has(h.do)&&h.target?{x:h.target.x-w.x,y:h.target.y-w.y}:void 0,A={x:(k.hands.right.x+k.fingertips.right.x)/2,y:(k.hands.right.y+k.fingertips.right.y)/2},M=T??(d==="arm"?A:k.toes.right),x=v<0?"right":"left",S=`${d}.${x}`;let E=m.pose;if(h.do==="point")E=He(i,E,S,M);else if(d==="arm")E=He(i,$x(i,E,x,M),S,M);else for(let P=0;P<3;P++){const I=fe(i,E).points,O=I[`ankle.${x}`],H=I[`toe.${x}`];E=He(i,E,S,{x:M.x-(H.x-O.x),y:M.y-(H.y-O.y)})}t[y]={...m,pose:E}})})}function Tx(t,e){const n=kt({[`arm.${e}.spread`]:90,[`arm.${e}.elbow`]:0,[`arm.${e}.bend`]:0}),s=fe(t,n).points;return Math.hypot(s[`hand.${e}`].x-s[`shoulder.${e}`].x,s[`hand.${e}`].y-s[`shoulder.${e}`].y)}const Ex=5,Ax=4,Px=8;function $x(t,e,n,s){const i=Tx(t,n)*.9,r=a=>{const l=fe(t,a).points[`shoulder.${n}`];return Math.hypot(s.x-l.x,s.y-l.y)<=i};if(r(e))return e;let o=e;for(let a=1;a<=Px;a++)if(o={...e,lean:(e.lean??0)+Ex*a,bend:(e.bend??0)+Ax*a},r(o))return o;return o}function Ix(t,e,n,s,i){const r=n.find(u=>u.property==="gait"),o=r?new Ht({id:`${t}-gait-of`,tracks:[r]}):void 0,a=u=>{const d=o?.getStateAtTime(u).values.get(t)?.get("gait");if(typeof d=="string")return Xt[d]??i.gaits?.[d]??d},l=e.keyframes,c=[];let h=l[0]?.value??0;return l.forEach((u,d)=>{if(d>0){const f=l[d-1],p=a((f.time+u.time)/2),g=Ir(p,s.height),m=Fm(s,p);h+=(u.value-f.value)*(m>0?g/m:1)}else h=u.value;c.push({...u,value:h})}),{...e,keyframes:c}}const mt=["rect","circle","text","line","path","image","custom"],Lo={x:{description:"Moves it right by this much from where it was placed (an offset; the target’s own x is its place)",unit:"px",types:mt},y:{description:"Moves it down by this much from where it was placed (an offset)",unit:"px",types:mt},opacity:{description:"How opaque it is",unit:"0..1",min:0,max:1,types:mt},rotate:{description:"Turns it clockwise about its origin",unit:"degrees",types:mt},rotateX:{description:"Tips it about the horizontal axis (3D; shows with perspective)",unit:"degrees",types:mt},rotateY:{description:"Turns it about the vertical axis (3D; shows with perspective)",unit:"degrees",types:mt},z:{description:"Depth toward the viewer (shows with perspective)",unit:"px",types:mt},perspective:{description:"Distance from the viewer: nearer parts grow, further ones shrink",unit:"px",min:1,types:mt},scale:{description:"Size, both ways",unit:"factor",types:mt},scaleX:{description:"Width factor",unit:"factor",types:mt},scaleY:{description:"Height factor",unit:"factor",types:mt},skewX:{description:"Slants it sideways",unit:"degrees",types:mt},skewY:{description:"Slants it up and down",unit:"degrees",types:mt},originX:{description:"Transform pivot across its box",unit:"% (0 left, 50 centre, 100 right)",min:0,max:100,types:mt},originY:{description:"Transform pivot down its box",unit:"% (0 top, 50 centre, 100 bottom)",min:0,max:100,types:mt},fill:{description:"Fill colour (also written fillStyle)",kind:"color",types:mt},stroke:{description:"Outline colour (also written strokeStyle)",kind:"color",types:mt},strokeWidth:{description:"Outline width (also written lineWidth)",unit:"px",min:0,types:mt},clipTop:{description:"Hides this much from the top edge, for reveals",unit:"% of its height",min:0,max:100,types:mt},clipRight:{description:"Hides this much from the right edge",unit:"% of its width",min:0,max:100,types:mt},clipBottom:{description:"Hides this much from the bottom edge",unit:"% of its height",min:0,max:100,types:mt},clipLeft:{description:"Hides this much from the left edge",unit:"% of its width",min:0,max:100,types:mt},blur:{description:"Gaussian blur",unit:"px",min:0,types:mt},brightness:{description:"Brightness factor (1 unchanged)",unit:"factor",min:0,types:mt},glow:{description:"Soft glow around it, in glowColor",unit:"px",min:0,types:mt},glowColor:{description:"Colour of the glow",kind:"color",types:mt},shadowX:{description:"Drop shadow offset right",unit:"px",types:mt},shadowY:{description:"Drop shadow offset down",unit:"px",types:mt},shadowBlur:{description:"Drop shadow softness",unit:"px",min:0,types:mt},shadowColor:{description:"Drop shadow colour",kind:"color",types:mt},shine:{description:"A highlight sweeping across the fill",unit:"0..1 (progress)",min:0,max:1,types:mt},drawOn:{description:"How much of the outline is drawn, for drawing a shape on; the fill appears when it is complete",unit:"0..1",min:0,max:1,types:["rect","circle","line","path"]},width:{description:"Box width",unit:"px",min:0,types:["rect","image"]},height:{description:"Box height",unit:"px",min:0,types:["rect","image"]},borderRadius:{description:"Rounded corners",unit:"px",min:0,types:["rect","image"]},radius:{description:"Circle radius",unit:"px",min:0,types:["circle"]},x2:{description:"Line end, x",unit:"px",types:["line"]},y2:{description:"Line end, y",unit:"px",types:["line"]},d:{description:"SVG path data; tween between paths to morph",kind:"string",types:["path"]},text:{description:"The text shown (a text track types or scrambles it)",kind:"string",types:["text"]},fontSize:{description:"Font size",unit:"px",min:0,types:["text"]},fontWeight:{description:"Font weight",unit:"100..900",min:100,max:900,types:["text"]},motionPath:{description:"Moves it along an SVG path (a motion-path track writes motionPathX/Y and, aligned, rotate)",kind:"string",types:mt},quaternion:{description:'A rotation as [x, y, z, w] (a track with interpolation: "slerp")',kind:"list",types:mt}},uh={fillStyle:"fill",strokeStyle:"stroke",lineWidth:"strokeWidth",rotateZ:"rotate",motionPathX:"x",motionPathY:"y",motionPathRotate:"rotate"},Ox={rotation:"rotate",angle:"rotate",alpha:"opacity",fade:"opacity",color:"fill",colour:"fill",background:"fill",size:"scale",left:"x",top:"y",translateX:"x",translateY:"y",r:"radius",path:"d",content:"text"};function Nm(t){const e=t,n=Object.entries(Lo).filter(([,i])=>i.types.includes(t.type)).map(([i,{types:r,...o}])=>({name:i,...o,...e[i]!==void 0&&typeof e[i]!="object"?{value:e[i]}:{}}));if(t.type!=="custom")return{type:t.type,properties:n};const s=t.about;for(const[i,r]of Object.entries(t.props??{}))n.push({name:i,description:s?.props?.[i]?.description??"",...s?.props?.[i],value:r});return{type:"custom",...s?{kind:s.kind,summary:s.summary}:{},properties:n,...s?.actions?{actions:s.actions}:{}}}function Wm(t){const e=Nm(t).properties.map(n=>n.name);return[...e,...Object.keys(uh).filter(n=>e.includes(uh[n]))]}function Cx(t,e){const n=[],s=Object.keys(e);for(const i of t){const r=d=>n.push({level:"error",track:i.id,message:d}),o=e[i.target];if(!o){r(ft("target",i.target,s));continue}const a=Wm(o),l=o.type==="custom"&&o.acceptsProp?.(i.property);if(!a.includes(i.property)&&!l){r(`${i.target}: ${ft("property",i.property,a,Ox[i.property])}`);continue}const c=i.keyframes??[];for(let d=1;d<c.length;d++)c[d].time<c[d-1].time&&r(`${i.target}.${i.property}: keyframes out of time order (${c[d-1].time} ms, then ${c[d].time} ms).`);const h=Lo[uh[i.property]??i.property]??o.about?.props?.[i.property],u=h&&(h.kind??"number")==="number";for(const d of c){if(u&&typeof d.value!="number"){r(`${i.target}.${i.property}: values are numbers${h.unit?` (${h.unit})`:""} (got ${JSON.stringify(d.value)} at ${d.time} ms).`);break}if(u&&typeof d.value=="number"&&(h.min!==void 0&&d.value<h.min||h.max!==void 0&&d.value>h.max)){n.push({level:"warning",track:i.id,message:`${i.target}.${i.property}: ${d.value} at ${d.time} ms is outside ${h.min??"−∞"}..${h.max??"∞"}${h.unit?` (${h.unit})`:""}.`});break}}}return n}const As=(t,e)=>t[2]<=-e;function dh(t,e,n){const s=(-n-t[2])/(e[2]-t[2]);return[t[0]+(e[0]-t[0])*s,t[1]+(e[1]-t[1])*s,-n]}function Dm(t,e){if(t.every(s=>As(s,e)))return t;const n=[];return t.forEach((s,i)=>{const r=t[(i+t.length-1)%t.length],o=As(s,e),a=As(r,e);o!==a&&n.push(dh(r,s,e)),o&&n.push(s)}),n.length>=3?n:[]}function _x(t,e){if(t.every(i=>As(i,e)))return[t];const n=[];let s=[];return t.forEach((i,r)=>{const o=As(i,e);if(r>0){const a=t[r-1],l=As(a,e);l&&!o?(s.push(dh(a,i,e)),n.push(s),s=[]):!l&&o&&s.push(dh(a,i,e))}o&&s.push(i)}),s.length>0&&n.push(s),n.filter(i=>i.length>=2)}function Bm(t,e,n){const s=e-t;if(!(s>=n*1.5))return[t,e];const i=Math.round(s/n);return Array.from({length:i+1},(r,o)=>t+s*o/i)}function Hx(t,e,n){const s=(i,r)=>Math.max(0,Math.min(i.length-2,i.findIndex((o,a)=>a>0&&r<=o)-1));return[s(t,n[0]),s(e,n[2])]}function Rx(t,e){const n=s=>{const i=[e[0]*s[0]+e[4]*s[1]+e[8]*s[2],e[1]*s[0]+e[5]*s[1]+e[9]*s[2],e[2]*s[0]+e[6]*s[1]+e[10]*s[2]],r=Math.hypot(...i)||1;return[i[0]/r,i[1]/r,i[2]/r]};return{...t,vertices:t.vertices.map(s=>ie(e,s)),faces:t.faces.map(s=>({corners:s.corners,normal:n(s.normal)}))}}function No(t,e,n,s){const i=o=>(o[e]-n)*s>=0;if(t.every(i))return t;const r=[];return t.forEach((o,a)=>{const l=t[(a+t.length-1)%t.length];if(i(o)!==i(l)){const c=(n-l[e])/(o[e]-l[e]);r.push([0,1,2].map(h=>h===e?n:l[h]+(o[h]-l[h])*c))}i(o)&&r.push(o)}),r.length>=3?r:[]}function Fx(t,e,n){const s=t.faces.map(o=>({points:o.corners.map(a=>t.vertices[a]),normal:o.normal})),i=[],r={x:e.slice(1,-1),z:n.slice(1,-1)};for(let o=0;o+1<e.length;o++)for(let a=0;a+1<n.length;a++){const l=[],c=new Map,h=p=>{const g=p.map(y=>Math.round(y*1e6)).join(",");let m=c.get(g);return m===void 0&&(m=l.length,l.push(p),c.set(g,m)),m},u=[],d=p=>p===0,f=(p,g)=>p+2===g.length;for(const p of s){let g=p.points;d(o)||(g=No(g,0,e[o],1)),g.length&&!f(o,e)&&(g=No(g,0,e[o+1],-1)),g.length&&!d(a)&&(g=No(g,2,n[a],1)),g.length&&!f(a,n)&&(g=No(g,2,n[a+1],-1)),g.length>=3&&u.push({corners:g.map(h),normal:p.normal})}u.length>0&&i.push({cell:[o,a],mesh:{vertices:l,faces:u,creases:t.creases,joined:t.joined,walls:r}})}return i}const Lx=new WeakMap,Nx=new WeakMap,Wx=48,zm=t=>t.map(e=>Math.round(e*1e5)).join(",");function qm(t,e,n,s){let i=t.get(e);i||t.set(e,i=new Map);let r=i.get(n);return r===void 0&&(i.size>=Wx&&i.clear(),i.set(n,r=s())),r}function fh(t,e){const n=zm(e);return qm(Lx,t,n,()=>{const s=Rx(t,e),i=[1/0,1/0,1/0],r=[-1/0,-1/0,-1/0];for(const o of s.vertices)for(const a of[0,1,2])i[a]=Math.min(i[a],o[a]),r[a]=Math.max(r[a],o[a]);return{key:n,inSpace:s,low:i,high:r}})}function Dx(t,e){const n=t.map(h=>({...h,...fh(h.mesh,h.local)})),s=[1/0,1/0,1/0],i=[-1/0,-1/0,-1/0];for(const h of n)for(const u of[0,1,2])s[u]=Math.min(s[u],h.low[u]),i[u]=Math.max(i[u],h.high[u]);const r=Bm(s[0],i[0],e),o=Bm(s[2],i[2],e),a=`${r.join(",")}|${o.join(",")}`,l=n.flatMap(h=>{if(h.high[0]-h.low[0]<=e*2.5&&h.high[2]-h.low[2]<=e*2.5||h.whole||h.mesh.joined||(h.mesh.marks?.length??0)>0){const d=[(h.low[0]+h.high[0])/2,(h.low[1]+h.high[1])/2,(h.low[2]+h.high[2])/2];return[{part:h.part,mesh:h.mesh,cut:!1,cell:Hx(r,o,d)}]}return qm(Nx,h.inSpace,a,()=>Fx(h.inSpace,r,o)).map(d=>({part:h.part,mesh:d.mesh,cut:!0,cell:d.cell}))}),c=(s[1]+i[1])/2;return{pieces:l,middle:([h,u])=>[(r[h]+r[h+1])/2,c,(o[u]+o[u+1])/2]}}const jm=.004,gh=.05,Ym=new WeakMap;function Bx(t){let e=Ym.get(t);return e===void 0&&(e=!t.joined&&!t.walls&&t.faces.length>=4&&t.faces.every(n=>{const s=t.vertices[n.corners[0]];return t.vertices.every(i=>n.normal[0]*(i[0]-s[0])+n.normal[1]*(i[1]-s[1])+n.normal[2]*(i[2]-s[2])<=1e-6)}),Ym.set(t,e)),e}const Km=new WeakMap;function Xm(t){return t.filter(({mesh:e})=>Bx(e)).map(({part:e,key:n,inSpace:s,low:i,high:r})=>{let o=Km.get(s);return o||(o=s.faces.map(a=>{const l=s.vertices[a.corners[0]];return{normal:a.normal,offset:a.normal[0]*l[0]+a.normal[1]*l[1]+a.normal[2]*l[2]}}),Km.set(s,o)),{part:e,key:n,planes:o,low:i,high:r}})}function zx(t,e,n,s){const i=e.reduce((r,o)=>[r[0]+o[0]/e.length,r[1]+o[1]/e.length,r[2]+o[2]/e.length],[0,0,0]);for(const r of s){if(r.part===t||[0,1,2].some(a=>i[a]<r.low[a]-gh||i[a]>r.high[a]+gh))continue;if(r.planes.every(a=>{const l=a.normal[0]*n[0]+a.normal[1]*n[1]+a.normal[2]*n[2],c=e.map(u=>a.normal[0]*u[0]+a.normal[1]*u[1]+a.normal[2]*u[2]-a.offset);if(c.every(u=>Math.abs(u)<=jm))return l<-.9;const h=Math.abs(l)<.5?gh:jm;return c.every(u=>u<=h)}))return!0}return!1}const Gm=new WeakMap;function Um(t,e,n,s,i){const r=`${s}|${i.map(l=>l.key).join(";")}`;let o=Gm.get(e);o||Gm.set(e,o=new Map);let a=o.get(r);if(!a){o.size>=48&&o.clear();const l=h=>{const u=[n[0]*h[0]+n[4]*h[1]+n[8]*h[2],n[1]*h[0]+n[5]*h[1]+n[9]*h[2],n[2]*h[0]+n[6]*h[1]+n[10]*h[2]],d=Math.hypot(...u)||1;return[u[0]/d,u[1]/d,u[2]/d]},c=e.vertices.map(h=>ie(n,h));a=e.faces.map(h=>zx(t,h.corners.map(u=>c[u]),l(h.normal),i)),o.set(r,a)}return a}const Ps={turn:{description:"Which way it faces: 0 toward the viewer, 1 screen-right, 2 away, 3 (or −1) screen-left; in between turns it in 3D",unit:"quarter turns"},tilt:{description:"How far the camera looks down on it: 0 level, 12 the ¾ look, 90 straight down",unit:"degrees",default:12,min:-90,max:90},pitch:{description:"Nose up (+) or down (−), about its middle on the ground",unit:"degrees"},roll:{description:"Tipped onto its right (+) or left (−) side",unit:"degrees"},squash:{description:"Squash and stretch about the ground, keeping its volume: 1 normal, below squashed, above stretched",unit:"factor",default:1,min:.3,max:3},lift:{description:"Off the ground",unit:"metres"},lean:{description:"The top sheared forward (+) or back (−): speed and drag",unit:"shear"},size:{description:"Its size, about the ground: 1 as built, 0 gone (pop it in or out)",unit:"factor",default:1,min:0}},ph=Math.PI/180;function Vm(t,e,n){return{toView:s=>Ol(Qt(s,t*90*ph),-e*ph),toScreen:s=>({x:s[0]*n,y:-s[1]*n})}}const Jm=new WeakMap,qi=t=>Wo(t),Wo=t=>{let e=Jm.get(t);return e||Jm.set(t,e=$p(t)),e};function It(t,e,n){return e[n]??t.controls[n]?.default??Ps[n]?.default??0}function ji(t,e){const n=Math.max(.05,It(t,e,"squash")),s=1/Math.sqrt(n),r=[1,0,0,0,0,1,It(t,e,"lean"),0,0,0,1,0,0,0,0,1];return[wn([0,It(t,e,"lift"),0]),me(Vt([1,0,0],-It(t,e,"pitch"))),me(Vt([0,0,1],It(t,e,"roll"))),r,kn([s,n,s]),kn(Array(3).fill(Math.max(0,It(t,e,"size"))))].reduce((o,a)=>Rt(o,a))}function mh(t,e){const n=ji(t,e),s=new Map,i=Object.entries(t.controls).flatMap(([o,a])=>(a.bind??[]).map(l=>({value:It(t,e,o),bind:l}))),r=o=>{const a=s.get(o.id);if(a)return a;const l=o.parent?t.parts.find(h=>h.id===o.parent):void 0;if(o.parent&&!l)throw new Error(`prop rig: part "${o.id}" hangs from "${o.parent}", which is not a part`);let c=Rt(l?r(l):n,wn(o.at??[0,0,0]));if(o.rotate){const[h,u,d]=o.rotate;h&&(c=Rt(c,me(Vt([1,0,0],h)))),u&&(c=Rt(c,me(Vt([0,1,0],u)))),d&&(c=Rt(c,me(Vt([0,0,1],d))))}for(const{value:h,bind:u}of i)if(!(!u.parts.includes(o.id)||h===0)){if(u.translate&&(c=Rt(c,wn([u.translate[0]*h,u.translate[1]*h,u.translate[2]*h]))),u.rotate){const d=u.rotate.pivot??[0,0,0],f=u.rotate.axis==="x"?[1,0,0]:u.rotate.axis==="y"?[0,1,0]:[0,0,1];c=[c,wn(d),me(Vt(f,u.rotate.degrees*h)),wn([-d[0],-d[1],-d[2]])].reduce((p,g)=>Rt(p,g))}u.scale&&(c=Rt(c,kn([1+(u.scale[0]-1)*h,1+(u.scale[1]-1)*h,1+(u.scale[2]-1)*h])))}return s.set(o.id,c),c};for(const o of t.parts)r(o);return s}const yh=(()=>{const t=[-.45,.75,.5],e=Math.hypot(...t);return[t[0]/e,t[1]/e,t[2]/e]})(),qx=Math.cos(35*ph);function bh(t,e,n,s,i={}){const r=t.derive?{...e,...t.derive(e)}:e,o=mh(t,r),a=n.toView([0,0,0]),l=H=>W=>[H[0]*W[0]+H[4]*W[1]+H[8]*W[2],H[1]*W[0]+H[5]*W[1]+H[9]*W[2],H[2]*W[0]+H[6]*W[1]+H[10]*W[2]],c=ji(t,r),h=i.slice===void 0?null:Fa(c),u=h?t.parts.map(H=>({part:H,mesh:Wo(H.shape),local:Rt(h,o.get(H.id)),whole:H.shape.type==="tube"})):void 0,d=u?Dx(u,i.slice):void 0,f=u?Xm(u.map(H=>({part:H.part.id,mesh:H.mesh,...fh(H.mesh,H.local)}))):void 0,p=(H,W,j,J)=>{const et=Q=>n.toView(ie(j,Q)),V=W.vertices.map(et),F=V.map(Q=>n.toScreen(Q)),B=i.perspective?i.near:void 0,K=Q=>Q.map(ot=>n.toScreen(ot)),_=Q=>B===void 0?Q:Dm(Q,B),Y=Q=>B===void 0?[Q]:_x(Q,B),st=l(j),$=W.faces.map(Q=>{const ot=n.toView(st(Q.normal)),ht=[ot[0]-a[0],ot[1]-a[1],ot[2]-a[2]],dt=Math.hypot(...ht)||1;return[ht[0]/dt,ht[1]/dt,ht[2]/dt]}),C=f&&J?Um(H.id,W,J,zm(J),f):void 0,z=Q=>C?.[Q]??!1,X=$.map((Q,ot)=>{if(z(ot))return!1;if(!i.perspective)return Q[2]>1e-6;const dt=W.faces[ot].corners.reduce((bt,wt)=>[bt[0]+V[wt][0],bt[1]+V[wt][1],bt[2]+V[wt][2]],[0,0,0]);return-(Q[0]*dt[0]+Q[1]*dt[1]+Q[2]*dt[2])>1e-9}),N=Q=>W.faces[Q].corners.reduce((ot,ht)=>ot+V[ht][2],0)/W.faces[Q].corners.length,L=W.faces.map((Q,ot)=>({face:Q,i:ot})).filter(({i:Q})=>X[Q]).map(({face:Q,i:ot})=>({i:ot,solved:{points:B===void 0?Q.corners.map(ht=>F[ht]):K(_(Q.corners.map(ht=>V[ht]))),depth:N(ot),tone:.72+.33*Math.max(0,$[ot][0]*yh[0]+$[ot][1]*yh[1]+$[ot][2]*yh[2])}})).filter(Q=>Q.solved.points.length>=3).sort((Q,ot)=>Q.solved.depth-ot.solved.depth);if(i.light){const Q=l(j);for(const{i:ot,solved:ht}of L){const dt=W.faces[ot].corners,bt=dt.reduce((Kh,GT)=>{const Xh=ie(j,W.vertices[GT]);return[Kh[0]+Xh[0]/dt.length,Kh[1]+Xh[1]/dt.length,Kh[2]+Xh[2]/dt.length]},[0,0,0]),wt=Q(W.faces[ot].normal),pe=Math.hypot(...wt)||1,Ji=i.light(bt,[wt[0]/pe,wt[1]/pe,wt[2]/pe]);ht.light=Ji.light,ht.fog=Ji.fog}}const D=L.map(Q=>Q.solved),G=jx(W),q=[],Z=[];for(const[Q,ot]of G){const ht=ot.filter(bt=>X[bt]).length;if(ht===0)continue;const dt=ot.length===2&&ht===2&&W.creases!==!1&&$[ot[0]][0]*$[ot[1]][0]+$[ot[0]][1]*$[ot[1]][1]+$[ot[0]][2]*$[ot[1]][2]<qx;ot.length===1&&(W.joined||Yx(W,Q))||(ot.length===1||ht===1||dt)&&(q.push(Q.split("-").map(Number)),Z.push(ot.filter(bt=>X[bt]).reduce((bt,wt)=>N(wt)>N(bt)?wt:bt)))}const tt=Q=>W.faces.findIndex(ot=>ot.corners.length>4&&Math.sign(Xx(W.vertices[Q],ot.normal))>0),R=(W.marks??[]).filter(([Q])=>tt(Q)<0||X[tt(Q)]),U=([Q,ot])=>B===void 0?[[F[Q],F[ot]]]:Y([V[Q],V[ot]]).map(K),nt=R.flatMap(U),at=Q=>B===void 0?[Q.map(ot=>F[ot])]:Y(Q.map(ot=>V[ot])).map(K);if(i.slice!==void 0){const Q=new Map;q.forEach((ot,ht)=>Q.set(Z[ht],[...Q.get(Z[ht])??[],ot]));for(const{i:ot,solved:ht}of L){ht.edges=ey(Q.get(ot)??[]).flatMap(at);const dt=W.faces[ot].corners;ht.center=dt.reduce((wt,pe)=>[wt[0]+V[pe][0]/dt.length,wt[1]+V[pe][1]/dt.length,wt[2]+V[pe][2]/dt.length],[0,0,0]),ht.normal=$[ot];const bt=L[L.length-1].i;ht.marks=R.filter(([wt])=>(tt(wt)>=0?tt(wt):bt)===ot).flatMap(U)}}const rt=H.glow?Math.max(0,Math.min(1,It(t,r,H.glow.control))):0,ct=H.fade?Math.max(0,Math.min(1,It(t,r,H.fade.control))):0,it=H.fade?Math.max(0,Math.min(1,H.fade.from+(H.fade.to-H.fade.from)*ct)):1;return{part:H,depth:V.reduce((Q,ot)=>Q+ot[2],0)/Math.max(1,V.length),faces:D,edges:ey(q).flatMap(at),marks:nt,glow:rt,opacity:it,...H.shape.type==="tube"?{spine:Kx(Y(H.shape.points.map(et)).map(K))}:{},...W.walls?{cut:!0}:{}}},g=new Map(u?.map(H=>[H.part.id,H.local])),y=(d?d.pieces.map(H=>({part:H.part,mesh:H.mesh,m:H.cut?c:o.get(H.part.id),local:H.cut?gr():g.get(H.part.id),cell:H.cell})):t.parts.map(H=>({part:H,mesh:Wo(H.shape),m:o.get(H.id),local:void 0,cell:void 0}))).map(H=>({cell:H.cell,solved:p(H.part,H.mesh,H.m,H.local)})),v=y.map(H=>H.solved),k=H=>H.filter(W=>W.faces.length>0&&W.opacity>.01).sort((W,j)=>W.depth-j.depth);let w;if(d){const H=new Map(t.parts.map(j=>{const J=o.get(j.id),et=Wo(j.shape).vertices;return[j.id,et.reduce((V,F)=>V+n.toView(ie(J,F))[2],0)/Math.max(1,et.length)]})),W=new Map;for(const j of y){const J=j.cell.join(",");W.has(J)||W.set(J,{cell:j.cell,parts:[]}),W.get(J).parts.push(j.solved),j.solved.depth=H.get(j.solved.part.id)}w=[...W.values()].map(({cell:j,parts:J})=>({depth:n.toView(ie(c,d.middle(j)))[2],parts:k(J)})).filter(j=>j.parts.length>0)}const T={};for(const[H,W]of Object.entries(t.anchors??{})){const j=W.part?o.get(W.part):ji(t,r);if(!j)throw new Error(`prop rig: anchor "${H}" is on "${W.part}", which is not a part`);const J=n.toView(ie(j,W.at));T[H]={point:n.toScreen(J),depth:J[2]}}const[A,M]=t.footprint??[t.length*.45,t.length],x=Math.max(0,It(t,r,"lift")),S=Math.max(0,It(t,r,"size"))/(1+x*.8),E=Array.from({length:24},(H,W)=>{const j=Math.PI*2*W/24;return n.toView([Math.cos(j)*A*.55*S,0,Math.sin(j)*M*.55*S])}),P=i.perspective?i.near:void 0,I={points:(P===void 0?E:Dm(E,P)).map(H=>n.toScreen(H)),opacity:.16*S},O=v.filter(H=>H.part.seeThrough&&H.opacity>.01).flatMap(H=>H.faces.map(W=>W.points));return{under:k(v.filter(H=>!H.part.overRider)),over:k(v.filter(H=>H.part.overRider)),...w?{cells:w}:{},anchors:T,openings:O,shadow:I,pxPerUnit:s,sizePx:t.height*s}}const Zm=new WeakMap;function jx(t){let e=Zm.get(t);if(!e){e=new Map;for(let n=0;n<t.faces.length;n++){const s=t.faces[n].corners;for(let i=0;i<s.length;i++){const r=s[i],o=s[(i+1)%s.length],a=r<o?`${r}-${o}`:`${o}-${r}`,l=e.get(a);l?l.push(n):e.set(a,[n])}}Zm.set(t,e)}return e}function Qm(t,e){const n=t.derive?{...e,...t.derive(e)}:e,s=mh(t,n),i=Fa(ji(t,n))??gr(),r=o=>Math.max(0,Math.min(1,o));return t.parts.map(o=>{const a=o.fade?r(It(t,n,o.fade.control)):0;return{part:o,matrix:s.get(o.id),local:Rt(i,s.get(o.id)),glow:o.glow?r(It(t,n,o.glow.control)):0,opacity:o.fade?r(o.fade.from+(o.fade.to-o.fade.from)*a):1}})}function ty(t,e){const n=t.derive?{...e,...t.derive(e)}:e,s=mh(t,n),i=ji(t,n),r={};for(const[o,a]of Object.entries(t.anchors??{})){const l=a.part?s.get(a.part):i;if(!l)throw new Error(`prop rig: anchor "${o}" is on "${a.part}", which is not a part`);r[o]=ie(l,a.at)}return r}function Yx(t,e){if(!t.walls)return!1;const[n,s]=e.split("-").map(r=>t.vertices[Number(r)]),i=(r,o)=>o.some(a=>Math.abs(n[r]-a)<1e-6&&Math.abs(s[r]-a)<1e-6);return i(0,t.walls.x)||i(2,t.walls.z)}function Kx(t){return t.reduce((e,n)=>!e||n.length>e.length?n:e,void 0)}const Xx=(t,e)=>t[0]*e[0]+t[1]*e[1]+t[2]*e[2];function ey(t){const e=t.map(s=>[...s]),n=[];for(;e.length>0;){const s=[...e.shift()];let i=!0;for(;i;){i=!1;for(let r=0;r<e.length;r++){const[o,a]=e[r],l=s[s.length-1],c=s[0];if(o===l)s.push(a);else if(a===l)s.push(o);else if(a===c)s.unshift(o);else if(o===c)s.unshift(a);else continue;e.splice(r,1),i=!0;break}}n.push(s)}return n}function wh(t,e){if(!t.loose?.size)return;const n={};for(const[s,i]of t.loose)n[s]={x:e[`piece.${i}.x`]??0,y:e[`piece.${i}.y`]??0,rotate:e[`piece.${i}.rotate`]??0,opacity:e[`piece.${i}.opacity`]??1};return n}function kh(t){const e={};for(const[n,s]of Object.entries({...Ps,...t.rig.controls})){const{bind:i,...r}=s;e[n]=r}return e}function ny(t){const{prop:e}=t,n=t.scale??60,s=e.rig.length*n*1.4,i=e.rig.height*n*1.6,r=kh(e),o={};for(const[l,c]of Object.entries(r))o[l]=t.values?.[l]??c.default??0;const a={look:t.look,ink:t.ink,lineWidth:t.lineWidth,pencil:t.pencil,seed:t.seed,style:t.style,paper:t.paper};return{type:"custom",x:t.x-s/2,y:t.y-i,width:s,height:i,props:o,prop:e,propScale:n,propDraw:a,about:{kind:e.kind,summary:e.summary,props:r,actions:Object.fromEntries(Object.entries(e.actions).map(([l,c])=>[l,c.summary]))},draw(l,c,h){const u=c.props??{};l.translate(s/2,i),bc(l,$s(e,u,n),{...a,time:h,loose:wh(c,u)})}}}function $s(t,e,n){const s=Vm(It(t.rig,e,"turn"),It(t.rig,e,"tilt"),n);return bh(t.rig,e,s,n)}function Do(t,e,n){const s={...t.props};let i=0,r=0;for(const[l,c]of e.state?.values.get(n)??[])typeof c=="number"&&(l==="x"?i=c:l==="y"?r=c:l in s&&(s[l]=c));const o={x:t.x+t.width/2+i,y:t.y+t.height+r},a=$s(t.prop,s,t.propScale);return{values:s,origin:o,solved:a,anchor(l){const c=a.anchors[l];if(!c)throw new Error(`${t.prop.kind}: no anchor "${l}" (it has ${Object.keys(a.anchors).join(", ")||"none"})`);return{x:o.x+c.point.x,y:o.y+c.point.y,depth:c.depth}}}}function Gx(t,e,n,s,i={}){const r=Do(e,n,s);return t.save(),t.translate(r.origin.x,r.origin.y),bc(t,r.solved,{...e.propDraw,time:n.time,loose:wh(e,r.values),rider:i.rider?o=>{o.save(),o.translate(-r.origin.x,-r.origin.y),i.rider(o),o.restore()}:void 0}),t.restore(),r}const Is={kind:"prop",create:"propSurface(propTarget({ x, y, prop }), { tracks? }): its controls and anchors are those the catalog lists for its preset",anchors:{box:"the prop’s whole box","anchor:NAME":"one of its rig’s anchors (door, seat, branch, ridge…), as posed at the time","part:ID":"one of its parts as seen at the time (window-1, door-left, wheel-0-left…); it can come loose as a piece","control:NAME":"where the parts a control moves or lights are (control:door is the doors, control:lights the lamps; a control of the whole prop, like lift, is its box)"},edits:{set:"control anchors; { at, value, duration? }: move a control to a value",switch:"control anchors; { at, on?, duration? }: a control to its full value (open, on), or back to its rest value with on: false",move:"a part; { at, to: an anchor name or { x, y }, duration? }: carry the part there, loose",fling:"a part; { at, velocity?, spin?, gravity?, duration? }: knock the part off on a spinning arc"}},Ux=400,Vx=.2;function Jx(t,e={}){const{prop:n}=t,s=kh(n),i=Object.keys(s),r=Object.keys(n.rig.anchors??{}),o=n.rig.parts.map(A=>A.id),a=vs(),l=Ci(a),c=e.tracks?.length?new Ht({id:`${n.kind}-surface`,tracks:e.tracks}):void 0,h=Math.max(0,...(e.tracks??[]).flatMap(A=>A.keyframes.map(M=>M.time))),u=new Map,d=new Map;t.loose=d;const f=t.props,p=A=>{const M={...t.props};let x=0,S=0;if(c){const E=c.getStateAtTime(Math.min(A,h));for(const P of E.values.values())for(const[I,O]of P)typeof O=="number"&&(I==="x"?x=O:I==="y"?S=O:I in M&&(M[I]=O))}for(const E of i)a.keys(E)?.length&&(M[E]=a.valueAt(E,A));return{values:M,origin:{x:t.x+t.width/2+x,y:t.y+t.height+S}}},g=A=>{const{kind:M,rest:x}=_n(A),S=E=>rn(n.kind,A,Is,E);if(M==="box"){if(x)throw S("box takes no arguments");return{kind:M}}if(M==="anchor"){if(!r.includes(x))throw S(ft(`${n.kind} anchor`,x,r));return{kind:M,name:x}}if(M==="part"){if(!o.includes(x))throw S(ft(`${n.kind} part`,x,o));return{kind:M,name:x}}if(M==="control"){if(!i.includes(x))throw S(ft(`${n.kind} control`,x,i));return{kind:M,name:x}}throw S()},m=A=>{const M=(n.rig.controls[A]?.bind??[]).flatMap(S=>S.parts),x=n.rig.parts.filter(S=>S.glow?.control===A).map(S=>S.id);return new Set([...M,...x])},y=new Map,v=A=>{let M=y.get(A);if(!M){const x=p(A);y.set(A,M={...x,solved:$s(n,x.values,t.propScale)})}return M},k=(A,M)=>{const x=g(A),{values:S,origin:E,solved:P}=v(M);if(x.kind==="box")return Mt(E.x-t.width/2,E.y-t.height,t.width,t.height);if(x.kind==="anchor"){const H=P.anchors[x.name].point,W=Vx*t.propScale;return Mt(E.x+H.x-W/2,E.y+H.y-W/2,W,W)}if(x.kind==="part")return O(new Set([x.name]),`part "${x.name}" is`);const I=m(x.name);if(I.size===0)return Mt(E.x-t.width/2,E.y-t.height,t.width,t.height);return O(I,`the parts control "${x.name}" moves are`);function O(H,W){const j=[...P.under,...P.over].filter(B=>H.has(B.part.id)).flatMap(B=>B.faces.flatMap(K=>K.points));if(j.length===0){const B=Number.isFinite(M)?`at ${M} ms`:"after its edits";throw new Error(`${n.kind}: ${W} turned away from the viewer ${B}; aim at an anchor (${r.map(K=>`anchor:${K}`).join(", ")||"none"}) or box`)}const J=j.map(B=>B.x),et=j.map(B=>B.y),V=Math.min(...J),F=Math.min(...et);return Mt(E.x+V,E.y+F,Math.max(...J)-V,Math.max(...et)-F)}},w=(A,M)=>{try{return k(A,M)}catch{return}},T={kind:"prop",prop:t,about:Is,target:t,box:Mt(t.x,t.y,t.width,t.height),anchor(A,M=1/0){return k(A,M)},piece(A){const M=g(A);if(M.kind!=="part")throw new Error(`${n.kind}: a piece is a part, part:ID (${o.slice(0,6).map(P=>`part:${P}`).join(", ")}…), not "${A}"`);const x=u.get(M.name);if(x)return x;const S=[M.name];for(let P=0;P<S.length;P++)for(const I of n.rig.parts)I.parent===S[P]&&!S.includes(I.id)&&S.push(I.id);const E={id:u.size+1,part:M.name,home:k(A,0)};u.set(M.name,E);for(const P of S)d.set(P,E.id);for(const P of["x","y","rotate"])f[`piece.${E.id}.${P}`]=0;return f[`piece.${E.id}.opacity`]=1,E},edit(A,M,x){if(!(A in Is.edits))throw _i(n.kind,A,Is);const S=Array.isArray(M)?M:[M];if(S.length===0)throw new Error(`${n.kind}.edit: ${A} takes at least one anchor`);if(y.clear(),A==="move"||A==="fling"){if(S.length>1)throw new Error(`${n.kind}.edit: ${A} takes one part anchor`);const E=T.piece(S[0]);if(A==="fling")return T.fling(E,x);const P=x.to;if(!P)throw new Error(`${n.kind}.edit: move needs \`to\`, an anchor name or { x, y }`);const I=typeof P=="string"?k(P,x.at):void 0;return T.move(E,{...x,to:I?{x:I.left+I.width/2,y:I.top+I.height/2}:P})}for(const E of S){const P=g(E);if(P.kind!=="control")throw new Error(`${n.kind}.edit: ${A} takes control anchors (control:${i.join(", control:")}), not "${E}"`);const I=s[P.name];let O;if(A==="set"){if(typeof x.value!="number"||!Number.isFinite(x.value))throw new Error(`${n.kind}.edit: set needs \`value\`, a number (${P.name}: ${I.description})`);O=x.value}else O=x.on===!1?I.default??I.min??0:I.max??1;a.tween(P.name,p(x.at).values[P.name],O,x,Ux)}return T},follow(A,M){return y.clear(),l.follow(A,M),T},fling(A,M){return y.clear(),l.fling(A,M),T},move(A,M){return y.clear(),l.move(A,M),T},ride(A,M,x){const S=[...i.flatMap(P=>Ms(a.keys(P))),...(e.tracks??[]).flatMap(P=>Ms(P.keyframes.filter(I=>typeof I.value=="number")))];if(S.length===0)return A;const E=[...r.map(P=>`anchor:${P}`),...o.map(P=>`part:${P}`)].flatMap(P=>{const I=w(P,0);return I?[{top:I.top,offset:O=>(w(P,O)?.top??I.top)-I.top,windows:S}]:[]});return xo(A,M,{ground:x.ground,every:x.every??sn,floors:E})},tracks:a.tracks};return T}const Zx={body:"#e8574a",trim:"#3b3b44",glass:"#bfe3f2",tyre:"#2c2c33",hub:"#c9ccd3",light:"#fff4b8",tail:"#ff5a4f",inside:"#3b3640",seat:"#6d5d55"};function Ne(t){const e={...Zx,...t.colors},n=[],{forwardMost:s,backMost:i,top:r}=sy(t);t.body&&n.push({id:"body",shape:{type:"extrude",profile:t.body,width:t.width},fill:e.body});for(const[h,u]of(t.frame??[]).entries())n.push({id:`frame-${h}`,shape:{type:"tube",points:u.points,radius:u.radius??.035,segments:6},fill:u.color??e.body,outline:.7});for(const[h,u]of(t.windows??[]).entries())for(const d of[1,-1])n.push({id:`window-${h}-${d>0?"left":"right"}`,shape:{type:"panel",points:[[u.from,u.low],[u.to,u.low],[u.to,u.high],[u.from,u.high]],facing:d>0?"left":"right"},at:[d*(t.width/2+.01),0,0],fill:e.glass,outline:.7,seeThrough:!0,glow:t.lights?{control:"lights",color:"#ffe9a3"}:void 0});for(const h of t.extras??[])n.push(h);if(t.cabin){const h=t.cabin.width??t.width*.85;n.push({id:"cabin",shape:{type:"extrude",profile:t.cabin.profile,width:h},fill:e.glass,outline:.9,seeThrough:!0,layer:1});const u=Math.min(...t.cabin.profile.map(([,f])=>f)),d=Math.max(...t.cabin.profile.map(([,f])=>f));for(const[f,p]of(t.cabin.pillars??[]).entries())n.push({id:`pillar-${f}`,shape:{type:"box",size:[h+.02,d-u,.1]},at:[0,(u+d)/2,p],fill:e.body,outline:.8,layer:1})}const o=t.wheels[0]?.radius??.4,a=[];t.wheels.forEach((h,u)=>{const d=h.side===0?[0]:[1,-1],f=h.thickness??(h.style==="spoked"?.05:.26);for(const p of d){const g=`wheel-${u}-${p>0?"left":p<0?"right":"middle"}`;if(a.push({parts:[g],rotate:{axis:"x",degrees:o/h.radius}}),n.push({id:g,shape:{type:"cylinder",radius:h.radius,length:f,axis:"x",segments:20,spokes:h.style==="spoked"?8:0},at:[p*h.side,h.radius,h.forward],fill:h.style==="spoked"?void 0:e.tyre,ink:h.style==="spoked"?e.tyre:void 0,outline:h.style==="spoked"?1.3:1}),h.style!=="spoked")for(const m of p===0?[1,-1]:[p])n.push({id:`${g}-hub${p===0?m>0?"-left":"-right":""}`,parent:g,shape:{type:"cylinder",radius:h.radius*.55,length:.02,axis:"x",segments:14,spokes:5},at:[m*(f/2+.012),0,0],fill:e.hub,outline:.6})}});const l={wheelSpin:{description:"How far the wheels have turned (keyed exactly with the distance driven, so they never skate)",unit:"degrees",bind:a}};if(t.door){const{from:h,to:u,low:d,high:f}=t.door,p=[[h,d],[u,d],[u,f],[h,f]];for(const g of[1,-1]){const m=g>0?"left":"right";n.push({id:`doorway-${m}`,shape:{type:"panel",points:p,facing:g>0?"left":"right"},at:[g*(t.width/2+.004),0,0],fill:e.inside,outline:.5,seeThrough:!0});const y=h+(u-h)*.15,v=h+(u-h)*.55;n.push({id:`seat-back-${m}`,shape:{type:"panel",points:[[y,d+.05],[v,d+.05],[v-.08,f-.06],[y+.06,f-.04]],facing:g>0?"left":"right"},at:[g*(t.width/2+.006),0,0],fill:e.seat,outline:.4}),n.push({id:`door-${m}`,shape:{type:"panel",points:p.map(([k,w])=>[k-u,w]),facing:g>0?"left":"right"},at:[g*(t.width/2+.01),0,u],fill:e.body,outline:.7,overRider:!0})}l.door={description:"Doors open: 0 shut, 1 open (hinged at the front)",unit:"0..1",min:0,max:1,bind:[{parts:["door-left"],rotate:{axis:"y",degrees:-70}},{parts:["door-right"],rotate:{axis:"y",degrees:70}}]}}if(t.lights){const{across:h,low:u,high:d,front:f,back:p}=t.lights,g=(t.lights.size??.32)/2,m=[[-g,u],[g,u],[g,d],[-g,d]];for(const y of[1,-1])n.push({id:`headlight-${y}`,shape:{type:"panel",points:m,facing:"front"},at:[y*h,0,f],fill:e.light,outline:.6,glow:{control:"lights",color:"#ffffff"}}),n.push({id:`taillight-${y}`,shape:{type:"panel",points:m,facing:"back"},at:[y*h,0,p],fill:bo(e.tail,.62),outline:.6,glow:{control:"lights",color:e.tail}});l.lights={description:"Lights on: 0 off, 1 on",unit:"0..1",min:0,max:1}}t.antenna&&(n.push({id:"antenna",shape:{type:"tube",points:[[0,0,0],[0,.75,0]],radius:.018,segments:5},at:t.antenna,fill:e.trim,outline:.6}),n.push({id:"antenna-tip",parent:"antenna",shape:{type:"ellipsoid",radii:[.05,.05,.05],segments:8},at:[0,.77,0],fill:e.tail,outline:.6}),l.antenna={description:"Antenna bend (follow-through: it trails the motion on a spring)",unit:"degrees",bind:[{parts:["antenna"],rotate:{axis:"x",degrees:1}}]});const c={parts:n,controls:l,length:s-i,height:r,footprint:[t.width,s-i],anchors:{...t.seat?{seat:{at:t.seat}}:{},front:{at:[0,r*.45,s]},back:{at:[0,r*.45,i]},roof:{at:[0,r,0]},...t.door?{door:{at:[-t.width/2,(t.door.low+t.door.high)/2,(t.door.from+t.door.to)/2]}}:{},...t.anchors}};return{kind:t.kind??"vehicle",family:"vehicle",summary:t.summary??"A wheeled vehicle",rig:c,actions:Qx(t),acting:iy,colors:{body:e.body,ink:"#26262b"},follow:t.antenna?[{control:"antenna",of:"x",per:.9,stiffness:140,damping:7,limit:35}]:void 0,wheelRadius:o,...t.wheels.length>0?{moves:{drive:{speed:t.speed??6,perMetre:{wheelSpin:180/(Math.PI*o)}}}}:{}}}function sy(t){const e=[...(t.body??[]).map(([s])=>s),...(t.frame??[]).flatMap(s=>s.points.map(i=>i[2])),...t.wheels.flatMap(s=>[s.forward+s.radius,s.forward-s.radius])],n=[...(t.body??[]).map(([,s])=>s),...(t.cabin?.profile??[]).map(([,s])=>s),...(t.frame??[]).flatMap(s=>s.points.map(i=>i[1])),...t.wheels.map(s=>s.radius*2)];return{forwardMost:Math.max(...e),backMost:Math.min(...e),top:Math.max(...n)}}const iy={depth:{turn:0,lift:0,lights:0,pitch:1,roll:1,squash:1,lean:1,door:2},limits:{turn:.08,pitch:5,roll:4,lean:.1,squash:.06,door:.12,lift:0},eyes:[],headTurns:{},drift:[]};function Bo(t,e,n,s,i,r,o=!1){const a=t.facing()||Math.sign(s-t.x)||1,l=t.values.wheelSpin??0,c=(s-t.x)*a/t.scale;t.set("wheelSpin",e,l),t.move(e,n,s,{easing:i}),t.set("wheelSpin",n,o?l:l+c/r*(180/Math.PI),i)}const ry=.4;function Qx(t){const e=t.wheels[0]?.radius??.4,{forwardMost:n,backMost:s}=sy(t),i=(n-s)/2,r=(a,l,c)=>{const h=a.exaggeration;let u=l;return a.facing()!==c&&(u=a.turnTo(u,c>0?"right":"left")),a.key(u+200,{pitch:4*h,squash:1-.07*h,lean:-.1*h},{act:!1,easing:"ease-out"}),Bo(a,u,u+200,a.x-c*.15*h*a.scale,"ease-out",e),a.effect({kind:"exhaust",time:u+150,x:a.x-c*i*a.scale,y:a.floor-.3*a.scale,length:900,direction:-c}),u+260},o=(a,l,c)=>{const h=a.exaggeration*(c?1.8:1);a.key(l,{pitch:-5*h,lean:-.08*h,squash:.95},{act:!1,easing:"ease-out"}),a.key(l+380,{pitch:0,lean:0,squash:1})};return{drive:{summary:"Drives to `to`: rocks back and squats, lunges forward stretched, and stops with a nose-dive that settles; wheels roll exactly the distance.",needs:["to"],uses:["speed","for"],run(a,l,c){const h=Math.sign(l.to-a.x);if(h===0)return{end:c};const u=r(a,c,h),d=a.exaggeration,f=Math.abs(l.to-a.x),p=l.for??Math.max(500,f/(l.speed??ry));return a.effect({kind:"dust",time:u,x:a.x-h*i*a.scale,y:a.floor,length:600,direction:-h}),a.key(u+140,{pitch:-1.5*d,squash:1+.05*d,lean:.12*d},{act:!1,easing:"ease-out"}),a.key(u+Math.max(160,p-160),{pitch:0,lean:.08*d,squash:1.02},{act:!1}),Bo(a,u,u+p,l.to,"ease-in-out",e),o(a,u+p,!1),{end:u+p+380,contact:u,release:u+p}}},brake:{summary:"Drives toward `to` and slams on the brakes: the wheels lock and it skids the last stretch, nose diving, leaving skid marks.",needs:["to"],uses:["speed","for"],run(a,l,c){const h=Math.sign(l.to-a.x);if(h===0)return{end:c};const u=r(a,c,h),d=a.exaggeration,f=a.x,p=Math.abs(l.to-f),g=l.for??Math.max(600,p/(l.speed??ry*1.2)),m=u+g*.55,y=f+(l.to-f)*.65;return a.key(u+140,{pitch:-1.5*d,squash:1+.06*d,lean:.14*d},{act:!1,easing:"ease-out"}),Bo(a,u,m,y,"ease-in",e),a.key(m+80,{pitch:-7*d,lean:-.12*d,squash:.94},{act:!1,easing:"ease-out"}),Bo(a,m,u+g,l.to,"ease-out",e,!0),a.effect({kind:"skid",time:m,x:y,toX:l.to,y:a.floor,length:g*.45+1500}),a.effect({kind:"dust",time:u+g,x:l.to+h*i*a.scale,y:a.floor,length:600,direction:h}),o(a,u+g,!0),{end:u+g+380,contact:m,release:u+g}}},bump:{summary:"Hits a bump: squashes, hops up stretched, lands squashed with dust, and springs back.",uses:["for"],run(a,l,c){const h=a.exaggeration;return a.key(c+90,{squash:1-.16*h,pitch:3*h},{act:!1,easing:"ease-out"}),a.key(c+300,{lift:.35*h,squash:1+.12*h,pitch:-3*h},{act:!1,easing:"ease-out"}),a.key(c+540,{lift:0,squash:1-.2*h,pitch:0},{act:!1,easing:"ease-in"}),a.key(c+820,{squash:1}),a.effect({kind:"dust",time:c+540,x:a.x,y:a.floor,length:500}),{end:c+820,contact:c+540}}},honk:{summary:"Honks: a stretch and squash pulse, with honk lines from the front.",run(a,l,c){const h=a.exaggeration;a.key(c+110,{squash:1+.12*h,lean:.04*h},{act:!1,easing:"ease-out"}),a.key(c+240,{squash:1-.06*h,lean:0},{act:!1}),a.key(c+520,{squash:1});const u=a.facing();return a.effect({kind:"honk",time:c+60,x:a.x+(u||1)*i*a.scale,y:a.floor-.7*a.scale,length:700,direction:u||1}),{end:c+520,contact:c+60}}},...t.door?{door:{summary:"Opens the doors (`open: true`) or shuts them (`open: false`).",needs:["open"],run(a,l,c){return a.key(c+450,{door:l.open?1:0}),{end:c+600,contact:c+450}}}}:{},...t.lights?{lights:{summary:"Switches the lights on (`on: true`) or off.",needs:["on"],run(a,l,c){return a.key(c+120,{lights:l.on?1:0},{act:!1}),{end:c+300,contact:c+120}}}}:{}}}function oy(t={}){return Ne({kind:"car",summary:"A cartoon car: drives, brakes, bumps, honks, opens its doors, lights up, and turns toward the camera.",body:[[-2,.32],[2,.32],[2.08,.52],[1.98,.82],[1.05,.95],[-1.72,.98],[-2.02,.86],[-2.08,.5]],width:1.8,cabin:{profile:[[-1.5,.94],[.92,.94],[.3,1.52],[-1.22,1.54]],width:1.56,pillars:[-.42]},wheels:[{forward:1.28,side:.8,radius:.4},{forward:-1.28,side:.8,radius:.4}],door:{from:-.4,to:.88,low:.36,high:.92},lights:{across:.58,low:.55,high:.72,front:2.05,back:-2.06},antenna:t.antenna===!1?void 0:[.5,1.5,-1.05],seat:[0,.3,-.15],colors:t.colors})}function ay(t={}){return Ne({kind:"truck",summary:"A box truck: drives, brakes, bumps, honks, opens its cab doors, lights up, turns toward the camera.",body:[[-3.2,.5],[3.1,.5],[3.15,.95],[3,1.85],[2.3,2.25],[1.2,2.25],[1.2,1],[-3.2,1]],width:2,cabin:{profile:[[1.6,1.35],[2.95,1.35],[2.85,1.85],[2.3,2.15],[1.6,2.15]],width:2.04},extras:[{id:"cargo",shape:{type:"box",size:[2.1,1.75,4.2]},at:[0,1.9,-1.05],fill:t.cargo??"#f1f1ee"}],wheels:[{forward:2.2,side:.85,radius:.48,thickness:.32},{forward:-1.4,side:.85,radius:.48,thickness:.32},{forward:-2.45,side:.85,radius:.48,thickness:.32}],door:{from:1.4,to:2.25,low:.6,high:1.9},lights:{across:.7,low:.62,high:.82,front:3.13,back:-3.22,size:.28},seat:[0,1.15,1.9],colors:{body:"#2f6fb7",...t.colors}})}function ly(t={}){return Ne({kind:"bus",summary:"A bus: drives, brakes, bumps, honks, opens its front doors, lights its windows, turns toward the camera.",body:[[-4.5,.45],[4.5,.45],[4.6,.9],[4.55,2.9],[4.3,3],[-4.4,3],[-4.55,2.75],[-4.55,.6]],width:2.4,windows:Array.from({length:6},(e,n)=>({from:-4+n*1.18,to:-4+n*1.18+1,low:1.55,high:2.6})),extras:[{id:"windscreen",shape:{type:"panel",points:[[-1.05,1.35],[1.05,1.35],[1.05,2.75],[-1.05,2.75]],facing:"front"},at:[0,0,4.58],fill:"#bfe3f2",outline:.8,seeThrough:!0}],wheels:[{forward:3,side:1,radius:.5,thickness:.34},{forward:-2.8,side:1,radius:.5,thickness:.34}],door:{from:3.2,to:4.2,low:.5,high:2.6},lights:{across:.85,low:.65,high:.85,front:4.6,back:-4.56,size:.3},seat:[0,1.2,3.6],colors:{body:"#f2c230",...t.colors}})}function cy(t={}){return Ne({kind:"tractor",summary:"A tractor: big rear wheels and small front ones turning at their own rates; drives, brakes, bumps, honks.",body:[[-.5,.75],[2,.75],[2.12,1.25],[1.9,1.52],[-.5,1.52]],width:1,cabin:{profile:[[-1.35,1],[-.25,1],[-.25,2.55],[-1.35,2.55]],width:1.35},extras:[{id:"roof",shape:{type:"box",size:[1.55,.1,1.35]},at:[0,2.62,-.8],fill:"#3f9b47"},{id:"exhaust",shape:{type:"tube",points:[[.28,1.5,1.25],[.28,2.35,1.25]],radius:.06,segments:6},fill:"#3b3b44",outline:.7}],wheels:[{forward:-.85,side:.85,radius:.78,thickness:.45},{forward:1.55,side:.7,radius:.42,thickness:.26}],lights:{across:.3,low:1,high:1.18,front:2.1,back:-.52,size:.2},seat:[0,1.25,-.8],colors:{body:"#3f9b47",hub:"#e9c64a",...t.colors}})}function hy(t={}){const e=t.colors?.body??"#a8743f";return Ne({kind:"cart",summary:"A wooden cart on spoked wheels with shafts: rolls when pulled (drive), bumps, tips.",body:[[-1.25,.78],[1.25,.78],[1.35,1.18],[-1.35,1.18]],width:1.4,frame:[{points:[[.5,.9,1],[.5,.95,2.7]],radius:.05,color:e},{points:[[-.5,.9,1],[-.5,.95,2.7]],radius:.05,color:e}],wheels:[{forward:0,side:.82,radius:.66,style:"spoked"}],seat:[0,1.2,0],anchors:{shafts:{at:[0,.95,2.7]}},colors:{body:e,tyre:"#5a3a1f",...t.colors}})}function uy(t={}){return Ne({kind:"train carriage",summary:"A railway carriage: rolls along (drive), brakes, lights its windows, turns toward the camera.",body:[[-4,.72],[4,.72],[4,2.8],[3.6,3.12],[-3.6,3.12],[-4,2.8]],width:2.6,windows:Array.from({length:5},(e,n)=>({from:-3.3+n*1.4,to:-3.3+n*1.4+1,low:1.7,high:2.5})),wheels:[{forward:3,side:1,radius:.36,thickness:.16},{forward:2.2,side:1,radius:.36,thickness:.16},{forward:-2.2,side:1,radius:.36,thickness:.16},{forward:-3,side:1,radius:.36,thickness:.16}],lights:{across:.9,low:1,high:1.2,front:4.01,back:-4.01,size:.22},seat:[0,1,1.5],colors:{body:"#2f7d6d",...t.colors}})}function dy(t={}){const e=t.colors?.body??"#e0473b",n=[0,.32,-.05],s=[0,.86,-.22],i=[0,.9,.42],r=[0,.34,.56],o=[0,.34,-.56];return Ne({kind:"bike",summary:"A bicycle: rides (drive) with its wire wheels turning, brakes, bumps, rings its bell (honk).",width:.5,frame:[{points:[o,n]},{points:[n,s]},{points:[s,o]},{points:[s,i]},{points:[n,i]},{points:[i,r]},{points:[[.24,.98,.44],[-.24,.98,.44]],radius:.025,color:"#3b3b44"},{points:[i,[0,.98,.44]],radius:.025,color:"#3b3b44"}],extras:[{id:"saddle",shape:{type:"ellipsoid",radii:[.08,.035,.15],segments:10},at:[0,.89,-.22],fill:"#3b3b44",outline:.7}],wheels:[{forward:.56,side:0,radius:.34,style:"spoked"},{forward:-.56,side:0,radius:.34,style:"spoked"}],seat:[0,.9,-.22],colors:{body:e,tyre:"#2c2c33",...t.colors}})}function fy(t={}){return Ne({kind:"motorbike",summary:"A motorbike: rides (drive) with a lunge, brakes into a skid, bumps, honks, lights up.",body:[[-.62,.62],[.42,.62],[.55,.95],[.3,1.02],[-.1,.92],[-.8,.88],[-.86,.72]],width:.4,frame:[{points:[[0,.33,.78],[0,1.05,.5]],radius:.04,color:"#8c8f98"},{points:[[.3,1.08,.48],[-.3,1.08,.48]],radius:.025,color:"#3b3b44"},{points:[[.12,.42,-.2],[.12,.5,-.95]],radius:.04,color:"#8c8f98"}],extras:[{id:"engine",shape:{type:"box",size:[.38,.34,.5]},at:[0,.45,.05],fill:"#5b5f6a",outline:.8}],wheels:[{forward:.78,side:0,radius:.33,thickness:.14},{forward:-.72,side:0,radius:.33,thickness:.14}],lights:{across:0,low:.9,high:1.04,front:.62,back:-.87,size:.14},seat:[0,.92,-.3],colors:{body:"#1f1f26",hub:"#c9ccd3",...t.colors}})}function gy(t={}){const e=t.height??2.4,n=t.trunkRadius??.16,s=t.canopy?.radius??1.1,i=t.canopy?.shape==="tall",r={trunk:"#8a5a3b",leaves:"#5cae5a",...t.colors},o=Ge(t.canopy?.seed??7),a=[{id:"trunk",shape:{type:"tube",points:[[0,0,0],[.06,e*.5,0],[-.02,e,0]],radius:n,segments:8},fill:r.trunk},{id:"branch",parent:"trunk",shape:{type:"tube",points:[[0,0,0],[.45,.4,.1]],radius:n*.45,segments:6},at:[.04,e*.62,0],fill:r.trunk},{id:"canopy",parent:"trunk",shape:{type:"ellipsoid",radii:[s,s*(i?1.35:.88),s],segments:14},at:[-.02,e+s*.55,0],fill:r.leaves}],l=t.canopy?.lobes??7;for(let h=0;h<l;h++){const u=Math.PI*2*h/l+o.next()*.6,d=(o.next()-.25)*s*(i?1.1:.7),f=s*(.48+o.next()*.22),p=[Math.cos(u)*s*.78,d,Math.sin(u)*s*.6];a.push({id:`lobe-${h}`,parent:"canopy",shape:{type:"ellipsoid",radii:[f,f*.86,f],segments:12},at:p,fill:r.leaves})}const c={parts:a,controls:{sway:{description:"The whole tree bending in the wind, about its base",unit:"degrees",bind:[{parts:["trunk"],rotate:{axis:"z",degrees:1}}]},canopySway:{description:"The canopy bending further than the trunk (it trails the sway)",unit:"degrees",bind:[{parts:["canopy"],rotate:{axis:"z",degrees:1,pivot:[0,-s*.8,0]}}]}},length:s*2.2,height:e+s*2,footprint:[s*1.6,s*1.6],anchors:{canopy:{part:"canopy",at:[0,0,0]},top:{part:"canopy",at:[0,s*.9,0]},base:{at:[0,0,0]},branch:{part:"branch",at:[.45,.4,.1]}}};return{kind:t.kind??"tree",family:"plant",summary:t.summary??"A tree: sways in the wind with its canopy trailing, shakes, sheds leaves, pops up.",rig:c,actions:t4(),acting:py,colors:{body:r.leaves}}}const py={depth:{sway:1,canopySway:2,size:0,squash:1},limits:{sway:2,canopySway:3,squash:.08},eyes:[],headTurns:{},drift:[]};function t4(){const t=(e,n,s,i)=>{const r=e.anchor("canopy");e.effect({kind:"leaves",time:n,x:r.x,y:r.y,length:s,direction:i,toY:e.floor})};return{sway:{summary:"Sways in gusts of `wind` (0..1, default 0.5) for `for` ms (default 3000); the canopy trails the trunk, and a strong wind sheds leaves.",uses:["wind","for"],run(e,n,s){const i=n.wind??.5,r=n.for??3e3,o=e.exaggeration,a=260;let l=0;for(let c=a;c<r;c+=a){const h=.55+.45*Math.sin(c/r*Math.PI*2.3),u=Math.sin(c/170)*.35,d=-i*9*o*(h+u*i);e.key(s+c,{sway:d,canopySway:l*1.3},{act:!1,easing:"ease-in-out"}),l=d}if(e.key(s+r,{sway:0,canopySway:0}),i>.45)for(let c=0;c<r;c+=700)t(e,s+c,2200,1);return{end:s+r}}},shake:{summary:"Shakes (something hit it): a quick wobble that dies away, shedding leaves.",uses:["for"],run(e,n,s){const i=n.for??900,r=e.exaggeration,o=6;for(let a=1;a<=o;a++){const l=1-a/(o+1),c=a%2===0?1:-1;e.key(s+i*a/(o+1),{sway:c*5*r*l,canopySway:-c*6*r*l},{act:!1,easing:"ease-in-out"})}return e.key(s+i,{sway:0,canopySway:0}),t(e,s+60,1800,1),t(e,s+260,1800,-1),{end:s+i,contact:s}}},shedLeaves:{summary:"Leaves fall from the canopy for `for` ms (default 2000).",uses:["for"],run(e,n,s){const i=n.for??2e3;for(let r=0;r<i;r+=500)t(e,s+r,2e3,r%1e3===0?1:-1);return{end:s+i}}}}}function my(t={}){const e=t.width??4,n=t.depth??3.2,s=t.wallHeight??2.5,i=t.roofHeight??1.5,r=t.overhang??.25,o={walls:"#f1d9a8",roof:"#b8433a",door:"#7a4b2a",doorway:"#3a2a22",glass:"#bfe3f2",lit:"#ffd66b",chimney:"#9b5a45",...t.colors},a=n/2+.01,l=t.door?.width??.9,c=t.door?.height??1.9,h=t.door?.at??0,u=t.windows??[{at:-1.25,low:1,width:.8,height:.8},{at:1.25,low:1,width:.8,height:.8}],d=[{id:"walls",shape:{type:"box",size:[e,s,n]},at:[0,s/2,0],fill:o.walls},{id:"roof",shape:{type:"extrude",profile:[[-n/2-r,s],[n/2+r,s],[0,s+i]],width:e+r*2},fill:o.roof,layer:1},{id:"doorway",shape:{type:"panel",points:[[0,0],[l,0],[l,c],[0,c]],facing:"front"},at:[h-l/2,0,a-.005],fill:o.doorway,outline:.6,seeThrough:!0},{id:"door",shape:{type:"panel",points:[[0,0],[l,0],[l,c],[0,c]],facing:"front"},at:[h-l/2,0,a+.005],fill:o.door,outline:.8,overRider:!0}];u.forEach((g,m)=>{d.push({id:`window-${m}`,shape:{type:"panel",points:[[-g.width/2,g.low],[g.width/2,g.low],[g.width/2,g.low+g.height],[-g.width/2,g.low+g.height]],facing:"front"},at:[g.at,0,a+.01],fill:o.glass,outline:.8,glow:{control:"lights",color:o.lit}})});for(const g of[1,-1])d.push({id:`side-window-${g>0?"left":"right"}`,shape:{type:"panel",points:[[-.4,1],[.4,1],[.4,1.8],[-.4,1.8]],facing:g>0?"left":"right"},at:[g*(e/2+.01),0,0],fill:o.glass,outline:.8,glow:{control:"lights",color:o.lit}});const f=t.chimney===!1?void 0:{at:t.chimney?.at??e*.28,back:t.chimney?.back??-n*.18};if(f){const g=s+i*(1-Math.abs(f.back)/(n/2+r)),m=s+i+.45;d.push({id:"chimney",shape:{type:"box",size:[.42,m-g+.3,.42]},at:[f.at,(m+g-.3)/2,f.back],fill:o.chimney,layer:1})}const p={parts:d,controls:{door:{description:"The front door open: 0 shut, 1 open",unit:"0..1",min:0,max:1,bind:[{parts:["door"],rotate:{axis:"y",degrees:-80}}]},lights:{description:"The windows lit: 0 dark, 1 lit",unit:"0..1",min:0,max:1}},length:n+r*2,height:s+i+.6,footprint:[e+.6,n+.6],anchors:{door:{at:[h,c/2,a]},doorstep:{at:[h,0,a+.4]},ridge:{at:[0,s+i,0]},...f?{chimney:{at:[f.at,s+i+.5,f.back]}}:{}}};return{kind:t.kind??"house",family:"building",summary:t.summary??"A house: opens its door, lights its windows, puffs chimney smoke, shakes, pops up.",rig:p,actions:e4(!!f),acting:yy,colors:{body:o.walls}}}const yy={depth:{door:1,lights:0,roll:1,squash:1,size:0},limits:{door:.1,roll:1.5,squash:.05},eyes:[],headTurns:{},drift:[]};function e4(t){return{door:{summary:"Opens the front door (`open: true`) or shuts it (`open: false`).",needs:["open"],run(e,n,s){return e.key(s+500,{door:n.open?1:0}),{end:s+650,contact:s+500}}},lights:{summary:"Lights the windows (`on: true`) or puts them out.",needs:["on"],run(e,n,s){return e.key(s+150,{lights:n.on?1:0},{act:!1}),{end:s+300,contact:s+150}}},shake:{summary:"Shakes, as when a door slams or something lands on it: a squash and a wobble that dies away, with dust.",uses:["for"],run(e,n,s){const i=n.for??700,r=e.exaggeration;e.key(s+80,{squash:1-.06*r},{act:!1,easing:"ease-out"});for(let o=1;o<=5;o++){const a=1-o/6;e.key(s+80+i*o/6,{roll:(o%2===0?1:-1)*2.2*r*a,squash:1+.02*a},{act:!1,easing:"ease-in-out"})}return e.key(s+i+80,{roll:0,squash:1}),e.effect({kind:"dust",time:s+80,x:e.x,y:e.floor,length:600}),{end:s+i+80,contact:s+80}}},...t?{smoke:{summary:"Starts smoke puffing from the chimney for `for` ms (default 3000), drifting with the wind; the next beat starts at once (the smoke carries on).",uses:["for","wind"],run(e,n,s){const i=n.for??3e3,r=e.anchor("chimney");return e.effect({kind:"smoke",time:s,x:r.x,y:r.y,length:i+1500,direction:(n.wind??.4)>=0?1:-1}),{end:s+50,release:s+i}}}}:{}}}function by(t={}){const e=t.width??.46,n=t.depth??.46,s=t.seatHeight??.46,i=t.backHeight??.95,r={wood:"#8a5a3b",seat:"#c48a4a",...t.colors},o=.05,a=.025,l=[{id:"seat",shape:{type:"box",size:[e,o,n]},at:[0,s-o/2,0],fill:r.seat},{id:"back",shape:{type:"box",size:[e,i-s,o]},at:[0,(i+s)/2,-n/2+o/2],fill:r.wood}];for(const[h,u,d]of[[-1,1,"front-left"],[1,1,"front-right"],[-1,-1,"back-left"],[1,-1,"back-right"]])l.push({id:`leg-${d}`,shape:{type:"tube",points:[[0,0,0],[0,s-o,0]],radius:a,segments:6},at:[h*(e/2-a*1.5),0,u*(n/2-a*1.5)],fill:r.wood});const c={parts:l,controls:{tip:{description:"Tipped back on its rear legs (+), degrees",unit:"degrees",min:0,max:60,bind:[{parts:l.map(h=>h.id),rotate:{axis:"x",degrees:1,pivot:[0,0,-n/2+a*1.5]}}]}},length:n,height:i,footprint:[e,n],anchors:{seat:{at:[0,s,0]},back:{at:[0,i,-n/2]},front:{at:[0,0,n/2+.3]}}};return{kind:t.kind??"chair",family:"furniture",summary:t.summary??"A chair: a seat to sit on (`seat`), tips back on its rear legs and settles, or falls over.",rig:c,actions:n4(),acting:wy,colors:{body:r.seat}}}const wy={depth:{tip:1,roll:1,squash:1,size:0},limits:{tip:2,roll:1,squash:.05},eyes:[],headTurns:{},drift:[]};function n4(){return{tip:{summary:"Tips back on its rear legs for `for` ms (default 1200), rocking a little, then settles down.",uses:["for"],run(t,e,n){const s=18*t.exaggeration,i=e.for??1200;return t.key(n+350,{tip:s},{easing:"ease-out"}),t.key(n+350+i*.4,{tip:s*.85},{act:!1,easing:"ease-in-out"}),t.key(n+350+i*.7,{tip:s},{act:!1,easing:"ease-in-out"}),t.key(n+350+i,{tip:0},{easing:"ease-in"}),{end:n+350+i,contact:n+350}}},fall:{summary:"Falls over backwards onto its back and bounces, with dust.",uses:["for"],run(t,e,n){const s=e.for??700;return t.key(n+s*.6,{tip:90},{act:!1,easing:"ease-in"}),t.key(n+s*.75,{tip:82},{act:!1,easing:"ease-out"}),t.key(n+s,{tip:90},{act:!1,easing:"ease-in"}),t.effect({kind:"dust",time:n+s*.6,x:t.x,y:t.floor,length:600}),{end:n+s,contact:n+s*.6}}}}}function ky(t={}){const e=t.width??1.4,n=t.depth??.7,s=t.height??.75,i={wood:"#8a5a3b",top:"#a9754a",knob:"#2b2b2b",...t.colors},r=.04,o=.03,a=.14,l=e*.4,c=[{id:"top",shape:{type:"box",size:[e,r,n]},at:[0,s-r/2,0],fill:i.top},{id:"drawer",shape:{type:"box",size:[l,a,n*.8]},at:[-e/2+l/2+.05,s-r-a/2,0],fill:i.wood},{id:"knob",parent:"drawer",shape:{type:"ellipsoid",radii:[.02,.02,.015],segments:8},at:[0,0,n*.4+.012],fill:i.knob,outline:.6}];for(const[u,d,f]of[[-1,1,"front-left"],[1,1,"front-right"],[-1,-1,"back-left"],[1,-1,"back-right"]])c.push({id:`leg-${f}`,shape:{type:"tube",points:[[0,0,0],[0,s-r,0]],radius:o,segments:6},at:[u*(e/2-o*2),0,d*(n/2-o*2)],fill:i.wood});const h={parts:c,controls:{drawer:{description:"The drawer out: 0 shut, 1 open",unit:"0..1",min:0,max:1,bind:[{parts:["drawer"],translate:[0,0,n*.5]}]}},length:n,height:s,footprint:[e,n],anchors:{top:{at:[0,s,0]},edge:{at:[0,s,n/2]},drawer:{part:"drawer",at:[0,0,n*.4]},chair:{at:[0,0,n/2+.35]}}};return{kind:t.kind??"desk",family:"furniture",summary:t.summary??"A desk: a top to work at (`top`, `edge`), a drawer that opens (`drawer`), a place for a chair in front (`chair`).",rig:h,actions:{drawer:{summary:"Opens the drawer (`open: true`) or shuts it (`open: false`).",needs:["open"],run(u,d,f){return u.key(f+400,{drawer:d.open?1:0},{easing:d.open?"ease-out":"ease-in"}),{end:f+500,contact:f+400}}}},acting:vy,colors:{body:i.top}}}const vy={depth:{drawer:1,roll:1,squash:1,size:0},limits:{drawer:.08,roll:1,squash:.04},eyes:[],headTurns:{},drift:[]};function My(t={}){const e=t.length??2,n=t.width??1,s=t.height??.55,i=t.headboard??.95,r={wood:"#8a5a3b",mattress:"#f1ece2",blanket:"#5b7fb0",pillow:"#fbf8f2",...t.colors},o=.3,a=s-o,c={parts:[{id:"frame",shape:{type:"box",size:[n,o,e]},at:[0,o/2,0],fill:r.wood},{id:"headboard",shape:{type:"box",size:[n+.06,i-o,.06]},at:[0,(i+o)/2,-e/2-.03],fill:r.wood},{id:"mattress",shape:{type:"box",size:[n-.04,a,e-.04]},at:[0,o+a/2,0],fill:r.mattress},{id:"blanket",parent:"mattress",shape:{type:"box",size:[n-.02,.04,e*.62]},at:[0,a/2+.02,e*.19],fill:r.blanket,outline:.7},{id:"pillow",parent:"mattress",shape:{type:"ellipsoid",radii:[n*.32,.07,.22],segments:12},at:[0,a/2+.06,-e/2+.32],fill:r.pillow,outline:.7}],controls:{give:{description:"The mattress pressed down: 1 as made, below squashed (someone landed on it)",unit:"factor",default:1,min:.5,max:1.2,bind:[{parts:["mattress"],scale:[1,1,1]}]}},length:e,height:i,footprint:[n,e],anchors:{mattress:{part:"mattress",at:[0,a/2,0]},pillow:{part:"mattress",at:[0,a/2+.1,-e/2+.32]},foot:{at:[0,s,e/2]},side:{at:[n/2+.25,0,0]}}};return{kind:t.kind??"bed",family:"furniture",summary:t.summary??"A bed: a mattress to lie on (`mattress`, `pillow`) that gives and springs back when someone lands on it (`bounce`), a side to sit on (`side`).",rig:c,actions:{bounce:{summary:"The mattress gives (someone landed on it) and springs back over `for` ms (default 700).",uses:["for"],run(h,u,d){const f=u.for??700,p=h.exaggeration;return h.key(d+90,{give:1-.18*p},{act:!1,easing:"ease-out"}),h.key(d+f*.45,{give:1+.05*p},{act:!1,easing:"ease-in-out"}),h.key(d+f*.7,{give:1-.04*p},{act:!1,easing:"ease-in-out"}),h.key(d+f,{give:1}),{end:d+f,contact:d+90}}}},acting:Sy,colors:{body:r.blanket}}}const Sy={depth:{give:1,roll:1,squash:1,size:0},limits:{give:.03,roll:.5,squash:.03},eyes:[],headTurns:{},drift:[]};function xy(t={}){const e=t.width??.9,n=t.height??2.05,s=t.hinge??"left",i={frame:"#d9d2c3",door:"#7a4b2a",handle:"#c9a227",beyond:"#2a2f3a",...t.colors},r=.1,o=s==="left"?1:-1,a=o>0?[[0,0],[-e,0],[-e,n],[0,n]]:[[0,0],[e,0],[e,n],[0,n]],c={parts:[{id:"post-left",shape:{type:"box",size:[r,n+r,r]},at:[e/2+r/2,(n+r)/2,0],fill:i.frame},{id:"post-right",shape:{type:"box",size:[r,n+r,r]},at:[-e/2-r/2,(n+r)/2,0],fill:i.frame},{id:"lintel",shape:{type:"box",size:[e+r*2,r,r]},at:[0,n+r/2,0],fill:i.frame},{id:"beyond",shape:{type:"panel",points:[[-e/2,0],[e/2,0],[e/2,n],[-e/2,n]],facing:"front"},at:[0,0,-.03],fill:i.beyond,outline:.4,seeThrough:!0},{id:"door",shape:{type:"panel",points:a,facing:"front"},at:[o*e/2,0,.005],fill:i.door,outline:.9,overRider:!0},{id:"handle",parent:"door",shape:{type:"ellipsoid",radii:[.03,.03,.03],segments:8},at:[-o*(e-.1),n*.47,.03],fill:i.handle,outline:.5}],controls:{open:{description:"How far the door is open: 0 shut, 1 open wide",unit:"0..1",min:0,max:1,bind:[{parts:["door"],rotate:{axis:"y",degrees:o*-95}}]}},length:.3,height:n+r,footprint:[e+r*2,.3],anchors:{handle:{part:"door",at:[-o*(e-.1),n*.47,.03]},doorway:{at:[0,0,0]},front:{at:[0,0,.5]},beyond:{at:[0,0,-.5]}}};return{kind:t.kind??"door",family:"furniture",summary:t.summary??"A door in its frame: opens and shuts on its hinge (`open`), slams, rattles when knocked; a figure goes through the `doorway` from `front` to `beyond`.",rig:c,actions:s4(),acting:Ty,colors:{body:i.door}}}const Ty={depth:{open:1,roll:1,squash:1,size:0},limits:{open:.08,roll:.6,squash:.03},eyes:[],headTurns:{},drift:[]};function s4(){return{open:{summary:"Opens the door (`open: true`, default) or shuts it (`open: false`), over `for` ms (default 600).",uses:["open","for"],run(t,e,n){const s=e.for??600;return t.key(n+s,{open:e.open===!1?0:1},{easing:"ease-in-out"}),{end:n+s+80,contact:n+s}}},slam:{summary:"Slams shut: a fast swing, a shudder in the frame, dust.",run(t,e,n){const s=t.exaggeration;t.key(n+180,{open:0},{act:!1,easing:"ease-in"});for(let i=1;i<=4;i++)t.key(n+180+i*70,{roll:(i%2===0?1:-1)*1.2*s*(1-i/5)},{act:!1});return t.key(n+180+350,{roll:0}),t.effect({kind:"dust",time:n+180,x:t.x,y:t.floor,length:500}),{end:n+180+350,contact:n+180}}},knock:{summary:"Someone knocks three times: the door rattles over `for` ms (default 700).",uses:["for"],run(t,e,n){const i=e.for??700,r=t.exaggeration;for(let o=0;o<3;o++){const a=n+i*(o+.5)/3;t.key(a,{open:.03*r},{act:!1,easing:"ease-out"}),t.key(a+60,{open:0},{act:!1,easing:"ease-in"})}return{end:n+i,contact:n+i/6}}}}}const Ey=1.4;function Ay(t={}){const e=t.width??.5,n=t.seatHeight??.5,s=t.wheelRadius??.3,i=.08,r={frame:"#2b2f36",seat:"#3c6ea5",tyre:"#1f2328",...t.colors},o=.04,a=.018,l=.44,c=n+.5,h=-.08,u=e/2+.06,d=[{id:"seat",shape:{type:"box",size:[e,o,l]},at:[0,n-o/2,0],fill:r.seat},{id:"back",shape:{type:"box",size:[e,c-n-.02,o]},at:[0,(c+n)/2,-l/2+o/2],fill:r.seat},{id:"footrest",shape:{type:"box",size:[e*.8,.02,.14]},at:[0,.12,l/2+.22],fill:r.frame}];for(const[g,m]of[[-1,"left"],[1,"right"]]){const y=g*u,v=(k,w,T=a)=>{d.push({id:k,shape:{type:"tube",points:w,radius:T,segments:6},fill:r.frame,outline:.7})};v(`post-${m}`,[[y,n-.1,-l/2],[y,c+.04,-l/2],[y,c+.04,-l/2-.14]]),v(`rail-${m}`,[[y,n-.03,-l/2],[y,n-.03,l/2]]),v(`leg-${m}`,[[y,n-.03,l/2],[y*.85,i,l/2+.06]]),v(`strut-${m}`,[[y*.85,i+.08,l/2+.04],[y*.8,.13,l/2+.22]]),v(`armrest-${m}`,[[y,n+.22,-l/2+.02],[y,n+.22,l/2-.08]],a*1.3),d.push({id:`wheel-${m}`,shape:{type:"cylinder",radius:s,length:.04,axis:"x",segments:20,spokes:8},at:[y+g*.03,s,h],ink:r.tyre,outline:1.3}),d.push({id:`rim-${m}`,shape:{type:"cylinder",radius:s*.9,length:.012,axis:"x",segments:20},at:[g*.045,0,0],parent:`wheel-${m}`,ink:r.frame,outline:.8}),d.push({id:`castor-${m}`,shape:{type:"cylinder",radius:i,length:.03,axis:"x",segments:12,spokes:3},at:[y*.85,i,l/2+.06],fill:r.tyre})}const f=d.map(g=>g.id).filter(g=>!g.startsWith("rim-")),p={parts:d,controls:{wheelSpin:{description:"How far the big wheels have turned, degrees (keyed with the distance rolled, so they never skate); the castors turn faster",unit:"degrees",bind:[{parts:["wheel-left","wheel-right"],rotate:{axis:"x",degrees:1}},{parts:["castor-left","castor-right"],rotate:{axis:"x",degrees:s/i}}]},tip:{description:"Tipped back on its big wheels (+), degrees: a wheelie, or a helper tipping it up a kerb",unit:"degrees",min:0,max:45,bind:[{parts:f,rotate:{axis:"x",degrees:1,pivot:[0,s,h]}}]}},length:l+.4,height:c+.04,footprint:[u*2+.1,l+.4],anchors:{seat:{at:[0,n,.02]},handles:{at:[0,0,-l/2-.5]},front:{at:[0,0,l/2+.6]},footrest:{at:[0,.13,l/2+.22]}}};return{kind:t.kind??"wheelchair",family:"furniture",summary:t.summary??"A wheelchair: rolls to `to` with its wheels turning the distance (roll), brakes, tips back on its big wheels (wheelie); its `seat` is ridden in the `wheeling` pose and a pusher stands at `handles`.",rig:p,actions:i4(s),acting:Py,colors:{body:r.seat,ink:r.frame},wheelRadius:s,moves:{roll:{speed:Ey,perMetre:{wheelSpin:180/(Math.PI*s)}}}}}const Py={depth:{wheelSpin:0,tip:1,roll:1,squash:1,size:0},limits:{tip:2,roll:1,squash:.03},eyes:[],headTurns:{},drift:[]};function $y(t,e,n,s,i,r,o=!1){const a=t.facing()||Math.sign(s-t.x)||1,l=t.values.wheelSpin??0,c=(s-t.x)*a/t.scale;t.set("wheelSpin",e,l),t.move(e,n,s,{easing:i}),t.set("wheelSpin",n,o?l:l+c/r*(180/Math.PI),i)}function i4(t){return{roll:{summary:"Rolls to `to` at `speed` px/ms (or over `for` ms): a small push-off, the wheels turning exactly the distance, and a gentle stop.",needs:["to"],uses:["speed","for"],run(e,n,s){const i=Math.sign(n.to-e.x);if(i===0)return{end:s};let r=s;e.facing()!==i&&(r=e.turnTo(r,i>0?"right":"left"));const o=Math.abs(n.to-e.x),a=n.for??Math.max(300,o/(n.speed??Ey*e.scale/1e3));return e.key(r+150,{tip:1.5*e.exaggeration},{act:!1,easing:"ease-out"}),$y(e,r,r+a,n.to,"ease-in-out",t),e.key(r+a,{tip:0},{easing:"ease-out"}),{end:r+a}}},brake:{summary:"Stops short at `to`: the wheels lock and it skids the last bit, tipping forward a touch.",needs:["to"],uses:["for"],run(e,n,s){if(Math.sign(n.to-e.x)===0)return{end:s};const r=n.for??500;return $y(e,s,s+r,n.to,"ease-out",t,!0),e.key(s+r,{tip:0},{easing:"ease-out"}),e.effect({kind:"dust",time:s+r*.5,x:n.to,y:e.floor,length:500}),{end:s+r,contact:s+r}}},wheelie:{summary:"Tips back onto its big wheels, balances there for `for` ms (default 1200), and drops down.",uses:["for"],run(e,n,s){const i=24*e.exaggeration,r=n.for??1200;return e.key(s+300,{tip:i},{easing:"ease-out"}),e.key(s+300+r*.5,{tip:i*.9},{act:!1,easing:"ease-in-out"}),e.key(s+300+r,{tip:i},{act:!1,easing:"ease-in-out"}),e.key(s+300+r+250,{tip:0},{easing:"ease-in"}),e.effect({kind:"dust",time:s+300+r+250,x:e.x,y:e.floor,length:400}),{end:s+300+r+250,contact:s+300+r+250}}}}}function Iy(t={}){const e={body:"#3f86c8",glass:"#cfeaf5",trim:"#2c2c33",rotor:"#3b3b44",...t.colors},n=2.15,i={parts:[{id:"cabin",shape:{type:"extrude",profile:[[-1.2,.6],[.9,.55],[1.6,.85],[1.65,1.25],[1.2,1.75],[-.6,1.85],[-1.3,1.45]],width:1.5},fill:e.body},{id:"window",shape:{type:"extrude",profile:[[.75,1],[1.6,.95],[1.6,1.3],[1.15,1.72],[.6,1.72]],width:1.54},fill:e.glass,outline:.8},{id:"boom",shape:{type:"tube",points:[[0,1.4,-1.2],[0,1.55,-3.4]],radius:.16,segments:8},fill:e.body},{id:"fin",shape:{type:"extrude",profile:[[-3.55,1.45],[-3.2,1.5],[-3.35,2.25],[-3.6,2.25]],width:.12},fill:e.body},{id:"mast",shape:{type:"tube",points:[[0,1.82,.1],[0,n,.1]],radius:.07,segments:6},fill:e.trim},{id:"rotor-disc",shape:{type:"cylinder",radius:2.4,length:.01,axis:"y",segments:28},at:[0,n+.02,.1],fill:"#c9d4dd",outline:.4,fade:{control:"blur",from:0,to:.45}},{id:"blades",shape:{type:"box",size:[.16,.03,4.8]},at:[0,n+.05,.1],fill:e.rotor,outline:.7,fade:{control:"blur",from:1,to:.3}},{id:"tail-rotor",shape:{type:"box",size:[.04,.9,.12]},at:[.12,1.85,-3.45],fill:e.rotor,outline:.6},{id:"skid-left",shape:{type:"tube",points:[[0,.08,-1.1],[0,.08,1.2],[0,.22,1.45]],radius:.05,segments:6},at:[.7,0,0],fill:e.trim},{id:"skid-right",shape:{type:"tube",points:[[0,.08,-1.1],[0,.08,1.2],[0,.22,1.45]],radius:.05,segments:6},at:[-.7,0,0],fill:e.trim},{id:"strut-left",shape:{type:"tube",points:[[.7,.08,.6],[.55,.62,.5]],radius:.04,segments:5},fill:e.trim},{id:"strut-right",shape:{type:"tube",points:[[-.7,.08,.6],[-.55,.62,.5]],radius:.04,segments:5},fill:e.trim}],controls:{rotor:{description:"How far the rotors have turned (keyed exactly, not acted; the blades blur into a disc when they spin fast)",unit:"degrees",bind:[{parts:["blades"],rotate:{axis:"y",degrees:1}},{parts:["tail-rotor"],rotate:{axis:"x",degrees:3,pivot:[0,0,0]}}]},blur:{description:"How blurred the main rotor is: 0 still blades, 1 a spinning disc",unit:"0..1",min:0,max:1}},length:5.2,height:2.4,footprint:[1.8,3.4],anchors:{seat:{at:[0,.75,.7]},door:{at:[-.76,1,.2]},rotor:{at:[0,n,.1]},skids:{at:[0,0,.2]},hook:{at:[0,.4,0]}}};return{kind:t.kind??"helicopter",family:"aircraft",summary:t.summary??"A cartoon helicopter: spools up and takes off, flies nose-down banking into its moves, hovers with a bob, and lands with a squash.",rig:i,actions:r4(),acting:vh,colors:{body:e.body,ink:"#26262b"},moves:{fly:{speed:15,flies:!0,hold:{blur:1},perSecond:{rotor:an*1e3}}}}}const vh={depth:{turn:0,lift:0,blur:0,pitch:1,roll:1,squash:1,lean:1,size:0},limits:{turn:.08,pitch:6,roll:6,squash:.06,lift:.15},eyes:[],headTurns:{},drift:[]},an=2.6;function r4(){const t=(n,s,i,r,o)=>{const a=n.values.rotor??0;n.set("rotor",s,a);const l=o?r*(i-s)*.5:r*(i-s);n.set("rotor",i,a+l,o)},e=n=>n.values.lift>.05;return{takeOff:{summary:"Spools the rotor up (the skids squash as it bites), then lifts off nose-down to `height` metres (default 3).",uses:["height"],run(n,s,i){const r=n.exaggeration,o=s.height??3;t(n,i,i+900,an,"ease-in"),n.key(i+900,{blur:1},{act:!1,easing:"ease-in"}),n.key(i+700,{squash:1-.08*r},{act:!1,easing:"ease-in"});const a=i+1e3;return n.key(a+150,{squash:1+.06*r,lift:.3},{act:!1,easing:"ease-out"}),n.key(a+1300,{squash:1,lift:o,pitch:-4*r},{act:!1,easing:"ease-in-out"}),n.key(a+1700,{pitch:0}),t(n,i+900,a+1700,an),n.effect({kind:"dust",time:a,x:n.x,y:n.floor,length:900}),{end:a+1700,contact:a}}},fly:{summary:"Flies to `to` (and to `height`, if given): nose down and banked into the move, nose up and leveling as it stops.",needs:["to"],uses:["height","speed","for"],run(n,s,i){const r=n.exaggeration,o=Math.sign(s.to-n.x);let a=i;o!==0&&n.facing()!==o&&(a=n.turnTo(a,o>0?"right":"left"));const l=Math.abs(s.to-n.x),c=s.for??Math.max(700,l/(s.speed??.3)),h=s.height??n.values.lift;return n.key(a+300,{pitch:-9*r,roll:6*r},{act:!1,easing:"ease-out"}),n.key(a+c-250,{pitch:-4*r,roll:3*r,lift:h},{act:!1}),n.key(a+c,{pitch:7*r,roll:0},{act:!1,easing:"ease-out"}),n.key(a+c+450,{pitch:0}),n.move(a,a+c,s.to,{easing:"ease-in-out"}),t(n,i,a+c+450,an),{end:a+c+450,contact:a,release:a+c}}},hover:{summary:"Hovers in place for `for` ms (default 2000), bobbing gently.",uses:["for"],run(n,s,i){const r=s.for??2e3,o=n.values.lift,a=n.exaggeration;for(let l=350,c=0;l<r;l+=350,c++)n.key(i+l,{lift:o+(c%2===0?.12:-.06)*a,roll:(c%2===0?1.5:-1.5)*a},{act:!1,easing:"ease-in-out"});return n.key(i+r,{lift:o,roll:0},{act:!1,easing:"ease-in-out"}),(e(n)||o>0)&&t(n,i,i+r,an),{end:i+r}}},land:{summary:"Settles down onto its skids: a flare, a squash on touchdown with dust, and the rotor spools down.",run(n,s,i){const r=n.exaggeration,o=i+Math.max(900,n.values.lift*450);return n.key(i+400,{pitch:3*r},{act:!1,easing:"ease-out"}),n.key(o,{lift:0,pitch:0,squash:1-.14*r},{act:!1,easing:"ease-in"}),n.key(o+280,{squash:1}),t(n,i,o,an),t(n,o,o+1600,an,"ease-out"),n.key(o+1600,{blur:0},{act:!1,easing:"ease-out"}),n.effect({kind:"dust",time:o,x:n.x,y:n.floor,length:800}),{end:o+1600,contact:o}}}}}function Oy(t={}){const e={body:"#e9e4d8",wings:"#d9483b",glass:"#cfeaf5",trim:"#2c2c33",...t.colors},n=3.15,i={parts:[{id:"fuselage",shape:{type:"extrude",profile:[[-3.7,1.55],[-2.6,1.05],[2.4,.85],[3,1],[3.1,1.4],[2.7,1.75],[1.4,1.9],[-2.9,1.85]],width:1},fill:e.body},{id:"canopy",shape:{type:"extrude",profile:[[.4,1.85],[1.6,1.85],[1.1,2.3],[.5,2.3]],width:.7},fill:e.glass,outline:.8},{id:"wing-left",shape:{type:"box",size:[3.6,.1,1.35]},at:[2.05,1.15,.55],fill:e.wings},{id:"wing-right",shape:{type:"box",size:[3.6,.1,1.35]},at:[-2.05,1.15,.55],fill:e.wings},{id:"tailplane-left",shape:{type:"box",size:[1.1,.07,.65]},at:[.6,1.7,-3.35],fill:e.wings},{id:"tailplane-right",shape:{type:"box",size:[1.1,.07,.65]},at:[-.6,1.7,-3.35],fill:e.wings},{id:"fin",shape:{type:"extrude",profile:[[-3.75,1.75],[-3,1.82],[-3.45,2.75],[-3.8,2.75]],width:.1},fill:e.wings},{id:"gear-left",shape:{type:"tube",points:[[.55,.95,1.2],[.75,.28,1.3]],radius:.04,segments:5},fill:e.trim},{id:"gear-right",shape:{type:"tube",points:[[-.55,.95,1.2],[-.75,.28,1.3]],radius:.04,segments:5},fill:e.trim},{id:"wheel-left",shape:{type:"cylinder",radius:.26,length:.14,axis:"x",segments:14},at:[.78,.26,1.3],fill:e.trim},{id:"wheel-right",shape:{type:"cylinder",radius:.26,length:.14,axis:"x",segments:14},at:[-.78,.26,1.3],fill:e.trim},{id:"tail-wheel",shape:{type:"cylinder",radius:.12,length:.08,axis:"x",segments:10},at:[0,.12,-3],fill:e.trim},{id:"tail-strut",shape:{type:"tube",points:[[0,.12,-3],[0,1.2,-2.9]],radius:.03,segments:5},fill:e.trim},{id:"spinner",shape:{type:"ellipsoid",radii:[.18,.18,.22],segments:10},at:[0,1.22,n],fill:e.wings,outline:.7},{id:"prop-disc",shape:{type:"cylinder",radius:.95,length:.01,axis:"z",segments:24},at:[0,1.22,n+.08],fill:"#c9d4dd",outline:.4,fade:{control:"blur",from:0,to:.45}},{id:"propeller",shape:{type:"box",size:[.12,1.85,.04]},at:[0,1.22,n+.1],fill:e.trim,outline:.6,fade:{control:"blur",from:1,to:.3}}],controls:{rotor:{description:"How far the propeller has turned (keyed exactly; it blurs into a disc at speed)",unit:"degrees",bind:[{parts:["propeller"],rotate:{axis:"z",degrees:1}}]},blur:{description:"How blurred the propeller is: 0 still, 1 a spinning disc",unit:"0..1",min:0,max:1}},length:7,height:2.8,footprint:[7.2,6.5],anchors:{seat:{at:[0,1.55,1]},nose:{at:[0,1.22,n+.2]},tail:{at:[0,1.6,-3.7]},wingtip:{at:[3.6,1.15,.55]}}};return{kind:t.kind??"airplane",family:"aircraft",summary:t.summary??"A propeller plane: takes off from a run, flies banked, loops the loop, and lands with a flare and a squash.",rig:i,actions:a4(),acting:vh,colors:{body:e.body,ink:"#26262b"},moves:{fly:{speed:30,flies:!0,hold:{blur:1},perSecond:{rotor:an*1e3}}}}}const o4=3.2;function a4(){const t=(n,s,i,r)=>{const o=n.values.rotor??0;n.set("rotor",s,o),n.set("rotor",i,o+o4*(i-s)*(r?.5:1),r)},e=(n,s,i)=>{const r=Math.sign(i-n.x);return r!==0&&n.facing()!==r?n.turnTo(s,r>0?"right":"left"):s};return{takeOff:{summary:"Spins the propeller up, runs along the ground toward `to`, lifts its nose and climbs to `height` metres (default 4).",needs:["to"],uses:["height","for"],run(n,s,i){const r=n.exaggeration,o=e(n,i,s.to);t(n,o,o+700,"ease-in"),n.key(o+700,{blur:1},{act:!1,easing:"ease-in"});const a=s.for??2600,l=n.x,c=o+700+a*.55,h=l+(s.to-l)*.45;return n.move(o+700,c,h,{easing:"ease-in"}),n.key(c,{pitch:8*r,squash:1+.04*r},{act:!1,easing:"ease-out"}),n.key(o+700+a,{lift:s.height??4,pitch:10*r,squash:1},{act:!1,easing:"ease-in-out"}),n.move(c,o+700+a,s.to),n.key(o+700+a+500,{pitch:0}),t(n,o+700,o+700+a+500),n.effect({kind:"dust",time:c,x:h,y:n.floor,length:700}),{end:o+700+a+500,contact:c}}},fly:{summary:"Flies to `to` (and `height`), banking into the move and leveling out.",needs:["to"],uses:["height","speed","for"],run(n,s,i){const r=n.exaggeration,o=e(n,i,s.to),a=s.for??Math.max(800,Math.abs(s.to-n.x)/(s.speed??.45)),l=s.height??n.values.lift;return n.key(o+350,{roll:10*r,pitch:l>n.values.lift?6*r:-3*r},{act:!1,easing:"ease-out"}),n.key(o+a-300,{roll:4*r,lift:l},{act:!1}),n.key(o+a,{roll:0,pitch:0}),n.move(o,o+a,s.to,{easing:"ease-in-out"}),t(n,i,o+a),{end:o+a,contact:o,release:o+a}}},loop:{summary:"Loops the loop: pulls up and over in a full circle (`for` ms, default 2400), carrying on the way it was going.",uses:["for"],run(n,s,i){const r=s.for??2400,o=2.2*n.exaggeration,a=n.facing()||1,l=16,c=n.x,h=n.values.lift,u=n.values.pitch;for(let d=1;d<=l;d++){const f=Math.PI*2*d/l,p=i+r*d/l;n.key(p,{lift:h+o*(1-Math.cos(f)),pitch:u+360*d/l},{act:!1}),n.move(i+r*(d-1)/l,p,c+a*(o*Math.sin(f)+d/l*o*1.2)*n.scale)}return n.key(i+r+1,{pitch:u},{act:!1}),t(n,i,i+r),{end:i+r+1}}},land:{summary:"Comes down toward `to`: descends, flares nose-up, touches down with a squash and dust, rolls to a stop and the propeller spools down.",needs:["to"],uses:["for"],run(n,s,i){const r=n.exaggeration,o=e(n,i,s.to),a=n.x,l=s.for??2200,c=o+l,h=a+(s.to-a)*.7;return n.key(o+l*.4,{pitch:-4*r},{act:!1,easing:"ease-out"}),n.key(c-250,{pitch:6*r,lift:.15},{act:!1,easing:"ease-in-out"}),n.key(c,{lift:0,pitch:0,squash:1-.12*r},{act:!1,easing:"ease-in"}),n.key(c+260,{squash:1}),n.move(o,c,h),n.move(c,c+1200,s.to,{easing:"ease-out"}),t(n,i,c),t(n,c,c+1600,"ease-out"),n.key(c+1600,{blur:0},{act:!1,easing:"ease-out"}),n.effect({kind:"dust",time:c,x:h,y:n.floor,length:700}),{end:c+1600,contact:c}}}}}const Os=["walk","trot","canter","gallop"],l4=Os,Cy=["fl","fr","hl","hr"],zo={walk:{offsets:{hl:0,fl:.25,hr:.5,fr:.75},swing:16,lift:45,bob:.02,rock:0,cycle:1100},trot:{offsets:{fl:0,hr:0,fr:.5,hl:.5},swing:22,lift:75,bob:.05,rock:0,cycle:640},canter:{offsets:{hr:0,hl:.33,fr:.33,fl:.66},swing:30,lift:70,bob:.08,rock:5,cycle:560},gallop:{offsets:{hr:0,hl:.1,fr:.5,fl:.6},swing:40,lift:80,bob:.1,rock:7,cycle:460}},ln=Math.PI/180;function qo(t,e){return 4*t*Math.sin(zo[e].swing*ln)}function cn(t){const{legs:e,colors:n}=t,s=e.upper+e.lower+e.foot,i=s+t.body.rise,r=(u,d)=>[d*u[0],u[1],u[2]],o=[{id:"body",shape:{type:"ellipsoid",radii:t.body.radii,segments:18},at:[0,i,0],fill:n.coat},{id:"neck",shape:{type:"tube",points:t.neck.points,radius:t.neck.points.map((u,d,f)=>t.neck.radius*(1.25-.4*d/Math.max(1,f.length-1))),segments:12},at:t.neck.at,fill:n.coat},{id:"head",parent:"neck",shape:{type:"ellipsoid",radii:t.head.radii,segments:14},at:t.head.at,rotate:t.head.rotate,fill:n.coat},...h4(t,n,i)];t.mane&&o.push({id:"mane",parent:"neck",shape:{type:"tube",points:t.mane.points,radius:t.mane.radius,segments:6},fill:n.dark,outline:.7}),t.muzzle&&o.push({id:"muzzle",parent:"head",shape:{type:"ellipsoid",radii:t.muzzle.radii,segments:10},at:t.muzzle.at,fill:n.muzzle,outline:.8});for(const u of[1,-1]){const d=u>0?"left":"right",f=t.ears.rotate?r(t.ears.rotate,1).map((p,g)=>g===2?u*p:p):void 0;o.push({id:`ear-${d}`,parent:"head",shape:{type:"ellipsoid",radii:t.ears.radii,segments:8},at:r(t.ears.at,u),rotate:f,fill:n.coat,outline:.7},{id:`eye-${d}`,parent:"head",shape:{type:"ellipsoid",radii:[t.eyes.size*.8,t.eyes.size,t.eyes.size*.9],segments:8},at:r(t.eyes.at,u),fill:"#1d1d22",outline:.4})}o.push(...t.extras?.(n)??[]);const a={walk:{description:"Phase of the stride, in full cycles (keyed in step with the distance covered)",unit:"cycles"},walking:{description:"How much of the gait is applied: 0 standing, 1 moving",unit:"0..1",min:0,max:1},gait:{description:`Which gait: ${t.gaits.map(u=>`${Os.indexOf(u)} ${u}`).join(", ")}`,unit:"index",min:0,max:3},neck:{description:"Neck bent down (+, eating, sniffing) or up (−, alert)",unit:"degrees",bind:[{parts:["neck"],rotate:{axis:"x",degrees:1}}]},tail:{description:"Tail flicked up and back (+), curling along its length, on a spring behind the motion",unit:"degrees",bind:[{parts:ke,rotate:{axis:"x",degrees:1/ke.length}}]},wag:{description:"Tail swung side to side, curling",unit:"degrees",bind:[{parts:ke,rotate:{axis:"y",degrees:1/ke.length}}]},ears:{description:"Ears pricked forward (+) or laid back (−), on a spring behind the motion",unit:"degrees",bind:[{parts:["ear-left","ear-right"],rotate:{axis:"x",degrees:1,pivot:[0,-t.ears.radii[1],0]}}]}};for(const u of Cy){const d=u[0]==="f",f=u[1]==="l"?1:-1,p=d?e.thickness[0]:e.thickness[1];o.push({id:`${u}-upper`,shape:{type:"tube",points:[[0,e.upper*.2,0],[0,-e.upper*.5,0],[0,-e.upper,0]],radius:[p,p*.85,e.lowerThickness*1.15],segments:10},at:[f*e.across,s,d?e.front:e.hind],fill:n.coat},{id:`${u}-knee`,parent:`${u}-upper`,shape:{type:"ellipsoid",radii:Array(3).fill(e.lowerThickness*1.08),segments:10},at:[0,-e.upper,0],fill:n.coat,solidOnly:!0},{id:`${u}-lower`,parent:`${u}-upper`,shape:{type:"tube",points:[[0,0,0],[0,-e.lower,0]],radius:[e.lowerThickness*1.1,e.lowerThickness*.85],segments:10},at:[0,-e.upper,0],fill:n.coat},{id:`${u}-foot`,parent:`${u}-lower`,shape:{type:"ellipsoid",radii:[e.footSize[0]/2,e.foot/2+.004,e.footSize[1]/2],segments:12},at:[0,-e.lower-e.foot/2,e.footSize[1]*.12],fill:n.foot,outline:.8});const g=`${d?"Front":"Hind"} ${f>0?"left":"right"} leg`;a[`${u}.swing`]={description:`${g}: forward (+) or back (−) from the hip`,unit:"degrees",bind:[{parts:[`${u}-upper`],rotate:{axis:"x",degrees:-1}}]},a[`${u}.knee`]={description:`${g}: knee (hock) folded`,unit:"degrees",bind:[{parts:[`${u}-lower`],rotate:{axis:"x",degrees:d?1:-1}}]},a[`${u}.ankle`]={description:`${g}: foot turned at the ankle (+ toe forward)`,unit:"degrees",bind:[{parts:[`${u}-foot`],rotate:{axis:"x",degrees:-1,pivot:[0,e.foot/2,-e.footSize[1]*.12]}}]}}const l=t.neck.points[t.neck.points.length-1],c={parts:o,controls:a,length:t.body.radii[2]*2+Math.max(0,t.neck.at[2]+l[2]+t.head.radii[2]-t.body.radii[2])+.3,height:t.neck.at[1]+l[1]+t.head.radii[1]*2,footprint:[e.across*2+t.body.radii[0],(e.front-e.hind)*1.4],anchors:{back:{at:[0,i+t.body.radii[1],-t.body.radii[2]*.05]},head:{part:"head",at:[0,0,0]},mouth:{part:t.muzzle?"muzzle":"head",at:t.muzzle?[0,0,t.muzzle.radii[2]]:[0,0,t.head.radii[2]]},front:{at:[0,i,t.body.radii[2]]},...t.anchors},derive:u=>u4(u,t,s)},h={legLength:s,upper:e.upper,lower:e.lower,foot:e.foot,tailHangs:t.tail.points[t.tail.points.length-1][1]<0,front:e.front,hind:e.hind,call(u,d){const f=u.anchor("mouth");u.effect({kind:"honk",time:d,x:f.x,y:f.y,length:800,direction:u.facing()||1})}};return{kind:t.kind,family:"animal",summary:t.summary,rig:c,actions:{...f4(t,h),...t.actions?.(h)},acting:Sh,colors:{body:n.coat,ink:"#26262b"},follow:[{control:"tail",of:"x",per:.6,stiffness:90,damping:6,limit:40},{control:"ears",of:"x",per:1.4,stiffness:150,damping:8,limit:45}],moves:c4(t,s)}}function c4(t,e){const n=i=>{const r=qo(e,i);return{speed:r/(zo[i].cycle*(t.cycleScale??1)/1e3),set:{gait:Os.indexOf(i)},hold:{walking:1},perMetre:{walk:1/r}}},s=Object.fromEntries(t.gaits.map(i=>[i==="gallop"&&!t.gaits.includes("canter")?"run":i,n(i)]));return t.gaits.includes("gallop")&&!s.gallop&&(s.gallop=n("gallop")),s}const ke=Array.from({length:7},(t,e)=>e===0?"tail":`tail-${e}`);function h4(t,e,n){const s=Pc(t.tail.points,ke.length+1),[,i,r]=t.body.radii,o=(t.tail.at[1]-n)/i,a=Math.abs(o)<1?-r*Math.sqrt(1-o*o):t.tail.at[2],l=[t.tail.at[0],t.tail.at[1],a+Math.min(.04,r*.08)],c=f=>t.tail.radius*(1-.5*f/ke.length),h=ke.map((f,p)=>{const g=s[p],m=s[p+1],y=[m[0]-g[0],m[1]-g[1],m[2]-g[2]],v=p===0?void 0:s[p-1];return{id:f,...p>0?{parent:ke[p-1]}:{},shape:{type:"tube",points:[[0,0,0],y],radius:[c(p),c(p+1)],segments:8,joined:!0},at:p===0?l:[g[0]-v[0],g[1]-v[1],g[2]-v[2]],fill:e.dark,outline:.8}}),u=s[s.length-1],d=s[s.length-2];return h.push({id:"tail-tip",parent:ke[ke.length-1],shape:{type:"ellipsoid",radii:Array(3).fill(c(ke.length)*1.05),segments:8},at:[u[0]-d[0],u[1]-d[1],u[2]-d[2]],fill:e.dark,outline:.8,solidOnly:!0}),h}function u4(t,e,n){const s=Math.max(0,Math.min(1,t.walking??0));if(s===0)return{};const i=Os[Math.max(0,Math.min(3,Math.round(t.gait??0)))],r=zo[e.gaits.includes(i)?i:e.gaits[0]],o=t.walk??0,a={};for(const c of Cy){const h=Math.PI*2*(o+r.offsets[c]);a[`${c}.swing`]=(t[`${c}.swing`]??0)+s*r.swing*Math.sin(h),a[`${c}.knee`]=(t[`${c}.knee`]??0)+s*r.lift*Math.max(0,Math.cos(h))}const l=Math.PI*2*o;return a.lift=(t.lift??0)+s*r.bob*n*Math.abs(Math.sin(l*2)),a.pitch=(t.pitch??0)+s*r.rock*Math.sin(l),a.neck=(t.neck??0)+s*(r.rock>0?-r.rock*1.4:5)*Math.sin(l*2),a}function Mh(t){const n=Math.sin(32*ln),s=t.legLength-(t.front-t.hind)*n,i=72,o=(s-t.upper*Math.cos(i*ln)-t.foot)/t.lower,a=o>=1?0:o<=-1?180:Math.acos(o)/ln,l={pitch:32,lift:t.legLength*(1-Math.cos(32*ln))-t.front*n,neck:-10,tail:t.tailHangs?35:-40,"fl.swing":-32,"fr.swing":-32};for(const c of["hl","hr"])l[`${c}.swing`]=i-32,l[`${c}.knee`]=-(i+a),l[`${c}.ankle`]=a;return l}const Sh={depth:{turn:0,lift:0,pitch:1,roll:1,squash:1,neck:2,tail:3,wag:3,"fl.swing":2,"fr.swing":2,"hl.swing":2,"hr.swing":2,"fl.knee":3,"fr.knee":3,"hl.knee":3,"hr.knee":3},limits:{pitch:6,neck:8,tail:10,wag:8,"fl.swing":8,"fr.swing":8,"hl.swing":8,"hr.swing":8,lift:0},eyes:[],headTurns:{},drift:[]},d4=Sh;function _y(t){const e=(t.upper+t.lower)*.32,n=Math.asin(Math.min(1,e/(t.upper+t.lower+t.foot)))/ln,s={pitch:0,lift:e-t.legLength,neck:-14,tail:t.tailHangs?60:-60,"fl.swing":90-n,"fr.swing":90-n,"fl.knee":0,"fr.knee":0,"fl.ankle":n,"fr.ankle":n};for(const i of["hl","hr"])s[`${i}.swing`]=70,s[`${i}.knee`]=-155,s[`${i}.ankle`]=85;return s}function f4(t,e){const n=t.cycleScale??1,s=o=>({summary:{walk:"Walks to `to` (four beats), its head bobbing.",trot:"Trots to `to`: legs in diagonal pairs, the body bouncing.",canter:"Canters to `to`: three beats, the body rocking.",gallop:"Gallops (runs) to `to`: legs reaching, the body rocking hard, kicking up dust."}[o],needs:["to"],uses:["for"],run(a,l,c){const h=Math.sign(l.to-a.x);if(h===0)return{end:c};let u=c;a.facing()!==h&&(u=a.turnTo(u,h>0?"right":"left"));const d=a.exaggeration;a.key(u+180,{neck:-12*d},{act:!1,easing:"ease-out"});const p=Math.abs(l.to-a.x)/a.scale/qo(e.legLength,o),g=l.for??Math.max(500,p*zo[o].cycle*n),m=a.values.walk??0;return a.set("gait",u,a.values.gait??0),a.set("gait",u+1,Os.indexOf(o)),a.set("walking",u,0),a.set("walking",u+240,1,"ease-out"),a.set("walking",u+g-240,1),a.set("walking",u+g,0,"ease-in"),a.set("walk",u,m),a.move(u,u+g,l.to,{easing:"ease-in-out"}),a.set("walk",u+g,m+p,"ease-in-out"),a.key(u+g+300,{neck:0}),(o==="gallop"||o==="canter")&&(a.effect({kind:"dust",time:u+200,x:a.x-h*e.legLength*a.scale,y:a.floor,length:700,direction:-h}),a.effect({kind:"dust",time:u+g,x:l.to+h*e.legLength*.6*a.scale,y:a.floor,length:600,direction:h})),{end:u+g+300,contact:u,release:u+g}}}),i=Object.fromEntries(t.gaits.map(o=>[o==="gallop"&&!t.gaits.includes("canter")?"run":o,s(o)]));t.gaits.includes("gallop")&&!i.gallop&&(i.gallop=s("gallop"));const r={...i,[t.call]:{summary:`Throws its head up and ${t.call}s.`,run(o,a,l){const c=o.exaggeration;return o.key(l+150,{neck:10*c},{act:!1,easing:"ease-out"}),o.key(l+380,{neck:-28*c,squash:1.05},{act:!1,easing:"ease-out"}),o.key(l+680,{neck:-20*c},{act:!1}),o.key(l+980,{neck:0,squash:1}),e.call(o,l+380),{end:l+980,contact:l+380}}},sit:{summary:"Sits on its haunches for `for` ms (default 1500): the rump goes down onto folded hind legs, paws flat on the ground, the front legs stay planted; then it gets up.",uses:["for"],run(o,a,l){const c=Mh(e),h=l+450;o.key(h,c,{act:!1,easing:"ease-in-out"}),o.key(h+(a.for??1500),c,{act:!1});const u=h+(a.for??1500)+450,d={};for(const f of Object.keys(c))d[f]=0;return o.key(u,d),{end:u,contact:h,release:u-450}}},lie:{summary:"Lies down for `for` ms (default 2000), head up and front paws forward (sinking back onto its haunches first), then gets up.",uses:["for"],run(o,a,l){const c=_y(e),h={...Mh(e)},u=l+400,d=u+450;o.key(u,h,{act:!1,easing:"ease-in-out"}),o.key(d,c,{act:!1,easing:"ease-in-out"}),o.key(d+(a.for??2e3),c,{act:!1});const f=d+(a.for??2e3)+600,p={};for(const g of new Set([...Object.keys(c),...Object.keys(h)]))p[g]=0;return o.key(f,p),{end:f,contact:d,release:f-600}}},jump:{summary:"Crouches and jumps (forward to `to`, or up on the spot), legs tucked in the air, landing with a squash and dust.",uses:["to"],run(o,a,l){const c=o.exaggeration,h=e.legLength*.8*c,u=l+260,d=u+90,f=d+520;if(o.key(u,{squash:.86,"hl.knee":40,"hr.knee":40,"fl.knee":25,"fr.knee":25,neck:8},{act:!1,easing:"ease-out"}),o.key(d,{squash:1.12,"hl.knee":0,"hr.knee":0,"fl.knee":0,"fr.knee":0,pitch:8,"fl.swing":35,"fr.swing":35,"hl.swing":-35,"hr.swing":-35},{act:!1,easing:"ease-out"}),o.key((d+f)/2,{lift:h,squash:1,pitch:0,"fl.knee":60,"fr.knee":60,"hl.knee":60,"hr.knee":60,"fl.swing":25,"fr.swing":25,"hl.swing":-20,"hr.swing":-20},{act:!1,easing:"ease-out"}),o.key(f,{lift:0,squash:.85,pitch:-4,"fl.knee":0,"fr.knee":0,"hl.knee":0,"hr.knee":0,"fl.swing":0,"fr.swing":0,"hl.swing":0,"hr.swing":0},{act:!1,easing:"ease-in"}),o.key(f+280,{squash:1,pitch:0,neck:0}),a.to!==void 0){const p=Math.sign(a.to-o.x);p!==0&&o.facing()!==p&&o.turnTo(l,p>0?"right":"left"),o.move(d,f,a.to)}return o.effect({kind:"dust",time:f,x:o.x,y:o.floor,length:550}),{end:f+280,contact:f}}},nod:{summary:"Nods its head twice.",run(o,a,l){return o.key(l+200,{neck:20},{act:!1,easing:"ease-out"}),o.key(l+400,{neck:-5},{act:!1,easing:"ease-in-out"}),o.key(l+600,{neck:18},{act:!1,easing:"ease-in-out"}),o.key(l+900,{neck:0}),{end:l+900}}},swish:{summary:"Swishes its tail a few times.",uses:["for"],run(o,a,l){const c=a.for??900;for(let h=1;h<=4;h++)o.key(l+c*h/5,{tail:h%2===0?10:35},{act:!1,easing:"ease-in-out"});return o.key(l+c,{tail:0}),{end:l+c}}}};return t.grazes&&(r.graze={summary:"Lowers its head to graze for `for` ms (default 1800), nibbling, then looks up.",uses:["for"],run(o,a,l){const c=a.for??1800;o.key(l+600,{neck:75},{act:!1,easing:"ease-in-out"});for(let h=900;h<600+c;h+=400)o.key(l+h,{neck:h%800===100?70:78},{act:!1,easing:"ease-in-out"});return o.key(l+600+c+500,{neck:0}),{end:l+600+c+500}}}),r}function Hy(t={}){return cn({kind:t.kind??"horse",summary:t.summary??"A cartoon horse: walks, trots, canters and gallops with its hooves in step with the ground, rears, bucks, neighs, grazes and swishes its tail.",legs:{upper:.5,lower:.42,foot:.08,footSize:[.12,.16],front:.62,hind:-.62,across:.2,thickness:[.075,.09],lowerThickness:.05},body:{radii:[.32,.36,.95],rise:.25},neck:{at:[0,1.42,.7],points:[[0,0,0],[0,.5,.3]],radius:.15},head:{at:[0,.48,.5],radii:[.13,.14,.3],rotate:[38,0,0]},muzzle:{at:[0,-.02,.24],radii:[.11,.1,.1]},ears:{at:[.07,.16,-.17],radii:[.035,.1,.05]},eyes:{at:[.115,.05,-.04],size:.04},tail:{at:[0,1.4,-.9],points:[[0,0,0],[0,-.22,-.2],[0,-.62,-.24]],radius:.08},mane:{points:[[0,.1,-.12],[0,.55,.17]],radius:.07},colors:{coat:"#b5763a",dark:"#4a2e1a",foot:"#3a2a22",muzzle:"#8d5a2c",accent:"#e8c9a0",...t.colors},gaits:["walk","trot","canter","gallop"],call:"neigh",grazes:!0,anchors:{hitch:{at:[0,.95,-.15]},saddle:{at:[0,1.6,-.05]}},actions:e=>({rear:{summary:"Rears up on its hind legs, front legs tucked and pawing, neighs, and drops back down with dust.",uses:["for"],run(n,s,i){const r=n.exaggeration,o=Math.min(55,32*r),a=-e.hind*Math.sin(o*ln),l=s.for??700;n.key(i+200,{pitch:-4,neck:6,"hl.knee":12,"hr.knee":12},{act:!1,easing:"ease-out"}),n.key(i+520,{pitch:o,lift:a,neck:-25,"fl.swing":55,"fl.knee":95,"fr.swing":40,"fr.knee":80,"hl.knee":0,"hr.knee":0},{act:!1,easing:"ease-out"}),n.key(i+520+l*.5,{"fl.swing":35,"fl.knee":70,"fr.swing":58,"fr.knee":100},{act:!1,easing:"ease-in-out"}),n.key(i+520+l,{"fl.swing":55,"fl.knee":95,"fr.swing":40,"fr.knee":80},{act:!1,easing:"ease-in-out"});const c=i+520+l+380;return n.key(c,{pitch:0,lift:0,neck:8,squash:.94,"fl.swing":0,"fl.knee":0,"fr.swing":0,"fr.knee":0},{act:!1,easing:"ease-in"}),n.key(c+320,{neck:0,squash:1}),e.call(n,i+520),n.effect({kind:"dust",time:c,x:n.x+(n.facing()||1)*e.front*n.scale,y:n.floor,length:600}),{end:c+320,contact:c}}},buck:{summary:"Bucks: drops its head and kicks both hind legs up and back.",run(n,s,i){const r=n.exaggeration,o=Math.min(35,18*r),a=e.front*Math.sin(o*ln);return n.key(i+220,{pitch:3,squash:.95},{act:!1,easing:"ease-out"}),n.key(i+480,{pitch:-o,lift:a,neck:30,"hl.swing":-65,"hr.swing":-60,"hl.knee":10,"hr.knee":10},{act:!1,easing:"ease-out"}),n.key(i+900,{pitch:0,lift:0,neck:0,squash:.95,"hl.swing":0,"hr.swing":0,"hl.knee":0,"hr.knee":0},{act:!1,easing:"ease-in"}),n.key(i+1150,{squash:1}),n.effect({kind:"dust",time:i+900,x:n.x-(n.facing()||1)*.6*n.scale,y:n.floor,length:600}),{end:i+1150,contact:i+480}}}})})}function Ry(t={}){return cn({kind:t.kind??"dog",summary:t.summary??"A cartoon dog: walks, trots and runs, barks, wags its tail, sits, jumps, sniffs the ground.",legs:{upper:.19,lower:.16,foot:.05,footSize:[.07,.1],front:.24,hind:-.24,across:.09,thickness:[.04,.05],lowerThickness:.032},body:{radii:[.14,.15,.36],rise:.1},neck:{at:[0,.56,.27],points:[[0,0,0],[0,.14,.06]],radius:.075},head:{at:[0,.15,.08],radii:[.12,.11,.13]},muzzle:{at:[0,-.03,.13],radii:[.065,.055,.08]},ears:{at:[.11,0,-.02],radii:[.025,.09,.05],rotate:[0,0,18]},eyes:{at:[.08,.04,.08],size:.025},tail:{at:[0,.58,-.34],points:[[0,0,0],[0,.1,-.08],[0,.2,-.1]],radius:.03},extras:e=>[{id:"nose",parent:"muzzle",shape:{type:"ellipsoid",radii:[.025,.02,.02],segments:8},at:[0,.03,.08],fill:"#1d1d22",outline:.4},{id:"patch",parent:"body",shape:{type:"ellipsoid",radii:[.012,.09,.11],segments:10},at:[.135,.04,-.06],fill:e.accent,outline:.5}],colors:{coat:"#d9a066",dark:"#a8703a",foot:"#a8703a",muzzle:"#f0d2a8",accent:"#f6ead8",...t.colors},gaits:["walk","trot","gallop"],cycleScale:.55,call:"bark",anchors:{leash:{part:"neck",at:[0,.06,0]}},actions:()=>({wag:{summary:"Wags its tail fast for `for` ms (default 1200).",uses:["for"],run(e,n,s){const i=n.for??1200;for(let r=80,o=0;r<i;r+=80,o++)e.key(s+r,{wag:o%2===0?35:-35,tail:25},{act:!1,easing:"ease-in-out"});return e.key(s+i,{wag:0,tail:0}),{end:s+i}}},sniff:{summary:"Puts its nose to the ground and sniffs (`for` ms, default 1400).",uses:["for"],run(e,n,s){const i=n.for??1400;e.key(s+350,{neck:70,pitch:-6},{act:!1,easing:"ease-in-out"});for(let r=500,o=0;r<i;r+=140,o++)e.key(s+r,{neck:o%2===0?74:66},{act:!1});return e.key(s+i+300,{neck:0,pitch:0}),{end:s+i+300}}}})})}function Fy(t={}){return cn({kind:t.kind??"cat",summary:t.summary??"A cartoon cat: walks, trots and runs, meows, arches its back, pounces, sits and swishes its tail.",legs:{upper:.13,lower:.11,foot:.035,footSize:[.05,.07],front:.17,hind:-.18,across:.06,thickness:[.028,.035],lowerThickness:.022},body:{radii:[.1,.105,.27],rise:.07},neck:{at:[0,.39,.2],points:[[0,0,0],[0,.08,.04]],radius:.05},head:{at:[0,.1,.05],radii:[.095,.085,.085]},muzzle:{at:[0,-.03,.07],radii:[.04,.03,.03]},ears:{at:[.055,.085,-.01],radii:[.03,.055,.02],rotate:[0,0,-12]},eyes:{at:[.045,.02,.07],size:.022},tail:{at:[0,.42,-.26],points:[[0,0,0],[0,.08,-.12],[0,.24,-.16],[0,.34,-.1]],radius:.022},extras:()=>[{id:"nose",parent:"muzzle",shape:{type:"ellipsoid",radii:[.014,.01,.01],segments:8},at:[0,.015,.03],fill:"#e48a9a",outline:.4}],colors:{coat:"#8f8a86",dark:"#5f5a57",foot:"#f2efe9",muzzle:"#f2efe9",accent:"#f2efe9",...t.colors},gaits:["walk","trot","gallop"],cycleScale:.5,call:"meow",actions:e=>({arch:{summary:"Arches its back, fur up and tail high, for `for` ms (default 1200): a startled cat.",uses:["for"],run(n,s,i){const r=n.exaggeration,o=s.for??1200,a={squash:1+.25*r,neck:25,tail:-45,"fl.swing":-8,"fr.swing":-8,"hl.swing":8,"hr.swing":8};return n.key(i+180,a,{act:!1,easing:"ease-out"}),n.key(i+180+o,a,{act:!1}),n.key(i+o+520,{squash:1,neck:0,tail:0,"fl.swing":0,"fr.swing":0,"hl.swing":0,"hr.swing":0}),{end:i+o+520,contact:i+180}}},pounce:{summary:"Crouches low, wiggles, and pounces to `to`, landing with a squash.",needs:["to"],run(n,s,i){const r=n.exaggeration,o=Math.sign(s.to-n.x);let a=i;o!==0&&n.facing()!==o&&(a=n.turnTo(a,o>0?"right":"left"));const l={squash:.75,"hl.knee":60,"hr.knee":60,"fl.knee":45,"fr.knee":45,neck:10,tail:-15};n.key(a+300,l,{act:!1,easing:"ease-out"});for(let u=1;u<=4;u++)n.key(a+300+u*110,{roll:u%2===0?3:-3},{act:!1});const c=a+300+550,h=c+480;return n.key(c,{roll:0,squash:1.2,"hl.knee":0,"hr.knee":0,"fl.knee":0,"fr.knee":0,"fl.swing":45,"fr.swing":45,"hl.swing":-45,"hr.swing":-45,tail:20},{act:!1,easing:"ease-out"}),n.key((c+h)/2,{lift:e.legLength*.9*r,squash:1.1,pitch:-6},{act:!1,easing:"ease-out"}),n.key(h,{lift:0,squash:.8,pitch:0,"fl.swing":0,"fr.swing":0,"hl.swing":0,"hr.swing":0,neck:0,tail:0},{act:!1,easing:"ease-in"}),n.key(h+260,{squash:1}),n.move(c,h,s.to),n.effect({kind:"dust",time:h,x:s.to,y:n.floor,length:450}),{end:h+260,contact:h}}}})})}function Ly(t={}){return cn({kind:t.kind??"cow",summary:t.summary??"A cartoon cow: walks and trots, moos, grazes, sits and swishes its tail.",legs:{upper:.42,lower:.36,foot:.08,footSize:[.13,.15],front:.68,hind:-.66,across:.24,thickness:[.085,.1],lowerThickness:.06},body:{radii:[.4,.42,1],rise:.32},neck:{at:[0,1.3,.85],points:[[0,0,0],[0,.22,.25]],radius:.19},head:{at:[0,.18,.4],radii:[.17,.19,.27],rotate:[30,0,0]},muzzle:{at:[0,-.06,.22],radii:[.15,.11,.1]},ears:{at:[.17,.06,-.12],radii:[.11,.035,.05],rotate:[0,0,-15]},eyes:{at:[.13,.06,.02],size:.04},tail:{at:[0,1.48,-1],points:[[0,0,0],[0,-.25,-.12],[0,-.7,-.14]],radius:.035},extras:e=>[{id:"horn-left",parent:"head",shape:{type:"tube",points:[[0,0,0],[.08,.12,.02]],radius:.025,segments:6},at:[.1,.16,-.14],fill:"#efe6d2",outline:.6},{id:"horn-right",parent:"head",shape:{type:"tube",points:[[0,0,0],[-.08,.12,.02]],radius:.025,segments:6},at:[-.1,.16,-.14],fill:"#efe6d2",outline:.6},{id:"udder",shape:{type:"ellipsoid",radii:[.16,.12,.18],segments:10},at:[0,.98,-.45],fill:"#f0a6b6",outline:.6},{id:"spot-1",parent:"body",shape:{type:"ellipsoid",radii:[.02,.2,.26],segments:10},at:[.39,.06,.2],fill:e.accent,outline:.4},{id:"spot-2",parent:"body",shape:{type:"ellipsoid",radii:[.02,.16,.22],segments:10},at:[-.39,.1,-.35],fill:e.accent,outline:.4},{id:"spot-3",parent:"body",shape:{type:"ellipsoid",radii:[.2,.02,.24],segments:10},at:[0,.41,-.2],fill:e.accent,outline:.4}],colors:{coat:"#f4f1ea",dark:"#2e2b2a",foot:"#3a3330",muzzle:"#f0b8c4",accent:"#2e2b2a",...t.colors},gaits:["walk","trot"],cycleScale:1.15,call:"moo",grazes:!0})}function g4(t){return qo(1,t)}function Ny(t={}){return cn({kind:t.kind??"goat",summary:t.summary??"A goat: walks, trots and gallops, bleats, grazes, sits, lies, jumps, and swishes its stubby tail.",legs:{upper:.22,lower:.2,foot:.05,footSize:[.07,.09],front:.26,hind:-.26,across:.1,thickness:[.045,.05],lowerThickness:.03},body:{radii:[.15,.17,.38],rise:.1},neck:{at:[0,.62,.3],points:[[0,0,0],[0,.16,.1]],radius:.07},head:{at:[0,.16,.1],radii:[.09,.1,.15],rotate:[-20,0,0]},muzzle:{at:[0,-.05,.13],radii:[.055,.05,.07]},ears:{at:[.1,.03,-.02],radii:[.06,.025,.03],rotate:[0,0,-20]},eyes:{at:[.065,.05,.09],size:.022},tail:{at:[0,.64,-.37],points:[[0,0,0],[0,.06,-.05]],radius:.025},extras:e=>[{id:"horn-left",parent:"head",shape:{type:"tube",points:[[0,0,0],[.01,.07,-.03],[.015,.12,-.08]],radius:.014,segments:6},at:[.045,.08,-.02],fill:e.dark},{id:"horn-right",parent:"head",shape:{type:"tube",points:[[0,0,0],[-.01,.07,-.03],[-.015,.12,-.08]],radius:.014,segments:6},at:[-.045,.08,-.02],fill:e.dark},{id:"beard",parent:"head",shape:{type:"ellipsoid",radii:[.025,.05,.02],segments:8},at:[0,-.12,.06],fill:e.accent,outline:.5}],colors:{coat:"#e9e2d3",dark:"#8c7b66",foot:"#4f4339",muzzle:"#d8cdb8",accent:"#cfc4b0",...t.colors},gaits:["walk","trot","gallop"],cycleScale:.8,call:"bleat",grazes:!0})}function Wy(t={}){return cn({kind:t.kind??"rabbit",summary:t.summary??"A rabbit: walks and hops (gallop), squeaks, nibbles the ground (graze), sits, lies and jumps; long ears and a puff of a tail.",legs:{upper:.07,lower:.07,foot:.03,footSize:[.04,.07],front:.11,hind:-.12,across:.06,thickness:[.028,.04],lowerThickness:.02},body:{radii:[.1,.11,.19],rise:.05},neck:{at:[0,.22,.14],points:[[0,0,0],[0,.06,.04]],radius:.05},head:{at:[0,.07,.04],radii:[.08,.075,.09]},muzzle:{at:[0,-.02,.07],radii:[.035,.028,.03]},ears:{at:[.035,.08,-.02],radii:[.022,.1,.03],rotate:[-15,0,-8]},eyes:{at:[.045,.015,.06],size:.02},tail:{at:[0,.2,-.18],points:[[0,0,0],[0,.03,-.02]],radius:.03},extras:()=>[{id:"nose",parent:"muzzle",shape:{type:"ellipsoid",radii:[.012,.009,.009],segments:8},at:[0,.012,.03],fill:"#e48a9a",outline:.4}],colors:{coat:"#c9b8a6",dark:"#9a8574",foot:"#b5a493",muzzle:"#eadfd2",accent:"#f4ece2",...t.colors},gaits:["walk","gallop"],cycleScale:.4,call:"squeak",grazes:!0})}function Dy(t={}){return cn({kind:t.kind??"squirrel",summary:t.summary??"A squirrel: scampers (gallop) and walks, chatters, sits up, nibbles (graze), with a bushy tail curled over its back.",legs:{upper:.05,lower:.05,foot:.02,footSize:[.025,.04],front:.08,hind:-.08,across:.04,thickness:[.02,.025],lowerThickness:.014},body:{radii:[.065,.07,.14],rise:.03},neck:{at:[0,.16,.1],points:[[0,0,0],[0,.04,.03]],radius:.035},head:{at:[0,.05,.03],radii:[.055,.05,.06]},muzzle:{at:[0,-.015,.05],radii:[.025,.02,.02]},ears:{at:[.03,.05,-.01],radii:[.015,.03,.012],rotate:[0,0,-5]},eyes:{at:[.035,.012,.04],size:.015},tail:{at:[0,.14,-.13],points:[[0,0,0],[0,.08,-.06],[0,.2,-.04],[0,.26,.04]],radius:.045},colors:{coat:"#a9663a",dark:"#7a4523",foot:"#7a4523",muzzle:"#e9c9a8",accent:"#f0dcc4",...t.colors},gaits:["walk","gallop"],cycleScale:.3,call:"chatter",grazes:!0})}const hn=.6,By=75,xh=80;function un(t){const{colors:e}=t,[n,s,i]=t.body.radii,r=(t.tail.raised??15)*Math.PI/180,o=t.tail.length*.4,a=[{id:"body",shape:{type:"ellipsoid",radii:t.body.radii,segments:16},at:[0,t.body.height,0],fill:e.body},{id:"neck",shape:{type:"ellipsoid",radii:[n*.55,s*.55,i*.3],segments:10},at:[0,t.body.height+s*.45,i*.65],fill:e.body,outline:.5,solidOnly:!0},{id:"head",parent:"neck",shape:{type:"ellipsoid",radii:[t.head.radius,t.head.radius*1.02,t.head.radius*1.05],segments:14},at:[t.head.at[0],t.head.at[1]-(t.body.height+s*.45),t.head.at[2]-i*.65],fill:e.body},{id:"beak",parent:"head",shape:{type:"tube",points:[[0,0,0],[0,-t.beak.thickness*.4,t.beak.length]],radius:[t.beak.thickness,t.beak.thickness*.08],segments:8},at:[0,-t.head.radius*.1,t.head.radius*.8],fill:e.beak,outline:.8},{id:"tail",shape:{type:"ellipsoid",radii:[t.tail.width/2,.012*(i/.08),t.tail.length/2],segments:10},at:[t.tail.at[0],t.tail.at[1]+o*Math.sin(r),t.tail.at[2]-o*Math.cos(r)],rotate:[t.tail.raised??15,0,0],fill:e.wing,outline:.8}];if(e.belly&&a.push({id:"belly",parent:"body",shape:{type:"ellipsoid",radii:[n*.82,s*.7,i*.75],segments:12},at:[0,-s*.25,i*.12],fill:e.belly,outline:.4}),t.comb){const h=t.head.radius;a.push({id:"comb",parent:"head",shape:{type:"extrude",profile:[[-h*.5,h*.6],[h*.6,h*.6],[h*.5,h*1.3],[h*.15,h*1.05],[-h*.05,h*1.4],[-h*.3,h*1.05],[-h*.6,h*1.25]],width:h*.25},fill:e.comb??"#d9372e",outline:.7},{id:"wattle",parent:"head",shape:{type:"ellipsoid",radii:[h*.15,h*.35,h*.2],segments:8},at:[0,-h*.7,h*.6],fill:e.comb??"#d9372e",outline:.6})}for(const h of[1,-1]){const u=h>0?"left":"right",d=t.head.radius;a.push({id:`eye-${u}`,parent:"head",shape:{type:"ellipsoid",radii:[d*.16,d*.2,d*.18],segments:8},at:[h*d*.72,d*.18,d*.42],fill:"#1d1d22",outline:.3}),a.push({id:`wing-${u}`,shape:{type:"ellipsoid",radii:[.004,.004,.004],segments:4},at:[h*t.wing.shoulder[0],t.wing.shoulder[1],t.wing.shoulder[2]],rotate:[-8,h*90,0],outline:0}),a.push({id:`wing-${u}-blade`,parent:`wing-${u}`,shape:{type:"ellipsoid",radii:[t.wing.span*hn/2,t.wing.chord*.1,t.wing.chord/2],segments:12},at:[h*t.wing.span*hn/2,0,-t.wing.chord*.1],rotate:[-xh,0,0],fill:e.wing,outline:.8}),a.push({id:`wing-${u}-tip`,parent:`wing-${u}-blade`,shape:{type:"ellipsoid",radii:[t.wing.span*hn/2.4,t.wing.chord*.06,t.wing.chord*.3],segments:10},at:[h*t.wing.span*hn/4,0,-t.wing.chord*.3],rotate:[0,h*14,0],fill:e.wing,outline:.8}),a.push({id:`leg-${u}`,shape:{type:"tube",points:[[0,0,0],[0,-t.legs.length,0]],radius:Math.max(.004,t.legs.length*.05),segments:5},at:[h*t.legs.across,t.legs.length,0],fill:e.legs,outline:.6}),a.push({id:`toes-${u}`,parent:`leg-${u}`,shape:{type:"tube",points:[[0,0,-t.legs.length*.15],[0,0,t.legs.length*.35]],radius:Math.max(.003,t.legs.length*.04),segments:5},at:[0,-t.legs.length,0],fill:e.legs,outline:.6})}const l={spread:{description:"Wings: 0 folded back along the body, 1 spread out",unit:"0..1",min:0,max:1,bind:[{parts:["wing-left"],rotate:{axis:"y",degrees:-90}},{parts:["wing-right"],rotate:{axis:"y",degrees:90}},{parts:["wing-left-blade"],translate:[t.wing.span*(1-hn)/2,0,0],rotate:{axis:"x",degrees:xh},scale:[1/hn,1,1]},{parts:["wing-right-blade"],translate:[-t.wing.span*(1-hn)/2,0,0],rotate:{axis:"x",degrees:xh},scale:[1/hn,1,1]}]},flap:{description:"Wings raised (+) or lowered (−) at the shoulders",unit:"degrees",bind:[{parts:["wing-left"],rotate:{axis:"z",degrees:1}},{parts:["wing-right"],rotate:{axis:"z",degrees:-1}}]},wingbeat:{description:"Phase of the wingbeat, in beats (keyed steadily while flapping)",unit:"beats"},flapping:{description:"How hard the wings beat: 0 still, 1 full beats",unit:"0..1",min:0,max:1},peck:{description:"Head bobbed down and forward (+, pecking) or up (−)",unit:"degrees",bind:[{parts:["neck"],rotate:{axis:"x",degrees:1},translate:[0,-(t.neckReach??0)/By,0]}]},step:{description:"Phase of a walk, in steps (a chicken’s legs)",unit:"steps"},stepping:{description:"How much of the walk is applied",unit:"0..1",min:0,max:1},"leg.left":{description:"Left leg swung forward (+)",unit:"degrees",bind:[{parts:["leg-left"],rotate:{axis:"x",degrees:-1}}]},"leg.right":{description:"Right leg swung forward (+)",unit:"degrees",bind:[{parts:["leg-right"],rotate:{axis:"x",degrees:-1}}]},grip:{description:"The toes curled down round a perch: 0 flat on the ground, 1 gripping",unit:"0..1",min:0,max:1,bind:[{parts:["toes-left","toes-right"],rotate:{axis:"x",degrees:55}}]}},c={parts:a,controls:l,length:i*2+t.tail.length+t.beak.length,height:t.head.at[1]+t.head.radius,footprint:[n*2.2,i*2.4],anchors:{beak:{part:"beak",at:[0,0,t.beak.length]},head:{part:"head",at:[0,0,0]},back:{at:[0,t.body.height+s,0]},feet:{at:[0,0,0]}},derive:h=>{const u={},d=Math.max(0,Math.min(1,h.flapping??0));d>0&&(u.flap=(h.flap??0)+d*48*Math.sin(Math.PI*2*(h.wingbeat??0)));const f=Math.max(0,Math.min(1,h.stepping??0));if(f>0){const p=Math.sin(Math.PI*2*(h.step??0));u["leg.left"]=(h["leg.left"]??0)+f*28*p,u["leg.right"]=(h["leg.right"]??0)-f*28*p,u.peck=(h.peck??0)+f*12*Math.sin(Math.PI*4*(h.step??0))}return u}};return{kind:t.kind,family:"bird",summary:t.summary,rig:c,actions:m4(t),acting:zy,colors:{body:e.body,ink:"#26262b"},moves:p4(t)}}function p4(t){const e=t.legs.length*1.2,n={walk:{speed:e/.42,hold:{stepping:1},perMetre:{step:.5/e}}};return t.flies!==!1&&(n.fly={speed:4+t.wing.span*12,flies:!0,hold:{flapping:1,spread:1},perSecond:{wingbeat:t.beatsPerSecond??4}}),n}const zy={depth:{turn:0,lift:0,pitch:1,roll:1,squash:1,spread:1,flap:2,peck:2},limits:{pitch:6,roll:6,squash:.06,peck:8,flap:10,lift:0},eyes:[],headTurns:{},drift:[]};function m4(t){const e=(t.beatsPerSecond??4)/1e3,n=(o,a,l)=>{const c=o.values.wingbeat??0;o.set("wingbeat",a,c),o.set("wingbeat",l,c+(l-a)*e)},s=(o,a,l)=>{const c=Math.sign(l-o.x);return c!==0&&o.facing()!==c?o.turnTo(a,c>0?"right":"left"):a},i=(o,a)=>{const l=o.anchor("beak");o.effect({kind:"honk",time:a,x:l.x,y:l.y,length:600,direction:o.facing()||1})},r={hop:{summary:"Hops to `to` in little bounces, wings twitching.",needs:["to"],run(o,a,l){const c=s(o,l,a.to),h=o.x,u=Math.abs(a.to-h),d=Math.max(1,Math.round(u/(t.body.radii[2]*3*o.scale))),f=260;for(let p=0;p<d;p++){const g=c+p*f;o.key(g+60,{squash:.85},{act:!1,easing:"ease-out"}),o.key(g+150,{squash:1.1,lift:t.legs.length*1.4,spread:.15},{act:!1,easing:"ease-out"}),o.key(g+f,{squash:.9,lift:0,spread:0},{act:!1,easing:"ease-in"}),o.move(g+60,g+f,h+(a.to-h)*(p+1)/d,{easing:"ease-in-out"})}return o.key(c+d*f+120,{squash:1}),{end:c+d*f+120}}},walk:{summary:"Walks to `to` on its two legs, its head bobbing with each step.",needs:["to"],uses:["for"],run(o,a,l){const c=s(o,l,a.to),h=Math.abs(a.to-o.x)/o.scale,u=t.legs.length*1.2,d=h/u,f=a.for??Math.max(400,d*420),p=o.values.step??0;return o.set("stepping",c,0),o.set("stepping",c+150,1,"ease-out"),o.set("stepping",c+f-150,1),o.set("stepping",c+f,0,"ease-in"),o.set("step",c,p),o.move(c,c+f,a.to,{easing:"ease-in-out"}),o.set("step",c+f,p+d/2,"ease-in-out"),{end:c+f,contact:c,release:c+f}}},peck:{summary:"Pecks at the ground (`for` ms, default 900): quick jabs of the head.",uses:["for"],run(o,a,l){const c=a.for??900,h=Math.max(1,Math.round(c/300));o.key(l+120,{pitch:-(t.stoop??12)},{act:!1,easing:"ease-out"});for(let u=0;u<h;u++)o.key(l+120+u*300+90,{peck:By},{act:!1,easing:"ease-in"}),o.key(l+120+u*300+260,{peck:20},{act:!1,easing:"ease-out"});return o.key(l+120+h*300+200,{peck:0,pitch:0}),{end:l+120+h*300+200,contact:l+210}}},flap:{summary:"Flaps its wings on the spot (`for` ms, default 900), lifting a little.",uses:["for"],run(o,a,l){const c=a.for??900;return o.key(l+120,{spread:1},{act:!1,easing:"ease-out"}),o.set("flapping",l,0),o.set("flapping",l+150,1,"ease-out"),o.set("flapping",l+c-150,1),o.set("flapping",l+c,0,"ease-in"),n(o,l,l+c),o.key(l+c*.5,{lift:t.legs.length*.6},{act:!1,easing:"ease-out"}),o.key(l+c,{lift:0,spread:0},{act:!1,easing:"ease-in"}),{end:l+c+80}}},[t.call]:{summary:`${t.call[0].toUpperCase()}${t.call.slice(1)}s: its head comes up and its beak opens to call.`,run(o,a,l){return o.key(l+120,{peck:-25,squash:1.06},{act:!1,easing:"ease-out"}),o.key(l+500,{peck:-20},{act:!1}),o.key(l+760,{peck:0,squash:1}),i(o,l+150),{end:l+760,contact:l+150}}}};return t.flies!==!1?(r.fly={summary:"Takes off (a crouch and a leap, wings beating) and flies to `to` at `height` metres (default 2); `land` brings it down.",needs:["to"],uses:["height","for"],run(o,a,l){const c=o.exaggeration;o.key(l+60,{grip:0},{act:!1});const h=s(o,l,a.to),u=a.height??2,d=a.for??Math.max(700,Math.abs(a.to-o.x)/.35),f=o.values.lift>t.legs.length,p=f?h:h+200;return f||(o.key(h+160,{squash:1-.18*c,spread:.6},{act:!1,easing:"ease-out"}),o.effect({kind:"dust",time:p,x:o.x,y:o.floor,length:400})),o.key(p+100,{spread:1,squash:1.08,pitch:10},{act:!1,easing:"ease-out"}),o.set("flapping",p,o.values.flapping??0),o.set("flapping",p+100,1,"ease-out"),o.set("flapping",p+d,.6),n(o,p,p+d),o.key(p+d*.4,{lift:u,pitch:-5,squash:1},{act:!1,easing:"ease-out"}),o.key(p+d,{lift:u,pitch:0},{act:!1,easing:"ease-in-out"}),o.move(p,p+d,a.to,{easing:"ease-in-out"}),{end:p+d,contact:p,release:p+d}}},r.glide={summary:"Glides to `to` on still, spread wings, sinking gently to `height` metres (default: a third lower than it is); from the ground it takes off first, flying the first stretch.",needs:["to"],uses:["height","for"],run(o,a,l){let c=l;if(o.values.lift<=t.legs.length){const f=o.x+(a.to-o.x)/3;c=r.fly.run(o,{do:"fly",to:f,height:(a.height??1.5)*1.3},l).end}c=s(o,c,a.to);const h=o.values.lift,u=a.height??h*.67,d=a.for??Math.max(900,Math.abs(a.to-o.x)/.3);return o.set("flapping",c,o.values.flapping??1),o.set("flapping",c+250,0,"ease-out"),n(o,c,c+250),o.key(c+300,{spread:1,flap:10,pitch:-6},{act:!1,easing:"ease-out"}),o.key(c+d,{lift:u,pitch:-3,flap:10},{act:!1,easing:"ease-in-out"}),o.move(c,c+d,a.to,{easing:"ease-in-out"}),{end:c+d,contact:c,release:c+d}}},r.land={summary:"Comes down to the floor it is over (or to `height` metres above it, a branch or a roof): wings braking, a squash on touchdown.",uses:["height","to"],run(o,a,l){const h=a.height??0;return o.set("flapping",l,o.values.flapping??1),o.set("flapping",l+700-120,1),o.set("flapping",l+700,0,"ease-in"),n(o,l,l+700),o.key(l+700*.6,{pitch:14},{act:!1,easing:"ease-out"}),o.key(l+700,{lift:h,pitch:0,squash:.85,grip:h>0?1:0},{act:!1,easing:"ease-in"}),a.to!==void 0&&o.move(l,l+700,a.to,{easing:"ease-out"}),o.key(l+700+160,{squash:1,spread:0,flap:0}),{end:l+700+200,contact:l+700}}}):r.flutter={summary:"Flutters up a little way and back down, wings beating hard (a chicken’s flight).",run(o,a,l){return o.key(l+100,{spread:1,squash:.9},{act:!1,easing:"ease-out"}),o.set("flapping",l+80,0),o.set("flapping",l+160,1,"ease-out"),o.set("flapping",l+900-100,1),o.set("flapping",l+900,0,"ease-in"),n(o,l+80,l+900),o.key(l+900*.5,{lift:t.legs.length*2.5,squash:1.08},{act:!1,easing:"ease-out"}),o.key(l+900,{lift:0,squash:.85,spread:0},{act:!1,easing:"ease-in"}),o.key(l+900+160,{squash:1}),{end:l+900+160,contact:l+900}}},r}function qy(t={}){return un({kind:"songbird",summary:"A small songbird: hops, pecks, tweets, flaps, flies and lands (on the ground, a branch or a roof).",body:{radii:[.05,.05,.075],height:.085},head:{at:[0,.145,.065],radius:.036},beak:{length:.03,thickness:.01},wing:{shoulder:[.04,.1,.03],span:.11,chord:.06},tail:{at:[0,.095,-.07],length:.07,width:.045},legs:{length:.04,across:.018},colors:{body:"#7b6a58",wing:"#5c4c3d",beak:"#e7a43a",legs:"#c47a35",belly:"#e9c8a3",...t.colors},call:"tweet",beatsPerSecond:9})}function jy(t={}){return un({kind:"crow",summary:"A crow: walks and hops, pecks, caws, flaps, flies and lands (on the ground, a branch or a roof).",body:{radii:[.09,.09,.17],height:.2},head:{at:[0,.32,.15],radius:.065},beak:{length:.08,thickness:.022},wing:{shoulder:[.07,.24,.06],span:.32,chord:.14},tail:{at:[0,.2,-.15],length:.16,width:.09},legs:{length:.1,across:.035},colors:{body:"#2b2b33",wing:"#1e1e25",beak:"#3b3b44",legs:"#3b3b44",...t.colors},call:"caw",beatsPerSecond:4})}function Yy(t={}){return un({kind:"chicken",summary:"A chicken: walks with a bobbing head, pecks, clucks, and flutters up and down (it cannot really fly).",body:{radii:[.13,.14,.19],height:.3},head:{at:[0,.5,.16],radius:.07},beak:{length:.05,thickness:.02},wing:{shoulder:[.11,.34,.04],span:.24,chord:.15},tail:{at:[0,.38,-.15],length:.16,width:.13,raised:50},legs:{length:.17,across:.05},comb:!0,stoop:20,neckReach:.12,colors:{body:"#f4ede0",wing:"#e6dccb",beak:"#e7a43a",legs:"#e7a43a",comb:"#d9372e",...t.colors},call:"cluck",flies:!1})}function Ky(t={}){return un({kind:"pigeon",summary:"A pigeon: walks with a bobbing head, pecks at crumbs, coos, flaps, flies and lands (on the ground, a ledge or a branch).",body:{radii:[.08,.075,.14],height:.14},head:{at:[0,.24,.12],radius:.045},beak:{length:.035,thickness:.014},wing:{shoulder:[.065,.17,.05],span:.24,chord:.11},tail:{at:[0,.13,-.13],length:.12,width:.08,raised:8},legs:{length:.06,across:.03},colors:{body:"#8d93a3",wing:"#6f7586",beak:"#5a5a66",legs:"#d9627a",belly:"#b9bdc8",...t.colors},call:"coo",beatsPerSecond:6,stoop:16})}function Xy(t={}){return un({kind:"duck",summary:"A duck: waddles, dabbles with its bill (peck), quacks, flaps, flies and lands (on the ground or the water’s edge).",body:{radii:[.11,.1,.2],height:.16},head:{at:[0,.33,.15],radius:.055},beak:{length:.075,thickness:.028},wing:{shoulder:[.09,.22,.06],span:.28,chord:.13},tail:{at:[0,.17,-.19],length:.1,width:.09,raised:30},legs:{length:.07,across:.045},colors:{body:"#c9b48b",wing:"#8f7a55",beak:"#f2a71b",legs:"#f2a71b",belly:"#e8dcc0",...t.colors},call:"quack",beatsPerSecond:7,stoop:22,neckReach:.04})}function Gy(t={}){return un({kind:"owl",summary:"An owl: a big round head, slow silent wingbeats; hoots, turns its head, flies and lands on a branch.",body:{radii:[.1,.12,.13],height:.19},head:{at:[0,.37,.07],radius:.085},beak:{length:.025,thickness:.02},wing:{shoulder:[.085,.27,.03],span:.34,chord:.18},tail:{at:[0,.14,-.12],length:.1,width:.1,raised:-10},legs:{length:.07,across:.04},colors:{body:"#9c7a55",wing:"#6e5538",beak:"#3d3028",legs:"#c9a76a",belly:"#e3cda8",...t.colors},call:"hoot",beatsPerSecond:3,stoop:6})}function Uy(t={}){return un({kind:"parrot",summary:"A parrot: bright, with a big hooked beak and a long tail; squawks, bobs, flies and lands on a perch, gripping it.",body:{radii:[.07,.08,.13],height:.15},head:{at:[0,.29,.1],radius:.055},beak:{length:.045,thickness:.03},wing:{shoulder:[.06,.2,.05],span:.26,chord:.11},tail:{at:[0,.12,-.12],length:.22,width:.06,raised:-20},legs:{length:.06,across:.03},colors:{body:"#4caf50",wing:"#2e7d32",beak:"#5a5a66",legs:"#8d8d8d",belly:"#a5d66f",comb:"#d9372e",...t.colors},call:"squawk",beatsPerSecond:6,stoop:10})}const Cs={car:oy,truck:ay,bus:ly,tractor:cy,cart:hy,trainCar:uy,bike:dy,motorbike:fy,tree:gy,house:my,chair:by,desk:ky,bed:My,door:xy,wheelchair:Ay,helicopter:Iy,airplane:Oy,horse:Hy,dog:Ry,cat:Fy,cow:Ly,goat:Ny,rabbit:Wy,squirrel:Dy,songbird:qy,crow:jy,chicken:Yy,pigeon:Ky,duck:Xy,owl:Gy,parrot:Uy};function Th(t,e={}){const n=Cs[t];if(!n)throw new Error(ft("prop preset",t,Object.keys(Cs)));return n(e)}const jo=["do","at","for","to","toward","speed","open","on","height","wind"],Eh={viewer:0,right:1,away:2,left:3},y4=420,Ah={hold:{summary:"Holds still (`for` ms, default 1000).",run:(t,e,n)=>({end:n+(e.for??1e3)})},turn:{summary:"Turns to face `toward`: viewer, right, away, left, or a quarter-turn value (it turns in 3D, through the nearer way).",needs:["toward"],run:(t,e,n)=>({end:t.turnTo(n,e.toward)})},pop:{summary:"Pops into being: grows from nothing, stretched, overshoots and settles (`for` ms, default 500).",uses:["for"],run(t,e,n){const s=e.for??500,i=t.exaggeration;return t.key(n,{size:0,squash:1},{act:!1}),t.key(n+s*.6,{size:1+.15*i,squash:1+.15*i},{act:!1,easing:"ease-out"}),t.key(n+s,{size:1,squash:1}),{end:n+s,contact:n}}},vanish:{summary:"Shrinks away to nothing, with a little stretch first (`for` ms, default 400).",uses:["for"],run(t,e,n){const s=e.for??400,i=t.exaggeration;return t.key(n+s*.3,{size:1+.08*i,squash:1+.12*i},{act:!1,easing:"ease-out"}),t.key(n+s,{size:0,squash:1},{act:!1,easing:"ease-in"}),{end:n+s,release:n+s}}}};function Yo(t){return{...Ah,...t.actions}}const Ph=t=>typeof t=="number"&&Number.isFinite(t);function Vy(t,e){if(!Array.isArray(t))return[{level:"error",beat:-1,message:`Beats must be an array of { do: … } objects (got ${typeof t}).`}];const n=Yo(e),s=Object.keys(n),i=[];return t.forEach((r,o)=>{const a=c=>i.push({level:"error",beat:o,message:c});if(!r||typeof r!="object"||Array.isArray(r))return a(`Each beat must be an object like { do: '${s[s.length-1]}' }.`);const l=r;for(const c of Object.keys(l))jo.includes(c)||a(ft("beat field",c,jo,c==="duration"?"for":c==="direction"?"toward":void 0));if(typeof l.do!="string"||!s.includes(l.do))return a(ft(`${e.kind} action`,l.do,s));for(const c of n[l.do].needs??[])l[c]===void 0&&a(`\`${l.do}\` needs \`${c}\`.`);for(const c of["at","for","speed","height","wind"])l[c]!==void 0&&!(Ph(l[c])&&l[c]>=0)&&a(`\`${c}\` must be a number ≥ 0 (got ${JSON.stringify(l[c])}).`);if(l.to!==void 0&&!Ph(l.to)&&a(`\`to\` is a scene x in px (got ${JSON.stringify(l.to)}).`),l.toward!==void 0&&!Ph(l.toward)&&!(typeof l.toward=="string"&&l.toward in Eh)){const c=typeof l.toward=="string"?Us(l.toward,Object.keys(Eh)):void 0;a(`\`toward\` is viewer, right, away, left or a quarter-turn number${c?` (did you mean "${c}"?)`:""} (got ${JSON.stringify(l.toward)}).`)}for(const c of["open","on"])l[c]!==void 0&&typeof l[c]!="boolean"&&a(`\`${c}\` is true or false (got ${JSON.stringify(l[c])}).`)}),i}function Jy(t,e,n,s={}){const i=Vy(n,e).filter(S=>S.level==="error");if(i.length>0)throw new Error(`propScript (${e.kind}): ${i.length} problem(s) in the beats:
|
|
61
61
|
${i.map(S=>` beat ${S.beat}: ${S.message}`).join(`
|
|
62
|
-
`)}`);const r=s.from??0,o=s.ground??0,a=s.scale??60,l=s.exaggeration??1,c=Yo(e),h={};for(const S of[...Object.keys(Ps),...Object.keys(e.rig.controls)])h[S]=s.start?.[S]??It(e.rig,{},S);const u=[{time:0,pose:{...h}}],d=new Map,f=[];let p=r,g=o;const m=(S,E,P,I)=>{const O=d.get(S)??[{time:0,value:S==="x"||S==="y"?0:h[S]}];O.push({time:E,value:P,...I?{easing:I}:{}}),d.set(S,O),S!=="x"&&S!=="y"&&(h[S]=P)},y=(S,E)=>{const P=S==="x"?p-r:S==="y"?g-o:h[S],I=d.get(S);(!I||I[I.length-1].time<E)&&m(S,E,P)},v={prop:e,scale:a,exaggeration:l,get x(){return p},get floor(){return g},values:h,facing(){const S=Math.sin(h.turn*Math.PI/2);return Math.abs(S)<.5?0:S>0?1:-1},key(S,E,P={}){Object.assign(h,E),u.push({time:S,pose:{...h},...P.act===!1?{act:!1}:{},...P.easing?{easing:P.easing}:{}})},move(S,E,P,I={}){y("x",S),m("x",E,P-r,I.easing),p=P,I.floor!==void 0&&(y("y",S),m("y",E,I.floor-o,I.easing),g=I.floor)},set(S,E,P,I){m(S,E,P,I)},turnTo(S,E){const P=typeof E=="number"?E:Eh[E],I=h.turn,H=[P-4,P,P+4].map(j=>({t:j,d:Math.abs(j-I)})).sort((j,J)=>j.d-J.d||Math.abs(j.t)-Math.abs(J.t))[0];if(H.d<.001)return S;const W=S+y4*Math.max(1,H.d);return v.key(W,{turn:H.t}),W},effect(S){f.push(S)},anchor(S){const P=$s(e,h,a).anchors[S];if(!P)throw new Error(`${e.kind}: no anchor "${S}"`);return{x:p+P.point.x,y:g+P.point.y}}},k=[];let w=0;for(const S of n){const E=Math.max(S.at??w,u[u.length-1].time),P=c[S.do].run(v,S,E);P.end>u[u.length-1].time&&u.push({time:P.end,pose:{...h}}),k.push({start:E,end:P.end,...P.contact!==void 0?{contact:P.contact}:{},...P.release!==void 0?{release:P.release}:{}}),w=P.end}const T=Xc(s.style??"snappy"),A={...T,anticipation:T.anticipation*l,overshoot:T.overshoot*l},M=Io(v4(u),e.acting,{style:A}),x=[...Object.entries(M).filter(([S])=>!d.has(S)).map(([S,E])=>({id:`${t}-${S}`,target:t,property:S,keyframes:E})),...[...d].map(([S,E])=>({id:`${t}-${S}`,target:t,property:S,keyframes:M4(E)}))];for(const S of w4(t,e,x,w,u[0].pose)){const E=x.findIndex(O=>O.property===S.property);if(E<0){x.push(S);continue}const P=new Ht({id:`${t}-own`,tracks:[x[E]]}),I=O=>Number(P.getStateAtTime(O).values.get(t)?.get(S.property)??0);x[E]={...S,keyframes:S.keyframes.map(O=>({time:O.time,value:Number(O.value)+I(O.time)}))}}return{tracks:x,duration:w,beats:k,effects:f}}const b4=1500;function w4(t,e,n,s,i){if(!e.follow?.length)return[];const r=new Ht({id:`${t}-follow`,tracks:n.filter(a=>a.property==="turn"||e.follow.some(l=>l.of===a.property))}),o=(a,l)=>{const c=r.getStateAtTime(a).values.get(t)?.get(l);return typeof c=="number"?c:i[l]??0};return e.follow.map(a=>{const l=s+b4,c=Vs(d=>o(d,a.of),{start:0,end:l,stiffness:a.stiffness,damping:a.damping}),h=a.limit??1/0,u=c.map(({time:d,value:f})=>{const p=Math.sin(o(d,"turn")*Math.PI/2),g=(f-o(d,a.of))*p;return{time:d,value:Math.max(-h,Math.min(h,g*a.per))}});return{id:`${t}-${a.control}`,target:t,property:a.control,keyframes:u}})}const k4=20;function v4(t){const e=[...t].sort((s,i)=>s.time-i.time),n=[];for(const s of e){const i=n[n.length-1];i&&s.time-i.time<k4?n[n.length-1]={...s,time:i.time}:n.push(s)}return n}function M4(t){const e=t.map((s,i)=>({k:s,i})).sort((s,i)=>s.k.time-i.k.time||s.i-i.i),n=[];for(const{k:s}of e)n.length>0&&n[n.length-1].time===s.time?n[n.length-1]=s:n.push(s);return n}const We=Object.freeze({test:Object.freeze({name:"Test",inningsPerSide:2,oversPerInnings:null,ballsPerOver:6,freeHitAfterNoBall:!1,summary:"Multi-day cricket. Each side can have two innings; there is no innings over limit."}),odi:Object.freeze({name:"ODI",inningsPerSide:1,oversPerInnings:50,ballsPerOver:6,freeHitAfterNoBall:!0,summary:"One innings per side, up to 50 overs. A no-ball gives a free hit on the next legitimate delivery."}),t20:Object.freeze({name:"T20",inningsPerSide:1,oversPerInnings:20,ballsPerOver:6,freeHitAfterNoBall:!0,summary:"One innings per side, up to 20 overs. A no-ball gives a free hit on the next legitimate delivery."})}),$h=Object.freeze({adults:"Adults",men:"Men",children:"Children",mixed:"Mixed cast"}),_s=Object.freeze({bowler:"Bowler",keeper:"Wicketkeeper",fielder:"Extra cover",slip:"Slip",point:"Point",cover:"Cover","mid-off":"Mid-off","mid-on":"Mid-on","square-leg":"Square leg","fine-leg":"Fine leg","third-man":"Third man"}),Wn=Object.freeze(Object.fromEntries(Object.entries({bowling:{name:"Pace bowling",summary:"Run up, deliver with a straight arm, bounce and follow through."},spin:{name:"Spin bowling",summary:"A shorter approach and a curved illustrative flight before the bounce."},batting:{name:"Drive",summary:"Two hands on the bat, a backlift, contact and a follow-through."},defend:{name:"Defensive block",summary:"Meet the ball with a controlled bat and keep it close."},running:{name:"Running between wickets",summary:"Both batters make the opposite ground to complete one run."},four:{name:"Boundary four",summary:"A struck ball reaches the boundary after touching the ground."},six:{name:"Boundary six",summary:"A struck ball clears the boundary before touching the ground."},catch:{name:"Catch",summary:"A fielder controls the struck ball before it touches the ground."},fielding:{name:"Ground field",summary:"A fielder moves to the ball, bends and gathers it."},throw:{name:"Field and throw",summary:"Gather, wind up, release and return the ball to the keeper."},bowled:{name:"Bowled",summary:"A legal delivery hits the wicket and removes a bail."},lbw:{name:"LBW illustration",summary:"Pad contact and a projected path to the stumps illustrate an authored LBW decision."},stumping:{name:"Stumping",summary:"The keeper holds the ball and breaks the wicket while the striker is out of ground, not attempting a run."},"run-out":{name:"Run-out",summary:"A direct throw breaks the wicket before the running batter makes that ground."},"no-ball":{name:"Front-foot no-ball",summary:"The landing front foot oversteps the popping crease at release; one extra, no legal ball."},wide:{name:"Wide ball",summary:"An untouched delivery passes beyond reach for a normal stroke; one extra, no legal ball."}}).map(([t,e])=>[t,Object.freeze(e)])));function ge(t,e,n){if(!Object.prototype.hasOwnProperty.call(t,e))throw new Error(`${n}: unknown choice '${e}'`);return e}const _t=(t,e,n)=>Math.max(0,Math.min(1,(t-e)/(n-e))),Lt=t=>t*t*(3-2*t),Tt=(t,e)=>Js(t,e),Ih=(t,e)=>yn(t,e);function Oh(t,e){const n=e+((t-e+2)%4+4)%4-2;return n===0?0:n}function Hs(t,e,n=0){return Math.hypot(e[0]-t[0],e[2]-t[2])<.001?n:Oh(Math.atan2(e[0]-t[0],e[2]-t[2])*2/Math.PI,n)}function Zy(){return{turn:1,"head.turn":90,"leg.left.spread":12,"leg.right.spread":12,"leg.left.swing":6,"leg.right.swing":6,"leg.left.knee":12,"leg.right.knee":12}}function Ch(t,e){const n=t.objects.find(s=>s.id===e);if(!n||n.kind!=="character")throw new Error(`cricketAction: required character '${e}' is missing`);if(n.parent||n.rotation?.some(s=>s!==0)||n.quaternion||n.scale!==void 0)throw new Error(`cricketAction: '${e}' must use position and pose.turn, without a transformed parent, scale or object rotation`);return{object:n,who:ms({...n.character,height:n.height??1.78})}}function Qy(t){return{position:[...t.object.position??[0,0,0]],pose:{...lt,...t.object.pose}}}function Rs(t,e,n,s){const i=Qe(t.who.plan,e.pose,{height:t.who.height,contact:t.who.contact});return Tt(e.position,i.chains[n][s])}function Yi(t,e,n){const s=Rs(t,e,`arm.${n}`,2),i=Rs(t,e,`arm.${n}`,1);return Tt(s,Ih(Jt(se(s,i)),t.who.lineWidth*.5))}function S4(t,e,n){const s={...e.pose,"head.turn":0,"head.nod":0,"head.tilt":0},i=Qe(t.who.plan,s,{height:t.who.height,contact:t.who.contact}).head,r=se(n,Tt(e.position,i.center)),o=i.axes.map(c=>Ie(r,c)),a=Math.atan2(o[0],o[2])*180/Math.PI,l=Math.atan2(-o[1],Math.hypot(o[0],o[2]))*180/Math.PI;return{...e,pose:{...e.pose,"head.turn":Math.max(-90,Math.min(90,a)),"head.nod":Math.max(-25,Math.min(30,l)),"head.tilt":0}}}function dn(t,e,n,s,i="hold"){let r={...e.pose};for(let o=0;o<10;o++){const a={...e,pose:r},l=Qe(t.who.plan,r,{height:t.who.height,contact:t.who.contact}),c=is(t.who.plan,r,t.who.height),h=se(Yi(t,a,n),Rs(t,a,`arm.${n}`,2)),u=se(se(se(s,h),e.position),l.hip),d=ss(u,(r.roll??0)*Math.PI/180),f=Tt(c.root,Qt(d,-(r.turn??0)*Math.PI/2));r=yi(t.who.plan,r,`arm.${n}`,f,{height:t.who.height})}for(const[o,a]of Object.entries(St[i]))r[`hand.${n}.${o}`]=a;return{...e,pose:r}}function x4(t,e,n,s){const i=Jt(s),r=t.who.height/1.78;let o=dn(t,e,"left",n);return o=dn(t,o,"right",Tt(Yi(t,o,"left"),Ih(i,.105*r))),{...o,bat:{grip:Yi(t,o,"left"),axis:i,scale:r}}}function T4(t){return Tt(t.grip,Ih(t.axis,.51*t.scale))}function t1(t){const e=Jt(t),n=Math.max(-1,Math.min(1,e[1]));return n>.999999?[0,0,0,1]:n<-.999999?Vt([1,0,0],180):Vt(Jt(Zs([0,1,0],e)),Math.acos(n)*180/Math.PI).map(s=>s===0?0:s)}function Ko(t,e,n){const s={};for(const i of Object.keys({...t,...e})){const r=t[i]??lt[i]??0;s[i]=r+((e[i]??lt[i]??0)-r)*n}return s}function _h(t,e){if(t<=e[0][0])return{...lt,...e[0][1]};for(let n=1;n<e.length;n++)if(t<=e[n][0])return Ko({...lt,...e[n-1][1]},{...lt,...e[n][1]},Lt(_t(t,e[n-1][0],e[n][0])));return{...lt,...e.at(-1)[1]}}function De(t,e){if(!Array.isArray(t)||t.length!==3||!t.every(Number.isFinite))throw new Error(`${e}: expected three finite coordinates`)}function e1(t,e,n=40,s=[]){if(!Number.isFinite(t)||!Number.isFinite(e)||t<0||e<t)throw new Error("sampleTimes: expected finite ordered nonnegative times");if(!Number.isFinite(n)||n<16||n>1e3)throw new Error("sampleTimes: every must be between 16 and 1000 ms");if((e-t)/n>2e4)throw new Error("sampleTimes: too many samples");const i=new Set([t,e,...s.filter(r=>r>=t&&r<=e&&Number.isFinite(r))]);for(let r=t+n;r<e;r+=n)i.add(r);return[...i].sort((r,o)=>r-o)}function Hh(t,e){if(n1(t),!Number.isFinite(e))throw new Error("ballFlightPoint: time must be finite");const n=Math.max(0,Math.min(1,(e-t.start)/(t.end-t.start))),s=4*n*(1-n),i=t.to[0]-t.from[0],r=t.to[2]-t.from[2],o=Math.hypot(i,r)||1;return[t.from[0]+i*n-r/o*(t.curve??0)*s,t.from[1]+(t.to[1]-t.from[1])*n+(t.arc??0)*s,t.from[2]+r*n+i/o*(t.curve??0)*s]}function n1(t){if(!t.target?.trim())throw new Error("ballFlight: target is required");if(De(t.from,"ballFlight.from"),De(t.to,"ballFlight.to"),!Number.isFinite(t.start)||!Number.isFinite(t.end)||t.start<0||t.end<=t.start)throw new Error("ballFlight: end must be greater than start, both finite and nonnegative");if(!Number.isFinite(t.arc??0)||(t.arc??0)<0||!Number.isFinite(t.curve??0))throw new Error("ballFlight: arc must be finite and nonnegative; curve must be finite")}function E4(t){n1(t);const e=e1(t.start,t.end,t.every),n=e.map(s=>Hh(t,s));return["x","y","z"].map((s,i)=>({id:`${t.id??"flight"}-${s}`,target:t.target,property:s,keyframes:e.map((r,o)=>({time:r,value:n[o][i]}))}))}const Ki=Object.freeze({"front-foot":Object.freeze({name:"Front-foot review",summary:"A fixed side view of the landing front foot and bowler’s popping crease at release."}),"striker-crease":Object.freeze({name:"Striker crease",summary:"A fixed side view of the striker’s popping crease, wicket and keeper arrival."}),"bowler-crease":Object.freeze({name:"Bowler crease",summary:"A fixed side view of the other crease and wicket for a running batter and return throw."})});function Rh(t){return Object.prototype.hasOwnProperty.call(Ki,t)}function Xo(t,e){if(!Rh(e))return;const n=i=>t.events.find(r=>r.id===i),s=e==="front-foot"?n("release"):e==="bowler-crease"?t.action==="run-out"?n("wicket"):n("run")??n("release"):(t.action!=="run-out"?n("wicket"):void 0)??n("run")??n("keeper")??n("return")??t.events.find(i=>i.kind==="contact");if(s){if(!Number.isFinite(s.time)||s.time<0||s.time>t.duration)throw new Error("cricketCameraReview: event time must be within the clip");return{...s}}}function Go(t,e,n){const s=Ch(t.scene,e),i=Qy(s);for(const r of t.timeline.tracks){if(r.target!==t.scene.id+"/"+e)continue;if(!("keyframes"in r))throw new Error("cricketCamera: review requires baked actor tracks");const o=new Xe(r).getValueAtTime(n);if(typeof o!="number"||!Number.isFinite(o))continue;const a=["x","y","z"].indexOf(r.property);a>=0?i.position[a]=o:i.pose[r.property]=o}return{actor:s,sample:i}}function s1(t){const e=Xo(t,"front-foot");if(!e)throw new Error("cricketCamera: front-foot view requires a release event");const{actor:n,sample:s}=Go(t,"bowler",e.time);return{point:Rs(n,s,"leg.right",2),height:n.who.height}}function i1(t,e){const n=e==="striker-crease"?"striker":"bowler",s=t.landmarks[n+"-crease"];return De(s,"cricketCamera.crease"),[...s]}function A4(t,e){if(!Rh(e))return[];const n=i1(t,e),s=e==="front-foot"?s1(t).point[0]:0;return[{id:"decision-review-"+e,name:Ki[e].name+": crease reference",kind:"line",color:"#f4b83f",width:.035,points:[[s-1.1,.045,n[2]],[s+1.1,.045,n[2]]]}]}function Fh(t,e,n,s){const i=e*Math.PI/180,r=n*Math.PI/180;return[t[0]+s*Math.cos(r)*Math.sin(i),t[1]+s*Math.sin(r),t[2]+s*Math.cos(r)*Math.cos(i)]}const Lh=(t,e,n)=>[t[0]+(e[0]-t[0])*n,t[1]+(e[1]-t[1])*n,t[2]+(e[2]-t[2])*n];function P4(t,e,n){const s={target:[0,0,0],yaw:0,pitch:15,distance:8,...t},i={...s,...e},r=Lh(s.target,i.target,n),o=s.position||i.position?Lh(s.position??Fh(s.target,s.yaw,s.pitch,s.distance),i.position??Fh(i.target,i.yaw,i.pitch,i.distance),n):Fh(r,s.yaw+(i.yaw-s.yaw)*n,s.pitch+(i.pitch-s.pitch)*n,s.distance+(i.distance-s.distance)*n),a=Lh(s.lookAt??s.target,i.lookAt??i.target,n),l=s.fov!==void 0||i.fov!==void 0?(s.fov??i.fov)+((i.fov??s.fov)-(s.fov??i.fov))*n:void 0;return{position:o,lookAt:a,fov:l}}function $4(t){const e=Math.max(1,t.every??33),n=Wt(t.easing??"ease-in-out"),s=`${t.scene}/${t.camera}`,i=[],r=[],o=[];for(let l=t.start;;l=Math.min(t.end,l+e)){const c=t.end>t.start?n((l-t.start)/(t.end-t.start)):1,h=P4(t.from,t.to,c);if(i.push({time:l,value:h.position}),r.push({time:l,value:h.lookAt}),h.fov!==void 0&&o.push({time:l,value:h.fov}),l>=t.end)break}const a=[{id:`${s}-move-position`,target:s,property:"position",keyframes:i},{id:`${s}-move-lookAt`,target:s,property:"lookAt",keyframes:r}];return o.length>0&&a.push({id:`${s}-move-fov`,target:s,property:"fov",keyframes:o}),a}function I4(t){const e=Math.max(1,t.every??33),n=t.offset??[0,2,6],s=t.lag??0,i=`${t.scene}/${t.camera}`,r=[],o=[];for(let a=t.start;;a=Math.min(t.end,a+e)){const l=t.subjectAt(a),c=t.subjectAt(Math.max(t.start,a-s));if(r.push({time:a,value:[c[0]+n[0],c[1]+n[1],c[2]+n[2]]}),o.push({time:a,value:l}),a>=t.end)break}return[{id:`${i}-follow-position`,target:i,property:"position",keyframes:r},{id:`${i}-follow-lookAt`,target:i,property:"lookAt",keyframes:o}]}const Uo=Object.freeze({pitch:"Whole pitch",batter:"Batter close-up",bowler:"Bowler close-up",keeper:"Keeper close-up",field:"Whole ground",overhead:"Overhead ground",orbit:"360° ground orbit","follow-ball":"Follow the ball",...Object.fromEntries(Object.entries(Ki).map(([t,e])=>[t,e.name]))}),Vo=Object.freeze({pitch:75,batter:145,bowler:35,keeper:145,field:75,overhead:75,orbit:75,"follow-ball":75,"front-foot":90,"striker-crease":90,"bowler-crease":90});function r1(t,e="pitch"){const n=ge(Uo,e,"cricketCamera.view");if(Rh(n)){const i=i1(t,n);if(n==="front-foot"){const c=s1(t);return{target:[c.point[0],.12,(c.point[2]+i[2])/2],pitch:25,distance:Math.max(2.2,2.6*c.height/1.78),fov:40}}const r=t.landmarks[n==="striker-crease"?"striker-wicket":"bowler-wicket"];De(r,"cricketCamera.wicket");let o=(i[2]+r[2])/2,a=4;if(t.action==="run-out"&&n==="bowler-crease"||t.action==="running"){const c=Xo(t,n);if(c){const u=Go(t,n==="bowler-crease"?"batter":"non-striker",c.time).sample.position;o=(Math.min(i[2],r[2],u[2])+Math.max(i[2],r[2],u[2]))/2,a=Math.max(4,Math.abs(r[2]-u[2])*1.8)}}let l=0;if(n==="striker-crease"&&t.action==="wide"){const c=Xo(t,n);if(c){const h=Go(t,"keeper",c.time).sample.position,u=Go(t,"batter",c.time).sample.position,d=Math.min(i[0],r[0],h[0],u[0]),f=Math.max(i[0],r[0],h[0],u[0]),p=Math.min(i[2],r[2],h[2],u[2]),g=Math.max(i[2],r[2],h[2],u[2]);l=(d+f)/2,o=(p+g)/2,a=Math.max(4,Math.hypot(f-d,g-p)*1.8)}}return{target:[l,.42,o],pitch:12,distance:a,fov:44}}if(n==="follow-ball"){const i=t.scene.objects.find(r=>r.id==="camera"&&r.kind==="camera");return{pitch:Math.atan2(3,Math.hypot(5,6))*180/Math.PI,distance:Math.sqrt(70),fov:i?.kind==="camera"&&i.projection==="perspective"?i.fov:48}}const s=n==="field"||n==="overhead"||n==="orbit";return{target:n==="batter"?[.1,.85,9.3]:n==="bowler"?[.68,1,-9.55]:n==="keeper"?[0,.7,10.1]:[0,.65,0],distance:s?t.boundaryRadius*2.8:n==="pitch"?29:4.3,pitch:n==="overhead"?89:s?52:n==="pitch"?16:12,fov:s?48:n==="pitch"?50:46}}function Nh(t,e,n,s){if(t!==void 0&&(!Number.isFinite(t)||t<e||t>n))throw new Error("cricketCamera: "+s+" must be between "+e+" and "+n)}function O4(t,e={}){const n=ge(Uo,e.view??"pitch","cricketCamera.view"),s=e.yaw??Vo[n];if(!Number.isFinite(s))throw new Error("cricketCamera: yaw must be finite");const i=(s%360+360)%360,r=e.zoom??1;if(!Number.isFinite(r)||r<.25||r>4)throw new Error("cricketCamera: zoom must be between 0.25 and 4");const o=g=>r===1?g:Math.atan(Math.tan(g*Math.PI/360)/r)*360/Math.PI,a=e.every??40;if(!Number.isFinite(a)||a<16||a>1e3)throw new Error("cricketCamera: every must be between 16 and 1000 ms");if(Nh(e.pitch,0,89,"pitch"),Nh(e.distance,.5,2e3,"distance"),Nh(e.fov,10,100,"fov"),e.target!==void 0&&(De(e.target,"cricketCamera.target"),n==="follow-ball"))throw new Error("cricketCamera: target override is not supported by follow-ball");const l=r1(t,n),c=e.pitch??l.pitch,h=e.distance??l.distance,u=o(e.fov??l.fov),d=e.target?[...e.target]:l.target??[0,0,0],f=t.scene.id+"/camera",p=g=>{if(e.distance===void 0&&e.target===void 0)return g;const m=g.find(k=>k.property==="position");if(!m||!("keyframes"in m))return g;const y=t.scene.objects.find(k=>k.id==="camera"&&k.kind==="camera");let v=y?.kind==="camera"?Math.max(600,y.far):600;for(const k of m.keyframes)v=Math.max(v,Math.hypot(...k.value)+t.boundaryRadius+10);if(!Number.isFinite(v))throw new Error("cricketCamera: framing exceeds finite camera range");return[...g,{id:f+"-framing-far",target:f,property:"far",keyframes:[{time:0,value:v},{time:t.duration,value:v}]}]};if(n==="follow-ball"){const g=["x","y","z"].map(w=>{const T=t.timeline.tracks.find(S=>S.target===t.scene.id+"/ball"&&S.property===w);if(!T||!("keyframes"in T)||!T.keyframes.length)throw new Error("cricketCamera: missing ball "+w+" keyframes");const A=T.keyframes;let M=0,x=new Xe({...T,keyframes:A.slice(0,2)});return S=>{const E=M;for(;M<A.length-2&&S-(T.delay??0)>A[M+1].time;)M++;return M!==E&&(x=new Xe({...T,keyframes:A.slice(M,M+2)})),x.getValueAtTime(S)}}),m=(Math.atan2(5,6)*180/Math.PI+i-Vo["follow-ball"])*Math.PI/180,y=c*Math.PI/180,v=i===Vo["follow-ball"]&&(e.pitch===void 0||e.pitch===l.pitch)&&(e.distance===void 0||e.distance===l.distance)?[5,3,6]:[Math.sin(m)*Math.cos(y)*h,Math.sin(y)*h,Math.cos(m)*Math.cos(y)*h],k=I4({scene:t.scene.id,camera:"camera",start:0,end:t.duration,every:a,offset:v,subjectAt:w=>g.map(T=>T(w))});return p([...k,{id:f+"-zoom-fov",target:f,property:"fov",keyframes:[{time:0,value:u},{time:t.duration,value:u}]}])}return p($4({scene:t.scene.id,camera:"camera",start:0,end:t.duration,every:a,easing:"linear",from:{target:d,yaw:i,pitch:c,distance:h,fov:u},to:{yaw:n==="orbit"?i+360:i}}))}const Jo=Object.freeze({mcc:Object.freeze({name:"MCC",poppingCreaseHalfWidth:1.83,fieldingRadius:null,summary:"MCC minimum crease markings. The base Laws do not prescribe a limited-over restriction area."}),"icc-men":Object.freeze({name:"ICC men",poppingCreaseHalfWidth:7.5,fieldingRadius:27.43,summary:"ICC men: extended crease markings; ODI/T20 restriction-area arcs have a 27.43 m radius."}),"icc-women":Object.freeze({name:"ICC women",poppingCreaseHalfWidth:7.5,fieldingRadius:23,summary:"ICC women: extended crease markings; ODI/T20 restriction-area arcs have a 23 m radius."})});function C4(t){const[e,n]=t.centres,s=Math.hypot(n[0]-e[0],n[2]-e[2]),i=(n[0]-e[0])/s,r=(n[2]-e[2])/s,o=[];for(let a=0;a<2;a++){const l=a===0?n:e;for(let c=0;c<=64;c++){const h=(a+c/64)*Math.PI,u=Math.cos(h)*t.radius,d=Math.sin(h)*t.radius;o.push([l[0]+r*u+i*d,.018,l[2]-i*u+r*d])}}return o}function o1(t,e){De(e,"cricketFieldingAreaContains.point");const n=t.fieldingArea;if(n==null)return null;if(!Number.isFinite(n.radius)||n.radius<=0)throw new Error("cricketFieldingAreaContains: radius must be positive and finite");if(!Array.isArray(n.centres)||n.centres.length!==2)throw new Error("cricketFieldingAreaContains: two centres are required");const[s,i]=n.centres;De(s,"cricketFieldingAreaContains.centre"),De(i,"cricketFieldingAreaContains.centre");const r=i[0]-s[0],o=i[2]-s[2],a=r*r+o*o,l=a?Math.max(0,Math.min(1,((e[0]-s[0])*r+(e[2]-s[2])*o)/a)):0;return Math.hypot(e[0]-s[0]-l*r,e[2]-s[2]-l*o)<=n.radius+1e-9}function a1(t){return Object.keys(_s).flatMap(e=>{const n=t.scene.objects.find(i=>i.id===e&&i.kind==="character");if(!n)return[];if(n.parent)throw new Error(`cricketFieldingPositions: '${e}' must be unparented for setup markers`);const s=[...n.position??[0,0,0]];return[{id:e,name:n.name??_s[e],position:s,inside:o1(t,s)}]})}function _4(t){return t.fieldingArea?a1(t).map(e=>({id:`fielding-review-${e.id}`,name:`${e.name}: ${e.inside?"inside":"outside"} restriction area`,kind:"line",closed:!0,width:.12,color:e.inside?"#d8eb8a":"#ee9670",points:Array.from({length:32},(n,s)=>[e.position[0]+Math.cos(s*Math.PI/16)*.7,.06,e.position[2]+Math.sin(s*Math.PI/16)*.7])})):[]}const Yt=Object.freeze({length:20.12,width:3.05,poppingCrease:1.22,returnCrease:1.32,stumpHeight:.711,wicketWidth:.2286});function l1(t){if(!t.id?.trim())throw new Error("cricketPlayer: id is required");ge({batter:1,bowler:1,keeper:1,fielder:1,umpire:1},t.role,"cricketPlayer.role");const e=ge(Li,t.preset??"youngMan","cricketPlayer.preset"),n=ge(We,t.format??"t20","cricketPlayer.format"),s=ge({none:1,cap:1,"sun-hat":1},t.headwear??"none","cricketPlayer.headwear"),i=e==="childBoy"||e==="childGirl",r=t.height??(i?1.24:1.78);if(!Number.isFinite(r)||r<.5||r>3)throw new Error("cricketPlayer: height must be between .5 and 3 metres");De(t.position??[0,0,0],"cricketPlayer.position");const o=t.role==="umpire"?"#f5ebd5":n==="test"?"#f5f0df":t.color??"#3577b5",a=JSON.parse(JSON.stringify({...Li[e],...t.appearance,outfit:rm("casual",{top:"shirt",shirt:o,trousers:t.role==="umpire"?"#405058":o,bottom:"trousers",trouserStyle:"plain",sleeves:"short",collar:!0,tie:null,shoes:"boots",shoeColor:"#f3ead7"}),hat:s==="none"?null:{style:s==="sun-hat"?"sunHat":"cap",color:o}}));return{id:t.id,name:t.role,kind:"character",look:"pen",height:r,position:[...t.position??[0,0,0]],character:a,pose:t.role==="batter"?Zy():{turn:t.role==="keeper"?2:0}}}function Zo(t,e,n,s,i=0){return{id:t,kind:"mesh",position:e,geometry:{type:"box",size:n},material:s,layer:i}}function H4(t,e){const n=Yt.stumpHeight,s=(Yt.wicketWidth-.036)/2;return[...[-1,0,1].map((i,r)=>({id:`${t}-stump-${r}`,kind:"mesh",position:[i*s,n/2,e],geometry:{type:"cylinder",radius:.018,height:n,segments:10},material:"wicket"})),...[-1,1].map((i,r)=>Zo(`${t}-bail-${r}`,[i*s/2,n+.015,e],[.105,.025,.035],"bail"))]}function c1(t,e){return[{id:t,kind:"group",scale:e,visible:!1},Zo(`${t}-grip`,[0,.1,0],[.036,.28,.036],"bat-grip"),Zo(`${t}-blade`,[0,.51,0],[.108,.54,.055],"bat-blade"),Zo(`${t}-label`,[0,.41,.029],[.07,.16,.004],"bat-label")].map((s,i)=>i===0?s:{...s,parent:t})}function Wh(t={}){const e=ge(We,t.format??"t20","cricketField.format"),n=ge($h,t.cast??"adults","cricketField.cast"),s=ge(Jo,t.markingProfile??"icc-men","cricketField.markingProfile"),i=Jo[s],r=t.boundaryRadius??64;if(!Number.isFinite(r)||r<24||r>250)throw new Error("cricketField: boundaryRadius must be between 24 and 250 metres");const o=t.id??"cricket";if(!o.trim())throw new Error("cricketField: id is required");const a=Yt.length/2,l=e!=="test"&&i.fieldingRadius!==null?{radius:i.fieldingRadius,centres:[[0,0,-a],[0,0,a]]}:null,c={"striker-wicket":[0,0,a],"bowler-wicket":[0,0,-a],"striker-crease":[0,0,a-Yt.poppingCrease],"bowler-crease":[0,0,-a+Yt.poppingCrease]},h=[{id:"camera",kind:"camera",projection:"perspective",position:[25,9,6],lookAt:[0,.65,0],fov:48,near:.02,far:Math.max(600,r*4)},{id:"sun",kind:"light",light:"directional",position:[4,8,5],intensity:.8,color:"#fff2dd"},{id:"ambient",kind:"light",light:"ambient",intensity:.85,color:"#eaf6f4"},{id:"outfield",kind:"mesh",layer:-4,position:[0,-.04,0],geometry:{type:"cylinder",radius:r+1,height:.06,segments:80},material:"grass"},{id:"square",kind:"mesh",layer:-3,geometry:{type:"plane",size:[8,25]},position:[0,.003,0],material:"square"},{id:"pitch",kind:"mesh",layer:-2,geometry:{type:"plane",size:[Yt.width,Yt.length]},position:[0,.008,0],material:"pitch"},{id:"boundary",kind:"line",layer:-1,closed:!0,width:.15,color:"#f8f2db",points:Array.from({length:96},(p,g)=>[Math.cos(g*Math.PI/48)*r,.022,Math.sin(g*Math.PI/48)*r])}];l&&h.push({id:"fielding-circle",kind:"line",layer:-1,closed:!0,width:.06,color:"#d6e4c8",points:C4(l)});for(const p of[-1,1]){const g=p>0?"striker":"bowler",m=p*a,y=m-p*Yt.poppingCrease;h.push(...H4(g,m));const v=(k,w)=>h.push({id:`${g}-${k}`,kind:"line",layer:-1,color:"#fffdf0",width:.045,points:w});v("popping-line",[[-i.poppingCreaseHalfWidth,.02,y],[i.poppingCreaseHalfWidth,.02,y]]),v("bowling-line",[[-1.32,.02,m],[1.32,.02,m]]);for(const k of[-1,1])v(`return-line-${k<0?"left":"right"}`,[[k*1.32,.02,y],[k*1.32,.02,m+p*2.5]])}const u=[["batter","batter",[-.38,0,9.3]],["non-striker","batter",[-.85,0,-9.3]],["bowler","bowler",[.68,0,-17]],["keeper","keeper",[0,0,11.25]],["fielder","fielder",[12,0,-3]],["slip","fielder",[3.5,0,12]],["point","fielder",[20,0,6]],["cover","fielder",[22,0,-16]],["mid-off","fielder",[9,0,-25]],["mid-on","fielder",[-9,0,-25]],["square-leg","fielder",[-20,0,7]],["fine-leg","fielder",[-20,0,35]],["third-man","fielder",[23,0,35]],["umpire","umpire",[0,0,-12.4]],["square-umpire","umpire",[-15,0,8.84]]];u.forEach(([p,g,m],y)=>{const v=n==="children"||n==="mixed"&&y%3===0,k=n==="men"?"youngMan":v?y%2?"childGirl":"childBoy":y%2?"youngWoman":"youngMan",w=Math.hypot(m[0],m[2]),T=w>r*.88?[m[0]*r*.88/w,0,m[2]*r*.88/w]:[...m];c[p]=[...T];const A=l1({id:p,role:g,preset:k,format:e,position:T,color:g==="batter"?t.battingColor??"#397cb9":t.fieldingColor??"#bf604e"});if(Object.hasOwn(_s,p)&&(A.name=_s[p]),p!=="batter"){const M=p==="non-striker"||p==="bowler"?u[0][2]:u.find(([x])=>x==="bowler")[2];A.pose={turn:Hs(T,M)}}h.push(A)});const d=p=>h.find(g=>g.id===p).height/1.78;h.push(...c1("bat",d("batter")),...c1("non-striker-bat",d("non-striker"))),h.push({id:"ball",kind:"mesh",position:[0,.075,0],geometry:{type:"sphere",radius:.075,segments:12},material:"ball"}),h.push({id:"lbw-guide",kind:"group",visible:!1},{id:"lbw-projection",kind:"line",parent:"lbw-guide",points:[[0,0,0],[0,1,0]],width:.04,color:"#e9ae38"});const f=p=>({color:p,shading:"toon",outline:{color:"#69513a",width:.8}});return{format:e,boundaryRadius:r,landmarks:c,markingProfile:s,fieldingArea:l,scene:{id:o,formatVersion:1,camera:"camera",background:{top:"#c8e5ef",bottom:"#e9efcc"},ground:0,objects:h,materials:{grass:{color:"#81a95c",shading:"unlit"},square:{color:"#a6b76a",shading:"unlit",doubleSided:!0},pitch:{color:"#ddbd85",shading:"unlit",doubleSided:!0},wicket:f("#edd99e"),bail:f("#bd8c4d"),"bat-grip":f("#385b5c"),"bat-blade":f("#e8c58d"),"bat-label":f("#c34d4c"),ball:{color:e==="test"?"#b32d36":"#fff9e7",shading:"toon",outline:{color:"#9b3840",width:1}}}}}}const Kt=1900,Xi=2450,Et=2900,Gi=4100,fn=4200,Fs=4600,Qo=5300,Dh=5500;function ta(t,e,n,s,i,r,o=t.object.pose?.turn??0){const a=_t(e,n,s),l=Qs(i,r),c=Hs(i,r,o),h=o+(c-o)*Lt(_t(e,n,n+200)),u={...lt,...t.object.pose,turn:h},d=io("run",t.who.height,1,t.object.character?.legLength??1),f=so("run",l*a/d,u),p=Math.min(a*12,(1-a)*12,1);return{position:bn(i,r,a),pose:Ko(u,f,Math.max(0,p))}}function Bh(t,e,n){const s=(t.pose.turn??0)*Math.PI/2;return Tt(t.position,[Math.sin(s)*e,n,Math.cos(s)*e])}function R4(t,e,n,s,i){const r=`${e}/${n.object.id}`,o={...lt,...n.object.pose},a=new Set(i.flatMap(l=>Object.keys(l.pose)));for(const l of a){const c=o[l]??0;i.some(h=>h.pose[l]!==c)&&t.push({id:`${n.object.id}-${l}`,target:r,property:l,keyframes:s.map((h,u)=>({time:h,value:i[u].pose[l]??c}))})}for(const[l,c]of["x","y","z"].entries())i.some(h=>h.position[l]!==(n.object.position?.[l]??0))&&t.push({id:`${n.object.id}-${c}`,target:r,property:c,keyframes:s.map((h,u)=>({time:h,value:i[u].position[l]}))});if(i[0].bat){const l=n.object.id==="batter"?"bat":"non-striker-bat",c=`${e}/${l}`;t.push({id:`${l}-visible`,target:c,property:"visible",keyframes:[{time:0,value:1}]}),t.push({id:`${l}-position`,target:c,property:"position",keyframes:s.map((h,u)=>({time:h,value:[...i[u].bat.grip]}))}),t.push({id:`${l}-rotation`,target:c,property:"quaternion",interpolation:"slerp",keyframes:s.map((h,u)=>({time:h,value:t1(i[u].bat.axis)}))})}}function F4(t,e){const n={runs:0,extras:0,wickets:0,legalBall:!0,freeHitNext:!1};t==="running"&&(n.runs=1),t==="four"&&(n.runs=4),t==="six"&&(n.runs=6),(t==="wide"||t==="no-ball")&&(n.extras=1,n.legalBall=!1),t==="no-ball"&&(n.freeHitNext=We[e].freeHitAfterNoBall);const i={catch:"caught",bowled:"bowled",lbw:"lbw",stumping:"stumped","run-out":"run-out"}[t];return i&&(n.wickets=1,n.dismissal=i),n}function h1(t,e={}){return u1(t,e)}function u1(t,e,n){const s=ge(Wn,e.action??"bowling","cricketAction.action"),i=n?n.delivery.legality==="no-ball":s==="no-ball",r=n?n.delivery.legality==="wide":s==="wide",o=n?n.delivery.style==="spin":s==="spin";ge(We,t.format,"cricketAction.format");const a=n?.result??F4(s,t.format),l=e.duration??6e3;if(!Number.isFinite(l)||l<4e3||l>6e4)throw new Error("cricketAction: duration must be between 4000 and 60000 ms");const c=t.scene.id;for(const $ of["ball","bat","non-striker-bat","lbw-guide","striker-bail-0","striker-bail-1","bowler-bail-0","bowler-bail-1"])if(!t.scene.objects.some(C=>C.id===$))throw new Error(`cricketAction: required equipment '${$}' is missing`);const h=Object.fromEntries(["batter","non-striker","bowler","keeper","fielder","umpire"].map($=>[$,Ch(t.scene,$)]));for(const $ of["slip","point","cover","mid-off","mid-on","square-leg","fine-leg","third-man","square-umpire"])t.scene.objects.some(C=>C.id===$&&C.kind==="character")&&(h[$]=Ch(t.scene,$));const u=$=>h[$].who.height,d=$=>Qy(h[$]),f=$=>Math.round($*6e3/l*1e9)/1e9,p=$=>$*l/6e3,g=["batting","defend","running","four","six","catch","fielding","throw","run-out"].includes(s),m=["bowling","spin","no-ball","stumping"].includes(s),y=["catch","fielding","throw","run-out","batting","running"].includes(s),v=s==="running"||s==="run-out",k=new Map,w=[d("bowler").position[0],0,i?-8.25:-9.55],T=s==="fielding"?[10.5,0,2]:[9,0,-1],A=d("fielder").position,M=($,C)=>{let z=k.get($);z||(z=new Map,k.set($,z));const X=z.get(C);if(X)return X;const N=h[$];let L=d($);if($==="bowler"){const D=L.position;if(C<1400){const G=Tt(w,[0,0,-.65]);L=ta(N,C,0,1400,D,G),L.pose["arm.right.swing"]=45,L.pose["arm.right.elbow"]=80}else L.position=C<=Kt?bn(Tt(w,[0,0,-.65]),w,Lt(_t(C,1400,Kt))):Tt(w,[0,0,.8*Lt(_t(C,Kt,2600))]),L.pose=_h(C,[[1400,{turn:0,"arm.right.swing":285,"arm.right.elbow":8,"arm.left.swing":115,"leg.right.swing":15,"leg.left.knee":45}],[1800,{turn:0,"arm.right.swing":180,"arm.right.elbow":0,"arm.left.swing":80,"leg.right.swing":25,"leg.right.knee":0,"leg.left.swing":-25,"leg.left.knee":60}],[Kt,{turn:0,lean:8,"arm.right.swing":155,"arm.right.elbow":0,"arm.left.swing":45,"leg.right.swing":25,"leg.right.knee":0,"leg.left.swing":-25,"leg.left.knee":60}],[2250,{turn:0,lean:26,bend:12,"arm.right.swing":40,"arm.right.elbow":0,"arm.left.swing":-35,"leg.left.swing":-35,"leg.left.knee":55}],[3e3,{turn:0,"head.turn":10}],[6e3,{turn:0,"head.turn":10}]]);o&&(L.pose={...L.pose,"arm.right.spread":18,"head.tilt":-5});for(const[G,q]of Object.entries(C<Kt?St.hold:St.open))L.pose[`hand.right.${G}`]=q}else if($==="batter"||$==="non-striker"){const D=u($);if(s==="lbw"&&$==="batter"&&(L.position[0]=0),s==="stumping"&&$==="batter"&&(L.position[2]-=1.1*Lt(_t(C,2150,2800))),v&&C>3050){const G=M($,3050),q=$==="batter"?[1,0,-9.5]:[-1,0,9.5];L=ta(N,C,3050,s==="run-out"?6e3:Dh,G.position,q,G.pose.turn);const tt=Yi(N,L,"right");L.bat={grip:tt,axis:Jt([.7,-.35,.5]),scale:D/1.78}}else{L.pose={...L.pose,...$==="batter"?Zy():{turn:.15,"leg.left.knee":8,"leg.right.knee":8}};let q=[0,-1,$==="batter"?.05:.12],Z=Tt(L.position,[D*.15,D*.44,D*.04]);if($==="non-striker"&&(Z=Tt(L.position,[D*.08,D*.44,D*.17])),$==="batter"){const tt=Lt(_t(C,2100,2600))*(1-Lt(_t(C,2600,Et))),R=Lt(_t(C,2600,Et))*(1-Lt(_t(C,Et,3800))),U=Lt(_t(C,Et,3250))*(1-Lt(_t(C,3250,4e3)));if(g){Z=Tt(L.position,[D*(.15+.03*tt-.02*R-.03*U),D*(.44+.14*tt+.07*R+.23*U),D*(.04+.16*tt-.12*R-.06*U)]),q=Jt([.15*tt+.25*U,-1+1.85*tt+1.6*U,.05+.55*tt-.4*R-.8*U]),L.pose.turn=1+.12*R+.3*U,L.pose.lean=3+4*R;const nt=12+4*R;L.pose["leg.left.spread"]=nt,L.pose["leg.right.spread"]=nt,s==="defend"&&(q=[0,-1,-.08],Z=Tt(L.position,[D*.1,D*.5,-D*.12]))}else if(["stumping","bowled","lbw"].includes(s)){const nt=Lt(_t(C,2100,2700))*(1-Lt(_t(C,4e3,4500)));q=Jt([.15*nt,-1+1.85*nt,.05+.55*nt]),Z=Tt(L.position,[D*(.15+.03*nt),D*(.44+.14*nt),D*(.04+.16*nt)])}}L=x4(N,L,Z,q)}}else if($==="keeper"){L.pose={...L.pose,turn:Hs(L.position,d("bowler").position,2),lean:20,"leg.left.swing":22,"leg.right.swing":22,"leg.left.knee":50,"leg.right.knee":50},r&&(L.position[0]=2.15*Lt(_t(C,2900,3500))),s==="stumping"&&(L.position[2]-=.85*Lt(_t(C,3400,3900)));const D=Bh(L,u($)*.27,u($)*.44);if(s==="stumping"&&C>=3500){const G=Bh({...L,position:d($).position},u($)*.27,u($)*.44),q=[0,Yt.stumpHeight,Yt.length/2],Z=bn(G,q,Lt(_t(C,3500,3900)));L=dn(N,L,"right",Z),L=dn(N,L,"left",Tt(Z,[.045,0,0]))}else L=dn(N,L,"right",D),L=dn(N,L,"left",Tt(D,[.045,0,0]))}else if($==="fielder"&&y){if(L=ta(N,C,3050,s==="catch"?3800:3950,A,T),C>=3800){const D={...lt,turn:Hs(T,d("batter").position,L.pose.turn),lean:s==="catch"?5:42,bend:s==="catch"?0:18,"leg.left.swing":s==="catch"?0:45,"leg.right.swing":s==="catch"?0:45,"leg.left.knee":s==="catch"?0:85,"leg.right.knee":s==="catch"?0:85,smile:.7};L.pose=Ko(L.pose,D,Lt(_t(C,3800,fn)));const G=Bh(L,u($)*.22,u($)*(s==="catch"?.73:.2));if(L=dn(N,L,"right",G),L=dn(N,L,"left",Tt(G,[.035,0,0])),(s==="throw"||s==="run-out")&&C>fn){const q={...lt,turn:Hs(T,s==="throw"?d("keeper").position:t.landmarks["bowler-wicket"],L.pose.turn),"arm.right.swing":225,"arm.right.elbow":60,"arm.left.spread":70,"leg.left.swing":15},Z={...q,"arm.right.swing":110,"arm.right.elbow":0,lean:15};L.pose=_h(C,[[fn,L.pose],[4450,q],[Fs,Z],[4900,{...lt,turn:q.turn,"arm.right.swing":25,lean:22}],[6e3,{...lt,turn:q.turn}]])}}}else if($==="umpire"){let D={...lt};const G=s==="stumping"?4150:s==="run-out"?5150:s==="bowled"||s==="lbw"?3500:s==="catch"?4350:5100;if(s==="no-ball")D={...D,"arm.right.spread":90,"arm.right.elbow":0};else if(s==="wide")D={...D,"arm.right.spread":90,"arm.left.spread":90,"arm.right.elbow":0,"arm.left.elbow":0};else if(s==="six")D={...D,"arm.right.spread":180,"arm.left.spread":180,"arm.right.elbow":0,"arm.left.elbow":0};else if(s==="four")D={...D,"arm.right.spread":90-70*(.5+Math.sin((C-5100)/180)*.5),"arm.right.elbow":12};else if(["catch","bowled","lbw","stumping","run-out"].includes(s)){D={...D,"arm.right.swing":165,"arm.right.elbow":0};for(const[q,Z]of Object.entries(St.point))D[`hand.right.${q}`]=Z}if(n){const q={...lt},Z=[[0,q]];let tt=q;if(i||r){const R=i?Kt:3100;tt=i?{...q,"arm.right.spread":90,"arm.right.elbow":0}:{...q,"arm.right.spread":90,"arm.left.spread":90,"arm.right.elbow":0,"arm.left.elbow":0},Z.push([R,q],[R+350,tt])}if(a.wickets||s==="four"||s==="six"){const R=a.wickets?G:5100;let U=D;if(a.wickets){U={...q,"arm.right.swing":165,"arm.right.elbow":0};for(const[nt,at]of Object.entries(St.point))U[`hand.right.${nt}`]=at}Z.push([R,tt],[R+350,U])}L.pose=_h(C,Z)}else L.pose=Ko(L.pose,D,Lt(_t(C,s==="no-ball"?Kt:s==="wide"?3100:G,(s==="no-ball"?Kt:s==="wide"?3100:G)+350)))}return z.set(C,L),L},x=($,C)=>Yi(h[$],M($,C),"right"),S=g?T4(M("batter",Et).bat):s==="lbw"?bn(Rs(h.batter,M("batter",Et),"leg.right",1),Rs(h.batter,M("batter",Et),"leg.right",2),.6):[m?Yt.wicketWidth/2+.075+.15:0,.45,9.25],E=x("bowler",Kt),P=[r?.85:o?-.35:s==="lbw"?S[0]*.6:0,.075,3.9],I=x("keeper",s==="stumping"?3400:3500),O=x("fielder",Gi),H=x("fielder",fn),W=s==="run-out"?"bowler":"striker",j=s==="run-out"?5e3:s==="stumping"?3900:3200,J=[t.boundaryRadius*.8,s==="six"?2.1:.075,-t.boundaryRadius*.6],et=($,C,z,X,N,L=0,D=0)=>Hh({target:`${c}/ball`,start:C,end:z,from:X,to:N,arc:L,curve:D},$),V=$=>{if($<=Kt)return x("bowler",$);if($<=Xi)return et($,Kt,Xi,E,P,.15,o?.35:0);const C=r?Tt(I,[0,0,-.6]):S;if($<=Et)return et($,Xi,Et,P,C,.08);if(s==="bowled"){const X=[0,.36,Yt.length/2];return $<=j?et($,Et,j,S,X):et($,j,4100,X,[0,.075,12.5],.2)}if(s==="lbw")return[...S];if(["bowling","spin","no-ball","wide","stumping"].includes(s)){const X=s==="stumping"?3400:3500;if(m&&$<=X){const N=[C[0],I[1],Yt.length/2+.2];return $<=3200?et($,Et,3200,C,N,.04):et($,3200,X,N,I,.04)}return $<=X?et($,Et,X,C,I,.04):x("keeper",$)}if(s==="defend")return et($,Et,3400,S,Tt(S,[-.5,-S[1]+.075,-.7]),.12);if(s==="four"||s==="six"){if(s==="six")return $<=5e3?et($,Et,5e3,S,J,12):et($,5e3,5700,J,Tt(J,[2,-2.025,-1.5]));const X=[5,.075,5];return $<=3300?et($,Et,3300,S,X,.5):et($,3300,5e3,X,J)}if(s==="catch")return $<=Gi?et($,Et,Gi,S,O,5):x("fielder",$);const z=[4,.075,5];if($<=3300)return et($,Et,3300,S,z,.8);if($<=fn)return et($,3300,fn,z,H);if(s==="throw"||s==="run-out"){if($<=Fs)return x("fielder",$);const X=x("fielder",Fs),N=s==="run-out"?[0,.42,-Yt.length/2]:x("keeper",Qo),L=s==="run-out"?j:Qo;return $<=L?et($,Fs,L,X,N,1.2):s==="run-out"?et($,L,5700,N,[0,.075,-12],.18):x("keeper",$)}return[...H]},F=[],B=($,C,z,X,N)=>F.push({id:$,time:p(C),kind:z,label:X,caption:N}),K=n?{bowled:"Delivery hits stumps",lbw:"Pad contact",stumping:"Keeper breaks wicket","run-out":"Throw breaks wicket"}[s]??Wn[s].name:Wn[s].name;if(B("setup",0,"setup",K,n?`${n.delivery.style} delivery · ${n.delivery.legality}${n.freeHit?" · free hit":""}. ${Wn[s].summary.replace("A legal delivery","A delivery")}`:Wn[s].summary),B("release",Kt,"release","Ball released",i?"The front foot has landed beyond the popping crease. No-ball.":"The bowler releases the ball; the front foot is behind the popping crease."),B("bounce",Xi,"bounce","Pitch bounce",o?"The curved flight is illustrative. Spin can change the ball’s path after it bounces.":"The delivery bounces on the pitch on its way to the striker."),g?B("contact",Et,"contact","Bat contact","The ball meets the blade. The bat is keyed from the same two hand grips."):s==="lbw"?B("pad-contact",Et,"contact","Pad contact",n?"The ball contacts the pad. The highlighted path is illustrative; the authored decision is resolved separately.":"The highlighted path illustrates a ball that would hit the stumps. This is an authored LBW example."):B("miss",Et,"contact",s==="wide"?"Beyond normal reach":"The batter misses",s==="wide"?"The untouched ball is too far away for a normal stroke. The umpire calls Wide.":"The untouched delivery passes the striker."),s==="catch"&&B("catch",Gi,"collect","Catch controlled",n?"The fielder controls the ball before it touches the ground. The authored decision is resolved separately.":"The fielder controls the ball before it touches the ground: caught."),["fielding","throw","run-out","batting","running"].includes(s)&&B("gather",fn,"collect","Ground ball gathered","The ball has touched the ground. Gathering it is fielding, not a catch dismissal."),["bowling","spin","wide","no-ball","stumping"].includes(s)&&B("keeper",s==="stumping"?3400:3500,"collect","Keeper gathers","The keeper controls the ball behind the striker’s wicket."),(s==="throw"||s==="run-out")&&B("throw",Fs,"throw","Throw released","The fielder releases the gathered ball toward the wicket."),s==="throw"&&B("return",Qo,"collect","Return received","The keeper receives and controls the return throw."),s==="stumping"&&B("wicket",j,"wicket",n?"Wicket broken":"Stumped","Holding the ball, the keeper removes a bail. The striker is out of ground and is not attempting a run."),s==="run-out"&&B("wicket",j,"wicket",n?"Wicket broken":"Run out","The direct throw removes a bail before the running batter makes this ground."),s==="bowled"&&B("wicket",j,"wicket",n?"Stumps hit":"Bowled",n?"The delivery hits the wicket and removes a bail. A broken wicket does not by itself decide a dismissal.":"The legal delivery hits the wicket and removes a bail."),(s==="four"||s==="six")&&B("boundary",5e3,"boundary",s==="four"?"Four runs":"Six runs",s==="four"?"The struck ball reaches the boundary after touching the ground: four.":"The struck ball clears the boundary without touching the ground: six."),s==="running"&&B("run",Dh,"result","One run completed","Both batters have reached the opposite ground. One run is completed."),B("result",5700,"result","Illustrated result",s==="no-ball"?`One no-ball extra; it does not count in the over.${a.freeHitNext?" The next legitimate delivery is a free hit.":" Test cricket has no automatic free hit."}`:s==="wide"?"One wide extra; the delivery does not count in the over.":s==="lbw"?"LBW is declared for this illustrated legal delivery. A full decision also checks pitching, impact and any bat contact.":`${a.runs} bat runs · ${a.extras} extras · ${a.wickets} wicket${a.wickets===1?"":"s"}.`),n){const $={"no-dismissal":"No dismissal was authored for this play.",dismissal:`The authored ${n.ruling.dismissal} decision is allowed in this delivery context.`,"no-ball":`Not out: ${s==="catch"?"a catch":"this dismissal"} cannot dismiss the striker on a no-ball.`,"free-hit":`Not out: ${s==="catch"?"a catch":"this dismissal"} cannot dismiss the striker on a free hit.`,wide:"Not out: this dismissal is not available from a Wide."},C=F.find(z=>z.id==="result");C.label=a.wickets?"Out":"Not out",C.caption=`${$[n.ruling.reason]} ${a.runs} bat runs · ${a.extras} extras · ${a.wickets} wickets. ${a.legalBall?"Counts as a legal ball.":"Does not count in the over."}${a.freeHitNext?" The next delivery is a free hit; an illegal delivery carries it forward.":n.freeHit?" This legal delivery consumes the free hit.":""}`}F.sort(($,C)=>$.time-C.time);const _=e1(0,l,e.every,[1400,1800,Kt,2100,2150,2250,Xi,2600,2800,Et,3050,3100,3200,3250,3300,3400,3500,3800,3900,3950,4e3,Gi,fn,4350,4450,Fs,4900,5e3,5100,5150,Qo,Dh,5700].map(p)),Y=_.map($=>V(f($))),st=[];for(const[$,C]of Object.entries(h)){let z=C.object.pose?.turn??0,X=z;const N=_.map((L,D)=>{const G=f(L);let q=$==="fielder"&&y&&G>3050&&G<3250?ta(C,G,3050,s==="catch"?3800:3950,A,T,X):M($,G),Z=Y[D];const tt=!["batter","non-striker","bowler","keeper"].includes($);if(tt){const U=M("bowler",Math.min(G,Kt)),nt=Tt(U.position,[0,u("bowler")*.8,0]);Z=G<=Kt?nt:G<2100?bn(nt,Z,Lt(_t(G,Kt,2100))):Z}if(v&&($==="batter"||$==="non-striker")&&G>3050&&(Z=$==="batter"?[1,u($)*.8,-10.5]:[-1,u($)*.8,10.5]),$==="bowler"&&G<=Et&&(Z=Tt(M("batter",G).position,[0,u("batter")*.65,0])),tt&&($!=="fielder"||!y||G<=3050)||$==="bowler"&&G>=3e3){const U=Hs(q.position,Z,z);z=$==="bowler"&&G<3500?(q.pose.turn??0)+(Oh(U,q.pose.turn??0)-(q.pose.turn??0))*Lt(_t(G,3e3,3500)):U,q={...q,pose:{...q.pose,turn:z}}}return $==="fielder"&&y&&(G===3050?X=z:G>3050&&(z=Oh(q.pose.turn??0,z),q={...q,pose:{...q.pose,turn:z}})),S4(C,q,Z)});R4(st,c,C,_,N)}for(const[$,C]of["x","y","z"].entries())st.push({id:`ball-${C}`,target:`${c}/ball`,property:C,keyframes:_.map((z,X)=>({time:z,value:Y[X][$]}))});if(["bowled","stumping","run-out"].includes(s))for(let $=0;$<2;$++){const C=`${W}-bail-${$}`,X=t.scene.objects.find(N=>N.id===C).position;st.push({id:`${C}-fall`,target:`${c}/${C}`,property:"position",keyframes:[{time:0,value:[...X]},{time:p(j),value:[...X]},{time:p(j+180),value:Tt(X,[$?.25:-.25,.22,W==="striker"?.22:-.22]),easing:"ease-out"},{time:p(j+650),value:[X[0]+($?.4:-.4),.035,X[2]+(W==="striker"?.45:-.45)],easing:"ease-in"}]}),st.push({id:`${C}-spin`,target:`${c}/${C}`,property:"rotateZ",keyframes:[{time:0,value:0},{time:p(j),value:0},{time:p(j+650),value:$?145:-145}]})}if(s==="lbw"){const $=[S[0]*.8,S[1],Yt.length/2],C=se($,S);st.push({id:"lbw-position",target:`${c}/lbw-guide`,property:"position",keyframes:[{time:0,value:[...S]}]},{id:"lbw-rotation",target:`${c}/lbw-guide`,property:"quaternion",interpolation:"slerp",keyframes:[{time:0,value:t1(C)}]},{id:"lbw-length",target:`${c}/lbw-guide`,property:"scaleY",keyframes:[{time:0,value:Qs(S,$)}]},{id:"lbw-visible",target:`${c}/lbw-guide`,property:"visible",keyframes:[{time:0,value:0},{time:p(Et)-.001,value:0},{time:p(Et),value:1}]})}return{action:s,duration:l,events:F,result:a,timeline:{id:`${c}-${s}`,formatVersion:2,name:K,config:{duration:l,markers:F.map($=>({id:$.id,time:$.time,label:$.label}))},captions:{en:Object.fromEntries(F.map($=>[$.id,$.caption]))},tracks:st}}}function L4(t={}){const e=Wh(t);return{...e,...h1(e,t)}}function N4(t,e){if(!Number.isFinite(e))throw new Error("cricketEventAt: time must be finite");let n;for(const s of t){if(s.time>e)break;n=s}return n}const gn=Object.freeze({deliveryStyles:Object.freeze(["pace","spin"]),deliveryLegalities:Object.freeze(["legal","no-ball","wide"]),shots:Object.freeze(["miss","drive","defend"]),finishes:Object.freeze(["none","single","four","six","stumps","pad"]),fielding:Object.freeze(["none","keeper","catch","gather","throw","stumping","run-out"]),dismissals:Object.freeze(["caught","bowled","lbw","stumped","run-out"])});function Ls(t,e,n){if(!t.includes(e))throw new Error(`cricketPlay.${n}: unknown choice '${e}'`);return e}function W4(t){const{shot:e,finish:n,fielding:s}=t;if(t.delivery.legality==="wide"){if(e!=="miss"||n!=="none"||s!=="keeper")throw new Error("cricketPlay: Wide currently supports only an untouched delivery gathered by the keeper");return"wide"}if(e==="miss"){if(s==="none"&&n==="stumps")return"bowled";if(s==="none"&&n==="pad")return"lbw";if(n==="none"&&s==="stumping")return"stumping";if(n==="none"&&s==="keeper")return t.delivery.style==="spin"?"spin":"bowling"}if(e==="defend"&&n==="none"&&s==="none")return"defend";if(e==="drive"){if(s==="none"&&(n==="four"||n==="six"))return n;if(s==="gather"&&n==="single")return"running";if(n==="none"){if(s==="catch")return"catch";if(s==="gather")return"fielding";if(s==="throw")return"throw";if(s==="run-out")return"run-out"}}throw new Error(`cricketPlay: unsupported motion combination (${e}, ${n}, ${s})`)}function D4(t){const e=Ls(gn.shots,t.shot??"miss","shot"),n=Ls(gn.finishes,t.finish??"none","finish");let s=e==="miss"?"keeper":"gather";(e==="defend"||n!=="none")&&(s=n==="single"?"gather":"none");const i=Ls(gn.fielding,t.fielding??s,"fielding"),r=t.context?.freeHit??!1;if(typeof r!="boolean")throw new Error("cricketPlay.context.freeHit must be boolean");const o=t.decision?.dismissal??null;return o!==null&&Ls(gn.dismissals,o,"decision.dismissal"),{delivery:{style:Ls(gn.deliveryStyles,t.delivery?.style??"pace","delivery.style"),legality:Ls(gn.deliveryLegalities,t.delivery?.legality??"legal","delivery.legality")},shot:e,finish:n,fielding:i,context:{freeHit:r},decision:{dismissal:o}}}function B4(t,e){const n=t.decision.dismissal;if(!n)return{dismissal:null,reason:"no-dismissal"};if({catch:"caught",bowled:"bowled",lbw:"lbw",stumping:"stumped","run-out":"run-out"}[e]!==n)throw new Error(`cricketPlay: '${n}' decision does not match '${e}' motion`);if(n!=="run-out"){if(t.context.freeHit)return{dismissal:null,reason:"free-hit"};if(t.delivery.legality==="no-ball")return{dismissal:null,reason:"no-ball"};if(t.delivery.legality==="wide"&&n!=="stumped")return{dismissal:null,reason:"wide"}}return{dismissal:n,reason:"dismissal"}}function d1(t,e={}){const n=ge(We,t.format,"cricketPlay.format"),s=D4(e);if(s.context.freeHit&&!We[n].freeHitAfterNoBall)throw new Error("cricketPlay: Test format does not support free-hit context");const i=W4(s),r=B4(s,i),o=s.delivery.legality==="legal",a={runs:s.finish==="single"?1:s.finish==="four"?4:s.finish==="six"?6:0,extras:o?0:1,wickets:r.dismissal?1:0,legalBall:o,freeHitNext:We[n].freeHitAfterNoBall&&(s.delivery.legality==="no-ball"||s.context.freeHit&&!o),...r.dismissal?{dismissal:r.dismissal}:{}};return{...u1(t,{action:i,duration:e.duration,every:e.every},{delivery:s.delivery,result:a,ruling:r,freeHit:s.context.freeHit}),play:s,ruling:r}}function z4(t={}){const e=Wh(t);return{...e,...d1(e,t)}}const f1=Object.freeze({"no-ball-stumps":Object.freeze({name:"No-ball + stumps hit",options:Object.freeze({delivery:Object.freeze({legality:"no-ball"}),finish:"stumps",decision:Object.freeze({dismissal:"bowled"})})}),"free-hit-catch":Object.freeze({name:"Free hit + catch",options:Object.freeze({context:Object.freeze({freeHit:!0}),shot:"drive",fielding:"catch",decision:Object.freeze({dismissal:"caught"})})}),"no-ball-four":Object.freeze({name:"No-ball + four",options:Object.freeze({delivery:Object.freeze({legality:"no-ball"}),shot:"drive",finish:"four"})}),"free-hit-run-out":Object.freeze({name:"Free hit + run-out",options:Object.freeze({context:Object.freeze({freeHit:!0}),shot:"drive",fielding:"run-out",decision:Object.freeze({dismissal:"run-out"})})}),"free-hit-wide":Object.freeze({name:"Free hit + Wide",options:Object.freeze({context:Object.freeze({freeHit:!0}),delivery:Object.freeze({legality:"wide"})})})}),q4={linear:!0,"ease-in":!0,"ease-out":!0,"ease-in-out":!0,"ease-in-quad":!0,"ease-out-quad":!0,"ease-in-out-quad":!0,"ease-in-cubic":!0,"ease-out-cubic":!0,"ease-in-out-cubic":!0};function g1(t,e={}){const n={};for(const s of Object.keys(Xt))n[s]={summary:`Walks to \`to\` in the ${s} gait.`,needs:["to"]};for(const s of Object.keys(ae))n[s]={summary:`Moves into the ${s} pose and holds it (\`for\` ms).`};for(const s of Object.keys(on))n[s]={summary:`The ${s} gag (${Wi(s)} ms).`};for(const[s,i]of Object.entries(Di))n[s]={...i};return{sports:{cricket:{actions:{...Wn},formats:{...We},casts:{...$h},fieldingPositions:{..._s},markingProfiles:{...Jo},cameras:{...Uo},decisionCameras:Ki,playComponents:gn,playExamples:f1}},...t?{version:t}:{},timing:"JSON timelines and tracks are in milliseconds; the GSAP-style API (live.to, tf.timeline) takes seconds. Scene x grows right, y grows down, in px.",easings:{named:Object.keys(q4),parametric:{"cubic-bezier":'{ type: "cubic-bezier", points: [x1, y1, x2, y2] }',steps:'{ type: "steps", count, position?: start | end | none | both }',elastic:'{ type: "elastic", mode?: in | out | in-out, amplitude?, period? }',bounce:'{ type: "bounce", mode?: in | out | in-out }',back:'{ type: "back", mode?: in | out | in-out, overshoot? }'}},trackKinds:{keyframe:"{ id, target, property, keyframes: [{ time, value, easing? }] }: values between keys are interpolated (numbers, colours, paths)",spring:'{ id, target, property, kind: "spring", spring: { from, to, stiffness?, damping?, mass?, velocity? }, delay? }: physics settle',inertia:'{ id, target, property, kind: "inertia", inertia: { from, velocity, friction?, min?, max?, end? }, delay? }: a flick that slows (end snaps to a value or the nearest of a list)',motionPath:'{ property: "motionPath", path, align? }: moves along an SVG path',text:'{ property: "text", … }: types or scrambles text'},canvasProperties:Lo,stickFigure:{poseFields:pd,props:md,handFields:yd,poses:Object.keys(ae),expressions:Object.keys(vt),gags:Object.fromEntries(Object.keys(on).map(s=>[s,Wi(s)])),gaits:Object.keys(Xt),actingStyles:Object.keys(Fn),beatFields:Oo,actions:n,dances:Object.fromEntries(Object.entries(Ze).map(([s,i])=>[s,Object.keys(i.moves)])),flips:Object.fromEntries(Object.entries(Pi).map(([s,i])=>[s,i.label])),handShapes:Object.keys(St),mudras:Object.keys(Hr)},props:{api:{"car() · truck() · bus() · tractor() · cart() · trainCar() · bike() · motorbike()":"wheeled vehicles (vehicle(spec) makes your own)","tree() · house()":"environment (tree(spec), house(spec))","helicopter() · airplane()":"aircraft","horse() · dog() · cat() · cow()":"animals (quadruped(spec) makes your own): gaits with footfall patterns keyed in step with the distance, sit, jump, their calls, species actions","songbird() · crow() · chicken()":"birds (bird(spec) makes your own): hop, walk, peck, flap, fly and land (a chicken flutters), their calls; wings fold and beat in rhythm","{ kind: 'prop', prop: 'car', position, rotation, values } with loadScene3D(scene, { kinds: [characterObjects, propObjects] })":"props in 3D scenes, by preset name, seen in perspective by the scene camera; controls are tracks on the object","characterScript3D(id, beats, { scene, position?, heading?, height?, pose? })":"a v2 character in world metres: gaits, face (shortest turn), spin (signed turns and duration), dance (native style, bpm, beats), hold, pose, gag; checkCharacterBeats3D checks the beats","propRide3D({ prop, propId, propTracks, scene, placement, anchor, riderId, pose, start, end, mount?, dismount? })":"a character riding a prop in a 3D scene: hips on a seat anchor (saddle, seat) as it moves, hopping on and off; RIDING_POSES.astride / .seated / .driving / .cycling / .wheeling (a wheelchair)","propScript3D(id, prop, beats, { scene, position?, heading?, values? })":"props scripted in world metres for 3D scenes: moves to [x, z] or through points (wheels and strides keyed with the distance), face, hold, and their actions; checkPropBeats3D checks the beats","propPreset(name, options?)":"a prop preset by name (did-you-mean on a wrong one)","propTarget({ …, style: 'stick' })":"line art to go with stick figures: tubes as single strokes, shapes outlined over paper","propTow({ leader, leaderId, leaderTracks, hitch, towed, towedId, anchor, start, end })":"a prop towed by another (a cart behind a horse): turns with it, its wheels roll exactly","propTarget({ x, y, prop, scale?, values?, look?, ink? })":"a canvas target that draws a prop (x, y: its middle on the ground; scale px per metre, default 60)","propScript(id, prop, beats, { from, ground, scale, style?, exaggeration?, start? })":"beats → acted tracks, with contact times and effect cues; checkPropBeats(beats, prop) checks them","drawProp(ctx, target, frame, id, { rider? })":"draw it as it is in a frame (a rider is drawn between its far and near parts)","propAt(target, frame, id).anchor(name)":"where an anchor (seat, door, chimney…) is, in scene px","propRide({ prop, propId, propTracks, anchor, figure, figureId, start, end, offset? })":"a figure carried at an anchor, turning with the prop; spliceTracks() puts it into the figure’s tracks","drawPropEffects(ctx, effects, time)":"dust, exhaust, skid marks, honk lines, leaves, smoke"},beatFields:jo,commonControls:Object.fromEntries(Object.entries(Ps).map(([s,i])=>[s,`${i.description}${i.unit?` (${i.unit})`:""}`])),commonActions:Object.fromEntries(Object.entries(Ah).map(([s,i])=>[s,i.summary])),presets:Object.fromEntries(Object.entries(Cs).map(([s,i])=>{const r=i();return[s,{family:r.family,summary:r.summary,actions:Object.fromEntries(Object.entries(r.actions).map(([o,a])=>[o,{summary:a.summary,...a.needs?{needs:a.needs}:{}}])),controls:Object.keys(r.rig.controls),anchors:Object.keys(r.rig.anchors??{})}]}))},custom:{api:{"defineAction({ summary, needs?, steps: (from, beat) => [{ after, pose, easing? }] })":"a new action written as timed pose steps from the current pose, like a gag","defineAction({ summary, needs?, beats: (beat) => [beats] })":"a new action built from other beats (which may be custom too)","defineGait({ swing, knee, arm, elbow, lean, cycle?, … })":"a new gait (the Gait fields in degrees; cycle is ms per two steps)","scriptTracks(id, beats, { actions, gaits })":"beats may then use those names; checkBeats(beats, { actions, gaits }) knows them","stickFigureTarget({ …, cast: { actions, gaits } })":"a figure that draws the gaits and lists the actions in describeTarget","persona({ name, summary?, height?, look?, acting?, gait?, mood?, stance?, energy?, actions?, gaits? })":"a character’s look, acting style and habits: .figure({ x, y }), .script(id, beats, { from, ground }), .check(beats), .handPath(…), .describe(); `go` walks in its gait, `stand` returns to its stance and face"},actions:Object.fromEntries(Object.entries(e.actions??{}).map(([s,i])=>[s,{summary:i.summary,...i.needs?{needs:i.needs}:{}}])),gaits:Object.fromEntries(Object.entries(e.gaits??{}).map(([s,i])=>[s,i.summary??"custom gait"]))},character:{figureStyles:["fluid","stick","organic"],body:{"body.torso · body.arm · body.leg · body.neck":"Organic half-width profiles: [{ at: 0..1, width: fractionOfHeight }], increasing from 0 to 1; independent of ink width.","body.measurements":`Organic torso from tape-measure girths { height, bust, underbust?, waist, hip } in any one unit, or a named shape (${Object.keys(Gr).join(" | ")}). Sets the front width, the side depth (bust forward, seat back, belly) and the hip and thigh spacing; reads correctly at every turn. An explicit torso / torsoFront / torsoBack / hipWidth still wins.`,"body.torsoFront · body.torsoBack":"Organic side-view depth from the spine line toward the chest/belly and toward the back/seat, same profile format; default torso × depth.","body.fill · body.outline · body.shading":"Shared skin fill, outline { color, width }, cel material { mode: cel | none, light: [x,y], shadow, opacity, highlight }.","softCartoonCharacter(name, options?)":"Original youngMan / youngWoman / childBoy / childGirl story presets. Children have larger head proportions, shorter limbs and rounded torsos; every face, hair, build, hand, clothing and material option can be overridden.","face.projection":"Organic default volume follows the head axes, keeps both eyes in three-quarter views and projects a small nose above the mouth; opaque hair covers features. cartoon keeps the classic face slide.","outfitPreset(category, overrides?)":"Fresh JSON Everyday / Formal / Casual wardrobe defaults for every actor; top: tshirt | shirt | blouse | dress, trouserStyle: plain | jeans | cargo, colours, sleeves, bottoms, collar and tie are editable.",leafOutfit:"Organic-only JSON garment { top?, color?, accent?, length? }; curved leaves follow torso/thighs at native part depths. Everyday basicOutfit also follows organic contours."},poses:Object.keys(be),dances:Object.keys(An),expressions:Object.keys(Il),faceStyles:["simple","anime"],faceShapes:["round","angular"],gags:Object.keys(ro),builds:Object.keys(Dr),hair:Object.keys(Vl),hairColors:{...Ae},facialHair:Object.keys(ec),glasses:Object.keys(sc),hats:Object.keys(no),feet:[...vf],cast:Object.keys(jc),heldItems:Object.fromEntries(Object.entries(ac).map(([s,i])=>[s,i.hands])),handMeetings:Object.keys(Ni)},codePanel:{languages:Ao,removeStyles:To,anchors:{"line(n, time?)":"line n’s text box { x, y, left, right, top, bottom, width, height }: stand on top, point at x, y","token(n, text, occurrence?, time?)":"a word on a line","spot(n, column, width?, time?)":"a place in a line, for put and write","landing(piece, n, column)":"where a dropped piece will land",box:"the whole panel"},edits:Nc},surfaces:{code:Hi,board:Re,chart:Hn,prop:Is},surfaceScript:{"surfaceScript(figureId, { name: surface }, beats, options)":"compiles beats that act on surfaces: returns the script result with `tracks` (the figure’s, ridden, then every surface’s, keyed by its name) and `figureTracks`; options are scriptTracks’ plus `figureStyle` (for carry) and `ride` (default true)","checkSurfaceBeats(beats, surfaces, cast?)":"every problem checkBeats finds, plus unknown surfaces, places, edits and moments, with suggestions","{ surface, anchor }":"a named place, where a beat takes `target` (its box), `to` (its centre x) or `onto` (its top); as laid out, before any edit moves it","then: { surface, edit, anchor, at?, until?, …options }":"what the surface does in answer to the beat (or a list of them): one of its edits, or `carry` (the piece follows the hand until `until`); the other fields are the edit’s options",at:`a moment of the beat: ${Es.join(", ")} (default contact, or start when the beat has none); not ms`,until:"a moment of this beat, or { beat: index, at? } of a later one; sets the edit’s duration (carry needs it)"},cameraShots:{frame:"{ at, duration?, easing?, frame: { focus?: { x, y }, scale?, rotate? } }: push in, pull out, or cut (duration 0)",shake:"{ at, duration, shake: { strength?, frequency?, roll?, seed? } }",follow:"{ at, until, follow: { x: <the subject’s x keyframes>, lead?, y?, lag?, scale? } }: keeps a subject centred"},teach:{"lesson({ id })":"steps as timeline JSON: to, set, together, wait, marker (with pause, question, captions)","cells, pointer, stack, queue, table, pipeline":"diagram primitives (SVG markup + step helpers)","figure({ width, height, children })":"the SVG holding the pieces"},math:{api:{"mathFigure(spec)":"checks a figure (JSON: width, height, x?, y?, theme?: dark | light | chalk, values, items) and says how to fix it","layoutFigure(spec, props)":"the figure at some values as shapes; drawDisplayList(ctx, list) or displayListToSvg(list) draws them","mathTarget(spec, { x, y })":"a canvas target for videos and canvas pages; tracks animate its values and item props","mathSteps(lesson, target, spec, { hidden })":"lesson steps: toValue, applyMatrix, drawOn, fadeIn, fadeOut, showStep (equations)","mountMath(element) / mountAllMath()":"lesson-page embeds: <figure data-tinyfly-math> with data-tinyfly-figure and data-tinyfly-timeline JSON scripts, stepped like any embed","mathExplorable(element, spec, { sliders, drag })":"reader-driven figures: sliders on number values, drag vector tips or matrix columns","mathFigureToSvg(spec, props)":"a standalone SVG of a figure at some values","linearMapFigure, determinantFigure, eigenFigure, vectorSumFigure, spanFigure":"ready linear algebra figures; the matrix is the value M","tangentFigure, secantFigure, riemannFigure, areaFigure, taylorFigure, limitFigure":"ready calculus figures; their moving parts are number values (a, h, n, b, order, p)","differentiate / compileDerivative / integrate":"exact symbolic derivatives of expressions; Simpson integration","normalFigure, binomialFigure, cltFigure, galtonFigure, monteCarloPiFigure, regressionFigure, bayesFigure":"ready probability and statistics figures","graphSearchFigure, shortestPathFigure, recursionTreeFigure, vennFigure, clockFigure":"ready discrete maths figures; searches move with the value step","searchEvents / parseSetExpression / regionCells":"graph searches as data; set expressions and their Venn cells",distributions:"{ kind: normal | uniform | exponential | binomial | poisson | dice | mean, …numbers or value names }; density, meanOf, sdOf, samples (seeded)","layoutTex(tex) / morphEquation(a, b, t)":"the built-in TeX subset, and term-by-term transitions","vec2, mat2":"2D vectors and 2×2 matrices (apply, multiply, determinant, inverse, eigen)"},items:{grid:"{ step?, transform?: matrix value, ghost? }: lines of the plane, warped by a matrix",axes:"{ ticks?, labels? }",vector:"{ to, from?, transform?, label? (TeX), labelAt?: tip | middle }",basis:"{ transform? }: î and ĵ",point:"{ at, transform?, label?, hollow? } or { on: expr, x } (a point riding a curve)",function:'{ expr: "sin(k x)", domain?, derivative?, dashed? }: y = f(x); number values are its parameters',parametric:"{ x, y (expressions in t), t?, transform? }",polygon:"{ points? (default the unit square), transform?, label? }: \\val{M.det} shows the determinant",line:"{ along } or { eigen: matrix value }: a span, or eigenlines",label:"{ tex, at, screen?, size?, align?, backdrop? }",equation:"{ steps: [TeX…], at, screen? }: ITEM.step moves between steps, terms gliding",tangent:"{ expr, at, h? (secant), label? }: \\val{ID.slope} is the exact slope",riemann:"{ expr, from, to, n, rule?: left | right | midpoint | trapezoid }: \\val{ID.sum}, \\val{ID.exact}",area:"{ expr, from, to, lower? }: signed, coloured by sign; \\val{ID.value}",taylor:"{ expr, at, order }: exact Taylor polynomials; a fractional order grows the next term in",histogram:"{ distribution, count, bins?, scale?, curve?, seed? }: seeded samples, binned; fills as count grows",distribution:"{ distribution, shade?: [a, b] }: a density curve (bars when discrete); \\val{ID.p}",galton:"{ rows?, balls, spacing?, top?, seed? }: a Galton board; fractional balls = the next one falling",scatter:"{ points: uniform | linear, count, inside?, fit?, seed? }: Monte Carlo and regression; \\val{ID.ratio}, \\val{ID.r}",bayes:"{ prior, truePositive, falsePositive }: Bayes as areas; \\val{ID.posterior}",graph:"{ nodes, edges, directed?, tree?, search?: { kind: bfs | dfs | dijkstra, start }, step?, frontier? }: searches step by step",venn:"{ sets (2 or 3), highlight?: set expression like (A | B)' }: shaded by clipping",clock:"{ modulus, value }: clock arithmetic; \\val{ID.hour}"},props:{NAME:"a value: a number, [x, y] vector or [a, b, c, d] matrix (row by row; columns are where î and ĵ land)","ITEM.draw":"0..1, draws an item on","ITEM.opacity":"0..1","ITEM.step":"an equation's step; fractional values are part way"},functions:["sin","cos","tan","asin","acos","atan","atan2","sinh","cosh","tanh","exp","ln","log","log2","sqrt","abs","floor","ceil","round","sign","min","max","sigmoid","relu"],tex:"^ _ \\frac \\sqrt \\vec \\hat \\bar, \\sum \\prod \\int with limits, \\sin \\lim … , Greek, \\cdot \\times \\le \\to \\infty …, pmatrix / bmatrix / vmatrix, \\text, \\color{c}{…}, \\id{name}{…} (names a term for transitions), \\val{name:digits} (a live value)"},cli:{"tinyfly capabilities [--json]":"this catalog","tinyfly check <beats.json>":"check a beat script (names, fields) with suggestions","tinyfly validate <timeline.json> [--markup file]":"check a timeline against its markup","tinyfly render <timeline.json> <markup> [--at …]":"a frame as static markup","tinyfly video <scene.mjs> [--stills dir --times …]":"MP4, or PNG stills to look at"}}}const yt=t=>t.map(e=>`\`${e}\``).join(", "),p1=t=>Object.entries(t).map(([e,n])=>`| \`${e}\` | ${n.unit??n.kind??""} | ${n.description} |`).join(`
|
|
62
|
+
`)}`);const r=s.from??0,o=s.ground??0,a=s.scale??60,l=s.exaggeration??1,c=Yo(e),h={};for(const S of[...Object.keys(Ps),...Object.keys(e.rig.controls)])h[S]=s.start?.[S]??It(e.rig,{},S);const u=[{time:0,pose:{...h}}],d=new Map,f=[];let p=r,g=o;const m=(S,E,P,I)=>{const O=d.get(S)??[{time:0,value:S==="x"||S==="y"?0:h[S]}];O.push({time:E,value:P,...I?{easing:I}:{}}),d.set(S,O),S!=="x"&&S!=="y"&&(h[S]=P)},y=(S,E)=>{const P=S==="x"?p-r:S==="y"?g-o:h[S],I=d.get(S);(!I||I[I.length-1].time<E)&&m(S,E,P)},v={prop:e,scale:a,exaggeration:l,get x(){return p},get floor(){return g},values:h,facing(){const S=Math.sin(h.turn*Math.PI/2);return Math.abs(S)<.5?0:S>0?1:-1},key(S,E,P={}){Object.assign(h,E),u.push({time:S,pose:{...h},...P.act===!1?{act:!1}:{},...P.easing?{easing:P.easing}:{}})},move(S,E,P,I={}){y("x",S),m("x",E,P-r,I.easing),p=P,I.floor!==void 0&&(y("y",S),m("y",E,I.floor-o,I.easing),g=I.floor)},set(S,E,P,I){m(S,E,P,I)},turnTo(S,E){const P=typeof E=="number"?E:Eh[E],I=h.turn,H=[P-4,P,P+4].map(j=>({t:j,d:Math.abs(j-I)})).sort((j,J)=>j.d-J.d||Math.abs(j.t)-Math.abs(J.t))[0];if(H.d<.001)return S;const W=S+y4*Math.max(1,H.d);return v.key(W,{turn:H.t}),W},effect(S){f.push(S)},anchor(S){const P=$s(e,h,a).anchors[S];if(!P)throw new Error(`${e.kind}: no anchor "${S}"`);return{x:p+P.point.x,y:g+P.point.y}}},k=[];let w=0;for(const S of n){const E=Math.max(S.at??w,u[u.length-1].time),P=c[S.do].run(v,S,E);P.end>u[u.length-1].time&&u.push({time:P.end,pose:{...h}}),k.push({start:E,end:P.end,...P.contact!==void 0?{contact:P.contact}:{},...P.release!==void 0?{release:P.release}:{}}),w=P.end}const T=Xc(s.style??"snappy"),A={...T,anticipation:T.anticipation*l,overshoot:T.overshoot*l},M=Io(v4(u),e.acting,{style:A}),x=[...Object.entries(M).filter(([S])=>!d.has(S)).map(([S,E])=>({id:`${t}-${S}`,target:t,property:S,keyframes:E})),...[...d].map(([S,E])=>({id:`${t}-${S}`,target:t,property:S,keyframes:M4(E)}))];for(const S of w4(t,e,x,w,u[0].pose)){const E=x.findIndex(O=>O.property===S.property);if(E<0){x.push(S);continue}const P=new Ht({id:`${t}-own`,tracks:[x[E]]}),I=O=>Number(P.getStateAtTime(O).values.get(t)?.get(S.property)??0);x[E]={...S,keyframes:S.keyframes.map(O=>({time:O.time,value:Number(O.value)+I(O.time)}))}}return{tracks:x,duration:w,beats:k,effects:f}}const b4=1500;function w4(t,e,n,s,i){if(!e.follow?.length)return[];const r=new Ht({id:`${t}-follow`,tracks:n.filter(a=>a.property==="turn"||e.follow.some(l=>l.of===a.property))}),o=(a,l)=>{const c=r.getStateAtTime(a).values.get(t)?.get(l);return typeof c=="number"?c:i[l]??0};return e.follow.map(a=>{const l=s+b4,c=Vs(d=>o(d,a.of),{start:0,end:l,stiffness:a.stiffness,damping:a.damping}),h=a.limit??1/0,u=c.map(({time:d,value:f})=>{const p=Math.sin(o(d,"turn")*Math.PI/2),g=(f-o(d,a.of))*p;return{time:d,value:Math.max(-h,Math.min(h,g*a.per))}});return{id:`${t}-${a.control}`,target:t,property:a.control,keyframes:u}})}const k4=20;function v4(t){const e=[...t].sort((s,i)=>s.time-i.time),n=[];for(const s of e){const i=n[n.length-1];i&&s.time-i.time<k4?n[n.length-1]={...s,time:i.time}:n.push(s)}return n}function M4(t){const e=t.map((s,i)=>({k:s,i})).sort((s,i)=>s.k.time-i.k.time||s.i-i.i),n=[];for(const{k:s}of e)n.length>0&&n[n.length-1].time===s.time?n[n.length-1]=s:n.push(s);return n}const We=Object.freeze({test:Object.freeze({name:"Test",inningsPerSide:2,oversPerInnings:null,ballsPerOver:6,freeHitAfterNoBall:!1,summary:"Multi-day cricket. Each side can have two innings; there is no innings over limit."}),odi:Object.freeze({name:"ODI",inningsPerSide:1,oversPerInnings:50,ballsPerOver:6,freeHitAfterNoBall:!0,summary:"One innings per side, up to 50 overs. A no-ball gives a free hit on the next legitimate delivery."}),t20:Object.freeze({name:"T20",inningsPerSide:1,oversPerInnings:20,ballsPerOver:6,freeHitAfterNoBall:!0,summary:"One innings per side, up to 20 overs. A no-ball gives a free hit on the next legitimate delivery."})}),$h=Object.freeze({adults:"Adults",men:"Men",children:"Children",mixed:"Mixed cast"}),_s=Object.freeze({bowler:"Bowler",keeper:"Wicketkeeper",fielder:"Extra cover",slip:"Slip",point:"Point",cover:"Cover","mid-off":"Mid-off","mid-on":"Mid-on","square-leg":"Square leg","fine-leg":"Fine leg","third-man":"Third man"}),Wn=Object.freeze(Object.fromEntries(Object.entries({bowling:{name:"Pace bowling",summary:"Run up, deliver with a straight arm, bounce and follow through."},spin:{name:"Spin bowling",summary:"A shorter approach and a curved illustrative flight before the bounce."},batting:{name:"Drive",summary:"Two hands on the bat, a backlift, contact and a follow-through."},defend:{name:"Defensive block",summary:"Meet the ball with a controlled bat and keep it close."},running:{name:"Running between wickets",summary:"Both batters make the opposite ground to complete one run."},four:{name:"Boundary four",summary:"A struck ball reaches the boundary after touching the ground."},six:{name:"Boundary six",summary:"A struck ball clears the boundary before touching the ground."},catch:{name:"Catch",summary:"A fielder controls the struck ball before it touches the ground."},fielding:{name:"Ground field",summary:"A fielder moves to the ball, bends and gathers it."},throw:{name:"Field and throw",summary:"Gather, wind up, release and return the ball to the keeper."},bowled:{name:"Bowled",summary:"A legal delivery hits the wicket and removes a bail."},lbw:{name:"LBW illustration",summary:"Pad contact and a projected path to the stumps illustrate an authored LBW decision."},stumping:{name:"Stumping",summary:"The keeper holds the ball and breaks the wicket while the striker is out of ground, not attempting a run."},"run-out":{name:"Run-out",summary:"A direct throw breaks the wicket before the running batter makes that ground."},"no-ball":{name:"Front-foot no-ball",summary:"The landing front foot oversteps the popping crease at release; one extra, no legal ball."},wide:{name:"Wide ball",summary:"An untouched delivery passes beyond reach for a normal stroke; one extra, no legal ball."}}).map(([t,e])=>[t,Object.freeze(e)])));function ge(t,e,n){if(!Object.prototype.hasOwnProperty.call(t,e))throw new Error(`${n}: unknown choice '${e}'`);return e}const _t=(t,e,n)=>Math.max(0,Math.min(1,(t-e)/(n-e))),Lt=t=>t*t*(3-2*t),Tt=(t,e)=>Js(t,e),Ih=(t,e)=>yn(t,e);function Oh(t,e){const n=e+((t-e+2)%4+4)%4-2;return n===0?0:n}function Hs(t,e,n=0){return Math.hypot(e[0]-t[0],e[2]-t[2])<.001?n:Oh(Math.atan2(e[0]-t[0],e[2]-t[2])*2/Math.PI,n)}function Zy(){return{turn:1,"head.turn":90,"leg.left.spread":12,"leg.right.spread":12,"leg.left.swing":6,"leg.right.swing":6,"leg.left.knee":12,"leg.right.knee":12}}function Ch(t,e){const n=t.objects.find(s=>s.id===e);if(!n||n.kind!=="character")throw new Error(`cricketAction: required character '${e}' is missing`);if(n.parent||n.rotation?.some(s=>s!==0)||n.quaternion||n.scale!==void 0)throw new Error(`cricketAction: '${e}' must use position and pose.turn, without a transformed parent, scale or object rotation`);return{object:n,who:ms({...n.character,height:n.height??1.78})}}function Qy(t){return{position:[...t.object.position??[0,0,0]],pose:{...lt,...t.object.pose}}}function Rs(t,e,n,s){const i=Qe(t.who.plan,e.pose,{height:t.who.height,contact:t.who.contact});return Tt(e.position,i.chains[n][s])}function Yi(t,e,n){const s=Rs(t,e,`arm.${n}`,2),i=Rs(t,e,`arm.${n}`,1);return Tt(s,Ih(Jt(se(s,i)),t.who.lineWidth*.5))}function S4(t,e,n){const s={...e.pose,"head.turn":0,"head.nod":0,"head.tilt":0},i=Qe(t.who.plan,s,{height:t.who.height,contact:t.who.contact}).head,r=se(n,Tt(e.position,i.center)),o=i.axes.map(c=>Ie(r,c)),a=Math.atan2(o[0],o[2])*180/Math.PI,l=Math.atan2(-o[1],Math.hypot(o[0],o[2]))*180/Math.PI;return{...e,pose:{...e.pose,"head.turn":Math.max(-90,Math.min(90,a)),"head.nod":Math.max(-25,Math.min(30,l)),"head.tilt":0}}}function dn(t,e,n,s,i="hold"){let r={...e.pose};for(let o=0;o<10;o++){const a={...e,pose:r},l=Qe(t.who.plan,r,{height:t.who.height,contact:t.who.contact}),c=is(t.who.plan,r,t.who.height),h=se(Yi(t,a,n),Rs(t,a,`arm.${n}`,2)),u=se(se(se(s,h),e.position),l.hip),d=ss(u,(r.roll??0)*Math.PI/180),f=Tt(c.root,Qt(d,-(r.turn??0)*Math.PI/2));r=yi(t.who.plan,r,`arm.${n}`,f,{height:t.who.height})}for(const[o,a]of Object.entries(St[i]))r[`hand.${n}.${o}`]=a;return{...e,pose:r}}function x4(t,e,n,s){const i=Jt(s),r=t.who.height/1.78;let o=dn(t,e,"left",n);return o=dn(t,o,"right",Tt(Yi(t,o,"left"),Ih(i,.105*r))),{...o,bat:{grip:Yi(t,o,"left"),axis:i,scale:r}}}function T4(t){return Tt(t.grip,Ih(t.axis,.51*t.scale))}function t1(t){const e=Jt(t),n=Math.max(-1,Math.min(1,e[1]));return n>.999999?[0,0,0,1]:n<-.999999?Vt([1,0,0],180):Vt(Jt(Zs([0,1,0],e)),Math.acos(n)*180/Math.PI).map(s=>s===0?0:s)}function Ko(t,e,n){const s={};for(const i of Object.keys({...t,...e})){const r=t[i]??lt[i]??0;s[i]=r+((e[i]??lt[i]??0)-r)*n}return s}function _h(t,e){if(t<=e[0][0])return{...lt,...e[0][1]};for(let n=1;n<e.length;n++)if(t<=e[n][0])return Ko({...lt,...e[n-1][1]},{...lt,...e[n][1]},Lt(_t(t,e[n-1][0],e[n][0])));return{...lt,...e.at(-1)[1]}}function De(t,e){if(!Array.isArray(t)||t.length!==3||!t.every(Number.isFinite))throw new Error(`${e}: expected three finite coordinates`)}function e1(t,e,n=40,s=[]){if(!Number.isFinite(t)||!Number.isFinite(e)||t<0||e<t)throw new Error("sampleTimes: expected finite ordered nonnegative times");if(!Number.isFinite(n)||n<16||n>1e3)throw new Error("sampleTimes: every must be between 16 and 1000 ms");if((e-t)/n>2e4)throw new Error("sampleTimes: too many samples");const i=new Set([t,e,...s.filter(r=>r>=t&&r<=e&&Number.isFinite(r))]);for(let r=t+n;r<e;r+=n)i.add(r);return[...i].sort((r,o)=>r-o)}function Hh(t,e){if(n1(t),!Number.isFinite(e))throw new Error("ballFlightPoint: time must be finite");const n=Math.max(0,Math.min(1,(e-t.start)/(t.end-t.start))),s=4*n*(1-n),i=t.to[0]-t.from[0],r=t.to[2]-t.from[2],o=Math.hypot(i,r)||1;return[t.from[0]+i*n-r/o*(t.curve??0)*s,t.from[1]+(t.to[1]-t.from[1])*n+(t.arc??0)*s,t.from[2]+r*n+i/o*(t.curve??0)*s]}function n1(t){if(!t.target?.trim())throw new Error("ballFlight: target is required");if(De(t.from,"ballFlight.from"),De(t.to,"ballFlight.to"),!Number.isFinite(t.start)||!Number.isFinite(t.end)||t.start<0||t.end<=t.start)throw new Error("ballFlight: end must be greater than start, both finite and nonnegative");if(!Number.isFinite(t.arc??0)||(t.arc??0)<0||!Number.isFinite(t.curve??0))throw new Error("ballFlight: arc must be finite and nonnegative; curve must be finite")}function E4(t){n1(t);const e=e1(t.start,t.end,t.every),n=e.map(s=>Hh(t,s));return["x","y","z"].map((s,i)=>({id:`${t.id??"flight"}-${s}`,target:t.target,property:s,keyframes:e.map((r,o)=>({time:r,value:n[o][i]}))}))}const Ki=Object.freeze({"front-foot":Object.freeze({name:"Front-foot review",summary:"A fixed side view of the landing front foot and bowler’s popping crease at release."}),"striker-crease":Object.freeze({name:"Striker crease",summary:"A fixed side view of the striker’s popping crease, wicket and keeper arrival."}),"bowler-crease":Object.freeze({name:"Bowler crease",summary:"A fixed side view of the other crease and wicket for a running batter and return throw."})});function Rh(t){return Object.prototype.hasOwnProperty.call(Ki,t)}function Xo(t,e){if(!Rh(e))return;const n=i=>t.events.find(r=>r.id===i),s=e==="front-foot"?n("release"):e==="bowler-crease"?t.action==="run-out"?n("wicket"):n("run")??n("release"):(t.action!=="run-out"?n("wicket"):void 0)??n("run")??n("keeper")??n("return")??t.events.find(i=>i.kind==="contact");if(s){if(!Number.isFinite(s.time)||s.time<0||s.time>t.duration)throw new Error("cricketCameraReview: event time must be within the clip");return{...s}}}function Go(t,e,n){const s=Ch(t.scene,e),i=Qy(s);for(const r of t.timeline.tracks){if(r.target!==t.scene.id+"/"+e)continue;if(!("keyframes"in r))throw new Error("cricketCamera: review requires baked actor tracks");const o=new Xe(r).getValueAtTime(n);if(typeof o!="number"||!Number.isFinite(o))continue;const a=["x","y","z"].indexOf(r.property);a>=0?i.position[a]=o:i.pose[r.property]=o}return{actor:s,sample:i}}function s1(t){const e=Xo(t,"front-foot");if(!e)throw new Error("cricketCamera: front-foot view requires a release event");const{actor:n,sample:s}=Go(t,"bowler",e.time);return{point:Rs(n,s,"leg.right",2),height:n.who.height}}function i1(t,e){const n=e==="striker-crease"?"striker":"bowler",s=t.landmarks[n+"-crease"];return De(s,"cricketCamera.crease"),[...s]}function A4(t,e){if(!Rh(e))return[];const n=i1(t,e),s=e==="front-foot"?s1(t).point[0]:0;return[{id:"decision-review-"+e,name:Ki[e].name+": crease reference",kind:"line",color:"#f4b83f",width:.035,points:[[s-1.1,.045,n[2]],[s+1.1,.045,n[2]]]}]}function Fh(t,e,n,s){const i=e*Math.PI/180,r=n*Math.PI/180;return[t[0]+s*Math.cos(r)*Math.sin(i),t[1]+s*Math.sin(r),t[2]+s*Math.cos(r)*Math.cos(i)]}const Lh=(t,e,n)=>[t[0]+(e[0]-t[0])*n,t[1]+(e[1]-t[1])*n,t[2]+(e[2]-t[2])*n];function P4(t,e,n){const s={target:[0,0,0],yaw:0,pitch:15,distance:8,...t},i={...s,...e},r=Lh(s.target,i.target,n),o=s.position||i.position?Lh(s.position??Fh(s.target,s.yaw,s.pitch,s.distance),i.position??Fh(i.target,i.yaw,i.pitch,i.distance),n):Fh(r,s.yaw+(i.yaw-s.yaw)*n,s.pitch+(i.pitch-s.pitch)*n,s.distance+(i.distance-s.distance)*n),a=Lh(s.lookAt??s.target,i.lookAt??i.target,n),l=s.fov!==void 0||i.fov!==void 0?(s.fov??i.fov)+((i.fov??s.fov)-(s.fov??i.fov))*n:void 0;return{position:o,lookAt:a,fov:l}}function $4(t){const e=Math.max(1,t.every??33),n=Wt(t.easing??"ease-in-out"),s=`${t.scene}/${t.camera}`,i=[],r=[],o=[];for(let l=t.start;;l=Math.min(t.end,l+e)){const c=t.end>t.start?n((l-t.start)/(t.end-t.start)):1,h=P4(t.from,t.to,c);if(i.push({time:l,value:h.position}),r.push({time:l,value:h.lookAt}),h.fov!==void 0&&o.push({time:l,value:h.fov}),l>=t.end)break}const a=[{id:`${s}-move-position`,target:s,property:"position",keyframes:i},{id:`${s}-move-lookAt`,target:s,property:"lookAt",keyframes:r}];return o.length>0&&a.push({id:`${s}-move-fov`,target:s,property:"fov",keyframes:o}),a}function I4(t){const e=Math.max(1,t.every??33),n=t.offset??[0,2,6],s=t.lag??0,i=`${t.scene}/${t.camera}`,r=[],o=[];for(let a=t.start;;a=Math.min(t.end,a+e)){const l=t.subjectAt(a),c=t.subjectAt(Math.max(t.start,a-s));if(r.push({time:a,value:[c[0]+n[0],c[1]+n[1],c[2]+n[2]]}),o.push({time:a,value:l}),a>=t.end)break}return[{id:`${i}-follow-position`,target:i,property:"position",keyframes:r},{id:`${i}-follow-lookAt`,target:i,property:"lookAt",keyframes:o}]}const Uo=Object.freeze({pitch:"Whole pitch",batter:"Batter close-up",bowler:"Bowler close-up",keeper:"Keeper close-up",field:"Whole ground",overhead:"Overhead ground",orbit:"360° ground orbit","follow-ball":"Follow the ball",...Object.fromEntries(Object.entries(Ki).map(([t,e])=>[t,e.name]))}),Vo=Object.freeze({pitch:75,batter:145,bowler:35,keeper:145,field:75,overhead:75,orbit:75,"follow-ball":75,"front-foot":90,"striker-crease":90,"bowler-crease":90});function r1(t,e="pitch"){const n=ge(Uo,e,"cricketCamera.view");if(Rh(n)){const i=i1(t,n);if(n==="front-foot"){const c=s1(t);return{target:[c.point[0],.12,(c.point[2]+i[2])/2],pitch:25,distance:Math.max(2.2,2.6*c.height/1.78),fov:40}}const r=t.landmarks[n==="striker-crease"?"striker-wicket":"bowler-wicket"];De(r,"cricketCamera.wicket");let o=(i[2]+r[2])/2,a=4;if(t.action==="run-out"&&n==="bowler-crease"||t.action==="running"){const c=Xo(t,n);if(c){const u=Go(t,n==="bowler-crease"?"batter":"non-striker",c.time).sample.position;o=(Math.min(i[2],r[2],u[2])+Math.max(i[2],r[2],u[2]))/2,a=Math.max(4,Math.abs(r[2]-u[2])*1.8)}}let l=0;if(n==="striker-crease"&&t.action==="wide"){const c=Xo(t,n);if(c){const h=Go(t,"keeper",c.time).sample.position,u=Go(t,"batter",c.time).sample.position,d=Math.min(i[0],r[0],h[0],u[0]),f=Math.max(i[0],r[0],h[0],u[0]),p=Math.min(i[2],r[2],h[2],u[2]),g=Math.max(i[2],r[2],h[2],u[2]);l=(d+f)/2,o=(p+g)/2,a=Math.max(4,Math.hypot(f-d,g-p)*1.8)}}return{target:[l,.42,o],pitch:12,distance:a,fov:44}}if(n==="follow-ball"){const i=t.scene.objects.find(r=>r.id==="camera"&&r.kind==="camera");return{pitch:Math.atan2(3,Math.hypot(5,6))*180/Math.PI,distance:Math.sqrt(70),fov:i?.kind==="camera"&&i.projection==="perspective"?i.fov:48}}const s=n==="field"||n==="overhead"||n==="orbit";return{target:n==="batter"?[.1,.85,9.3]:n==="bowler"?[.68,1,-9.55]:n==="keeper"?[0,.7,10.1]:[0,.65,0],distance:s?t.boundaryRadius*2.8:n==="pitch"?29:4.3,pitch:n==="overhead"?89:s?52:n==="pitch"?16:12,fov:s?48:n==="pitch"?50:46}}function Nh(t,e,n,s){if(t!==void 0&&(!Number.isFinite(t)||t<e||t>n))throw new Error("cricketCamera: "+s+" must be between "+e+" and "+n)}function O4(t,e={}){const n=ge(Uo,e.view??"pitch","cricketCamera.view"),s=e.yaw??Vo[n];if(!Number.isFinite(s))throw new Error("cricketCamera: yaw must be finite");const i=(s%360+360)%360,r=e.zoom??1;if(!Number.isFinite(r)||r<.25||r>4)throw new Error("cricketCamera: zoom must be between 0.25 and 4");const o=g=>r===1?g:Math.atan(Math.tan(g*Math.PI/360)/r)*360/Math.PI,a=e.every??40;if(!Number.isFinite(a)||a<16||a>1e3)throw new Error("cricketCamera: every must be between 16 and 1000 ms");if(Nh(e.pitch,0,89,"pitch"),Nh(e.distance,.5,2e3,"distance"),Nh(e.fov,10,100,"fov"),e.target!==void 0&&(De(e.target,"cricketCamera.target"),n==="follow-ball"))throw new Error("cricketCamera: target override is not supported by follow-ball");const l=r1(t,n),c=e.pitch??l.pitch,h=e.distance??l.distance,u=o(e.fov??l.fov),d=e.target?[...e.target]:l.target??[0,0,0],f=t.scene.id+"/camera",p=g=>{if(e.distance===void 0&&e.target===void 0)return g;const m=g.find(k=>k.property==="position");if(!m||!("keyframes"in m))return g;const y=t.scene.objects.find(k=>k.id==="camera"&&k.kind==="camera");let v=y?.kind==="camera"?Math.max(600,y.far):600;for(const k of m.keyframes)v=Math.max(v,Math.hypot(...k.value)+t.boundaryRadius+10);if(!Number.isFinite(v))throw new Error("cricketCamera: framing exceeds finite camera range");return[...g,{id:f+"-framing-far",target:f,property:"far",keyframes:[{time:0,value:v},{time:t.duration,value:v}]}]};if(n==="follow-ball"){const g=["x","y","z"].map(w=>{const T=t.timeline.tracks.find(S=>S.target===t.scene.id+"/ball"&&S.property===w);if(!T||!("keyframes"in T)||!T.keyframes.length)throw new Error("cricketCamera: missing ball "+w+" keyframes");const A=T.keyframes;let M=0,x=new Xe({...T,keyframes:A.slice(0,2)});return S=>{const E=M;for(;M<A.length-2&&S-(T.delay??0)>A[M+1].time;)M++;return M!==E&&(x=new Xe({...T,keyframes:A.slice(M,M+2)})),x.getValueAtTime(S)}}),m=(Math.atan2(5,6)*180/Math.PI+i-Vo["follow-ball"])*Math.PI/180,y=c*Math.PI/180,v=i===Vo["follow-ball"]&&(e.pitch===void 0||e.pitch===l.pitch)&&(e.distance===void 0||e.distance===l.distance)?[5,3,6]:[Math.sin(m)*Math.cos(y)*h,Math.sin(y)*h,Math.cos(m)*Math.cos(y)*h],k=I4({scene:t.scene.id,camera:"camera",start:0,end:t.duration,every:a,offset:v,subjectAt:w=>g.map(T=>T(w))});return p([...k,{id:f+"-zoom-fov",target:f,property:"fov",keyframes:[{time:0,value:u},{time:t.duration,value:u}]}])}return p($4({scene:t.scene.id,camera:"camera",start:0,end:t.duration,every:a,easing:"linear",from:{target:d,yaw:i,pitch:c,distance:h,fov:u},to:{yaw:n==="orbit"?i+360:i}}))}const Jo=Object.freeze({mcc:Object.freeze({name:"MCC",poppingCreaseHalfWidth:1.83,fieldingRadius:null,summary:"MCC minimum crease markings. The base Laws do not prescribe a limited-over restriction area."}),"icc-men":Object.freeze({name:"ICC men",poppingCreaseHalfWidth:7.5,fieldingRadius:27.43,summary:"ICC men: extended crease markings; ODI/T20 restriction-area arcs have a 27.43 m radius."}),"icc-women":Object.freeze({name:"ICC women",poppingCreaseHalfWidth:7.5,fieldingRadius:23,summary:"ICC women: extended crease markings; ODI/T20 restriction-area arcs have a 23 m radius."})});function C4(t){const[e,n]=t.centres,s=Math.hypot(n[0]-e[0],n[2]-e[2]),i=(n[0]-e[0])/s,r=(n[2]-e[2])/s,o=[];for(let a=0;a<2;a++){const l=a===0?n:e;for(let c=0;c<=64;c++){const h=(a+c/64)*Math.PI,u=Math.cos(h)*t.radius,d=Math.sin(h)*t.radius;o.push([l[0]+r*u+i*d,.018,l[2]-i*u+r*d])}}return o}function o1(t,e){De(e,"cricketFieldingAreaContains.point");const n=t.fieldingArea;if(n==null)return null;if(!Number.isFinite(n.radius)||n.radius<=0)throw new Error("cricketFieldingAreaContains: radius must be positive and finite");if(!Array.isArray(n.centres)||n.centres.length!==2)throw new Error("cricketFieldingAreaContains: two centres are required");const[s,i]=n.centres;De(s,"cricketFieldingAreaContains.centre"),De(i,"cricketFieldingAreaContains.centre");const r=i[0]-s[0],o=i[2]-s[2],a=r*r+o*o,l=a?Math.max(0,Math.min(1,((e[0]-s[0])*r+(e[2]-s[2])*o)/a)):0;return Math.hypot(e[0]-s[0]-l*r,e[2]-s[2]-l*o)<=n.radius+1e-9}function a1(t){return Object.keys(_s).flatMap(e=>{const n=t.scene.objects.find(i=>i.id===e&&i.kind==="character");if(!n)return[];if(n.parent)throw new Error(`cricketFieldingPositions: '${e}' must be unparented for setup markers`);const s=[...n.position??[0,0,0]];return[{id:e,name:n.name??_s[e],position:s,inside:o1(t,s)}]})}function _4(t){return t.fieldingArea?a1(t).map(e=>({id:`fielding-review-${e.id}`,name:`${e.name}: ${e.inside?"inside":"outside"} restriction area`,kind:"line",closed:!0,width:.12,color:e.inside?"#d8eb8a":"#ee9670",points:Array.from({length:32},(n,s)=>[e.position[0]+Math.cos(s*Math.PI/16)*.7,.06,e.position[2]+Math.sin(s*Math.PI/16)*.7])})):[]}const Yt=Object.freeze({length:20.12,width:3.05,poppingCrease:1.22,returnCrease:1.32,stumpHeight:.711,wicketWidth:.2286});function l1(t){if(!t.id?.trim())throw new Error("cricketPlayer: id is required");ge({batter:1,bowler:1,keeper:1,fielder:1,umpire:1},t.role,"cricketPlayer.role");const e=ge(Li,t.preset??"youngMan","cricketPlayer.preset"),n=ge(We,t.format??"t20","cricketPlayer.format"),s=ge({none:1,cap:1,"sun-hat":1},t.headwear??"none","cricketPlayer.headwear"),i=e==="childBoy"||e==="childGirl",r=t.height??(i?1.24:1.78);if(!Number.isFinite(r)||r<.5||r>3)throw new Error("cricketPlayer: height must be between .5 and 3 metres");De(t.position??[0,0,0],"cricketPlayer.position");const o=t.role==="umpire"?"#f5ebd5":n==="test"?"#f5f0df":t.color??"#3577b5",a=JSON.parse(JSON.stringify({...Li[e],...t.appearance,outfit:rm("casual",{top:"shirt",shirt:o,trousers:t.role==="umpire"?"#405058":o,bottom:"trousers",trouserStyle:"plain",sleeves:"short",collar:!0,tie:null,shoes:"boots",shoeColor:"#f3ead7"}),hat:s==="none"?null:{style:s==="sun-hat"?"sunHat":"cap",color:o}}));return{id:t.id,name:t.role,kind:"character",look:"pen",height:r,position:[...t.position??[0,0,0]],character:a,pose:t.role==="batter"?Zy():{turn:t.role==="keeper"?2:0}}}function Zo(t,e,n,s,i=0){return{id:t,kind:"mesh",position:e,geometry:{type:"box",size:n},material:s,layer:i}}function H4(t,e){const n=Yt.stumpHeight,s=(Yt.wicketWidth-.036)/2;return[...[-1,0,1].map((i,r)=>({id:`${t}-stump-${r}`,kind:"mesh",position:[i*s,n/2,e],geometry:{type:"cylinder",radius:.018,height:n,segments:10},material:"wicket"})),...[-1,1].map((i,r)=>Zo(`${t}-bail-${r}`,[i*s/2,n+.015,e],[.105,.025,.035],"bail"))]}function c1(t,e){return[{id:t,kind:"group",scale:e,visible:!1},Zo(`${t}-grip`,[0,.1,0],[.036,.28,.036],"bat-grip"),Zo(`${t}-blade`,[0,.51,0],[.108,.54,.055],"bat-blade"),Zo(`${t}-label`,[0,.41,.029],[.07,.16,.004],"bat-label")].map((s,i)=>i===0?s:{...s,parent:t})}function Wh(t={}){const e=ge(We,t.format??"t20","cricketField.format"),n=ge($h,t.cast??"adults","cricketField.cast"),s=ge(Jo,t.markingProfile??"icc-men","cricketField.markingProfile"),i=Jo[s],r=t.boundaryRadius??64;if(!Number.isFinite(r)||r<24||r>250)throw new Error("cricketField: boundaryRadius must be between 24 and 250 metres");const o=t.id??"cricket";if(!o.trim())throw new Error("cricketField: id is required");const a=Yt.length/2,l=e!=="test"&&i.fieldingRadius!==null?{radius:i.fieldingRadius,centres:[[0,0,-a],[0,0,a]]}:null,c={"striker-wicket":[0,0,a],"bowler-wicket":[0,0,-a],"striker-crease":[0,0,a-Yt.poppingCrease],"bowler-crease":[0,0,-a+Yt.poppingCrease]},h=[{id:"camera",kind:"camera",projection:"perspective",position:[25,9,6],lookAt:[0,.65,0],fov:48,near:.02,far:Math.max(600,r*4)},{id:"sun",kind:"light",light:"directional",position:[4,8,5],intensity:.8,color:"#fff2dd"},{id:"ambient",kind:"light",light:"ambient",intensity:.85,color:"#eaf6f4"},{id:"outfield",kind:"mesh",layer:-4,position:[0,-.04,0],geometry:{type:"cylinder",radius:r+1,height:.06,segments:80},material:"grass"},{id:"square",kind:"mesh",layer:-3,geometry:{type:"plane",size:[8,25]},position:[0,.003,0],material:"square"},{id:"pitch",kind:"mesh",layer:-2,geometry:{type:"plane",size:[Yt.width,Yt.length]},position:[0,.008,0],material:"pitch"},{id:"boundary",kind:"line",layer:-1,closed:!0,width:.15,color:"#f8f2db",points:Array.from({length:96},(p,g)=>[Math.cos(g*Math.PI/48)*r,.022,Math.sin(g*Math.PI/48)*r])}];l&&h.push({id:"fielding-circle",kind:"line",layer:-1,closed:!0,width:.06,color:"#d6e4c8",points:C4(l)});for(const p of[-1,1]){const g=p>0?"striker":"bowler",m=p*a,y=m-p*Yt.poppingCrease;h.push(...H4(g,m));const v=(k,w)=>h.push({id:`${g}-${k}`,kind:"line",layer:-1,color:"#fffdf0",width:.045,points:w});v("popping-line",[[-i.poppingCreaseHalfWidth,.02,y],[i.poppingCreaseHalfWidth,.02,y]]),v("bowling-line",[[-1.32,.02,m],[1.32,.02,m]]);for(const k of[-1,1])v(`return-line-${k<0?"left":"right"}`,[[k*1.32,.02,y],[k*1.32,.02,m+p*2.5]])}const u=[["batter","batter",[-.38,0,9.3]],["non-striker","batter",[-.85,0,-9.3]],["bowler","bowler",[.68,0,-17]],["keeper","keeper",[0,0,11.25]],["fielder","fielder",[12,0,-3]],["slip","fielder",[3.5,0,12]],["point","fielder",[20,0,6]],["cover","fielder",[22,0,-16]],["mid-off","fielder",[9,0,-25]],["mid-on","fielder",[-9,0,-25]],["square-leg","fielder",[-20,0,7]],["fine-leg","fielder",[-20,0,35]],["third-man","fielder",[23,0,35]],["umpire","umpire",[0,0,-12.4]],["square-umpire","umpire",[-15,0,8.84]]];u.forEach(([p,g,m],y)=>{const v=n==="children"||n==="mixed"&&y%3===0,k=n==="men"?"youngMan":v?y%2?"childGirl":"childBoy":y%2?"youngWoman":"youngMan",w=Math.hypot(m[0],m[2]),T=w>r*.88?[m[0]*r*.88/w,0,m[2]*r*.88/w]:[...m];c[p]=[...T];const A=l1({id:p,role:g,preset:k,format:e,position:T,color:g==="batter"?t.battingColor??"#397cb9":t.fieldingColor??"#bf604e"});if(Object.hasOwn(_s,p)&&(A.name=_s[p]),p!=="batter"){const M=p==="non-striker"||p==="bowler"?u[0][2]:u.find(([x])=>x==="bowler")[2];A.pose={turn:Hs(T,M)}}h.push(A)});const d=p=>h.find(g=>g.id===p).height/1.78;h.push(...c1("bat",d("batter")),...c1("non-striker-bat",d("non-striker"))),h.push({id:"ball",kind:"mesh",position:[0,.075,0],geometry:{type:"sphere",radius:.075,segments:12},material:"ball"}),h.push({id:"lbw-guide",kind:"group",visible:!1},{id:"lbw-projection",kind:"line",parent:"lbw-guide",points:[[0,0,0],[0,1,0]],width:.04,color:"#e9ae38"});const f=p=>({color:p,shading:"toon",outline:{color:"#69513a",width:.8}});return{format:e,boundaryRadius:r,landmarks:c,markingProfile:s,fieldingArea:l,scene:{id:o,formatVersion:1,camera:"camera",background:{top:"#c8e5ef",bottom:"#e9efcc"},ground:0,objects:h,materials:{grass:{color:"#81a95c",shading:"unlit"},square:{color:"#a6b76a",shading:"unlit",doubleSided:!0},pitch:{color:"#ddbd85",shading:"unlit",doubleSided:!0},wicket:f("#edd99e"),bail:f("#bd8c4d"),"bat-grip":f("#385b5c"),"bat-blade":f("#e8c58d"),"bat-label":f("#c34d4c"),ball:{color:e==="test"?"#b32d36":"#fff9e7",shading:"toon",outline:{color:"#9b3840",width:1}}}}}}const Kt=1900,Xi=2450,Et=2900,Gi=4100,fn=4200,Fs=4600,Qo=5300,Dh=5500;function ta(t,e,n,s,i,r,o=t.object.pose?.turn??0){const a=_t(e,n,s),l=Qs(i,r),c=Hs(i,r,o),h=o+(c-o)*Lt(_t(e,n,n+200)),u={...lt,...t.object.pose,turn:h},d=io("run",t.who.height,1,t.object.character?.legLength??1),f=so("run",l*a/d,u),p=Math.min(a*12,(1-a)*12,1);return{position:bn(i,r,a),pose:Ko(u,f,Math.max(0,p))}}function Bh(t,e,n){const s=(t.pose.turn??0)*Math.PI/2;return Tt(t.position,[Math.sin(s)*e,n,Math.cos(s)*e])}function R4(t,e,n,s,i){const r=`${e}/${n.object.id}`,o={...lt,...n.object.pose},a=new Set(i.flatMap(l=>Object.keys(l.pose)));for(const l of a){const c=o[l]??0;i.some(h=>h.pose[l]!==c)&&t.push({id:`${n.object.id}-${l}`,target:r,property:l,keyframes:s.map((h,u)=>({time:h,value:i[u].pose[l]??c}))})}for(const[l,c]of["x","y","z"].entries())i.some(h=>h.position[l]!==(n.object.position?.[l]??0))&&t.push({id:`${n.object.id}-${c}`,target:r,property:c,keyframes:s.map((h,u)=>({time:h,value:i[u].position[l]}))});if(i[0].bat){const l=n.object.id==="batter"?"bat":"non-striker-bat",c=`${e}/${l}`;t.push({id:`${l}-visible`,target:c,property:"visible",keyframes:[{time:0,value:1}]}),t.push({id:`${l}-position`,target:c,property:"position",keyframes:s.map((h,u)=>({time:h,value:[...i[u].bat.grip]}))}),t.push({id:`${l}-rotation`,target:c,property:"quaternion",interpolation:"slerp",keyframes:s.map((h,u)=>({time:h,value:t1(i[u].bat.axis)}))})}}function F4(t,e){const n={runs:0,extras:0,wickets:0,legalBall:!0,freeHitNext:!1};t==="running"&&(n.runs=1),t==="four"&&(n.runs=4),t==="six"&&(n.runs=6),(t==="wide"||t==="no-ball")&&(n.extras=1,n.legalBall=!1),t==="no-ball"&&(n.freeHitNext=We[e].freeHitAfterNoBall);const i={catch:"caught",bowled:"bowled",lbw:"lbw",stumping:"stumped","run-out":"run-out"}[t];return i&&(n.wickets=1,n.dismissal=i),n}function h1(t,e={}){return u1(t,e)}function u1(t,e,n){const s=ge(Wn,e.action??"bowling","cricketAction.action"),i=n?n.delivery.legality==="no-ball":s==="no-ball",r=n?n.delivery.legality==="wide":s==="wide",o=n?n.delivery.style==="spin":s==="spin";ge(We,t.format,"cricketAction.format");const a=n?.result??F4(s,t.format),l=e.duration??6e3;if(!Number.isFinite(l)||l<4e3||l>6e4)throw new Error("cricketAction: duration must be between 4000 and 60000 ms");const c=t.scene.id;for(const $ of["ball","bat","non-striker-bat","lbw-guide","striker-bail-0","striker-bail-1","bowler-bail-0","bowler-bail-1"])if(!t.scene.objects.some(C=>C.id===$))throw new Error(`cricketAction: required equipment '${$}' is missing`);const h=Object.fromEntries(["batter","non-striker","bowler","keeper","fielder","umpire"].map($=>[$,Ch(t.scene,$)]));for(const $ of["slip","point","cover","mid-off","mid-on","square-leg","fine-leg","third-man","square-umpire"])t.scene.objects.some(C=>C.id===$&&C.kind==="character")&&(h[$]=Ch(t.scene,$));const u=$=>h[$].who.height,d=$=>Qy(h[$]),f=$=>Math.round($*6e3/l*1e9)/1e9,p=$=>$*l/6e3,g=["batting","defend","running","four","six","catch","fielding","throw","run-out"].includes(s),m=["bowling","spin","no-ball","stumping"].includes(s),y=["catch","fielding","throw","run-out","batting","running"].includes(s),v=s==="running"||s==="run-out",k=new Map,w=[d("bowler").position[0],0,i?-8.25:-9.55],T=s==="fielding"?[10.5,0,2]:[9,0,-1],A=d("fielder").position,M=($,C)=>{let z=k.get($);z||(z=new Map,k.set($,z));const X=z.get(C);if(X)return X;const N=h[$];let L=d($);if($==="bowler"){const D=L.position;if(C<1400){const G=Tt(w,[0,0,-.65]);L=ta(N,C,0,1400,D,G),L.pose["arm.right.swing"]=45,L.pose["arm.right.elbow"]=80}else L.position=C<=Kt?bn(Tt(w,[0,0,-.65]),w,Lt(_t(C,1400,Kt))):Tt(w,[0,0,.8*Lt(_t(C,Kt,2600))]),L.pose=_h(C,[[1400,{turn:0,"arm.right.swing":285,"arm.right.elbow":8,"arm.left.swing":115,"leg.right.swing":15,"leg.left.knee":45}],[1800,{turn:0,"arm.right.swing":180,"arm.right.elbow":0,"arm.left.swing":80,"leg.right.swing":25,"leg.right.knee":0,"leg.left.swing":-25,"leg.left.knee":60}],[Kt,{turn:0,lean:8,"arm.right.swing":155,"arm.right.elbow":0,"arm.left.swing":45,"leg.right.swing":25,"leg.right.knee":0,"leg.left.swing":-25,"leg.left.knee":60}],[2250,{turn:0,lean:26,bend:12,"arm.right.swing":40,"arm.right.elbow":0,"arm.left.swing":-35,"leg.left.swing":-35,"leg.left.knee":55}],[3e3,{turn:0,"head.turn":10}],[6e3,{turn:0,"head.turn":10}]]);o&&(L.pose={...L.pose,"arm.right.spread":18,"head.tilt":-5});for(const[G,q]of Object.entries(C<Kt?St.hold:St.open))L.pose[`hand.right.${G}`]=q}else if($==="batter"||$==="non-striker"){const D=u($);if(s==="lbw"&&$==="batter"&&(L.position[0]=0),s==="stumping"&&$==="batter"&&(L.position[2]-=1.1*Lt(_t(C,2150,2800))),v&&C>3050){const G=M($,3050),q=$==="batter"?[1,0,-9.5]:[-1,0,9.5];L=ta(N,C,3050,s==="run-out"?6e3:Dh,G.position,q,G.pose.turn);const tt=Yi(N,L,"right");L.bat={grip:tt,axis:Jt([.7,-.35,.5]),scale:D/1.78}}else{L.pose={...L.pose,...$==="batter"?Zy():{turn:.15,"leg.left.knee":8,"leg.right.knee":8}};let q=[0,-1,$==="batter"?.05:.12],Z=Tt(L.position,[D*.15,D*.44,D*.04]);if($==="non-striker"&&(Z=Tt(L.position,[D*.08,D*.44,D*.17])),$==="batter"){const tt=Lt(_t(C,2100,2600))*(1-Lt(_t(C,2600,Et))),R=Lt(_t(C,2600,Et))*(1-Lt(_t(C,Et,3800))),U=Lt(_t(C,Et,3250))*(1-Lt(_t(C,3250,4e3)));if(g){Z=Tt(L.position,[D*(.15+.03*tt-.02*R-.03*U),D*(.44+.14*tt+.07*R+.23*U),D*(.04+.16*tt-.12*R-.06*U)]),q=Jt([.15*tt+.25*U,-1+1.85*tt+1.6*U,.05+.55*tt-.4*R-.8*U]),L.pose.turn=1+.12*R+.3*U,L.pose.lean=3+4*R;const nt=12+4*R;L.pose["leg.left.spread"]=nt,L.pose["leg.right.spread"]=nt,s==="defend"&&(q=[0,-1,-.08],Z=Tt(L.position,[D*.1,D*.5,-D*.12]))}else if(["stumping","bowled","lbw"].includes(s)){const nt=Lt(_t(C,2100,2700))*(1-Lt(_t(C,4e3,4500)));q=Jt([.15*nt,-1+1.85*nt,.05+.55*nt]),Z=Tt(L.position,[D*(.15+.03*nt),D*(.44+.14*nt),D*(.04+.16*nt)])}}L=x4(N,L,Z,q)}}else if($==="keeper"){L.pose={...L.pose,turn:Hs(L.position,d("bowler").position,2),lean:20,"leg.left.swing":22,"leg.right.swing":22,"leg.left.knee":50,"leg.right.knee":50},r&&(L.position[0]=2.15*Lt(_t(C,2900,3500))),s==="stumping"&&(L.position[2]-=.85*Lt(_t(C,3400,3900)));const D=Bh(L,u($)*.27,u($)*.44);if(s==="stumping"&&C>=3500){const G=Bh({...L,position:d($).position},u($)*.27,u($)*.44),q=[0,Yt.stumpHeight,Yt.length/2],Z=bn(G,q,Lt(_t(C,3500,3900)));L=dn(N,L,"right",Z),L=dn(N,L,"left",Tt(Z,[.045,0,0]))}else L=dn(N,L,"right",D),L=dn(N,L,"left",Tt(D,[.045,0,0]))}else if($==="fielder"&&y){if(L=ta(N,C,3050,s==="catch"?3800:3950,A,T),C>=3800){const D={...lt,turn:Hs(T,d("batter").position,L.pose.turn),lean:s==="catch"?5:42,bend:s==="catch"?0:18,"leg.left.swing":s==="catch"?0:45,"leg.right.swing":s==="catch"?0:45,"leg.left.knee":s==="catch"?0:85,"leg.right.knee":s==="catch"?0:85,smile:.7};L.pose=Ko(L.pose,D,Lt(_t(C,3800,fn)));const G=Bh(L,u($)*.22,u($)*(s==="catch"?.73:.2));if(L=dn(N,L,"right",G),L=dn(N,L,"left",Tt(G,[.035,0,0])),(s==="throw"||s==="run-out")&&C>fn){const q={...lt,turn:Hs(T,s==="throw"?d("keeper").position:t.landmarks["bowler-wicket"],L.pose.turn),"arm.right.swing":225,"arm.right.elbow":60,"arm.left.spread":70,"leg.left.swing":15},Z={...q,"arm.right.swing":110,"arm.right.elbow":0,lean:15};L.pose=_h(C,[[fn,L.pose],[4450,q],[Fs,Z],[4900,{...lt,turn:q.turn,"arm.right.swing":25,lean:22}],[6e3,{...lt,turn:q.turn}]])}}}else if($==="umpire"){let D={...lt};const G=s==="stumping"?4150:s==="run-out"?5150:s==="bowled"||s==="lbw"?3500:s==="catch"?4350:5100;if(s==="no-ball")D={...D,"arm.right.spread":90,"arm.right.elbow":0};else if(s==="wide")D={...D,"arm.right.spread":90,"arm.left.spread":90,"arm.right.elbow":0,"arm.left.elbow":0};else if(s==="six")D={...D,"arm.right.spread":180,"arm.left.spread":180,"arm.right.elbow":0,"arm.left.elbow":0};else if(s==="four")D={...D,"arm.right.spread":90-70*(.5+Math.sin((C-5100)/180)*.5),"arm.right.elbow":12};else if(["catch","bowled","lbw","stumping","run-out"].includes(s)){D={...D,"arm.right.swing":165,"arm.right.elbow":0};for(const[q,Z]of Object.entries(St.point))D[`hand.right.${q}`]=Z}if(n){const q={...lt},Z=[[0,q]];let tt=q;if(i||r){const R=i?Kt:3100;tt=i?{...q,"arm.right.spread":90,"arm.right.elbow":0}:{...q,"arm.right.spread":90,"arm.left.spread":90,"arm.right.elbow":0,"arm.left.elbow":0},Z.push([R,q],[R+350,tt])}if(a.wickets||s==="four"||s==="six"){const R=a.wickets?G:5100;let U=D;if(a.wickets){U={...q,"arm.right.swing":165,"arm.right.elbow":0};for(const[nt,at]of Object.entries(St.point))U[`hand.right.${nt}`]=at}Z.push([R,tt],[R+350,U])}L.pose=_h(C,Z)}else L.pose=Ko(L.pose,D,Lt(_t(C,s==="no-ball"?Kt:s==="wide"?3100:G,(s==="no-ball"?Kt:s==="wide"?3100:G)+350)))}return z.set(C,L),L},x=($,C)=>Yi(h[$],M($,C),"right"),S=g?T4(M("batter",Et).bat):s==="lbw"?bn(Rs(h.batter,M("batter",Et),"leg.right",1),Rs(h.batter,M("batter",Et),"leg.right",2),.6):[m?Yt.wicketWidth/2+.075+.15:0,.45,9.25],E=x("bowler",Kt),P=[r?.85:o?-.35:s==="lbw"?S[0]*.6:0,.075,3.9],I=x("keeper",s==="stumping"?3400:3500),O=x("fielder",Gi),H=x("fielder",fn),W=s==="run-out"?"bowler":"striker",j=s==="run-out"?5e3:s==="stumping"?3900:3200,J=[t.boundaryRadius*.8,s==="six"?2.1:.075,-t.boundaryRadius*.6],et=($,C,z,X,N,L=0,D=0)=>Hh({target:`${c}/ball`,start:C,end:z,from:X,to:N,arc:L,curve:D},$),V=$=>{if($<=Kt)return x("bowler",$);if($<=Xi)return et($,Kt,Xi,E,P,.15,o?.35:0);const C=r?Tt(I,[0,0,-.6]):S;if($<=Et)return et($,Xi,Et,P,C,.08);if(s==="bowled"){const X=[0,.36,Yt.length/2];return $<=j?et($,Et,j,S,X):et($,j,4100,X,[0,.075,12.5],.2)}if(s==="lbw")return[...S];if(["bowling","spin","no-ball","wide","stumping"].includes(s)){const X=s==="stumping"?3400:3500;if(m&&$<=X){const N=[C[0],I[1],Yt.length/2+.2];return $<=3200?et($,Et,3200,C,N,.04):et($,3200,X,N,I,.04)}return $<=X?et($,Et,X,C,I,.04):x("keeper",$)}if(s==="defend")return et($,Et,3400,S,Tt(S,[-.5,-S[1]+.075,-.7]),.12);if(s==="four"||s==="six"){if(s==="six")return $<=5e3?et($,Et,5e3,S,J,12):et($,5e3,5700,J,Tt(J,[2,-2.025,-1.5]));const X=[5,.075,5];return $<=3300?et($,Et,3300,S,X,.5):et($,3300,5e3,X,J)}if(s==="catch")return $<=Gi?et($,Et,Gi,S,O,5):x("fielder",$);const z=[4,.075,5];if($<=3300)return et($,Et,3300,S,z,.8);if($<=fn)return et($,3300,fn,z,H);if(s==="throw"||s==="run-out"){if($<=Fs)return x("fielder",$);const X=x("fielder",Fs),N=s==="run-out"?[0,.42,-Yt.length/2]:x("keeper",Qo),L=s==="run-out"?j:Qo;return $<=L?et($,Fs,L,X,N,1.2):s==="run-out"?et($,L,5700,N,[0,.075,-12],.18):x("keeper",$)}return[...H]},F=[],B=($,C,z,X,N)=>F.push({id:$,time:p(C),kind:z,label:X,caption:N}),K=n?{bowled:"Delivery hits stumps",lbw:"Pad contact",stumping:"Keeper breaks wicket","run-out":"Throw breaks wicket"}[s]??Wn[s].name:Wn[s].name;if(B("setup",0,"setup",K,n?`${n.delivery.style} delivery · ${n.delivery.legality}${n.freeHit?" · free hit":""}. ${Wn[s].summary.replace("A legal delivery","A delivery")}`:Wn[s].summary),B("release",Kt,"release","Ball released",i?"The front foot has landed beyond the popping crease. No-ball.":"The bowler releases the ball; the front foot is behind the popping crease."),B("bounce",Xi,"bounce","Pitch bounce",o?"The curved flight is illustrative. Spin can change the ball’s path after it bounces.":"The delivery bounces on the pitch on its way to the striker."),g?B("contact",Et,"contact","Bat contact","The ball meets the blade. The bat is keyed from the same two hand grips."):s==="lbw"?B("pad-contact",Et,"contact","Pad contact",n?"The ball contacts the pad. The highlighted path is illustrative; the authored decision is resolved separately.":"The highlighted path illustrates a ball that would hit the stumps. This is an authored LBW example."):B("miss",Et,"contact",s==="wide"?"Beyond normal reach":"The batter misses",s==="wide"?"The untouched ball is too far away for a normal stroke. The umpire calls Wide.":"The untouched delivery passes the striker."),s==="catch"&&B("catch",Gi,"collect","Catch controlled",n?"The fielder controls the ball before it touches the ground. The authored decision is resolved separately.":"The fielder controls the ball before it touches the ground: caught."),["fielding","throw","run-out","batting","running"].includes(s)&&B("gather",fn,"collect","Ground ball gathered","The ball has touched the ground. Gathering it is fielding, not a catch dismissal."),["bowling","spin","wide","no-ball","stumping"].includes(s)&&B("keeper",s==="stumping"?3400:3500,"collect","Keeper gathers","The keeper controls the ball behind the striker’s wicket."),(s==="throw"||s==="run-out")&&B("throw",Fs,"throw","Throw released","The fielder releases the gathered ball toward the wicket."),s==="throw"&&B("return",Qo,"collect","Return received","The keeper receives and controls the return throw."),s==="stumping"&&B("wicket",j,"wicket",n?"Wicket broken":"Stumped","Holding the ball, the keeper removes a bail. The striker is out of ground and is not attempting a run."),s==="run-out"&&B("wicket",j,"wicket",n?"Wicket broken":"Run out","The direct throw removes a bail before the running batter makes this ground."),s==="bowled"&&B("wicket",j,"wicket",n?"Stumps hit":"Bowled",n?"The delivery hits the wicket and removes a bail. A broken wicket does not by itself decide a dismissal.":"The legal delivery hits the wicket and removes a bail."),(s==="four"||s==="six")&&B("boundary",5e3,"boundary",s==="four"?"Four runs":"Six runs",s==="four"?"The struck ball reaches the boundary after touching the ground: four.":"The struck ball clears the boundary without touching the ground: six."),s==="running"&&B("run",Dh,"result","One run completed","Both batters have reached the opposite ground. One run is completed."),B("result",5700,"result","Illustrated result",s==="no-ball"?`One no-ball extra; it does not count in the over.${a.freeHitNext?" The next legitimate delivery is a free hit.":" Test cricket has no automatic free hit."}`:s==="wide"?"One wide extra; the delivery does not count in the over.":s==="lbw"?"LBW is declared for this illustrated legal delivery. A full decision also checks pitching, impact and any bat contact.":`${a.runs} bat runs · ${a.extras} extras · ${a.wickets} wicket${a.wickets===1?"":"s"}.`),n){const $={"no-dismissal":"No dismissal was authored for this play.",dismissal:`The authored ${n.ruling.dismissal} decision is allowed in this delivery context.`,"no-ball":`Not out: ${s==="catch"?"a catch":"this dismissal"} cannot dismiss the striker on a no-ball.`,"free-hit":`Not out: ${s==="catch"?"a catch":"this dismissal"} cannot dismiss the striker on a free hit.`,wide:"Not out: this dismissal is not available from a Wide."},C=F.find(z=>z.id==="result");C.label=a.wickets?"Out":"Not out",C.caption=`${$[n.ruling.reason]} ${a.runs} bat runs · ${a.extras} extras · ${a.wickets} wickets. ${a.legalBall?"Counts as a legal ball.":"Does not count in the over."}${a.freeHitNext?" The next delivery is a free hit; an illegal delivery carries it forward.":n.freeHit?" This legal delivery consumes the free hit.":""}`}F.sort(($,C)=>$.time-C.time);const _=e1(0,l,e.every,[1400,1800,Kt,2100,2150,2250,Xi,2600,2800,Et,3050,3100,3200,3250,3300,3400,3500,3800,3900,3950,4e3,Gi,fn,4350,4450,Fs,4900,5e3,5100,5150,Qo,Dh,5700].map(p)),Y=_.map($=>V(f($))),st=[];for(const[$,C]of Object.entries(h)){let z=C.object.pose?.turn??0,X=z;const N=_.map((L,D)=>{const G=f(L);let q=$==="fielder"&&y&&G>3050&&G<3250?ta(C,G,3050,s==="catch"?3800:3950,A,T,X):M($,G),Z=Y[D];const tt=!["batter","non-striker","bowler","keeper"].includes($);if(tt){const U=M("bowler",Math.min(G,Kt)),nt=Tt(U.position,[0,u("bowler")*.8,0]);Z=G<=Kt?nt:G<2100?bn(nt,Z,Lt(_t(G,Kt,2100))):Z}if(v&&($==="batter"||$==="non-striker")&&G>3050&&(Z=$==="batter"?[1,u($)*.8,-10.5]:[-1,u($)*.8,10.5]),$==="bowler"&&G<=Et&&(Z=Tt(M("batter",G).position,[0,u("batter")*.65,0])),tt&&($!=="fielder"||!y||G<=3050)||$==="bowler"&&G>=3e3){const U=Hs(q.position,Z,z);z=$==="bowler"&&G<3500?(q.pose.turn??0)+(Oh(U,q.pose.turn??0)-(q.pose.turn??0))*Lt(_t(G,3e3,3500)):U,q={...q,pose:{...q.pose,turn:z}}}return $==="fielder"&&y&&(G===3050?X=z:G>3050&&(z=Oh(q.pose.turn??0,z),q={...q,pose:{...q.pose,turn:z}})),S4(C,q,Z)});R4(st,c,C,_,N)}for(const[$,C]of["x","y","z"].entries())st.push({id:`ball-${C}`,target:`${c}/ball`,property:C,keyframes:_.map((z,X)=>({time:z,value:Y[X][$]}))});if(["bowled","stumping","run-out"].includes(s))for(let $=0;$<2;$++){const C=`${W}-bail-${$}`,X=t.scene.objects.find(N=>N.id===C).position;st.push({id:`${C}-fall`,target:`${c}/${C}`,property:"position",keyframes:[{time:0,value:[...X]},{time:p(j),value:[...X]},{time:p(j+180),value:Tt(X,[$?.25:-.25,.22,W==="striker"?.22:-.22]),easing:"ease-out"},{time:p(j+650),value:[X[0]+($?.4:-.4),.035,X[2]+(W==="striker"?.45:-.45)],easing:"ease-in"}]}),st.push({id:`${C}-spin`,target:`${c}/${C}`,property:"rotateZ",keyframes:[{time:0,value:0},{time:p(j),value:0},{time:p(j+650),value:$?145:-145}]})}if(s==="lbw"){const $=[S[0]*.8,S[1],Yt.length/2],C=se($,S);st.push({id:"lbw-position",target:`${c}/lbw-guide`,property:"position",keyframes:[{time:0,value:[...S]}]},{id:"lbw-rotation",target:`${c}/lbw-guide`,property:"quaternion",interpolation:"slerp",keyframes:[{time:0,value:t1(C)}]},{id:"lbw-length",target:`${c}/lbw-guide`,property:"scaleY",keyframes:[{time:0,value:Qs(S,$)}]},{id:"lbw-visible",target:`${c}/lbw-guide`,property:"visible",keyframes:[{time:0,value:0},{time:p(Et)-.001,value:0},{time:p(Et),value:1}]})}return{action:s,duration:l,events:F,result:a,timeline:{id:`${c}-${s}`,formatVersion:2,name:K,config:{duration:l,markers:F.map($=>({id:$.id,time:$.time,label:$.label}))},captions:{en:Object.fromEntries(F.map($=>[$.id,$.caption]))},tracks:st}}}function L4(t={}){const e=Wh(t);return{...e,...h1(e,t)}}function N4(t,e){if(!Number.isFinite(e))throw new Error("cricketEventAt: time must be finite");let n;for(const s of t){if(s.time>e)break;n=s}return n}const gn=Object.freeze({deliveryStyles:Object.freeze(["pace","spin"]),deliveryLegalities:Object.freeze(["legal","no-ball","wide"]),shots:Object.freeze(["miss","drive","defend"]),finishes:Object.freeze(["none","single","four","six","stumps","pad"]),fielding:Object.freeze(["none","keeper","catch","gather","throw","stumping","run-out"]),dismissals:Object.freeze(["caught","bowled","lbw","stumped","run-out"])});function Ls(t,e,n){if(!t.includes(e))throw new Error(`cricketPlay.${n}: unknown choice '${e}'`);return e}function W4(t){const{shot:e,finish:n,fielding:s}=t;if(t.delivery.legality==="wide"){if(e!=="miss"||n!=="none"||s!=="keeper")throw new Error("cricketPlay: Wide currently supports only an untouched delivery gathered by the keeper");return"wide"}if(e==="miss"){if(s==="none"&&n==="stumps")return"bowled";if(s==="none"&&n==="pad")return"lbw";if(n==="none"&&s==="stumping")return"stumping";if(n==="none"&&s==="keeper")return t.delivery.style==="spin"?"spin":"bowling"}if(e==="defend"&&n==="none"&&s==="none")return"defend";if(e==="drive"){if(s==="none"&&(n==="four"||n==="six"))return n;if(s==="gather"&&n==="single")return"running";if(n==="none"){if(s==="catch")return"catch";if(s==="gather")return"fielding";if(s==="throw")return"throw";if(s==="run-out")return"run-out"}}throw new Error(`cricketPlay: unsupported motion combination (${e}, ${n}, ${s})`)}function D4(t){const e=Ls(gn.shots,t.shot??"miss","shot"),n=Ls(gn.finishes,t.finish??"none","finish");let s=e==="miss"?"keeper":"gather";(e==="defend"||n!=="none")&&(s=n==="single"?"gather":"none");const i=Ls(gn.fielding,t.fielding??s,"fielding"),r=t.context?.freeHit??!1;if(typeof r!="boolean")throw new Error("cricketPlay.context.freeHit must be boolean");const o=t.decision?.dismissal??null;return o!==null&&Ls(gn.dismissals,o,"decision.dismissal"),{delivery:{style:Ls(gn.deliveryStyles,t.delivery?.style??"pace","delivery.style"),legality:Ls(gn.deliveryLegalities,t.delivery?.legality??"legal","delivery.legality")},shot:e,finish:n,fielding:i,context:{freeHit:r},decision:{dismissal:o}}}function B4(t,e){const n=t.decision.dismissal;if(!n)return{dismissal:null,reason:"no-dismissal"};if({catch:"caught",bowled:"bowled",lbw:"lbw",stumping:"stumped","run-out":"run-out"}[e]!==n)throw new Error(`cricketPlay: '${n}' decision does not match '${e}' motion`);if(n!=="run-out"){if(t.context.freeHit)return{dismissal:null,reason:"free-hit"};if(t.delivery.legality==="no-ball")return{dismissal:null,reason:"no-ball"};if(t.delivery.legality==="wide"&&n!=="stumped")return{dismissal:null,reason:"wide"}}return{dismissal:n,reason:"dismissal"}}function d1(t,e={}){const n=ge(We,t.format,"cricketPlay.format"),s=D4(e);if(s.context.freeHit&&!We[n].freeHitAfterNoBall)throw new Error("cricketPlay: Test format does not support free-hit context");const i=W4(s),r=B4(s,i),o=s.delivery.legality==="legal",a={runs:s.finish==="single"?1:s.finish==="four"?4:s.finish==="six"?6:0,extras:o?0:1,wickets:r.dismissal?1:0,legalBall:o,freeHitNext:We[n].freeHitAfterNoBall&&(s.delivery.legality==="no-ball"||s.context.freeHit&&!o),...r.dismissal?{dismissal:r.dismissal}:{}};return{...u1(t,{action:i,duration:e.duration,every:e.every},{delivery:s.delivery,result:a,ruling:r,freeHit:s.context.freeHit}),play:s,ruling:r}}function z4(t={}){const e=Wh(t);return{...e,...d1(e,t)}}const f1=Object.freeze({"no-ball-stumps":Object.freeze({name:"No-ball + stumps hit",options:Object.freeze({delivery:Object.freeze({legality:"no-ball"}),finish:"stumps",decision:Object.freeze({dismissal:"bowled"})})}),"free-hit-catch":Object.freeze({name:"Free hit + catch",options:Object.freeze({context:Object.freeze({freeHit:!0}),shot:"drive",fielding:"catch",decision:Object.freeze({dismissal:"caught"})})}),"no-ball-four":Object.freeze({name:"No-ball + four",options:Object.freeze({delivery:Object.freeze({legality:"no-ball"}),shot:"drive",finish:"four"})}),"free-hit-run-out":Object.freeze({name:"Free hit + run-out",options:Object.freeze({context:Object.freeze({freeHit:!0}),shot:"drive",fielding:"run-out",decision:Object.freeze({dismissal:"run-out"})})}),"free-hit-wide":Object.freeze({name:"Free hit + Wide",options:Object.freeze({context:Object.freeze({freeHit:!0}),delivery:Object.freeze({legality:"wide"})})})}),q4={linear:!0,"ease-in":!0,"ease-out":!0,"ease-in-out":!0,"ease-in-quad":!0,"ease-out-quad":!0,"ease-in-out-quad":!0,"ease-in-cubic":!0,"ease-out-cubic":!0,"ease-in-out-cubic":!0};function g1(t,e={}){const n={};for(const s of Object.keys(Xt))n[s]={summary:`Walks to \`to\` in the ${s} gait.`,needs:["to"]};for(const s of Object.keys(ae))n[s]={summary:`Moves into the ${s} pose and holds it (\`for\` ms).`};for(const s of Object.keys(on))n[s]={summary:`The ${s} gag (${Wi(s)} ms).`};for(const[s,i]of Object.entries(Di))n[s]={...i};return{sports:{cricket:{actions:{...Wn},formats:{...We},casts:{...$h},fieldingPositions:{..._s},markingProfiles:{...Jo},cameras:{...Uo},decisionCameras:Ki,playComponents:gn,playExamples:f1}},...t?{version:t}:{},timing:"JSON timelines and tracks are in milliseconds; the GSAP-style API (live.to, tf.timeline) takes seconds. Scene x grows right, y grows down, in px.",easings:{named:Object.keys(q4),parametric:{"cubic-bezier":'{ type: "cubic-bezier", points: [x1, y1, x2, y2] }',steps:'{ type: "steps", count, position?: start | end | none | both }',elastic:'{ type: "elastic", mode?: in | out | in-out, amplitude?, period? }',bounce:'{ type: "bounce", mode?: in | out | in-out }',back:'{ type: "back", mode?: in | out | in-out, overshoot? }'}},trackKinds:{keyframe:"{ id, target, property, keyframes: [{ time, value, easing? }] }: values between keys are interpolated (numbers, colours, paths)",spring:'{ id, target, property, kind: "spring", spring: { from, to, stiffness?, damping?, mass?, velocity? }, delay? }: physics settle',inertia:'{ id, target, property, kind: "inertia", inertia: { from, velocity, friction?, min?, max?, end? }, delay? }: a flick that slows (end snaps to a value or the nearest of a list)',motionPath:'{ property: "motionPath", path, align? }: moves along an SVG path',text:'{ property: "text", … }: types or scrambles text'},canvasProperties:Lo,stickFigure:{poseFields:pd,props:md,handFields:yd,poses:Object.keys(ae),expressions:Object.keys(vt),gags:Object.fromEntries(Object.keys(on).map(s=>[s,Wi(s)])),gaits:Object.keys(Xt),actingStyles:Object.keys(Fn),beatFields:Oo,actions:n,dances:Object.fromEntries(Object.entries(Ze).map(([s,i])=>[s,Object.keys(i.moves)])),flips:Object.fromEntries(Object.entries(Pi).map(([s,i])=>[s,i.label])),handShapes:Object.keys(St),mudras:Object.keys(Hr)},props:{api:{"car() · truck() · bus() · tractor() · cart() · trainCar() · bike() · motorbike()":"wheeled vehicles (vehicle(spec) makes your own)","tree() · house()":"environment (tree(spec), house(spec))","helicopter() · airplane()":"aircraft","horse() · dog() · cat() · cow()":"animals (quadruped(spec) makes your own): gaits with footfall patterns keyed in step with the distance, sit, jump, their calls, species actions","songbird() · crow() · chicken()":"birds (bird(spec) makes your own): hop, walk, peck, flap, fly and land (a chicken flutters), their calls; wings fold and beat in rhythm","{ kind: 'prop', prop: 'car', position, rotation, values } with loadScene3D(scene, { kinds: [characterObjects, propObjects] })":"props in 3D scenes, by preset name, seen in perspective by the scene camera; controls are tracks on the object","characterScript3D(id, beats, { scene, position?, heading?, height?, pose? })":"a v2 character in world metres: gaits, face (shortest turn), spin (signed turns and duration), dance (native style, bpm, beats), hold, pose, gag; checkCharacterBeats3D checks the beats","propRide3D({ prop, propId, propTracks, scene, placement, anchor, riderId, pose, start, end, mount?, dismount? })":"a character riding a prop in a 3D scene: hips on a seat anchor (saddle, seat) as it moves, hopping on and off; RIDING_POSES.astride / .seated / .driving / .cycling / .wheeling (a wheelchair)","propScript3D(id, prop, beats, { scene, position?, heading?, values? })":"props scripted in world metres for 3D scenes: moves to [x, z] or through points (wheels and strides keyed with the distance), face, hold, and their actions; checkPropBeats3D checks the beats","propPreset(name, options?)":"a prop preset by name (did-you-mean on a wrong one)","propTarget({ …, style: 'stick' })":"line art to go with stick figures: tubes as single strokes, shapes outlined over paper","propTow({ leader, leaderId, leaderTracks, hitch, towed, towedId, anchor, start, end })":"a prop towed by another (a cart behind a horse): turns with it, its wheels roll exactly","propTarget({ x, y, prop, scale?, values?, look?, ink? })":"a canvas target that draws a prop (x, y: its middle on the ground; scale px per metre, default 60)","propScript(id, prop, beats, { from, ground, scale, style?, exaggeration?, start? })":"beats → acted tracks, with contact times and effect cues; checkPropBeats(beats, prop) checks them","drawProp(ctx, target, frame, id, { rider? })":"draw it as it is in a frame (a rider is drawn between its far and near parts)","propAt(target, frame, id).anchor(name)":"where an anchor (seat, door, chimney…) is, in scene px","propRide({ prop, propId, propTracks, anchor, figure, figureId, start, end, offset? })":"a figure carried at an anchor, turning with the prop; spliceTracks() puts it into the figure’s tracks","drawPropEffects(ctx, effects, time)":"dust, exhaust, skid marks, honk lines, leaves, smoke"},beatFields:jo,commonControls:Object.fromEntries(Object.entries(Ps).map(([s,i])=>[s,`${i.description}${i.unit?` (${i.unit})`:""}`])),commonActions:Object.fromEntries(Object.entries(Ah).map(([s,i])=>[s,i.summary])),presets:Object.fromEntries(Object.entries(Cs).map(([s,i])=>{const r=i();return[s,{family:r.family,summary:r.summary,actions:Object.fromEntries(Object.entries(r.actions).map(([o,a])=>[o,{summary:a.summary,...a.needs?{needs:a.needs}:{}}])),controls:Object.keys(r.rig.controls),anchors:Object.keys(r.rig.anchors??{})}]}))},custom:{api:{"defineAction({ summary, needs?, steps: (from, beat) => [{ after, pose, easing? }] })":"a new action written as timed pose steps from the current pose, like a gag","defineAction({ summary, needs?, beats: (beat) => [beats] })":"a new action built from other beats (which may be custom too)","defineGait({ swing, knee, arm, elbow, lean, cycle?, … })":"a new gait (the Gait fields in degrees; cycle is ms per two steps)","scriptTracks(id, beats, { actions, gaits })":"beats may then use those names; checkBeats(beats, { actions, gaits }) knows them","stickFigureTarget({ …, cast: { actions, gaits } })":"a figure that draws the gaits and lists the actions in describeTarget","persona({ name, summary?, height?, look?, acting?, gait?, mood?, stance?, energy?, actions?, gaits? })":"a character’s look, acting style and habits: .figure({ x, y }), .script(id, beats, { from, ground }), .check(beats), .handPath(…), .describe(); `go` walks in its gait, `stand` returns to its stance and face"},actions:Object.fromEntries(Object.entries(e.actions??{}).map(([s,i])=>[s,{summary:i.summary,...i.needs?{needs:i.needs}:{}}])),gaits:Object.fromEntries(Object.entries(e.gaits??{}).map(([s,i])=>[s,i.summary??"custom gait"]))},character:{figureStyles:["fluid","stick","organic"],body:{"body.torso · body.arm · body.leg · body.neck":"Organic half-width profiles: [{ at: 0..1, width: fractionOfHeight }], increasing from 0 to 1; independent of ink width.","body.measurements":`Organic torso from tape-measure girths { height, bust, underbust?, waist, hip } in any one unit, or a named shape (${Object.keys(Gr).join(" | ")}). Sets the front width, the side depth (bust forward, seat back, belly) and the hip and thigh spacing; reads correctly at every turn. An explicit torso / torsoFront / torsoBack / hipWidth still wins.`,"body.torsoFront · body.torsoBack":"Organic side-view depth from the spine line toward the chest/belly and toward the back/seat, same profile format; default torso × depth.","body.fill · body.outline · body.shading":"Shared skin fill, outline { color, width }, cel material { mode: cel | none, light: [x,y], shadow, opacity, highlight }.","softCartoonCharacter(name, options?)":"Original youngMan / youngWoman / childBoy / childGirl story presets. Children have larger head proportions, shorter limbs and rounded torsos; every face, hair, build, hand, clothing and material option can be overridden.","face.projection":"Organic default volume follows the head axes, keeps both eyes in three-quarter views and projects a small nose above the mouth; opaque hair covers features. cartoon keeps the classic face slide.","outfitPreset(category, overrides?)":"Fresh JSON Everyday / Formal / Casual wardrobe defaults for every actor; top: tshirt | shirt | blouse | dress, trouserStyle: plain | jeans | cargo, colours, sleeves, bottoms, collar and tie are editable.",leafOutfit:"Organic-only JSON garment { top?, color?, accent?, length? }; curved leaves follow torso/thighs at native part depths. Everyday basicOutfit also follows organic contours."},poses:Object.keys(be),dances:Object.keys(An),expressions:Object.keys(Il),faceStyles:["simple","anime"],faceShapes:["round","angular"],gags:Object.keys(ro),builds:Object.keys(Dr),hair:Object.keys(Vl),hairColors:{...Ae},facialHair:Object.keys(ec),glasses:Object.keys(sc),hats:Object.keys(no),feet:[...vf],cast:Object.keys(jc),heldItems:Object.fromEntries(Object.entries(ac).map(([s,i])=>[s,i.hands])),handMeetings:Object.keys(Ni)},codePanel:{languages:Ao,removeStyles:To,anchors:{"line(n, time?)":"line n’s text box { x, y, left, right, top, bottom, width, height }: stand on top, point at x, y","token(n, text, occurrence?, time?)":"a word on a line","spot(n, column, width?, time?)":"a place in a line, for put and write","landing(piece, n, column)":"where a dropped piece will land",box:"the whole panel"},edits:Nc},surfaces:{code:Hi,board:Re,chart:Hn,prop:Is},surfaceScript:{"surfaceScript(figureId, { name: surface }, beats, options)":"compiles beats that act on surfaces: returns the script result with `tracks` (the figure’s, ridden, then every surface’s, keyed by its name) and `figureTracks`; options are scriptTracks’ plus `figureStyle` (for carry) and `ride` (default true)","checkSurfaceBeats(beats, surfaces, cast?)":"every problem checkBeats finds, plus unknown surfaces, places, edits and moments, with suggestions","{ surface, anchor }":"a named place, where a beat takes `target` (its box), `to` (its centre x) or `onto` (its top); as laid out, before any edit moves it","then: { surface, edit, anchor, at?, until?, …options }":"what the surface does in answer to the beat (or a list of them): one of its edits, or `carry` (the piece follows the hand until `until`); the other fields are the edit’s options",at:`a moment of the beat: ${Es.join(", ")} (default contact, or start when the beat has none); not ms`,until:"a moment of this beat, or { beat: index, at? } of a later one; sets the edit’s duration (carry needs it)"},cameraShots:{frame:"{ at, duration?, easing?, frame: { focus?: { x, y }, scale?, rotate? } }: push in, pull out, or cut (duration 0)",shake:"{ at, duration, shake: { strength?, frequency?, roll?, seed? } }",follow:"{ at, until, follow: { x: <the subject’s x keyframes>, lead?, y?, lag?, scale? } }: keeps a subject centred"},teach:{"lesson({ id })":"steps as timeline JSON: to, set, together, wait, marker (with pause, question, captions)","cells, pointer, stack, queue, table, pipeline":"diagram primitives (SVG markup + step helpers)","figure({ width, height, children })":"the SVG holding the pieces"},math:{api:{"mathFigure(spec)":"checks a figure (JSON: width, height, x?, y?, theme?: dark | light | chalk, values, items) and says how to fix it","layoutFigure(spec, props)":"the figure at some values as shapes; drawDisplayList(ctx, list) or displayListToSvg(list) draws them","mathTarget(spec, { x, y })":"a canvas target for videos and canvas pages; tracks animate its values and item props","mathSteps(lesson, target, spec, { hidden })":"lesson steps: toValue, applyMatrix, drawOn, fadeIn, fadeOut, showStep (equations)","mountMath(element) / mountAllMath()":"lesson-page embeds: <figure data-tinyfly-math> with data-tinyfly-figure and data-tinyfly-timeline JSON scripts, stepped like any embed","mathExplorable(element, spec, { sliders, drag })":"reader-driven figures: sliders on number values, drag vector tips or matrix columns","mathFigureToSvg(spec, props)":"a standalone SVG of a figure at some values","linearMapFigure, determinantFigure, eigenFigure, vectorSumFigure, spanFigure":"ready linear algebra figures; the matrix is the value M","tangentFigure, secantFigure, riemannFigure, areaFigure, taylorFigure, limitFigure":"ready calculus figures; their moving parts are number values (a, h, n, b, order, p)","differentiate / compileDerivative / integrate":"exact symbolic derivatives of expressions; Simpson integration","normalFigure, binomialFigure, cltFigure, galtonFigure, monteCarloPiFigure, regressionFigure, bayesFigure":"ready probability and statistics figures","graphSearchFigure, shortestPathFigure, recursionTreeFigure, vennFigure, clockFigure":"ready discrete maths figures; searches move with the value step","searchEvents / parseSetExpression / regionCells":"graph searches as data; set expressions and their Venn cells","neuralNetworkFigure, gradientDescentFigure, attentionFigure, decisionBoundaryFigure, kmeansFigure, activationFigure":"ready AI/ML figures",distributions:"{ kind: normal | uniform | exponential | binomial | poisson | dice | mean, …numbers or value names }; density, meanOf, sdOf, samples (seeded)","layoutTex(tex) / morphEquation(a, b, t)":"the built-in TeX subset, and term-by-term transitions","vec2, mat2":"2D vectors and 2×2 matrices (apply, multiply, determinant, inverse, eigen)"},items:{grid:"{ step?, transform?: matrix value, ghost? }: lines of the plane, warped by a matrix",axes:"{ ticks?, labels? }",vector:"{ to, from?, transform?, label? (TeX), labelAt?: tip | middle }",basis:"{ transform? }: î and ĵ",point:"{ at, transform?, label?, hollow? } or { on: expr, x } (a point riding a curve)",function:'{ expr: "sin(k x)", domain?, derivative?, dashed? }: y = f(x); number values are its parameters',parametric:"{ x, y (expressions in t), t?, transform? }",polygon:"{ points? (default the unit square), transform?, label? }: \\val{M.det} shows the determinant",line:"{ along } or { eigen: matrix value }: a span, or eigenlines",label:"{ tex, at, screen?, size?, align?, backdrop? }",equation:"{ steps: [TeX…], at, screen? }: ITEM.step moves between steps, terms gliding",tangent:"{ expr, at, h? (secant), label? }: \\val{ID.slope} is the exact slope",riemann:"{ expr, from, to, n, rule?: left | right | midpoint | trapezoid }: \\val{ID.sum}, \\val{ID.exact}",area:"{ expr, from, to, lower? }: signed, coloured by sign; \\val{ID.value}",taylor:"{ expr, at, order }: exact Taylor polynomials; a fractional order grows the next term in",histogram:"{ distribution, count, bins?, scale?, curve?, seed? }: seeded samples, binned; fills as count grows",distribution:"{ distribution, shade?: [a, b] }: a density curve (bars when discrete); \\val{ID.p}",galton:"{ rows?, balls, spacing?, top?, seed? }: a Galton board; fractional balls = the next one falling",scatter:"{ points: uniform | linear, count, inside?, fit?, seed? }: Monte Carlo and regression; \\val{ID.ratio}, \\val{ID.r}",bayes:"{ prior, truePositive, falsePositive }: Bayes as areas; \\val{ID.posterior}",graph:"{ nodes, edges, directed?, tree?, search?: { kind: bfs | dfs | dijkstra, start }, step?, frontier? }: searches step by step",venn:"{ sets (2 or 3), highlight?: set expression like (A | B)' }: shaded by clipping",clock:"{ modulus, value }: clock arithmetic; \\val{ID.hour}",network:"{ layers, activation?, inputs?, flow?, seed?, labels? }: a forward pass, layer by layer",heatmap:"{ cells (softmax? per row) or expr in x, y; colormap?, rowLabels?, colLabels?, values? }: attention maps, loss fields",contours:"{ expr in x, y, levels? }: level curves (marching squares)",descent:"{ expr in x, y, start, rate, steps, momentum? }: gradient descent with an exact gradient",classifier:"{ epochs, centres?, rate?, start? }: logistic regression training; \\val{ID.accuracy}",kmeans:"{ centres, iteration, k? }: Lloyd iterations; \\val{ID.inertia}"},props:{NAME:"a value: a number, [x, y] vector or [a, b, c, d] matrix (row by row; columns are where î and ĵ land)","ITEM.draw":"0..1, draws an item on","ITEM.opacity":"0..1","ITEM.step":"an equation's step; fractional values are part way"},functions:["sin","cos","tan","asin","acos","atan","atan2","sinh","cosh","tanh","exp","ln","log","log2","sqrt","abs","floor","ceil","round","sign","min","max","sigmoid","relu"],tex:"^ _ \\frac \\sqrt \\vec \\hat \\bar, \\sum \\prod \\int with limits, \\sin \\lim … , Greek, \\cdot \\times \\le \\to \\infty …, pmatrix / bmatrix / vmatrix, \\text, \\color{c}{…}, \\id{name}{…} (names a term for transitions), \\val{name:digits} (a live value)"},cli:{"tinyfly capabilities [--json]":"this catalog","tinyfly check <beats.json>":"check a beat script (names, fields) with suggestions","tinyfly validate <timeline.json> [--markup file]":"check a timeline against its markup","tinyfly render <timeline.json> <markup> [--at …]":"a frame as static markup","tinyfly video <scene.mjs> [--stills dir --times …]":"MP4, or PNG stills to look at"}}}const yt=t=>t.map(e=>`\`${e}\``).join(", "),p1=t=>Object.entries(t).map(([e,n])=>`| \`${e}\` | ${n.unit??n.kind??""} | ${n.description} |`).join(`
|
|
63
63
|
`);function j4(t,e={}){const n=g1(t,e),s=n.stickFigure;return[`# tinyfly capabilities${n.version?` (v${n.version})`:""}`,"","Generated from the library itself: every name below is accepted, and names not listed are rejected (beat scripts, code panels and `checkTracks` say which name was probably meant).","",`**Timing.** ${n.timing}`,"","## Easings","",`Named: ${yt(n.easings.named)}.`,"",...Object.entries(n.easings.parametric).map(([r,o])=>`- ${r}: \`${o}\``),"","## Track kinds","",...Object.entries(n.trackKinds).map(([r,o])=>`- **${r}**: ${o}`),"","## Canvas targets","","Types: `rect`, `circle`, `text`, `line`, `path`, `image`, `custom`. `describeTarget(target)` lists what one can animate with its values; `checkTracks(tracks, targets)` checks tracks before playing them.","","| Property | Unit | What it does | Types |","|---|---|---|---|",...Object.entries(n.canvasProperties).map(([r,o])=>`| \`${r}\` | ${o.unit??o.kind??""} | ${o.description} | ${o.types.length===7?"all":o.types.join(", ")} |`),"","## Stick figure (`@algorisys/tinyfly/characters`)","","`stickFigureTarget({ x, y, style })` is a custom canvas target; its props are the pose fields and the props below. Pose it with tracks (`poseTracks`), or write beats (`scriptTracks`).","","Style proportions: `headSize` is a fraction of height; `armLength` multiplies both upper arm and forearm lengths (default 1, positive finite). Hands, shoulders, torso and legs retain their sizes.","","### Pose fields","","| Field | Unit | What it does |","|---|---|---|",p1(s.poseFields),"","### Other props","","| Prop | Unit | What it does |","|---|---|---|",p1(s.props),"",`With \`style.hands\`, each hand has \`hand.left.<field>\` / \`hand.right.<field>\` props: ${yt(Object.keys(s.handFields))}.`,"",`**Poses** (a beat's \`do\`, or a pose key): ${yt(s.poses)}.`,"",`**Expressions** (a beat's \`mood\`): ${yt(s.expressions)}.`,"",`**Gags** (ms): ${Object.entries(s.gags).map(([r,o])=>`\`${r}\` (${o})`).join(", ")}.`,"",`**Gaits**: ${yt(s.gaits)}. **Acting styles** (\`style\`): ${yt(s.actingStyles)}.`,"","### Beat scripts","",`\`scriptTracks(target, beats, { from, ground, height, facing, style })\`. A beat has these fields only: ${yt(s.beatFields)}. Times are ms; \`to\` and \`target\` are scene px; \`onto\` is a floor's scene y.`,"","`characterScript(target, who, beats, options)` compiles the same beats for a v2 `character()` on a `characterTarget` (every option but `height`; the same result, its key poses on the human body; the walk phase keyed to that character's stride, and `walk` / `walking` / `gait` tracks that step the gait as the target draws). Add `hairFollowTracks(target, tracks, who)` after it so hanging hair swings.","","| `do` | Needs | What happens |","|---|---|---|",...Object.entries(s.actions).map(([r,o])=>`| \`${r}\` | ${(o.needs??[]).map(a=>`\`${a}\``).join(", ")} | ${o.summary} |`),"","Beats that touch something report `contact` (and `release`) times in `result.beats[i]`; key the thing they touch to those.","",`**Dances** (\`dancer(style, { move })\`): ${Object.entries(s.dances).map(([r,o])=>`\`${r}\` (${o.join(", ")})`).join("; ")}.`,"",`**Flips**: ${Object.entries(s.flips).map(([r,o])=>`\`${r}\` (${o})`).join(", ")}.`,"",`**Hand shapes**: ${yt(s.handShapes)}. **Mudras**: ${yt(s.mudras)}.`,"","### Your own actions, gaits and personas","","Nothing is registered globally: pass your definitions where they are used.","",...Object.entries(n.custom.api).map(([r,o])=>`- \`${r}\`: ${o}`),"",...Object.keys(n.custom.actions).length||Object.keys(n.custom.gaits).length?["**This cast’s own:**","",...Object.entries(n.custom.actions).map(([r,o])=>`- \`${r}\`${o.needs?.length?` (needs ${o.needs.map(a=>`\`${a}\``).join(", ")})`:""}: ${o.summary}`),...Object.entries(n.custom.gaits).map(([r,o])=>`- \`${r}\` (gait): ${o}`),""]:[],"## Props (everyday objects with behaviours)","","A prop is a 3D rig of simple parts drawn with the characters’ pens (clean, pencil, silhouette), so it turns toward the camera (`turn`), and its beats go through the same acting pass (anticipation, overshoot, overlap; `exaggeration` scales them).","",...Object.entries(n.props.api).map(([r,o])=>`- \`${r}\`: ${o}`),"",`Prop beat fields: ${yt(n.props.beatFields)}. Every prop has the controls ${Object.keys(n.props.commonControls).map(r=>`\`${r}\``).join(", ")} and the actions ${Object.keys(n.props.commonActions).map(r=>`\`${r}\``).join(", ")}.`,"","Scenery: `scenery({ x, y, width, height, kind: sky | room, hour, clouds, wind, rain, snow, horizon: hills | city | flat })` is a canvas target whose values `hour` (0–24), `clouds`, `rain`, `snow` (0–1) and `wind` (−1..1) are tracks (`set(prop, { at, value, duration })`, `tracks(id)`; `anchor('sun' | 'moon' | 'horizon' | 'ground', time)`); the same `wind` streams hair (`hairFollowTracks(…, { wind })`). `scenePreset('park' | 'street' | 'office' | 'home', { width, height })` lays out scenery and props as data; `buildScene` builds them into targets.","","| Preset | Family | Actions (needs) | Controls | Anchors |","|---|---|---|---|---|",...Object.entries(n.props.presets).map(([r,o])=>`| \`${r}()\` | ${o.family} | ${Object.entries(o.actions).map(([a,l])=>`\`${a}\`${l.needs?.length?` (${l.needs.join(", ")})`:""}`).join(", ")} | ${o.controls.map(a=>`\`${a}\``).join(", ")} | ${o.anchors.join(", ")} |`),"","## Character (v2 human)","",`Poses: ${yt(n.character.poses)}. Expressions: ${yt(n.character.expressions)}. Gags: ${yt(n.character.gags)}.`,`Native dances: ${yt(n.character.dances)}; \`humanDanceFrame(style, beat, base)\` keeps body heading independent; \`humanDanceTracks(target, options)\` bakes JSON pose tracks. \`danceCircleAt(beat, { radius, count, beatsPerTurn, facing, spins })\` gives a formation with planted toes; \`danceCircleTracks(targets, options)\` bakes scene tracks. \`plantDanceFoot(partner, side, worldPoint)\` returns pose AND position; \`meetDandiya(a, b)\` solves both stick tips to one shared world point and reports unreachable contacts.`,"","Appearance options of `character({ … })`, all plain data that turns with the head (see docs/character-appearance.md):","",`- \`build\`: ${yt(n.character.builds)}`,`- \`figure\`: ${yt(n.character.figureStyles)}`,"- `look`: `clean` (default), `pencil`, `silhouette`, `illustrated` (inked and painted: line weight follows the light, brush-tapered strokes, shadow/core/highlight tones from each fill; `illustrated: { light: [x, y], weight, taper, shadow, highlight }`, each 0–1)",...Object.entries(n.character.body).map(([r,o])=>`- \`${r}\`: ${o}`),`- \`hair\`: ${yt(n.character.hair)} (colours: ${yt(Object.keys(n.character.hairColors))} in \`HAIR_COLORS\`)`,"- Flowing hair: `softSweep`, `flowingBob`, `cascadingWaves`; editable `locks: [{ path, width, follow? }]` with cubic `{ around, up, lift? }` points (around in degrees, dimensions in head radii), `fall: { taper, wave }` and `shine` (0–1). Roots stay attached; `hairFollowTracks` also drives flexible short locks.",`- \`facialHair\`: ${yt(n.character.facialHair)}`,`- \`glasses\`: ${yt(n.character.glasses)}; \`hat\`: ${yt(n.character.hats)}; \`ears: true\`; \`face: { teeth, tongue }\` (shown when the mouth opens); \`feet\`: ${yt(n.character.feet)}`,"- `outfit`: `{ top: tshirt | shirt | blouse | dress, trouserStyle: plain | jeans | cargo, shirt: top colour, trousers: bottom colour, sleeves: short | long | none, bottom: trousers | shorts | skirt, collar, tie: colour, over: apron | labCoat | hoodie | cardigan | overalls | sari, overColor, shoes: boots, shoeColor }`",`- \`castMember(name, height)\`: ${yt(n.character.cast)}`,"- Face marks (pose fields, 0–1): `blush`, `tears`, `sweat`; close-up fields `pupil` (size, 1 usual), `lid` (upper lids lowered, 0–1), `bulge` (eyes out of the head, 0–1); `face: { nose: true, inPupil(ctx, pupil) }`; `drawCharacterHead(ctx, who, pose, { x, y, radius })` draws just the head big",`- Face styles: ${yt(n.character.faceStyles)}; \`face: { style: 'anime', iris: '#4b7fce', lashes: true, ageLines: 0.8 }\` uses coloured eyes and the same expressions, blinks and gaze. \`ANIME_CAST\` contains eight age presets, also available through \`castMember\`.`,`- Face shapes: ${yt(n.character.faceShapes)}; \`face: { shape: 'angular', jawWidth: 0.74, chinWidth: 0.14, eyeScale: 0.8, eyeAspect: 0.65 }\` sets a tapered 3D jaw and narrower anime eyes; \`jawRoundness: 1\` softens the cheek/chin corners (default 0 keeps sharp jaws). \`MANGA_CAST\` contains four original young adult presets; hair styles \`mangaSpikes\` and \`mangaSweep\` remain editable.`,"- Hair in motion (pose fields): `hair.swing` (degrees round the head, + toward its left), `hair.trail` (head radii back), `hair.lift` (head radii up); key them with `hairFollowTracks(target, tracks, who)` after the character's tracks, or `hairFollow` + `hairMotionAt` when posing per frame",`- \`holding\`: ${Object.entries(n.character.heldItems).map(([r,o])=>`\`${r}\` (${o==="both"?"both":o==="either"?"one hand or both":"left or right"})`).join(", ")}; pose fields \`held.left\`, \`held.right\`, \`held.both\` (below 0.5 lets go); \`handGrip(joints, side)\``,`- \`meetHands(kind, a, b)\` (stand them \`meetingSpacing(kind, a, b)\` apart): ${yt(n.character.handMeetings)}; \`embrace(a, b)\` (a hug, \`embraceSpacing\` apart); \`helpUp(helper, sitter, progress)\` (0 on the floor, hand taken; 1 standing; \`helpUpSpacing\` apart)`,"- Everyday cycles like a gait: `humanCyclePose('sweeping' | 'brushing', phase, base)` (0 → 1 is one stroke and back; sweeping with `holding: { right: 'broom' }`)","","## Code panel","",`\`codePanel({ code, language, x, y, fontSize?, lineHeight?, width? })\`: a code listing as a scene object. Languages: ${yt(n.codePanel.languages)}. Remove styles: ${yt(n.codePanel.removeStyles)}.`,"",...Object.entries(n.codePanel.anchors).map(([r,o])=>`- \`${r}\`: ${o}`),"",...Object.values(n.codePanel.edits).map(r=>`- \`${r.split(":")[0]}\`:${r.split(":").slice(1).join(":")}`),"","## Surfaces","","Scene objects figures act on. Places are named `kind:args`: `surface.anchor(name)` gives the box there (stand on `top`, point at `x`, `y`; pass it as a beat `target`), `surface.piece(name)` makes the part there come loose, and `surface.edit(name, anchor, options)` changes the surface at a time (`at`, ms).","","Beats name places and say what surfaces do in answer (`surfaceScript`):","",...Object.entries(n.surfaceScript).map(([r,o])=>`- \`${r}\`: ${o}`),"",...Object.entries(n.surfaces).flatMap(([r,o])=>[`### ${r}`,"",...o.create?[`\`${o.create}\``,""]:[],"Anchors:",...Object.entries(o.anchors).map(([a,l])=>`- \`${a}\`: ${l}`),"","Edits:",...Object.entries(o.edits).map(([a,l])=>`- \`${a}\`: ${l}`),""]),"## Cricket stories (`@algorisys/tinyfly/sports`)","","`cricketClip({ format, action, cast })` returns an organic-player scene, JSON tracks, timed events/captions and a declared result. `cricketField`, `cricketPlayer` and `cricketAction` compose separately; `cricketCameraTracks` adds camera tracks. These are authored tutorial plays, not physics or automatic umpiring. See docs/cricket.md.","",`Marking profiles: ${yt(Object.keys(n.sports.cricket.markingProfiles))}; default ICC men, independently of cast. Limited-over ICC profiles draw a wicket-centred capsule; Test/MCC have no restriction-area line. \`cricketFieldingAreaContains(field, point)\` returns true/false/null; \`cricketFieldingPositions\` and \`cricketFieldingOverlay\` provide owned setup markers, not umpiring decisions.`,"","`cricketPlay(field, options)` / `cricketPlayClip(options)` independently author delivery style/legality, shot, finish, fielding, current free-hit context and candidate dismissal. Omitted dismissal means no dismissal. Unsupported motion combinations throw; no-ball/free-hit protection changes result/signals without removing physical catches or wicket breaks. Run-out remains available. Illegal free hits carry forward; legal ones consume context. Test rejects free-hit context. Keep innings/score/strike in the consuming app.","",...Object.entries(n.sports.cricket.playComponents).map(([r,o])=>`Play ${r}: ${yt(o)}`),...Object.entries(n.sports.cricket.playExamples).map(([r,o])=>`- Composed example \`${r}\`: ${o.name}`),"",...Object.entries(n.sports.cricket.actions).map(([r,o])=>`- \`${r}\`: ${o.summary}`),"",`Formats: ${yt(Object.keys(n.sports.cricket.formats))}. Casts: ${yt(Object.keys(n.sports.cricket.casts))}. Cameras: ${yt(Object.keys(n.sports.cricket.cameras))}. Orbit turns 360° around the whole ground. \`cricketCameraTracks(clip, { view, zoom })\` supports 0.25–4× optical magnification (default 1) in every view.`,"",`Stock fielding labels (\`CRICKET_FIELDING_POSITIONS\`): ${Object.entries(n.sports.cricket.fieldingPositions).map(([r,o])=>`\`${r}\`: ${o}`).join(", ")}. Eleven fielders, two on-field batters and two umpires; nine batting teammates wait off-field. Mid-on is closer to the pitch; long-on is its deeper boundary alternative, not an extra stock fielder. For the right-handed striker, +x is off side and -x is on/leg side.`,"","Decision review cameras: front-foot, striker-crease, bowler-crease. cricketCameraFraming returns owned defaults; cricketCameraReview returns a physical event without seeking. Optional cricketDecisionOverlay marks the crease reference. pitch 0–89, distance 0.5–2000, fov 10–100 before zoom, and fixed-view target customize framing. Ball-follow yaw rotates its default offset relative to 75 degrees; pitch/distance apply too. Export all camera tracks, including far for distant framing. These APIs never alter motion or rulings.","","## Camera shots (`cameraTracks(shots, { stage })`)","",...Object.entries(n.cameraShots).map(([r,o])=>`- **${r}**: \`${o}\``),"","## Teaching (`@algorisys/tinyfly/teach`)","",...Object.entries(n.teach).map(([r,o])=>`- \`${r}\`: ${o}`),"","## Maths (`@algorisys/tinyfly/math`)","","A figure is JSON: a plane and items. Tracks on its target animate values by name and item props. One layout feeds a canvas (videos) and SVG (lesson embeds), so they match.","",...Object.entries(n.math.api).map(([r,o])=>`- \`${r}\`: ${o}`),"","Items (each has `id`, `kind`, and optional `color`, `draw`, `opacity`):","",...Object.entries(n.math.items).map(([r,o])=>`- \`${r}\` ${o}`),"","Props a timeline animates:","",...Object.entries(n.math.props).map(([r,o])=>`- \`${r}\`: ${o}`),"",`Expression functions: ${n.math.functions.map(r=>`\`${r}\``).join(", ")}; constants \`pi\`, \`e\`, \`tau\`.`,"",`TeX subset: ${n.math.tex}`,"","## Command line","",...Object.entries(n.cli).map(([r,o])=>`- \`${r}\`: ${o}`),""].join(`
|
|
64
64
|
`)}function Y4(t,e,n,s={}){const i=s.color??"#555",r=s.size??60;for(const o of e){const a=(n-o.time)/o.length;if(a<=0||a>=1)continue;const l=ne(`${o.kind}:${o.time}:${o.x}`);o.kind==="dust"?pm(t,{x:o.x,y:o.y},a,{size:r,color:i,seed:l}):o.kind==="exhaust"?G4(t,o,a,r,i,l):o.kind==="skid"?U4(t,o,a,n,i):o.kind==="honk"?V4(t,o,a,r,i):o.kind==="smoke"?K4(t,o,n,r,i):o.kind==="leaves"&&X4(t,o,a,r,s.leafColor??"#5cae5a",i,l)}}function K4(t,e,n,s,i,r){const o=e.direction??1,a=380,l=1500;t.save(),t.strokeStyle=i,t.lineWidth=Math.max(1,s*.025);for(let c=e.time;c<=e.time+e.length-l;c+=a){const h=(n-c)/l;if(h<=0||h>=1)continue;const u=Math.sin(c/97+h*4)*s*.06,d=e.x+o*h*s*.7+u,f=e.y-h*s*1.6;t.globalAlpha=Math.min(1,h*6)*(1-h)*.85,t.beginPath(),t.arc(d,f,s*(.07+h*.2),0,Math.PI*2),t.stroke()}t.restore()}function X4(t,e,n,s,i,r,o){const a=e.direction??1,l=e.toY??e.y+s*3;t.save(),t.lineWidth=Math.max(1,s*.02),t.strokeStyle=r,t.fillStyle=i;for(let c=0;c<4;c++){const h=ne(`${o}:${c}`)%1e3/1e3,u=Math.min(1,n*(1.1+h*.4)),d=e.x+(h-.5)*s*1.2,f=e.y+(h-.3)*s*.4,p=u*u*.4+u*.6,g=d+a*u*s*(.6+h)+Math.sin(u*9+h*6)*s*.18,m=Math.min(l-2,f+(l-f)*p);t.globalAlpha=n>.85?(1-n)/.15:1,t.save(),t.translate(g,m),t.rotate(Math.sin(u*7+h*5)*1.2),t.beginPath(),t.ellipse(0,0,s*.07,s*.035,0,0,Math.PI*2),t.fill(),t.stroke(),t.restore()}t.restore()}function G4(t,e,n,s,i,r){const o=e.direction??-1;t.save(),t.strokeStyle=i,t.lineWidth=Math.max(1,s*.025);for(let a=0;a<3;a++){const l=n*1.6-a*.25;if(l<=0||l>=1)continue;const c=(ne(`${r}:${a}`)%100/100-.5)*s*.1,h=e.x+o*l*s*.9,u=e.y-l*s*.45+c;t.globalAlpha=(1-l)*.9,t.beginPath(),t.arc(h,u,s*(.06+l*.14),0,Math.PI*2),t.stroke()}t.restore()}function U4(t,e,n,s,i){const r=e.toX??e.x,o=Math.min(1,(s-e.time)/e.length*3),a=e.x+(r-e.x)*o;t.save(),t.strokeStyle=i,t.lineCap="round",t.globalAlpha=n<.6?.8:.8*(1-(n-.6)/.4),t.lineWidth=3;for(const l of[-2,4])t.beginPath(),t.moveTo(e.x,e.y+l),t.lineTo(a,e.y+l),t.stroke();t.restore()}function V4(t,e,n,s,i){const r=e.direction??1;t.save(),t.strokeStyle=i,t.lineWidth=Math.max(1.5,s*.04),t.lineCap="round",t.globalAlpha=n<.7?1:(1-n)/.3;const o=s*(.15+.5*(1-(1-n)**2));for(let a=-1;a<=1;a++){const l=a*Math.PI/7,c=e.x+r*Math.cos(l)*o,h=e.y+Math.sin(l)*o;t.beginPath(),t.arc(c,h,s*.12,r>0?-Math.PI/3:Math.PI*2/3,r>0?Math.PI/3:Math.PI*4/3),t.stroke()}t.restore()}function J4(t){const e=new Ht({id:`${t.propId}-ride`,tracks:t.propTracks.filter(h=>h.target===t.propId)}),n=t.every??33,s=[],i=[],r=[],o=[];let a=1;for(let h=t.start;;h=Math.min(t.end,h+n)){const u=Do(t.prop,{state:e.getStateAtTime(h)},t.propId),d=u.anchor(t.anchor);s.push({time:h,value:d.x+(t.offset?.x??0)-t.figure.x}),i.push({time:h,value:d.y+(t.offset?.y??0)-t.figure.y});const f=Math.sin(u.values.turn*Math.PI/2);if(Math.abs(f)>.15&&(a=f>0?1:-1),r.push({time:h,value:Math.abs(f)}),o.push({time:h,value:a}),h>=t.end)break}const l=t.figureId,c=[{id:`${l}-x`,target:l,property:"x",keyframes:s},{id:`${l}-y`,target:l,property:"y",keyframes:i}];return t.turn!==!1&&c.push({id:`${l}-turn`,target:l,property:"turn",keyframes:r},{id:`${l}-facing`,target:l,property:"facing",keyframes:Z4(o)}),c}function Z4(t){const e=[];for(const n of t){const s=e[e.length-1];s&&s.value!==n.value&&e.push({time:n.time-1,value:s.value}),(!s||s.value!==n.value||n===t[t.length-1])&&e.push(n)}return e}function Q4(t,e,n){const s=o=>`${o.target}\0${o.property}`,i=new Map(e.map(o=>[s(o),o]));return[...t.map(o=>{const a=i.get(s(o));if(!a)return o;i.delete(s(o));const c=[...(o.keyframes??[]).filter(h=>h.time<n.from||h.time>n.to),...a.keyframes??[]].sort((h,u)=>h.time-u.time);return{...o,keyframes:c}}),...i.values()]}function tT(t){const e=new Ht({id:`${t.leaderId}-tow`,tracks:t.leaderTracks.filter(f=>f.target===t.leaderId)}),n=t.every??33,s=t.towed,i=s.x+s.width/2,r=s.props,o=s.prop.wheelRadius,a=[],l=[],c=[];let h=r.wheelSpin??0,u;for(let f=t.start;;f=Math.min(t.end,f+n)){const p=Do(t.leader,{state:e.getStateAtTime(f)},t.leaderId),g=p.anchor(t.hitch),m=p.values.turn,y=$s(s.prop,{...r,turn:m},s.propScale).anchors[t.anchor];if(!y)throw new Error(`propTow: ${s.prop.kind} has no anchor "${t.anchor}"`);const v=g.x-y.point.x;if(u!==void 0&&o){const k=Math.sin(m*Math.PI/2);h+=(v-u)*(k||1)/s.propScale/o*(180/Math.PI)}if(u=v,a.push({time:f,value:v-i}),l.push({time:f,value:m}),c.push({time:f,value:h}),f>=t.end)break}const d=t.towedId;return[{id:`${d}-x`,target:d,property:"x",keyframes:a},{id:`${d}-turn`,target:d,property:"turn",keyframes:l},...o?[{id:`${d}-wheelSpin`,target:d,property:"wheelSpin",keyframes:c}]:[]]}const m1=new WeakMap;function eT(t,e){const n=e?.some(Boolean)?e.map(d=>d?1:0).join(""):"";let s=m1.get(t);s||m1.set(t,s=new Map);const i=s.get(n);if(i)return i;const r=qi(t),o={vertices:r.vertices,faces:r.faces.filter((d,f)=>!e?.[f])},a=o.vertices.flatMap(d=>[d[0],d[1],d[2]]),l=o.vertices.map(()=>[0,0,0]),c=[];o.faces.forEach(d=>{for(const g of d.corners)for(const m of[0,1,2])l[g][m]+=d.normal[m];const[f,...p]=d.corners;for(let g=0;g+1<p.length;g++){const[m,y,v]=[f,p[g],p[g+1]],[k,w,T]=[o.vertices[m],o.vertices[y],o.vertices[v]],A=[w[0]-k[0],w[1]-k[1],w[2]-k[2]],M=[T[0]-k[0],T[1]-k[1],T[2]-k[2]],x=[A[1]*M[2]-A[2]*M[1],A[2]*M[0]-A[0]*M[2],A[0]*M[1]-A[1]*M[0]],S=x[0]*d.normal[0]+x[1]*d.normal[1]+x[2]*d.normal[2];c.push(...S>=0?[m,y,v]:[m,v,y])}});const h=l.flatMap(d=>{const f=Math.hypot(...d)||1;return[d[0]/f,d[1]/f,d[2]/f]}),u=mo({positions:a,normals:h,indices:c});return s.size>=16&&s.clear(),s.set(n,u),u}function nT(t,e,n={}){const s=t.ink??n.ink??"#26262b",i=(n.outline??2)*(t.outline??1),r=t.glow&&e.glow>0?sT(t.glow.color,e.glow):void 0;return{color:t.fill??s,creases:qi(t.shape).creases!==!1,shading:n.shading??"toon",...i>0?{outline:{width:i,color:s}}:{},...r?{emissive:r}:{},...t.seeThrough?{opacity:.45*e.opacity}:e.opacity<1?{opacity:e.opacity}:{}}}function sT(t,e){const n=/^#([0-9a-f]{6})$/i.exec(t.trim());return n?`#${[0,2,4].map(i=>Math.round(parseInt(n[1].slice(i,i+2),16)*Math.max(0,Math.min(1,e)))).map(i=>i.toString(16).padStart(2,"0")).join("")}`:t}const iT=mo(ap(1,.002,28));function rT(t,e,n){const s=t.rig,[i,r]=s.footprint??[s.length*.45,s.length],o=Math.max(0,It(s,e,"lift")),a=Math.max(0,It(s,e,"size"))/(1+o*.8);return{mesh:iT,world:Rt(n,Ra([0,.004,0],[0,0,0,1],[i*.55*a||1e-4,1,r*.55*a||1e-4])),material:{color:"#000000",shading:"unlit",opacity:.16*a}}}const oT=new Set(["x","y","z","position","rotateX","rotateY","rotateZ","quaternion","scale","scaleX","scaleY","scaleZ","visible","opacity","color"]),aT=1,lT={kind:"prop",validate(t){const e=t,n=typeof e.prop=="string"&&e.prop in Cs?[]:[ft("prop preset",e.prop,Object.keys(Cs))];for(const[s,i]of[[0,"rotateX"],[1,"rotateY"],[2,"rotateZ"]])i in e&&n.push(`${i} is a track, not a field: place it turned with rotation: [${[0,1,2].map(r=>r===s?e[i]:0).join(", ")}]`);return n},prepare(t){const e=t;return Th(e.prop,e.options)},resolve({object:t,prepared:e,values:n,world:s,camera:i,lights:r=[],fog:o,toScreen:a}){const l=t,c=e,h={...l.values};for(const[M,x]of n)typeof x=="number"&&!oT.has(M)&&(h[M]=x);h.turn=0,h.tilt=0;const u=Rt(i.view,s),d={toView:M=>ie(u,M),toScreen:M=>a(M)},f=d.toView([0,c.rig.height/2,0]);if(-f[2]<=i.near)return null;if(l.look==="mesh"){const M=Qm(c.rig,h),x=M.map(({part:P,local:I})=>({part:P.id,mesh:qi(P.shape),...fh(qi(P.shape),I)})),S=Xm(x),E=M.map((P,I)=>({...P,hidden:Um(P.part.id,x[I].mesh,P.local,x[I].key,S)})).filter(({opacity:P})=>P>.01).map(({part:P,matrix:I,glow:O,opacity:H,hidden:W})=>({mesh:eT(P.shape,W),world:Rt(s,I),material:nT(P,{glow:O,opacity:H},{shading:l.shading,ink:l.ink,outline:l.outline})}));return{meshes:l.shadow===!1?E:[rT(c,h,s),...E]}}const p=a(f),g=a(d.toView([0,c.rig.height/2+1,0])),m=Math.hypot(g.x-p.x,g.y-p.y),y=r.length===0?void 0:(M,x)=>{const S=ie(s,M),E=[s[0]*x[0]+s[4]*x[1]+s[8]*x[2],s[1]*x[0]+s[5]*x[1]+s[9]*x[2],s[2]*x[0]+s[6]*x[1]+s[10]*x[2]],P=Math.hypot(...E)||1;return{light:Md(S,[E[0]/P,E[1]/P,E[2]/P],r),fog:Sd(o,Math.hypot(S[0]-i.position[0],S[1]-i.position[1],S[2]-i.position[2]))}},v=bh(c.rig,h,d,m,{perspective:!0,near:i.near,slice:aT,light:y}),k={look:l.look,style:l.style,ink:l.ink,paper:l.paper,fog:o?.color},w=wc(v),T=v.cells??[],A=Math.max(...T.map(M=>-M.depth),-f[2]);return{drawables:[...l.shadow===!1?[]:[{depth:A+c.rig.length,draw:M=>kc(M,v,k)}],...T.map(M=>({depth:-M.depth,draw(x,S){x.lineCap="round",x.lineJoin="round",cp(x,M.parts,w,{...k,time:S.time})}}))]}}},zh=["do","at","for","to","through","toward","speed","height","open","on","wind"],cT=.25,hT=800/180,uT=220,dT=300,fT=["turn"];function gT(t){const e=Yo(t),n=Object.keys(t.moves??{});return Object.keys(e).filter(s=>!n.includes(s)&&!fT.includes(s)&&!(e[s].needs??[]).includes("to"))}function y1(t,e){if(!Array.isArray(t))return[{beat:-1,message:`Beats must be an array of { do: … } objects (got ${typeof t}).`}];const n=Object.keys(e.moves??{}),s=gT(e),i=[...n,"face","hold",...s.filter(o=>o!=="hold")],r=[];return t.forEach((o,a)=>{const l=u=>r.push({beat:a,message:u});if(!o||typeof o!="object"||Array.isArray(o))return l(`Each beat must be an object like { do: '${i[0]??"hold"}' }.`);const c=o,h={duration:"for",path:"through",points:"through",position:"to",heading:"toward",direction:"toward"};for(const u of Object.keys(c))zh.includes(u)||l(ft("beat field",u,zh,h[u]));if(typeof c.do!="string"||!i.includes(c.do)){const u=c.do==="turn"?"face":void 0;return l(ft(`${e.kind} 3D beat`,c.do,i,u))}n.includes(c.do)&&(c.to===void 0&&c.through===void 0&&l(`\`${c.do}\` needs \`to\` ([x, z] metres) or \`through\` (a list of them).`),c.to!==void 0&&!Cn(c.to)&&l(`\`to\` is a point on the ground, [x, z] metres (got ${JSON.stringify(c.to)}).`),c.through!==void 0&&!(Array.isArray(c.through)&&c.through.length>0&&c.through.every(Cn))&&l("`through` is a list of points on the ground, each [x, z] metres.")),c.do==="face"&&!(Cn(c.toward)||typeof c.toward=="number")&&l("`face` needs `toward`: a point [x, z] or a heading in degrees.")}),r}function pT(t,e,n,s){const i=y1(n,e);if(i.length>0)throw new Error(`propScript3D (${e.kind}): ${i.length} problem(s) in the beats:
|
|
65
65
|
${i.map(k=>` beat ${k.beat}: ${k.message}`).join(`
|