Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions src/experiments/firefly/firefly-beat-ui.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {createBeatLesson,selectBeatCase,guessBeat,runBeat,retryBeat,createCatBeatScene,runCatBeat} from './firefly-beat.mjs?v=pond-bobby-v1';
import {createBeatLesson,selectBeatCase,guessBeat,runBeat,retryBeat,createCatBeatScene,runCatBeat} from './firefly-beat.mjs?v=firefly-render-v1';

const names={faster:'加快追上',slower:'放慢等一等',same:'照自己的节拍走'};
const contexts={ahead:'三只邻居此刻领先 ¼ 圈。它们和金色这只的天生步速完全相同。',behind:'三只邻居此刻落后 ¼ 圈。它们和金色这只的天生步速完全相同。',out:'邻居仍领先 ¼ 圈,但距离在听见范围外。这只还会追上去吗?'};
Expand Down Expand Up @@ -99,7 +99,19 @@ export function mountBeatLesson({document=globalThis.document,onStart=()=>{}}={}
});
$('beat-retry').addEventListener('click',()=>{prepare();state=retryBeat(state);index=0;render();$('beat-faster').focus({preventScroll:true});});
$('beat-scrub').addEventListener('input',()=>{if(!state.comparison)return;prepare();const value=Number($('beat-scrub').value);index=Number.isFinite(value)?Math.max(0,Math.min(30,Math.round(value))):0;renderFrames();});
function schedule(){const current=token;raf=requestAnimationFrame(now=>{if(current!==token||document.hidden)return;raf=null;if(origin===null)origin=now;index=Math.min(30,startIndex+Math.floor((now-origin)*30/2000));if(index<30)schedule();renderFrames();});}
function schedule(){
const current=token;
raf=requestAnimationFrame(now=>{
if(current!==token||document.hidden)return;
raf=null;if(origin===null)origin=now;
const previous=index;
index=Math.min(30,startIndex+Math.floor((now-origin)*30/2000));
if(index<30)schedule();
// This replay shows recorded beats, not interpolated animation. Preserve
// the DOM until the beat changes, including the final stopped state.
if(index!==previous)renderFrames();
});
}
$('beat-replay').addEventListener('click',()=>{
if(!state.comparison||reduced||document.hidden)return;
if(raf!==null){stop();renderFrames();return;}
Expand Down
2 changes: 1 addition & 1 deletion src/experiments/firefly/firefly-beat.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {TAU,stepSwarm,configureSwarm,perturbSwarm} from './firefly-core.mjs?v=pond-bobby-v1';
import {TAU,stepSwarm,configureSwarm,perturbSwarm} from './firefly-core.mjs?v=firefly-render-v1';

const copy=world=>({...world,settings:{...world.settings},points:world.points.map(p=>({...p}))});
const scenarios=new Set(['ahead','behind','out']),guesses=new Set(['faster','slower','same']);
Expand Down
4 changes: 2 additions & 2 deletions src/experiments/firefly/firefly.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="description" content="点乱一片萤火,看看它们如何重新找到同一个节拍。可交互的相位同步算法实验。">
<meta name="color-scheme" content="light dark"><link rel="icon" href="data:,">
<link rel="stylesheet" href="./style.css"><link rel="stylesheet" href="./firefly.css?v=pond-bobby-v1"><link rel="stylesheet" href="./firefly-beat.css?v=pond-bobby-v1">
<script type="module" src="./firefly.mjs?v=pond-bobby-v1&amp;entry=bobby-tap"></script><title>算法游乐场 · 萤火虫合奏</title>
<link rel="stylesheet" href="./style.css"><link rel="stylesheet" href="./firefly.css?v=firefly-render-v1"><link rel="stylesheet" href="./firefly-beat.css?v=firefly-render-v1">
<script type="module" src="./firefly.mjs?v=firefly-render-v1&amp;entry=bobby-tap"></script><title>算法游乐场 · 萤火虫合奏</title>
<link rel="stylesheet" href="./navigation.css?v=three-cat-brand-v1"><script type="module" src="./navigation.mjs?v=cats-in-scenes-v1"></script>
<link rel="stylesheet" href="./space-theme.css">
<link rel="stylesheet" href="./experiment-showcase.css?v=home-aligned-v1">
Expand Down
11 changes: 7 additions & 4 deletions src/experiments/firefly/firefly.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {TAU,createSwarm,stepSwarm,coherence,configureSwarm,perturbSwarm,measureGroups,createListening,advanceListening,chooseListening,listeningOutcome,answerListening} from './firefly-core.mjs?v=pond-bobby-v1';
import {mountBeatLesson} from './firefly-beat-ui.mjs?v=pond-bobby-v1&entry=bobby-tap';
import {TAU,createSwarm,stepSwarm,coherence,configureSwarm,perturbSwarm,measureGroups,createListening,advanceListening,chooseListening,listeningOutcome,answerListening} from './firefly-core.mjs?v=firefly-render-v1';
import {mountBeatLesson} from './firefly-beat-ui.mjs?v=firefly-render-v1&entry=bobby-tap';

const $=id=>document.getElementById(id),field=$('fireflies'),ctx=field.getContext('2d');
const clock=$('phase-clock').getContext('2d'),chart=$('history').getContext('2d');
Expand Down Expand Up @@ -152,8 +152,11 @@ if(!ctx||!clock||!chart){
function frame(now){
raf=null;if(!playing||document.hidden)return;
if(last!==null)accumulator+=Math.min(.1,(now-last)/1000);last=now;
while(accumulator>=DT&&playing){tick();accumulator-=DT;}
draw();schedule();
let advanced=false;
while(accumulator>=DT&&playing){tick();accumulator-=DT;advanced=true;}
// Display refreshes may outnumber the fixed simulation steps. Inputs still
// draw immediately; an unchanged animation frame needs no duplicate paint.
if(advanced)draw();schedule();
}
function cancelGesture(){gesture=null;}
function pause(message){document.dispatchEvent(new Event('firefly-world-action'));playing=false;cancelGesture();if(raf!==null)cancelAnimationFrame(raf);raf=null;last=null;accumulator=0;controls(message);draw();}
Expand Down
27 changes: 24 additions & 3 deletions tests/experiments/firefly/firefly-beat-ui.test.mjs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFile,access} from 'node:fs/promises';
async function boot({reduced=false,hash='#listening-lesson'}={}){
async function boot({reduced=false,hash='#listening-lesson',source=false}={}){
const html=await readFile(new URL('../../../dist/firefly.html',import.meta.url),'utf8');
assert.match(html,/id="beat-open"/,'the microscope needs a real user entry point');
const file=new URL('../../../dist/firefly-beat-ui.mjs',import.meta.url);assert.ok(await access(file).then(()=>true,()=>false));
const file=new URL(`../../../${source?'src/experiments/firefly':'dist'}/firefly-beat-ui.mjs`,import.meta.url);assert.ok(await access(file).then(()=>true,()=>false));
let doc,pauses=0,seq=0;
class Element extends EventTarget{
constructor(){super();this.dataset={};this.attrs={};this.hidden=false;this.disabled=false;this.value='';this.textContent='';this.innerHTML='';}
constructor(){super();this.dataset={};this.attrs={};this.hidden=false;this.disabled=false;this.value='';this.textContent='';this.htmlWrites=0;this.innerHTML='';}
set innerHTML(value){this.html=value;this.htmlWrites++;}get innerHTML(){return this.html;}
setAttribute(k,v){this.attrs[k]=String(v);}getAttribute(k){return this.attrs[k];}
focus(){doc.activeElement=this;}scrollIntoView(options){doc.scrollTarget=this;doc.scrollOptions=options;}
}
Expand All @@ -27,6 +28,26 @@ async function boot({reduced=false,hash='#listening-lesson'}={}){
visible(value){doc.hidden=!value;doc.dispatchEvent(new Event('visibilitychange'));},
reduce(value){media.matches=value;media.dispatchEvent(Object.assign(new Event('change'),{matches:value}));}};
}
test('slow replay draws each of its 30 recorded beats once on a 120Hz screen',async()=>{
const u=await boot({source:true});try{
const e=id=>u.els.get(id);
u.click('beat-open');u.click('beat-faster');u.click('beat-run');
const sealed=e('beat-numbers').textContent,finalDial=e('beat-after').innerHTML;
u.click('beat-replay');
const writes=e('beat-after').htmlWrites,before=e('beat-before').innerHTML;
assert.match(e('beat-replay').textContent,/暂停/);
u.frame(0);u.frame(1000/120);
assert.equal(e('beat-after').htmlWrites,writes,'no DOM replacement while the recorded beat is unchanged');
for(let i=2;i<=240;i++)u.frame(i*1000/120);
assert.equal(e('beat-after').htmlWrites-writes,30);
assert.equal(e('beat-scrub').value,'30');assert.equal(u.frames.size,0);
assert.equal(e('beat-after').innerHTML,finalDial);
assert.equal(e('beat-before').innerHTML,before);
assert.equal(e('beat-numbers').textContent,sealed,'slow playback cannot change the sealed experiment');
assert.match(e('beat-replay').textContent,/慢放/,'the final beat must restore the replay action');
}finally{u.restore();}
});

test('the listening heading offers one optional native link to the cat beat',async()=>{
const html=await readFile(new URL('../../../dist/firefly.html',import.meta.url),'utf8');
const links=[...html.matchAll(/<a\b[^>]*href="#cat-beat"[^>]*>/g)];
Expand Down
27 changes: 23 additions & 4 deletions tests/experiments/firefly/firefly-ui.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@ test('mobile reading order reaches scene settings before secondary observation c
}
});
let bootNumber=0;
async function boot({hidden=false,reducedMotion=false}={}){
async function boot({hidden=false,reducedMotion=false,source=false}={}){
const frames=new Map();let nextFrame=0;
const paints={field:0,gradients:0};
const arcs=[];
const context={createRadialGradient:()=>({addColorStop(){}})};
const context={createRadialGradient:()=>{paints.gradients++;return {addColorStop(){}};}};
for(const name of ['fillRect','beginPath','arc','fill','stroke','setLineDash','ellipse','moveTo','lineTo','clearRect','fillText'])context[name]=()=>{};
context.fillRect=()=>{paints.field++;};
context.setLineDash=values=>{context.dash=[...values];};
context.arc=(...args)=>arcs.push({args,dash:[...(context.dash||[])]});
class Element extends EventTarget{
Expand All @@ -42,15 +44,32 @@ async function boot({hidden=false,reducedMotion=false}={}){
const previous=new Map(Object.keys(globals).map(key=>[key,Object.getOwnPropertyDescriptor(globalThis,key)]));
const restore=()=>{for(const [key,descriptor] of previous)if(descriptor)Object.defineProperty(globalThis,key,descriptor);else delete globalThis[key];};
Object.assign(globalThis,globals);
try{await import(new URL(`../../../dist/firefly.mjs?lifecycle-test=${++bootNumber}`,import.meta.url));}
try{await import(new URL(`../../../${source?'src/experiments/firefly':'dist'}/firefly.mjs?lifecycle-test=${++bootNumber}`,import.meta.url));}
catch(error){restore();throw error;}
return {document,frames,elements,arcs,restore,visible(value){document.hidden=!value;document.dispatchEvent(new Event('visibilitychange'));}};
return {document,frames,elements,arcs,paints,restore,
frame(now){const pending=[...frames.values()];frames.clear();for(const callback of pending)callback(now);},
visible(value){document.hidden=!value;document.dispatchEvent(new Event('visibilitychange'));}};
}
const press=(field,key,repeat=false)=>field.dispatchEvent(Object.assign(new Event('keydown',{cancelable:true}),{key,repeat}));
function tap(field,x,y){
for(const name of ['pointerdown','pointerup'])field.dispatchEvent(Object.assign(new Event(name),{pointerId:1,pointerType:'touch',isPrimary:true,button:0,clientX:x,clientY:y}));
}

test('high-refresh playback redraws the pond only after a real simulation step',async()=>{
const ui=await boot({source:true});try{
const initial={...ui.paints};
ui.frame(0);ui.frame(1000/120);
assert.equal(ui.paints.field-initial.field,0,'unchanged 120Hz frames must not rebuild the pond');
assert.equal(ui.paints.gradients-initial.gradients,0);
for(let i=2;i<720;i++)ui.frame(i*1000/120);
ui.frame(6001);
assert.equal(ui.paints.field-initial.field,360,'six simulated seconds still run 360 original steps');
assert.equal(ui.paints.gradients-initial.gradients,360*81,'each changed frame keeps all 80 original fireflies and the backdrop');
assert.equal(ui.elements.get('elapsed').textContent,'6.0 秒');
assert.equal(ui.frames.size,1,'skipping a redraw must not stop the simulation clock');
}finally{ui.restore();}
});

test('range legend distinguishes the adjustable neighbor radius from the fixed direct intervention',async()=>{
const ui=await boot({reducedMotion:true});
try{
Expand Down
Loading