Optimise
All checks were successful
Check & deploy / build (pull_request) Successful in 1m51s

This commit is contained in:
Andras Schmelczer 2026-05-21 20:33:49 +01:00
commit ed5a4379db
69 changed files with 1418 additions and 988 deletions

View file

@ -22,12 +22,22 @@ export interface GardenAudioVibeProfile extends GardenAudioVibeSettings {
progression: Array<GardenAudioChord>;
}
export const defaultGardenAudioVibeSettings: GardenAudioVibeSettings = {
idleIntensity: 0.08,
bpm: 74,
rampUpIntensity: 0.85,
rampUpTime: 0.08,
noteLength: 0.42,
notePitchOffset: 0,
brightness: 1,
};
export const createGardenAudioConfig = () => ({
masterVolume: DEFAULT_AUDIO_VOLUME,
fadeInSeconds: 0.45,
updateRampSeconds: 0.08,
delay: {
timeSeconds: 0.46,
timeSeconds: 0.405,
feedback: 0.12,
wetGain: 0.044,
erasingActivity: 0.12,
@ -43,9 +53,9 @@ export const createGardenAudioConfig = () => ({
maxVoices: 24,
gain: 0.48,
sustainSeconds: 0.42,
sustainLevel: 0.32,
releaseSeconds: 0.24,
lowpassHz: 7600,
sustainLevel: 0.26,
releaseSeconds: 0.34,
lowpassHz: 7000,
gainAttackSeconds: 0.006,
lowpassMaxHz: 12000,
lowpassMinHz: 1400,
@ -53,8 +63,8 @@ export const createGardenAudioConfig = () => ({
sustainVelocityRange: 0.55,
},
rhythm: {
idleIntensity: 0.08,
bpm: 74,
idleIntensity: defaultGardenAudioVibeSettings.idleIntensity,
bpm: defaultGardenAudioVibeSettings.bpm,
stepsPerBeat: 4,
stepsPerBar: 16,
sparseActivity: 0.055,
@ -69,9 +79,7 @@ export const createGardenAudioConfig = () => ({
pianoActivity: 0,
},
energy: {
attackSeconds: 0.08,
decaySeconds: 0.9,
immediateActivityScale: 0.85,
releaseSeconds: 1.15,
strokeDecaySeconds: 0.32,
},

View file

@ -13,7 +13,10 @@ export const getStrokeMetrics = (stroke: GardenAudioStroke): GardenAudioStrokeMe
const dy = stroke.to[1] - stroke.from[1];
const distancePixels = Math.hypot(dx, dy);
const elapsedSeconds = Math.max(minElapsedSeconds, stroke.elapsedSeconds ?? 0);
const normalizationPixels = Math.max(1, Math.min(stroke.canvasSize[0], stroke.canvasSize[1]));
const normalizationPixels = Math.max(
1,
Math.min(stroke.canvasSize[0], stroke.canvasSize[1])
);
const normalizedDistance = distancePixels / normalizationPixels;
return {

View file

@ -260,11 +260,10 @@ export class GardenAudio {
}
public stroke(stroke: GardenAudioStroke): void {
if (this.lifecycle === 'destroyed' || this.isMuted) {
if (this.lifecycle !== 'started' || this.isMuted) {
return;
}
this.start(stroke.vibe);
const context = this.graph.context;
if (!context) {
return;

View file

@ -207,8 +207,8 @@ export const generativePianoTuning: GenerativePianoTuning = {
},
{
midiMin: 62,
midiMax: 81,
preferredMidi: 72,
midiMax: 78,
preferredMidi: 70,
pan: 0.18,
scaleDegrees: [2, 3, 4, 6],
},
@ -254,10 +254,10 @@ export const generativePianoTuning: GenerativePianoTuning = {
expressionMultiplier: 0.9,
},
padChord: {
velocities: [0.052, 0.041, 0.033],
expressionVelocityWeight: 0.02,
velocities: [0.046, 0.036, 0.029],
expressionVelocityWeight: 0.018,
delaySend: 0.008,
lowpassExpressionWeight: 0.28,
lowpassExpressionWeight: 0.24,
},
supportNote: {
velocityBase: 0.105,
@ -316,7 +316,7 @@ export const generativePianoTuning: GenerativePianoTuning = {
brushStream: {
inferredManiaThreshold: 0.82,
inferredManiaRange: 0.18,
registerManiaShift: 0.45,
registerManiaShift: 0.3,
chordToneEverySteps: 4,
durationBaseSeconds: 0.48,
durationIntensitySeconds: 0.08,
@ -329,22 +329,22 @@ export const generativePianoTuning: GenerativePianoTuning = {
delaySendMin: 0.006,
delaySendMax: 0.032,
velocityBase: 0.1,
velocityIntensityWeight: 0.13,
velocityIntensityWeight: 0.1,
lowpassBaseExpression: 0.39,
lowpassIntensityWeight: 0.48,
lowpassManiaWeight: 0.18,
intenseThreshold: 0.62,
intenseThreshold: 0.68,
activeThreshold: 0.34,
},
brushStreamEcho: {
maniaThreshold: 0.86,
stepModulo: 2,
maniaThreshold: 0.92,
stepModulo: 3,
stepRemainder: 1,
intensityThreshold: 0.95,
octaveSemitones: 12,
maxMidi: 88,
velocityBase: 0.045,
velocityIntensityWeight: 0.05,
maxMidi: 84,
velocityBase: 0.035,
velocityIntensityWeight: 0.04,
durationMinSeconds: 0.11,
durationScale: 0.68,
panScale: -0.75,
@ -361,7 +361,7 @@ export const generativePianoTuning: GenerativePianoTuning = {
lowOffset: -1,
},
registerBias: {
maniaShiftSemitones: 4,
maniaShiftSemitones: 2,
midiMin: 36,
midiMaxForMin: 86,
minimumSpan: 4,
@ -375,7 +375,7 @@ export const generativePianoTuning: GenerativePianoTuning = {
lowpass: {
midiBase: 48,
midiRange: 33,
midiLiftHz: 720,
midiLiftHz: 500,
expressionBase: 0.58,
expressionWeight: 0.32,
},
@ -396,16 +396,16 @@ export const generativePianoTuning: GenerativePianoTuning = {
strokeAccentMinSteps: 12,
strokeAccentThreshold: 0.58,
maxBrushPhraseLayers: 3,
maxBrushStreamNotesPerBar: 9,
maxBrushStreamNotesPerBar: 7,
brushLayerBaseSeconds: 5.5,
brushLayerEnergySeconds: 2.5,
brushLayerMinIntensity: 0.12,
brushStreamIdleIntervalBeats: 2,
brushStreamActiveIntervalBeats: 1,
brushStreamIntenseIntervalBeats: 0.5,
brushStreamIntenseIntervalBeats: 0.75,
brushMotifMaxSteps: 8,
brushMotifCanonDelaySeconds: 0.055,
padDurationBarScale: 0.46,
padDurationBarScale: 0.82,
};
export const styleVoices: [

View file

@ -196,7 +196,8 @@ export class GenerativePianoEngine {
if (
this.isWaitingForGestureAccent &&
now - this.lastGestureAccentAt >= generativePianoTuning.gestureAccentMinIntervalSeconds
now - this.lastGestureAccentAt >=
generativePianoTuning.gestureAccentMinIntervalSeconds
) {
this.recordTouchDown({
vibe,
@ -554,7 +555,9 @@ export class GenerativePianoEngine {
const chordIntervals = getChordIntervals(chord, false);
const degrees = this.rotate(
pool.scaleDegrees,
Math.round(strength * generativePianoTuning.gestureAccent.rotationStrengthMultiplier)
Math.round(
strength * generativePianoTuning.gestureAccent.rotationStrengthMultiplier
)
);
const midi = this.chooseMidi(
@ -705,7 +708,9 @@ export class GenerativePianoEngine {
);
layer.motifOffsets.push(this.getMotifOffset(strength));
if (layer.motifOffsets.length > generativePianoTuning.brushMotifMaxSteps) {
layer.motifOffsets = layer.motifOffsets.slice(-generativePianoTuning.brushMotifMaxSteps);
layer.motifOffsets = layer.motifOffsets.slice(
-generativePianoTuning.brushMotifMaxSteps
);
}
}
@ -789,7 +794,9 @@ export class GenerativePianoEngine {
const chordIntervals = getChordIntervals(chord, false);
const rootMidi = profile.rootMidi + chord.rootOffset;
const useChordTone =
this.brushStreamNoteIndex % generativePianoTuning.brushStream.chordToneEverySteps === 0;
this.brushStreamNoteIndex %
generativePianoTuning.brushStream.chordToneEverySteps ===
0;
const source = useChordTone
? {
baseMidi: rootMidi,
@ -897,7 +904,8 @@ export class GenerativePianoEngine {
layer.energy *
this.getBrushPhraseFade(layer, startTime) *
(generativePianoTuning.brushPhrase.layerIntensityBase +
layer.maniaAmount * generativePianoTuning.brushPhrase.layerIntensityManiaWeight),
layer.maniaAmount *
generativePianoTuning.brushPhrase.layerIntensityManiaWeight),
}));
const dominant = layerStates.reduce<{
layer: BrushPhraseLayer;
@ -1073,7 +1081,8 @@ export class GenerativePianoEngine {
}
return (
barIndex % generativePianoTuning.supportBarSpacing === generativePianoTuning.supportBarOffset
barIndex % generativePianoTuning.supportBarSpacing ===
generativePianoTuning.supportBarOffset
);
}
@ -1136,7 +1145,8 @@ export class GenerativePianoEngine {
): number {
const midiLift =
clamp01(
(midi - generativePianoTuning.lowpass.midiBase) / generativePianoTuning.lowpass.midiRange
(midi - generativePianoTuning.lowpass.midiBase) /
generativePianoTuning.lowpass.midiRange
) * generativePianoTuning.lowpass.midiLiftHz;
return clamp(
this.config.piano.lowpassHz *

View file

@ -7,8 +7,6 @@ import { getLoadedPianoSamples, loadPianoSamples } from './piano-samples';
export const PIANO_SCHEDULE_AHEAD_SECONDS = 0.002;
type PianoLoadState = 'idle' | 'loading' | 'loaded';
interface ActivePianoVoice {
gain: GainNode;
source: AudioScheduledSourceNode;
@ -27,7 +25,6 @@ const pianoSamplerTuning = {
};
export class PianoSampler {
private loadState: PianoLoadState = 'idle';
private samples: Array<LoadedPianoSample> = [];
private activeVoices: Array<ActivePianoVoice> = [];
@ -37,27 +34,19 @@ export class PianoSampler {
) {}
public load(context: BaseAudioContext): Promise<void> {
if (this.loadState === 'loaded') {
if (this.samples.length > 0) {
return Promise.resolve();
}
const loadedSamples = getLoadedPianoSamples();
if (loadedSamples) {
this.setSamples(loadedSamples);
this.loadState = 'loaded';
return Promise.resolve();
}
this.loadState = 'loading';
return loadPianoSamples(context)
.then((samples) => {
this.setSamples(samples);
this.loadState = 'loaded';
})
.catch((error) => {
this.loadState = 'idle';
throw error;
});
return loadPianoSamples(context).then((samples) => {
this.setSamples(samples);
});
}
public play({
@ -154,7 +143,6 @@ export class PianoSampler {
}
public reset(): void {
this.loadState = 'idle';
this.samples = [];
this.activeVoices = [];
}

View file

@ -5,6 +5,11 @@ import type { GardenAppConfig } from './config/types';
import { defaultVibeId, vibePresets } from './config/vibe-presets';
import { APP_STORAGE_KEYS, DEFAULT_AUDIO_VOLUME } from './consts';
export {
normalizeNumberControlValue,
normalizeRuntimeSettings,
} from './config/normalize-runtime-settings';
export type {
GardenAppConfig,
GardenRuntimeSettings,
@ -107,8 +112,6 @@ export const appConfig = {
stroke: {
densityMultiplier: 110,
maxAgentCount: 2_400,
minAgentCount: 140,
minSegmentLengthPx: 1,
},
},
storage: {

View file

@ -19,7 +19,7 @@ const computeDefaultInternalRenderAreaMegapixels = (): number => {
const dpr = Math.min(Math.max(rawDpr, 1), DEFAULT_DEVICE_PIXEL_RATIO_CAP);
const cssWidth = typeof window !== 'undefined' ? window.innerWidth : 1920;
const cssHeight = typeof window !== 'undefined' ? window.innerHeight : 1080;
const cssMegapixels = Math.max(cssWidth, 1) * Math.max(cssHeight, 1) / 1_000_000;
const cssMegapixels = (Math.max(cssWidth, 1) * Math.max(cssHeight, 1)) / 1_000_000;
return Math.min(
INTERNAL_RENDER_AREA_BOUNDS.max,
Math.max(INTERNAL_RENDER_AREA_BOUNDS.min, dpr * dpr * cssMegapixels)

View file

@ -0,0 +1,46 @@
import type {
GardenAppConfig,
GardenRuntimeSettings,
NumberControlConfig,
} from './types';
type RuntimeSettingControls = GardenAppConfig['runtimeSettings']['controls'];
export const normalizeNumberControlValue = (
value: number,
config: NumberControlConfig
): number => {
if (config.options) {
const optionValues = Object.values(config.options);
if (optionValues.includes(value)) {
return value;
}
return optionValues.includes(0) ? 0 : (optionValues[0] ?? config.min ?? 0);
}
const min = config.min ?? Number.NEGATIVE_INFINITY;
const max = config.max ?? Number.POSITIVE_INFINITY;
const fallbackValue = config.min ?? 0;
const finiteValue = Number.isFinite(value) ? value : fallbackValue;
const clampedValue = Math.min(max, Math.max(min, finiteValue));
return config.integer ? Math.round(clampedValue) : clampedValue;
};
export const normalizeRuntimeSettings = (
settings: GardenRuntimeSettings,
controls: RuntimeSettingControls
): GardenRuntimeSettings => {
const normalized = { ...settings };
(
Object.entries(controls) as Array<
[keyof GardenRuntimeSettings, NumberControlConfig | undefined]
>
).forEach(([key, config]) => {
if (config) {
normalized[key] = normalizeNumberControlValue(normalized[key], config);
}
});
return normalized;
};

View file

@ -6,15 +6,15 @@ const formatRadiansAsDegrees = (value: number): string =>
`${Math.round((value * 180) / Math.PI)} deg`;
export const runtimeControls: GardenAppConfig['runtimeSettings']['controls'] = {
color1ToColor1: colorInteractionControl('Primary Follows Primary'),
color1ToColor2: colorInteractionControl('Primary Follows Secondary'),
color1ToColor3: colorInteractionControl('Primary Follows Accent'),
color2ToColor1: colorInteractionControl('Secondary Follows Primary'),
color2ToColor2: colorInteractionControl('Secondary Follows Secondary'),
color2ToColor3: colorInteractionControl('Secondary Follows Accent'),
color3ToColor1: colorInteractionControl('Accent Follows Primary'),
color3ToColor2: colorInteractionControl('Accent Follows Secondary'),
color3ToColor3: colorInteractionControl('Accent Follows Accent'),
color1ToColor1: colorInteractionControl('Color 1 Follows Color 1'),
color1ToColor2: colorInteractionControl('Color 1 Follows Color 2'),
color1ToColor3: colorInteractionControl('Color 1 Follows Color 3'),
color2ToColor1: colorInteractionControl('Color 2 Follows Color 1'),
color2ToColor2: colorInteractionControl('Color 2 Follows Color 2'),
color2ToColor3: colorInteractionControl('Color 2 Follows Color 3'),
color3ToColor1: colorInteractionControl('Color 3 Follows Color 1'),
color3ToColor2: colorInteractionControl('Color 3 Follows Color 2'),
color3ToColor3: colorInteractionControl('Color 3 Follows Color 3'),
brushSize: {
folder: 'Brush',
@ -25,7 +25,7 @@ export const runtimeControls: GardenAppConfig['runtimeSettings']['controls'] = {
},
spawnPerPixel: {
folder: 'Brush',
label: 'Agent Density',
label: 'Density',
min: 0.01,
max: 1,
step: 0.001,
@ -39,28 +39,28 @@ export const runtimeControls: GardenAppConfig['runtimeSettings']['controls'] = {
step: 0.01,
},
sensorOffsetDistance: {
folder: 'Agents',
folder: 'Movement',
label: 'Sensor Reach',
min: 0,
max: 200,
step: 1,
},
moveSpeed: {
folder: 'Agents',
folder: 'Movement',
label: 'Travel Speed',
min: 10,
max: 500,
step: 1,
},
turnSpeed: {
folder: 'Agents',
folder: 'Movement',
label: 'Turning Speed',
min: 1,
max: 200,
step: 1,
},
forwardRotationScale: {
folder: 'Agents',
folder: 'Movement',
format: formatPercent,
label: 'Forward Focus',
min: 0,
@ -68,21 +68,21 @@ export const runtimeControls: GardenAppConfig['runtimeSettings']['controls'] = {
step: 0.01,
},
turnWhenLost: {
folder: 'Agents',
folder: 'Movement',
label: 'Wander Turn',
min: 0,
max: 6.28,
step: 0.01,
},
individualTrailWeight: {
folder: 'Agents',
folder: 'Movement',
label: 'Trail Strength',
min: 0,
max: 1,
step: 0.001,
},
decayRateTrails: {
folder: 'Agents',
folder: 'Movement',
label: 'Trail Fade',
min: 800,
max: 1000,
@ -107,7 +107,7 @@ export const runtimeControls: GardenAppConfig['runtimeSettings']['controls'] = {
maxAgentCount: {
folder: 'Performance',
integer: true,
label: 'Agent Limit',
label: 'Population Limit',
min: 0,
step: 10_000,
},

View file

@ -22,6 +22,7 @@ export interface NumberControlConfig {
export type GardenRuntimeSettings = {
adaptiveCapInitial: number;
adaptiveCapMin: number;
backgroundGrainStrength: number;
brushCurveResolution: number;
brushCurveMinBrushRadius: number;
brushCurveMinSegmentSpacing: number;
@ -70,12 +71,14 @@ type GardenDefaultSettings = Omit<
>;
export enum VibeId {
CandyRain = 'candy-rain',
SunlitMoss = 'sunlit-moss',
CoralTide = 'coral-tide',
MoonOrchid = 'moon-orchid',
PeachNeon = 'peach-neon',
FrostBloom = 'frost-bloom',
AuroraMycelium = 'aurora-mycelium',
EmberCircuit = 'ember-circuit',
VelvetObservatory = 'velvet-observatory',
LichenSignal = 'lichen-signal',
UltravioletSiren = 'ultraviolet-siren',
TidepoolLantern = 'tidepool-lantern',
PaperLanternFog = 'paper-lantern-fog',
ChromePollen = 'chrome-pollen',
}
export interface VibePreset {
@ -181,8 +184,6 @@ export interface GardenAppConfig {
stroke: {
densityMultiplier: number;
maxAgentCount: number;
minAgentCount: number;
minSegmentLengthPx: number;
};
};
storage: {

View file

@ -1,166 +1,255 @@
import type { GardenAudioVibeSettings } from '../audio/garden-audio-config';
import { defaultGardenAudioVibeSettings } from '../audio/garden-audio-config';
import { VibeId, type VibePreset } from './types';
const defaultAudioSettings = {
idleIntensity: 0.08,
bpm: 74,
rampUpIntensity: 0.85,
rampUpTime: 0.08,
noteLength: 0.42,
notePitchOffset: 0,
} satisfies Omit<GardenAudioVibeSettings, 'brightness'>;
export const defaultVibeId = VibeId.CandyRain;
export const defaultVibeId = VibeId.AuroraMycelium;
export const vibePresets: Array<VibePreset> = [
{
id: VibeId.CandyRain,
name: 'Candy Rain',
id: VibeId.AuroraMycelium,
name: 'Aurora Mycelium',
colors: [
[255, 93, 162],
[54, 215, 208],
[255, 216, 77],
[78, 255, 176],
[154, 99, 255],
[169, 238, 255],
],
backgroundColor: [16, 21, 31],
backgroundColor: [6, 13, 22],
settings: {
backgroundGrainStrength: 0.018,
brushSize: 14,
clarity: 0.62,
decayRateTrails: 965,
individualTrailWeight: 0.07,
moveSpeed: 82,
sensorOffsetDistance: 38,
spawnPerPixel: 0.22,
turnSpeed: 58,
backgroundGrainStrength: 0.016,
brushSize: 20,
clarity: 0.52,
decayRateTrails: 988,
individualTrailWeight: 0.085,
moveSpeed: 54,
sensorOffsetDistance: 72,
spawnPerPixel: 0.13,
turnSpeed: 35,
},
audio: {
...defaultAudioSettings,
brightness: 1.04,
...defaultGardenAudioVibeSettings,
idleIntensity: 0.12,
bpm: 60,
rampUpIntensity: 0.7,
rampUpTime: 0.14,
noteLength: 0.86,
notePitchOffset: -2,
brightness: 0.84,
},
},
{
id: VibeId.SunlitMoss,
name: 'Sunlit Moss',
id: VibeId.EmberCircuit,
name: 'Ember Circuit',
colors: [
[131, 212, 131],
[246, 215, 107],
[94, 193, 161],
[255, 95, 38],
[255, 43, 132],
[43, 219, 255],
],
backgroundColor: [23, 32, 22],
backgroundColor: [17, 10, 8],
settings: {
backgroundGrainStrength: 0.014,
brushSize: 16,
clarity: 0.68,
decayRateTrails: 975,
individualTrailWeight: 0.06,
moveSpeed: 70,
sensorOffsetDistance: 46,
spawnPerPixel: 0.18,
turnSpeed: 44,
backgroundGrainStrength: 0.03,
brushSize: 8,
clarity: 0.82,
decayRateTrails: 918,
individualTrailWeight: 0.04,
moveSpeed: 150,
sensorOffsetDistance: 24,
spawnPerPixel: 0.31,
turnSpeed: 130,
},
audio: {
...defaultAudioSettings,
brightness: 0.92,
...defaultGardenAudioVibeSettings,
idleIntensity: 0.03,
bpm: 124,
rampUpIntensity: 1.35,
rampUpTime: 0.04,
noteLength: 0.18,
notePitchOffset: 7,
brightness: 1.34,
},
},
{
id: VibeId.CoralTide,
name: 'Coral Tide',
id: VibeId.VelvetObservatory,
name: 'Velvet Observatory',
colors: [
[255, 127, 110],
[64, 184, 255],
[244, 240, 166],
[72, 98, 255],
[255, 89, 176],
[235, 236, 255],
],
backgroundColor: [15, 24, 34],
backgroundColor: [7, 8, 20],
settings: {
backgroundGrainStrength: 0.022,
brushSize: 13,
clarity: 0.58,
decayRateTrails: 955,
individualTrailWeight: 0.055,
moveSpeed: 90,
sensorOffsetDistance: 35,
spawnPerPixel: 0.25,
turnSpeed: 62,
backgroundGrainStrength: 0.01,
brushSize: 24,
clarity: 0.45,
decayRateTrails: 992,
individualTrailWeight: 0.095,
moveSpeed: 45,
sensorOffsetDistance: 86,
spawnPerPixel: 0.1,
turnSpeed: 24,
},
audio: {
...defaultAudioSettings,
brightness: 1,
...defaultGardenAudioVibeSettings,
idleIntensity: 0.14,
bpm: 56,
rampUpIntensity: 0.6,
rampUpTime: 0.16,
noteLength: 1.15,
notePitchOffset: -5,
brightness: 0.72,
},
},
{
id: VibeId.MoonOrchid,
name: 'Moon Orchid',
id: VibeId.LichenSignal,
name: 'Lichen Signal',
colors: [
[201, 147, 255],
[125, 216, 255],
[240, 244, 255],
[174, 205, 91],
[71, 162, 126],
[229, 117, 71],
],
backgroundColor: [20, 18, 29],
backgroundColor: [18, 24, 17],
settings: {
backgroundGrainStrength: 0.018,
brushSize: 12,
clarity: 0.64,
decayRateTrails: 968,
backgroundGrainStrength: 0.028,
brushSize: 17,
clarity: 0.66,
decayRateTrails: 974,
individualTrailWeight: 0.065,
moveSpeed: 76,
sensorOffsetDistance: 42,
spawnPerPixel: 0.2,
turnSpeed: 52,
moveSpeed: 68,
sensorOffsetDistance: 52,
spawnPerPixel: 0.19,
turnSpeed: 38,
},
audio: {
...defaultAudioSettings,
brightness: 0.9,
...defaultGardenAudioVibeSettings,
idleIntensity: 0.1,
bpm: 68,
rampUpIntensity: 0.8,
rampUpTime: 0.1,
noteLength: 0.62,
notePitchOffset: -3,
brightness: 0.82,
},
},
{
id: VibeId.PeachNeon,
name: 'Peach Neon',
id: VibeId.UltravioletSiren,
name: 'Ultraviolet Siren',
colors: [
[255, 155, 115],
[91, 240, 169],
[110, 168, 255],
[184, 75, 255],
[0, 224, 255],
[214, 255, 72],
],
backgroundColor: [25, 23, 22],
backgroundColor: [13, 9, 31],
settings: {
backgroundGrainStrength: 0.024,
brushSize: 15,
clarity: 0.55,
decayRateTrails: 948,
individualTrailWeight: 0.05,
moveSpeed: 96,
sensorOffsetDistance: 32,
spawnPerPixel: 0.24,
turnSpeed: 70,
backgroundGrainStrength: 0.02,
brushSize: 11,
clarity: 0.72,
decayRateTrails: 946,
individualTrailWeight: 0.052,
moveSpeed: 118,
sensorOffsetDistance: 30,
spawnPerPixel: 0.28,
turnSpeed: 96,
},
audio: {
...defaultAudioSettings,
brightness: 1.08,
...defaultGardenAudioVibeSettings,
idleIntensity: 0.04,
bpm: 112,
rampUpIntensity: 1.2,
rampUpTime: 0.05,
noteLength: 0.25,
notePitchOffset: 5,
brightness: 1.22,
},
},
{
id: VibeId.FrostBloom,
name: 'Frost Bloom',
id: VibeId.TidepoolLantern,
name: 'Tidepool Lantern',
colors: [
[180, 247, 255],
[158, 200, 255],
[255, 184, 210],
[30, 219, 194],
[61, 118, 255],
[255, 191, 91],
],
backgroundColor: [16, 24, 32],
backgroundColor: [5, 20, 28],
settings: {
backgroundGrainStrength: 0.018,
brushSize: 15,
clarity: 0.6,
decayRateTrails: 963,
individualTrailWeight: 0.058,
moveSpeed: 88,
sensorOffsetDistance: 44,
spawnPerPixel: 0.22,
turnSpeed: 60,
},
audio: {
...defaultGardenAudioVibeSettings,
idleIntensity: 0.08,
bpm: 82,
rampUpIntensity: 0.95,
rampUpTime: 0.08,
noteLength: 0.48,
notePitchOffset: 0,
brightness: 0.98,
},
},
{
id: VibeId.PaperLanternFog,
name: 'Paper Lantern Fog',
colors: [
[255, 174, 104],
[242, 102, 107],
[132, 211, 185],
],
backgroundColor: [31, 23, 20],
settings: {
backgroundGrainStrength: 0.036,
brushSize: 22,
clarity: 0.5,
decayRateTrails: 984,
individualTrailWeight: 0.08,
moveSpeed: 56,
sensorOffsetDistance: 64,
spawnPerPixel: 0.14,
turnSpeed: 32,
},
audio: {
...defaultGardenAudioVibeSettings,
idleIntensity: 0.13,
bpm: 64,
rampUpIntensity: 0.72,
rampUpTime: 0.12,
noteLength: 0.9,
notePitchOffset: -4,
brightness: 0.76,
},
},
{
id: VibeId.ChromePollen,
name: 'Chrome Pollen',
colors: [
[235, 255, 238],
[255, 214, 48],
[77, 240, 157],
],
backgroundColor: [9, 13, 12],
settings: {
backgroundGrainStrength: 0.012,
brushSize: 18,
clarity: 0.7,
decayRateTrails: 982,
individualTrailWeight: 0.075,
moveSpeed: 62,
sensorOffsetDistance: 52,
spawnPerPixel: 0.16,
turnSpeed: 40,
brushSize: 10,
clarity: 0.9,
decayRateTrails: 935,
individualTrailWeight: 0.045,
moveSpeed: 104,
sensorOffsetDistance: 36,
spawnPerPixel: 0.24,
turnSpeed: 78,
},
audio: {
...defaultAudioSettings,
brightness: 0.88,
...defaultGardenAudioVibeSettings,
idleIntensity: 0.05,
bpm: 96,
rampUpIntensity: 1.05,
rampUpTime: 0.07,
noteLength: 0.3,
notePitchOffset: 3,
brightness: 1.18,
},
},
];

View file

@ -1,9 +1,6 @@
export const ENABLED_FLAG_VALUE = '1';
export const DISABLED_FLAG_VALUE = '0';
export const UNIT_INTERVAL_INPUT_MIN = '0';
export const UNIT_INTERVAL_INPUT_MAX = '1';
export const DEFAULT_AUDIO_VOLUME = 0.5;
export const APP_STORAGE_KEYS = {

View file

@ -0,0 +1,166 @@
import { vec2 } from 'gl-matrix';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { appConfig } from '../config';
import { type AgentGenerationPipeline } from '../pipelines/agents/agent-generation/agent-generation-pipeline';
import { AGENT_FLOAT_COUNT } from '../pipelines/agents/agent-limits';
import { settings } from '../settings';
import { AgentPopulation } from './agent-population';
import { type FramePerformance } from './frame-performance';
const originalSettings = {
brushSize: settings.brushSize,
maxAgentCount: settings.maxAgentCount,
selectedColorIndex: settings.selectedColorIndex,
spawnPerPixel: settings.spawnPerPixel,
strokeAngleJitterRadians: settings.strokeAngleJitterRadians,
};
class RecordingAgentGenerationPipeline {
public readonly writtenAgentCounts: Array<number> = [];
public readonly writtenAgentOffsets: Array<number> = [];
public readonly writtenBatches: Array<Float32Array> = [];
public readonly maxSupportedAgentCount = 1_000_000;
public maxAgentCount = 1_000_000;
private compactResolver: ((compactedAgentCount: number) => void) | null = null;
public ensureMaxAgentCount(requestedMaxAgentCount: number): number {
this.maxAgentCount = Math.max(this.maxAgentCount, requestedMaxAgentCount);
return this.maxAgentCount;
}
public writeAgents(agentOffset: number, data: Float32Array): void {
this.writtenAgentOffsets.push(agentOffset);
this.writtenAgentCounts.push(data.length / AGENT_FLOAT_COUNT);
this.writtenBatches.push(data.slice());
}
public compactAgents(): Promise<number> {
return new Promise((resolve) => {
this.compactResolver = resolve;
});
}
public finishCompaction(compactedAgentCount: number): void {
this.compactResolver?.(compactedAgentCount);
this.compactResolver = null;
}
}
const framePerformance = {
adaptiveCapDecreaseAgents: 0,
adaptiveCapInitial: 1_000_000,
adaptiveCapMin: 0,
hasAdaptiveCapHeadroom: true,
} as FramePerformance;
const createPopulation = (): {
pipeline: RecordingAgentGenerationPipeline;
population: AgentPopulation;
} => {
const pipeline = new RecordingAgentGenerationPipeline();
const population = new AgentPopulation(
pipeline as unknown as AgentGenerationPipeline,
0,
() => 1,
framePerformance
);
population.beginStroke();
return { pipeline, population };
};
const setSpawnRate = (agentsPerPixel: number): void => {
settings.spawnPerPixel = agentsPerPixel / appConfig.simulation.stroke.densityMultiplier;
};
describe('AgentPopulation stroke spawning', () => {
beforeEach(() => {
settings.brushSize = 0;
settings.maxAgentCount = 1_000_000;
settings.selectedColorIndex = 0;
settings.strokeAngleJitterRadians = 0;
setSpawnRate(1);
});
afterEach(() => {
Object.assign(settings, originalSettings);
});
it('spawns the same count for the same stroke length regardless of segmentation', () => {
const segmented = createPopulation();
for (let x = 0; x < 10; x++) {
segmented.population.spawnStrokeAgents(
vec2.fromValues(x, 0),
vec2.fromValues(x + 1, 0)
);
}
const singleSegment = createPopulation();
singleSegment.population.spawnStrokeAgents(
vec2.fromValues(0, 0),
vec2.fromValues(10, 0)
);
expect(segmented.population.activeAgentCount).toBe(10);
expect(singleSegment.population.activeAgentCount).toBe(10);
});
it('carries fractional spawn budget within a stroke', () => {
setSpawnRate(0.5);
const { population } = createPopulation();
population.spawnStrokeAgents(vec2.fromValues(0, 0), vec2.fromValues(1, 0));
expect(population.activeAgentCount).toBe(0);
population.spawnStrokeAgents(vec2.fromValues(1, 0), vec2.fromValues(2, 0));
expect(population.activeAgentCount).toBe(1);
population.spawnStrokeAgents(vec2.fromValues(2, 0), vec2.fromValues(3, 0));
expect(population.activeAgentCount).toBe(1);
population.spawnStrokeAgents(vec2.fromValues(3, 0), vec2.fromValues(4, 0));
expect(population.activeAgentCount).toBe(2);
});
it('chunks long stroke writes without clipping length-linear spawn counts', () => {
const { pipeline, population } = createPopulation();
const batchCapacity = appConfig.simulation.stroke.maxAgentCount;
const expectedAgentCount = batchCapacity + 10;
population.spawnStrokeAgents(
vec2.fromValues(0, 0),
vec2.fromValues(expectedAgentCount, 0)
);
expect(population.activeAgentCount).toBe(expectedAgentCount);
expect(pipeline.writtenAgentCounts).toEqual([batchCapacity, 10]);
});
it('spawns agents in the movement direction', () => {
const { pipeline, population } = createPopulation();
population.spawnStrokeAgents(vec2.fromValues(0, 0), vec2.fromValues(3, 0));
expect(population.activeAgentCount).toBe(3);
expect(pipeline.writtenBatches[0][2]).toBe(0);
});
it('queues stroke writes while async compaction is in flight', async () => {
const { pipeline, population } = createPopulation();
population.spawnStrokeAgents(vec2.fromValues(0, 0), vec2.fromValues(10, 0));
population.requestCompactionAfterErase();
population.compactAfterErase(false);
population.spawnStrokeAgents(vec2.fromValues(10, 0), vec2.fromValues(15, 0));
expect(population.activeAgentCount).toBe(10);
expect(pipeline.writtenAgentCounts).toEqual([10]);
pipeline.finishCompaction(6);
await population.waitForCompaction();
expect(population.activeAgentCount).toBe(11);
expect(pipeline.writtenAgentOffsets).toEqual([0, 6]);
expect(pipeline.writtenAgentCounts).toEqual([10, 5]);
});
});

View file

@ -1,10 +1,8 @@
import { vec2 } from 'gl-matrix';
import { appConfig } from '../config';
import {
AGENT_FLOAT_COUNT,
AgentGenerationPipeline,
} from '../pipelines/agents/agent-generation/agent-generation-pipeline';
import { AgentGenerationPipeline } from '../pipelines/agents/agent-generation/agent-generation-pipeline';
import { AGENT_FLOAT_COUNT, writeAgentValues } from '../pipelines/agents/agent-limits';
import { getSafePixelRatio } from '../pipelines/brush/brush-pipeline';
import { settings } from '../settings';
import type { FramePerformance } from './frame-performance';
@ -20,8 +18,8 @@ export class AgentPopulation {
private shouldCompactAfterErase = false;
private isCompacting = false;
private pendingCompaction: Promise<void> | null = null;
// Highest active slot written while async compaction is running.
private postCompactionWriteEnd = 0;
private readonly queuedAgentBatches: Array<Float32Array> = [];
private pendingStrokeAgentCount = 0;
private readonly strokeAgentData = new Float32Array(
appConfig.simulation.stroke.maxAgentCount * AGENT_FLOAT_COUNT
);
@ -64,16 +62,20 @@ export class AgentPopulation {
}
this.pipeline.writeAgents(0, data);
this.markPostCompactionWrite(0, data.length / AGENT_FLOAT_COUNT);
this.activeCount = data.length / AGENT_FLOAT_COUNT;
this.replacementCursor = 0;
}
public onVibeChanged(): void {
this.pendingStrokeAgentCount = 0;
this.adaptiveCap = this.clampAndEnsureAdaptiveCap(this.adaptiveCap);
this.trimActiveCountToBudget();
}
public beginStroke(): void {
this.pendingStrokeAgentCount = 0;
}
public resizeAgents(scale: vec2): void {
this.pipeline.resizeAgents(this.activeCount, scale);
}
@ -93,17 +95,13 @@ export class AgentPopulation {
}
this.isCompacting = true;
this.postCompactionWriteEnd = 0;
this.pendingCompaction = this.pipeline
.compactAgents(this.activeCount)
.then((compactedAgentCount) => {
const finiteCompactedAgentCount = Number.isFinite(compactedAgentCount)
? Math.max(0, Math.floor(compactedAgentCount))
: 0;
this.activeCount = Math.min(
this.activeCount,
Math.max(finiteCompactedAgentCount, this.postCompactionWriteEnd)
);
this.activeCount = Math.min(this.activeCount, finiteCompactedAgentCount);
this.clampReplacementCursor();
this.trimActiveCountToBudget();
})
@ -113,7 +111,7 @@ export class AgentPopulation {
.finally(() => {
this.isCompacting = false;
this.pendingCompaction = null;
this.postCompactionWriteEnd = 0;
this.flushQueuedAgentBatches();
});
}
@ -144,40 +142,86 @@ export class AgentPopulation {
public spawnStrokeAgents(from: vec2, to: vec2): void {
const deltaX = to[0] - from[0];
const deltaY = to[1] - from[1];
const length = Math.max(
appConfig.simulation.stroke.minSegmentLengthPx,
Math.hypot(deltaX, deltaY)
);
const count = Math.max(
appConfig.simulation.stroke.minAgentCount,
Math.min(
appConfig.simulation.stroke.maxAgentCount,
this.strokeAgentData.length / AGENT_FLOAT_COUNT,
Math.ceil(
length * settings.spawnPerPixel * appConfig.simulation.stroke.densityMultiplier
)
)
);
const length = Math.hypot(deltaX, deltaY);
const spawnRate = getStrokeSpawnRate();
if (!Number.isFinite(length) || length <= 0 || spawnRate <= 0) {
return;
}
const expectedAgentCount = length * spawnRate + this.pendingStrokeAgentCount;
if (!Number.isFinite(expectedAgentCount)) {
this.pendingStrokeAgentCount = 0;
return;
}
const count = Math.floor(expectedAgentCount);
this.pendingStrokeAgentCount = expectedAgentCount - count;
if (count <= 0) {
return;
}
const baseAngle = Math.atan2(deltaY, deltaX);
const spread = settings.brushSize * getSafePixelRatio(this.getCanvasPixelRatio());
const batchCapacity = this.strokeAgentData.length / AGENT_FLOAT_COUNT;
if (batchCapacity <= 0) {
return;
}
for (let i = 0; i < count; i++) {
const t = count === 1 ? 1 : i / (count - 1);
for (let written = 0; written < count; written += batchCapacity) {
const batchCount = Math.min(batchCapacity, count - written);
this.populateStrokeAgentBatch({
baseAngle,
batchCount,
from,
spread,
to,
totalCount: count,
written,
});
this.writeAgentBatch(
this.strokeAgentData.subarray(0, batchCount * AGENT_FLOAT_COUNT)
);
}
}
private populateStrokeAgentBatch({
baseAngle,
batchCount,
from,
spread,
to,
totalCount,
written,
}: {
baseAngle: number;
batchCount: number;
from: vec2;
spread: number;
to: vec2;
totalCount: number;
written: number;
}): void {
for (let i = 0; i < batchCount; i++) {
const agentIndex = written + i;
const t = totalCount === 1 ? 0.5 : agentIndex / (totalCount - 1);
const x = from[0] + (to[0] - from[0]) * t;
const y = from[1] + (to[1] - from[1]) * t;
const angle = baseAngle + (Math.random() - 0.5) * settings.strokeAngleJitterRadians;
const base = i * AGENT_FLOAT_COUNT;
this.strokeAgentData[base] = x + (Math.random() - 0.5) * spread;
this.strokeAgentData[base + 1] = y + (Math.random() - 0.5) * spread;
this.strokeAgentData[base + 2] = angle;
this.strokeAgentData[base + 3] = settings.selectedColorIndex;
this.strokeAgentData[base + 4] = -1;
this.strokeAgentData[base + 5] = -1;
this.strokeAgentData[base + 6] = angle;
this.strokeAgentData[base + 7] = 0;
}
const positionX = x + (Math.random() - 0.5) * spread;
const positionY = y + (Math.random() - 0.5) * spread;
this.writeAgentBatch(this.strokeAgentData.subarray(0, count * AGENT_FLOAT_COUNT));
writeAgentValues(this.strokeAgentData, i, {
positionX,
positionY,
angle,
colorIndex: settings.selectedColorIndex,
targetPositionX: -1,
targetPositionY: -1,
targetAngle: angle,
introDelay: 0,
});
}
}
private writeAgentBatch(data: Float32Array): void {
@ -185,6 +229,11 @@ export class AgentPopulation {
return;
}
if (this.isCompacting) {
this.queuedAgentBatches.push(data.slice());
return;
}
const count = data.length / AGENT_FLOAT_COUNT;
this.adaptiveCap = this.clampAndEnsureAdaptiveCap(this.adaptiveCap);
this.expandAdaptiveCapForPendingAgents(count);
@ -197,7 +246,6 @@ export class AgentPopulation {
this.activeCount,
data.subarray(0, appendCount * AGENT_FLOAT_COUNT)
);
this.markPostCompactionWrite(this.activeCount, appendCount);
this.activeCount += appendCount;
}
@ -216,22 +264,15 @@ export class AgentPopulation {
(sourceAgentOffset + chunkAgentCount) * AGENT_FLOAT_COUNT
)
);
this.markPostCompactionWrite(targetAgentOffset, chunkAgentCount);
sourceAgentOffset += chunkAgentCount;
this.replacementCursor = (targetAgentOffset + chunkAgentCount) % this.activeCount;
}
}
private markPostCompactionWrite(agentOffset: number, agentCount: number): void {
if (!this.isCompacting || agentCount <= 0) {
return;
}
this.postCompactionWriteEnd = Math.max(
this.postCompactionWriteEnd,
Math.ceil(agentOffset + agentCount)
);
private flushQueuedAgentBatches(): void {
const batches = this.queuedAgentBatches.splice(0);
batches.forEach((batch) => this.writeAgentBatch(batch));
}
private expandAdaptiveCapForPendingAgents(requestedAgentCount: number): void {
@ -279,3 +320,13 @@ export class AgentPopulation {
);
}
}
const getStrokeSpawnRate = (): number => {
const spawnPerPixel = Number.isFinite(settings.spawnPerPixel)
? settings.spawnPerPixel
: 0;
const densityMultiplier = Number.isFinite(appConfig.simulation.stroke.densityMultiplier)
? appConfig.simulation.stroke.densityMultiplier
: 0;
return Math.max(0, spawnPerPixel * densityMultiplier);
};

View file

@ -5,6 +5,7 @@ import type { VibeId } from '../vibes';
interface ExportSnapshotRendererOptions {
device: GPUDevice;
renderPipeline: RenderPipeline;
canvasFormat: GPUTextureFormat;
statusElement: HTMLElement;
seed: string;
getSourceSize: () => { width: number; height: number };
@ -50,7 +51,6 @@ export class ExportSnapshotRenderer {
private async renderSnapshot(layout: SnapshotLayout): Promise<void> {
const { width, height, unpaddedBytesPerRow, bytesPerRow } = layout;
const format = navigator.gpu.getPreferredCanvasFormat();
let texture: GPUTexture | null = null;
let output: GPUBuffer | null = null;
let isOutputMapped = false;
@ -58,7 +58,7 @@ export class ExportSnapshotRenderer {
try {
texture = this.device.createTexture({
size: { width, height },
format,
format: this.options.canvasFormat,
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
});
output = this.device.createBuffer({
@ -89,7 +89,7 @@ export class ExportSnapshotRenderer {
height,
unpaddedBytesPerRow,
bytesPerRow,
isBgra: format === 'bgra8unorm',
isBgra: this.options.canvasFormat === 'bgra8unorm',
});
output.unmap();
isOutputMapped = false;

View file

@ -44,10 +44,11 @@ export class GameLoopResources {
public constructor(
canvas: HTMLCanvasElement,
private readonly device: GPUDevice,
private readonly canvasFormat: GPUTextureFormat,
canvasSize: vec2,
initialAgentCapacity: number
) {
const context = initializeContext({ device, canvas });
const context = initializeContext({ device, canvas, format: canvasFormat });
this.textures = new SimulationTextures(this.device, canvasSize);
@ -73,8 +74,16 @@ export class GameLoopResources {
);
this.eraserTexturePipeline = new EraserTexturePipeline(this.device, this.commonState);
this.diffusionPipeline = new DiffusionPipeline(this.device);
this.renderPipeline = new RenderPipeline(context, this.device, this.commonState);
this.gpuProfiler = GpuProfiler.create(this.device);
this.renderPipeline = new RenderPipeline(
context,
this.device,
this.commonState,
this.canvasFormat
);
this.gpuProfiler = GpuProfiler.create(
this.device,
() => appConfig.tuningPane.showFpsOverlay
);
this.frameRenderer = new SimulationFrameRenderer(
this.device,
@ -104,6 +113,10 @@ export class GameLoopResources {
return this.frameRenderer.isSourceMapActive;
}
public get gpuPassTimeMs(): number | undefined {
return this.gpuProfiler?.latestTotalPassMs;
}
public setFrameParameters({
time,
deltaTime,
@ -140,7 +153,6 @@ export class GameLoopResources {
this.diffusionPipeline.setParameters(settings);
this.renderPipeline.setParameters({
...settings,
backgroundGrainStrength: 0,
channelColors,
backgroundColor,
});

View file

@ -38,11 +38,14 @@ export default class GameLoop {
private previousAccentColor = '';
private previousGrainStrength = Number.NaN;
private hasFinished = false;
private animationFrameId: number | null = null;
private destroyPromise: Promise<void> | null = null;
private readonly finished = Promise.withResolvers<void>();
public constructor(
private readonly canvas: HTMLCanvasElement,
private readonly device: GPUDevice,
private readonly canvasFormat: GPUTextureFormat,
private readonly deltaTimeCalculator: DeltaTimeCalculator,
private readonly ui: GardenUi
) {
@ -50,11 +53,17 @@ export default class GameLoop {
this.resources = new GameLoopResources(
canvas,
device,
this.canvasFormat,
this.canvasSize,
this.framePerformance.adaptiveCapInitial
);
this.introPrompt = new IntroPrompt(ui.prompt);
this.toolbarContrastMonitor = new ToolbarContrastMonitor(canvas, ui.toolbar, device);
this.toolbarContrastMonitor = new ToolbarContrastMonitor(
canvas,
ui.toolbar,
device,
this.canvasFormat
);
this.agentPopulation = new AgentPopulation(
this.resources.agentGenerationPipeline,
this.seedValue,
@ -72,7 +81,10 @@ export default class GameLoop {
),
getCanvasPixelRatio: () => this.canvasPixelRatio,
getMirrorSegmentCount: () => this.mirrorSegmentCount,
onStartDrawing: () => this.introPrompt.markStartedDrawing(),
onStartDrawing: () => {
this.introPrompt.markStartedDrawing();
this.agentPopulation.beginStroke();
},
onEraseGestureEnded: () => this.agentPopulation.requestCompactionAfterErase(),
spawnStrokeAgents: (from, to) => this.agentPopulation.spawnStrokeAgents(from, to),
});
@ -84,6 +96,7 @@ export default class GameLoop {
this.exportSnapshotRenderer = new ExportSnapshotRenderer({
device,
renderPipeline: this.resources.renderPipeline,
canvasFormat: this.canvasFormat,
statusElement: ui.exportStatus,
seed: this.seed,
getSourceSize: () => {
@ -139,7 +152,9 @@ export default class GameLoop {
}
public async start(): Promise<void> {
requestAnimationFrame(this.render);
if (this.animationFrameId === null && !this.hasFinished) {
this.animationFrameId = requestAnimationFrame(this.render);
}
return this.finished.promise;
}
@ -148,8 +163,17 @@ export default class GameLoop {
}
public async destroy(): Promise<void> {
this.destroyPromise ??= this.dispose();
return this.destroyPromise;
}
private async dispose(): Promise<void> {
this.hasFinished = true;
await this.finished.promise;
if (this.animationFrameId !== null) {
cancelAnimationFrame(this.animationFrameId);
this.animationFrameId = null;
}
this.finished.resolve();
window.removeEventListener('resize', this.resizeListener);
this.pointerInput.detach();
@ -164,6 +188,7 @@ export default class GameLoop {
}
private readonly render = (time: DOMHighResTimeStamp) => {
this.animationFrameId = null;
if (this.hasFinished) {
this.finished.resolve();
return;
@ -216,11 +241,12 @@ export default class GameLoop {
fps: this.framePerformance.measuredFps,
agentCount: this.agentPopulation.activeAgentCount,
frameTimeMs: this.framePerformance.measuredFrameTimeMs,
gpuPassTimeMs: this.resources.gpuPassTimeMs,
renderWidth: this.canvas.width,
renderHeight: this.canvas.height,
});
requestAnimationFrame(this.render);
this.animationFrameId = requestAnimationFrame(this.render);
};
private syncPerfStatsOverlay(): void {

View file

@ -16,11 +16,6 @@ interface GpuProfilerSample {
totalPassMs: number;
}
interface FleetingGardenPerf {
latest?: GpuProfilerSample;
samples: Array<GpuProfilerSample>;
}
interface ActivePass {
endQueryIndex: number;
name: GpuPassName;
@ -32,33 +27,29 @@ interface ReadbackSlot {
state: 'idle' | 'encoding' | 'mapping';
}
declare global {
interface Window {
__fleetingGardenPerf?: FleetingGardenPerf;
}
}
const MAX_QUERY_COUNT = PASS_NAMES.length * 2;
const QUERY_BYTES = BigUint64Array.BYTES_PER_ELEMENT;
const READBACK_SLOT_COUNT = 4;
const MAX_SAMPLE_COUNT = 600;
export class GpuProfiler {
private readonly querySet: GPUQuerySet;
private readonly resolveBuffer: GPUBuffer;
private readonly readbackSlots: Array<ReadbackSlot>;
private readonly isEnabled: () => boolean;
private activePasses: Array<ActivePass> = [];
private nextQueryIndex = 0;
private frame = 0;
private latestSample: GpuProfilerSample | null = null;
public static create(device: GPUDevice): GpuProfiler | null {
public static create(device: GPUDevice, isEnabled: () => boolean): GpuProfiler | null {
if (!device.features.has('timestamp-query')) {
return null;
}
return new GpuProfiler(device);
return new GpuProfiler(device, isEnabled);
}
private constructor(device: GPUDevice) {
private constructor(device: GPUDevice, isEnabled: () => boolean) {
this.isEnabled = isEnabled;
this.querySet = device.createQuerySet({
type: 'timestamp',
count: MAX_QUERY_COUNT,
@ -85,6 +76,9 @@ export class GpuProfiler {
public timestampWrites(
name: GpuPassName
): (GPUComputePassTimestampWrites & GPURenderPassTimestampWrites) | undefined {
if (!this.isEnabled()) {
return undefined;
}
if (this.nextQueryIndex + 1 >= MAX_QUERY_COUNT) {
return undefined;
}
@ -146,6 +140,10 @@ export class GpuProfiler {
});
}
public get latestTotalPassMs(): number | undefined {
return this.latestSample?.totalPassMs;
}
private publishSample(
frame: number,
passes: Array<ActivePass>,
@ -170,11 +168,6 @@ export class GpuProfiler {
sample.totalPassMs += elapsedMs;
});
const perf = (window.__fleetingGardenPerf ??= { samples: [] });
perf.latest = sample;
perf.samples.push(sample);
if (perf.samples.length > MAX_SAMPLE_COUNT) {
perf.samples.splice(0, perf.samples.length - MAX_SAMPLE_COUNT);
}
this.latestSample = sample;
}
}

View file

@ -1,5 +1,5 @@
import { appConfig } from '../config';
import { AGENT_FLOAT_COUNT } from '../pipelines/agents/agent-generation/agent-generation-pipeline';
import { AGENT_FLOAT_COUNT, writeAgentValues } from '../pipelines/agents/agent-limits';
import { clamp, easeOutQuad, mix, mixAngle, smoothstep } from '../utils/math';
interface IntroTitlePoint {
@ -114,15 +114,16 @@ export const createIntroTitleAgents = ({
pathProgress
)
);
const base = i * AGENT_FLOAT_COUNT;
data[base] = mix(startX, targetX, pathProgress);
data[base + 1] = mix(startY, targetY, pathProgress);
data[base + 2] = currentAngle;
data[base + 3] = point.colorIndex;
data[base + 4] = targetX;
data[base + 5] = targetY;
data[base + 6] = targetAngle;
data[base + 7] = introDelay;
writeAgentValues(data, i, {
positionX: mix(startX, targetX, pathProgress),
positionY: mix(startY, targetY, pathProgress),
angle: currentAngle,
colorIndex: point.colorIndex,
targetPositionX: targetX,
targetPositionY: targetY,
targetAngle,
introDelay,
});
}
return data;

Some files were not shown because too many files have changed in this diff Show more