Spectacular Cellular Automata
    Preparing search index...

    Function applyPreset

    • Parameters

      • presetKey: string

      Returns void

      export function applyPreset(presetKey) {
      let preset = presets[presetKey];
      if (!preset) return;

      let width = reactiveState.cellGridWidth;
      let height = reactiveState.cellGridHeight;
      let newCells;

      if (presetKey === "random") {
      newCells = generateRandomCells(width, height);
      } else {
      const cells = preset.cells;

      let minX = Infinity,
      maxX = -Infinity;
      let minY = Infinity,
      maxY = -Infinity;
      cells.forEach(([x, y]) => {
      minX = Math.min(minX, x);
      maxX = Math.max(maxX, x);
      minY = Math.min(minY, y);
      maxY = Math.max(maxY, y);
      });
      const originalCenterX = (minX + maxX) / 2;
      const originalCenterY = (minY + maxY) / 2;
      const gridCenterX = Math.floor(width / 2);
      const gridCenterY = Math.floor(height / 2);
      const dx = Math.round(gridCenterX - originalCenterX);
      const dy = Math.round(gridCenterY - originalCenterY);
      const adjustedCells = cells.map(([x, y]) => [x + dx, y + dy]);
      newCells = generateCells(width, height, adjustedCells);
      }

      const newCellsFlat = new Uint8Array(newCells.flat());
      let changedCellsAlive = new Set();
      let changedCellsDead = new Set();

      // Calculate difference
      sharedState.cells.forEach((cell, i) => {
      if (cell === 0 && newCellsFlat[i] === 1) {
      changedCellsAlive.add(i);
      } else if (cell === 1 && newCellsFlat[i] === 0) {
      changedCellsDead.add(i);
      }
      });

      pushHistory({
      setCellsAlive: changedCellsAlive,
      setCellsDead: changedCellsDead,
      actionName: "Apply Preset",
      });

      sharedState.cells = newCellsFlat;
      }