Spaces:
Running
Running
Download app/src/pet/source.js from FormaLau/DuckAgochi: direct link, hf CLI and curl.
- Browser
- Download file 11.3 kB
-
https://huggingface.co/spaces/FormaLau/DuckAgochi/resolve/main/app/src/pet/source.js
- Command line
-
hf download hf://spaces/FormaLau/DuckAgochi/app/src/pet/source.js
-
curl -L -o source.js https://huggingface.co/spaces/FormaLau/DuckAgochi/resolve/main/app/src/pet/source.js
11.3 kB
| import { NeedReminders } from './emotions.js'; | |
| import { MEAL, BED, waterStation, TREAT, COURSE, nearestRollSpot, rollSafe, GOAL, wrap, route, clearSegment, safePoint } from './world.js'; | |
| // Real-time sequencer: accelerated needs never accelerate locomotion or audio. | |
| export class PetSource { | |
| id='pet';command=new Float32Array(3);axes={jaw:0};pressed={}; | |
| reminders=new NeedReminders();reminderWait=0; | |
| token=null;emotionSeq=-1;phase='idle';elapsed=0;wait=0;bites=0;ring=0;attempts=0; | |
| path=[];target=null;stats={kicks:0,rolls:0,goals:0,rings:0}; | |
| constructor({state,pose,blocked,posture,world={},voice=null,event=()=>{}}) { | |
| Object.assign(this,{state,pose,blocked,posture,world,voice,event}); | |
| } | |
| isActive(){return this.command.some(v=>Math.abs(v)>.001);} | |
| setPhase(phase,extra={}){this.phase=phase;this.event('phase',{phase,bites:this.bites,...this.stats,...extra});} | |
| reset(){this.token=null;this.voice?.stop();this.command.fill(0);this.axes.jaw=0;this.world.expression?.(null);this.world.course?.(-1);} | |
| finish(success){this.command.fill(0);this.world.course?.(-1);this.setPhase('idle');this.event('finish',success);} | |
| navigate(target,yaw=null,tolerance=.075) { | |
| const [x,y,heading]=this.pose(),position=[x,y]; | |
| const dist=Math.hypot(target[0]-x,target[1]-y); | |
| if(dist<tolerance) { | |
| if(yaw===null || Math.abs(wrap(yaw-heading))<.19) return true; | |
| // Align on the spot after retreating from the table; avoid backing away | |
| // from the waypoint while trying to face the plate. | |
| this.command[0]=0; | |
| this.command[2]=Math.sign(wrap(yaw-heading));return false; | |
| } | |
| let next=target; | |
| if(!clearSegment(position,target)) { | |
| if(!this.target || Math.hypot(target[0]-this.target[0],target[1]-this.target[1])>.08 || !this.path.length){this.path=route(position,target);this.target=[...target];} | |
| while(this.path.length && Math.hypot(this.path[0][0]-x,this.path[0][1]-y)<.13)this.path.shift(); | |
| const visible=this.path.filter(p=>clearSegment(position,p));next=visible.at(-1)||this.path[0]; | |
| if(!next)return false; | |
| } | |
| let err=wrap(Math.atan2(next[1]-y,next[0]-x)-heading); | |
| const reverse=Math.abs(err)>Math.PI/2; | |
| this.command[0]=reverse ? -.4 : .25; | |
| if(reverse)err=wrap(err-Math.sign(err)*Math.PI); | |
| this.command[2]=Math.abs(err)<.08?0:Math.max(-1,Math.min(1,err*2.5)); | |
| return false; | |
| } | |
| poll(dt=.016) { | |
| this.command.fill(0);this.axes.jaw=0; | |
| const {pet,paused,environment="home"}=this.state(); | |
| const blocked=this.blocked(); | |
| this.reminderWait=Math.max(0,this.reminderWait-dt); | |
| const free=!paused && !blocked && pet.activity==='idle' && !pet.task && !this.voice?.current && this.reminderWait===0 && (!this.world.mode || this.world.mode()==='walk'); | |
| const reminder=this.reminders.next(pet.needs,paused?0:dt,free); | |
| if(reminder){this.reminderWait=6;this.event('emotion',reminder);return;} | |
| if(free && pet.remaining<=0){this.event('autonomous');return;} | |
| if(paused || blocked){this.voice?.stop();this.world.expression?.(null);return;} | |
| const token=`${environment}:${pet.activity}:${pet.actionId||0}`; | |
| if(token!==this.token) { | |
| this.token=token;this.elapsed=0;this.wait=0;this.bites=0;this.ring=0;this.attempts=0;this.path=[];this.target=null;this.initialKicks=this.stats.kicks; | |
| this.world.course?.(-1); | |
| this.exitTable=!['eat','drink','treat','cuddle'].includes(pet.activity) && this.pose()[0]>.5 && this.pose()[0]<.85 && this.pose()[1]>.4 && this.pose()[1]<1.05;this.exitY=this.pose()[1];this.restSettle=0; | |
| if(['eat','treat','drink'].includes(pet.activity)){this.station=pet.activity==='drink'?waterStation(environment):pet.activity==='treat'?TREAT:MEAL;this.stationStaged=Math.hypot(this.pose()[0]-this.station.approach[0],this.pose()[1]-this.station.approach[1])<.04;this.retreatY=this.pose()[1];this.retreatNeeded=!this.stationStaged && this.pose()[0]>.47;this.world.serve?.(pet.activity);this.setPhase(pet.activity==='drink'?'drink-approach':pet.activity==='treat'?'treat-approach':'meal-approach');} | |
| else if(pet.activity==='play') { | |
| this.game=pet.playStyle && pet.playStyle!=='auto'?pet.playStyle:((pet.actionId||0)%3===0?'roll':'ball'); | |
| if(this.game==='roll')this.rollTarget=nearestRollSpot(this.pose()); | |
| if(['ball','goal'].includes(this.game))this.world.spawnBall?.(this.game); | |
| if(this.game==='goal')this.game='ball'; | |
| if(this.game==='course')this.world.course?.(0); | |
| this.setPhase(this.game==='ball'?'ball-detour':`${this.game}-approach`); | |
| } else this.setPhase(pet.activity==='rest'?'sleep-approach':pet.activity==='drink'?'drink-approach':pet.activity); | |
| } | |
| if(pet.emotionSeq!==this.emotionSeq && ['angry','defiant'].includes(pet.emotion) && !this.posture(false))return; | |
| if(pet.emotionSeq!==this.emotionSeq){this.emotionSeq=pet.emotionSeq;this.voice?.stop();if(pet.emotion)this.voice?.start(pet.emotion);} | |
| // Stand up before protesting so the complete angry body motion can play. | |
| if(pet.emotion==='angry' && this.voice?.current==='angry')this.posture(false); | |
| const expression=this.voice?.update(dt); | |
| this.world.expression?.(expression); | |
| if(expression){this.axes.jaw=expression.mouth;return;} | |
| this.elapsed+=dt;this.wait+=dt; | |
| if(this.world.locomotion && !this.world.locomotion(pet.activity==='explore' && pet.playStyle==='rollers'?'rollers':'legs'))return; | |
| if(this.exitTable){if(this.posture(false) && this.navigate([.4,this.exitY],null,.06))this.exitTable=false;return;} | |
| if(pet.task && this.elapsed>90){this.finish(false);return;} | |
| if(['meal-peck','drink-sip','treat-peck'].includes(this.phase)) { | |
| // The official ground-pick policy bends the legs, body and neck together. | |
| // Its own phase drives the beak; do not overlay walking head targets. | |
| this.world.expression?.(null); | |
| const mouth=this.world.mouth?.(); | |
| if(!this.tookBite && mouth && (this.world.jaw?.() ?? 0)>.2 && Math.hypot(mouth[0]-this.station.plate[0],mouth[1]-this.station.plate[1],mouth[2]-this.station.height)<.075) { | |
| this.tookBite=true;this.bites++;if(pet.activity!=='drink'){this.world.eat?.(this.bites,pet.activity);this.event('bite');}this.setPhase(this.phase); | |
| } | |
| if(this.wait>1 && this.world.mode?.()==='walk'){ | |
| this.wait=0; | |
| if(this.bites>=(pet.activity==='drink'?2:3)){this.finish(true);return;} | |
| this.setPhase(this.tookBite?'meal-chew':pet.activity==='drink'?'drink-approach':pet.activity==='treat'?'treat-approach':'meal-approach'); | |
| } | |
| return; | |
| } | |
| if(this.phase==='meal-chew') { | |
| this.axes.jaw=.25+.2*Math.sin(this.wait*13); | |
| if(this.wait>1.1)this.setPhase('meal-approach');return; | |
| } | |
| if(this.phase==='roll-running'){ | |
| if(this.wait>1 && this.world.mode?.()==='walk'){this.stats.rolls++;this.finish(true);this.event('emotion','excited');}return; | |
| } | |
| if(this.phase==='ball-kick'){ | |
| const b=this.world.ball?.(); | |
| if(this.wait>1 && this.world.mode?.()==='walk'){ | |
| if(b && this.kickPosition && Math.hypot(b[0]-this.kickPosition[0],b[1]-this.kickPosition[1])>.06)this.stats.kicks++; | |
| if(pet.autonomous && this.stats.kicks>this.initialKicks){this.finish(true);return;} | |
| this.setPhase('ball-approach'); | |
| } | |
| return; | |
| } | |
| if(this.phase==='ball-settle') { | |
| if(this.wait>.7 && this.world.kick?.()) { | |
| this.kickPosition=this.world.ball?.();this.attempts++;this.wait=0;this.setPhase('ball-kick'); | |
| } | |
| return; | |
| } | |
| if(pet.activity==='rest') { | |
| const [x,y]=this.pose(); | |
| // Keep arrival latched during settling: walking sway must not restart | |
| // the approach each time the duck crosses the arrival boundary. | |
| if(!this.world.lying?.() && Math.hypot(x-BED[0],y-BED[1])>((pet.sleeping || this.restSettle>0)?.28:.20)) { | |
| this.restSettle=0;if(pet.sleeping)this.event('sleep',false); | |
| this.setPhase('sleep-approach'); | |
| if(this.posture(false))this.navigate(BED,null,.08); | |
| } else { | |
| this.restSettle=(this.restSettle||0)+dt; | |
| if(this.restSettle<1.2){this.setPhase('sleep-approach');return;} | |
| this.posture(true); | |
| if(!pet.sleeping && (this.world.seated?.() ?? this.world.mode?.()==='sitstand'))this.event('sleep',true); | |
| this.setPhase('sleeping'); | |
| } | |
| return; | |
| } | |
| if(!this.posture(false))return; | |
| if(pet.activity==='cuddle') { | |
| // Gentle nuzzling continues after the official excited expression. | |
| this.world.expression?.({neck:.08,head_pitch:-.12,head_yaw:.18*Math.sin(this.elapsed*2.4),head_roll:.14*Math.sin(this.elapsed*3),body_pitch:.04*Math.sin(this.elapsed*3),body_z:.008*Math.sin(this.elapsed*4),mouth:.12}); | |
| return; | |
| } | |
| if(['eat','treat','drink'].includes(pet.activity)) { | |
| if(this.retreatNeeded){if(this.navigate([.42,this.retreatY],null,.07))this.retreatNeeded=false;return;} | |
| if(!this.stationStaged){if(this.navigate(this.station.staging || [.43,this.station.approach[1]],this.station.yaw,.06))this.stationStaged=true;return;} | |
| if(this.navigate(this.station.approach,this.station.yaw,.03) && this.world.peck?.()){ | |
| this.sawPeck=true;this.tookBite=false;this.wait=0;this.setPhase(pet.activity==='drink'?'drink-sip':pet.activity==='treat'?'treat-peck':'meal-peck'); | |
| } | |
| } else if(pet.activity==='play' && this.game==='roll') { | |
| if(this.phase==='roll-ready'){if(this.wait>.8 && this.world.roll?.()){this.wait=0;this.setPhase('roll-running');}} | |
| else if(rollSafe(this.pose()) || this.navigate(this.rollTarget,null,.04)){this.wait=0;this.setPhase('roll-ready');} | |
| } else if(pet.activity==='play' && this.game==='course') { | |
| if(this.navigate(COURSE[this.ring],null,.13)) { | |
| this.ring++;this.stats.rings++;this.world.course?.(this.ring);this.setPhase('course-approach'); | |
| if(this.ring===COURSE.length)this.finish(true); | |
| } | |
| } else if(pet.activity==='play' && this.game==='ball') { | |
| const b=this.world.ball?.();if(!b)return; | |
| if(b[0]>GOAL.x && Math.abs(b[1]-GOAL.y)<GOAL.halfWidth-.03){this.stats.goals++;this.finish(true);this.event('emotion','laugh');return;} | |
| if(this.attempts>=8 || this.elapsed>85){this.finish(this.stats.kicks>this.initialKicks);return;} | |
| const angle=pet.autonomous ? Math.atan2(-b[1],-b[0]) : Math.atan2(GOAL.y-b[1],GOAL.x-b[0]); | |
| if(this.phase==='ball-detour') { | |
| const detour=[b[0]-.45*Math.cos(angle)-.4*Math.sin(angle),b[1]-.45*Math.sin(angle)+.4*Math.cos(angle)]; | |
| if(this.navigate(detour,null,.1))this.setPhase('ball-stage'); | |
| return; | |
| } | |
| if(this.phase==='ball-stage') { | |
| const staging=[b[0]-.45*Math.cos(angle),b[1]-.45*Math.sin(angle)+.035]; | |
| if(this.navigate(staging,angle,.1))this.setPhase('ball-approach'); | |
| return; | |
| } | |
| const target=[b[0]-.065*Math.cos(angle)-.03*Math.sin(angle),b[1]-.065*Math.sin(angle)+.03*Math.cos(angle)]; | |
| if(!safePoint(target)){this.finish(false);return;} | |
| if(this.navigate(target,angle,.025)){ | |
| this.wait=0;this.setPhase('ball-settle'); | |
| } | |
| } else if(pet.activity==='explore') { | |
| const phase=Math.floor(pet.clock/16)+pet.traits.curious*6; | |
| this.navigate([.6*Math.cos(phase*2.4),.6*Math.sin(phase*2.4)],null,.13); | |
| } | |
| } | |
| } | |