Compare commits

..

4 Commits

Author SHA1 Message Date
MartinOpat 9f36f7c921 Added player 2025-11-11 23:02:13 +01:00
MartinOpat f9ec2e855d Switched 'intensive' functions to cpp 2025-11-11 00:23:12 +01:00
MartinOpat c92c6d4432 godot-cpp init. 2025-11-11 00:22:57 +01:00
Martin Opat 1c1d8bf3aa Initial commit 2025-11-09 17:09:27 +01:00
23 changed files with 588 additions and 0 deletions

4
.gitmodules vendored Normal file
View File

@ -0,0 +1,4 @@
[submodule "game-of-life-test/thirdparty/godot-cpp"]
path = game-of-life-test/thirdparty/godot-cpp
url = https://github.com/godotengine/godot-cpp.git
branch = 4.5

View File

@ -0,0 +1,4 @@
root = true
[*]
charset = utf-8

2
game-of-life-test/.gitattributes vendored Normal file
View File

@ -0,0 +1,2 @@
# Normalize EOL for all files that Git considers text files.
* text=auto eol=lf

3
game-of-life-test/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
# Godot 4+ specific ignores
.godot/
/android/

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://c7assq3lqgw8x"
path="res://.godot/imported/black_sq.png-43fbf60d129e97f2df8400c8ac3589c6.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://black_sq.png"
dest_files=["res://.godot/imported/black_sq.png-43fbf60d129e97f2df8400c8ac3589c6.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1

View File

@ -0,0 +1,36 @@
shader_type canvas_item;
uniform sampler2D unlitTex;
uniform sampler2D litTex;
uniform sampler2D binDataTex;
uniform int n;
const int cellSize = 8;
void vertex() {
// Called for every vertex the material is visible on.
}
void fragment() {
// Called for every pixel the material is visible on.
vec2 totalGridSize = vec2(float(n) * float(cellSize));
vec2 scaledUV = UV * float(n);
ivec2 cellIdx = ivec2(floor(scaledUV));
vec2 cellUV = fract(scaledUV);
float binVal = texelFetch(binDataTex, cellIdx, 0).r;
bool isWhite = binVal > 0.5;
vec4 color = texture(unlitTex, cellUV);
if (isWhite) {
color = texture(litTex, cellUV);
}
COLOR = color;
}
//void light() {
// // Called for every pixel for every light affecting the material.
// // Uncomment to replace the default light processing function with this one.
//}

View File

@ -0,0 +1 @@
uid://cidrd2kca02ko

View File

@ -0,0 +1,23 @@
[gd_scene load_steps=7 format=3 uid="uid://bawvofeipkkmn"]
[ext_resource type="Texture2D" uid="uid://dma7owg4valo7" path="res://icon.svg" id="1_4fmrq"]
[ext_resource type="Shader" uid="uid://cidrd2kca02ko" path="res://dot_matrix.gdshader" id="1_wjpme"]
[ext_resource type="Texture2D" uid="uid://csm64p7o7eyc6" path="res://white_sq.png" id="2_og22u"]
[ext_resource type="Texture2D" uid="uid://c7assq3lqgw8x" path="res://black_sq.png" id="3_b70w7"]
[ext_resource type="Script" uid="uid://cgwkfjisbqbwt" path="res://gol.gd" id="5_og22u"]
[sub_resource type="ShaderMaterial" id="ShaderMaterial_wvg0l"]
shader = ExtResource("1_wjpme")
shader_parameter/unlitTex = ExtResource("3_b70w7")
shader_parameter/litTex = ExtResource("2_og22u")
shader_parameter/n = 64
[node name="Dot Matrix" type="Node2D"]
[node name="Renderer" type="Sprite2D" parent="."]
material = SubResource("ShaderMaterial_wvg0l")
position = Vector2(960, 960)
scale = Vector2(15, 15)
texture = ExtResource("1_4fmrq")
script = ExtResource("5_og22u")
metadata/_edit_lock_ = true

196
game-of-life-test/gol.gd Normal file
View File

@ -0,0 +1,196 @@
extends Sprite2D
var n: int = 64
var arr := []
var data_img: Image
var data_tex: ImageTexture
var gol := GoL.new()
@onready var mat: ShaderMaterial = material as ShaderMaterial
# sim. consts
var T := 0.01
var t := 0.0
# player (2x2 block)
var player_alive := true
var player_col := 10
var player_row := 10
var PLAYER_SHAPE := [Vector2i(0,0), Vector2i(1,0), Vector2i(0,1), Vector2i(1,1)]
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
data_img = Image.create(n, n, false, Image.FORMAT_R8)
data_img.fill(Color8(0, 0, 0, 255))
data_tex = ImageTexture.create_from_image(data_img)
mat.set_shader_parameter("binDataTex", data_tex)
mat.set_shader_parameter("n", n)
# player
_seed_clear()
_fill_example()
_spawn_player(20, 10)
_upload_arr()
func _upload_arr() -> void:
for y in n:
for x in n:
var v := int(arr[y][x]) * 255
data_img.set_pixel(x, y, Color8(v, 0, 0, 255))
data_tex.update(data_img)
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(_delta: float) -> void:
if Input.is_action_just_pressed("move_right"):
_move_player(1, 0)
if Input.is_action_just_pressed("move_left"):
_move_player(-1, 0)
if Input.is_action_just_pressed("move_up"):
_move_player(0, -1)
if Input.is_action_just_pressed("move_down"):
_move_player(0, 1)
t += _delta
if t >= T:
t = 0.0
_game_of_life_step()
# arr = gol.step_once(arr, n) # cpp step (no player)
_track_player_after_step()
_upload_arr()
func _game_of_life_step() -> void:
var next := []
for y in n:
var row := []
for x in n:
var alive: bool = arr[y][x] == 1
var cn := _count_neighs(x, y)
var newv := 0
if alive:
newv = int(cn == 2 or cn == 3)
else:
newv = int(cn == 3)
row.append(newv)
next.append(row)
arr = next
func _count_neighs(x:int, y:int) -> int:
var ans := 0
for _dy in 3:
var dy := _dy-1
for _dx in 3:
var dx := _dx-1
if dx == 0 and dy == 0:
continue
var nx := int((x + dx + n)%n)
var ny := int((y + dy + n)%n)
ans += arr[ny][nx]
return ans
func _track_player_after_step() -> void:
if not player_alive:
return
var best_count := -1
var best_shift := Vector2i(0, 0)
# search a 5x5 neighborhood for where the 2x2 footprint moved
for dy in range(-2, 3):
for dx in range(-2, 3):
var cnt := 0
for off in PLAYER_SHAPE:
var x:int = (player_col + off.x + dx + n) % n
var y:int = (player_row + off.y + dy + n) % n
cnt += arr[y][x]
if cnt > best_count:
best_count = cnt
best_shift = Vector2i(dx, dy)
# if nothing from the footprint survived, the player is dead
if best_count <= 0:
player_alive = false
print("Player dead!")
return
player_col = (player_col + best_shift.x + n) % n
player_row = (player_row + best_shift.y + n) % n
func _fill_example() -> void:
#_checkerboard()
_ship()
# inits
func _checkerboard() -> void:
for y in n:
var row := []
for x in n:
row.append((x + y) % 2) # checkerboard
arr.append(row)
func _ship() -> void:
var i: int = 0
var j: int = 0
while (i < n):
var row := []
j = 0
while (j < n):
row.append(0)
j+=1
arr.append(row)
i+=1
arr[0][1] = 1
arr[1][2] = 1
arr[2][0] = 1
arr[2][1] = 1
arr[2][2] = 1
# Player
func _write_player(val:int) -> void:
for off in PLAYER_SHAPE:
var x:int = (player_col + off.x + n) % n
var y:int = (player_row + off.y + n) % n
arr[y][x] = val
func _spawn_player(col:int, row:int) -> void:
player_col = (col + n) % n
player_row = (row + n) % n
player_alive = true
_write_player(1)
_upload_arr()
func _despawn_player() -> void:
if player_alive:
_write_player(0)
player_alive = false
_upload_arr()
func _move_player(dx:int, dy:int) -> void:
if not player_alive:
return
# erase old footprint
_write_player(0)
# move
player_col = (player_col + dx + n) % n
player_row = (player_row + dy + n) % n
# write new footprint
_write_player(1)
_upload_arr()
# Clear
func _seed_clear() -> void:
arr.clear()
for _y in n:
var row := []
for _x in n:
row.append(0)
arr.append(row)

View File

@ -0,0 +1 @@
uid://cgwkfjisbqbwt

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128"><rect width="124" height="124" x="2" y="2" fill="#363d52" stroke="#212532" stroke-width="4" rx="14"/><g fill="#fff" transform="translate(12.322 12.322)scale(.101)"><path d="M105 673v33q407 354 814 0v-33z"/><path fill="#478cbf" d="m105 673 152 14q12 1 15 14l4 67 132 10 8-61q2-11 15-15h162q13 4 15 15l8 61 132-10 4-67q3-13 15-14l152-14V427q30-39 56-81-35-59-83-108-43 20-82 47-40-37-88-64 7-51 8-102-59-28-123-42-26 43-46 89-49-7-98 0-20-46-46-89-64 14-123 42 1 51 8 102-48 27-88 64-39-27-82-47-48 49-83 108 26 42 56 81zm0 33v39c0 276 813 276 814 0v-39l-134 12-5 69q-2 10-14 13l-162 11q-12 0-16-11l-10-65H446l-10 65q-4 11-16 11l-162-11q-12-3-14-13l-5-69z"/><path d="M483 600c0 34 58 34 58 0v-86c0-34-58-34-58 0z"/><circle cx="725" cy="526" r="90"/><circle cx="299" cy="526" r="90"/></g><g fill="#414042" transform="translate(12.322 12.322)scale(.101)"><circle cx="307" cy="532" r="60"/><circle cx="717" cy="532" r="60"/></g></svg>

After

Width:  |  Height:  |  Size: 995 B

View File

@ -0,0 +1,43 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://dma7owg4valo7"
path="res://.godot/imported/icon.svg-218a8f2b3041327d8a5756f3a245f83b.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://icon.svg"
dest_files=["res://.godot/imported/icon.svg-218a8f2b3041327d8a5756f3a245f83b.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1
svg/scale=1.0
editor/scale_with_editor_scale=false
editor/convert_colors_with_editor_theme=false

View File

@ -0,0 +1,23 @@
extends Area2D
@export var speed = 400 # How fast the player will move (pixels/sec).
var screen_size # Size of the game window.
func _ready() -> void:
screen_size = get_viewport_rect().size
func _process(delta):
var velocity = Vector2.ZERO # The player's movement vector.
if Input.is_action_pressed("move_right"):
velocity.x += 1
if Input.is_action_pressed("move_left"):
velocity.x -= 1
if velocity.length() > 0:
velocity = velocity.normalized() * speed
$AnimatedSprite2D.play()
else:
$AnimatedSprite2D.stop()
position += velocity * delta
position = position.clamp(Vector2.ZERO, screen_size)

View File

@ -0,0 +1 @@
uid://cvxhfc50fgdyb

View File

@ -0,0 +1,44 @@
; Engine configuration file.
; It's best edited using the editor UI and not directly,
; since the parameters that go here are not all obvious.
;
; Format:
; [section] ; section goes between []
; param=value ; assign values to parameters
config_version=5
[application]
config/name="GameOfLifeTest"
run/main_scene="uid://bawvofeipkkmn"
config/features=PackedStringArray("4.5", "Forward Plus")
config/icon="res://icon.svg"
[display]
window/size/viewport_width=1920
window/size/viewport_height=1920
[input]
move_right={
"deadzone": 0.2,
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":0,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194321,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
]
}
move_left={
"deadzone": 0.2,
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":0,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194319,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
]
}
move_up={
"deadzone": 0.2,
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":0,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194320,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
]
}
move_down={
"deadzone": 0.2,
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":0,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194322,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
]
}

10
game-of-life-test/thirdparty/.gitignore vendored Normal file
View File

@ -0,0 +1,10 @@
bin
*.uid
*sconsign.dblite
**.os
game-of-life-test/thirdparty/godot-cpp/bin/
game-of-life-test/thirdparty/bin/
*.o
*.so

31
game-of-life-test/thirdparty/SConstruct vendored Normal file
View File

@ -0,0 +1,31 @@
import os
from SCons.Script import DefaultEnvironment, ARGUMENTS, Glob, Dir
env = DefaultEnvironment()
platform = ARGUMENTS.get("platform", "linux")
target = ARGUMENTS.get("target", "template_debug") # or template_release
arch = ARGUMENTS.get("arch", "x86_64")
HERE = Dir(".").abspath
GODOTCPP = os.path.join(HERE, "godot-cpp")
inc_paths = [
os.path.join(GODOTCPP, "include"),
os.path.join(GODOTCPP, "gen", "include"),
]
for extra in ("godot-headers", "gdextension"):
p = os.path.join(GODOTCPP, extra)
if os.path.isdir(p):
inc_paths.append(p)
env.Append(CPPPATH=inc_paths)
env.Append(LIBPATH=[os.path.join(GODOTCPP, "bin")])
env.Append(CXXFLAGS=["-std=c++17", "-fPIC"])
env.Append(LIBS=[f"godot-cpp.{platform}.{target}.{arch}"])
outdir = os.path.join(HERE, "bin")
os.makedirs(outdir, exist_ok=True)
soname = f"gol.{platform}.{'debug' if target == 'template_debug' else 'release'}.{arch}"
env.SharedLibrary(target=os.path.join(outdir, soname), source=Glob("src/*.cpp"))

@ -0,0 +1 @@
Subproject commit abe94570a16e38eec442d1c9acc0c518c479e725

View File

@ -0,0 +1,9 @@
[configuration]
entry_symbol = "gol_library_init"
compatibility_minimum = "4.5" ; required in 4.5+
reloadable = true
[libraries]
linux.debug.x86_64 = "res://thirdparty/bin/libgol.linux.debug.x86_64"

View File

@ -0,0 +1,75 @@
// src/gol.cpp
#include <gdextension_interface.h>
#include <godot_cpp/classes/ref_counted.hpp>
#include <godot_cpp/core/class_db.hpp>
#include <godot_cpp/core/defs.hpp>
#include <godot_cpp/godot.hpp>
#include <godot_cpp/variant/array.hpp>
using namespace godot;
class GoL : public RefCounted {
GDCLASS(GoL, RefCounted);
static void _bind_methods() {
ClassDB::bind_method(D_METHOD("step_once", "arr", "n"), &GoL::step_once);
}
static int neighs(const Array &a, int n, int x, int y) {
int s = 0;
for (int dy = -1; dy <= 1; ++dy) {
for (int dx = -1; dx <= 1; ++dx) {
if (dx == 0 && dy == 0)
continue;
const int nx = ((x + dx) % n + n) % n;
const int ny = ((y + dy) % n + n) % n;
const Array row = a[ny];
s += (int)row[nx];
}
}
return s;
}
public:
Array step_once(const Array &arr, int n) const {
Array next;
next.resize(n);
for (int y = 0; y < n; ++y) {
Array row;
row.resize(n);
const Array crow = arr[y];
for (int x = 0; x < n; ++x) {
const bool alive = ((int)crow[x]) == 1;
const int cn = neighs(arr, n, x, y);
row.set(x, alive ? int(cn == 2 || cn == 3) : int(cn == 3));
}
next.set(y, row);
}
return next;
}
};
extern "C" GDExtensionBool GDE_EXPORT
gol_library_init(GDExtensionInterfaceGetProcAddress get_proc_address,
GDExtensionClassLibraryPtr library,
GDExtensionInitialization *r_initialization) {
static GDExtensionBinding::InitObject init(get_proc_address, library,
r_initialization);
init.register_initializer([](ModuleInitializationLevel p_level) {
if (p_level != MODULE_INITIALIZATION_LEVEL_SCENE)
return;
ClassDB::register_class<GoL>();
});
init.register_terminator([](ModuleInitializationLevel /*p_level*/) {
// no-op
});
init.set_minimum_library_initialization_level(
MODULE_INITIALIZATION_LEVEL_SCENE);
return init.init();
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://csm64p7o7eyc6"
path="res://.godot/imported/white_sq.png-7baf4040d7b03bc76a02f41aa766a5a0.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://white_sq.png"
dest_files=["res://.godot/imported/white_sq.png-7baf4040d7b03bc76a02f41aa766a5a0.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1