aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.envrc20
-rw-r--r--.gitignore3
-rw-r--r--README.org48
-rw-r--r--UNLICENSE24
-rwxr-xr-xbuild.sh11
-rw-r--r--doc/biblio.bib13
-rw-r--r--doc/gost/gost-7-32-bibliography.sty57
-rw-r--r--doc/gost/gost-7-32-captions.sty23
-rw-r--r--doc/gost/gost-7-32-counters.sty44
-rw-r--r--doc/gost/gost-7-32-headings.sty114
-rw-r--r--doc/gost/gost-7-32-lists.sty17
-rw-r--r--doc/gost/gost-7-32-tables.sty29
-rw-r--r--doc/gost/gost-7-32-toc.sty34
-rw-r--r--doc/gost/gost-7-32.cls62
-rw-r--r--doc/its.plt40
-rw-r--r--doc/ox-init.el31
-rw-r--r--doc/report.org735
-rw-r--r--doc/setup.org30
-rw-r--r--doc/spbstu-report.cls74
-rw-r--r--doc/task.org14
-rw-r--r--src/bitarray.c33
-rw-r--r--src/bitarray.h18
-rw-r--r--src/board.c36
-rw-r--r--src/board.h19
-rw-r--r--src/cellular-automaton.c49
-rw-r--r--src/cellular-automaton.h19
-rw-r--r--src/config.h52
-rw-r--r--src/dynamic-array.h59
-rw-r--r--src/main.c576
-rw-r--r--src/utils.h65
30 files changed, 2349 insertions, 0 deletions
diff --git a/.envrc b/.envrc
new file mode 100644
index 0000000..003f58a
--- /dev/null
+++ b/.envrc
@@ -0,0 +1,20 @@
1CHANNELS=./etc/channels-lock.scm
2MANIFEST=./etc/manifest.scm
3LOAD_PATH=./lib
4ROOT=./.guix-shell
5
6TIME_MACHINE_FLAGS+=" --channels=$CHANNELS"
7SHELL_FLAGS+=" --manifest=$MANIFEST"
8SHELL_FLAGS+=" --search-paths"
9SHELL_FLAGS+=" --root=$ROOT"
10SHELL_FLAGS+=" --load-path=$LOAD_PATH"
11
12use_guix_shell() {
13 test -d "$ROOT" && unlink "$ROOT"
14 eval "$(guix time-machine $TIME_MACHINE_FLAGS -- shell $SHELL_FLAGS "$@")"
15}
16
17use guix_shell
18export TEXINPUTS=${TEXINPUTS}:./:./gost/
19export LD_LIBRARY_PATH=${PWD}/.guix-shell/lib/:${LIBRARY_PATH}
20export LIBRARY_PATH=${PWD}/.guix-shell/lib/:${LIBRARY_PATH}
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..a7aea74
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,3 @@
1*.html
2*.pdf
3/main \ No newline at end of file
diff --git a/README.org b/README.org
new file mode 100644
index 0000000..7bac321
--- /dev/null
+++ b/README.org
@@ -0,0 +1,48 @@
1#+title: 2D cellular automaton
2#+date: 2024H2
3
4* Task
5:PROPERTIES:
6:CUSTOM_ID: task
7:END:
8Implement a two‑dimensional cellular automaton with a von Neumann
9neighborhood and it's visualization. The automaton’s functionality
10should include:
111. The ability to generate a random state.
122. The ability to manually configure the state.
133. The ability to set the field size.
144. The ability to determine the number of iterations.
15
16The automaton function: *7931880* (=0x007907E8=)
17
18* Documentation
19:PROPERTIES:
20:CUSTOM_ID: documentation
21:END:
22The exported report can be found at [[https://git.michalec.dev/files/uni/term-05/automata-theory/lab-01/report.pdf][this link]].
23
24* Showcase
25:PROPERTIES:
26:CUSTOM_ID: showcase
27:END:
28#+caption: Help
29#+attr_html: :width 75%
30[[https://git.michalec.dev/uni/term-05/automata-theory/lab-01/help.png][https://git.michalec.dev/uni/term-05/automata-theory/lab-01/help.png]]
31
32#+caption: Making cells live in while the automaton runs
33#+attr_html: :width 75%
34[[https://git.michalec.dev/uni/term-05/automata-theory/lab-01/sierpinsky.png][https://git.michalec.dev/uni/term-05/automata-theory/lab-01/sierpinsky.png]]
35
36#+caption: Sample initial state
37#+attr_html: :width 75%
38[[https://git.michalec.dev/uni/term-05/automata-theory/lab-01/gnu0.png][https://git.michalec.dev/uni/term-05/automata-theory/lab-01/gnu0.png]]
39
40#+caption: Sample state after 30 iterations
41#+attr_html: :width 75%
42[[https://git.michalec.dev/uni/term-05/automata-theory/lab-01/gnu30.png][https://git.michalec.dev/uni/term-05/automata-theory/lab-01/gnu30.png]]
43
44* Unlicense
45:PROPERTIES:
46:CUSTOM_ID: unlicense
47:END:
48#+include: UNLICENSE verse
diff --git a/UNLICENSE b/UNLICENSE
new file mode 100644
index 0000000..efb9808
--- /dev/null
+++ b/UNLICENSE
@@ -0,0 +1,24 @@
1This is free and unencumbered software released into the public domain.
2
3Anyone is free to copy, modify, publish, use, compile, sell, or
4distribute this software, either in source code form or as a compiled
5binary, for any purpose, commercial or non-commercial, and by any
6means.
7
8In jurisdictions that recognize copyright laws, the author or authors
9of this software dedicate any and all copyright interest in the
10software to the public domain. We make this dedication for the benefit
11of the public at large and to the detriment of our heirs and
12successors. We intend this dedication to be an overt act of
13relinquishment in perpetuity of all present and future rights to this
14software under copyright law.
15
16THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22OTHER DEALINGS IN THE SOFTWARE.
23
24For more information, please refer to <https://unlicense.org/>
diff --git a/build.sh b/build.sh
new file mode 100755
index 0000000..976f5aa
--- /dev/null
+++ b/build.sh
@@ -0,0 +1,11 @@
1#!/bin/sh
2
3set -xe
4
5gcc -O3 -ggdb3 -std=gnu99 \
6 `pkg-config --libs --cflags raylib` -lm \
7 -o ./main \
8 src/main.c \
9 src/cellular-automaton.c \
10 src/board.c \
11 src/bitarray.c
diff --git a/doc/biblio.bib b/doc/biblio.bib
new file mode 100644
index 0000000..cc53e65
--- /dev/null
+++ b/doc/biblio.bib
@@ -0,0 +1,13 @@
1@book{WOLFRAM2002,
2author = {Стивен Вольфрам},
3title = {Наука нового типа},
4publisher = {Wolfram Media},
5year = {2002},
6pages = {1197}
7}
8@online{VOSTROV2024,
9author = {Востров А. В},
10title = {Теория алгоритмов},
11url = {https://tema.spbstu.ru/algorithm/},
12urldate = {2024-12-01}
13}
diff --git a/doc/gost/gost-7-32-bibliography.sty b/doc/gost/gost-7-32-bibliography.sty
new file mode 100644
index 0000000..dca60fa
--- /dev/null
+++ b/doc/gost/gost-7-32-bibliography.sty
@@ -0,0 +1,57 @@
1\ProvidesPackage{gost-7-32-bibliography}[2022/01/28 GOST 7.32-2017]
2
3\def\UrlBreaks{\do\/\do-}
4\RequirePackage{url}
5
6\newdimen\bibindent
7\renewenvironment{thebibliography}[1]{
8 \chapter*{\bibname}\addcontentsline{toc}{chapter}{\bibname}%
9 \list{\@biblabel{\@arabic\c@enumiv}}%
10 {\settowidth\labelwidth{\@biblabel{#1}}%
11 \leftmargin\labelwidth
12 \advance\leftmargin\labelsep
13 \@openbib@code
14 \usecounter{enumiv}%
15 \let\p@enumiv\@empty
16 \renewcommand\theenumiv{\@arabic\c@enumiv}}%
17 \sloppy\clubpenalty4000\widowpenalty4000%
18 \sfcode`\.\@m
19}{
20 \setcounter{totalbib}{\c@enumiv}%
21 \def\@noitemerr
22 {\@latex@warning{Empty `thebibliography' environment}}%
23 \endlist
24}
25\renewcommand\@biblabel{}%
26\setlength\bibindent{1.5em}
27
28% Точки после номеров в библиографии. Несовместимо с natbib! -- Коротков И.
29%\makeatletter
30\renewcommand*{\@biblabel}[1]{\hfill#1.}
31
32
33%
34% Remove References header completely
35% Stolen from original article.cls
36%
37\makeatletter
38\renewenvironment{thebibliography}[1]{%
39% \usection{\refname}%
40% \@mkboth{\MakeUppercase\refname}{\MakeUppercase\refname}%
41 \list{\@biblabel{\@arabic\c@enumiv}}%
42 {\settowidth\labelwidth{\@biblabel{#1}}%
43 \leftmargin\labelwidth
44 \advance\leftmargin\labelsep
45 \@openbib@code
46 \usecounter{enumiv}%
47 \let\p@enumiv\@empty
48 \renewcommand\theenumiv{\@arabic\c@enumiv}}%
49 \sloppy
50 \clubpenalty4000
51 \@clubpenalty \clubpenalty
52 \widowpenalty4000%
53 \sfcode`\.\@m}
54 {\def\@noitemerr
55 {\@latex@warning{Empty `thebibliography' environment}}%
56 \endlist}
57\makeatother
diff --git a/doc/gost/gost-7-32-captions.sty b/doc/gost/gost-7-32-captions.sty
new file mode 100644
index 0000000..43447d5
--- /dev/null
+++ b/doc/gost/gost-7-32-captions.sty
@@ -0,0 +1,23 @@
1\ProvidesPackage{gost-7-32-captions}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{caption}
4\RequirePackage{subcaption}
5
6%
7% Table caption aligned to the left with dash as a separator
8%
9\captionsetup[table]{labelsep=endash, justification=centering, singlelinecheck=off}
10
11%
12% Dash as separator in figure caption and centering
13%
14\captionsetup[figure]{labelsep=endash, justification=centering}
15
16%
17% Listing caption
18%
19\captionsetup[listing]{labelsep=endash, skip=-0.5em, singlelinecheck=off, position=above}
20
21\addto\captionsrussian{\renewcommand{\figurename}{Рис.}}
22% \addto\captionsrussian{\renewcommand{\mintedname}{Рис.}}
23\addto\captionsrussian{\captionsetup[listing]{name=Рис.}}
diff --git a/doc/gost/gost-7-32-counters.sty b/doc/gost/gost-7-32-counters.sty
new file mode 100644
index 0000000..ee95480
--- /dev/null
+++ b/doc/gost/gost-7-32-counters.sty
@@ -0,0 +1,44 @@
1\ProvidesPackage{gost-7-32-counters}[2022/01/29 GOST 7.32-2017]
2
3%
4% Values for capital russian letters counter
5%
6\makeatletter
7\newcommand\AlphRus[1]{%
8 \expandafter \@AlphRus \csname c@#1\endcsname
9}
10
11\newcommand\@AlphRus[1]{%
12 \ifcase #1%
13 \or А\or Б\or В\or Г\or Д\or Е\or Ж\or И\or К\or
14 Л\or М\or Н\or П\or Р\or С\or Т\or У\or Ф\or
15 Х\or Ц\or Ш\or Щ\or Э\or Ю\or Я%
16 \else \@ctrerr
17\fi
18}
19\makeatother
20
21%
22% Values for lowercase russian letters counter
23%
24\makeatletter
25\newcommand\alphRus[1]{%
26 \expandafter \@alphRus \csname c@#1\endcsname
27}
28
29\newcommand\@alphRus[1]{%
30 \ifcase #1%
31 \or а\or б\or в\or г\or д\or е\or ж\or и\or к\or
32 л\or м\or н\or п\or р\or с\or т\or у\or ф\or
33 х\or ц\or ш\or щ\or э\or ю\or я%
34 \else \@ctrerr
35\fi
36}
37\makeatother
38
39% Increment figure counter when using lstlisting
40% \let\oldlstlisting\lstlisting
41% \renewcommand{\lstlisting}[1][]{%
42% \refstepcounter{figure}
43% \oldlstlisting[#1]
44% }
diff --git a/doc/gost/gost-7-32-headings.sty b/doc/gost/gost-7-32-headings.sty
new file mode 100644
index 0000000..cb2a7f0
--- /dev/null
+++ b/doc/gost/gost-7-32-headings.sty
@@ -0,0 +1,114 @@
1\ProvidesPackage{gost-7-32-headings}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{titlesec}
4\RequirePackage{titling}
5\RequirePackage{setspace}
6
7\RequirePackage{gost-7-32-counters}
8
9\setcounter{secnumdepth}{5}
10
11%
12% Set custom formatting to well-known LaTeX commands: section, subsection and subsubsection
13%
14\titleformat{\section}[block]{\centering\Large\setstretch{1}\bfseries}{\thesection}{0.5em}{}
15\titlespacing*{\section}{0cm}{0cm}{0.5cm}
16\newcommand{\sectionbreak}{\clearpage}
17
18\titleformat{\subsection}[block]{\Large\bfseries}{\thesubsection}{0.5em}{}
19\titlespacing{\subsection}{0cm}{0.5cm}{0.25cm}
20
21\titleformat{\subsubsection}[block]{\normalsize\bfseries}{\thesubsubsection}{0.5em}{}
22\titlespacing{\subsubsection}{0cm}{0.5em}{0.25cm}
23
24\titleformat{\paragraph}[block]{\normalsize\bfseries}{\theparagraph}{0.5em}{}
25\titlespacing*{\paragraph}{0cm}{0.5em}{0.25cm}
26
27\titleformat{\subparagraph}[block]{\normalsize\bfseries}{\thesubparagraph}{0.5em}{}
28\titlespacing{\subparagraph}{0cm}{0.5em}{0.25cm}
29
30\makeatletter
31\let\oldsection\section
32\newcommand{\@sectionnostar}[1]{\oldsection*{#1}\addcontentsline{toc}{section}{#1}}
33\newcommand{\@sectionstar}[1]{\oldsection{#1}}
34\renewcommand{\section}{\sectionbreak\@ifstar{\@sectionnostar}{\@sectionstar}}
35\makeatother
36
37%
38% Make special headings, that have their own formatting rules:
39% - centered
40% - all-caps
41% - bold
42%
43% Only three of them must appear in TOC: introduction, conclusion and references
44%
45\newcommand{\introduction}{
46 \addcontentsline{toc}{section}{ВВЕДЕНИЕ}
47 \begin{center}
48 \bfseries\large
49 ВВЕДЕНИЕ
50 \end{center}
51}
52
53\newcommand{\conclusion}{
54 \addcontentsline{toc}{section}{ЗАКЛЮЧЕНИЕ}
55 \begin{center}
56 \bfseries\large
57 ЗАКЛЮЧЕНИЕ
58 \end{center}
59}
60
61\newcommand{\references}{
62 \addcontentsline{toc}{section}{СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ}
63 \begin{center}
64 \bfseries\large
65 СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ
66 \end{center}
67}
68
69\newcommand{\essay}{
70 \begin{center}
71 \bfseries\large
72 РЕФЕРАТ
73 \end{center}
74}
75
76\newcommand{\definitions}{
77 \begin{center}
78 \bfseries\large
79 ОПРЕДЕЛЕНИЯ
80 \end{center}
81}
82
83\newcommand{\abbreviations}{
84 \begin{center}
85 \bfseries\large
86 ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ
87 \end{center}
88}
89
90\newcommand{\defsabbrs}{
91 \begin{center}
92 \bfseries\large
93 ОПРЕДЕЛЕНИЯ, ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ
94 \end{center}
95}
96
97%
98% Appendices headings. Appendices have autoincrementing number,
99% that is represented with russian letter.
100% This heading must appear in TOC
101%
102\newcounter{appendixcnt}
103\setcounter{appendixcnt}{1}
104
105\renewcommand{\appendix}[1]{
106 \addcontentsline{toc}{section}{ПРИЛОЖЕНИЕ \AlphRus{appendixcnt}. #1}
107 \begin{center}
108 \bfseries\large
109 ПРИЛОЖЕНИЕ \AlphRus{appendixcnt}
110
111 #1
112 \end{center}
113 \stepcounter{appendixcnt}
114}
diff --git a/doc/gost/gost-7-32-lists.sty b/doc/gost/gost-7-32-lists.sty
new file mode 100644
index 0000000..6f41980
--- /dev/null
+++ b/doc/gost/gost-7-32-lists.sty
@@ -0,0 +1,17 @@
1\ProvidesPackage{gost-7-32-lists}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{enumitem}
4\RequirePackage{gost-7-32-counters}
5
6\AddEnumerateCounter*{\alphRus}{\c@alphRus}{1}
7
8\setlist{nosep}
9\setlist[itemize, 1]{label=\textendash}
10\setlist[itemize, 2]{label=\bullet}
11\setlist[itemize, 3]{label=\bullet}
12
13\setlist[enumerate, 2]{label=\alphRus*)}
14
15\setlist[1]{wide=\parindent}
16\setlist[2]{wide=2\parindent, leftmargin=\parindent}
17\setlist[3]{wide=2\parindent}
diff --git a/doc/gost/gost-7-32-tables.sty b/doc/gost/gost-7-32-tables.sty
new file mode 100644
index 0000000..750ab75
--- /dev/null
+++ b/doc/gost/gost-7-32-tables.sty
@@ -0,0 +1,29 @@
1\ProvidesPackage{gost-7-32-tables}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{tabularx}
4
5%
6% Center-aligned column with automatic width
7%
8\newcolumntype{Y}{>{\centering\arraybackslash}X}
9
10%
11% Right-aligned column with automatic width
12%
13\newcolumntype{Z}{>{\raggedleft\arraybackslash}X}
14
15%
16% Table with designations
17%
18\newenvironment{designations}{
19 \noindent
20 \tabularx{\textwidth}{@{}
21 >{\raggedright \arraybackslash \hsize=0.25\hsize}X
22 >{\centering \arraybackslash \hsize=0.05\hsize}X
23 >{\arraybackslash \hsize=0.70\hsize}X
24 }
25}{
26 \endtabularx
27}
28
29\newcommand{\designation}[2]{#1 &---& #2. \\}
diff --git a/doc/gost/gost-7-32-toc.sty b/doc/gost/gost-7-32-toc.sty
new file mode 100644
index 0000000..328079d
--- /dev/null
+++ b/doc/gost/gost-7-32-toc.sty
@@ -0,0 +1,34 @@
1\ProvidesPackage{gost-7-32-toc}[2022/01/28 GOST 7.32-2017]
2
3\RequirePackage{tocloft}
4\RequirePackage[
5 bookmarks=true,
6 colorlinks=true,
7 unicode=true,
8 urlcolor=black,
9 linkcolor=black,
10 anchorcolor=black,
11 citecolor=black,
12 menucolor=black,
13 filecolor=black,
14 hidelinks
15]{hyperref}
16
17%
18% Set custom font styles
19%
20\renewcommand{\cftsecfont}{\normalfont}
21\renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}}
22\renewcommand{\cftsecpagefont}{\normalsize}
23\renewcommand{\cftaftertoctitle}{\hfill\hfill}
24\renewcommand{\cfttoctitlefont}{\hfill\normalfont\large\bfseries}
25\titleformat{\tableofcontents}[block]{\centering\large\bfseries}{\thesection}{0.5em}{}
26\titlespacing{\tableofcontents}{0cm}{0cm}{1cm}
27
28%
29% Set indents and line spacing
30%
31\setlength{\cftbeforesecskip}{0cm}
32\setlength{\cftbeforesubsecskip}{0cm}
33\setlength{\cftbeforesubsubsecskip}{0cm}
34\setlength{\cftbeforeparaskip}{0cm}
diff --git a/doc/gost/gost-7-32.cls b/doc/gost/gost-7-32.cls
new file mode 100644
index 0000000..c13b00e
--- /dev/null
+++ b/doc/gost/gost-7-32.cls
@@ -0,0 +1,62 @@
1\NeedsTeXFormat{LaTeX2e}
2\ProvidesClass{gost-7-32}[2022/01/28 GOST 7.32-2017]
3
4%
5% Supported font sizes: 12pt, 14pt
6%
7\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
8\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
9
10\ProcessOptions\relax
11
12%
13% Set A4 paper format
14%
15\LoadClass[a4paper]{extarticle}
16
17%
18% Use 1.5 line spacing
19%
20\RequirePackage{setspace}
21\spacing{1.5}
22
23%
24% First paragraph indentation
25%
26\RequirePackage{indentfirst}
27\setlength{\parindent}{12.5mm}
28
29%
30% Page margin
31%
32\RequirePackage[
33 left=2.5cm,
34 right=2cm,
35 top=2cm,
36 bottom=2cm,
37 footskip=1cm,
38]{geometry}
39
40%
41% Use TMR-like font
42%
43\RequirePackage{fontspec}
44\RequirePackage{xunicode}
45\defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text}
46\setmainfont{Times New Roman}
47
48%
49% Use russian language
50%
51\RequirePackage[main=russian, english]{babel}
52\babelhyphenation[russian]{}
53
54%
55% gost-7-32 packages
56%
57\RequirePackage{gost-7-32-headings}
58\RequirePackage{gost-7-32-toc}
59\RequirePackage{gost-7-32-lists}
60\RequirePackage{gost-7-32-bibliography}
61\RequirePackage{gost-7-32-captions}
62\RequirePackage{gost-7-32-tables}
diff --git a/doc/its.plt b/doc/its.plt
new file mode 100644
index 0000000..944674e
--- /dev/null
+++ b/doc/its.plt
@@ -0,0 +1,40 @@
1# -*- Gnuplot -*-
2# its.plt --- Plot...
3
4set term cairolatex pdf input \
5 blacktext notransparent nocrop \
6 size 12cm,6cm \
7 noheader
8
9set size ratio 0.5
10set lmargin at screen 0.1
11set rmargin at screen 0.9
12set bmargin at screen 0.1
13set tmargin at screen 0.95
14
15set output "./res/its.tex"
16
17set x2label "Номер итерации"
18set y2label "Количество «живых» клеток"
19unset key
20unset grid
21# set grid x mx y my
22# set grid linestyle 1 palette
23# set tics out
24# set xtics .5/3**(n), 1./3**(n - 1), 1 - .5/3**(n)
25# set ytics .5/3**(n), 1./3**(n - 1), 1 - .5/3**(n)
26# set mxtics 3
27# set mytics 3
28# set format x ""
29# set format y ""
30set xrange [1:400]
31set yrange [120:200]
32
33plot for [i=2:11] "./res/its.dat" using 1:i \
34 with lines \
35 linetype 1 linewidth 1 linecolor i
36
37set output "./res/avg.tex"
38plot "./res/avg.dat" using 1:2 \
39 with lines \
40 linetype 1 linewidth 1 linecolor 8
diff --git a/doc/ox-init.el b/doc/ox-init.el
new file mode 100644
index 0000000..671adce
--- /dev/null
+++ b/doc/ox-init.el
@@ -0,0 +1,31 @@
1;;; ox-init.el --- Initialization script for async org exprort session
2;;; Commentary:
3;;; Code:
4(org-babel-do-load-languages
5 'org-babel-load-languages
6 '((latex . t)
7 (C . t)))
8
9(require 'ox-extra)
10(ox-extras-activate '(ignore-headlines))
11
12(setq org-latex-src-block-backend 'minted)
13
14(require 'oc-bibtex)
15(setq org-latex-bib-compiler "biber")
16
17(setq org-latex-remove-logfiles nil)
18
19(setq org-latex-caption-above '(table src-block))
20
21(setq org-latex-pdf-process '("%latex -shell-escape -interaction nonstopmode -output-directory %o %f"
22 "%bib %b"
23 "%latex -shell-escape -interaction nonstopmode -output-directory %o %f"))
24(setq org-latex-classes '(("spbstu-report" "\\documentclass[12pt]{spbstu-report}"
25 ("\\section{%s}" . "\\section*{%s}")
26 ("\\subsection{%s}" . "\\subsection*{%s}")
27 ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
28 ("\\paragraph{%s}" . "\\paragraph*{%s}")
29 ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))))
30
31;;; ox-init.el ends here
diff --git a/doc/report.org b/doc/report.org
new file mode 100644
index 0000000..bf5439e
--- /dev/null
+++ b/doc/report.org
@@ -0,0 +1,735 @@
1#+title: Двумерный клеточный автомат
2#+author: Михалец М.
3#+latex_header: \reportof{О ВЫПОЛНЕНИИ ЛАБОРАТОРНОЙ РАБОТЫ №1}
4#+latex_header: \subject{по дисциплине «Теория алгоритмов»}
5#+latex_header: \university{Федеральное государственное автономное образовательное учреждение высшего образования \enquote{Санкт-Петербургский политехнический университет Петра Великого}}
6#+latex_header: \institute{Институт компьютерных наук и кибербезопасности}
7#+latex_header: \school{Высшая школа технологии искусственного интеллекта}
8#+latex_header: \direction{02.03.01 Математика и компьютерные науки}
9#+latex_header: \reviewertitle{}\reviewer{Востров А.В.}
10#+latex_header: \city{Санкт-Петербург}
11#+date: 2024
12
13#+latex_header: \newcommand{\overbar}[1]{\mkern1.5mu\overline{\mkern-1.5mu#1\mkern-1.5mu}\mkern 1.5mu}
14
15#+latex_header: \newcommand{\cellboard}[3]{
16#+latex_header: \begin{tikzpicture}[scale=#2]
17#+latex_header: \foreach \x in {0,...,#1} {
18#+latex_header: \foreach \y in {0,...,#1} {
19#+latex_header: \fill[black] (\x,\y) rectangle (\x+1,\y+1);
20#+latex_header: }
21#+latex_header: }
22#+latex_header: \foreach \x/\y in {#3} {
23#+latex_header: \fill[white] (\x,\y) rectangle (\x+1,\y+1);
24#+latex_header: }
25#+latex_header: \draw[step=1cm, color=gray] (0,0) grid (#1+1,#1+1);
26#+latex_header: \end{tikzpicture}
27#+latex_header: }
28
29#+setupfile: setup.org
30#+latex: \sloppy
31
32* ВВЕДЕНИЕ
33:PROPERTIES:
34:UNNUMBERED: t
35:END:
36Данный отчёт содержит в себе описание лабораторной работы №1 по
37дисциплине «Теория Алгоритмов». В задание входили реализация
38двумерного клеточного автомата с окрестностью фон Неймана и его
39визуализация. В функционале автомата должны присутствовать:
401. Возможность генерации случайного состояния.
412. Возможность ручной настройки состояния.
423. Возможность задания размеров поля.
434. Возможность определения количества итерации.
44
45Функция рассмотрена в данной работе: *7931880* (=0x007907E8=)
46
47* Математическое описание
48** Клеточный автомат
49/Клеточный автомат/ --- это регулярная структура динамических объектов
50(клеток), функционирующих синхронно. Клеточные автоматы моделируют
51процессы, разворачивающиеся в дискретном пространстве и в дискретном
52времени.
53
54Клеточный автомат имеет состояние, определяемое как набор (вектор или
55матрица) состояний компонентных автоматов. Каждый автомат
56функционирует как автомат Мура, т.е. это автомат без выхода, выходом
57является его состояние. Вход на каждом шаге клеточного автомата
58состояния его соседей. На следующем шаге (в следующем такте) новое
59состояние каждого автомата определяется как функция его текущего
60состояния и текущих состояний его соседей.
61
62Обычно правила изменения состояний всех автоматов (кроме граничных)
63идентичны (однородность системы), множество состояний каждого автомата
64--- конечно. Изменение состояния системы во всех клетках происходит
65синхронно: состояния клеток меняются одновременно на каждом такте.
66
67*** Описание функции и тип реализованного клеточного автомата
68Для данного варианта была задана функция обновления автомата на новой
69итерации: 7931880 (вариант 15) в десятичной системе счисления,
70007907E8 в шестнадцатеричной и 0000 0000 0111 1001 0000 0111 1110 1000
71в двоичной. Для получения функции обновления клеточного автомата на
72новой итерации была построена таблица истинности, где переменными
73являются значения клеток из окрестности фон Неймана. Полученная
74таблица истинности приведена в таблице [[truth-table]]. Будем считать,
75что значение 1 -- клетка жива, 0 -- клетка мертва. Тогда для
76получения состояния клетки на следующей итерации можно воспользоваться
77формулой:
78
79#+begin_export latex
80\begin{aligned}
81 F_{+1} =\,&(\overbar{s_{0}}\overbar{s_{1}}\overbar{s_{2}}s_{3}s_{4}) \lor
82 (\overbar{s_{0}}\overbar{s_{1}}s_{2}\overbar{s_{3}}s_{4}) \lor
83 (\overbar{s_{0}}\overbar{s_{1}}s_{2}s_{3}\overbar{s_{4}}) \lor
84 (\overbar{s_{0}}\overbar{s_{1}}s_{2}s_{3}s_{4})\,\lor\\
85 \lor\,&(\overbar{s_{0}}s_{1}\overbar{s_{2}}\overbar{s_{3}}\overbar{s_{4}}) \lor
86 (\overbar{s_{0}}s_{1}\overbar{s_{2}}\overbar{s_{3}}s_{4}) \lor
87 (\overbar{s_{0}}s_{1}\overbar{s_{2}}s_{3}\overbar{s_{4}}) \lor
88 (s_{0}\overbar{s_{1}}\overbar{s_{2}}\overbar{s_{3}}\overbar{s_{4}})\,\lor\\
89 \lor\,&(s_{0}\overbar{s_{1}}\overbar{s_{2}}s_{3}s_{4})\,\lor
90 (s_{0}\overbar{s_{1}}s_{2}\overbar{s_{3}}\overbar{s_{4}}) \lor
91 (s_{0}\overbar{s_{1}}s_{2}\overbar{s_{3}}s_{4}) \lor
92 (s_{0}\overbar{s_{1}}s_{2}s_{3}\overbar{s_{4}})\\
93\end{aligned}
94#+end_export
95
96Где:
97- $F_{+1}$ --- состояние клетки на следующей итерации
98- $s_{0}, s_{1}, s_{2}, s_{3}, s_{4}$ --- состояния клеток из
99 окрестности фон Неймана на текущей итерации.
100
101#+name: truth-table
102#+caption: Таблица истинности реализованного леточного автомата
103#+attr_latex: :align |r|ccccc|c|
104|----+---------+---------+---------+---------+---------+----------|
105| № | $s_{0}$ | *$s_{1}$* | *$s_{2}$* | *$s_{3}$* | *$s_{4}$* | *$F_{+1}$* |
106|----+---------+---------+---------+---------+---------+----------|
107| 0 | 0 | 0 | 0 | 0 | 0 | 0 |
108| 1 | 0 | 0 | 0 | 0 | 1 | 0 |
109| 2 | 0 | 0 | 0 | 1 | 0 | 0 |
110|----+---------+---------+---------+---------+---------+----------|
111| *3* | *0* | *0* | *0* | *1* | *1* | *1* |
112|----+---------+---------+---------+---------+---------+----------|
113| 4 | 0 | 0 | 1 | 0 | 0 | 0 |
114|----+---------+---------+---------+---------+---------+----------|
115| *5* | *0* | *0* | *1* | *0* | *1* | *1* |
116| *6* | *0* | *0* | *1* | *1* | *0* | *1* |
117| *7* | *0* | *0* | *1* | *1* | *1* | *1* |
118| *8* | *0* | *1* | *0* | *0* | *0* | *1* |
119| *9* | *0* | *1* | *0* | *0* | *1* | *1* |
120| *10* | *0* | *1* | *0* | *1* | *0* | *1* |
121|----+---------+---------+---------+---------+---------+----------|
122| 11 | 0 | 1 | 0 | 1 | 1 | 0 |
123| 12 | 0 | 1 | 1 | 0 | 0 | 0 |
124| 13 | 0 | 1 | 1 | 0 | 1 | 0 |
125| 14 | 0 | 1 | 1 | 1 | 0 | 0 |
126| 15 | 0 | 1 | 1 | 1 | 1 | 0 |
127|----+---------+---------+---------+---------+---------+----------|
128| *16* | *1* | *0* | *0* | *0* | *0* | *1* |
129|----+---------+---------+---------+---------+---------+----------|
130| 17 | 1 | 0 | 0 | 0 | 1 | 0 |
131| 18 | 1 | 0 | 0 | 1 | 0 | 0 |
132|----+---------+---------+---------+---------+---------+----------|
133| *19* | *1* | *0* | *0* | *1* | *1* | *1* |
134| *20* | *1* | *0* | *1* | *0* | *0* | *1* |
135| *21* | *1* | *0* | *1* | *0* | *1* | *1* |
136| *22* | *1* | *0* | *1* | *1* | *0* | *1* |
137|----+---------+---------+---------+---------+---------+----------|
138| 23 | 1 | 0 | 1 | 1 | 1 | 0 |
139| 24 | 1 | 1 | 0 | 0 | 0 | 0 |
140| 25 | 1 | 1 | 0 | 0 | 1 | 0 |
141| 26 | 1 | 1 | 0 | 1 | 0 | 0 |
142| 27 | 1 | 1 | 0 | 1 | 1 | 0 |
143| 28 | 1 | 1 | 1 | 0 | 0 | 0 |
144| 29 | 1 | 1 | 1 | 0 | 1 | 0 |
145| 30 | 1 | 1 | 1 | 1 | 0 | 0 |
146| 31 | 1 | 1 | 1 | 1 | 1 | 0 |
147|----+---------+---------+---------+---------+---------+----------|
148
149/Окрестность фон Неймана порядка $r$/ --- множество клеток,
150манхэттенское расстояние до которых от данной клетки не превышает $r$
151Окрестность фон Неймана порядка $r$ имеет форму ромба и включает в
152себя $C_{4,r+1}$ клеток, где $C_{4,n} = n^2 + (n - 1)^2$ --- n-е
153центрированное квадратное число.
154
155В данной работе рассматривается окрестность размера $r = 1$ в
156двумерном пространстве. Окрестность фон Неймана порядка $r = 1$ и
157расположение переменных функции изображены на рисунке
158[[von-neumann-neighborhood]].
159
160#+name: von-neumann-neighborhood
161#+caption: Окрестность фон Неймана
162#+begin_figure
163\centering
164\begin{tikzpicture}
165 % Highlight the central cells
166 \fill[yellow!50] (2, 2) rectangle (3, 3); % s0
167 \fill[green!50] (2, 3) rectangle (3, 4); % s1
168 \fill[green!50] (2, 1) rectangle (3, 2); % s2
169 \fill[green!50] (1, 2) rectangle (2, 3); % s3
170 \fill[green!50] (3, 2) rectangle (4, 3); % s4
171
172 % Draw the grid
173 \draw[step=1cm, black, thin] (0, 0) grid (5, 5);
174
175 % Add labels to the cells
176 \node at (2.5, 2.5) {$s_{0}$};
177 \node at (2.5, 3.5) {$s_{1}$};
178 \node at (2.5, 1.5) {$s_{2}$};
179 \node at (1.5, 2.5) {$s_{3}$};
180 \node at (3.5, 2.5) {$s_{4}$};
181\end{tikzpicture}
182#+end_figure
183
184Для получения информации о состоянии клеток на следующей итерации из
185таблицы истинности берутся значения переменных при значениях функции
186равных 1 (выделено жирно в таблице [[truth-table]]) и согласно окрестности
187фон Неймана анализируется текущее состояние поля клегочного автомата.
188Так, например, для 10-ой строки таблицы истинности данного варианта на
189следующей итерации клетка будет жить если:
1901. центральная клетка была мертва
1912. клетка сверху была жива
1923. клетка снизу была мертва
1934. клетка слева была жива
1945. клетка справа была мертва
195
196Это одно из условий жизни клетки перечисленных в порождающей функции.
197В данном варианте клетка будет жить всего при 12 различных условиях её
198окрестности фон Неймана. В остальных 20 случаях клетка на следующей
199итерации будет мёртвой.
200
201Для разрешения граничных случаев было выбрано тороидальное граничное
202условие. При этом условии значения выходящие за границы поля берутся
203с противоположного границ поля, образуя цикл или «тор». Для
204определения значения клеток в граничных условиях можно использовать
205формулу:
206
207#+begin_export latex
208\begin{displaymath}
209 C_{\textrm{тор}}(i, j) = C(i \bmod m, j \bmod n)
210\end{displaymath}
211#+end_export
212где:
213- $C_{\textrm{тор}}$ --- состояние клетки на тороидальной плоскости;
214- $C(i, j)$ --- состояние клетки с координатами $i,j$;
215- $i$ --- индекс строки, $0 \le i < m$;
216- $i$ --- индекс столбца, $0 \le i < n$;
217- $m$ --- количество клеток в каждом столбце клеточного автомата;
218- $n$ --- количество клеток в каждой строке клеточного автомата.
219
220* Особенности реализации
221Проекта реализован тремя основными абстракциями: битовый массив ---
222предоставляет интерфейс для работы с отдельными битами массива байтов;
223доска --- предоставляет интерфейс для работы с битами битового массива
224как будто бы они были расположены на тороидальной плоскости; конечный
225автомат --- предоставляет интерфейс продвижения доски к следующему её
226состоянию.
227
228Обработка событий пользователя как и визуализация реализованы подходом
229немедленного режима по следующему алгоритму:
2301. Инициализация
2312. Если приложение должно закрыться, переход к шагу 7.
2323. Обработка действий пользователя
2334. Обновление собственного состояния
2345. Отрисовка кадра
2356. Переход к шагу 2.
2367. Деинициализация
237
238Такой вид реализации позволяет симулировать полноэкранную доску
239(294000 клеток при разрешений 1366x768) при 20 кадрах (итерациях
240автомата) в секунду на процессоре выпущенном в 2012 год (Intel
241i5-3320M (4) @ 3.300GHz).
242
243** Абстракции
244*** Битовый массив
245~bitarray~ --- абстракция предоставляющая интерфейс для работы с
246отдельными битами массива байтов. В ней хранятся:
247- ~uint8_t *bytes~ --- указатель на массив байтов;
248- ~size_t size~ --- размер выделенной памяти под массив байтов.
249
250**** Интерфейс
251#+begin_src C
252struct bitarray {
253 uint8_t *bytes;
254 size_t size;
255};
256
257void bitarray_init (struct bitarray *, size_t bit_count);
258void bitarray_free (struct bitarray *);
259void bitarray_set (struct bitarray *, size_t index, bool);
260bool bitarray_get (struct bitarray *, size_t index);
261#+end_src
262
263**** Функция инициализации
264- Вход: :: указатель на структуру битового массива и количество битов
265 -- его размер.
266- Выход: :: инициализированная структура битового массива с выделенной
267 памятью под хранение указанного количества битов.
268#+begin_src C
269void
270bitarray_init (struct bitarray *bitarray, size_t bit_count)
271{
272 bitarray->size = CEIL_INT_DIV (bit_count, 8);
273 bitarray->bytes = calloc (bitarray->size, 1);
274}
275#+end_src
276
277**** Функция установки значения бита
278- Вход: :: указатель на структуру битового массива, индекс бита и его
279 требуемое значение.
280- Выход: :: изменена структура битового массива с указанным значением
281 установленным на указанном индексе.
282#+begin_src C
283void
284bitarray_set (struct bitarray *bitarray, size_t index, bool value)
285{
286 ASSERT (bitarray);
287 ASSERT (bitarray->bytes);
288 ASSERT (index >> 3 < bitarray->size);
289 setbit (bitarray->bytes, index, value);
290}
291#+end_src
292где функция ~setbit~ определена следующим образом:
293- Вход: :: указатель на массив байтов, индекс бита и его требуемое
294 значение.
295- Выход: :: изменена массив байтов с указанным значением установленным
296 на указанном индексе.
297#+begin_src C
298inline void
299setbit (uint8_t *bytes, size_t index, bool value)
300{
301 uint8_t *byte = &bytes[index >> 3];
302 uint8_t offset = index & ((1 << 3) - 1);
303 uint8_t mask = ~(1 << offset);
304 ,*byte = *byte & mask | value << offset;
305}
306#+end_src
307
308**** Функция получения значения бита
309- Вход: :: указатель на структуру битового массива и индекс бита.
310- Выход: :: значение бита битового массива на указанном индексе.
311#+begin_src C
312bool
313bitarray_get (struct bitarray *bitarray, size_t index)
314{
315 ASSERT (bitarray);
316 ASSERT (bitarray->bytes);
317 ASSERT (index >> 3 < bitarray->size);
318 return getbit (bitarray->bytes, index);
319}
320#+end_src
321где функция ~getbit~ определена следующим образом:
322- Вход: :: указатель на массив байтов и индекс бита.
323- Выход: :: значение бита массива байтом на указанном индексе.
324#+begin_src C
325inline bool
326getbit (uint8_t *bytes, size_t index)
327{
328 uint8_t byte = bytes[index >> 3];
329 uint8_t offset = index & ((1 << 3) - 1);
330 uint8_t mask = 1 << offset;
331 return (byte & mask) >> offset;
332}
333#+end_src
334
335**** Функция освобождения памяти
336- Вход: :: указатель на структуру битового массива.
337- Выход: :: структура битовой массив без выделенной памяти.
338#+begin_src C
339void
340bitarray_free (struct bitarray *bitarray)
341{
342 FREE (bitarray->bytes);
343}
344#+end_src
345
346*** Доска
347~board~ --- абстракция предоставляющая интерфейс для работы с битами
348битового массива как будто бы это были клетки расположены на
349тороидальной плоскости. В ней хранятся:
350- ~struct bitarray cells~ --- битовый массив хранящий состояния клеток доски;
351- ~uint32_t rows~ --- количество строк доски;
352- ~uint32_t cols~ --- количество столбцов доски.
353
354**** Интерфейс
355#+begin_src C
356struct board {
357 struct bitarray cells;
358 uint32_t rows;
359 uint32_t cols;
360};
361
362void board_init (struct board *, uint32_t rows, uint32_t cols);
363void board_free (struct board *);
364void board_set (struct board *, int32_t row, int32_t col, bool);
365bool board_get (struct board *, int32_t row, int32_t col);
366#+end_src
367
368**** Функция инициализации
369- Вход: :: указатель на структуру доски, количество строк и столбцов.
370- Выход: :: инициализированная доска с выделенной памятью под указанное
371 количество строк и столбцов.
372#+begin_src C
373void
374board_init (struct board *board, uint32_t rows, uint32_t cols)
375{
376 bitarray_init (&board->cells, rows*cols);
377 board->rows = rows;
378 board->cols = cols;
379}
380#+end_src
381
382**** Функция установления значения клетки
383- Вход: :: указатель на структуру доски, индексы строки и столбца
384 клетки, и устанавливаемое значение.
385- Выход: :: структура доски с установленным указанным значением в
386 указанной клетке.
387#+begin_src C
388void
389board_set (struct board *board, int32_t row, int32_t col, bool value)
390{
391 ASSERT (board);
392
393 row = MOD (row, (int32_t) board->rows);
394 col = MOD (col, (int32_t) board->cols);
395 bitarray_set (&board->cells, row*board->cols + col, value);
396}
397#+end_src
398
399**** Функция извлечения значения клетки
400- Вход: :: указатель на структуру доски, индексы строки и столбца
401 клетки.
402- Выход: :: значение указанной клетки.
403#+begin_src C
404bool
405board_get (struct board *board, int32_t row, int32_t col)
406{
407 ASSERT (board);
408
409 row = MOD (row, (int32_t) board->rows);
410 col = MOD (col, (int32_t) board->cols);
411 return bitarray_get (&board->cells, row*board->cols + col);
412}
413#+end_src
414
415**** Функция освобождения памяти
416- Вход: :: указатель на структуру доски.
417- Выход: :: структура доски без выделенной памяти.
418#+begin_src C
419void
420board_free (struct board *board)
421{
422 bitarray_free (&board->cells);
423}
424#+end_src
425
426*** Клеточный автомат
427~cellular_automaton~ --- абстракция предоставляющая интерфейс
428продвижения доски к следующему её состоянию. В ней хранятся:
429- ~struct board board~ --- доска;
430- ~uint8_t *back_board_bitarray~ --- фоновая память для хранения
431 промежуточного результата при переходе к следующему состоянию;
432- ~uint32_t function~ --- функция перехода к следующему состоянию,
433 представлена в виде 32 битовой строки.
434
435**** Интерфейс
436#+begin_src C
437struct cellular_automaton {
438 struct board board;
439 uint8_t *back_board_bitarray;
440 uint32_t function;
441};
442
443void cellular_automaton_init (struct cellular_automaton *,
444 uint32_t function,
445 uint32_t rows, uint32_t cols);
446void cellular_automaton_free (struct cellular_automaton *);
447void cellular_automaton_progress (struct cellular_automaton *);
448#+end_src
449
450**** Функция инициализации
451- Вход: :: указатель на структуру клеточного автомата, функция ,
452 количество строк и столбцов.
453- Выход: :: инициализированная доска с выделенной памятью под указанное
454 количество строк и столбцов.
455#+begin_src C
456void
457cellular_automaton_init (struct cellular_automaton *cellular_automaton,
458 uint32_t function, uint32_t rows, uint32_t cols)
459{
460 board_init (&cellular_automaton->board, rows, cols);
461 cellular_automaton->back_board_bitarray =
462 malloc (cellular_automaton->board.bitarray.size);
463 cellular_automaton->function = function;
464}
465#+end_src
466
467**** Функция освобождения памяти
468- Вход: :: указатель на структуру клеточного автомата.
469- Выход: :: структура клеточного автомата без выделенной памяти.
470#+begin_src C
471void
472cellular_automaton_free (struct cellular_automaton *cellular_automaton)
473{
474 board_free (&cellular_automaton->board);
475 FREE (cellular_automaton->back_board_bitarray);
476}
477#+end_src
478
479**** Функция перехода к следующему состоянию
480- Вход: :: указатель на структуру клеточного автомата.
481- Выход: :: структура клеточного автомата со значениями клеток доски
482 продвинутыми к их следующим состояниям.
483#+begin_src C
484void
485cellular_automaton_progress (struct cellular_automaton *cellular_automaton)
486{
487 for (int32_t row = 0; row < cellular_automaton->board.rows; ++row) {
488 for (int32_t col = 0; col < cellular_automaton->board.cols; ++col) {
489 struct board *board = &cellular_automaton->board;
490 uint8_t state =
491 board_get (board, row - 1, col + 0) << 1 |
492 board_get (board, row + 0, col - 1) << 3 |
493 board_get (board, row + 0, col + 0) << 4 |
494 board_get (board, row + 0, col + 1) << 2 |
495 board_get (board, row + 1, col + 0) << 0;
496
497 setbit (cellular_automaton->back_board_bitarray,
498 row*board->cols + col,
499 cellular_automaton->function >> state & 1);
500 }
501 }
502
503 SWAP (cellular_automaton->back_board_bitarray,
504 cellular_automaton->board.bitarray.cells);
505}
506#+end_src
507
508** Обработка действий пользователя и отрисовки кадра
509Из-за громоздкости функции выполнения обработки действий пользователя,
510отрисовки экрана и прочих функции (например инициализации и
511деинициализации окна) и их сравнительно незначимому отношению к данной
512работе, приводится лишь их исходный код в приложении [[*ПРИЛОЖЕНИЕ А][А]].
513
514* Результаты работы программы
515На рис. [[open]]-[[gnu30]] представлены снимки окна работы программы
516клеточного автомата с полем $620 \times 400$ клеток.
517
518При открытий сразу получаете заполненную случайным образом доску и на
519экран выводятся справочная информация о доступных горячих клавишах
520(см. Рис. [[open]]).
521
522#+name: open
523#+caption: Вид программы при запуска
524[[./res/open.png]]
525
526Дальше можно закрыть окно со справочной информацией, нажав на клавишу
527=h=, и запустить симуляцию нажав на клавишу =SPC= (см. Рис. [[rand-it100]]).
528По умолчанию будет программа переходить к следующему состоянию
529периодически каждых 0.5с, этот параметр можно настроить кр учением
530колечка мыши. Сверху также отображается рабочая итерация и количество
531сохраненных состояний, между которыми можно передвигаться при
532остановленной симуляции (повторно нажав =SPC=) используя клавиши =LEFT= и
533=RIGHT=. В любой момент можно курсоров рисовать на доске -- при нажатой
534левой (правой) кнопке мыши клетка становится живой (мёртвой)
535(см. Рис. [[cool]]). Доску можно очистить нажав на клавишу =c=. Размер
536доски и также используемую функцию перехода к следующему состоянию
537можно изменить интуитивно, нажав на нужное поле на верхней панели и
538набрав нужное значение.
539
540#+name: rand-it100
541#+caption: 100-ое состояние при доске заполеной случайно, используя нормальное распределение
542[[./res/rand-it100.png]]
543
544#+name: cool
545#+caption: Пример изменения состояния клеток доски пользователем в реальном времени
546[[./res/cool.png]]
547
548#+name: gnu
549#+caption: Пример состояния установленного пользователем
550#+begin_figure
551\centering
552#+name: gnu0
553#+caption: Начальное состояние
554#+attr_latex: :options [b]{\textwidth}
555#+begin_subfigure
556\centering
557[[./res/gnu0.png]]
558#+end_subfigure
559
560\vskip 1cm
561
562#+name: gnu30
563#+caption: 30-ое состояние
564#+attr_latex: :options [b]{\textwidth}
565#+begin_subfigure
566\centering
567[[./res/gnu30.png]]
568#+end_subfigure
569#+end_figure
570
571* Анализ работы клеточного автомата
572** Паттерны
573В ходе анализа клеточного автомата был обнаружено явно выраженный
574вертикальный паттерн горизонтального сечения треугольника Серпинского.
575Вручную изменяя доску во времени можно получить друг за другом
576последовательные его сечения, если между столбцами удерживать
577расстояние в 2 клетки, иначе паттерн превратится в псевдо-случайный
578шум (см. Рис. [[cool]]).
579
580** Классификация по типам поведения
581Проанализировав работу данного клеточного автомата можно прийти к
582выводу, что он относится к типу *псевдо-случайных* или к *классу 3*
583[cite:см. @WOLFRAM2002 с. 1197]. Результатом эволюции почти всех
584начальных условий являются псевдо-случайные, хаотические
585последовательности. Любые стабильные структуры, которые возникают
586почти сразу же уничтожаются окружающим их шумом. Локальные изменения
587в начальных условиях оказывают неопределяемое влияние на ход эволюции
588системы.
589
590На Рис. [[it0]]-[[it5]] представлены состояния доски последовательной эволюции
591клеточного автомата. По изображениям видно, что после нескольких
592итераций изначальная картина так и остается псвевдо-случайной.
593
594Было проведено 20 экспериментов с размером доски $20 \times 20$ и 400
595интерациями для проверки и демонстрации псевдо-случайности, построены
596график изменения количества «живых» клеток (равных единице)
597относительно номера итерации для каждого эксперимента Рис. [[itsc]] и
598график апроксимирующей функции данных экспериментов Рис. [[avgc]].
599
600#+name: figs
601#+caption: Графики изменения количества «живых» клеток относительно итерации
602#+attr_latex: :options [h!]
603#+begin_figure
604\centering
605#+name: itsc
606#+caption: Графики 20 экспериментов
607#+attr_latex: :options [b]{\textwidth}
608#+begin_subfigure
609\centering
610\input{./res/its.tex}
611#+end_subfigure
612
613#+name: avgc
614#+caption: График среднего значения при 20 экспериментах
615#+attr_latex: :options [b]{\textwidth}
616#+begin_subfigure
617\centering
618\input{./res/avg.tex}
619#+end_subfigure
620#+end_figure
621
622#+name: its
623#+caption: Последовательные итерации работы клеточного автомата
624#+begin_figure
625#+name: it0
626#+caption: Исходное состояние
627#+attr_latex: :options [b]{.5\textwidth}
628#+begin_subfigure
629\centering
630\cellboard{6}{1}{0/0, 0/1, 0/2, 0/5, 1/0, 1/3, 2/1, 2/2, 2/4, 2/5, 3/0, 3/3, 3/5, 3/6, 4/3, 4/5, 5/3, 6/3, 6/5, 6/6}
631#+end_subfigure
632#+name: it1
633#+caption: Состояние после 1-ой итерации
634#+attr_latex: :options [b]{.5\textwidth}
635#+begin_subfigure
636\centering
637\cellboard{6}{1}{0/0, 0/1, 0/2, 0/5, 1/0, 2/1, 2/2, 2/4, 2/5, 3/0, 3/1, 3/6, 4/0, 4/4, 4/5, 4/6, 5/6, 6/1, 6/2, 6/3, 6/4, 6/5, 6/6}
638#+end_subfigure
639
640#+name: it2
641#+caption: Состояние после 2-ой итерации
642#+attr_latex: :options [b]{.5\textwidth}
643#+begin_subfigure
644\centering
645\cellboard{6}{1}{0/0, 0/3, 0/5, 1/0, 1/4, 2/1, 2/2, 2/3, 2/4, 2/5, 3/2, 3/6, 4/1, 4/4, 4/5, 5/0, 5/1, 5/2, 5/3, 6/0, 6/1, 6/3, 6/4}
646#+end_subfigure
647#+name: it3
648#+caption: Состояние после 3-ой итерации
649#+attr_latex: :options [b]{.5\textwidth}
650#+begin_subfigure
651\centering
652\cellboard{6}{1}{0/1, 0/3, 0/6, 1/0, 1/2, 2/1, 2/3, 2/5, 3/2, 3/3, 4/0, 4/3, 4/4, 4/5, 4/6, 5/0, 5/2, 5/3, 5/5, 6/4}
653#+end_subfigure
654
655#+name: it4
656#+caption: Состояние после 4-ой итерации
657#+attr_latex: :options [b]{.5\textwidth}
658#+begin_subfigure
659\centering
660\cellboard{6}{1}{0/0, 0/2, 0/4, 1/5, 2/4, 3/0, 3/2, 3/6, 4/0, 4/4, 4/6, 5/0, 5/1, 5/2, 5/5, 6/0, 6/1, 6/2, 6/5, 6/6}
661#+end_subfigure
662#+name: it5
663#+caption: Состояние после 5-ой итерации
664#+attr_latex: :options [b]{.5\textwidth}
665#+begin_subfigure
666\centering
667\cellboard{6}{1}{0/0, 0/2, 0/3, 1/0, 1/2, 2/0, 2/2, 2/5, 2/6, 3/0, 3/1, 3/6, 4/5, 5/2, 6/4, 6/6}
668#+end_subfigure
669#+end_figure
670
671** Сходимость
672С графиков эксперимента представленного на Рис. [[figs]] также видно, что
673при случайном начальном заполнений и размером доски $20 \times 20$
674количество «живых» клеток варирует около $165 \pm 10$.
675
676* ЗАКЛЮЧЕНИЕ
677:PROPERTIES:
678:UNNUMBERED: t
679:END:
680В результате работы был реализован и визуализирован клеточный автомат
681с окрестностью фон Неймана обеспечивающий:
6821. Возможность генерации случайного состояния.
6832. Возможность ручной настройки состояния.
6843. Возможность задания размеров поля.
6854. Возможность определения количества итерации.
686
687Клеточный автомат реализованный в данной работе принадлежит к типу
688*псевдо-случайных* или к *классу 3* [cite:@WOLFRAM2002]. Были выбраны
689тороидальные граничные условия.
690
691Код лабораторной работы был написан в продвинутом, расширяемом,
692настраиваемом и самодокументирующемся редакторе --- GNU/Emacs 29.4, на
693языке программирования Си (=gnu99=), используя библиотеку Raylib 5.0 для
694управления окном.
695
696*Достоинства:*
697- Высокая производительность реализации (см. п. [[*Особенности
698 реализации]]).
699- Графическая реализация проекта.
700- Интуитивное и оперативное управление, позволяющее быстро и
701 занимательно находить интересные узоры.
702
703*Недостатки:*
704- Параметры программы настраиваются макросами в заголовочном файле во
705 время сборки, а не загружаются во время работы программы (напр. из
706 аргументов командной строки).
707- Отсутствие выбора окрестности и граничных условий.
708
709*Масштабируемость:*
710- Можно расширить возможности кисти, добавить горячие клавиши,
711 распределения для случайного заполнения доски и т.д. для улучшения
712 развлекательного фактора.
713- Можно реализовать систему загрузочных модулей, для удобного
714 расширения программы пользователями, например для сохранения
715 состоянии автомата в файл в нестандартном формате.
716
717* СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ
718:PROPERTIES:
719:UNNUMBERED: t
720:END:
721#+latex: \nocite{VOSTROV2024}
722#+print_bibliography: :heading none
723
724* ПРИЛОЖЕНИЕ А
725:PROPERTIES:
726:UNNUMBERED: t
727:END:
728#+attr_latex:
729#+include: "../src/main.c" src C
730
731# Local Variables:
732# org-confirm-babel-evaluate: nil
733# org-export-async-init-file: "ox-init.el"
734# org-export-in-background: t
735# End:
diff --git a/doc/setup.org b/doc/setup.org
new file mode 100644
index 0000000..247ca4b
--- /dev/null
+++ b/doc/setup.org
@@ -0,0 +1,30 @@
1#+options: ':nil *:t -:t ::t <:t H:4 \n:nil ^:{} arch:headline
2#+options: author:t broken-links:nil c:nil creator:nil
3#+options: d:(not "LOGBOOK") date:t e:t email:nil f:t inline:f num:t
4#+options: p:nil pri:nil prop:nil stat:f tags:f tasks:f tex:t
5#+options: timestamp:nil title:t toc:t todo:t |:t
6
7#+select_tags: export
8#+exclude_tags: noexport
9
10#+bibliography: biblio.bib
11#+cite_export: biblatex
12
13#+latex_compiler: xelatex
14#+latex_class: spbstu-report
15# #+latex_class_options: [draft]
16
17#+latex_header: \usepackage{enumitem}
18
19#+latex_header: \usepackage[newfloat]{minted}
20#+latex_header: \usemintedstyle{bw}
21#+latex_header: \setminted{baselinestretch=1,linenos,breaklines,escapeinside=\#\#,ignorelexererrors}
22
23#+latex_header: \renewcommand\theFancyVerbLine{\large\arabic{FancyVerbLine}}
24
25#+latex_header: \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text}
26#+latex_header: \setmainfont{Times New Roman}
27#+latex_header: \setmonofont{Iosevka Term Slab}[Contextuals=AlternateOff]
28
29#+latex_header: \usepackage{tikz}
30#+latex_header: \usepackage{pgfplots}
diff --git a/doc/spbstu-report.cls b/doc/spbstu-report.cls
new file mode 100644
index 0000000..7ae6b05
--- /dev/null
+++ b/doc/spbstu-report.cls
@@ -0,0 +1,74 @@
1\NeedsTeXFormat{LaTeX2e}
2\ProvidesClass{spbstu-report}[2023/05/12 Класс для отчетов]
3
4%
5% Support font sizes: 12pt, 14pt
6%
7\DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
8\DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}}
9
10\ProcessOptions\relax
11
12\LoadClass[a4paper]{gost-7-32}
13
14\RequirePackage{csquotes}
15\RequirePackage{amsmath}
16\RequirePackage{adjustbox}
17\RequirePackage{setspace}
18
19\newcommand{\@reportof}{}\newcommand{\reportof}[1]{\renewcommand{\@reportof}{#1}}
20\newcommand{\@university}{}\newcommand{\university}[1]{\renewcommand{\@university}{#1}}
21\newcommand{\@institute}{}\newcommand{\institute}[1]{\renewcommand{\@institute}{#1}}
22\newcommand{\@school}{}\newcommand{\school}[1]{\renewcommand{\@school}{#1}}
23\newcommand{\@direction}{}\newcommand{\direction}[1]{\renewcommand{\@direction}{#1}}
24\newcommand{\@subject}{}\newcommand{\subject}[1]{\renewcommand{\@subject}{#1}}
25\newcommand{\@reviewer}{}\newcommand{\reviewer}[1]{\renewcommand{\@reviewer}{#1}}
26\newcommand{\@reviewertitle}{}\newcommand{\reviewertitle}[1]{\renewcommand{\@reviewertitle}{#1}}
27\newcommand{\signdate}{$\underset{\centering\text{\normalsize подпись, дата}}{\underline{\hspace{5cm}}}$}
28\newcommand{\@city}{}\newcommand{\city}[1]{\renewcommand{\@city}{#1}}
29\renewcommand{\maketitle}{
30 \begin{titlepage}
31 \begin{center}
32 \vspace{2cm}
33 \small{МИНИСТЕРСТВО НАУКИ И ВЫСШЕГО ОБРАЗОВАНИЯ РОССИЙСКОЙ ФЕДЕРАЦИИ}
34
35 \normalsize{\@university}
36
37 \vspace{0.5cm}
38 \normalsize{\@institute}
39
40 \normalsize{\@school}
41
42 \normalsize{Направление \@direction}
43
44 \vspace{2cm}
45 \LARGE{ОТЧЁТ}
46
47 \normalsize{\@reportof}
48
49 \large{\@subject}
50
51 \large{\textit{\@title}}
52 \end{center}
53
54 \vspace{3cm}
55 \small{
56 \begin{tabular}{lrrl}
57 \!\!\!Студент, & \hspace{2cm} & & \\
58 \!\!\!группы 5130201/20102 & \hspace{2cm} & \underline{\hspace{3cm}} & \@author \\\\
59 \!\!\!Преподаватель, & \hspace{2cm} & \\
60 \!\!\!\@reviewertitle & \hspace{2cm} & \underline{\hspace{3cm}} & \@reviewer \\\\
61 &&\hspace{5cm}
62 \end{tabular}
63 \begin{flushright}
64 \enquote{\underline{\hspace{1cm}}}\underline{\hspace{2.5cm}} \@date г.
65 \end{flushright}
66 }
67
68 \vspace*{\fill}
69 \begin{center}
70 \small{\@city, \@date}
71 \end{center}
72 \end{titlepage}
73 \setcounter{page}{2}
74}
diff --git a/doc/task.org b/doc/task.org
new file mode 100644
index 0000000..2b9dec8
--- /dev/null
+++ b/doc/task.org
@@ -0,0 +1,14 @@
1#+title: Лабораторная работа 1
2
3Реализовать двумерный клеточный автомат с окрестностью фон Неймана в
4соответствии с полученным номером №. Граничный условия предложить
5самостоятельно (торроидальные, нулевые, единичные). Пользователь
6определяет ширину поля и количество итераций. Необходимо учесть
7возможность ввода различных начальных условий (как вручную, так и
8случайным образом) по выбору пользователя. Реализация возможна в
9консоли или в графике. В итоге необходимо проанализировать свой
10клеточный автомат в отчете (его поведение, паттерны, "сходимость" и
11т.д.).
12
13№ = номер варианта * 11 * год рождения * день * месяц = src_elisp{(*
1415 11 2003 12 2)} {{{results(=7931880=)}}}
diff --git a/src/bitarray.c b/src/bitarray.c
new file mode 100644
index 0000000..5d7c1e3
--- /dev/null
+++ b/src/bitarray.c
@@ -0,0 +1,33 @@
1#include "board.h"
2#include "utils.h"
3
4void
5bitarray_init (struct bitarray *bitarray, size_t bit_count)
6{
7 bitarray->size = (bit_count + 7)/8;
8 bitarray->bytes = calloc (bitarray->size, 1);
9}
10
11void
12bitarray_set (struct bitarray *bitarray, size_t index, bool value)
13{
14 ASSERT (bitarray);
15 ASSERT (bitarray->bytes);
16 ASSERT (index >> 3 < bitarray->size);
17 setbit (bitarray->bytes, index, value);
18}
19
20bool
21bitarray_get (struct bitarray *bitarray, size_t index)
22{
23 ASSERT (bitarray);
24 ASSERT (bitarray->bytes);
25 ASSERT (index >> 3 < bitarray->size);
26 return getbit (bitarray->bytes, index);
27}
28
29void
30bitarray_free (struct bitarray *bitarray)
31{
32 FREE (bitarray->bytes);
33}
diff --git a/src/bitarray.h b/src/bitarray.h
new file mode 100644
index 0000000..934b84e
--- /dev/null
+++ b/src/bitarray.h
@@ -0,0 +1,18 @@
1#ifndef INCLUDED_BITARRAY_H
2#define INCLUDED_BITARRAY_H
3
4#include <stdlib.h>
5#include <stdbool.h>
6#include <inttypes.h>
7
8struct bitarray {
9 uint8_t *bytes;
10 size_t size;
11};
12
13void bitarray_init (struct bitarray *, size_t bit_count);
14void bitarray_free (struct bitarray *);
15void bitarray_set (struct bitarray *, size_t index, bool);
16bool bitarray_get (struct bitarray *, size_t index);
17
18#endif
diff --git a/src/board.c b/src/board.c
new file mode 100644
index 0000000..fe798f7
--- /dev/null
+++ b/src/board.c
@@ -0,0 +1,36 @@
1#include "board.h"
2#include "utils.h"
3
4void
5board_init (struct board *board, uint32_t rows, uint32_t cols)
6{
7 bitarray_init (&board->bitarray, rows*cols);
8 board->rows = rows;
9 board->cols = cols;
10}
11
12void
13board_set (struct board *board, int32_t row, int32_t col, bool value)
14{
15 ASSERT (board);
16
17 row = MOD (row, (int32_t) board->rows);
18 col = MOD (col, (int32_t) board->cols);
19 bitarray_set (&board->bitarray, row*board->cols + col, value);
20}
21
22bool
23board_get (struct board *board, int32_t row, int32_t col)
24{
25 ASSERT (board);
26
27 row = MOD (row, (int32_t) board->rows);
28 col = MOD (col, (int32_t) board->cols);
29 return bitarray_get (&board->bitarray, row*board->cols + col);
30}
31
32void
33board_free (struct board *board)
34{
35 bitarray_free (&board->bitarray);
36}
diff --git a/src/board.h b/src/board.h
new file mode 100644
index 0000000..7ce113e
--- /dev/null
+++ b/src/board.h
@@ -0,0 +1,19 @@
1#ifndef INCLUDED_BOARD_H
2#define INCLUDED_BOARD_H
3
4#include <inttypes.h>
5#include <stdbool.h>
6#include "bitarray.h"
7
8struct board {
9 struct bitarray bitarray;
10 uint32_t rows;
11 uint32_t cols;
12};
13
14void board_init (struct board *, uint32_t rows, uint32_t cols);
15void board_free (struct board *);
16void board_set (struct board *, int32_t row, int32_t col, bool);
17bool board_get (struct board *, int32_t row, int32_t col);
18
19#endif
diff --git a/src/cellular-automaton.c b/src/cellular-automaton.c
new file mode 100644
index 0000000..183684a
--- /dev/null
+++ b/src/cellular-automaton.c
@@ -0,0 +1,49 @@
1#include <stdio.h>
2#include "cellular-automaton.h"
3#include "utils.h"
4
5void
6cellular_automaton_init (struct cellular_automaton *cellular_automaton,
7 uint32_t function, uint32_t rows, uint32_t cols)
8{
9 board_init (&cellular_automaton->board, rows, cols);
10 cellular_automaton->back_board_bitarray =
11 malloc (cellular_automaton->board.bitarray.size);
12 cellular_automaton->function = function;
13}
14
15void
16cellular_automaton_progress (struct cellular_automaton *cellular_automaton)
17{
18 // uint32_t alive = 0;
19 for (int32_t row = 0; row < cellular_automaton->board.rows; ++row) {
20 for (int32_t col = 0; col < cellular_automaton->board.cols; ++col) {
21 struct board *board = &cellular_automaton->board;
22 uint8_t state =
23 board_get (board, row - 1, col + 0) << 3 |
24 board_get (board, row + 0, col - 1) << 1 |
25 board_get (board, row + 0, col + 0) << 0 |
26 board_get (board, row + 0, col + 1) << 2 |
27 board_get (board, row + 1, col + 0) << 4;
28
29 // if (board_get (board, row, col)) {
30 // // printf ("%d/%d, ", row, col);
31 // ++alive;
32 // }
33
34 setbit (cellular_automaton->back_board_bitarray,
35 row*board->cols + col,
36 cellular_automaton->function >> state & 1);
37 }
38 } // printf ("%u\n", alive);
39
40 SWAP (cellular_automaton->back_board_bitarray,
41 cellular_automaton->board.bitarray.bytes);
42}
43
44void
45cellular_automaton_free (struct cellular_automaton *cellular_automaton)
46{
47 board_free (&cellular_automaton->board);
48 free (cellular_automaton->back_board_bitarray);
49}
diff --git a/src/cellular-automaton.h b/src/cellular-automaton.h
new file mode 100644
index 0000000..8be8951
--- /dev/null
+++ b/src/cellular-automaton.h
@@ -0,0 +1,19 @@
1#ifndef INCLUDED_CELLULAR_AUTOMATON_H
2#define INCLUDED_CELLULAR_AUTOMATON_H
3
4#include <inttypes.h>
5#include "board.h"
6
7struct cellular_automaton {
8 struct board board;
9 uint8_t *back_board_bitarray;
10 uint32_t function;
11};
12
13void cellular_automaton_init (struct cellular_automaton *,
14 uint32_t function,
15 uint32_t rows, uint32_t cols);
16void cellular_automaton_free (struct cellular_automaton *);
17void cellular_automaton_progress (struct cellular_automaton *);
18
19#endif
diff --git a/src/config.h b/src/config.h
new file mode 100644
index 0000000..e93a9d4
--- /dev/null
+++ b/src/config.h
@@ -0,0 +1,52 @@
1#ifndef INCLUDED_CONFIG_H
2#define INCLUDED_CONFIG_H
3
4#define INITIAL_WINDOW_WIDTH 900
5#define INITIAL_WINDOW_HEIGHT 600
6#define INITIAL_WINDOW_TITLE "Двумерный клеточный автомат с окрестностью фон Неймана"
7
8#define INITIAL_CELLULAR_AUTOMATON_FUNCTION ((uint32_t) 0x7907E8)
9#define INITIAL_CELLULAR_AUTOMATON_BOARD_COLS 735
10#define INITIAL_CELLULAR_AUTOMATON_BOARD_ROWS 400
11// #define INITIAL_CELLULAR_AUTOMATON_BOARD_COLS 620
12// #define INITIAL_CELLULAR_AUTOMATON_BOARD_ROWS 400
13
14#define INITIAL_IS_RANDOM true
15
16#define INITIAL_TICK_RATE 0 //1./2
17#define TICK_RATE_CHANGE_SPEED 1./100
18#define TICK_RATE_CHANGE_SPEED_MULTIPLIER 10
19
20#define BACKGROUND_COLOR BLACK
21
22#define INITIAL_IS_PAUSED true
23#define INITIAL_IS_GRID_SHOWN false
24#define INITIAL_IS_HELP_SHOWN true
25
26#define AFTER_CLEAR_IS_PAUSED true
27
28#define GRID_THICKNESS 1
29#define GRID_COLOR GRAY
30
31#define CELL_COLOR_ALIVE WHITE
32#define CELL_COLOR_DEAD BACKGROUND_COLOR
33
34#define TEXT_SPACING 2
35
36#define INFOBAR_FONT_SIZE 20
37#define INFOBAR_HEIGHT 20
38#define INFOBAR_COLOR_TEXT WHITE
39#define INFOBAR_COLOR_TEXT_EDITING RED
40#define INFOBAR_COLOR_BACKGROUND DARKBLUE
41#define INFOBAR_COLOR_OUTLINE BLUE
42#define INFOBAR_TEXT_PAUSED "*PAUSED*"
43
44#define HELP_TITLE "HELP"
45#define HELP_FONT_SIZE_HEADING 28
46#define HELP_FONT_SIZE_POINT 22
47#define HELP_PADDING 20
48#define HELP_COLOR_TEXT ((Color) { 0xDF, 0x00, 0x00, 0xFF })
49#define HELP_COLOR_BACKGROUND ((Color) { 0x2F, 0x00, 0x00, 0xDF })
50#define HELP_COLOR_OUTLINE ((Color) { 0xFF, 0x00, 0x00, 0xFF })
51
52#endif
diff --git a/src/dynamic-array.h b/src/dynamic-array.h
new file mode 100644
index 0000000..726fcce
--- /dev/null
+++ b/src/dynamic-array.h
@@ -0,0 +1,59 @@
1#ifndef INCLUDED_DYNAMIC_ARRAY_H
2#define INCLUDED_DYNAMIC_ARRAY_H
3
4#include "utils.h"
5
6#ifndef DYNAMIC_ARRAY_INIT_CAP
7#define DYNAMIC_ARRAY_INIT_CAP 256
8#endif
9
10#define DYNAMIC_ARRAY_ENSURE_CAPACITY(DYNAMIC_ARRAY, COUNT) \
11 ({ \
12 if ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) { \
13 if ((DYNAMIC_ARRAY).capacity == 0) \
14 (DYNAMIC_ARRAY).capacity = DYNAMIC_ARRAY_INIT_CAP; \
15 while ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) \
16 (DYNAMIC_ARRAY).capacity *= 2; \
17 (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \
18 (DYNAMIC_ARRAY).capacity * \
19 sizeof (*(DYNAMIC_ARRAY).items)); \
20 ASSERT((DYNAMIC_ARRAY).items); \
21 } \
22 })
23
24#define DYNAMIC_ARRAY_SHRINK(DYNAMIC_ARRAY) \
25 ({ \
26 (DYNAMIC_ARRAY).capacity = (DYNAMIC_ARRAY).count; \
27 (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \
28 (DYNAMIC_ARRAY).capacity * \
29 sizeof (*(DYNAMIC_ARRAY).items)); \
30 ASSERT((DYNAMIC_ARRAY).items); \
31 \
32 })
33
34#define DYNAMIC_ARRAY_APPEND(DYNAMIC_ARRAY, ITEM) \
35 ({ \
36 DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), 1); \
37 (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count++] = (ITEM); \
38 })
39
40#define DYNAMIC_ARRAY_APPEND_MANY(DYNAMIC_ARRAY, NEW_ITEMS, NEW_ITEMS_COUNT) \
41 ({ \
42 DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), (NEW_ITEMS_COUNT)); \
43 memcpy ((DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count, (NEW_ITEMS), \
44 (NEW_ITEMS_COUNT)*sizeof (*(DYNAMIC_ARRAY).items)); \
45 (DYNAMIC_ARRAY).count += (NEW_ITEMS_COUNT); \
46 })
47
48#define DYNAMIC_ARRAY_LAST(DYNAMIC_ARRAY) \
49 (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count - 1]
50
51#define DYNAMIC_ARRAY_RESET(DYNAMIC_ARRAY) ({ (DYNAMIC_ARRAY).count = 0; })
52
53#define DYNAMIC_ARRAY_FREE(DYNAMIC_ARRAY) FREE((DYNAMIC_ARRAY).items)
54
55#define DYNAMIC_ARRAY_FOREACH(ITEM, DYNAMIC_ARRAY) for ( \
56 typeof ((DYNAMIC_ARRAY).items) ITEM = (DYNAMIC_ARRAY).items; \
57 ITEM < (DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count; ++ITEM)
58
59#endif
diff --git a/src/main.c b/src/main.c
new file mode 100644
index 0000000..89741da
--- /dev/null
+++ b/src/main.c
@@ -0,0 +1,576 @@
1// src/main.c --- entry point and window management
2#include <stdlib.h>
3#include <stdio.h>
4#include <stdbool.h>
5#include <inttypes.h>
6#include <assert.h>
7#include <string.h>
8#include <ctype.h>
9#include <time.h>
10#include <raylib.h>
11#include <raymath.h>
12
13#include "config.h"
14#include "dynamic-array.h"
15#include "cellular-automaton.h"
16
17static struct cellular_automaton cellular_automaton;
18
19static float cell_size = 0;
20static Rectangle board_bounding_box = {0};
21static Font font;
22
23static float tick_rate = INITIAL_TICK_RATE;
24static float time_from_last_udpate = 0;
25
26static bool is_paused = INITIAL_IS_PAUSED;
27static bool is_grid_shown = INITIAL_IS_GRID_SHOWN;
28static bool is_help_shown = INITIAL_IS_HELP_SHOWN;
29
30static uint8_t *transient_iteration_bytes;
31static size_t iteration;
32static struct {
33 uint8_t *items;
34 uint32_t count;
35 uint32_t capacity;
36} iterations = {0};
37
38#define TEXT_SIZE_FUNCTION 9
39static char text_function[TEXT_SIZE_FUNCTION];
40static bool text_function_is_editing = false;
41
42#define TEXT_SIZE_COLS 4
43static char text_cols[TEXT_SIZE_COLS];
44static bool text_cols_is_editing = false;
45
46#define TEXT_SIZE_ROWS 4
47static char text_rows[TEXT_SIZE_ROWS];
48static bool text_rows_is_editing = false;
49
50static void
51init (void)
52{
53 srand (time (NULL));
54
55 cellular_automaton_init (&cellular_automaton,
56 INITIAL_CELLULAR_AUTOMATON_FUNCTION,
57 INITIAL_CELLULAR_AUTOMATON_BOARD_ROWS,
58 INITIAL_CELLULAR_AUTOMATON_BOARD_COLS);
59 if (INITIAL_IS_RANDOM) {
60 for (uint32_t row = 0; row < cellular_automaton.board.rows; ++row) {
61 for (uint32_t col = 0; col < cellular_automaton.board.cols; ++col) {
62 board_set (&cellular_automaton.board, row, col, rand () % 2);
63 }
64 }
65 }
66
67 DYNAMIC_ARRAY_APPEND_MANY (iterations,
68 cellular_automaton.board.bitarray.bytes,
69 cellular_automaton.board.bitarray.size);
70 iteration = 0;
71 if (INITIAL_IS_PAUSED)
72 transient_iteration_bytes = cellular_automaton.board.bitarray.bytes;
73
74 SetConfigFlags (FLAG_MSAA_4X_HINT |
75 FLAG_WINDOW_RESIZABLE |
76 FLAG_FULLSCREEN_MODE |
77 FLAG_VSYNC_HINT);
78
79 // InitWindow (INITIAL_WINDOW_WIDTH,
80 // INITIAL_WINDOW_HEIGHT,
81 // INITIAL_WINDOW_TITLE);
82 InitWindow (0, 0, INITIAL_WINDOW_TITLE);
83
84 font = GetFontDefault ();
85
86 snprintf (text_function, TEXT_SIZE_FUNCTION, "%08X", cellular_automaton.function);
87 snprintf (text_cols, TEXT_SIZE_COLS, "%u", cellular_automaton.board.cols);
88 snprintf (text_rows, TEXT_SIZE_ROWS, "%u", cellular_automaton.board.rows);
89}
90
91static void
92deinit (void)
93{
94 CloseWindow ();
95 cellular_automaton_free (&cellular_automaton);
96}
97
98static void
99handel_input (void)
100{
101 if (IsKeyPressed (KEY_SPACE)) {
102 if (is_paused) {
103 is_paused = false;
104 cellular_automaton.board.bitarray.bytes = transient_iteration_bytes;
105 memcpy (cellular_automaton.board.bitarray.bytes,
106 &iterations.items[iteration*cellular_automaton.board.bitarray.size],
107 cellular_automaton.board.bitarray.size);
108 iterations.count = (iteration + 1)*cellular_automaton.board.bitarray.size;
109 } else {
110 is_paused = true;
111 transient_iteration_bytes = cellular_automaton.board.bitarray.bytes;
112 memcpy (&iterations.items[iteration*cellular_automaton.board.bitarray.size],
113 cellular_automaton.board.bitarray.bytes,
114 cellular_automaton.board.bitarray.size);
115 }
116 }
117
118 if (IsKeyPressed (KEY_F1) || IsKeyPressed (KEY_H))
119 is_help_shown = !is_help_shown;
120
121 if (is_help_shown && IsKeyPressed (KEY_Q))
122 is_help_shown = false;
123
124 if (IsKeyPressed (KEY_G))
125 is_grid_shown = !is_grid_shown;
126
127 if (IsKeyPressed (KEY_C) && !text_function_is_editing) {
128 if (is_paused)
129 cellular_automaton.board.bitarray.bytes = transient_iteration_bytes;
130 memset (cellular_automaton.board.bitarray.bytes, 0,
131 cellular_automaton.board.bitarray.size);
132 DYNAMIC_ARRAY_RESET (iterations);
133 DYNAMIC_ARRAY_APPEND_MANY (iterations,
134 cellular_automaton.board.bitarray.bytes,
135 cellular_automaton.board.bitarray.size);
136 iteration = 0;
137 is_paused = AFTER_CLEAR_IS_PAUSED;
138 if (is_paused)
139 transient_iteration_bytes = cellular_automaton.board.bitarray.bytes;
140 }
141
142 if (is_paused) {
143 int change = 0;
144 change += GetMouseWheelMove () > 0 ||
145 IsKeyPressed (KEY_N) || IsKeyPressed (KEY_RIGHT) ||
146 IsKeyDown (KEY_LEFT_SHIFT) && (IsKeyDown (KEY_N) ||
147 IsKeyDown (KEY_RIGHT));
148 change -= GetMouseWheelMove () < 0 ||
149 IsKeyPressed (KEY_P) || IsKeyPressed (KEY_LEFT) ||
150 IsKeyDown (KEY_LEFT_SHIFT) && (IsKeyDown (KEY_P) ||
151 IsKeyDown (KEY_LEFT));
152 if (change < 0 && iteration >= -change ||
153 change > 0 && (iteration + change <=
154 (iterations.count - 1) /
155 cellular_automaton.board.bitarray.size))
156 iteration += change;
157 cellular_automaton.board.bitarray.bytes =
158 &iterations.items[iteration*cellular_automaton.board.bitarray.size];
159 } else {
160 tick_rate = fmaxf (tick_rate +
161 TICK_RATE_CHANGE_SPEED*GetMouseWheelMove () *
162 (1 + (TICK_RATE_CHANGE_SPEED_MULTIPLIER - 1) *
163 IsKeyDown (KEY_LEFT_SHIFT)), 0);
164 }
165
166 enum cell_action {
167 CELL_ACTION_NONE = 0b00,
168 CELL_ACTION_KILL = 0b01,
169 CELL_ACTION_RESURRECT = 0b10,
170 } cell_action = CELL_ACTION_NONE;
171
172 if (!text_function_is_editing &&
173 !text_cols_is_editing &&
174 !text_rows_is_editing) {
175 if (IsMouseButtonDown (MOUSE_LEFT_BUTTON))
176 cell_action = CELL_ACTION_RESURRECT;
177 else if (IsMouseButtonDown (MOUSE_RIGHT_BUTTON))
178 cell_action = CELL_ACTION_KILL;
179 }
180
181 if (cell_action) {
182 Vector2 mouse = GetMousePosition ();
183 if (CheckCollisionPointRec (mouse, board_bounding_box)) {
184 uint32_t row = (mouse.y - board_bounding_box.y)/cell_size;
185 uint32_t col = (mouse.x - board_bounding_box.x)/cell_size;
186 board_set (&cellular_automaton.board, row, col, cell_action >> 1 & 1);
187 }
188 }
189}
190
191static void
192update (void)
193{
194 cell_size = fminf (
195 (GetScreenHeight () - INFOBAR_HEIGHT)/(float) cellular_automaton.board.rows,
196 (GetScreenWidth () )/(float) cellular_automaton.board.cols);
197 board_bounding_box.width = cell_size*cellular_automaton.board.cols;
198 board_bounding_box.height = cell_size*cellular_automaton.board.rows;
199 board_bounding_box.x = (GetScreenWidth () - board_bounding_box.width )/2.;
200 board_bounding_box.y = (GetScreenHeight () - board_bounding_box.height + INFOBAR_HEIGHT)/2.;
201
202 time_from_last_udpate += GetFrameTime ();
203 if (!is_paused && time_from_last_udpate >= tick_rate) {
204 time_from_last_udpate = 0;
205
206 cellular_automaton_progress (&cellular_automaton);
207 DYNAMIC_ARRAY_APPEND_MANY (iterations,
208 cellular_automaton.board.bitarray.bytes,
209 cellular_automaton.board.bitarray.size);
210 iteration += 1;
211 }
212}
213
214static void
215draw_fps (int x, int y, float font_size)
216{
217 DrawTextEx (font, TextFormat ("%2i FPS", GetFPS ()), (Vector2) { x, y },
218 font_size, TEXT_SPACING, INFOBAR_COLOR_TEXT);
219}
220
221static void
222draw_infobar (void)
223{
224 DrawRectangle (0, 0, GetScreenWidth (), INFOBAR_HEIGHT, INFOBAR_COLOR_BACKGROUND);
225 DrawRectangleLines (0, 0, GetScreenWidth (), INFOBAR_HEIGHT, INFOBAR_COLOR_OUTLINE);
226
227 draw_fps (3, 1, INFOBAR_FONT_SIZE);
228
229 if (is_paused) {
230 Vector2 text_center = Vector2Scale (MeasureTextEx (
231 font, INFOBAR_TEXT_PAUSED,
232 INFOBAR_FONT_SIZE, TEXT_SPACING), .5);
233 text_center.y -= 1;
234 Vector2 infobar_center = { GetScreenWidth ()/2., INFOBAR_HEIGHT/2. };
235 DrawTextEx (font, INFOBAR_TEXT_PAUSED, Vector2Subtract (infobar_center, text_center),
236 INFOBAR_FONT_SIZE, TEXT_SPACING, INFOBAR_COLOR_TEXT);
237 }
238
239 {
240 Vector2 head = { GetScreenWidth () - 3, 1 };
241 {
242 Vector2 text_size = MeasureTextEx (font, text_function, INFOBAR_FONT_SIZE, TEXT_SPACING);
243 head.x -= text_size.x;
244 if (IsMouseButtonPressed (MOUSE_BUTTON_LEFT) ||
245 IsMouseButtonPressed (MOUSE_BUTTON_RIGHT)) {
246 Rectangle bounding_box = {
247 .x = head.x,
248 .y = head.y,
249 .width = text_size.x,
250 .height = text_size.y,
251 };
252 if (CheckCollisionPointRec (GetMousePosition (), bounding_box))
253 text_function_is_editing = true;
254 else
255 text_function_is_editing = false;
256 sscanf (text_function, "%X", &cellular_automaton.function);
257 }
258
259 if (text_function_is_editing) {
260 if (IsKeyPressed (KEY_ENTER)) {
261 text_function_is_editing = false;
262 sscanf (text_function, "%X", &cellular_automaton.function);
263 } else {
264 int key;
265 while (text_function[0] == '0' &&
266 (key = toupper (GetCharPressed ()))) {
267 if ('0' <= key && key <= '9' ||
268 'A' <= key && key <= 'F') {
269 char last_char;
270 for (int i = 0; i < TEXT_SIZE_FUNCTION - 2; ++i) {
271 last_char = text_function[i];
272 text_function[i] = text_function[i + 1];
273 } text_function[TEXT_SIZE_FUNCTION - 2] = key;
274 }
275 }
276
277 if (IsKeyPressed (KEY_BACKSPACE)) {
278 if (IsKeyDown (KEY_CAPS_LOCK)) {
279 memset (text_function, '0', TEXT_SIZE_FUNCTION - 1);
280 } else {
281 char last_char = '0';
282 for (int i = 0; i < TEXT_SIZE_FUNCTION - 1; ++i) {
283 char tmp = text_function[i];
284 text_function[i] = last_char;
285 last_char = tmp;
286 }
287 }
288 }
289 }
290 }
291
292 DrawTextEx (font, text_function, head, INFOBAR_FONT_SIZE, TEXT_SPACING,
293 text_function_is_editing ? INFOBAR_COLOR_TEXT_EDITING : INFOBAR_COLOR_TEXT);
294 }
295 head.x -= MeasureTextEx (font, " | 0x", INFOBAR_FONT_SIZE, TEXT_SPACING).x + TEXT_SPACING;
296 DrawTextEx (font, " | 0x", head, INFOBAR_FONT_SIZE, TEXT_SPACING, INFOBAR_COLOR_TEXT);
297
298 bool resize = false;
299 if ((text_cols_is_editing || text_rows_is_editing) &&
300 IsKeyPressed (KEY_TAB)) {
301 text_cols_is_editing = !text_cols_is_editing;
302 text_rows_is_editing = !text_rows_is_editing;
303 }
304
305 {
306 Vector2 text_size = MeasureTextEx (font, text_rows, INFOBAR_FONT_SIZE, TEXT_SPACING);
307 head.x -= text_size.x;
308 if (IsMouseButtonPressed (MOUSE_BUTTON_LEFT) ||
309 IsMouseButtonPressed (MOUSE_BUTTON_RIGHT)) {
310 Rectangle bounding_box = {
311 .x = head.x,
312 .y = head.y,
313 .width = text_size.x,
314 .height = text_size.y,
315 };
316 if (CheckCollisionPointRec (GetMousePosition (), bounding_box))
317 text_rows_is_editing = true;
318 else {
319 if (text_rows_is_editing) {
320 resize = true;
321 text_rows_is_editing = false;
322 }
323 }
324 }
325
326 if (text_rows_is_editing) {
327 if (IsKeyPressed (KEY_ENTER)) {
328 text_rows_is_editing = false;
329 resize = true;
330 } else {
331 int key;
332 size_t len;
333 while ((len = strlen (text_rows)) < TEXT_SIZE_ROWS - 1 &&
334 (key = GetCharPressed ())) {
335 if ('0' <= key && key <= '9') {
336 if (text_rows[0] == '0') {
337 text_rows[0] = key;
338 } else {
339 text_rows[len] = key;
340 text_rows[len + 1] = '\0';
341 }
342 }
343 }
344
345 if (IsKeyPressed (KEY_BACKSPACE)) {
346 if (IsKeyDown (KEY_CAPS_LOCK) || len == 1) {
347 text_rows[0] = '0';
348 text_rows[1] = '\0';
349 } else {
350 text_rows[len - 1] = '\0';
351 }
352 }
353 }
354 }
355
356 DrawTextEx (font, text_rows, head, INFOBAR_FONT_SIZE, TEXT_SPACING,
357 text_rows_is_editing ? INFOBAR_COLOR_TEXT_EDITING : INFOBAR_COLOR_TEXT);
358 }
359 head.x -= MeasureTextEx (font, "x", INFOBAR_FONT_SIZE, TEXT_SPACING).x + TEXT_SPACING;
360 DrawTextEx (font, "x", head, INFOBAR_FONT_SIZE, TEXT_SPACING, INFOBAR_COLOR_TEXT);
361 {
362 Vector2 text_size = MeasureTextEx (font, text_cols, INFOBAR_FONT_SIZE, TEXT_SPACING);
363 head.x -= text_size.x + TEXT_SPACING;
364 if (IsMouseButtonPressed (MOUSE_BUTTON_LEFT) ||
365 IsMouseButtonPressed (MOUSE_BUTTON_RIGHT)) {
366 Rectangle bounding_box = {
367 .x = head.x,
368 .y = head.y,
369 .width = text_size.x,
370 .height = text_size.y,
371 };
372 if (CheckCollisionPointRec (GetMousePosition (), bounding_box))
373 text_cols_is_editing = true;
374 else {
375 if (text_cols_is_editing) {
376 resize = true;
377 text_cols_is_editing = false;
378 }
379 }
380 }
381
382 if (text_cols_is_editing) {
383 if (IsKeyPressed (KEY_ENTER)) {
384 text_cols_is_editing = false;
385 resize = true;
386 } else {
387 int key;
388 size_t len;
389 while ((len = strlen (text_cols)) < TEXT_SIZE_COLS - 1 &&
390 (key = GetCharPressed ())) {
391 if ('0' <= key && key <= '9') {
392 if (text_cols[0] == '0') {
393 text_cols[0] = key;
394 } else {
395 text_cols[len] = key;
396 text_cols[len + 1] = '\0';
397 }
398 }
399 }
400
401 if (IsKeyPressed (KEY_BACKSPACE)) {
402 if (IsKeyDown (KEY_CAPS_LOCK) || len == 1) {
403 text_cols[0] = '0';
404 text_cols[1] = '\0';
405 } else {
406 text_cols[len - 1] = '\0';
407 }
408 }
409 }
410 }
411
412 DrawTextEx (font, text_cols, head, INFOBAR_FONT_SIZE, TEXT_SPACING,
413 text_cols_is_editing ? INFOBAR_COLOR_TEXT_EDITING : INFOBAR_COLOR_TEXT);
414 }
415
416 if (resize) {
417 uint32_t rows, cols;
418 sscanf (text_rows, "%u", &rows);
419 sscanf (text_cols, "%u", &cols);
420
421 if (rows != cellular_automaton.board.rows ||
422 cols != cellular_automaton.board.cols) {
423 if (is_paused)
424 cellular_automaton.board.bitarray.bytes = transient_iteration_bytes;
425 board_free (&cellular_automaton.board);
426 board_init (&cellular_automaton.board, rows, cols);
427 DYNAMIC_ARRAY_RESET (iterations);
428 DYNAMIC_ARRAY_APPEND_MANY (iterations,
429 cellular_automaton.board.bitarray.bytes,
430 cellular_automaton.board.bitarray.size);
431 iteration = 0;
432 is_paused = INITIAL_IS_PAUSED;
433 if (is_paused)
434 transient_iteration_bytes = cellular_automaton.board.bitarray.bytes;
435 }
436 }
437
438 const char *text_rest = TextFormat (
439 "%u/%u | %.2fs | ",
440 iteration + 1, iterations.count/cellular_automaton.board.bitarray.size,
441 tick_rate,
442 cellular_automaton.board.rows);
443 head.x -= MeasureTextEx (font, text_rest, INFOBAR_FONT_SIZE, TEXT_SPACING).x + TEXT_SPACING;
444 DrawTextEx (font, text_rest, head, INFOBAR_FONT_SIZE, TEXT_SPACING, INFOBAR_COLOR_TEXT);
445 }
446}
447
448static void
449draw_heading (Vector2 *head, const char *heading)
450{
451 DrawTextEx (font, heading, *head,
452 HELP_FONT_SIZE_HEADING, TEXT_SPACING, HELP_COLOR_TEXT);
453 head->y += HELP_FONT_SIZE_HEADING;
454}
455
456static void
457draw_point (Vector2 *head, const char *lhs, const char *rhs)
458{
459 DrawTextEx (font, lhs, Vector2Add (*head, (Vector2) { 1*HELP_PADDING, 0 }),
460 HELP_FONT_SIZE_POINT, TEXT_SPACING, HELP_COLOR_TEXT);
461 DrawTextEx (font, rhs, Vector2Add (*head, (Vector2) { 7*HELP_FONT_SIZE_POINT, 0 }),
462 HELP_FONT_SIZE_POINT, TEXT_SPACING, HELP_COLOR_TEXT);
463 head->y += HELP_FONT_SIZE_POINT;
464}
465
466static void
467draw_help (void)
468{
469 Rectangle bounding_box = {
470 .x = .1*GetScreenWidth (),
471 .y = .1*GetScreenHeight () + INFOBAR_HEIGHT,
472 .width = .8*GetScreenWidth (),
473 .height = .8*(GetScreenHeight () - INFOBAR_HEIGHT),
474 };
475
476 DrawRectangleRec (bounding_box, HELP_COLOR_BACKGROUND);
477 DrawRectangleLinesEx (bounding_box, 1, HELP_COLOR_OUTLINE);
478
479 Vector2 head = { bounding_box.x + HELP_PADDING,
480 bounding_box.y + HELP_PADDING - 3 };
481 Vector2 offset_point = { 1*HELP_PADDING, 0 };
482 Vector2 offset_description = { 7*HELP_FONT_SIZE_POINT, 0 };
483 draw_heading (&head, "General:");
484 draw_point (&head, "- F1, H", "Show this help window.");
485 draw_point (&head, "- Q", "Quit any transient window.");
486 draw_point (&head, "- SPC", "Pause/Unpause.");
487 draw_point (&head, "- G", "Toggle grid display.");
488 draw_point (&head, "- C", "Clear automaton's state.");
489 draw_point (&head, "- LMB", "Make cell under cursor alive.");
490 draw_point (&head, "- RMB", "Make cell under cursor dead.");
491 draw_point (&head, "- SHIFT", "Make adjustments faster.");
492 head.y += HELP_FONT_SIZE_HEADING;
493 draw_heading (&head, "Running:");
494 draw_point (&head, "- SCROLL", "Adjust tick rate.");
495 head.y += HELP_FONT_SIZE_HEADING;
496 draw_heading (&head, "Paused:");
497 draw_point (&head, "- SCROLL", "Move between states.");
498 draw_point (&head, "- P, LEFT", "Move to previous state.");
499 draw_point (&head, "- N, RIGHT", "Move to next state.");
500}
501
502static void
503draw (void)
504{
505 BeginDrawing (); {
506 ClearBackground (BACKGROUND_COLOR);
507
508 draw_infobar ();
509
510 Rectangle rec = {
511 .x = board_bounding_box.x,
512 .y = board_bounding_box.y,
513 .width = cell_size,
514 .height = cell_size,
515 };
516 for (uint32_t row = 0; row < cellular_automaton.board.rows; ++row) {
517 for (uint32_t col = 0; col < cellular_automaton.board.cols; ++col) {
518 DrawRectangleRec (rec,
519 board_get (&cellular_automaton.board, row, col)
520 ? CELL_COLOR_ALIVE
521 : CELL_COLOR_DEAD);
522 rec.x += cell_size;
523 }
524 rec.x = board_bounding_box.x;
525 rec.y += cell_size;
526 }
527
528 DrawRectangleLinesEx (board_bounding_box, GRID_THICKNESS, GRID_COLOR);
529 if (is_grid_shown) {
530 Vector2 line_begin;
531 Vector2 line_end;
532
533 line_begin = (Vector2) {
534 board_bounding_box.x,
535 board_bounding_box.y + cell_size,
536 };
537 line_end = (Vector2) {
538 board_bounding_box.x + board_bounding_box.width,
539 board_bounding_box.y + cell_size,
540 };
541 for (uint32_t i = 0; i < cellular_automaton.board.rows - 1; ++i) {
542 DrawLineEx (line_begin, line_end, GRID_THICKNESS, GRID_COLOR);
543 line_begin.y += cell_size;
544 line_end.y += cell_size;
545 }
546
547 line_begin = (Vector2) {
548 board_bounding_box.x + cell_size,
549 board_bounding_box.y,
550 };
551 line_end = (Vector2) {
552 board_bounding_box.x + cell_size,
553 board_bounding_box.y + board_bounding_box.height,
554 };
555 for (uint32_t i = 0; i < cellular_automaton.board.cols - 1; ++i) {
556 DrawLineEx (line_begin, line_end, GRID_THICKNESS, GRID_COLOR);
557 line_begin.x += cell_size;
558 line_end.x += cell_size;
559 }
560 }
561
562 if (is_help_shown) draw_help ();
563 } EndDrawing ();
564}
565
566int
567main (int argc, char *argv[])
568{
569 init ();
570 while (!WindowShouldClose ()) {
571 handel_input ();
572 update ();
573 draw ();
574 } deinit ();
575 return EXIT_SUCCESS;
576}
diff --git a/src/utils.h b/src/utils.h
new file mode 100644
index 0000000..d5a1242
--- /dev/null
+++ b/src/utils.h
@@ -0,0 +1,65 @@
1#ifndef INCLUDED_UTILS_H
2#define INCLUDED_UTILS_H
3
4#include <stdlib.h>
5#include <stdio.h>
6#include <stdbool.h>
7#include <inttypes.h>
8#include <assert.h>
9
10#define MALLOC malloc
11#define REALLOC realloc
12#ifdef DEBUG
13#define FREE(PTR) ({free (PTR); PTR = NULL;})
14#define ASSERT assert
15#else
16#define FREE free
17#define ASSERT
18#endif
19
20#define CEIL_INT_DIV(A, B) ((A + (B - 1))/B)
21// #define CEIL_INT_DIV(A, B) (1 + (A - 1)/B) // A != 0
22
23#define MOD(A, B) (((A % B) + B) % B)
24
25#define SWAP(A, B) \
26 ({ \
27 typeof (A) tmp = A; \
28 A = B; \
29 B = tmp; \
30 })
31
32#define MIN(A, B) \
33 ({ \
34 typeof (A) a = A; \
35 typeof (B) b = B; \
36 a < b ? a : b; \
37 }) \
38
39inline void
40setbit (uint8_t *bytes, size_t index, bool value)
41{
42 uint8_t *byte = &bytes[index >> 3];
43 uint8_t offset = index & ((1 << 3) - 1);
44 uint8_t mask = ~(1 << offset);
45 *byte = *byte & mask | value << offset;
46}
47
48inline bool
49getbit (uint8_t *bytes, size_t index)
50{
51 uint8_t byte = bytes[index >> 3];
52 uint8_t offset = index & ((1 << 3) - 1);
53 uint8_t mask = 1 << offset;
54 return (byte & mask) >> offset;
55}
56
57inline void
58prompt (char *label, char *fmt, void *where)
59{
60 printf ("%s: ", label);
61 scanf (fmt, where);
62 while (getchar () != '\n');
63}
64
65#endif