Compare commits

..

No commits in common. "master" and "load-picture" have entirely different histories.

25 changed files with 2677 additions and 3526 deletions

View File

@ -44,4 +44,3 @@ See [Configuration Reference](https://vitejs.dev/guide/).
- https://en.wikipedia.org/wiki/Hashlife - https://en.wikipedia.org/wiki/Hashlife
- https://plato.stanford.edu/entries/cellular-automata/supplement.html - https://plato.stanford.edu/entries/cellular-automata/supplement.html
- https://www.conwaylife.com/wiki/Cellular_automaton - https://www.conwaylife.com/wiki/Cellular_automaton
- https://conwaylife.com/

4150
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -7,25 +7,20 @@
"build": "vite build", "build": "vite build",
"serve": "vite preview", "serve": "vite preview",
"lint": "eslint --ext .js,.vue --ignore-path .gitignore --fix src", "lint": "eslint --ext .js,.vue --ignore-path .gitignore --fix src",
"format": "prettier . --write", "format": "prettier . --write"
"coverage": "vitest run --coverage",
"test": "vitest"
}, },
"dependencies": { "dependencies": {
"@vitejs/plugin-vue": "3.2.0", "@vitejs/plugin-vue": "^3.2.0",
"install": "0.13.0", "install": "^0.13.0",
"pinia": "2.0.27", "pinia": "^2.0.27",
"vite": "^3.2.10", "vite": "^3.2.4",
"vue": "3.2" "vue": "3.2"
}, },
"devDependencies": { "devDependencies": {
"@testing-library/vue": "^6.6.1",
"eslint": "^8.28.0", "eslint": "^8.28.0",
"eslint-config-prettier": "^8.5.0", "eslint-config-prettier": "^8.5.0",
"eslint-plugin-vue": "^9.8.0", "eslint-plugin-vue": "^9.8.0",
"happy-dom": "^8.1.1", "prettier": "2.8.0"
"prettier": "2.8.0",
"vitest": "^0.26.2"
}, },
"eslintConfig": { "eslintConfig": {
"root": true, "root": true,

View File

@ -1,57 +1,154 @@
<script setup> <template>
<div id="main">
<h1 id="main-title">
<span id="burger-toggle" @click="toggleMainMenu">{{
mainMenu == true ? "▼" : "☰"
}}</span>
Cellular Automata Explorer
</h1>
<div id="container">
<MainMenu v-if="mainMenu || windowWidth >= 800" />
<CanvasBoard />
</div>
<MenuReset row-title="" />
</div>
</template>
<script>
import MainMenu from "./components/MainMenu.vue"; import MainMenu from "./components/MainMenu.vue";
import CanvasBoard from "./components/CanvasBoard.vue"; import CanvasBoard from "./components/CanvasBoard.vue";
import MenuReset from "./components/MenuReset.vue"; import MenuReset from "./components/MenuReset.vue";
import { mapState, mapWritableState, mapActions } from "pinia";
import { globalStore } from "./stores/index.js"; import { globalStore } from "./stores/index.js";
import { nextTick, onBeforeUnmount, onMounted, ref } from "vue";
const store = globalStore(); export default {
name: "App",
const windowWidth = ref(window.innerWidth); components: {
MainMenu,
const toggleMainMenu = () => { MenuReset,
store.setMainMenu(!store.mainMenu); CanvasBoard,
},
data() {
return {
windowWidth: window.innerWidth,
}; };
},
const onResize = () => { computed: {
nextTick(() => { ...mapState(globalStore, ["mainMenu", "activeSubMenu"]),
windowWidth.value = window.innerWidth; ...mapWritableState(globalStore, ["canvasWidth", "canvasHeight"]),
// TODO: changing the width will clear the canvas. Find something else },
store.renderer.resize(window.innerWidth, window.innerHeight); mounted() {
store.setBoardWidth(); this.$nextTick(() => {
store.setBoardHeight(); window.addEventListener("resize", this.onResize);
}); });
},
beforeUnmount() {
window.removeEventListener("resize", this.onResize);
},
methods: {
...mapActions(globalStore, [
"setBoardWidth",
"setBoardHeight",
"setMainMenu",
]),
toggleMainMenu() {
this.setMainMenu(!this.mainMenu);
},
onResize() {
this.$nextTick(() => {
this.windowWidth = window.innerWidth;
this.canvasWidth = window.innerWidth;
this.canvasHeight = window.innerHeight;
this.setBoardWidth();
this.setBoardHeight();
});
},
},
}; };
onMounted(() => {
nextTick(() => {
window.addEventListener("resize", onResize);
});
});
onBeforeUnmount(() => {
window.removeEventListener("resize", onResize);
});
</script> </script>
<template> <style scope>
<main> :root {
<h1 --dark1: #000000;
v-if="store.mainMenu || windowWidth <= 800" --dark2: #333333;
id="main-title" --dark3: #666666;
class="main-title" --light1: #999999;
> --light2: #cccccc;
<span id="burger-toggle" class="burger-toggle" @click="toggleMainMenu"> --light3: #eeeeee;
{{ store.mainMenu == true ? "▼" : "☰" }} }
</span>
<span>Cellular Automata Explorer</span>
</h1>
<div id="container" class="container">
<MainMenu v-if="store.mainMenu || windowWidth >= 800" class="main-menu" />
<CanvasBoard />
</div>
<MenuReset :window-width="windowWidth" />
</main>
</template>
<style src="./assets/css/main.css"></style> #app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
/* color: #2c3e50; */
}
* {
margin: 0;
padding: 0;
}
body {
background: var(--dark1);
color: var(--light3);
font-family: Courier New;
}
canvas {
flex: auto;
background: rgb(0, 0, 0);
background: linear-gradient(
90deg,
rgba(0, 0, 0, 1) 0%,
rgba(131, 131, 131, 1) 52%,
rgba(0, 0, 0, 1) 100%
);
}
h1,
h2 {
font-weight: bold;
}
h1 {
margin: 10px auto;
font-size: larger;
text-transform: uppercase;
}
#container {
display: flex;
height: calc(100vh - 100px);
overflow: hidden;
flex-direction: column;
}
#burger-toggle {
display: none;
cursor: pointer;
font-size: 1.5em;
vertical-align: middle;
color: var(--light2);
}
@media screen and (max-width: 800px) {
h1 {
font-size: medium;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 10px;
}
#burger-toggle {
display: inline;
}
#main-menu {
background: var(--dark2);
margin: 0 auto;
}
}
</style>

View File

@ -1,228 +0,0 @@
:root {
--dark1: #000000;
--dark2: #333333;
--dark3: #666666;
--light1: #999999;
--light2: #cccccc;
--light3: #eeeeee;
}
* {
margin: 0;
padding: 0;
}
body {
background: var(--dark1);
color: var(--light3);
/* font-family: Courier New; */
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
}
canvas {
flex: auto;
background: linear-gradient(
90deg,
rgba(0, 0, 0, 1) 0%,
rgba(131, 131, 131, 1) 52%,
rgba(0, 0, 0, 1) 100%
);
}
h1,
h2,
.desktop-title {
font-weight: bold;
}
h1,
.desktop-title {
font-size: larger;
text-transform: uppercase;
}
.container {
display: flex;
height: calc(100vh - 100px);
overflow: hidden;
flex-direction: column;
}
.burger-toggle {
display: none;
cursor: pointer;
font-size: 1.5em;
vertical-align: middle;
color: var(--light2);
}
a {
font-weight: bold;
border: 1px solid white;
padding: 2px;
}
h2:hover {
cursor: pointer;
color: var(--light2);
}
select {
margin-top: 10px;
padding: 5px;
}
input[type="number"] {
max-width: 100%;
height: 100%;
}
input[type="button"] {
min-width: 40px;
min-height: 40px;
margin: 0 5px;
font-weight: bold;
line-height: 1.5em;
border-radius: 0;
outline: none;
border: none;
font-size: 1.1em;
background: var(--light2);
}
input[type="button"]:hover {
background: var(--light3);
}
.form-field {
display: flex;
margin: 10px;
justify-content: space-between;
}
.menu-row {
flex: 1;
position: relative;
}
.menu-row h2 {
font-size: medium;
padding: 10px;
cursor: pointer;
border-bottom: 1px solid var(--dark3);
border-top: 1px solid var(--dark3);
}
.menu-row a {
color: white;
font-weight: bold;
text-decoration: none;
font-size: small;
}
.menu-row-content {
position: absolute;
background: var(--dark1);
width: 100%;
overflow: scroll;
}
label,
.form-field label {
margin-right: 10px;
font-weight: bold;
}
.canvas-board {
flex: 1;
margin: 0 auto;
}
.main-menu {
display: flex;
flex-direction: row;
width: 100%;
flex: 1;
}
/* Hide scrollbar for Chrome, Safari and Opera */
.main-menu::-webkit-scrollbar {
display: none;
}
/* Hide scrollbar for IE, Edge and Firefox */
.main-menu {
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none; /* Firefox */
}
.reset-menu {
display: flex;
justify-content: space-between;
padding: 10px;
vertical-align: center;
}
.next,
.stop,
.reset {
display: inline-block;
vertical-align: bottom;
}
.reset-menu .loop {
padding: 5px;
display: inline-block;
}
@media screen and (max-width: 800px) {
h1 {
font-size: medium;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 10px;
}
.burger-toggle {
display: inline;
}
.main-menu {
background: var(--dark2);
margin: 0 auto;
flex-direction: column;
position: absolute;
}
.menu-row {
margin: 0 auto;
width: 100%;
}
.menu-row h2,
.form-field {
margin: 0;
}
.menu-row h2 {
border-bottom: 1px solid var(--dark3);
border-top: none;
}
.form-field {
padding: 10px;
}
.menu-row-content {
position: relative;
width: 100%;
}
.reset-menu {
justify-content: flex-end;
}
}

BIN
src/assets/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

0
src/assets/main.css Normal file
View File

View File

@ -1,194 +1,240 @@
<script setup> <template>
import { onMounted, watch } from "vue"; <canvas
id="board-canvas"
ref="board-canvas"
:width="canvasWidth"
:height="canvasHeight"
/>
<canvas
id="work-canvas"
ref="work-canvas"
:width="canvasWidth"
:height="canvasHeight"
/>
</template>
<script>
import { mapActions, mapState, mapWritableState } from "pinia";
import { globalStore } from "../stores/index.js"; import { globalStore } from "../stores/index.js";
import { import {
create1dState,
create1dStateOneCell,
create2dState,
createBoard, createBoard,
conwayRules, conwayRules,
overpopulationRules, overpopulationRules,
lonelinessRules, lonelinessRules,
threebornRules, threebornRules,
highLifeRules,
servietteRules,
evolve2d, evolve2d,
} from "../modules/core.js"; } from "../modules/automata.js";
import { import { getRandomInt, sleep } from "../modules/common.js";
create1dInitialState, import { picToBoard, picToBlackAndWhite } from "../modules/picture.js";
create2dRandomGrid,
} from "../modules/board.js";
import { picToBoard } from "../modules/picture.js";
const store = globalStore(); export default {
const available2dRules = { name: "CanvasBoard",
data() {
return {
canvas: null,
workCanvas: null,
workCtx: null,
ctx: null,
available2dRules: {
conway: conwayRules, conway: conwayRules,
overpopulation: overpopulationRules, overpopulation: overpopulationRules,
loneliness: lonelinessRules, loneliness: lonelinessRules,
threeborn: threebornRules, threeborn: threebornRules,
highlife: highLifeRules, },
serviette: servietteRules,
}; };
},
computed: {
...mapState(globalStore, {
cellProperties: "cellProperties",
ruleset: "ruleset1d",
refreshRate: "refreshRate",
initial1dState: "initial1dState",
drawingDirection: "drawingDirection",
canDraw: "canDraw",
getDraw1d: "draw1d",
getDraw2d: "draw2d",
getDraw2dLast: "draw2dLast",
getDraw2dPicture: "draw2dpicture",
boardWidth: "boardWidth",
boardHeight: "boardHeight",
picture: "picture",
selected2dRules: "selected2dRules",
}),
...mapWritableState(globalStore, {
lastBoard: "lastBoard",
canvasWidth: "canvasWidth",
canvasHeight: "canvasHeight",
getReset: "reset",
}),
// used to determine the dimensions of the board // used to determine the dimensions of the board
// TODO: should be a Board method max() {
const max = () => { return Math.max(this.boardWidth, this.boardHeight);
return Math.max(store.board.width, store.board.height); },
}; },
watch: {
const selectedRules = () => { getDraw1d(value) {
return available2dRules[store.selected2dRules.id]; if (value == true) this.draw1d();
}; },
getDraw2d(value) {
watch( if (value == true) this.draw2dNew();
() => store.draw1d, },
(value) => { getDraw2dLast(value) {
if (value == true) draw1d(); if (value == true) this.draw2dLast();
} },
); getDraw2dPicture(value) {
if (value == true) this.draw2dPicture();
watch( },
() => store.draw2d, getReset(value) {
(value) => { if (value == true) this.reset();
if (value == true) draw2dNew(); },
} },
); mounted() {
this.canvas = Object.freeze(document.getElementById("board-canvas"));
watch( this.workCanvas = Object.freeze(document.getElementById("work-canvas"));
() => store.draw2dLast, this.ctx = this.canvas.getContext("2d", { willReadFrequently: true });
async (value) => { this.workCtx = this.workCanvas.getContext("2d", {
if (value == true) await draw2dLast();
}
);
watch(
() => store.draw2dpicture,
(value) => {
if (value == true) draw2dPicture();
}
);
watch(
() => store.reset,
(value) => {
if (value == true) reset();
}
);
onMounted(() => {
// TODO : butt ugly.
const canvas = document.getElementById("board-canvas");
store.renderer.width = canvas.parentElement.clientWidth;
store.renderer.height = canvas.parentElement.clientHeight;
store.renderer.canvas = canvas;
store.renderer.ctx = store.renderer.canvas.getContext("2d", {
willReadFrequently: true, willReadFrequently: true,
}); });
if (typeof OffscreenCanvas != "undefined") { this.canvasWidth = this.canvas.parentElement.clientWidth;
store.renderer.workCanvas = new OffscreenCanvas( this.canvasHeight = this.canvas.parentElement.clientHeight;
canvas.parentElement.clientWidth, this.setBoardWidth();
canvas.parentElement.clientHeight this.setBoardHeight();
); },
} methods: {
// https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas/OffscreenCanvas#Browser_compatibility ...mapActions(globalStore, [
// Fallback for when offscreenCanvas is unsupported or disabled (Firefox < 44, default for Firefox?) "toggleStop",
else { "setBoardWidth",
store.renderer.workCanvas = document.createElement("canvas"); "setBoardHeight",
store.renderer.workCanvas.width = canvas.parentElement.clientWidth; ]),
store.renderer.workCanvas.height = canvas.parentElement.clientHeight;
}
store.renderer.workCtx = store.renderer.workCanvas.getContext("2d", {
willReadFrequently: true,
});
store.setBoardWidth();
store.setBoardHeight();
});
// draws the board on the canvas // draws the board on the canvas
const drawCanvas = async (board) => { drawCanvas(board) {
store.renderer.render(board); const props = this.cellProperties;
}; board.map((row, y) => {
const d = props.size;
return row.map((cell, x) => {
this.ctx.fillStyle = (() => {
if (cell === 1) return props.liveColor;
return props.deadColor;
})();
if (this.drawingDirection === "x")
this.ctx.fillRect(y * d, x * d, d, d);
else this.ctx.fillRect(x * d, y * d, d, d);
return cell;
});
});
},
// create a first state, either a single living cell
// at the center or random ones
compute1dInitialState() {
if (this.initial1dState === "onecell")
return create1dStateOneCell(this.boardWidth);
return create1dState(this.boardWidth, getRandomInt, [0, 2]);
},
// draw elementary automaton on the canvas based on selected ruleset // draw elementary automaton on the canvas based on selected ruleset
const draw1d = () => { draw1d() {
const initialState = create1dInitialState( const initialState = this.compute1dInitialState();
store.board, const board = createBoard(initialState, this.ruleset.rules, this.max);
store.initial1dState this.lastBoard = Object.freeze(board);
); this.drawCanvas(this.lastBoard);
const board = createBoard(initialState, store.ruleset1d.rules, max()); this.toggleStop();
store.board.grid = Object.freeze(board); },
drawCanvas(store.board);
store.toggleStop();
};
// draw 2D automaton on the canvas in a loop // draw 2D automaton on the canvas in a loop
const draw2d = (board) => { draw2d(board) {
drawCanvas(store.board); if (!this.canDraw) return;
const newBoard = Object.freeze(evolve2d(board.grid, selectedRules())); const draw2dNext = async (b) => {
if (store.board.grid == newBoard) store.toggleStop(); if (!this.canDraw) return;
store.board.grid = newBoard; const newBoard = evolve2d(
}; b,
this.available2dRules[this.selected2dRules.id]
// draw 2d automaton in a loop, starting from passed state
const draw2dNext = async (board) => {
setTimeout(() => {
if (!store.canDraw) return;
draw2d(board);
return draw2dNext(store.board);
}, store.renderer.refreshRate);
};
// draw 2d automaton from a new state
const draw2dNew = async () => {
if (!store.canDraw) return;
const initialGrid = create2dRandomGrid(
store.board.width,
store.board.height
); );
store.board.grid = Object.freeze(evolve2d(initialGrid, selectedRules())); this.drawCanvas(b, this.cellProperties);
if (store.loop) return draw2dNext(store.board); this.lastBoard = Object.freeze(newBoard);
else draw2d(store.board); await sleep(this.refreshRate);
store.toggleStop(); draw2dNext(newBoard);
}; };
return draw2dNext(board);
},
// draw 2d automaton from a new state
draw2dNew() {
const initialState = create2dState(
this.boardWidth,
this.boardHeight,
getRandomInt,
[0, 2]
);
const board = evolve2d(initialState, conwayRules);
this.lastBoard = Object.freeze(board);
this.draw2d(board);
},
// draw 2d automaton from the last known generated board // draw 2d automaton from the last known generated board
const draw2dLast = async () => { draw2dLast() {
if (!store.canDraw) return; if (this.lastBoard != undefined) this.draw2d(this.lastBoard);
if (store.loop) return draw2dNext(store.board); },
else draw2d(store.board);
store.toggleStop();
};
// draw 2d automaton from an uploaded picture. // draw 2d automaton from an uploaded picture.
// use the picture representation as an initial state // use the picture representation as an initial state
const draw2dPicture = async () => { draw2dPicture() {
store.renderer.renderImage( // get image data by drawing it on a work canvas
store.picture, this.workCtx.drawImage(
store.renderer.ctx, this.picture,
store.renderer.width, 0,
store.renderer.height 0,
this.canvasWidth,
this.canvasHeight
); );
const resized = store.renderer.renderImage( const imgData = this.workCtx.getImageData(
store.picture, 0,
store.renderer.workCtx, 0,
store.board.width, this.canvasWidth,
store.board.height this.canvasHeight
); );
const newBoard = picToBoard(resized.data, store.board);
store.board.grid = Object.freeze(newBoard);
store.toggleStop();
};
const reset = () => { // convert the image to black and white
store.toggleStop(); const black = picToBlackAndWhite(
store.board.grid = null; imgData.data,
store.renderer.reset(); this.canvasWidth,
store.toggleReset(); this.canvasHeight
);
// draw it back on the canvas
this.ctx.putImageData(black, 0, 0);
// draw the image back on the work canvas with the dimensions of the board
this.workCtx.drawImage(
this.picture,
0,
0,
this.boardWidth,
this.boardHeight
);
const resized = this.workCtx.getImageData(
0,
0,
this.boardWidth,
this.boardHeight
);
// convert the resized image into a 2D board of boolean based on pixel value
this.lastBoard = Object.freeze(
picToBoard(resized.data, this.boardWidth, this.boardHeight)
);
this.toggleStop();
},
// stop drawing routines and clear the canvas
reset() {
this.toggleStop();
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.getReset = 0;
},
},
}; };
</script> </script>
<template> <style>
<canvas #canvas-board {
id="board-canvas" flex: 1;
ref="board-canvas" margin: 0 auto;
class="board-canvas" }
:width="store.renderer.width" </style>
:height="store.renderer.height"
/>
</template>

View File

@ -7,9 +7,45 @@
</div> </div>
</template> </template>
<script setup> <script>
import MenuCellProperties from "./MenuCellProperties.vue"; import MenuCellProperties from "./MenuCellProperties.vue";
import MenuGeneralOptions from "./MenuGeneralOptions.vue"; import MenuGeneralOptions from "./MenuGeneralOptions.vue";
import MenuElementaryCA from "./MenuElementaryCA.vue"; import MenuElementaryCA from "./MenuElementaryCA.vue";
import Menu2dCA from "./Menu2dCA.vue"; import Menu2dCA from "./Menu2dCA.vue";
export default {
name: "MainMenu",
components: {
MenuCellProperties,
MenuGeneralOptions,
MenuElementaryCA,
Menu2dCA,
},
};
</script> </script>
<style>
#main-menu {
display: flex;
flex-direction: row;
width: 100%;
flex: 1;
}
/* Hide scrollbar for Chrome, Safari and Opera */
#main-menu::-webkit-scrollbar {
display: none;
}
/* Hide scrollbar for IE, Edge and Firefox */
#main-menu {
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none; /* Firefox */
}
@media screen and (max-width: 800px) {
#main-menu {
flex-direction: column;
position: absolute;
}
}
</style>

View File

@ -1,48 +1,3 @@
<script setup>
import MenuRow from "./MenuRow.vue";
import { globalStore } from "../stores/index.js";
import { preset2dRules } from "../modules/preset.js";
import { shallowRef } from "vue";
const store = globalStore();
const uploadedPicture = shallowRef(null);
const img = new Image();
// TODO : I have no idea why this works
const preparePicture = () => {
const file = uploadedPicture.value.files[0];
if (!file || file.type.indexOf("image/") !== 0) return;
if (FileReader && file) {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = (event) => {
img.onload = () => {
store.picture.width = img.width;
store.picture.height = img.height;
};
store.picture.src = event.target.result;
store.toggle2dDrawFromPicture();
};
reader.onerror = () => {
console.log(reader.error);
};
}
};
const update2dRules = (event) => {
const elem = event.target;
const id = elem.value;
const newRuleset = preset2dRules.find((ruleset) => {
return ruleset.id === id;
});
store.selected2dRules = newRuleset;
};
</script>
<template> <template>
<MenuRow row-title="2D Cellular Automaton"> <MenuRow row-title="2D Cellular Automaton">
<div class="form-field"> <div class="form-field">
@ -50,17 +5,17 @@
<input <input
type="button" type="button"
name="start2d" name="start2d"
value="" value="start"
@click="store.toggleDraw2d()" @click="toggleDraw2d()"
/> />
</div> </div>
<div class="form-field"> <div class="form-field">
<label>Start from last result</label> <label>Start from last result</label>
<input type="button" value="▶" @click="store.toggleDraw2dLast()" /> <input type="button" value="start" @click="toggleDraw2dLast()" />
</div> </div>
<div class="form-field"> <div class="form-field">
<label>Start from picture</label><br /> <label>Start from picture</label><br />
<input ref="uploadedPicture" type="file" @change="preparePicture" /> <input type="file" @change="preparePicture" />
</div> </div>
<div class="form-field"> <div class="form-field">
<label> <label>
@ -68,7 +23,7 @@
<br /> <br />
<select <select
name="preset2dRules" name="preset2dRules"
:value="store.selected2dRules.id" :value="selected2dRules.id"
@input="update2dRules" @input="update2dRules"
> >
<option <option
@ -83,3 +38,59 @@
</div> </div>
</MenuRow> </MenuRow>
</template> </template>
<script>
import MenuRow from "./MenuRow.vue";
import { mapActions, mapWritableState } from "pinia";
import { globalStore } from "../stores/index.js";
import { preset2dRules } from "../modules/preset.js";
export default {
name: "Menu2dCA",
components: {
MenuRow,
},
data() {
return {
uploadedFile: "",
preset2dRules: preset2dRules,
};
},
computed: {
...mapWritableState(globalStore, ["picture", "selected2dRules"]),
},
methods: {
...mapActions(globalStore, [
"toggleDraw2dLast",
"toggleDraw2d",
"toggle2dDrawFromPicture",
]),
preparePicture(event) {
const files = event.target.files;
this.picture = new Image();
this.picture.width = this.canvasWidth;
if (FileReader && files && files.length) {
const reader = new FileReader();
reader.onload = () => {
this.picture.src = Object.freeze(reader.result);
this.toggle2dDrawFromPicture();
};
reader.onerror = () => {
console.log(reader.error);
};
reader.readAsDataURL(files[0]);
}
},
update2dRules(event) {
const elem = event.target;
const id = elem.value;
const newRuleset = this.preset2dRules.find((ruleset) => {
return ruleset.id === id;
});
this.selected2dRules = newRuleset;
},
},
};
</script>

View File

@ -1,21 +1,3 @@
<script setup>
import { globalStore } from "../stores/index.js";
import MenuRow from "./MenuRow.vue";
const store = globalStore();
const updateCellProperties = (event) => {
const { name, value } = event.target;
store.setCellProperties(name, value);
store.setBoardWidth();
store.setBoardHeight();
};
const switchColor = () => {
store.switchColor();
};
</script>
<template> <template>
<MenuRow row-title="Cell Properties"> <MenuRow row-title="Cell Properties">
<form> <form>
@ -24,7 +6,7 @@
<input <input
name="liveColor" name="liveColor"
type="color" type="color"
:value="store.board.cellProperties.liveColor" :value="cellProperties.liveColor"
@input="updateCellProperties" @input="updateCellProperties"
/> />
</div> </div>
@ -33,7 +15,7 @@
<input <input
name="deadColor" name="deadColor"
type="color" type="color"
:value="store.board.cellProperties.deadColor" :value="cellProperties.deadColor"
@input="updateCellProperties" @input="updateCellProperties"
/> />
</div> </div>
@ -46,10 +28,50 @@
name="size" name="size"
type="number" type="number"
min="1" min="1"
:value="store.board.cellProperties.size" :value="cellProperties.size"
@click="updateCellProperties" @click="updateCellProperties"
/> />
</div> </div>
</form> </form>
</MenuRow> </MenuRow>
</template> </template>
<script>
import { mapActions, mapWritableState } from "pinia";
import { globalStore } from "../stores/index.js";
import MenuRow from "./MenuRow.vue";
export default {
name: "MenuCellProperties",
components: {
MenuRow,
},
computed: {
...mapWritableState(globalStore, ["cellProperties"]),
},
methods: {
...mapActions(globalStore, ["setBoardHeight", "setBoardWidth"]),
getCellProperties(event) {
const elem = event.target;
const prop = this.cellProperties;
return prop[elem.name];
},
updateCellProperties(event) {
const elem = event.target;
this.cellProperties[elem.name] = elem.value;
this.setBoardWidth();
this.setBoardHeight();
},
switchColor() {
[this.cellProperties["liveColor"], this.cellProperties["deadColor"]] = [
this.cellProperties["deadColor"],
this.cellProperties["liveColor"],
];
},
},
};
</script>
<style scoped>
a:hover {
cursor: pointer;
}
</style>

View File

@ -1,36 +1,3 @@
<script setup>
import { presetRuleset, initialStates } from "../modules/preset.js";
import { globalStore } from "../stores/index.js";
import MenuRow from "./MenuRow.vue";
const store = globalStore();
const copyRuleset = () => {
const newRuleset = JSON.stringify(store.ruleset1d);
navigator.clipboard.writeText(newRuleset);
};
const updateSingleRule = (event) => {
const elem = event.target;
const value = elem.checked ? 1 : 0;
store.ruleset1d.rules[elem.name] = value;
};
const updateRuleset = (event) => {
const elem = event.target;
const name = elem.value;
const newRuleset = presetRuleset.find((ruleset) => {
return ruleset.name === name;
});
store.ruleset1d = newRuleset;
};
const updateInitialState = (event) => {
const elem = event.target;
store.initial1dState = elem.value;
};
</script>
<template> <template>
<MenuRow row-title="Elementary Automaton"> <MenuRow row-title="Elementary Automaton">
<form> <form>
@ -38,8 +5,8 @@
<input <input
type="button" type="button"
name="start" name="start"
value="" value="start"
@click="store.toggleDraw1d()" @click="toggleDraw1d()"
/> />
</div> </div>
<div class="form-field"> <div class="form-field">
@ -48,7 +15,7 @@
<br /> <br />
<select <select
name="initialStates" name="initialStates"
:value="store.initial1dState" :value="initialState"
@input="updateInitialState" @input="updateInitialState"
> >
<option <option
@ -70,7 +37,7 @@
<br /> <br />
<select <select
name="ruleset-elementary" name="ruleset-elementary"
:value="store.ruleset1d.name" :value="ruleset.name"
@input="updateRuleset" @input="updateRuleset"
> >
<option <option
@ -87,7 +54,7 @@
<a style="cursor: pointer" @click="copyRuleset">copy rules</a> <a style="cursor: pointer" @click="copyRuleset">copy rules</a>
</div> </div>
<div <div
v-for="(rule, name, index) in store.ruleset1d.rules" v-for="(rule, name, index) in ruleset.rules"
:key="'rule-' + index" :key="'rule-' + index"
class="form-field" class="form-field"
> >
@ -105,3 +72,74 @@
</form> </form>
</MenuRow> </MenuRow>
</template> </template>
<script>
import { mapActions, mapWritableState } from "pinia";
import { presetRuleset, initialStates } from "../modules/preset.js";
import { globalStore } from "../stores/index.js";
import MenuRow from "./MenuRow.vue";
export default {
name: "MenuElementaryCA",
components: {
MenuRow,
},
data() {
return {
presetRuleset: presetRuleset,
initialStates: initialStates,
};
},
computed: {
...mapWritableState(globalStore, {
initialState: "initial1dState",
ruleset: "ruleset1d",
}),
rules1dFileName() {
// TODO: broken
return (
Object.keys(this.ruleset)
.map((index) => {
return this.ruleset[index];
})
.join("_") + ".json"
);
},
},
methods: {
...mapActions(globalStore, ["toggleDraw1d"]),
copyRuleset() {
const newRuleset = JSON.stringify(this.ruleset);
navigator.clipboard.writeText(newRuleset);
},
isCurrentPreset(event) {
const elem = event.target;
return this.initialState === elem.value;
},
updateSingleRule(event) {
const elem = event.target;
const value = elem.checked ? 1 : 0;
this.ruleset.rules[elem.name] = value;
},
updateRuleset(event) {
const elem = event.target;
const name = elem.value;
const newRuleset = this.presetRuleset.find((ruleset) => {
return ruleset.name === name;
});
this.ruleset = newRuleset;
},
updateInitialState(event) {
const elem = event.target;
this.initialState = elem.value;
},
},
};
</script>
<style>
.menu-row a {
color: white;
font-weight: bold;
text-decoration: none;
font-size: small;
}
</style>

View File

@ -1,31 +1,3 @@
<script setup>
import { globalStore } from "../stores/index.js";
import MenuRow from "./MenuRow.vue";
const store = globalStore();
const updateCanvasHeight = (event) => {
const elem = event.target;
store.renderer.resize(store.renderer.width, elem.value);
};
const updateCanvasWidth = (event) => {
const elem = event.target;
store.renderer.resize(elem.value, store.renderer.height);
};
const updateRefreshRate = (event) => {
const elem = event.target;
store.renderer.refreshRate = elem.value;
};
const updateDrawingDirection = (event) => {
const elem = event.target;
const value = elem.checked ? "x" : "y";
store.drawingDirection = value;
};
</script>
<template> <template>
<MenuRow row-title="General Options"> <MenuRow row-title="General Options">
<form> <form>
@ -39,7 +11,7 @@
name="canvasWidth" name="canvasWidth"
type="number" type="number"
step="10" step="10"
:value="store.renderer.width" :value="canvasWidth"
@input="updateCanvasWidth" @input="updateCanvasWidth"
/> />
</div> </div>
@ -50,19 +22,21 @@
name="canvasHeight" name="canvasHeight"
type="number" type="number"
step="10" step="10"
:value="store.renderer.height" :value="canvasHeight"
@input="updateCanvasHeight" @input="updateCanvasHeight"
/> />
</div> </div>
<div class="form-field"> <div class="form-field">
<label>Refresh Rate (ms)</label> <label>Refresh Rate (ms)</label>
</div>
<div class="form-field">
<input <input
id="refreshRate" id="refreshRate"
name="refreshRate" name="refreshRate"
type="number" type="number"
min="100" min="100"
step="100" step="100"
:value="store.renderer.refreshRate" :value="refreshRate"
@input="updateRefreshRate" @input="updateRefreshRate"
/> />
</div> </div>
@ -71,8 +45,8 @@
>Invert Drawing Direction >Invert Drawing Direction
<input <input
type="checkbox" type="checkbox"
:checked="store.drawingDirection === 'x'" :checked="drawingDirection === 'x'"
:value="store.drawingDirection" :value="drawingDirection"
@input="updateDrawingDirection" @input="updateDrawingDirection"
/> />
</label> </label>
@ -80,3 +54,42 @@
</form> </form>
</MenuRow> </MenuRow>
</template> </template>
<script>
import { mapWritableState } from "pinia";
import { globalStore } from "../stores/index.js";
import MenuRow from "./MenuRow.vue";
export default {
name: "MenuGeneralOptions",
components: {
MenuRow,
},
computed: {
...mapWritableState(globalStore, [
"canvasWidth",
"canvasHeight",
"refreshRate",
"drawingDirection",
]),
},
methods: {
updateCanvasHeight: function (event) {
const elem = event.target;
this.canvasHeight = elem.value;
},
updateCanvasWidth: function (event) {
const elem = event.target;
this.canvasWidth = elem.value;
},
updateRefreshRate: function (event) {
const elem = event.target;
this.refreshRate = elem.value;
},
updateDrawingDirection: function (event) {
const elem = event.target;
const value = elem.checked ? "x" : "y";
this.drawingDirection = value;
},
},
};
</script>

View File

@ -1,56 +1,36 @@
<script setup>
import { globalStore } from "../stores/index.js";
import { defineProps } from "vue";
const props = defineProps(
{
windowWidth: {
type: Number,
default: 800
}
}
);
const store = globalStore();
</script>
<template> <template>
<div class="reset-menu"> <div class="form-field">
<div v-if="props.windowWidth >= 800" class="desktop-title">
Cellular Automata Explorer
</div>
<div class="reset-input">
<div class="loop">
<label>
loop
<input
:value="store.loop"
type="checkbox"
:checked="store.loop"
@input="store.toggleLoop()"
/>
</label>
</div>
<input
type="button"
name="next"
class="next"
value="⇨"
@click="store.toggleNext()"
/>
<input <input
type="button" type="button"
name="stop" name="stop"
class="stop" class="stop"
value="⏹" value="stop"
@click="store.toggleStop()" @click="toggleStop()"
/> />
<input <input
type="button" type="button"
name="reset" name="reset"
class="reset" class="reset"
value="⌫" value="reset"
@click="store.toggleReset()" @click="toggleReset()"
/> />
</div> </div>
</div>
</template> </template>
<script>
import { mapActions } from "pinia";
import { globalStore } from "../stores/index.js";
export default {
name: "MenuReset",
methods: {
...mapActions(globalStore, ["toggleReset", "toggleStop"]),
},
};
</script>
<style scoped>
.form-field {
display: flex;
margin: 5px;
justify-content: flex-end;
}
</style>

View File

@ -1,44 +1,3 @@
<script setup>
import { computed, defineProps, onBeforeUnmount, ref } from "vue";
import { globalStore } from "../stores/index.js";
const store = globalStore();
const props = defineProps({
rowTitle: {
type: String,
default: "",
},
});
const content = ref(null);
const isActive = computed(() => {
return props.rowTitle == store.activeSubMenu;
});
const storeActiveSubMenu = () => {
window.addEventListener("click", onWindowClick);
store.setActiveSubMenu(props.rowTitle);
};
// hides submenu when click is detected outside from it
const onWindowClick = (event) => {
const form = content.value;
if (form != null) {
if (!form.contains(event.target)) {
store.setActiveSubMenu("");
store.setMainMenu(false);
}
return;
}
};
onBeforeUnmount(() => {
window.removeEventListener("click", onWindowClick);
});
</script>
<template> <template>
<div class="menu-row"> <div class="menu-row">
<h2 :id="rowTitle" @click.stop="storeActiveSubMenu"> <h2 :id="rowTitle" @click.stop="storeActiveSubMenu">
@ -49,3 +8,132 @@
</div> </div>
</div> </div>
</template> </template>
<script>
import { mapActions, mapState } from "pinia";
import { globalStore } from "../stores/index.js";
export default {
name: "MenuRow",
props: {
rowTitle: {
type: String,
default: "",
},
},
computed: {
...mapState(globalStore, ["activeSubMenu"]),
isActive() {
return this.rowTitle == this.activeSubMenu;
},
},
beforeUnmount() {
window.removeEventListener("click", this.onWindowClick);
},
methods: {
...mapActions(globalStore, [
"setActiveSubMenu",
"toggleMainMenu",
"setMainMenu",
]),
onKeyDown: function (event) {
// escape
if (event.keyCode == 27) {
this.setActiveSubMenu("");
}
},
storeActiveSubMenu() {
window.addEventListener("click", this.onWindowClick);
this.setActiveSubMenu(this.rowTitle);
},
// hides submenu when click is detected outside from it
onWindowClick(event) {
const form = this.$refs.content;
if (form != null) {
if (!form.contains(event.target)) {
this.setActiveSubMenu("");
this.setMainMenu(false);
}
return;
}
},
},
};
</script>
<style>
.menu-row h2 {
font-size: medium;
padding: 10px;
cursor: pointer;
border-bottom: 1px solid var(--dark3);
border-top: 1px solid var(--dark3);
margin: 0 0 10px 0;
}
select {
margin-top: 10px;
padding: 5px;
}
input[type="button"] {
min-width: 60px;
padding: 5px;
font-weight: bold;
margin-right: 10px;
}
.form-field {
display: flex;
margin: 10px;
justify-content: space-between;
}
.menu-row {
flex: 1;
position: relative;
}
.menu-row-content {
position: absolute;
background: var(--dark1);
width: 100%;
}
label,
.form-field label {
margin-right: 10px;
font-weight: bold;
}
@media screen and (max-width: 800px) {
.menu-row {
margin: 0 auto;
width: 100%;
}
.menu-row h2,
.form-field {
margin: 0;
}
.menu-row h2 {
border-bottom: 1px solid var(--dark3);
border-top: none;
}
.form-field {
padding: 10px;
}
/* .menu-row:active .menu-row-content {
display: flex;
flex-direction: column;
height: 100%;
} */
.menu-row-content {
position: relative;
width: 100%;
}
}
</style>

95
src/components/preset.js Normal file
View File

@ -0,0 +1,95 @@
const presetRuleset = [
{
name: "rule 73",
rules: {
100: 0,
101: 0,
110: 1,
111: 0,
"011": 1,
"010": 0,
"001": 0,
"000": 1,
},
},
{
name: "rule 86",
rules: {
100: 1,
101: 0,
110: 0,
111: 1,
"011": 0,
"010": 1,
"001": 0,
"000": 1,
},
},
{
name: "rule 90",
rules: {
100: 1,
101: 0,
110: 1,
111: 0,
"011": 0,
"010": 0,
"001": 1,
"000": 0,
},
},
{
name: "rule 45?",
rules: {
100: 0,
101: 0,
110: 1,
111: 0,
"011": 1,
"010": 0,
"001": 1,
"000": 1,
},
},
{
name: "rule 54?",
rules: {
100: 1,
101: 0,
110: 1,
111: 1,
"011": 0,
"010": 1,
"001": 1,
"000": 0,
},
},
{
name: "unknown rule",
rules: {
100: 0,
101: 0,
110: 0,
111: 1,
"011": 0,
"010": 0,
"001": 1,
"000": 1,
},
},
];
const initialStates = [
{
id: "onecell",
name: "One cell at center",
description: "State with a single cell in the middle",
},
{
id: "random",
name: "Random cell",
description: "State populated with random cells",
},
];
export { presetRuleset, initialStates };

View File

@ -1,26 +1,22 @@
// core functions to generate initial states and evolve them // handles negative index and index bigger than its array length
function guard(index, array) {
// get the next evolution of a 1D CA initial state if (index > array.length - 1) return 0;
// buggy BUT produces interesting results if (index < 0) return array.length - 1;
// function evolve1d(state, rules) { return index;
// const sl = state.length - 1; }
// return [
// rules[[state[sl - 1], state[sl], state[sl + 1]].join("")],
// ...state.map((_,x) => (rules[[state[x - 1], state[x], state[x + 1]].join("")])).slice(0, sl),
// rules[[state[0], state[1], state[2]].join("")]
// ]
// }
// get the next evolution of a 1D CA initial state // get the next evolution of a 1D CA initial state
function evolve1d(state, rules) { function evolve1d(state, rules) {
const sl = state.length - 1; function getCell(index) {
const edge1 = [state[sl - 2], state[sl - 1], state[sl]].join(""); const safeIndex = guard(index, state);
const edge2 = [state[0], state[1], state[2]].join(""); return state[safeIndex];
// normal case (3 neighbor cells) }
const center = state const newState = state.map((_, x) => {
.map((_, x) => rules[[state[x - 1], state[x], state[x + 1]].join("")]) const cells = [getCell(x - 1), getCell(x), getCell(x + 1)];
.slice(1, sl); return rules[cells.join("")];
return [rules[edge1], ...center, rules[edge2]]; });
return newState.map(Number);
} }
// create a 2D board from a 1D CA initial state // create a 2D board from a 1D CA initial state
@ -52,6 +48,31 @@ function createBoard(state, rules, max) {
return board; return board;
} }
// Find the neighbor of a given cell in a 2D CA board
function getCellNeighbors(board, cellCoordinates) {
const [x, y] = cellCoordinates;
const rowLength = board[0].length; // caca?
// handles board edges where the cell is missing neighbors
function getCell(xx, yy) {
const safeX = guard(xx, board);
const safeY = guard(yy, rowLength);
return board[safeX][safeY];
}
// the current cell is not included in the result
return [
getCell(x - 1, y - 1),
getCell(x, y - 1),
getCell(x + 1, y - 1),
getCell(x - 1, y),
getCell(x + 1, y),
getCell(x - 1, y + 1),
getCell(x, y + 1),
getCell(x + 1, y - 1),
];
}
// Sums the value of a cell's neighbors // Sums the value of a cell's neighbors
function getNeighborsSum(cells) { function getNeighborsSum(cells) {
return cells.reduce((cell, acc) => cell + acc, 0); return cells.reduce((cell, acc) => cell + acc, 0);
@ -70,30 +91,6 @@ function conwayRules(cell, neighbors) {
return cell; return cell;
} }
// Get the next evolution of a cell according to
// Conway's game of life rules
function servietteRules(cell, neighbors) {
// loneliness rule
if (cell === 0 && [2, 3, 4].find((x) => x == neighbors)) return 1;
// the cell remains the same if none apply
return 0;
}
// variation of the game of life where a
// cell comes to live if 6 neigbor cells are alive
function highLifeRules(cell, neighbors) {
// loneliness rule
if (cell === 1 && neighbors < 2) return 0;
// overpopulation rule
if (cell === 1 && neighbors > 3) return 0;
// born when three live neighbors rule
if (cell === 0 && neighbors === 2) return 1;
// highlife rules
if ((cell === 0 && neighbors === 3) || neighbors === 6) return 1;
// the cell remains the same if none apply
return cell;
}
// variation on the game of life's rules, // variation on the game of life's rules,
// where the "three live neighbors" rule is ignored // where the "three live neighbors" rule is ignored
function threebornRules(cell, neighbors) { function threebornRules(cell, neighbors) {
@ -130,31 +127,13 @@ function overpopulationRules(cell, neighbors) {
// get the next evolution of a 2D CA initial state // get the next evolution of a 2D CA initial state
// Rules : Moore neighborhood // Rules : Moore neighborhood
function evolve2d(board, rulesFn) { function evolve2d(board, rulesFn) {
const bh = board.length - 1; return board.map((row, x) =>
const bw = board[0].length - 1; row.map((cell, y) => {
return board.map((row, y) => { const neighbors = getCellNeighbors(board, [x, y]);
// handle edges
const prow = y - 1 < 0 ? board[bh] : board[y - 1];
const nrow = y + 1 > bh ? board[0] : board[y + 1];
return row.map((cell, x) => {
// handle edges too
const pcell = x - 1 < 0 ? bw : x - 1;
const ncell = x + 1 > bw ? 0 : x + 1;
// the current cell is not included in the result
const neighbors = [
prow[pcell],
prow[x],
prow[ncell],
row[pcell],
row[ncell],
nrow[pcell],
nrow[x],
nrow[ncell],
];
const sum = getNeighborsSum(neighbors); const sum = getNeighborsSum(neighbors);
return rulesFn(cell, sum); return rulesFn(cell, sum);
}); })
}); );
} }
function getDrawingValues(state, acc, cell) { function getDrawingValues(state, acc, cell) {
@ -205,8 +184,6 @@ export {
overpopulationRules, overpopulationRules,
lonelinessRules, lonelinessRules,
threebornRules, threebornRules,
highLifeRules,
servietteRules,
evolve1d, evolve1d,
evolve2d, evolve2d,
}; };

View File

@ -1,28 +0,0 @@
import { create2dState, create1dStateOneCell, create1dState } from "./core.js";
import { getRandomInt } from "./common.js";
function Board(width, height, grid = []) {
this.width = width;
this.height = height;
(this.cellProperties = {
size: 3,
liveColor: "#000000",
deadColor: "#F5F5F5",
}),
(this.grid = grid);
}
// create a first state, either a single living cell
// at the center or random ones
const create1dInitialState = (board, type = "onecell") => {
if (type === "onecell") return create1dStateOneCell(board.width);
return create1dState(board.width, getRandomInt, [0, 2]);
};
// initialize 2d board with random cells
const create2dRandomGrid = (width, height) => {
return create2dState(width, height, getRandomInt, [0, 2]);
};
export { Board, create1dInitialState, create2dRandomGrid };

View File

@ -1,13 +1,3 @@
// https://stackoverflow.com/questions/21646738/convert-hex-to-rgba
// [
function hexToRGB(hex) {
return [
parseInt(hex.slice(1, 3), 16),
parseInt(hex.slice(3, 5), 16),
parseInt(hex.slice(5, 7), 16),
];
}
// https://stackoverflow.com/questions/4492385/convert-simple-array-into-two-dimensional-array-matrix // https://stackoverflow.com/questions/4492385/convert-simple-array-into-two-dimensional-array-matrix
// convert a 1D array into a 2D matrix // convert a 1D array into a 2D matrix
export function toMatrix(array, width) { export function toMatrix(array, width) {
@ -36,45 +26,14 @@ export function picToBlackAndWhite(pixels, width, height) {
} }
// convert an ImageData into a 2D array of boolean (0, 1) values // convert an ImageData into a 2D array of boolean (0, 1) values
export function picToBoard(pixels, board) { export function picToBoard(pixels, width, height) {
const flat = pixels.reduce((acc, pixel, index) => { const flat = pixels.reduce((acc, pixel, index) => {
const i = index * 4; if (index % 4 == 0) {
const count = pixels[i] + pixels[i + 1] + pixels[i + 2]; const count = pixels[index] + pixels[index + 1] + pixels[index + 2];
const value = (count >= 255) & 1; const value = count >= 255 ? 1 : 0;
acc[index] = value; acc.push(value);
}
return acc; return acc;
}, []); }, []);
// TODO: The representation has to be 2D, not the data structure return toMatrix(flat, Math.max(width, height));
// (change to flat)
return toMatrix(flat, board.width, board.height);
}
// convert board to ImageData
// TODO : different cell to color functions
// (binary, intermediate states, camaieux, etc)
export function boardToPic(board) {
const live = board.cellProperties.liveColor;
const dead = board.cellProperties.deadColor;
const img = new ImageData(board.width, board.height);
const colors = [hexToRGB(live), hexToRGB(dead)];
board.grid.flat().reduce((acc, cell, index) => {
const color = colors[(cell === 1) & 1];
const i = index * 4;
acc[i] = color[0];
acc[i + 1] = color[1];
acc[i + 2] = color[2];
acc[i + 3] = 255;
return acc;
}, img.data);
return img;
}
// https://stackoverflow.com/questions/3332237/image-resizing-algorithm
export function scaleToTargetSize(w1, h1, w2, h2) {
const sourceRatio = w1 / h1;
const targetRatio = w2 / h2;
if (sourceRatio > targetRatio) {
return [w2, w2 / sourceRatio];
}
return [h2 * sourceRatio, h2];
} }

View File

@ -64,19 +64,6 @@ const presetRuleset = [
"000": 0, "000": 0,
}, },
}, },
{
name: "rule 30",
rules: {
100: 1,
101: 0,
110: 0,
111: 0,
"011": 1,
"010": 1,
"001": 1,
"000": 0,
},
},
{ {
name: "unknown rule", name: "unknown rule",
rules: { rules: {
@ -90,45 +77,6 @@ const presetRuleset = [
"000": 1, "000": 1,
}, },
}, },
{
name: "unknown rule 2",
rules: {
100: 1,
101: 0,
110: 1,
111: 0,
"011": 0,
"010": 0,
"001": 0,
"000": 1,
},
},
{
name: "rule 184",
rules: {
100: 1,
101: 1,
110: 0,
111: 1,
"011": 1,
"010": 0,
"001": 0,
"000": 0,
},
},
{
name: "rule 110",
rules: {
100: 0,
101: 1,
110: 1,
111: 0,
"011": 1,
"010": 1,
"001": 1,
"000": 0,
},
},
]; ];
const initialStates = [ const initialStates = [
@ -168,17 +116,6 @@ const preset2dRules = [
description: description:
"Variation on Conway's Game of Life *without* the 'three live neighbors' rule", "Variation on Conway's Game of Life *without* the 'three live neighbors' rule",
}, },
{
id: "highlife",
name: "HighLife variation",
description:
"Variation on Conway's Game of Life where a cell live if the six neighbor cells are alive",
},
{
id: "serviette",
name: "Serviette variation",
description: "bla",
},
]; ];
export { presetRuleset, initialStates, preset2dRules }; export { presetRuleset, initialStates, preset2dRules };

View File

@ -1,67 +0,0 @@
import { boardToPic, scaleToTargetSize } from "./picture.js";
function scaleAndApply(context, ratio, callback) {
context.save();
// rescale
context.imageSmoothingEnabled = false;
context.scale(ratio, ratio);
// apply
callback();
context.restore();
}
// draws the board representation on the canvas
function render(board) {
const d = board.cellProperties.size;
// bool to RGBA colors
const img = boardToPic(board);
this.ctx.clearRect(0, 0, this.width, this.height);
scaleAndApply(this.ctx, d, () => {
this.workCtx.putImageData(img, 0, 0);
this.ctx.drawImage(this.workCanvas, 0, 0, this.width, this.height);
});
}
// draw image on canvas
function renderImage(image, ctx, tw, th) {
ctx.fillStyle = "black";
ctx.fillRect(0, 0, tw, th);
const dimensions = scaleToTargetSize(image.width, image.height, tw, th);
ctx.drawImage(
image,
Math.floor((tw - dimensions[0]) / 2),
Math.floor((th - dimensions[1]) / 2),
dimensions[0],
dimensions[1]
);
return ctx.getImageData(0, 0, tw, th);
}
function resize(width, height) {
this.width = width;
this.height = height;
this.canvas.height = height;
this.canvas.width = width;
this.workCanvas.height = height;
this.workCanvas.width = width;
}
function reset() {
this.ctx.clearRect(0, 0, this.width, this.height);
}
function Renderer() {
this.canvas = null;
this.workCanvas = null;
this.workCtx = null;
this.width = null;
this.height = null;
this.ctx = null;
this.refreshRate = 300;
this.render = render;
this.renderImage = renderImage;
this.reset = reset;
this.resize = resize;
}
export { Renderer };

View File

@ -1,6 +1,4 @@
import { defineStore } from "pinia"; import { defineStore } from "pinia";
import { Board } from "../modules/board.js";
import { Renderer } from "../modules/renderer.js";
export const globalStore = defineStore("globalStore", { export const globalStore = defineStore("globalStore", {
state: () => { state: () => {
@ -23,75 +21,66 @@ export const globalStore = defineStore("globalStore", {
name: "Conway's Game of Life", name: "Conway's Game of Life",
description: "The most popular 2d automata", description: "The most popular 2d automata",
}, },
cellProperties: {
size: 3,
liveColor: "#000000",
deadColor: "#F5F5F5",
},
canvasWidth: 0,
canvasHeight: 0,
boardWidth: 0,
boardHeight: 0,
refreshRate: 300,
initial1dState: "onecell", initial1dState: "onecell",
drawingDirection: "y", drawingDirection: "y",
board: new Board(), lastBoard: {},
draw1d: false, draw1d: false,
draw2d: false, draw2d: false,
draw2dLast: false, draw2dLast: false,
draw2dpicture: false, draw2dpicture: false,
reset: false, reset: false,
canDraw: true, canDraw: true,
picture: new Image(), picture: null,
mainMenu: false, mainMenu: false,
activeSubMenu: "", activeSubMenu: "",
loop: true,
lastAction: "drawfromlast",
renderer: new Renderer(),
}; };
}, },
actions: { actions: {
setBoardWidth() { setBoardWidth() {
this.board.width = Math.floor( this.boardWidth = Math.floor(this.canvasWidth / this.cellProperties.size);
this.renderer.width / this.board.cellProperties.size
);
}, },
setBoardHeight() { setBoardHeight() {
this.board.height = Math.floor( this.boardHeight = Math.floor(
this.renderer.height / this.board.cellProperties.size this.canvasHeight / this.cellProperties.size
); );
}, },
setCellProperties(name, value) {
this.board.cellProperties[name] = value;
},
switchColor() {
[
this.board.cellProperties["liveColor"],
this.board.cellProperties["deadColor"],
] = [
this.board.cellProperties["deadColor"],
this.board.cellProperties["liveColor"],
];
},
toggleDraw1d() { toggleDraw1d() {
this.setActiveSubMenu(""); this.setActiveSubMenu("");
this.setMainMenu(false); this.setMainMenu(false);
this.draw1d = !this.draw1d; this.draw1d = true;
}, },
toggleDraw2d() { toggleDraw2d() {
this.setActiveSubMenu(""); this.setActiveSubMenu("");
this.lastAction = "draw2d";
this.setMainMenu(false); this.setMainMenu(false);
this.toggleStop(); this.toggleStop();
this.canDraw = !this.canDraw; this.canDraw = true;
this.draw2d = !this.draw2d; this.draw2d = true;
}, },
toggleDraw2dLast() { toggleDraw2dLast() {
this.setActiveSubMenu(""); this.setActiveSubMenu("");
this.lastAction = "drawfromlast";
this.setMainMenu(false); this.setMainMenu(false);
this.toggleStop(); this.toggleStop();
this.canDraw = !this.canDraw; this.canDraw = true;
this.draw2dLast = !this.draw2dLast; this.draw2dLast = true;
}, },
toggle2dDrawFromPicture() { toggle2dDrawFromPicture() {
this.toggleStop(); this.toggleStop();
this.canDraw = !this.canDraw; this.canDraw = true;
this.draw2dpicture = !this.draw2dpicture; this.draw2dpicture = true;
}, },
toggleReset() { toggleReset() {
this.toggleStop(); this.toggleStop();
this.reset = !this.reset; this.reset = true;
}, },
toggleStop() { toggleStop() {
this.draw1d = false; this.draw1d = false;
@ -100,21 +89,6 @@ export const globalStore = defineStore("globalStore", {
this.draw2dpicture = false; this.draw2dpicture = false;
this.canDraw = false; this.canDraw = false;
}, },
toggleLoop() {
this.loop = !this.loop;
},
toggleNext() {
switch (this.lastAction) {
case "drawfromlast":
this.toggleDraw2dLast();
break;
case "draw2d":
this.toggleDraw2d();
break;
default:
return;
}
},
setActiveSubMenu(data) { setActiveSubMenu(data) {
if (this.activeSubMenu == data) this.activeSubMenu = ""; if (this.activeSubMenu == data) this.activeSubMenu = "";
else this.activeSubMenu = data; else this.activeSubMenu = data;

View File

@ -1,28 +0,0 @@
import { describe, expect, test } from "vitest";
import {
Board,
create1dInitialState,
create2dRandomGrid,
} from "src/modules/board.js";
describe("Board", () => {
const board = new Board(503, 301);
test("create1dInitialState onecell", () => {
const stateOne = create1dInitialState(board);
expect(stateOne.length).toBe(board.width);
expect(stateOne).toContain(1);
});
test("create1dInitialState random", () => {
const stateRandom = create1dInitialState(board, "random");
expect(stateRandom.length).toBe(board.width);
expect(stateRandom).toContain(1);
});
test("create2dRandomGrid", () => {
const board = new Board(503, 301);
const got = create2dRandomGrid(board.width, board.height);
expect(got.length).toBe(board.height);
expect(got[0].length).toBe(board.width);
});
});

View File

@ -1,18 +0,0 @@
import { describe, expect, test } from "vitest";
import { evolve1d, create1dStateOneCell } from "src/modules/core.js";
import { presetRuleset } from "src/modules/preset.js";
describe("Core", () => {
test("evolve1d, rules73, 9 cells", () => {
const state = [0, 0, 0, 0, 1, 0, 0, 0, 0];
const got = evolve1d(state, presetRuleset[0].rules);
const valid = [1, 1, 1, 0, 0, 0, 1, 1, 1];
expect(got.length).toBe(state.length);
expect(got).toEqual(valid);
}),
test("create1dStateOneCell, 49 cells", () => {
const got = create1dStateOneCell(49);
expect(got.length).toBe(49);
expect(got[24]).toBe(1);
});
});

View File

@ -13,11 +13,4 @@ export default defineConfig({
"@": path.resolve(__dirname, "./src"), "@": path.resolve(__dirname, "./src"),
}, },
}, },
test: {
// enable jest-like global test APIs
globals: true,
// simulate DOM with happy-dom
// (requires installing happy-dom as a peer dependency)
environment: "happy-dom",
},
}); });