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
6 changes: 6 additions & 0 deletions .github/workflows/archive-check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@ permissions:
jobs:
validate:
runs-on: ubuntu-latest
timeout-minutes: 25
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: 22
Expand Down Expand Up @@ -50,6 +52,10 @@ jobs:
sudo apt-get install -y fonts-noto-cjk
npm install --prefix "$RUNNER_TEMP/gallery-tools" --no-package-lock --no-save sharp@0.35.4 playwright@1.63.0
"$RUNNER_TEMP/gallery-tools/node_modules/.bin/playwright" install --with-deps chromium
- name: Compare full-detail performance with the previous release
run: node scripts/garden-performance-check.mjs
env:
GALLERY_TOOLS_DIR: ${{ runner.temp }}/gallery-tools
- name: Check realistic seasons, attachments and camera interactions in cloud Chromium
run: node scripts/garden-browser-check.mjs
env:
Expand Down
7 changes: 4 additions & 3 deletions app/garden/SeasonGarden.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,22 +62,23 @@ export default function SeasonGarden(){
const c=control.current,dt=last?Math.min((now-last)/1000,.1):0;last=now;
if(!c.paused){time+=dt;if(c.automatic)c.elapsed+=dt;}
if(c.revision!==previousRevision){
previousRevision=c.revision;dirty=true;renderer.shadowMap.needsUpdate=true;
previousRevision=c.revision;dirty=true;
if(c.reset!==previousReset){previousReset=c.reset;home();}
}
orbit.enableDamping=!c.paused&&!reduce.matches;
renderer.shadowMap.autoUpdate=!c.paused;
renderer.shadowMap.autoUpdate=false;
const changed=orbit.update();
if(changed)dirty=true;
if(dirty||(!c.paused&&now-lastRender>(low?33:24))){
const sampled=sampleSeason(c.elapsed);
model.updateGarden(world,sampled,time);
if(model.updateGarden(world,sampled,time))renderer.shadowMap.needsUpdate=true;
presentation.render();
const labelKey=sampled.from+":"+sampled.to;
if(labelKey!==previousLabel){previousLabel=labelKey;setSeason(sampled);}
element.dataset.season=sampled.label;
element.dataset.seasonMix=sampled.mix.toFixed(4);
element.dataset.weatherTime=time.toFixed(3);
element.dataset.weatherPaused=String(c.paused);
element.dataset.camera=camera.position.toArray().concat(orbit.target.toArray()).map((n:number)=>n.toFixed(3)).join(",");
dirty=false;lastRender=now;
}
Expand Down
54 changes: 36 additions & 18 deletions app/garden/world.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,16 @@ export function buildGarden(low=false,assets={}){
dummy.scale.set(.0027,length+.004,.0027);dummy.updateMatrix();petioles.setMatrixAt(i,dummy.matrix);
});
group.add(petioles);
// Full-size bounds are computed once and cover every later seasonal size.
const baseMatrices=new Float64Array(seeds.length*16);
seeds.forEach((s,i)=>{
dummy.position.copy(s.petioleEnd);dummy.quaternion.copy(s.quaternion);dummy.scale.setScalar(s.scale);dummy.updateMatrix();
leaves.setMatrixAt(i,dummy.matrix);dummy.matrix.toArray(baseMatrices,i*16);leaves.setColorAt(i,color.set("#ffffff"));
});
// One draw per tree, with fixed maximum-growth bounds; the shadow pass
// tests these bounds against its own light frustum, not the viewer's.
leaves.computeBoundingSphere();leaves.boundingSphere.radius+=.12;leaves.frustumCulled=true;
petioles.computeBoundingSphere();petioles.frustumCulled=true;
const snow=new T.Mesh(bark.geometry,new T.MeshStandardMaterial({color:"#e7edf0",roughness:1,transparent:true,opacity:0,polygonOffset:true,polygonOffsetFactor:-1}));
snow.material.onBeforeCompile=shader=>{
shader.vertexShader="varying float gardenUp;\n"+shader.vertexShader;
Expand All @@ -235,7 +245,7 @@ export function buildGarden(low=false,assets={}){
};
snow.material.depthWrite=false;
snow.scale.setScalar(1.018);group.add(snow);
trees.push({group,bark,leaves,petioles,seeds,shoots,snow});
trees.push({group,bark,leaves,petioles,seeds,shoots,snow,baseMatrices});
}
// Grass blades form the clearing, not a floating pedestal.
const grassGeo=new T.PlaneGeometry(.045,.4,1,4);grassGeo.translate(0,.2,0);
Expand All @@ -248,17 +258,17 @@ export function buildGarden(low=false,assets={}){
const az=random()*TAU,r=Math.sqrt(random())*12,x=Math.cos(az)*r,z=Math.sin(az)*r;
dummy.position.set(x,terrainY(x,z),z);dummy.rotation.set((random()-.5)*.4,random()*TAU, (random()-.5)*.4);dummy.scale.setScalar(.3+random()*.9);dummy.updateMatrix();grass.setMatrixAt(i,dummy.matrix);
}
scene.add(grass);
grass.computeBoundingSphere();grass.frustumCulled=true;scene.add(grass);
const count=low?180:440,seeds=[],positions=new Float32Array(count*3),rainPositions=new Float32Array(count*6);
for(let i=0;i<count;i++)seeds.push({x:(random()-.5)*24,y:random()*13,z:(random()-.5)*18,phase:random()*TAU,speed:.5+random()});
const particlesGeo=new T.BufferGeometry();particlesGeo.setAttribute("position",new T.BufferAttribute(positions,3));
const particlesGeo=new T.BufferGeometry();particlesGeo.setAttribute("position",new T.BufferAttribute(positions,3).setUsage(T.DynamicDrawUsage));
const particleMat=new T.ShaderMaterial({transparent:true,depthWrite:false,uniforms:{tint:{value:new T.Color("#ffe4d3")},size:{value:6},alpha:{value:.5}},vertexShader:`
uniform float size;void main(){vec4 p=modelViewMatrix*vec4(position,1.);gl_PointSize=clamp(size*18./-p.z,1.,12.);gl_Position=projectionMatrix*p;}
`,fragmentShader:`
uniform vec3 tint;uniform float alpha;void main(){float d=length(gl_PointCoord-.5);float a=1.-smoothstep(.12,.5,d);gl_FragColor=vec4(tint,a*alpha);}
`});
const particles=new T.Points(particlesGeo,particleMat);particles.frustumCulled=false;scene.add(particles);
const rainGeo=new T.BufferGeometry();rainGeo.setAttribute("position",new T.BufferAttribute(rainPositions,3));
const rainGeo=new T.BufferGeometry();rainGeo.setAttribute("position",new T.BufferAttribute(rainPositions,3).setUsage(T.DynamicDrawUsage));
const rainMat=new T.LineBasicMaterial({color:"#b3d3df",transparent:true,opacity:0,depthWrite:false});
const rain=new T.LineSegments(rainGeo,rainMat);rain.frustumCulled=false;scene.add(rain);
const falling=new T.InstancedMesh(leafGeo,surfaces.leaf,low?14:26);falling.frustumCulled=false;scene.add(falling);
Expand All @@ -267,17 +277,19 @@ export function buildGarden(low=false,assets={}){
const az=random()*TAU,r=Math.sqrt(random())*3.1,x=(i%2===0?-2.7:2.8)+Math.cos(az)*r,z=Math.sin(az)*r;
dummy.position.set(x,terrainY(x,z)+.025,z);dummy.rotation.set(-Math.PI/2,0,random()*TAU);dummy.scale.setScalar(.45+random()*.65);dummy.updateMatrix();fallen.setMatrixAt(i,dummy.matrix);color.set("#be6c29").lerp(new T.Color("#ddae54"),random());fallen.setColorAt(i,color);
}
return {scene,assets,wind,snowWeight,surfaces,trees,ground,grass,mountains,sky,light,hemi,fill,particles,particleMat,positions,rain,rainMat,rainPositions,particleSeeds:seeds,falling,fallen,leafDepth,seasonKey:"",low};
return {scene,assets,wind,snowWeight,surfaces,trees,ground,grass,mountains,sky,light,hemi,fill,particles,particleMat,positions,rain,rainMat,rainPositions,particleSeeds:seeds,falling,fallen,leafDepth,seasonKey:"",lastTime:NaN,low,scratch:{sun:new T.Vector3(),origin:new T.Vector3(),dummy:new T.Object3D(),color:new T.Color()}};
}
export function updateGarden(w,state,time){
const {from,to,mix}=state,a=palette[from],b=palette[to];
const key=[from,to,mix.toFixed(3)].join(":");
if(w.lastTime===time&&w.lastFrom===from&&w.lastTo===to&&w.lastMix===mix)return false;
w.lastTime=time;w.lastFrom=from;w.lastTo=to;w.lastMix=mix;
const blend=key=>new T.Color(a[key]).lerp(new T.Color(b[key]),mix);
const weight=i=>(from===i?1-mix:0)+(to===i?mix:0);
const spring=weight(0),summer=weight(1),autumn=weight(2),winter=weight(3);
w.wind.value=time;w.snowWeight.value=winter;
const sunshine=new T.Vector3(.32,.25+summer*.035-winter*.07+Math.sin(time*.055)*.018,-.92).normalize();
const sunshine=w.scratch.sun.set(.32,.25+summer*.035-winter*.07+Math.sin(time*.055)*.018,-.92).normalize();
w.sky.material.uniforms.sunPosition.value.copy(sunshine);w.light.position.copy(sunshine).multiplyScalar(25);
const key=[from,to,mix.toFixed(3)].join(":");
if(w.seasonKey!==key){
w.seasonKey=key;w.scene.background.copy(blend("sky"));w.scene.fog.color.copy(blend("fog"));
w.scene.fog.near=28;w.scene.fog.far=110;
Expand All @@ -288,16 +300,16 @@ export function updateGarden(w,state,time){
w.sky.material.uniforms.rayleigh.value=1.4+autumn*.7-winter*.4;
w.sky.material.uniforms.turbidity.value=3+spring*2+winter*4;
w.surfaces.bark.color.set("#d0c2ae");
const c1=blend("leaf"),c2=blend("tip"),dummy=new T.Object3D(),color=new T.Color();
const c1=blend("leaf"),c2=blend("tip");
for(const tree of w.trees){
tree.snow.material.opacity=winter*.9;tree.snow.visible=winter>.01;tree.petioles.visible=winter<.99;
tree.leaves.visible=winter<1;
const matrices=tree.leaves.instanceMatrix.array,colors=tree.leaves.instanceColor.array,base=tree.baseMatrices;
for(let i=0;i<tree.seeds.length;i++){
const s=tree.seeds[i];
// Individual leaf shedding exposes the full twig structure in winter.
const density=Math.max(0,1-winter-autumn*s.drop*.58);
const size=s.scale*density*(.82+summer*.18);
dummy.position.copy(s.petioleEnd);dummy.quaternion.copy(s.quaternion);dummy.scale.setScalar(size);dummy.updateMatrix();tree.leaves.setMatrixAt(i,dummy.matrix);
color.copy(c1).lerp(c2,s.tone);tree.leaves.setColorAt(i,color);
const s=tree.seeds[i],growth=Math.max(0,1-winter-autumn*s.drop*.58)*(.82+summer*.18),m=i*16,c=i*3;
// Same basal transform as before, without rebuilding 7,920 quaternions.
for(let column=0;column<3;column++)for(let row=0;row<3;row++){const j=column*4+row;matrices[m+j]=base[m+j]*growth;}
colors[c]=c1.r+(c2.r-c1.r)*s.tone;colors[c+1]=c1.g+(c2.g-c1.g)*s.tone;colors[c+2]=c1.b+(c2.b-c1.b)*s.tone;
}
tree.leaves.instanceMatrix.needsUpdate=true;tree.leaves.instanceColor.needsUpdate=true;
}
Expand All @@ -316,13 +328,16 @@ export function updateGarden(w,state,time){
const y=((s.y-time*8*s.speed)%13+13)%13;
w.rainPositions[k]=s.x;w.rainPositions[k+1]=y;w.rainPositions[k+2]=s.z;w.rainPositions[k+3]=s.x+.07;w.rainPositions[k+4]=y+.35;w.rainPositions[k+5]=s.z;
}
w.particles.geometry.attributes.position.needsUpdate=true;w.rain.geometry.attributes.position.needsUpdate=true;
const dummy=new T.Object3D(),color=new T.Color();
w.particles.visible=w.particleMat.uniforms.alpha.value>0;w.rain.visible=w.rainMat.opacity>0;
if(w.particles.visible)w.particles.geometry.attributes.position.needsUpdate=true;if(w.rain.visible)w.rain.geometry.attributes.position.needsUpdate=true;
const {dummy,color,origin}=w.scratch;
if(w.falling.visible){
for(const tree of w.trees)tree.group.updateWorldMatrix(true,false);
for(let i=0;i<w.falling.count;i++){
const tree=w.trees[i%2],s=tree.seeds[(i*137)%tree.seeds.length];
const speed=.12+s.drop*.055,life=((time*speed+s.tone)%1+1)%1;
tree.group.updateMatrixWorld();
const origin=s.petioleEnd.clone().applyMatrix4(tree.group.matrixWorld),duration=1/speed,age=life*duration;
origin.copy(s.petioleEnd).applyMatrix4(tree.group.matrixWorld);
const duration=1/speed,age=life*duration;
const floor=terrainY(origin.x,origin.z)+.03;
// Shed from actual canopy attachments, then descend; no spring leaf confetti.
dummy.position.set(origin.x+Math.sin(age*1.2+s.tone*TAU)*life*.65,Math.max(floor,origin.y-age*age*.16),origin.z+Math.sin(age*.7)*life*.42);
Expand All @@ -332,10 +347,13 @@ export function updateGarden(w,state,time){
color.set("#c68832");w.falling.setColorAt(i,color);
}
w.falling.instanceMatrix.needsUpdate=true;w.falling.instanceColor.needsUpdate=true;
}
return true;
}
export function disposeGarden(w){
const geometries=new Set(),materials=new Set(),textures=new Set(Object.values(w.assets));
w.scene.traverse(o=>{if(o.geometry)geometries.add(o.geometry);if(o.material)(Array.isArray(o.material)?o.material:[o.material]).forEach(m=>materials.add(m));});
for(const m of Object.values(w.surfaces))materials.add(m);
for(const tree of w.trees){materials.add(tree.petioles.material);geometries.add(tree.petioles.geometry);}
materials.add(w.leafDepth);geometries.forEach(g=>g.dispose());materials.forEach(m=>m.dispose());textures.forEach(t=>t.dispose());
}
14 changes: 14 additions & 0 deletions scripts/garden-browser-check.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,20 @@ try{
// Keep camera verification independent of Chromium's extra WebGL readback.

results.push("Desktop: drag rotate, wheel zoom, right pan, exact reset, paused interaction");
// Exercise zoom while full weather/shadows are animating, not just paused QA.
const frozenTime=Number(await scene.getAttribute("data-weather-time"));
await page.getByRole("button",{name:"播放天气",exact:true}).click();
await page.waitForFunction(t=>Number(document.querySelector(".garden-canvas").dataset.weatherTime)>t+.05,frozenTime);
const activeBefore=await camera();await page.mouse.move(x,y);
for(let i=0;i<5;i++)await page.mouse.wheel(0,-70);
await page.waitForFunction(c=>document.querySelector(".garden-canvas").dataset.camera!==c,activeBefore);
await page.getByRole("button",{name:"暂停天气",exact:true}).click();
await page.waitForFunction(()=>document.querySelector(".garden-canvas").dataset.weatherPaused==="true");
const pausedTime=await scene.getAttribute("data-weather-time");
const pausedBefore=await camera();await page.mouse.move(x,y);await page.mouse.wheel(0,200);
await page.waitForFunction(c=>document.querySelector(".garden-canvas").dataset.camera!==c,pausedBefore);
assert.equal(await scene.getAttribute("data-weather-time"),pausedTime);
results.push("Active-weather wheel zoom, pause, and further paused zoom remain responsive");
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
await context.close();
// Mobile uses real Chromium touch events, not synthetic mouse aliases.
Expand Down
53 changes: 53 additions & 0 deletions scripts/garden-perf-page.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import * as T from "three";
const query=new URLSearchParams(location.search),model=await import(/* @vite-ignore */ query.get("model"));
const assets=await model.loadGardenAssets(),world=model.buildGarden(false,assets);
const renderer=new T.WebGLRenderer({antialias:true,alpha:false,powerPreference:"high-performance"});
renderer.setSize(1000,700);renderer.setPixelRatio(1);
renderer.toneMapping=T.ACESFilmicToneMapping;renderer.toneMappingExposure=1.05;
renderer.shadowMap.enabled=true;renderer.shadowMap.type=T.PCFSoftShadowMap;
document.body.style.margin="0";document.body.appendChild(renderer.domElement);
const camera=new T.PerspectiveCamera(40,1000/700,.2,250),gl=renderer.getContext();
const pixel=new Uint8Array(4);
// Chromium intentionally implements WebGL finish as flush. Synchronous CPU
// readback is required for this benchmark to include completed GPU work.
const complete=()=>gl.readPixels(0,0,1,1,gl.RGBA,gl.UNSIGNED_BYTE,pixel);
const stats=values=>{const s=values.toSorted((a,b)=>a-b);return {p50:s[Math.floor(s.length*.5)],p95:s[Math.min(s.length-1,Math.floor(s.length*.95))]};};
const state=(season,mix=0)=>({from:season,to:mix?(season+1)%4:season,mix});
function pose(view){
if(view==="overview"){camera.position.set(2.28,5.25,19);camera.lookAt(0,2.4,0);}
if(view==="detail"){camera.position.set(-2.6,4.9,7);camera.lookAt(-2.6,4,0);}
if(view==="edge"){camera.position.set(-6,4,5.5);camera.lookAt(-6,4,0);}
camera.updateMatrixWorld();camera.updateProjectionMatrix();
}
window.measure=async(view,season,mix=0)=>{
pose(view);const sample=state(season,mix);
const cpu=[],completed=[],counts=[];
for(let i=0;i<4;i++){
const time=12+i/60,start=performance.now();model.updateGarden(world,sample,time);const simulated=performance.now();
renderer.info.autoReset=false;renderer.info.reset();renderer.render(world.scene,camera);
complete();const end=performance.now();
if(i>=1){cpu.push(simulated-start);completed.push(end-start);counts.push({...renderer.info.render});}
}
// A deterministic frame for image equivalence, independent of timing.
model.updateGarden(world,sample,12);renderer.render(world.scene,camera);complete();
return {view,season,mix,cpuMs:stats(cpu),completedFrameMs:stats(completed),draw:counts.at(-1)};
};
window.cpuMeasure=()=>{
const results={};
for(const [name,step] of [["hold",0],["transition",.003],["paused",null]]){
const values=[];model.updateGarden(world,state(0),12);
for(let round=0;round<4;round++){
const start=performance.now();
for(let i=0;i<60;i++)model.updateGarden(world,state(0,step===null?0:step*i),step===null?12:12+i/60);
if(round)values.push((performance.now()-start)/60);
}results[name]=stats(values);
}
return results;
};
window.inventory=()=>{
const geometries=[];
world.scene.traverse(o=>{if(o.isMesh){const vertices=o.geometry.attributes.position.count,triangles=o.geometry.index?o.geometry.index.count/3:vertices/3;geometries.push({vertices,triangles,count:o.isInstancedMesh?o.count:1});}});
return {leaves:world.trees.reduce((sum,t)=>sum+t.leaves.count,0),petioles:world.trees.reduce((sum,t)=>sum+t.petioles.count,0),grass:world.grass.count,
allocatedTriangles:geometries.reduce((sum,g)=>sum+g.triangles*g.count,0),shadowSize:world.light.shadow.mapSize.toArray(),pixelRatio:renderer.getPixelRatio()};
};
window.ready=true;
1 change: 1 addition & 0 deletions scripts/garden-perf.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<!doctype html><html><head><meta charset="utf-8"/></head><body><script type="module" src="/scripts/garden-perf-page.mjs"></script></body></html>
Loading
Loading