-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.ts
More file actions
340 lines (289 loc) · 10.1 KB
/
Copy pathapp.ts
File metadata and controls
340 lines (289 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
/**
* Algorithmic Visual Evolution - Main Application
*
* Entry point for the application that initializes all core components:
* - Sets up the canvas and grid system
* - Creates and manages the simulation algorithms
* - Handles color generation and processing
* - Initializes UI components, parameters and macros
* - Manages the animation loop and timing
*/
// File: app.ts
import { config, Config } from './config.js';
import { GridManager } from './utils/gridManager.js';
import { TickManager } from './utils/tickManager.js';
import { setupKeyControls } from './utils/keys.js';
import { Kaleidoscope } from './algorithms/kaleidoscope.js';
import { EquilibriumManager } from './utils/equilibriumManager.js';
import { setupUI, parameterSliders, PARAM_DEFINITIONS } from './utils/uiManager.js';
import { setupMacrosUI, macros } from './utils/macrosUI.js';
import { getDerivedColors, rgbToCss } from './utils/colorTheory.js';
import { Cell, RGB } from './types.js';
import { presetManager } from './utils/presetManager.js';
let gm: GridManager;
let kaleidoscope: Kaleidoscope;
const equilibriumManager = new EquilibriumManager();
const tickManager = new TickManager();
function createSimulation(): void {
const canvas = document.getElementById('canvas') as HTMLCanvasElement;
canvas.width = config.canvasWidth;
canvas.height = config.canvasHeight;
const rows = Math.floor(config.canvasHeight / config.cellSize);
const cols = Math.floor(config.canvasWidth / config.cellSize);
gm = new GridManager(rows, cols);
kaleidoscope = new Kaleidoscope(
Math.floor(rows / 4),
Math.floor(cols / 4),
gm.getCells(),
rows,
cols,
gm
);
}
function updateDerivedColors(): void {
const cs = config.colorSettings;
config.derivedColors = getDerivedColors(cs.baseH, cs.baseS, cs.baseB, cs.scheme);
}
interface MacroTarget {
path: string;
baseline?: number;
}
interface Macro {
enabled: boolean;
getModulation: (t: number) => number;
targets: MacroTarget[];
}
function applyMacros(): void {
const t = tickManager.cycleCount || 0;
macros.forEach((macro: Macro) => {
if (!macro.enabled) return;
let rawWave = macro.getModulation(t);
let normWave = (rawWave + 1) / 2; // normalized to [0,1]
macro.targets.forEach(tgt => {
if (config._overrides[tgt.path]) return;
let currentVal = getConfigValueByPath(tgt.path);
if (tgt.baseline === undefined) {
tgt.baseline = currentVal;
}
const def = PARAM_DEFINITIONS.find(d => d.path === tgt.path);
if (!def || def.max === undefined || def.min === undefined) return;
// Create perfect wave oscillation across full parameter range
const targetVal = def.min + (normWave * (def.max - def.min));
let newVal = Math.max(def.min, Math.min(def.max, targetVal));
newVal = Math.round(newVal * 100) / 100;
// Set the new value
setConfigValueByPath(tgt.path, newVal);
// Special handling for parameters that need immediate updates
if (tgt.path === "tickRate") {
tickManager.stop();
tickManager.start();
} else if (tgt.path === "cellSize") {
createSimulation();
}
});
});
config._overrides = {};
}
function getConfigValueByPath(pathStr: string): any {
const parts = pathStr.split(".");
let current: any = config;
for (const p of parts) {
current = current[p];
}
return current;
}
function setConfigValueByPath(pathStr: string, newValue: any): void {
const parts = pathStr.split(".");
let current: any = config;
for (let i = 0; i < parts.length - 1; i++) {
current = current[parts[i]];
}
current[parts[parts.length - 1]] = newValue;
}
function updateParameterSliders(): void {
for (const path in parameterSliders) {
const { slider, valueDisplay } = parameterSliders[path];
const currentVal = getConfigValueByPath(path);
slider.value = currentVal;
valueDisplay.textContent = (Math.round(currentVal * 100) / 100).toString();
}
}
function render(): void {
const canvas = document.getElementById('canvas') as HTMLCanvasElement;
const ctx = canvas.getContext('2d');
if (!ctx) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
const cells = gm.getCells();
const rows = gm.getRows();
const cols = gm.getCols();
const cellSize = config.cellSize;
const binaryOn = config.binaryTransitions.enabled;
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
const cell = cells[i][j];
if (cell.state === 1 && cell.color) {
// Use modified RGB color with adjusted alpha if needed
const displayColor: RGB = {
...cell.color,
a: binaryOn ? 1.0 : cell.color.a
};
// Use the rgbToCss utility instead of manual string creation
ctx.fillStyle = rgbToCss(displayColor);
ctx.fillRect(j * cellSize, i * cellSize, cellSize, cellSize);
}
}
}
updateParameterSliders();
}
function onTick(): void {
updateDerivedColors();
applyMacros();
let activeCellsCount = 0;
const cells = gm.getCells();
const rows = gm.getRows();
const cols = gm.getCols();
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
const cell = cells[i][j];
if (cell.state === 1 && cell.color && cell.color.a > 0) activeCellsCount++;
}
}
const coverageFraction = (activeCellsCount / (gm.getRows() * gm.getCols())) || 0;
equilibriumManager.update(coverageFraction);
const { growthMultiplier, decayMultiplier } = {
growthMultiplier: equilibriumManager.getGrowthMultiplier(),
decayMultiplier: equilibriumManager.getDecayMultiplier()
};
kaleidoscope.update(growthMultiplier, decayMultiplier);
render();
}
declare global {
interface Window {
updateConfig: (path: string, val: any) => void;
}
}
function updateConfig(path: string, val: any): void {
console.log(`[Config Updated] ${path} = ${val}`);
if (path === "tickRate") {
tickManager.stop();
tickManager.start();
} else if (path === "cellSize") {
createSimulation();
}
// Update the config object
const parts = path.split('.');
let current: any = config;
for (let i = 0; i < parts.length - 1; i++) {
current = current[parts[i]];
}
current[parts[parts.length - 1]] = val;
// Update macro baselines for this parameter
updateMacroBaselines(path, val);
}
// Track which parameters are currently being manually adjusted
function updateMacroBaselines(path: string, newValue: any): void {
// Import macros and update baselines for matching parameters
import('./utils/macrosUI.js').then(({ macros }) => {
macros.forEach(macro => {
macro.targets.forEach(target => {
if (target.path === path) {
// Update the baseline to the new manual value
target.baseline = newValue;
console.log(`Updated baseline for ${path} to ${newValue}`);
}
});
});
}).catch(error => {
console.warn('Failed to update macro baselines:', error);
});
}
// Initialize preset system
async function initializePresets(): Promise<void> {
// Add a small delay to ensure server is ready
await new Promise(resolve => setTimeout(resolve, 100));
await presetManager.loadPresets();
// Always load a preset - either random or default
let presetToLoad: any = null;
if (config.RANDOM_START) {
presetToLoad = presetManager.getRandomPreset();
if (presetToLoad) {
console.log(`Loading random preset: ${presetToLoad.name}`);
}
}
// If no random preset or RANDOM_START is false, load the first available preset
if (!presetToLoad) {
const allPresets = presetManager.getPresets();
if (allPresets.length > 0) {
// Load the first preset (usually default)
const firstPreset = allPresets[0];
if (firstPreset) {
presetToLoad = firstPreset;
console.log(`Loading first available preset: ${firstPreset.name}`);
}
}
}
// Apply the preset if we found one
if (presetToLoad) {
presetManager.applyPreset(presetToLoad);
console.log(`Applied preset: ${presetToLoad.name}`);
// Show which preset was loaded in the UI
const title = document.querySelector('title');
if (title) {
title.textContent = `Algorithmic Visual Evolution - ${presetToLoad.name}`;
}
} else {
console.warn('No presets available, using default config');
}
}
// Initialize the application
async function initializeApp(): Promise<void> {
await initializePresets();
// Debug: Check config values after preset application
console.log('Config values after preset application:', {
cellSize: config.cellSize,
tickRate: config.tickRate,
activeCellDensity: config.activeCellDensity,
colorSettings: config.colorSettings,
binaryTransitions: config.binaryTransitions
});
// Wait a moment for macros to be fully applied
await new Promise(resolve => setTimeout(resolve, 100));
setupUI(updateConfig);
setupMacrosUI((macro: Macro | null) => {
// Optionally integrate with key controls.
});
createSimulation();
tickManager.onTick(onTick);
tickManager.start();
setupKeyControls(config, () => {}, console.log);
}
// Start the application
initializeApp();
// Hide UI by default
window.addEventListener('DOMContentLoaded', () => {
const paramPanel = document.getElementById('parametersPanel');
const macrosPanel = document.getElementById('macrosPanel');
if (paramPanel && macrosPanel) {
paramPanel.style.display = 'none';
macrosPanel.style.display = 'none';
}
});
window.addEventListener('keydown', (e: KeyboardEvent) => {
if (e.code === 'Space') {
e.preventDefault();
const paramPanel = document.getElementById('parametersPanel');
const macrosPanel = document.getElementById('macrosPanel');
if (paramPanel && macrosPanel) {
paramPanel.style.display = (paramPanel.style.display === 'none') ? 'block' : 'none';
macrosPanel.style.display = (macrosPanel.style.display === 'none') ? 'block' : 'none';
}
}
});
// Assign the updateConfig function to the window object
window.updateConfig = updateConfig;
// Expose preset manager functions for debugging
declare global {
interface Window {
updateConfig: (path: string, val: any) => void;
}
}