1846 lines
74 KiB
C
1846 lines
74 KiB
C
#define _POSIX_C_SOURCE 200809L
|
|
#define _FILE_OFFSET_BITS 64
|
|
#include <GL/glut.h>
|
|
#include <stdint.h>
|
|
#include <ctype.h>
|
|
#include <errno.h>
|
|
#include <limits.h>
|
|
#include <unistd.h>
|
|
#include <pthread.h>
|
|
#include <spawn.h>
|
|
#include <sys/wait.h>
|
|
#include <sys/types.h>
|
|
#include <stdbool.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <time.h>
|
|
#include <dirent.h>
|
|
#include <sys/stat.h>
|
|
#include "tool_icons.h"
|
|
#include "app_identity.h"
|
|
#include "app_paths.h"
|
|
|
|
#define MIN_RESOLUTION 25
|
|
#define MAX_RESOLUTION 400
|
|
#define RESOLUTION_STEP 25
|
|
#define MIN_INTERVAL 10
|
|
#define MAX_INTERVAL 1000
|
|
#define UNDO_LIMIT 32
|
|
#define MAX_LOOP_END 999999999ULL
|
|
|
|
/* Two compact buffers keep resizing and generation updates allocation-free. */
|
|
static unsigned char cells[2][MAX_RESOLUTION * MAX_RESOLUTION];
|
|
static unsigned char *grid = cells[0], *nextGrid = cells[1];
|
|
static int resolution = 200, startDensity = 50, updateInterval = 100;
|
|
static int windowWidth = 1240, windowHeight = 900;
|
|
static float boardX, boardY, boardSize = 900;
|
|
static int boardViewX, boardViewY, boardViewSize = 900;
|
|
static float boardZoom = 1.0f, cameraX = 0.5f, cameraY = 0.5f;
|
|
static int population;
|
|
static bool paused, showControls = true, reversePlayback;
|
|
static bool showTopBar = true;
|
|
static bool controlsAnimating;
|
|
static float controlsSlideWidth, controlsSlideFrom;
|
|
static double controlsSlideStarted;
|
|
static void setControlsVisible(bool visible);
|
|
static unsigned long long generation;
|
|
static bool loopEnabled, loopActive, editingLoopEnd;
|
|
static unsigned long long loopEnd = 100, loopStartGeneration, loopStartHistory;
|
|
static char loopEndInput[16], loopMessage[160];
|
|
static int lastUpdate, lastFrameTime, frameCount;
|
|
static float fps;
|
|
static int hue = 275;
|
|
static bool rainbowHue;
|
|
static int rainbowSpeed = 30; /* Degrees per second. */
|
|
static double rainbowOffset, rainbowLastTime;
|
|
static bool rainbowClockReady;
|
|
/* Bit-packed temporary history has no fixed generation limit. */
|
|
static FILE *historyFile;
|
|
static unsigned long long historyCount;
|
|
static char historyError[160];
|
|
typedef struct {
|
|
uint64_t generation;
|
|
uint32_t population, resolution;
|
|
} HistoryHeader;
|
|
static unsigned char packedHistory[(MAX_RESOLUTION * MAX_RESOLUTION + 7) / 8];
|
|
|
|
enum { TOOL_BRUSH, TOOL_ERASER, TOOL_LINE, TOOL_STAMP, TOOL_CIRCLE, TOOL_SELECT, TOOL_PASTE };
|
|
enum { UI_TOGGLE, UI_PAUSE, UI_STEP, UI_BACK, UI_RESEED, UI_CLEAR,
|
|
UI_SPEED, UI_DENSITY, UI_RESOLUTION, UI_BRUSH, UI_HUE, UI_RESET_ZOOM, UI_TOP_BAR, UI_RAINBOW, UI_RAINBOW_SPEED,
|
|
UI_TOOL, UI_STAMP, UI_ROTATE, UI_MIRROR, UI_SNAP, UI_CIRCLE_ANCHOR, UI_PAUSE_ON_DRAW, UI_UNDO, UI_COPY, UI_PASTE, UI_GRID, UI_REVERSE, UI_RESTORE_START, UI_CATEGORY, UI_LABEL, UI_LOOP, UI_LOOP_END, UI_LOOP_LESS, UI_LOOP_MORE, UI_SAVE_BOARD, UI_OPEN_BOARD, UI_EXAMPLES, UI_EXAMPLE, UI_PAGE_BACK, UI_OPEN_FILE, UI_USER_BOARD, UI_SAVE_NAME, UI_SAVE_CONFIRM };
|
|
typedef struct { const char *name; int width, height; const char *cells; } Stamp;
|
|
static const Stamp stamps[] = {
|
|
{"Glider", 3, 3, ".O." "..O" "OOO"},
|
|
{"LW spaceship", 5, 4, ".O..O" "O...." "O...O" "OOOO."},
|
|
{"Blinker", 3, 1, "OOO"},
|
|
{"Toad", 4, 2, ".OOO" "OOO."},
|
|
{"Beacon", 4, 4, "OO.." "OO.." "..OO" "..OO"},
|
|
{"Pulsar", 13, 13,
|
|
"..OOO...OOO.." "............." "O....O.O....O" "O....O.O....O"
|
|
"O....O.O....O" "..OOO...OOO.." "............." "..OOO...OOO.."
|
|
"O....O.O....O" "O....O.O....O" "O....O.O....O" "............." "..OOO...OOO.."},
|
|
{"R-pentomino", 3, 3, ".OO" "OO." ".O."},
|
|
{"Acorn", 7, 3, ".O....." "...O..." "OO..OOO"},
|
|
{"Gosper Glider Gun", 36, 9,
|
|
"........................O..........."
|
|
"......................O.O..........."
|
|
"............OO......OO............OO"
|
|
"...........O...O....OO............OO"
|
|
"OO........O.....O...OO.............."
|
|
"OO........O...O.OO....O.O..........."
|
|
"..........O.....O.......O..........."
|
|
"...........O...O...................."
|
|
"............OO......................"}
|
|
};
|
|
#define STAMP_COUNT ((int)(sizeof(stamps) / sizeof(stamps[0])))
|
|
typedef struct { int id, value, x, y, w, h; bool slider; char label[100]; } Widget;
|
|
static Widget widgets[128];
|
|
static int widgetCount, activeSlider = -1, panelScroll, panelContentHeight;
|
|
enum { CATEGORY_DRAW, CATEGORY_BOARD, CATEGORY_VIEW, CATEGORY_HELP };
|
|
static int category = CATEGORY_DRAW;
|
|
enum { PAGE_CONTROLS, PAGE_EXAMPLES, PAGE_OPEN, PAGE_SAVE };
|
|
static int sidebarPage, returnScroll;
|
|
static Widget previousWidgets[128];
|
|
static int previousWidgetCount, pageDirection;
|
|
static double pageSlideStarted = -1000;
|
|
static char boardName[49];
|
|
static bool confirmReplace;
|
|
static void changeSidebarPage(int page);
|
|
static void submitBoardName(void);
|
|
static void pollBoardCatalog(void);
|
|
static int tool = TOOL_BRUSH, brushSize = 1, selectedStamp, rotation;
|
|
static bool snapLine = true, drawing, circleFromCorner;
|
|
static bool pauseOnDraw = true;
|
|
enum { GRID_OFF, GRID_CELLS, GRID_GUIDELINES };
|
|
static int gridMode = GRID_OFF;
|
|
/* Mirror bits reflect horizontally (left/right) and vertically (top/bottom). */
|
|
static int mirrorMode;
|
|
static bool hasSelection;
|
|
static int selectLeft, selectTop, selectRight, selectBottom;
|
|
static unsigned char clipboard[MAX_RESOLUTION * MAX_RESOLUTION];
|
|
static int clipboardWidth, clipboardHeight;
|
|
typedef struct {
|
|
unsigned char cells[MAX_RESOLUTION * MAX_RESOLUTION];
|
|
int resolution, population;
|
|
unsigned long long generation;
|
|
} EditSnapshot;
|
|
static EditSnapshot undoHistory[UNDO_LIMIT], pendingEdit, playbackStart;
|
|
static bool hasPlaybackStart;
|
|
static int undoNext, undoCount;
|
|
static bool editPending;
|
|
static void copySelection(void);
|
|
static void startPaste(void);
|
|
static int strokeValue, startCol, startRow, endCol, endRow, lastCol, lastRow;
|
|
static int hoverCol = -1, hoverRow = -1;
|
|
static void reshape(int width, int height);
|
|
static void drawPanel(void);
|
|
static void updateControlsAnimation(double now);
|
|
static void drawPreview(void);
|
|
static void refreshCircleConstraint(void);
|
|
|
|
#include "settings.inc"
|
|
|
|
static void closeHistory(void) {
|
|
if (historyFile) fclose(historyFile);
|
|
historyFile = NULL;
|
|
}
|
|
|
|
static void clearHistory(void) {
|
|
closeHistory();
|
|
historyCount = 0;
|
|
historyError[0] = '\0';
|
|
loopMessage[0] = '\0';
|
|
if (reversePlayback || loopActive) paused = true;
|
|
loopActive = false;
|
|
}
|
|
|
|
static void beginEdit(void) {
|
|
memcpy(pendingEdit.cells, grid, (size_t)resolution * resolution);
|
|
pendingEdit.resolution = resolution;
|
|
pendingEdit.population = population;
|
|
pendingEdit.generation = generation;
|
|
editPending = true;
|
|
}
|
|
|
|
static void commitEdit(void) {
|
|
if (!editPending) return;
|
|
undoHistory[undoNext] = pendingEdit;
|
|
undoNext = (undoNext + 1) % UNDO_LIMIT;
|
|
if (undoCount < UNDO_LIMIT) ++undoCount;
|
|
editPending = false;
|
|
}
|
|
|
|
static void capturePlaybackStart(void) {
|
|
memcpy(playbackStart.cells, grid, (size_t)resolution * resolution);
|
|
playbackStart.resolution = resolution;
|
|
playbackStart.population = population;
|
|
playbackStart.generation = generation;
|
|
hasPlaybackStart = true;
|
|
}
|
|
|
|
static bool prepareLoop(void) {
|
|
if (loopEnd <= generation) {
|
|
snprintf(loopMessage, sizeof(loopMessage), "Loop end must exceed Gen %llu. Restore start or raise the end.", generation);
|
|
paused = true;
|
|
return false;
|
|
}
|
|
loopStartGeneration = generation;
|
|
loopStartHistory = historyCount;
|
|
capturePlaybackStart();
|
|
loopActive = true;
|
|
reversePlayback = false;
|
|
loopMessage[0] = '\0';
|
|
return true;
|
|
}
|
|
|
|
static void setLoopEnd(unsigned long long value) {
|
|
if (value < 1) value = 1;
|
|
if (value > MAX_LOOP_END) value = MAX_LOOP_END;
|
|
if (loopEnd == value) return;
|
|
loopEnd = value;
|
|
if (loopEnabled) paused = true;
|
|
loopActive = false;
|
|
loopMessage[0] = '\0';
|
|
saveSettingsIfChanged();
|
|
}
|
|
|
|
static void finishLoopInput(void) {
|
|
if (!editingLoopEnd) return;
|
|
if (loopEndInput[0]) setLoopEnd(strtoull(loopEndInput, NULL, 10));
|
|
editingLoopEnd = false;
|
|
}
|
|
|
|
static void toggleForward(void) {
|
|
drawing = editPending = false;
|
|
finishLoopInput();
|
|
if (loopEnabled) {
|
|
if (!paused) paused = true;
|
|
else if (loopActive || prepareLoop()) paused = false;
|
|
} else if (!paused && !reversePlayback) paused = true;
|
|
else {
|
|
capturePlaybackStart();
|
|
reversePlayback = false;
|
|
paused = false;
|
|
}
|
|
lastUpdate = glutGet(GLUT_ELAPSED_TIME);
|
|
}
|
|
|
|
static void toggleReverse(void) {
|
|
drawing = editPending = false;
|
|
if (!paused && reversePlayback) paused = true;
|
|
else {
|
|
reversePlayback = true;
|
|
paused = historyCount == 0;
|
|
}
|
|
lastUpdate = glutGet(GLUT_ELAPSED_TIME);
|
|
}
|
|
|
|
static void restorePlaybackStart(void) {
|
|
if (!hasPlaybackStart) return;
|
|
beginEdit();
|
|
commitEdit();
|
|
drawing = editPending = hasSelection = false;
|
|
activeSlider = -1;
|
|
paused = true;
|
|
reversePlayback = false;
|
|
resolution = playbackStart.resolution;
|
|
population = playbackStart.population;
|
|
generation = playbackStart.generation;
|
|
memcpy(grid, playbackStart.cells, (size_t)resolution * resolution);
|
|
clearHistory();
|
|
lastUpdate = glutGet(GLUT_ELAPSED_TIME);
|
|
}
|
|
|
|
static void undoEdit(void) {
|
|
drawing = editPending = false;
|
|
activeSlider = -1;
|
|
paused = true;
|
|
if (!undoCount) return;
|
|
undoNext = (undoNext + UNDO_LIMIT - 1) % UNDO_LIMIT;
|
|
--undoCount;
|
|
const EditSnapshot *saved = &undoHistory[undoNext];
|
|
resolution = saved->resolution;
|
|
population = saved->population;
|
|
generation = saved->generation;
|
|
memcpy(grid, saved->cells, (size_t)resolution * resolution);
|
|
hasSelection = false;
|
|
clearHistory();
|
|
lastUpdate = glutGet(GLUT_ELAPSED_TIME);
|
|
}
|
|
|
|
static bool historyFailure(const char *message) {
|
|
snprintf(historyError, sizeof(historyError), "%s", message);
|
|
paused = true;
|
|
if (historyFile) clearerr(historyFile);
|
|
return false;
|
|
}
|
|
|
|
static bool seekHistory(unsigned long long index, size_t recordSize) {
|
|
if (index > (uint64_t)INT64_MAX / recordSize)
|
|
return historyFailure("History storage limit reached; simulation paused.");
|
|
if (fseeko(historyFile, (off_t)(index * recordSize), SEEK_SET) != 0)
|
|
return historyFailure("Cannot seek history file; simulation paused.");
|
|
return true;
|
|
}
|
|
|
|
static bool saveGeneration(void) {
|
|
if (!historyFile) historyFile = tmpfile();
|
|
if (!historyFile)
|
|
return historyFailure("Cannot create temporary history file; simulation paused.");
|
|
size_t cellCount = (size_t)resolution * resolution;
|
|
size_t packedSize = (cellCount + 7) / 8;
|
|
memset(packedHistory, 0, packedSize);
|
|
for (size_t i = 0; i < cellCount; ++i)
|
|
if (grid[i]) packedHistory[i / 8] |= (unsigned char)(1u << (i % 8));
|
|
HistoryHeader header = {generation, (uint32_t)population, (uint32_t)resolution};
|
|
/* Writing at the current cursor replaces the abandoned future after rewind. */
|
|
if (!seekHistory(historyCount, sizeof(header) + packedSize)) return false;
|
|
if (fwrite(&header, sizeof(header), 1, historyFile) != 1
|
|
|| fwrite(packedHistory, 1, packedSize, historyFile) != packedSize
|
|
|| fflush(historyFile) != 0)
|
|
return historyFailure("Cannot save history (check free space); simulation paused.");
|
|
++historyCount;
|
|
historyError[0] = '\0';
|
|
return true;
|
|
}
|
|
|
|
static bool rewindGeneration(void) {
|
|
if (historyCount == 0) return false;
|
|
if (!historyFile) return historyFailure("History file unavailable; simulation paused.");
|
|
size_t cellCount = (size_t)resolution * resolution;
|
|
size_t packedSize = (cellCount + 7) / 8;
|
|
HistoryHeader header;
|
|
if (!seekHistory(historyCount - 1, sizeof(header) + packedSize)) return false;
|
|
if (fread(&header, sizeof(header), 1, historyFile) != 1
|
|
|| fread(packedHistory, 1, packedSize, historyFile) != packedSize)
|
|
return historyFailure("Cannot read history; simulation paused.");
|
|
if (header.resolution != (uint32_t)resolution || header.population > cellCount)
|
|
return historyFailure("Invalid history record; simulation paused.");
|
|
int restoredPopulation = 0;
|
|
for (size_t i = 0; i < cellCount; ++i) {
|
|
nextGrid[i] = (packedHistory[i / 8] >> (i % 8)) & 1u;
|
|
restoredPopulation += nextGrid[i];
|
|
}
|
|
if (restoredPopulation != (int)header.population)
|
|
return historyFailure("Invalid history population; simulation paused.");
|
|
/* Only commit a rewind after the entire record has been read and checked. */
|
|
unsigned char *old = grid;
|
|
grid = nextGrid;
|
|
nextGrid = old;
|
|
--historyCount;
|
|
population = restoredPopulation;
|
|
generation = header.generation;
|
|
historyError[0] = '\0';
|
|
return true;
|
|
}
|
|
|
|
static void previousGeneration(void) {
|
|
loopActive = false;
|
|
paused = true;
|
|
drawing = editPending = false;
|
|
activeSlider = -1;
|
|
rewindGeneration();
|
|
lastUpdate = glutGet(GLUT_ELAPSED_TIME);
|
|
}
|
|
|
|
static void restart(void) {
|
|
beginEdit();
|
|
commitEdit();
|
|
hasSelection = false;
|
|
clearHistory();
|
|
int remaining = resolution * resolution;
|
|
int wanted = remaining * startDensity / 100;
|
|
population = wanted;
|
|
/* Sampling without replacement produces exactly the requested population. */
|
|
for (int i = 0; remaining > 0; ++i, --remaining) {
|
|
grid[i] = ((double)rand() / ((double)RAND_MAX + 1.0)) * remaining < wanted;
|
|
wanted -= grid[i];
|
|
}
|
|
generation = 0;
|
|
lastUpdate = glutGet(GLUT_ELAPSED_TIME);
|
|
}
|
|
|
|
static void updateGrid(void) {
|
|
if (!saveGeneration()) return;
|
|
population = 0;
|
|
for (int row = 0; row < resolution; ++row) {
|
|
int above = (row + resolution - 1) % resolution;
|
|
int below = (row + 1) % resolution;
|
|
for (int col = 0; col < resolution; ++col) {
|
|
int left = (col + resolution - 1) % resolution;
|
|
int right = (col + 1) % resolution;
|
|
int neighbors = grid[above * resolution + left]
|
|
+ grid[above * resolution + col]
|
|
+ grid[above * resolution + right]
|
|
+ grid[row * resolution + left]
|
|
+ grid[row * resolution + right]
|
|
+ grid[below * resolution + left]
|
|
+ grid[below * resolution + col]
|
|
+ grid[below * resolution + right];
|
|
int index = row * resolution + col;
|
|
nextGrid[index] = neighbors == 3 || (grid[index] && neighbors == 2);
|
|
population += nextGrid[index];
|
|
}
|
|
}
|
|
unsigned char *old = grid;
|
|
grid = nextGrid;
|
|
nextGrid = old;
|
|
++generation;
|
|
}
|
|
|
|
static void resizeGrid(int target) {
|
|
if (target < MIN_RESOLUTION || target > MAX_RESOLUTION || target == resolution) return;
|
|
beginEdit();
|
|
commitEdit();
|
|
hasSelection = false;
|
|
clearHistory();
|
|
population = 0;
|
|
/* Nearest-neighbor resampling retains the visible pattern at its new size. */
|
|
for (int row = 0; row < target; ++row) {
|
|
for (int col = 0; col < target; ++col) {
|
|
int source = (row * resolution / target) * resolution
|
|
+ col * resolution / target;
|
|
nextGrid[row * target + col] = grid[source];
|
|
population += nextGrid[row * target + col];
|
|
}
|
|
}
|
|
unsigned char *old = grid;
|
|
grid = nextGrid;
|
|
nextGrid = old;
|
|
resolution = target;
|
|
lastUpdate = glutGet(GLUT_ELAPSED_TIME);
|
|
}
|
|
|
|
#include "boards.inc"
|
|
#include "board_browser.inc"
|
|
|
|
static void rectangle(float x, float y, float width, float height) {
|
|
glVertex2f(x, y);
|
|
glVertex2f(x + width, y);
|
|
glVertex2f(x + width, y + height);
|
|
glVertex2f(x, y + height);
|
|
}
|
|
|
|
/* HSV keeps live cells bright and dead cells dark at every selected hue. */
|
|
static void updateRainbowHue(double now) {
|
|
if (rainbowClockReady && rainbowHue && now >= rainbowLastTime) {
|
|
rainbowOffset += (now - rainbowLastTime) * rainbowSpeed / 1000.0;
|
|
rainbowOffset -= (unsigned long long)(rainbowOffset / 360.0) * 360.0;
|
|
}
|
|
rainbowLastTime = now;
|
|
rainbowClockReady = true;
|
|
}
|
|
|
|
static float currentHue(void) {
|
|
return (float)(hue + (rainbowHue ? rainbowOffset : 0));
|
|
}
|
|
|
|
static void hueRGB(float degrees, float saturation, float value, float rgb[3]) {
|
|
degrees -= (int)(degrees / 360.0f) * 360.0f;
|
|
float h = degrees / 60.0f;
|
|
int sector = (int)h;
|
|
float fraction = h - sector;
|
|
float p = value * (1 - saturation);
|
|
float q = value * (1 - saturation * fraction);
|
|
float t = value * (1 - saturation * (1 - fraction));
|
|
const float colors[6][3] = {
|
|
{value, t, p}, {q, value, p}, {p, value, t},
|
|
{p, q, value}, {t, p, value}, {value, p, q}
|
|
};
|
|
memcpy(rgb, colors[sector], sizeof(float) * 3);
|
|
}
|
|
|
|
static void themeColor(float saturation, float value, float alpha) {
|
|
float rgb[3];
|
|
hueRGB(currentHue(), saturation, value, rgb);
|
|
glColor4f(rgb[0], rgb[1], rgb[2], alpha);
|
|
}
|
|
|
|
static void textPass(float x, float y, const char *text) {
|
|
glRasterPos2f(x, y);
|
|
for (; *text; ++text) glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *text);
|
|
}
|
|
|
|
typedef enum { TEXT_LABEL, TEXT_VALUE, TEXT_ON, TEXT_OFF } TextColor;
|
|
|
|
static TextColor wordColor(const char *word, size_t length) {
|
|
if (length == 2 && tolower((unsigned char)word[0]) == 'o'
|
|
&& tolower((unsigned char)word[1]) == 'n') return TEXT_ON;
|
|
if (length == 3 && tolower((unsigned char)word[0]) == 'o'
|
|
&& tolower((unsigned char)word[1]) == 'f'
|
|
&& tolower((unsigned char)word[2]) == 'f') return TEXT_OFF;
|
|
return TEXT_LABEL;
|
|
}
|
|
|
|
static void textColor(TextColor color) {
|
|
if (color == TEXT_ON) glColor3f(0.35f, 1.0f, 0.48f);
|
|
else if (color == TEXT_OFF) glColor3f(1.0f, 0.38f, 0.38f);
|
|
else if (color == TEXT_VALUE) {
|
|
float rgb[3];
|
|
hueRGB(currentHue() + 180, 0.62f, 1.0f, rgb);
|
|
glColor3fv(rgb);
|
|
} else themeColor(0.10f, 1.0f, 1.0f);
|
|
}
|
|
|
|
static void drawText(float x, float y, const char *text) {
|
|
glColor4f(0.0f, 0.0f, 0.0f, 0.95f);
|
|
textPass(x + 2, y + 2, text);
|
|
bool inValue = false;
|
|
TextColor wordStyle = TEXT_LABEL;
|
|
for (const char *c = text; *c; ++c) {
|
|
if (*c == '|') inValue = false;
|
|
if (isalpha((unsigned char)*c)) {
|
|
if (c == text || !isalnum((unsigned char)c[-1])) {
|
|
size_t length = 0;
|
|
while (isalnum((unsigned char)c[length])) ++length;
|
|
wordStyle = (inValue || (c == text && c[length] == '\0'))
|
|
? wordColor(c, length) : TEXT_LABEL;
|
|
}
|
|
} else wordStyle = TEXT_LABEL;
|
|
TextColor color = wordStyle != TEXT_LABEL ? wordStyle
|
|
: inValue || isdigit((unsigned char)*c) ? TEXT_VALUE : TEXT_LABEL;
|
|
textColor(color);
|
|
/* Raster color is latched with the raster position, not the bitmap call. */
|
|
glRasterPos2f(x, y);
|
|
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c);
|
|
x += glutBitmapWidth(GLUT_BITMAP_HELVETICA_18, *c);
|
|
if (*c == ':') inValue = true;
|
|
}
|
|
}
|
|
|
|
static void drawBoardNotification(void) {
|
|
float visibility = boardNotificationVisibility(notificationTime());
|
|
if (!boardMessage[0] || visibility <= 0) return;
|
|
int width = windowWidth - 32;
|
|
if (width > 440) width = 440;
|
|
if (width < 48) return;
|
|
char lines[160][160] = {{0}};
|
|
int line = 0, used = 0, pixels = 0;
|
|
for (const char *c = boardMessage; *c; ++c) {
|
|
int advance = glutBitmapWidth(GLUT_BITMAP_HELVETICA_18, *c);
|
|
if (used && pixels + advance > width - 32) {
|
|
lines[line++][used] = '\0';
|
|
used = pixels = 0;
|
|
}
|
|
lines[line][used++] = *c;
|
|
pixels += advance;
|
|
}
|
|
int height = 24 + (line + 1) * 24;
|
|
float x = windowWidth - width - 16;
|
|
float y = -height - 8 + visibility * (height + 64);
|
|
glColor4f(0, 0, 0, 0.35f);
|
|
glBegin(GL_QUADS);
|
|
rectangle(x + 3, y + 4, width, height);
|
|
themeColor(0.65f, 0.12f, 0.98f);
|
|
rectangle(x, y, width, height);
|
|
themeColor(0.6f, 0.95f, 1.0f);
|
|
rectangle(x, y, 3, height);
|
|
glEnd();
|
|
for (int i = 0; i <= line; ++i) drawText(x + 16, y + 28 + i * 24, lines[i]);
|
|
}
|
|
|
|
static void display(void) {
|
|
updateControlsAnimation(notificationTime());
|
|
refreshCircleConstraint();
|
|
float background[3];
|
|
hueRGB(currentHue(), 0.77f, 0.035f, background);
|
|
glClearColor(background[0], background[1], background[2], 1.0f);
|
|
glClear(GL_COLOR_BUFFER_BIT);
|
|
glEnable(GL_SCISSOR_TEST);
|
|
glScissor(boardViewX, windowHeight - boardViewY - boardViewSize, boardViewSize, boardViewSize);
|
|
themeColor(0.82f, 0.14f, 1.0f);
|
|
glBegin(GL_QUADS);
|
|
rectangle((float)boardX, (float)boardY, (float)boardSize, (float)boardSize);
|
|
glEnd();
|
|
|
|
float size = (float)boardSize / resolution;
|
|
float gap = gridMode == GRID_CELLS && size >= 6.0f ? 0.7f : 0.0f;
|
|
themeColor(0.80f, 1.0f, 1.0f);
|
|
/* Batch all live cells in one draw sequence. Dead cells use the board color. */
|
|
glBegin(GL_QUADS);
|
|
for (int row = 0; row < resolution; ++row) {
|
|
for (int col = 0; col < resolution; ++col) {
|
|
if (grid[row * resolution + col]) {
|
|
rectangle(boardX + col * size + gap / 2,
|
|
boardY + row * size + gap / 2, size - gap, size - gap);
|
|
}
|
|
}
|
|
}
|
|
glEnd();
|
|
|
|
int now = glutGet(GLUT_ELAPSED_TIME);
|
|
++frameCount;
|
|
if (now - lastFrameTime >= 1000) {
|
|
fps = frameCount * 1000.0f / (now - lastFrameTime);
|
|
frameCount = 0;
|
|
lastFrameTime = now;
|
|
}
|
|
|
|
drawPreview();
|
|
if (gridMode == GRID_CELLS) {
|
|
themeColor(0.25f, 0.65f, 0.40f);
|
|
glBegin(GL_LINES);
|
|
for (int i = 0; i <= resolution; ++i) {
|
|
float offset = i * size;
|
|
glVertex2f(boardX + offset, (float)boardY);
|
|
glVertex2f(boardX + offset, (float)(boardY + boardSize));
|
|
glVertex2f((float)boardX, boardY + offset);
|
|
glVertex2f((float)(boardX + boardSize), boardY + offset);
|
|
}
|
|
glEnd();
|
|
}
|
|
if (gridMode == GRID_GUIDELINES || (gridMode == GRID_CELLS && mirrorMode)) {
|
|
themeColor(0.05f, 1.0f, 0.8f);
|
|
glBegin(GL_LINES);
|
|
if (gridMode == GRID_GUIDELINES || (mirrorMode & 1)) {
|
|
glVertex2f(boardX + boardSize / 2.0f, (float)boardY);
|
|
glVertex2f(boardX + boardSize / 2.0f, (float)(boardY + boardSize));
|
|
}
|
|
if (gridMode == GRID_GUIDELINES || (mirrorMode & 2)) {
|
|
glVertex2f((float)boardX, boardY + boardSize / 2.0f);
|
|
glVertex2f((float)(boardX + boardSize), boardY + boardSize / 2.0f);
|
|
}
|
|
glEnd();
|
|
}
|
|
if (hasSelection) {
|
|
themeColor(0.05f, 1.0f, 0.95f);
|
|
glBegin(GL_LINE_LOOP);
|
|
rectangle(boardX + selectLeft * size, boardY + selectTop * size,
|
|
(selectRight - selectLeft + 1) * size, (selectBottom - selectTop + 1) * size);
|
|
glEnd();
|
|
}
|
|
glDisable(GL_SCISSOR_TEST);
|
|
drawPanel();
|
|
if (historyError[0] || loopMessage[0] || settingsError[0]) {
|
|
glColor4f(0.10f, 0.015f, 0.015f, 0.95f);
|
|
glBegin(GL_QUADS);
|
|
rectangle(0, windowHeight - 38, (float)windowWidth, 38);
|
|
glEnd();
|
|
drawText(16, windowHeight - 13, historyError[0] ? historyError : loopMessage[0] ? loopMessage : settingsError);
|
|
}
|
|
drawBoardNotification();
|
|
glutSwapBuffers();
|
|
}
|
|
|
|
static void updateBoardCamera(void) {
|
|
float margin = 0.5f / boardZoom;
|
|
if (cameraX < margin) cameraX = margin;
|
|
if (cameraX > 1 - margin) cameraX = 1 - margin;
|
|
if (cameraY < margin) cameraY = margin;
|
|
if (cameraY > 1 - margin) cameraY = 1 - margin;
|
|
boardSize = boardViewSize * boardZoom;
|
|
boardX = boardViewX + boardViewSize * 0.5f - cameraX * boardSize;
|
|
boardY = boardViewY + boardViewSize * 0.5f - cameraY * boardSize;
|
|
}
|
|
|
|
static bool insideBoardView(int x, int y) {
|
|
return x >= boardViewX && y >= boardViewY
|
|
&& x < boardViewX + boardViewSize && y < boardViewY + boardViewSize;
|
|
}
|
|
|
|
static void zoomBoard(int direction, int x, int y) {
|
|
float target = boardZoom * (direction > 0 ? 1.25f : 0.8f);
|
|
if (target < 1.0001f) target = 1;
|
|
if (target > 16) target = 16;
|
|
if (target == boardZoom) return;
|
|
float cellX = (x - boardX) / boardSize, cellY = (y - boardY) / boardSize;
|
|
boardZoom = target;
|
|
cameraX = cellX - (x - boardViewX - boardViewSize * 0.5f) / (boardViewSize * boardZoom);
|
|
cameraY = cellY - (y - boardViewY - boardViewSize * 0.5f) / (boardViewSize * boardZoom);
|
|
updateBoardCamera();
|
|
}
|
|
|
|
static float controlsWidth(void) {
|
|
return controlsAnimating ? controlsSlideWidth : showControls ? 320.0f : 0.0f;
|
|
}
|
|
|
|
static void updateBoardLayout(void) {
|
|
int sidebarWidth = (int)(controlsWidth() + 0.5f);
|
|
int available = windowWidth - sidebarWidth;
|
|
if (available < 1) available = 1;
|
|
int top = showTopBar ? 44 : 0;
|
|
int heightAvailable = windowHeight > top ? windowHeight - top : 1;
|
|
boardViewSize = available < heightAvailable ? available : heightAvailable;
|
|
boardViewX = sidebarWidth + (available - boardViewSize) / 2;
|
|
boardViewY = top + (heightAvailable - boardViewSize) / 2;
|
|
updateBoardCamera();
|
|
}
|
|
|
|
static void updateControlsAnimation(double now) {
|
|
if (!controlsAnimating) return;
|
|
float progress = (float)((now - controlsSlideStarted) / 240.0);
|
|
if (progress < 0) progress = 0;
|
|
if (progress >= 1) {
|
|
controlsAnimating = false;
|
|
controlsSlideWidth = showControls ? 320 : 0;
|
|
} else {
|
|
float eased = progress * progress * (3 - 2 * progress);
|
|
controlsSlideWidth = controlsSlideFrom + ((showControls ? 320 : 0) - controlsSlideFrom) * eased;
|
|
}
|
|
updateBoardLayout();
|
|
}
|
|
|
|
static void setControlsVisible(bool visible) {
|
|
double now = notificationTime();
|
|
updateControlsAnimation(now);
|
|
if (visible == showControls) return;
|
|
controlsSlideFrom = controlsWidth();
|
|
controlsSlideWidth = controlsSlideFrom;
|
|
controlsSlideStarted = now;
|
|
showControls = visible;
|
|
controlsAnimating = true;
|
|
drawing = editPending = editingLoopEnd = false;
|
|
activeSlider = -1;
|
|
hoverCol = hoverRow = -1;
|
|
saveSettingsIfChanged();
|
|
}
|
|
|
|
static void reshape(int width, int height) {
|
|
windowWidth = width > 0 ? width : 1;
|
|
windowHeight = height > 0 ? height : 1;
|
|
updateBoardLayout();
|
|
hoverCol = hoverRow = -1;
|
|
glViewport(0, 0, windowWidth, windowHeight);
|
|
glMatrixMode(GL_PROJECTION);
|
|
glLoadIdentity();
|
|
/* Pixel coordinates keep text a consistent size and cells square. */
|
|
glOrtho(0, windowWidth, windowHeight, 0, -1, 1);
|
|
glMatrixMode(GL_MODELVIEW);
|
|
glLoadIdentity();
|
|
saveSettingsIfChanged();
|
|
}
|
|
|
|
static void playbackTick(void) {
|
|
if (loopEnabled && loopActive) {
|
|
if (!reversePlayback && generation >= loopEnd) reversePlayback = true;
|
|
if (reversePlayback) {
|
|
if (historyCount <= loopStartHistory) {
|
|
reversePlayback = false;
|
|
return;
|
|
}
|
|
if (!rewindGeneration()) { paused = true; return; }
|
|
if (generation <= loopStartGeneration) reversePlayback = false;
|
|
} else {
|
|
updateGrid();
|
|
if (!paused && generation >= loopEnd) reversePlayback = true;
|
|
}
|
|
} else if (reversePlayback) {
|
|
if (!rewindGeneration() || historyCount == 0) paused = true;
|
|
} else updateGrid();
|
|
}
|
|
|
|
static void timer(int value) {
|
|
(void)value;
|
|
updateRainbowHue(notificationTime());
|
|
pollSettingsWriter();
|
|
pollBoardJob();
|
|
pollBoardCatalog();
|
|
int now = glutGet(GLUT_ELAPSED_TIME);
|
|
if (!paused && now - lastUpdate >= updateInterval) {
|
|
playbackTick();
|
|
lastUpdate = now;
|
|
}
|
|
glutPostRedisplay();
|
|
glutTimerFunc(10, timer, 0);
|
|
}
|
|
|
|
static void keyboard(int key, int x, int y) {
|
|
(void)x;
|
|
(void)y;
|
|
if (showControls && sidebarPage == PAGE_SAVE) return;
|
|
if (key == GLUT_KEY_UP && updateInterval > MIN_INTERVAL) updateInterval -= 10;
|
|
if (key == GLUT_KEY_DOWN && updateInterval < MAX_INTERVAL) updateInterval += 10;
|
|
saveSettingsIfChanged();
|
|
glutPostRedisplay();
|
|
}
|
|
|
|
static void chooseDrawingTool(int nextTool) {
|
|
drawing = editPending = false;
|
|
activeSlider = -1;
|
|
if (sidebarPage != PAGE_CONTROLS && showControls) changeSidebarPage(PAGE_CONTROLS);
|
|
else sidebarPage = PAGE_CONTROLS;
|
|
tool = nextTool;
|
|
category = CATEGORY_DRAW;
|
|
panelScroll = 0;
|
|
}
|
|
|
|
static void keyboardNormal(unsigned char key, int x, int y) {
|
|
(void)x;
|
|
(void)y;
|
|
if (key == 27) {
|
|
/* End an in-progress gesture before changing the board viewport. */
|
|
drawing = editPending = editingLoopEnd = false;
|
|
activeSlider = -1;
|
|
setControlsVisible(!showControls);
|
|
glutPostRedisplay();
|
|
return;
|
|
}
|
|
if (boardBusy) return;
|
|
if (showControls && sidebarPage == PAGE_SAVE) {
|
|
size_t length = strlen(boardName);
|
|
if (key == 13 || key == '\n') submitBoardName();
|
|
else if ((key == 8 || key == 127) && length) { boardName[length - 1] = '\0'; confirmReplace = false; }
|
|
else if (key >= 32 && key < 127 && key != '/' && key != '\\' && length < sizeof(boardName) - 1) {
|
|
boardName[length] = (char)key; boardName[length + 1] = '\0'; confirmReplace = false;
|
|
}
|
|
glutPostRedisplay();
|
|
return;
|
|
}
|
|
if (editingLoopEnd) {
|
|
size_t length = strlen(loopEndInput);
|
|
if (key >= '0' && key <= '9' && length < 9) {
|
|
loopEndInput[length] = (char)key;
|
|
loopEndInput[length + 1] = '\0';
|
|
} else if ((key == 8 || key == 127) && length) loopEndInput[length - 1] = '\0';
|
|
else if (key == 13 || key == '\n') finishLoopInput();
|
|
glutPostRedisplay();
|
|
return;
|
|
}
|
|
switch (key) {
|
|
case 'b': case 'B': chooseDrawingTool(TOOL_BRUSH); break;
|
|
case 'e': case 'E': chooseDrawingTool(TOOL_ERASER); break;
|
|
case 'l': case 'L': chooseDrawingTool(TOOL_LINE); break;
|
|
case 's': case 'S': chooseDrawingTool(TOOL_STAMP); break;
|
|
case 'o': case 'O': chooseDrawingTool(TOOL_CIRCLE); break;
|
|
case 'v': case 'V': chooseDrawingTool(TOOL_SELECT); break;
|
|
case 'p': case 'P': startPaste(); break;
|
|
case ',': case '<': if (brushSize > 1) --brushSize; break;
|
|
case '.': case '>': if (brushSize < 25) ++brushSize; break;
|
|
case 't': case 'T':
|
|
if (tool == TOOL_STAMP || tool == TOOL_PASTE)
|
|
rotation = (rotation + ((glutGetModifiers() & GLUT_ACTIVE_SHIFT) ? 3 : 1)) % 4;
|
|
break;
|
|
case 'x': case 'X': mirrorMode = (mirrorMode + 1) % 4; break;
|
|
case 'g': case 'G': gridMode = (gridMode + 1) % 3; break;
|
|
case '0':
|
|
boardZoom = 1;
|
|
cameraX = cameraY = 0.5f;
|
|
updateBoardCamera();
|
|
hoverCol = hoverRow = -1;
|
|
drawing = editPending = false;
|
|
break;
|
|
case '1': case '2': case '3': case '4': case '5':
|
|
case '6': case '7': case '8': case '9':
|
|
if (key - '1' < STAMP_COUNT) {
|
|
selectedStamp = key - '1';
|
|
chooseDrawingTool(TOOL_STAMP);
|
|
}
|
|
break;
|
|
case 19: changeSidebarPage(PAGE_SAVE); break; /* Ctrl+S */
|
|
case 15: changeSidebarPage(PAGE_OPEN); break; /* Ctrl+O */
|
|
case 26: undoEdit(); break; /* Ctrl+Z */
|
|
case 3: copySelection(); break; /* Ctrl+C */
|
|
case 22: startPaste(); break; /* Ctrl+V */
|
|
case ' ':
|
|
if (glutGetModifiers() & GLUT_ACTIVE_SHIFT) toggleReverse();
|
|
else toggleForward();
|
|
break;
|
|
case 'n': case 'N': loopActive = false; paused = true; updateGrid(); break;
|
|
case 'm': case 'M': previousGeneration(); break;
|
|
case 'h': case 'H': setControlsVisible(!showControls); break;
|
|
case 'r': case 'R': restorePlaybackStart(); break;
|
|
case 'c': case 'C':
|
|
beginEdit();
|
|
commitEdit();
|
|
hasSelection = false;
|
|
clearHistory();
|
|
memset(grid, 0, (size_t)resolution * resolution);
|
|
population = 0;
|
|
generation = 0;
|
|
paused = true;
|
|
break;
|
|
case '[': case '{':
|
|
if (startDensity > 0) { startDensity -= 5; restart(); }
|
|
break;
|
|
case ']': case '}':
|
|
if (startDensity < 100) { startDensity += 5; restart(); }
|
|
break;
|
|
case '-': case '_': resizeGrid(resolution - RESOLUTION_STEP); break;
|
|
case '+': case '=': resizeGrid(resolution + RESOLUTION_STEP); break;
|
|
default: break;
|
|
}
|
|
saveSettingsIfChanged();
|
|
glutPostRedisplay();
|
|
}
|
|
|
|
static int clamp(int value, int low, int high) {
|
|
return value < low ? low : value > high ? high : value;
|
|
}
|
|
|
|
static void addWidget(int id, int value, int x, int y, int w, int h,
|
|
bool slider, const char *label) {
|
|
Widget *item = &widgets[widgetCount++];
|
|
*item = (Widget){id, value, x, y, w, h, slider, ""};
|
|
snprintf(item->label, sizeof(item->label), "%s", label);
|
|
}
|
|
|
|
static void layoutPanel(void) {
|
|
widgetCount = 0;
|
|
addWidget(UI_TOGGLE, 0, 10, 6, 140, 30, false, showControls ? "Hide controls" : "Show controls");
|
|
if (!showControls && !controlsAnimating) {
|
|
if (!showTopBar) widgetCount = 0;
|
|
return;
|
|
}
|
|
int y = 56 - panelScroll;
|
|
char label[100];
|
|
if (sidebarPage != PAGE_CONTROLS) {
|
|
addWidget(UI_PAGE_BACK, 0, 16, y + panelScroll, 286, 34, false, "Back"); y += 48;
|
|
addWidget(UI_LABEL, 0, 16, y + panelScroll, 286, 24, false,
|
|
sidebarPage == PAGE_EXAMPLES ? "EXAMPLES" : sidebarPage == PAGE_OPEN ? "YOUR BOARDS" : "SAVE BOARD");
|
|
y += 34;
|
|
if (sidebarPage == PAGE_SAVE) {
|
|
addWidget(UI_LABEL, 0, 16, y, 286, 24, false, "Name your board:"); y += 30;
|
|
snprintf(label, sizeof(label), "%s_", boardName);
|
|
addWidget(UI_SAVE_NAME, 0, 16, y, 286, 40, false, label); y += 54;
|
|
addWidget(UI_LABEL, 0, 16, y, 286, 24, false, APP_PORTABLE ? "Saved in boards/ as a .life file." : "Saved in your board library."); y += 32;
|
|
addWidget(UI_SAVE_CONFIRM, 0, 16, y, 286, 34, false, confirmReplace ? "Replace existing board" : "Save board"); y += 48;
|
|
addWidget(UI_LABEL, 0, 16, y, 286, 24, false, "Enter: Save Esc: Hide controls"); y += 30;
|
|
} else {
|
|
int which = sidebarPage == PAGE_EXAMPLES ? 0 : 1;
|
|
if (sidebarPage == PAGE_OPEN) {
|
|
addWidget(UI_OPEN_FILE, 0, 16, y + panelScroll, 286, 34, false, "Open File"); y += 48;
|
|
}
|
|
BoardCatalog *catalog = &catalogs[which];
|
|
if (!catalog->ready) {
|
|
addWidget(UI_LABEL, 0, 16, y, 286, 24, false, "Loading boards..."); y += 30;
|
|
} else if (!catalog->count) {
|
|
addWidget(UI_LABEL, 0, 16, y, 286, 24, false, "No saved boards yet."); y += 30;
|
|
}
|
|
if (catalog->message[0]) {
|
|
addWidget(UI_LABEL, 0, 16, y, 286, 24, false, catalog->message); y += 30;
|
|
}
|
|
/* Only create widgets for visible cards; large libraries remain scrollable. */
|
|
for (size_t i = 0; i < catalog->count; ++i) {
|
|
if (y + 170 >= 44 && y < windowHeight && widgetCount < 63)
|
|
addWidget(which ? UI_USER_BOARD : UI_EXAMPLE, (int)i, 16, y, 286, 170, false, catalog->items[i].name);
|
|
y += 182;
|
|
}
|
|
}
|
|
goto layout_done;
|
|
}
|
|
addWidget(UI_LABEL, 0, 16, y, 286, 24, false, "PLAYBACK");
|
|
y += 30;
|
|
addWidget(UI_PAUSE, 0, 16, y, 138, 62, false,
|
|
!paused && (loopActive || !reversePlayback) ? "Pause" : loopEnabled ? "Play loop" : "Play forward");
|
|
addWidget(UI_REVERSE, 0, 164, y, 138, 62, false,
|
|
!paused && reversePlayback ? "Pause reverse" : "Play reverse");
|
|
y += 72;
|
|
addWidget(UI_BACK, 0, 16, y, 64, 62, false, "Back");
|
|
addWidget(UI_STEP, 0, 90, y, 64, 62, false, "Step");
|
|
addWidget(UI_RESTORE_START, 0, 164, y, 138, 62, false, "Restore start");
|
|
y += 72;
|
|
snprintf(label, sizeof(label), "Step interval: %d ms", updateInterval);
|
|
addWidget(UI_SPEED, 0, 16, y, 286, 48, true, label);
|
|
y += 62;
|
|
addWidget(UI_LOOP, 0, 16, y, 286, 34, false, loopEnabled ? "Looping: On" : "Looping: Off");
|
|
y += 44;
|
|
if (loopEnabled) {
|
|
addWidget(UI_LOOP_LESS, 0, 16, y, 40, 34, false, "-");
|
|
if (editingLoopEnd) snprintf(label, sizeof(label), "End: %s_", loopEndInput);
|
|
else snprintf(label, sizeof(label), "End: %llu", loopEnd);
|
|
addWidget(UI_LOOP_END, 0, 66, y, 186, 34, false, label);
|
|
addWidget(UI_LOOP_MORE, 0, 262, y, 40, 34, false, "+");
|
|
y += 44;
|
|
if (loopActive) snprintf(label, sizeof(label), "Loop: %llu - %llu", loopStartGeneration, loopEnd);
|
|
else snprintf(label, sizeof(label), "Click End to type a generation.");
|
|
addWidget(UI_LABEL, 0, 16, y, 286, 24, false, label);
|
|
y += 30;
|
|
}
|
|
const char *categories[] = {"Draw", "Board", "View", "Help"};
|
|
for (int i = 0; i < 4; ++i)
|
|
addWidget(UI_CATEGORY, i, 16 + i * 72, y, 70, 66, false, categories[i]);
|
|
y += 80;
|
|
if (category == CATEGORY_DRAW) {
|
|
addWidget(UI_LABEL, 0, 16, y, 286, 24, false, "TOOLS");
|
|
y += 30;
|
|
const char *names[] = {"Brush (B)", "Eraser (E)", "Line (L)", "Stamp (S)", "Circle (O)", "Select (V)"};
|
|
for (int i = 0; i < 6; ++i)
|
|
addWidget(UI_TOOL, i, 16 + (i % 2) * 148, y + (i / 2) * 44, 138, 34, false, names[i]);
|
|
y += 132;
|
|
snprintf(label, sizeof(label), "Undo (%d)", undoCount);
|
|
addWidget(UI_UNDO, 0, 16, y, 138, 34, false, label);
|
|
addWidget(UI_PASTE, 0, 164, y, 138, 34, false, "Paste (P)");
|
|
y += 44;
|
|
addWidget(UI_PAUSE_ON_DRAW, 0, 16, y, 286, 34, false,
|
|
pauseOnDraw ? "Pause on draw: On" : "Pause on draw: Off");
|
|
y += 48;
|
|
const char *toolNames[] = {"BRUSH OPTIONS", "ERASER OPTIONS", "LINE OPTIONS",
|
|
"STAMP LIBRARY", "CIRCLE OPTIONS", "SELECTION", "PASTE OPTIONS"};
|
|
addWidget(UI_LABEL, 0, 16, y, 286, 24, false, toolNames[tool]);
|
|
y += 30;
|
|
if (tool == TOOL_BRUSH || tool == TOOL_ERASER || tool == TOOL_LINE || tool == TOOL_CIRCLE) {
|
|
snprintf(label, sizeof(label), "Width: %d cell%s", brushSize, brushSize == 1 ? "" : "s");
|
|
addWidget(UI_BRUSH, 0, 16, y, 286, 48, true, label);
|
|
y += 62;
|
|
}
|
|
if (tool != TOOL_SELECT) {
|
|
const char *mirrorNames[] = {"Off", "Horizontal", "Vertical", "Both"};
|
|
snprintf(label, sizeof(label), "Mirror: %s", mirrorNames[mirrorMode]);
|
|
addWidget(UI_MIRROR, 0, 16, y, 286, 34, false, label);
|
|
y += 44;
|
|
}
|
|
if (tool == TOOL_LINE) {
|
|
addWidget(UI_SNAP, 0, 16, y, 286, 34, false,
|
|
snapLine ? "Line snap: 45 degrees (On)" : "Line snap: free angle");
|
|
y += 44;
|
|
}
|
|
if (tool == TOOL_CIRCLE) {
|
|
addWidget(UI_CIRCLE_ANCHOR, 0, 16, y, 286, 34, false,
|
|
circleFromCorner ? "Circle anchor: corner" : "Circle anchor: center");
|
|
y += 44;
|
|
if (circleFromCorner) {
|
|
addWidget(UI_LABEL, 0, 16, y, 286, 24, false, "Hold Ctrl for a perfect circle.");
|
|
y += 30;
|
|
}
|
|
}
|
|
if (tool == TOOL_SELECT) {
|
|
addWidget(UI_COPY, 0, 16, y, 286, 34, false, "Copy selection (Ctrl+C)");
|
|
y += 44;
|
|
addWidget(UI_LABEL, 0, 16, y, 286, 24, false, "Drag a box, then click Copy.");
|
|
y += 30;
|
|
}
|
|
if (tool == TOOL_STAMP || tool == TOOL_PASTE) {
|
|
snprintf(label, sizeof(label), "Rotate: %d degrees", rotation * 90);
|
|
addWidget(UI_ROTATE, 0, 16, y, 286, 34, false, label);
|
|
y += 44;
|
|
}
|
|
if (tool == TOOL_STAMP) {
|
|
for (int i = 0; i < STAMP_COUNT; ++i)
|
|
addWidget(UI_STAMP, i, 16 + (i % 2) * 148, y + (i / 2) * 110,
|
|
i == STAMP_COUNT - 1 && STAMP_COUNT % 2 ? 286 : 138, 100, false, stamps[i].name);
|
|
y += ((STAMP_COUNT + 1) / 2) * 110;
|
|
}
|
|
if (tool == TOOL_PASTE) {
|
|
snprintf(label, sizeof(label), "Clipboard: %d x %d cells", clipboardWidth, clipboardHeight);
|
|
addWidget(UI_LABEL, 0, 16, y, 286, 24, false, label);
|
|
y += 30;
|
|
}
|
|
} else if (category == CATEGORY_BOARD) {
|
|
addWidget(UI_LABEL, 0, 16, y, 286, 24, false, "BOARD FILES");
|
|
y += 30;
|
|
addWidget(UI_SAVE_BOARD, 0, 16, y, 90, 62, false, "Save");
|
|
addWidget(UI_OPEN_BOARD, 0, 114, y, 90, 62, false, "Open");
|
|
addWidget(UI_EXAMPLES, 0, 212, y, 90, 62, false, "Examples");
|
|
y += 76;
|
|
addWidget(UI_LABEL, 0, 16, y, 286, 24, false, "BOARD SETUP");
|
|
y += 30;
|
|
snprintf(label, sizeof(label), "Seed: %d%% / %d cells", startDensity, resolution * resolution * startDensity / 100);
|
|
addWidget(UI_DENSITY, 0, 16, y, 286, 48, true, label);
|
|
y += 62;
|
|
snprintf(label, sizeof(label), "Resolution: %d x %d", resolution, resolution);
|
|
addWidget(UI_RESOLUTION, 0, 16, y, 286, 48, true, label);
|
|
y += 62;
|
|
addWidget(UI_RESEED, 0, 16, y, 138, 34, false, "Reseed");
|
|
addWidget(UI_CLEAR, 0, 164, y, 138, 34, false, "Clear");
|
|
y += 44;
|
|
addWidget(UI_LABEL, 0, 16, y, 286, 24, false, "Seed changes apply on Reseed.");
|
|
y += 30;
|
|
} else if (category == CATEGORY_VIEW) {
|
|
addWidget(UI_LABEL, 0, 16, y, 286, 24, false, "APPEARANCE");
|
|
y += 30;
|
|
snprintf(label, sizeof(label), "Color hue: %d degrees", hue);
|
|
addWidget(UI_HUE, 0, 16, y, 286, 48, true, label);
|
|
y += 62;
|
|
addWidget(UI_RAINBOW, 0, 16, y, 286, 34, false, rainbowHue ? "Rainbow Hue: On" : "Rainbow Hue: Off");
|
|
y += 44;
|
|
if (rainbowHue) {
|
|
snprintf(label, sizeof(label), "Rainbow speed: %d deg/s", rainbowSpeed);
|
|
addWidget(UI_RAINBOW_SPEED, 0, 16, y, 286, 48, true, label);
|
|
y += 62;
|
|
}
|
|
addWidget(UI_TOP_BAR, 0, 16, y, 286, 34, false, showTopBar ? "Show top bar: On" : "Show top bar: Off");
|
|
y += 44;
|
|
snprintf(label, sizeof(label), "Reset zoom: %.0f%%", boardZoom * 100);
|
|
addWidget(UI_RESET_ZOOM, 0, 16, y, 286, 34, false, label);
|
|
y += 44;
|
|
const char *gridNames[] = {"Grid: Off", "Grid: Cell boundaries", "Grid: Guidelines"};
|
|
addWidget(UI_GRID, 0, 16, y, 286, 34, false, gridNames[gridMode]);
|
|
y += 44;
|
|
} else {
|
|
static const char *helpLines[] = {
|
|
"KEYBOARD SHORTCUTS",
|
|
"Space: Play / pause",
|
|
"Shift + Space: Reverse / pause",
|
|
"N: Step forward",
|
|
"M: Step backward",
|
|
"R: Restore start",
|
|
"C: Clear board",
|
|
"H: Hide / show controls",
|
|
"Up / Down: Faster / slower",
|
|
"- / +: Board resolution",
|
|
"[ / ]: Seed density + reseed",
|
|
"Ctrl + Z: Undo edit",
|
|
"Ctrl + C: Copy selection",
|
|
"Ctrl + V: Paste selection",
|
|
"Ctrl + S: Save board",
|
|
"Ctrl + O: Open board",
|
|
"Esc: Hide / show controls",
|
|
"",
|
|
"TOOL SHORTCUTS",
|
|
"B: Brush E: Eraser",
|
|
"L: Line O: Circle",
|
|
"S: Stamp V: Select",
|
|
"P: Paste copied cells",
|
|
"1 - 9: Pick a stamp",
|
|
", / .: Smaller / larger brush",
|
|
"T: Rotate stamp / paste",
|
|
"Shift + T: Rotate backward",
|
|
"X: Cycle mirror mode",
|
|
"G: Cycle grid mode",
|
|
"0: Reset zoom",
|
|
"",
|
|
"DRAWING",
|
|
"Left drag: Draw or select",
|
|
"Right drag: Erase cells",
|
|
"Ctrl + circle: Keep it round",
|
|
"Ctrl + wheel: Zoom at pointer",
|
|
"View: Reset zoom to fit board",
|
|
"Scroll sidebar to see more.",
|
|
"",
|
|
"PLAYBACK & BOARDS",
|
|
"Restore start returns to the",
|
|
"board before your last Play.",
|
|
"Reverse retraces recorded",
|
|
"generations back to the start.",
|
|
"Looping plays to End, then",
|
|
"reverses and repeats.",
|
|
"Board tab: Save, open, examples.",
|
|
"Settings save automatically.",
|
|
"",
|
|
"LIFE RULES",
|
|
"Live cells survive with 2 or 3",
|
|
"neighbors; 3 births a new cell.",
|
|
"Board edges wrap around.",
|
|
};
|
|
for (size_t i = 0; i < sizeof(helpLines) / sizeof(helpLines[0]); ++i) {
|
|
addWidget(UI_LABEL, 0, 16, y, 286, 24, false, helpLines[i]);
|
|
y += 26;
|
|
}
|
|
}
|
|
layout_done:
|
|
panelContentHeight = y + panelScroll + 16;
|
|
int maxScroll = panelContentHeight > windowHeight ? panelContentHeight - windowHeight : 0;
|
|
if (panelScroll > maxScroll) {
|
|
panelScroll = maxScroll;
|
|
layoutPanel();
|
|
}
|
|
}
|
|
|
|
static float sliderFraction(int id) {
|
|
switch (id) {
|
|
case UI_HUE: return hue / 360.0f;
|
|
case UI_RAINBOW_SPEED: return (rainbowSpeed - 1) / 179.0f;
|
|
case UI_SPEED: return (updateInterval - 10) / 990.0f;
|
|
case UI_DENSITY: return startDensity / 100.0f;
|
|
case UI_RESOLUTION: return (resolution - 25) / 375.0f;
|
|
default: return (brushSize - 1) / 24.0f;
|
|
}
|
|
}
|
|
|
|
static ToolIcon widgetIcon(const Widget *w) {
|
|
switch (w->id) {
|
|
case UI_CATEGORY: {
|
|
static const ToolIcon icons[] = {ICON_BRUSH, ICON_GRID, ICON_VIEW, ICON_HELP};
|
|
return icons[w->value];
|
|
}
|
|
case UI_PAUSE: return !paused && (loopActive || !reversePlayback) ? ICON_PAUSE : ICON_PLAY;
|
|
case UI_REVERSE: return !paused && reversePlayback ? ICON_PAUSE : ICON_REVERSE;
|
|
case UI_STEP: return ICON_STEP;
|
|
case UI_BACK: return ICON_BACK;
|
|
case UI_RESTORE_START: return ICON_RESTORE;
|
|
case UI_TOOL: {
|
|
static const ToolIcon icons[] = {ICON_BRUSH, ICON_ERASER, ICON_LINE,
|
|
ICON_STAMP, ICON_CIRCLE, ICON_SELECT, ICON_PASTE};
|
|
return icons[w->value];
|
|
}
|
|
case UI_MIRROR: {
|
|
static const ToolIcon icons[] = {ICON_MIRROR_OFF, ICON_MIRROR_H,
|
|
ICON_MIRROR_V, ICON_MIRROR_BOTH};
|
|
return icons[mirrorMode];
|
|
}
|
|
case UI_GRID: {
|
|
static const ToolIcon icons[] = {ICON_GRID_OFF, ICON_GRID, ICON_GUIDES};
|
|
return icons[gridMode];
|
|
}
|
|
case UI_TOP_BAR: return ICON_VIEW;
|
|
case UI_RESET_ZOOM: return ICON_CENTER;
|
|
case UI_CIRCLE_ANCHOR: return circleFromCorner ? ICON_CORNER : ICON_CENTER;
|
|
case UI_PAUSE_ON_DRAW: return pauseOnDraw ? ICON_PAUSE : ICON_PLAY;
|
|
case UI_SNAP: return snapLine ? ICON_SNAP : ICON_LINE;
|
|
case UI_ROTATE: case UI_LOOP: case UI_RAINBOW: return ICON_ROTATE;
|
|
case UI_SAVE_BOARD: case UI_SAVE_CONFIRM: return ICON_SAVE;
|
|
case UI_PAGE_BACK: return ICON_BACK;
|
|
case UI_OPEN_BOARD: case UI_OPEN_FILE: return ICON_OPEN;
|
|
case UI_EXAMPLES: case UI_EXAMPLE: return ICON_STAMP;
|
|
case UI_COPY: return ICON_COPY;
|
|
case UI_PASTE: return ICON_PASTE;
|
|
case UI_UNDO: return ICON_UNDO;
|
|
case UI_RESEED: return ICON_RESEED;
|
|
case UI_CLEAR: return ICON_CLEAR;
|
|
default: return ICON_NONE;
|
|
}
|
|
}
|
|
|
|
static void drawIcon(ToolIcon icon, float x, float y, bool selected) {
|
|
if (icon == ICON_NONE) return;
|
|
/* Exact 2x pixels stay crisp and inherit the chosen hue. */
|
|
for (int pass = 0; pass < 2; ++pass) {
|
|
float offset = pass == 0 ? 1.0f : 0.0f;
|
|
if (pass == 0) glColor4f(0, 0, 0, 0.8f);
|
|
else themeColor(selected ? 0.12f : 0.30f, 1.0f, 1.0f);
|
|
glBegin(GL_QUADS);
|
|
for (int row = 0; row < 12; ++row)
|
|
for (int col = 0; col < 12; ++col)
|
|
if (toolIconPixels[icon][row] & (1u << col))
|
|
rectangle(x + col * 2 + offset, y + row * 2 + offset, 2, 2);
|
|
glEnd();
|
|
}
|
|
}
|
|
|
|
static void drawFittedText(float x, float y, const char *text, int maxWidth, bool tail) {
|
|
char label[256];
|
|
snprintf(label, sizeof(label), "%s", text);
|
|
int width = 0;
|
|
for (const char *c = label; *c; ++c) width += glutBitmapWidth(GLUT_BITMAP_HELVETICA_18, *c);
|
|
if (tail) {
|
|
char *start = label;
|
|
while (*start && width > maxWidth) width -= glutBitmapWidth(GLUT_BITMAP_HELVETICA_18, *start++);
|
|
drawText(x, y, start);
|
|
} else {
|
|
size_t length = strlen(label);
|
|
if (width > maxWidth) {
|
|
while (length && width > maxWidth - 18)
|
|
width -= glutBitmapWidth(GLUT_BITMAP_HELVETICA_18, label[--length]);
|
|
snprintf(label + length, sizeof(label) - length, "...");
|
|
}
|
|
drawText(x, y, label);
|
|
}
|
|
}
|
|
|
|
static void drawBoardCard(const Widget *w) {
|
|
BoardCatalog *catalog = &catalogs[w->id == UI_USER_BOARD];
|
|
if (w->value < 0 || (size_t)w->value >= catalog->count) return;
|
|
const BoardEntry *entry = &catalog->items[w->value];
|
|
float left = w->x + (w->w - 112) / 2.0f, top = w->y + 8;
|
|
themeColor(0.7f, 0.055f, 1);
|
|
glBegin(GL_QUADS);
|
|
rectangle(left, top, 112, 112);
|
|
themeColor(0.7f, 1, 1);
|
|
float cell = 112.0f / BOARD_THUMB_SIZE;
|
|
for (int y = 0; y < BOARD_THUMB_SIZE; ++y)
|
|
for (int x = 0; x < BOARD_THUMB_SIZE; ++x)
|
|
if (entry->preview[y * BOARD_THUMB_SIZE + x]) rectangle(left + x * cell, top + y * cell, cell, cell);
|
|
glEnd();
|
|
drawFittedText(w->x + 12, w->y + 140, entry->name, w->w - 24, false);
|
|
char label[100];
|
|
snprintf(label, sizeof(label), "%d x %d | %d cells", entry->resolution, entry->resolution, entry->population);
|
|
drawFittedText(w->x + 12, w->y + 162, label, w->w - 24, false);
|
|
}
|
|
|
|
static void drawPanel(void) {
|
|
layoutPanel();
|
|
float width = controlsWidth();
|
|
float offset = width - 320;
|
|
int clipWidth = (int)width;
|
|
if (clipWidth > windowWidth) clipWidth = windowWidth;
|
|
if (width > 0) {
|
|
themeColor(0.78f, 0.055f, 1.0f);
|
|
glBegin(GL_QUADS);
|
|
rectangle(0, 44, width, (float)windowHeight);
|
|
glEnd();
|
|
}
|
|
/* Clip scrollable controls below the fixed header. */
|
|
glEnable(GL_SCISSOR_TEST);
|
|
glScissor(0, 0, clipWidth, windowHeight > 44 ? windowHeight - 44 : 0);
|
|
float slide = (float)((notificationTime() - pageSlideStarted) / 240.0);
|
|
if (slide < 0) slide = 0;
|
|
if (slide > 1) slide = 1;
|
|
slide = slide * slide * (3 - 2 * slide);
|
|
for (int pass = slide < 1 && width > 0 ? 0 : 1; pass < 2; ++pass) {
|
|
glPushMatrix();
|
|
glTranslatef(offset + pageDirection * 320 * (pass == 0 ? -slide : 1 - slide), 0, 0);
|
|
int count = pass == 0 ? previousWidgetCount : widgetCount;
|
|
for (int i = 1; i < count; ++i) {
|
|
Widget *w = pass == 0 ? &previousWidgets[i] : &widgets[i];
|
|
if (w->id == UI_LABEL) {
|
|
drawText(w->x, w->y + 18, w->label);
|
|
} else if (w->slider) {
|
|
drawText((float)w->x, (float)w->y + 17, w->label);
|
|
float fraction = sliderFraction(w->id);
|
|
themeColor(0.64f, 0.22f, 1.0f);
|
|
glBegin(GL_QUADS);
|
|
rectangle(w->x + 8, w->y + 32, w->w - 16, 6);
|
|
themeColor(0.76f, 0.85f, 1.0f);
|
|
if (w->id == UI_HUE) {
|
|
for (int segment = 0; segment < 60; ++segment) {
|
|
float rgb[3];
|
|
hueRGB(segment * 6, 0.8f, 1.0f, rgb);
|
|
glColor3fv(rgb);
|
|
rectangle(w->x + 8 + segment * (w->w - 16) / 60.0f,
|
|
w->y + 32, (w->w - 16) / 60.0f, 6);
|
|
}
|
|
} else rectangle(w->x + 8, w->y + 32, fraction * (w->w - 16), 6);
|
|
themeColor(0.35f, 1.0f, 1.0f);
|
|
rectangle(w->x + 3 + fraction * (w->w - 16), w->y + 26, 10, 18);
|
|
glEnd();
|
|
} else {
|
|
bool selected = (w->id == UI_CATEGORY && w->value == category)
|
|
|| (w->id == UI_TOOL && w->value == tool)
|
|
|| (w->id == UI_STAMP && w->value == selectedStamp && tool == TOOL_STAMP);
|
|
if (w->id == UI_EXAMPLE || w->id == UI_USER_BOARD) {
|
|
int top = w->id == UI_USER_BOARD ? 186 : 138;
|
|
glScissor(0, 0, clipWidth, windowHeight > top ? windowHeight - top : 0);
|
|
}
|
|
themeColor(0.70f, selected ? 0.38f : 0.16f, 1.0f);
|
|
glBegin(GL_QUADS);
|
|
rectangle((float)w->x, (float)w->y, (float)w->w, (float)w->h);
|
|
glEnd();
|
|
if (w->id == UI_EXAMPLE || w->id == UI_USER_BOARD) {
|
|
int top = w->id == UI_USER_BOARD ? 186 : 138;
|
|
glScissor(0, 0, clipWidth, windowHeight > top ? windowHeight - top : 0);
|
|
drawBoardCard(w);
|
|
glScissor(0, 0, clipWidth, windowHeight > 44 ? windowHeight - 44 : 0);
|
|
} else if (w->id == UI_SAVE_NAME) {
|
|
drawFittedText(w->x + 10, w->y + 26, w->label, w->w - 20, true);
|
|
} else if (w->id == UI_CATEGORY || w->id == UI_PAUSE || w->id == UI_REVERSE
|
|
|| w->id == UI_STEP || w->id == UI_BACK || w->id == UI_RESTORE_START
|
|
|| w->id == UI_SAVE_BOARD || w->id == UI_OPEN_BOARD || w->id == UI_EXAMPLES) {
|
|
drawIcon(widgetIcon(w), w->x + (w->w - 24) / 2.0f, w->y + 6, selected);
|
|
int width = 0;
|
|
for (const char *c = w->label; *c; ++c) width += glutBitmapWidth(GLUT_BITMAP_HELVETICA_18, *c);
|
|
drawText(w->x + (w->w - width) / 2.0f, w->y + 51, w->label);
|
|
if (w->id == UI_CATEGORY) {
|
|
themeColor(0.15f, 0.55f, 1.0f);
|
|
glBegin(GL_QUADS);
|
|
rectangle(w->x, w->y + w->h - 2, w->w + (w->value < CATEGORY_HELP ? 2 : 0), 2);
|
|
if (selected) {
|
|
themeColor(0.6f, 1.0f, 1.0f);
|
|
rectangle(w->x, w->y + w->h - 5, w->w, 5);
|
|
}
|
|
glEnd();
|
|
}
|
|
} else if (w->id == UI_STAMP) {
|
|
const Stamp *s = &stamps[w->value];
|
|
float size = 54.0f / s->height;
|
|
if (size > (w->w - 24.0f) / s->width) size = (w->w - 24.0f) / s->width;
|
|
if (size > 10) size = 10;
|
|
float left = w->x + (w->w - s->width * size) / 2;
|
|
float top = w->y + 8 + (58 - s->height * size) / 2;
|
|
themeColor(0.7f, 1.0f, 1.0f);
|
|
glBegin(GL_QUADS);
|
|
for (int row = 0; row < s->height; ++row)
|
|
for (int col = 0; col < s->width; ++col)
|
|
if (s->cells[row * s->width + col] == 'O')
|
|
rectangle(left + col * size, top + row * size, size - 0.7f, size - 0.7f);
|
|
glEnd();
|
|
int width = 0;
|
|
for (const char *c = w->label; *c; ++c) width += glutBitmapWidth(GLUT_BITMAP_HELVETICA_18, *c);
|
|
drawText(w->x + (w->w - width) / 2.0f, w->y + 88, w->label);
|
|
} else {
|
|
ToolIcon icon = widgetIcon(w);
|
|
drawIcon(icon, w->x + 9, w->y + (w->h - 24) / 2.0f, selected);
|
|
drawText(w->x + (icon == ICON_NONE ? 9 : 41), w->y + 23, w->label);
|
|
}
|
|
}
|
|
}
|
|
glPopMatrix();
|
|
}
|
|
if (width > 0 && panelContentHeight > windowHeight) {
|
|
float track = windowHeight - 52.0f;
|
|
float thumb = track * (windowHeight - 44.0f) / (panelContentHeight - 44.0f);
|
|
float top = 48 + (track - thumb) * panelScroll / (panelContentHeight - windowHeight);
|
|
themeColor(0.35f, 0.75f, 0.7f);
|
|
glBegin(GL_QUADS);
|
|
rectangle(offset + 312, top, 3, thumb);
|
|
glEnd();
|
|
}
|
|
glDisable(GL_SCISSOR_TEST);
|
|
themeColor(0.78f, 0.055f, 1.0f);
|
|
glBegin(GL_QUADS);
|
|
if (showTopBar || width > 0) rectangle(0, 0, showTopBar ? (float)windowWidth : width, 44);
|
|
themeColor(0.71f, 0.24f, 1.0f);
|
|
if (showTopBar || width > 0) rectangle(10 + (showTopBar ? 0 : offset), 6, 140, 30);
|
|
glEnd();
|
|
if (showTopBar || width > 0) drawText(20 + (showTopBar ? 0 : offset), 27, showControls ? "Hide controls" : "Show controls");
|
|
char status[160];
|
|
snprintf(status, sizeof(status), "%s | Gen %llu | Active %d | %.0f FPS | Back: %llu",
|
|
paused ? "PAUSED" : reversePlayback ? "REVERSE" : "RUNNING", generation, population, fps, historyCount);
|
|
if (showTopBar) drawText(170, 28, status);
|
|
}
|
|
|
|
/* Both previews and edits use the same rasterization, including edge clipping. */
|
|
static void emitOneCell(int col, int row, int value, bool preview) {
|
|
if (col < 0 || row < 0 || col >= resolution || row >= resolution) return;
|
|
if (preview) {
|
|
float size = (float)boardSize / resolution;
|
|
rectangle(boardX + col * size, boardY + row * size, size, size);
|
|
} else {
|
|
int index = row * resolution + col;
|
|
if (grid[index] != value) { commitEdit(); clearHistory(); }
|
|
population += value - grid[index];
|
|
grid[index] = (unsigned char)value;
|
|
}
|
|
}
|
|
|
|
static void emitCell(int col, int row, int value, bool preview) {
|
|
emitOneCell(col, row, value, preview);
|
|
int reflectedCol = resolution - 1 - col, reflectedRow = resolution - 1 - row;
|
|
if ((mirrorMode & 1) && reflectedCol != col) emitOneCell(reflectedCol, row, value, preview);
|
|
if ((mirrorMode & 2) && reflectedRow != row) emitOneCell(col, reflectedRow, value, preview);
|
|
if (mirrorMode == 3 && reflectedCol != col && reflectedRow != row)
|
|
emitOneCell(reflectedCol, reflectedRow, value, preview);
|
|
}
|
|
|
|
static void copySelection(void) {
|
|
if (!hasSelection || drawing) return;
|
|
clipboardWidth = selectRight - selectLeft + 1;
|
|
clipboardHeight = selectBottom - selectTop + 1;
|
|
for (int y = 0; y < clipboardHeight; ++y)
|
|
memcpy(clipboard + y * clipboardWidth,
|
|
grid + (selectTop + y) * resolution + selectLeft, (size_t)clipboardWidth);
|
|
}
|
|
|
|
static void startPaste(void) {
|
|
if (!clipboardWidth || drawing) return;
|
|
chooseDrawingTool(TOOL_PASTE);
|
|
rotation = 0;
|
|
}
|
|
|
|
static void paste(int col, int row, bool preview) {
|
|
int width = rotation % 2 ? clipboardHeight : clipboardWidth;
|
|
int height = rotation % 2 ? clipboardWidth : clipboardHeight;
|
|
for (int y = 0; y < clipboardHeight; ++y) {
|
|
for (int x = 0; x < clipboardWidth; ++x) {
|
|
int tx = x, ty = y;
|
|
for (int r = 0; r < rotation; ++r) {
|
|
int oldX = tx;
|
|
tx = (r % 2 ? clipboardWidth : clipboardHeight) - 1 - ty;
|
|
ty = oldX;
|
|
}
|
|
int value = clipboard[y * clipboardWidth + x];
|
|
if (preview) themeColor(0.2f, value ? 1.0f : 0.20f, 0.65f);
|
|
emitCell(col + tx - width / 2, row + ty - height / 2, value, preview);
|
|
}
|
|
}
|
|
}
|
|
|
|
static void brush(int col, int row, int value, bool preview) {
|
|
int offset = (brushSize - 1) / 2;
|
|
for (int y = 0; y < brushSize; ++y)
|
|
for (int x = 0; x < brushSize; ++x)
|
|
emitCell(col + x - offset, row + y - offset, value, preview);
|
|
}
|
|
|
|
static void line(int x0, int y0, int x1, int y1, int value, bool preview) {
|
|
int dx = abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
|
|
int dy = -abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
|
|
int error = dx + dy;
|
|
for (;;) {
|
|
brush(x0, y0, value, preview);
|
|
if (x0 == x1 && y0 == y1) break;
|
|
int twice = 2 * error;
|
|
if (twice >= dy) { error += dy; x0 += sx; }
|
|
if (twice <= dx) { error += dx; y0 += sy; }
|
|
}
|
|
}
|
|
|
|
/* Opposite corners define independent horizontal and vertical radii.
|
|
Half-cell centers keep odd and even bounding boxes symmetric. */
|
|
static void ellipse(int x0, int y0, int x1, int y1, int value, bool preview) {
|
|
if (x0 == x1 || y0 == y1) {
|
|
line(x0, y0, x1, y1, value, preview);
|
|
return;
|
|
}
|
|
float cx = (x0 + x1) / 2.0f, cy = (y0 + y1) / 2.0f;
|
|
float rx = abs(x1 - x0) / 2.0f, ry = abs(y1 - y0) / 2.0f;
|
|
float halfWidth = brushSize / 2.0f;
|
|
float outerX = rx + halfWidth, outerY = ry + halfWidth;
|
|
float innerX = rx - halfWidth, innerY = ry - halfWidth;
|
|
int padding = (brushSize + 1) / 2;
|
|
int left = clamp((x0 < x1 ? x0 : x1) - padding, 0, resolution - 1);
|
|
int right = clamp((x0 > x1 ? x0 : x1) + padding, 0, resolution - 1);
|
|
int top = clamp((y0 < y1 ? y0 : y1) - padding, 0, resolution - 1);
|
|
int bottom = clamp((y0 > y1 ? y0 : y1) + padding, 0, resolution - 1);
|
|
for (int row = top; row <= bottom; ++row) {
|
|
for (int col = left; col <= right; ++col) {
|
|
float dx = col - cx, dy = row - cy;
|
|
float outer = dx * dx / (outerX * outerX) + dy * dy / (outerY * outerY);
|
|
bool insideHole = innerX > 0 && innerY > 0
|
|
&& dx * dx / (innerX * innerX) + dy * dy / (innerY * innerY) < 1;
|
|
if (outer < 1 && !insideHole) emitCell(col, row, value, preview);
|
|
}
|
|
}
|
|
}
|
|
|
|
/* An annulus gives circles a uniform, symmetric outline of brushSize cells. */
|
|
static void circle(int cx, int cy, int edgeX, int edgeY, int value, bool preview) {
|
|
if (circleFromCorner) {
|
|
ellipse(cx, cy, edgeX, edgeY, value, preview);
|
|
return;
|
|
}
|
|
int dx = edgeX - cx, dy = edgeY - cy;
|
|
int distanceSquared = dx * dx + dy * dy;
|
|
int radius = 0;
|
|
while ((radius + 1) * (radius + 1) <= distanceSquared) ++radius;
|
|
if (4 * distanceSquared > 4 * radius * radius + 4 * radius + 1) ++radius;
|
|
int outer = 2 * radius + brushSize;
|
|
int inner = 2 * radius - brushSize;
|
|
if (inner < 0) inner = 0;
|
|
int reach = (outer + 1) / 2;
|
|
for (int row = clamp(cy - reach, 0, resolution - 1);
|
|
row <= clamp(cy + reach, 0, resolution - 1); ++row) {
|
|
for (int col = clamp(cx - reach, 0, resolution - 1);
|
|
col <= clamp(cx + reach, 0, resolution - 1); ++col) {
|
|
int x = col - cx, y = row - cy;
|
|
int d = 4 * (x * x + y * y);
|
|
if (d >= inner * inner && d < outer * outer)
|
|
emitCell(col, row, value, preview);
|
|
}
|
|
}
|
|
}
|
|
|
|
static void stamp(int col, int row, bool preview) {
|
|
const Stamp *s = &stamps[selectedStamp];
|
|
int width = rotation % 2 ? s->height : s->width;
|
|
int height = rotation % 2 ? s->width : s->height;
|
|
for (int y = 0; y < s->height; ++y) {
|
|
for (int x = 0; x < s->width; ++x) {
|
|
if (s->cells[y * s->width + x] != 'O') continue;
|
|
int tx = x, ty = y;
|
|
for (int r = 0; r < rotation; ++r) {
|
|
int oldX = tx;
|
|
tx = (r % 2 ? s->width : s->height) - 1 - ty;
|
|
ty = oldX;
|
|
}
|
|
emitCell(col + tx - width / 2, row + ty - height / 2, 1, preview);
|
|
}
|
|
}
|
|
}
|
|
|
|
static bool boardCell(int x, int y, int *col, int *row) {
|
|
if (!insideBoardView(x, y)) return false;
|
|
*col = (x - boardX) * resolution / boardSize;
|
|
*row = (y - boardY) * resolution / boardSize;
|
|
return true;
|
|
}
|
|
|
|
static void lineEndpoint(int col, int row) {
|
|
endCol = col;
|
|
endRow = row;
|
|
if (!snapLine) return;
|
|
int dx = col - startCol, dy = row - startRow;
|
|
if (abs(dx) > 2 * abs(dy)) endRow = startRow;
|
|
else if (abs(dy) > 2 * abs(dx)) endCol = startCol;
|
|
else {
|
|
int distance = abs(dx) > abs(dy) ? abs(dx) : abs(dy);
|
|
endCol = startCol + (dx < 0 ? -distance : distance);
|
|
endRow = startRow + (dy < 0 ? -distance : distance);
|
|
}
|
|
}
|
|
|
|
/* glutGetModifiers is event-local and is not reliable in motion/display
|
|
callbacks. Query the live pointer mask so either Ctrl key works throughout
|
|
a drag, including when Ctrl changes without any mouse movement. */
|
|
#ifndef CIRCLE_CTRL_HELD
|
|
static bool circleControlHeld(void) {
|
|
#if defined(__linux__)
|
|
Display *display = glXGetCurrentDisplay();
|
|
Window window = (Window)glXGetCurrentDrawable();
|
|
if (display && window) {
|
|
Window root, child;
|
|
int rootX, rootY, windowX, windowY;
|
|
unsigned int mask;
|
|
if (XQueryPointer(display, window, &root, &child, &rootX, &rootY,
|
|
&windowX, &windowY, &mask))
|
|
return (mask & ControlMask) != 0;
|
|
}
|
|
#endif
|
|
return false;
|
|
}
|
|
#define CIRCLE_CTRL_HELD() circleControlHeld()
|
|
#endif
|
|
|
|
static void circleEndpoint(int col, int row, bool constrain) {
|
|
endCol = col;
|
|
endRow = row;
|
|
if (!circleFromCorner || !constrain) return;
|
|
int dx = col - startCol, dy = row - startRow;
|
|
int size = abs(dx) > abs(dy) ? abs(dx) : abs(dy);
|
|
endCol = startCol + (dx < 0 ? -size : size);
|
|
endRow = startRow + (dy < 0 ? -size : size);
|
|
}
|
|
|
|
static void refreshCircleConstraint(void) {
|
|
if (drawing && tool == TOOL_CIRCLE && hoverCol >= 0 && hoverRow >= 0)
|
|
circleEndpoint(hoverCol, hoverRow, CIRCLE_CTRL_HELD());
|
|
}
|
|
|
|
static void drawPreview(void) {
|
|
if (tool == TOOL_SELECT || (hoverCol < 0 && !drawing)) return;
|
|
themeColor(tool == TOOL_ERASER || (drawing && !strokeValue) ? 0.05f : 0.35f, 1.0f, 0.45f);
|
|
glBegin(GL_QUADS);
|
|
if (drawing && tool == TOOL_LINE) line(startCol, startRow, endCol, endRow, strokeValue, true);
|
|
else if (drawing && tool == TOOL_CIRCLE) circle(startCol, startRow, endCol, endRow, strokeValue, true);
|
|
else if (hoverCol >= 0) {
|
|
if (tool == TOOL_STAMP) stamp(hoverCol, hoverRow, true);
|
|
else if (tool == TOOL_PASTE) paste(hoverCol, hoverRow, true);
|
|
else brush(hoverCol, hoverRow, 1, true);
|
|
}
|
|
glEnd();
|
|
}
|
|
|
|
static void changeSlider(Widget *w, int x) {
|
|
float f = (float)(x - w->x - 8) / (w->w - 16);
|
|
if (f < 0) f = 0;
|
|
if (f > 1) f = 1;
|
|
switch (w->id) {
|
|
case UI_HUE: hue = (int)(f * 360 + 0.5f); break;
|
|
case UI_RAINBOW_SPEED:
|
|
updateRainbowHue(notificationTime());
|
|
rainbowSpeed = 1 + (int)(f * 179 + 0.5f);
|
|
break;
|
|
case UI_SPEED: updateInterval = 10 + (int)(f * 99 + 0.5f) * 10; break;
|
|
case UI_DENSITY: startDensity = (int)(f * 20 + 0.5f) * 5; break;
|
|
case UI_RESOLUTION: {
|
|
int target = 25 + (int)(f * 15 + 0.5f) * 25;
|
|
if (target != resolution) resizeGrid(target);
|
|
break;
|
|
}
|
|
case UI_BRUSH: brushSize = 1 + (int)(f * 24 + 0.5f); break;
|
|
}
|
|
saveSettingsIfChanged();
|
|
}
|
|
|
|
static void activate(Widget *w) {
|
|
if (boardBusy) return;
|
|
if (w->id != UI_LOOP_END) finishLoopInput();
|
|
switch (w->id) {
|
|
case UI_RESET_ZOOM:
|
|
boardZoom = 1;
|
|
cameraX = cameraY = 0.5f;
|
|
updateBoardCamera();
|
|
hoverCol = hoverRow = -1;
|
|
break;
|
|
case UI_TOP_BAR:
|
|
showTopBar = !showTopBar;
|
|
drawing = editPending = false;
|
|
reshape(windowWidth, windowHeight);
|
|
break;
|
|
case UI_RAINBOW:
|
|
rainbowHue = !rainbowHue;
|
|
rainbowOffset = 0;
|
|
rainbowLastTime = notificationTime();
|
|
rainbowClockReady = true;
|
|
break;
|
|
case UI_SAVE_BOARD: changeSidebarPage(PAGE_SAVE); break;
|
|
case UI_SAVE_CONFIRM: submitBoardName(); break;
|
|
case UI_SAVE_NAME: break;
|
|
case UI_PAGE_BACK: changeSidebarPage(PAGE_CONTROLS); break;
|
|
case UI_OPEN_FILE: startBoardJob(false, -1); break;
|
|
case UI_OPEN_BOARD: changeSidebarPage(PAGE_OPEN); break;
|
|
case UI_EXAMPLES: changeSidebarPage(PAGE_EXAMPLES); break;
|
|
case UI_EXAMPLE: case UI_USER_BOARD: {
|
|
BoardCatalog *catalog = &catalogs[w->id == UI_USER_BOARD];
|
|
if (w->value >= 0 && (size_t)w->value < catalog->count) {
|
|
startBoardPath(false, catalog->items[w->value].path, false, false);
|
|
}
|
|
break;
|
|
}
|
|
case UI_LOOP:
|
|
loopEnabled = !loopEnabled;
|
|
loopActive = false;
|
|
if (loopEnabled) paused = true;
|
|
loopMessage[0] = '\0';
|
|
break;
|
|
case UI_LOOP_END:
|
|
editingLoopEnd = true;
|
|
loopEndInput[0] = '\0';
|
|
break;
|
|
case UI_LOOP_LESS: setLoopEnd(loopEnd > 1 ? loopEnd - 1 : 1); break;
|
|
case UI_LOOP_MORE: setLoopEnd(loopEnd + 1); break;
|
|
case UI_TOGGLE: keyboardNormal('h', 0, 0); break;
|
|
case UI_PAUSE: toggleForward(); break;
|
|
case UI_REVERSE: toggleReverse(); break;
|
|
case UI_RESTORE_START: restorePlaybackStart(); break;
|
|
case UI_CATEGORY: category = w->value; panelScroll = 0; break;
|
|
case UI_STEP: keyboardNormal('n', 0, 0); break;
|
|
case UI_BACK: keyboardNormal('m', 0, 0); break;
|
|
case UI_RESEED: restart(); break;
|
|
case UI_CLEAR: keyboardNormal('c', 0, 0); break;
|
|
case UI_TOOL: chooseDrawingTool(w->value); break;
|
|
case UI_STAMP: selectedStamp = w->value; tool = TOOL_STAMP; break;
|
|
case UI_ROTATE: rotation = (rotation + 1) % 4; break;
|
|
case UI_MIRROR: mirrorMode = (mirrorMode + 1) % 4; break;
|
|
case UI_UNDO: undoEdit(); break;
|
|
case UI_COPY: copySelection(); break;
|
|
case UI_PASTE: startPaste(); break;
|
|
case UI_GRID: gridMode = (gridMode + 1) % 3; break;
|
|
case UI_SNAP: snapLine = !snapLine; break;
|
|
case UI_PAUSE_ON_DRAW: pauseOnDraw = !pauseOnDraw; break;
|
|
case UI_CIRCLE_ANCHOR: circleFromCorner = !circleFromCorner; break;
|
|
}
|
|
saveSettingsIfChanged();
|
|
}
|
|
|
|
static void motion(int x, int y) {
|
|
hoverCol = hoverRow = -1;
|
|
if (boardBusy || controlsAnimating) return;
|
|
/* Once a stroke starts on the board, keep its endpoint at the nearest
|
|
edge even when the pointer moves over the sidebar or outside the window. */
|
|
if (drawing && activeSlider < 0) {
|
|
x = clamp(x, boardViewX, boardViewX + boardViewSize - 1);
|
|
y = clamp(y, boardViewY, boardViewY + boardViewSize - 1);
|
|
}
|
|
if (activeSlider >= 0) {
|
|
changeSlider(&widgets[activeSlider], x);
|
|
} else if (boardCell(x, y, &hoverCol, &hoverRow)) {
|
|
if (drawing && tool == TOOL_SELECT) {
|
|
selectLeft = startCol < hoverCol ? startCol : hoverCol;
|
|
selectRight = startCol > hoverCol ? startCol : hoverCol;
|
|
selectTop = startRow < hoverRow ? startRow : hoverRow;
|
|
selectBottom = startRow > hoverRow ? startRow : hoverRow;
|
|
}
|
|
else if (drawing && tool == TOOL_LINE) lineEndpoint(hoverCol, hoverRow);
|
|
else if (drawing && tool == TOOL_CIRCLE) {
|
|
circleEndpoint(hoverCol, hoverRow, CIRCLE_CTRL_HELD());
|
|
}
|
|
else if (drawing && tool != TOOL_STAMP) {
|
|
if (lastCol < 0) brush(hoverCol, hoverRow, strokeValue, false);
|
|
else line(lastCol, lastRow, hoverCol, hoverRow, strokeValue, false);
|
|
lastCol = hoverCol;
|
|
lastRow = hoverRow;
|
|
}
|
|
} else if (drawing) {
|
|
lastCol = -1;
|
|
}
|
|
glutPostRedisplay();
|
|
}
|
|
|
|
static void mouse(int button, int state, int x, int y) {
|
|
if (boardBusy) return;
|
|
if (controlsAnimating) {
|
|
if (showTopBar && button == GLUT_LEFT_BUTTON && state == GLUT_DOWN
|
|
&& x >= 10 && x < 150 && y >= 6 && y < 36)
|
|
setControlsVisible(!showControls);
|
|
glutPostRedisplay();
|
|
return;
|
|
}
|
|
if ((button == 3 || button == 4) && state == GLUT_DOWN
|
|
&& (glutGetModifiers() & GLUT_ACTIVE_CTRL) && insideBoardView(x, y)) {
|
|
if (!drawing && activeSlider < 0) {
|
|
zoomBoard(button == 3 ? 1 : -1, x, y);
|
|
motion(x, y);
|
|
}
|
|
return;
|
|
}
|
|
if (x < 320 && y >= 44 && notificationTime() - pageSlideStarted < 240) return;
|
|
if ((button == 3 || button == 4) && state == GLUT_DOWN && showControls && x < 320 && y >= 44) {
|
|
layoutPanel();
|
|
panelScroll = clamp(panelScroll + (button == 3 ? -40 : 40), 0,
|
|
windowHeight < panelContentHeight ? panelContentHeight - windowHeight : 0);
|
|
glutPostRedisplay();
|
|
return;
|
|
}
|
|
if (button != GLUT_LEFT_BUTTON && button != GLUT_RIGHT_BUTTON) return;
|
|
if (state == GLUT_UP) {
|
|
if (drawing) {
|
|
motion(x, y);
|
|
if (tool == TOOL_CIRCLE)
|
|
circle(startCol, startRow, endCol, endRow, strokeValue, false);
|
|
else if (tool == TOOL_LINE)
|
|
line(startCol, startRow, endCol, endRow, strokeValue, false);
|
|
}
|
|
drawing = editPending = false;
|
|
activeSlider = -1;
|
|
motion(x, y);
|
|
return;
|
|
}
|
|
layoutPanel();
|
|
if ((showTopBar && y < 44) || (showControls && x < 320)) {
|
|
if (button == GLUT_LEFT_BUTTON) {
|
|
for (int i = 0; i < widgetCount; ++i) {
|
|
Widget *w = &widgets[i];
|
|
if (w->id != UI_LABEL && (w->id != UI_EXAMPLE || y >= 138)
|
|
&& (w->id != UI_USER_BOARD || y >= 186) && (i == 0 || y >= 44) && x >= w->x && x < w->x + w->w && y >= w->y && y < w->y + w->h) {
|
|
if (w->slider) { finishLoopInput(); activeSlider = i; changeSlider(w, x); }
|
|
else activate(w);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
glutPostRedisplay();
|
|
return;
|
|
}
|
|
finishLoopInput();
|
|
if (!boardCell(x, y, &startCol, &startRow)) return;
|
|
if (pauseOnDraw) paused = true;
|
|
if (tool == TOOL_SELECT) {
|
|
if (button != GLUT_LEFT_BUTTON) return;
|
|
hasSelection = drawing = true;
|
|
selectLeft = selectRight = startCol;
|
|
selectTop = selectBottom = startRow;
|
|
glutPostRedisplay();
|
|
return;
|
|
}
|
|
beginEdit();
|
|
drawing = true;
|
|
strokeValue = button == GLUT_RIGHT_BUTTON || tool == TOOL_ERASER ? 0 : 1;
|
|
lastCol = endCol = hoverCol = startCol;
|
|
lastRow = endRow = hoverRow = startRow;
|
|
if (tool == TOOL_PASTE) {
|
|
if (button == GLUT_LEFT_BUTTON) paste(startCol, startRow, false);
|
|
drawing = editPending = false;
|
|
} else if (tool == TOOL_STAMP) {
|
|
if (button == GLUT_LEFT_BUTTON) stamp(startCol, startRow, false);
|
|
else brush(startCol, startRow, 0, false);
|
|
drawing = editPending = false;
|
|
} else if (tool != TOOL_LINE && tool != TOOL_CIRCLE) brush(startCol, startRow, strokeValue, false);
|
|
glutPostRedisplay();
|
|
}
|
|
|
|
int main(int argc, char **argv) {
|
|
if (argc == 2 && strcmp(argv[1], "--version") == 0) {
|
|
printf("%s %s\n", APP_NAME, APP_VERSION);
|
|
return EXIT_SUCCESS;
|
|
}
|
|
if (argc == 2 && (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0)) {
|
|
printf("%s\nUsage: %s [--help | --version]\n"
|
|
"A graphical Conway's Game of Life editor and simulator.\n"
|
|
"Use the Help tab for controls; Esc toggles the sidebar.\n", APP_NAME, argv[0]);
|
|
return EXIT_SUCCESS;
|
|
}
|
|
atexit(closeHistory);
|
|
atexit(closeBoardCatalogs);
|
|
initializeSettings();
|
|
startSettingsWriter();
|
|
atexit(stopSettingsWriter);
|
|
glutInit(&argc, argv);
|
|
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
|
|
glutInitWindowSize(windowWidth, windowHeight);
|
|
glutCreateWindow(APP_NAME);
|
|
setAppIdentity();
|
|
glClearColor(0.008f, 0.035f, 0.016f, 1.0f);
|
|
glEnable(GL_BLEND);
|
|
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
|
|
srand((unsigned int)time(NULL));
|
|
/* Start with an empty canvas; saved seed density applies only on Reseed. */
|
|
memset(grid, 0, (size_t)resolution * resolution);
|
|
population = 0;
|
|
generation = 0;
|
|
paused = true;
|
|
undoNext = undoCount = 0;
|
|
capturePlaybackStart();
|
|
lastFrameTime = glutGet(GLUT_ELAPSED_TIME);
|
|
glutDisplayFunc(display);
|
|
glutReshapeFunc(reshape);
|
|
glutSpecialFunc(keyboard);
|
|
glutKeyboardFunc(keyboardNormal);
|
|
glutMouseFunc(mouse);
|
|
glutMotionFunc(motion);
|
|
glutPassiveMotionFunc(motion);
|
|
glutTimerFunc(10, timer, 0);
|
|
glutMainLoop();
|
|
return EXIT_SUCCESS;
|
|
}
|