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
2 changes: 1 addition & 1 deletion src/experiments/evolution/evolution-birth.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {WIDTH,HEIGHT,ROAD_RADIUS,CAR_RADIUS,inspectBirth,positionAt,compareRuns} from './evolution-core.mjs';
import {WIDTH,HEIGHT,ROAD_RADIUS,CAR_RADIUS,inspectBirth,positionAt,compareRuns} from './evolution-core.mjs?v=road-distance-v1';

const result=run=>run.finished?`${run.time.toFixed(2)} 秒 · 完赛`:`未完赛 · 走到 ${(run.progress*100).toFixed(0)}%`;
function difference(before,after){
Expand Down
13 changes: 10 additions & 3 deletions src/experiments/evolution/evolution-core.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,16 @@ export function presetTrack(name='sweep'){
]);
throw Error('Unknown track preset');
}
function segmentDistance(p,a,b){
function withinRoadBoundary(p,a,b){
const dx=b.x-a.x,dy=b.y-a.y,den=dx*dx+dy*dy;
const t=den?clamp(((p.x-a.x)*dx+(p.y-a.y)*dy)/den,0,1):0;
return Math.hypot(p.x-a.x-dx*t,p.y-a.y-dy*t);
const x=p.x-a.x-dx*t,y=p.y-a.y-dy*t,distance2=x*x+y*y;
const limit=ROAD_RADIUS-CAR_RADIUS-1,limit2=limit*limit;
// Away from the boundary, comparing squared distances avoids a norm for
// every sample/segment pair. In this conservative floating-point rounding
// band, keep the original hypot decision (including the inclusive edge).
if(Math.abs(distance2-limit2)>limit2*Number.EPSILON*16)return distance2<limit2;
return Math.hypot(x,y)<=limit;
}
function validateObstacles(obstacles){
if(!Array.isArray(obstacles)||obstacles.length>12||obstacles.some(o=>!o||![o.x,o.y,o.radius].every(Number.isFinite)||o.x<0||o.x>WIDTH||o.y<0||o.y>HEIGHT||o.radius<=0||o.radius>60))throw Error('Invalid obstacle');
Expand All @@ -49,7 +55,8 @@ function blocked(p,track,obstacles){
// Sampling is <=2 units apart. One unit of extra clearance is conservative:
// distance-to-obstacle/road-boundary is 1-Lipschitz, including between samples.
if(obstacles.some(o=>distance(p,o)<=o.radius+CAR_RADIUS+1))return true;
return !track.points.slice(1).some((b,i)=>segmentDistance(p,track.points[i],b)<=ROAD_RADIUS-CAR_RADIUS-1);
for(let i=1;i<track.points.length;i++)if(withinRoadBoundary(p,track.points[i-1],track.points[i]))return false;
return true;
}
export function evaluateGenome(track,genes,obstacles=[]){
if(!Array.isArray(genes)||genes.length!==GENES||genes.some(n=>!Number.isFinite(n)||Math.abs(n)>1))throw Error('Invalid genome');
Expand Down
2 changes: 1 addition & 1 deletion src/experiments/evolution/evolution.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<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="./evolution.css?v=birth-cats-v1&amp;art=roadblock-pit-v1">
<script type="module" src="./evolution.mjs?v=birth-cats-v1&amp;art=roadblock-pit-v2"></script><title>算法游乐场 · 遗传赛车</title>
<script type="module" src="./evolution.mjs?v=birth-cats-v1&amp;art=roadblock-pit-v2&amp;perf=road-distance-v1"></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
4 changes: 2 additions & 2 deletions src/experiments/evolution/evolution.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {WIDTH,HEIGHT,POPULATION,ROAD_RADIUS,presetTrack,makeTrack,createRace,nextGeneration,positionAt,changeObstacles,suggestRoadblock,compareRuns} from './evolution-core.mjs';
import {createBirthView} from './evolution-birth.mjs?v=birth-cats-v1';
import {WIDTH,HEIGHT,POPULATION,ROAD_RADIUS,presetTrack,makeTrack,createRace,nextGeneration,positionAt,changeObstacles,suggestRoadblock,compareRuns} from './evolution-core.mjs?v=road-distance-v1';
import {createBirthView} from './evolution-birth.mjs?v=birth-cats-v1&perf=road-distance-v1';

const $=id=>document.getElementById(id),field=$('race'),ctx=field.getContext('2d');
const chart=$('history').getContext('2d'),geneCanvas=$('genes').getContext('2d');
Expand Down
2 changes: 1 addition & 1 deletion src/experiments/sand/sand.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<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="./sand.css?v=chouchou-bowl-v1">
<script type="module" src="./sand.mjs?v=chouchou-bowl-v1&amp;ui=bowl-focus-v1"></script><title>算法游乐场 · 落沙实验室</title>
<script type="module" src="./sand.mjs?v=chouchou-bowl-v1&amp;ui=bowl-focus-v1&amp;perf=hover-frame-v1"></script><title>算法游乐场 · 落沙实验室</title>
<script type="module" src="./sand-lesson-ui.mjs?v=chouchou-bowl-v1"></script>
<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">
Expand Down
21 changes: 20 additions & 1 deletion src/experiments/sand/sand.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const tips={splitter:'往屋顶尖端倒水,再擦掉一小段斜坡。两边
let scene='splitter',world=createWorld(scene),material=SAND,radius=2,stroke=null,cursor={x:36,y:5},showCursor=false;
let playing=!document.hidden&&!matchMedia('(prefers-reduced-motion:reduce)').matches,raf=null,lastTick=performance.now(),lastPour=0;
let history=createHistory(),pendingEdit=null,frameToken=0,activePaintKey=null;
let hoverRaf=null,hoverToken=0,hoverDirty=false;
const sceneNames={splitter:'分流器',hourglass:'沙漏',empty:'空白','cat-bowl':'臭臭的水碗'},editNames=['擦除','倒沙','倒水','筑墙'];
const unit=canvas.width/world.width;
const currentState=()=>snapshot(scene,world);
Expand All @@ -30,7 +31,21 @@ function applyPaint(from,to){
if(changed){if(pendingEdit)pendingEdit.changed=true;history=discardFuture(history);}
}
function simulate(){history=discardFuture(history);world=stepWorld(world);}
function cancelHoverRender(){
hoverToken++;if(hoverRaf!==null){cancelAnimationFrame(hoverRaf);hoverRaf=null;}
}
function scheduleHoverRender(){
if(hoverRaf!==null||document.hidden)return;
const token=hoverToken;
hoverRaf=requestAnimationFrame(()=>{
if(token!==hoverToken)return;
hoverRaf=null;if(!document.hidden)render();
});
}
function render(){
// A real edit or simulation frame already includes the latest cursor. Only
// hover previews may be deferred; paint segments and history stay synchronous.
cancelHoverRender();hoverDirty=false;
const brushHint=names[material]+' · '+sizes[radius]+'笔刷'+(material===EMPTY?',拖动擦除':material===WALL?',拖动筑墙':',按住持续倒下');
if($('brush-preview').textContent!==brushHint)$('brush-preview').textContent=brushHint;
ctx.fillStyle='#152023';ctx.fillRect(0,0,canvas.width,canvas.height);
Expand Down Expand Up @@ -91,6 +106,7 @@ function frame(now){
if(dirty)render();schedule();
}
function stop(){
cancelHoverRender();
playing=false;frameToken++;if(raf!==null){cancelAnimationFrame(raf);raf=null;}controls();
}
function endStroke(){
Expand Down Expand Up @@ -123,7 +139,10 @@ canvas.addEventListener('pointermove',event=>{
if(stroke){
if(event.pointerId!==stroke.id)return;
extendStroke(event);
}else if(p&&event.pointerType==='mouse'){cursor=p;showCursor=true;render();}
}else if(p&&event.pointerType==='mouse'){
if(showCursor&&!hoverDirty&&cursor.x===p.x&&cursor.y===p.y)return;
cursor=p;showCursor=true;hoverDirty=true;scheduleHoverRender();
}
});
canvas.addEventListener('pointerup',event=>{
if(!stroke||event.pointerId!==stroke.id)return;
Expand Down
91 changes: 91 additions & 0 deletions tests/experiments/evolution/evolution-performance.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFile} from 'node:fs/promises';
import {makeTrack,evaluateGenome,createRace,nextGeneration,presetTrack,changeObstacles,suggestRoadblock} from '../../../src/experiments/evolution/evolution-core.mjs';

// Source-only tests do not race the build used by browser/UI verification.
const source=await readFile(new URL('../../../src/experiments/evolution/evolution-core.mjs',import.meta.url),'utf8');
const load=code=>import('data:text/javascript;base64,'+Buffer.from(code).toString('base64'));
const {boundaryBlocked}=await load(source+'\nexport {blocked as boundaryBlocked};');
// Freeze the pre-optimization collision predicate, not a second gameplay model.
// The public race/selection pipeline stays shared; only this numerical kernel
// is replaced so full samples, scores, RNG, births and records can be compared.
const legacyBlocked=`function blocked(p,track,obstacles){
if(obstacles.some(o=>Math.hypot(p.x-o.x,p.y-o.y)<=o.radius+CAR_RADIUS+1))return true;
return !track.points.slice(1).some((b,i)=>{
const a=track.points[i],dx=b.x-a.x,dy=b.y-a.y,den=dx*dx+dy*dy;
const t=den?clamp(((p.x-a.x)*dx+(p.y-a.y)*dy)/den,0,1):0;
return Math.hypot(p.x-a.x-dx*t,p.y-a.y-dy*t)<=ROAD_RADIUS-CAR_RADIUS-1;
});
}
`;
const legacySource=source.replace(/function blocked\(p,track,obstacles\)\{[\s\S]*?(?=export function evaluateGenome)/,legacyBlocked);
assert.notEqual(legacySource,source,'the differential harness must install the frozen collision predicate');
const legacy=await load(legacySource+'\nexport {blocked as boundaryBlocked};');

test('a centered race avoids per-sample road-segment hypot work while keeping its real result',()=>{
const track=makeTrack([{x:80,y:240},{x:820,y:240}]),original=Math.hypot;
let calls=0,run;
try{
Math.hypot=(...args)=>{calls++;return original(...args);};
run=evaluateGenome(track,Array(24).fill(0));
}finally{Math.hypot=original;}
assert.equal(run.finished,true);
assert.ok(Math.abs(run.time-7.4)<1e-8);
// This path is far inside the road: only route geometry needs a norm.
// A call budget tied to route vertices catches restoring the sample×segment
// hot loop without a flaky wall-clock or device-speed assertion.
assert.ok(calls<=track.points.length*2,`${calls} hypot calls for ${track.points.length} route vertices`);
});

test('road boundary keeps legacy hypot decisions even when squared rounding disagrees',()=>{
const degenerate={points:[{x:0,y:0},{x:0,y:0}]};
const fixtures=[
{x:37,y:0,blocked:false},
{x:37-1e-10,y:0,blocked:false},
{x:37+1e-10,y:0,blocked:true},
// Hand-checked opposite ULP cases: hypot is 37, then 37.00000000000001.
{x:36.999934268454155,y:0.0697433156093402,blocked:false},
{x:36.99999116275657,y:0.025572562164266156,blocked:true}
];
for(const {x,y,blocked} of fixtures)assert.equal(boundaryBlocked({x,y},degenerate,[]),blocked);
});

test('road segment projection clamps endpoints and tolerates a duplicate vertex',()=>{
const track={points:[{x:0,y:0},{x:0,y:0},{x:100,y:0}]};
for(const [point,blocked] of [
[{x:50,y:37},false],[{x:50,y:37.001},true],
[{x:-37,y:0},false],[{x:-37.001,y:0},true],
[{x:137,y:0},false],[{x:137.001,y:0},true]
])assert.equal(boundaryBlocked(point,track,[]),blocked);
// Obstacles retain their separate inclusive radius + car + clearance rule.
assert.equal(boundaryBlocked({x:20,y:0},track,[{x:0,y:0,radius:15}]),true);
assert.equal(boundaryBlocked({x:20.001,y:0},track,[{x:0,y:0,radius:15}]),false);
});

test('rotated near-boundary projections preserve the old predicate on both sides of the rounding band',()=>{
for(let i=0;i<256;i++){
const angle=i*Math.PI/128,dx=Math.cos(angle),dy=Math.sin(angle);
const a={x:450,y:240},b={x:a.x+100*dx,y:a.y+100*dy},track={points:[a,b]};
for(const along of [0,.5,1])for(const offset of [-64,-2,0,2,64]){
const radius=37*(1+offset*Number.EPSILON);
const p={x:a.x+along*(b.x-a.x)-radius*dy,y:a.y+along*(b.y-a.y)+radius*dx};
assert.equal(boundaryBlocked(p,track,[]),legacy.boundaryBlocked(p,track,[]),`${i}/${along}/${offset}`);
}
}
});

test('full races and adaptation records exactly match the old kernel across presets, seeds and generations',()=>{
for(const preset of ['sweep','hairpin','slalom'])for(const seed of [1,42,12345]){
let current=createRace(presetTrack(preset),{seed}),before=legacy.createRace(legacy.presetTrack(preset),{seed});
assert.deepEqual(current,before,`${preset}/${seed}/initial`);
for(let generation=0;generation<6;generation++){
if(generation===3){
const obstacle=suggestRoadblock(current);
if(obstacle){current=changeObstacles(current,[obstacle]);before=legacy.changeObstacles(before,[obstacle]);assert.deepEqual(current,before,`${preset}/${seed}/roadblock`);}
}
current=nextGeneration(current);before=legacy.nextGeneration(before);
assert.deepEqual(current,before,`${preset}/${seed}/generation-${generation+2}`);
}
}
});
91 changes: 88 additions & 3 deletions tests/experiments/sand/sand-history-ui.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@ import {readFile} from 'node:fs/promises';
let serial=0;
async function boot({reduced=true,hidden=false}={}){
const html=await readFile(new URL('../../../dist/sand.html',import.meta.url),'utf8');let doc;
const pixels=new Map();
const ctx=new Proxy({fillRect(x,y,w,h){if(w===864&&h===576)pixels.clear();else if(w===12&&h===12)pixels.set(`${x},${y}`,this.fillStyle);}},{get:(o,k)=>o[k]??(()=>{})});
const pixels=new Map(),drawing={worlds:0,fills:0,cursor:null};
const ctx=new Proxy({
fillRect(x,y,w,h){drawing.fills++;if(w===864&&h===576){drawing.worlds++;drawing.cursor=null;pixels.clear();}else if(w===12&&h===12)pixels.set(`${x},${y}`,this.fillStyle);},
arc(x,y,r){drawing.cursor={x,y,r};}
},{get:(o,k)=>o[k]??(()=>{})});
class Element extends EventTarget{
constructor(){super();this.dataset={};this.attrs={};this.value='';this.width=864;this.height=576;this.disabled=false;this.captures=new Set();this.textContent='';}
setAttribute(k,v){this.attrs[k]=String(v);}getAttribute(k){return this.attrs[k];}getContext(){return ctx;}
Expand All @@ -26,7 +29,7 @@ async function boot({reduced=true,hidden=false}={}){
const restore=()=>{for(const[k,d]of old)d?Object.defineProperty(globalThis,k,d):delete globalThis[k];};
try{await import(new URL('../../../dist/sand.mjs?history-test='+ ++serial,import.meta.url));}catch(e){restore();throw e;}
const fire=(el,type,props={})=>{const e=Object.assign(new Event(type,{cancelable:true}),props);el.dispatchEvent(e);return e;};
return {els,doc,frames,stage,win,restore,pixels:()=>new Map(pixels),
return {els,doc,frames,stage,win,restore,drawing,pixels:()=>new Map(pixels),
click:id=>{const el=els.get(id);assert.ok(el,`missing control ${id}`);if(!el.disabled)fire(el,'click');},
scene:name=>fire(scenes.find(e=>e.dataset.scene===name),'click'),
material:value=>fire(materials.find(e=>e.dataset.material===String(value)),'click'),
Expand All @@ -39,6 +42,88 @@ async function boot({reduced=true,hidden=false}={}){
stamp(x=8,y=10){this.pointer('pointerdown',x,y);this.pointer('pointerup',x,y);}};
}

test('mouse preview merges a burst into one frame at the final cell without changing the world',async()=>{
const u=await boot();try{
const before=u.pixels(),draws=u.drawing.worlds,counts=['sand','water','wall'].map(u.count);
for(let i=0;i<120;i++)u.pointer('pointermove',i%60,10);
assert.equal(u.drawing.worlds,draws,'hover should not synchronously redraw the whole world for every event');
assert.equal(u.frames.size,1,'a paused world only needs one pending preview frame');
u.tick(1000);
assert.equal(u.drawing.worlds,draws+1);assert.deepEqual(u.drawing.cursor,{x:714,y:126,r:30});
assert.deepEqual(u.pixels(),before);assert.deepEqual(['sand','water','wall'].map(u.count),counts);
assert.equal(u.els.get('tick-count').textContent,'第 0 拍');assert.equal(u.els.get('history-undo').disabled,true);
assert.equal(u.frames.size,0,'hover must not start a permanent loop or simulation');
}finally{u.restore();}
});

test('same-cell hover does no new painting, while leaving and returning restores the preview',async()=>{
const u=await boot();try{
u.pointer('pointermove');u.tick(1000);const draws=u.drawing.worlds,fills=u.drawing.fills;
for(let i=0;i<120;i++)u.pointer('pointermove');
assert.equal(u.frames.size,0);assert.equal(u.drawing.worlds,draws);assert.equal(u.drawing.fills,fills);
u.pointer('pointerleave');assert.equal(u.drawing.cursor,null);
u.pointer('pointermove');assert.equal(u.frames.size,1);u.tick(1100);
assert.deepEqual(u.drawing.cursor,{x:102,y:126,r:30});assert.equal(u.frames.size,0);
}finally{u.restore();}
});

test('a real stroke supersedes pending hover and preserves every painted segment and undo checkpoint',async()=>{
const u=await boot();try{
u.scene('empty');u.material(3);u.brush(0);const before=u.pixels();
u.pointer('pointermove',2,2);const stale=[...u.frames.values()];
assert.equal(stale.length,1);
u.pointer('pointerdown',8,10);u.pointer('pointermove',20,10);u.pointer('pointerup',25,10);
assert.equal(u.count('wall'),18,'paint and the final pointerup segment stay synchronous');
assert.deepEqual(u.drawing.cursor,{x:306,y:126,r:6});assert.equal(u.frames.size,0);
const after=u.pixels(),draws=u.drawing.worlds;stale.forEach(fn=>fn(1000));
assert.equal(u.drawing.worlds,draws);assert.deepEqual(u.pixels(),after);
u.click('history-undo');assert.deepEqual(u.pixels(),before);assert.equal(u.count('wall'),0);
u.click('history-redo');assert.deepEqual(u.pixels(),after);assert.equal(u.count('wall'),18);
}finally{u.restore();}
});

test('simulation render absorbs queued hover without an extra world redraw or simulation tick',async()=>{
const u=await boot({reduced:false});try{
const draws=u.drawing.worlds;u.pointer('pointermove',20,10);u.tick(10000);
assert.equal(u.drawing.worlds,draws+1);assert.equal(u.els.get('tick-count').textContent,'第 1 拍');
assert.deepEqual(u.drawing.cursor,{x:246,y:126,r:30});assert.equal(u.frames.size,1);
u.click('play');assert.equal(u.frames.size,0);
}finally{u.restore();}
});

test('hidden pages and pagehide cancel hover, including an already-dispatched stale callback',async()=>{
for(const event of ['visibilitychange','pagehide']){
const u=await boot();try{
u.pointer('pointermove',12,10);const stale=[...u.frames.values()],draws=u.drawing.worlds,before=u.pixels();
assert.equal(stale.length,1);
if(event==='visibilitychange'){u.doc.hidden=true;u.doc.dispatchEvent(new Event(event));}
else u.win.dispatchEvent(new Event(event));
assert.equal(u.frames.size,0);stale.forEach(fn=>fn(1000));
assert.equal(u.drawing.worlds,draws);assert.deepEqual(u.pixels(),before);
assert.equal(u.els.get('tick-count').textContent,'第 0 拍');assert.equal(u.els.get('history-undo').disabled,true);
u.doc.hidden=false;u.pointer('pointermove',12,10);assert.equal(u.frames.size,1,'the cancelled cursor has not actually been drawn, even in the same cell');u.tick(1100);
assert.deepEqual(u.drawing.cursor,{x:150,y:126,r:30});
}finally{u.restore();}
}
});

test('pausing before hover is drawn still allows the same-cell preview to appear',async()=>{
const u=await boot({reduced:false});try{
u.pointer('pointermove',12,10);u.click('play');assert.equal(u.frames.size,0);
u.pointer('pointermove',12,10);assert.equal(u.frames.size,1);u.tick(1000);
assert.deepEqual(u.drawing.cursor,{x:150,y:126,r:30});assert.equal(u.els.get('tick-count').textContent,'第 0 拍');
}finally{u.restore();}
});

test('keyboard preview updates immediately and invalidates pending mouse preview',async()=>{
const u=await boot();try{
u.pointer('pointermove',12,10);const stale=[...u.frames.values()];assert.equal(stale.length,1);u.key('ArrowRight');
assert.deepEqual(u.drawing.cursor,{x:162,y:126,r:30});assert.equal(u.frames.size,0);
const draws=u.drawing.worlds;stale.forEach(fn=>fn(1000));assert.equal(u.drawing.worlds,draws);
u.key('Enter');u.key('Enter',{},'keyup');assert.ok(u.count('sand')>0);
}finally{u.restore();}
});

test('a background initial load stays paused and starts with one Continue without losing its world',async()=>{
const u=await boot({reduced:false,hidden:true});try{
const initial=u.pixels();
Expand Down
Loading