Add chiadni plate, fourier simulator, make main buttons smaller

This commit is contained in:
csd4ni3l
2025-09-24 22:24:21 +02:00
parent c9326b2d53
commit df8c83ea61
7 changed files with 352 additions and 24 deletions

View File

@@ -0,0 +1,125 @@
import pyglet, arcade, arcade.gui, os, json, numpy as np
from game.chladni_plate_simulator.shader import create_shader
from utils.preload import button_texture, button_hovered_texture
from utils.constants import button_style
class Game(arcade.gui.UIView):
def __init__(self, pypresence_client):
super().__init__()
self.pypresence_client = pypresence_client
self.pypresence_client.update(state="Playing a simulator", details="Chladni Plate Simulator")
self.anchor = self.add_widget(arcade.gui.UIAnchorLayout(size_hint=(1, 1)))
self.settings_box = self.anchor.add(arcade.gui.UIBoxLayout(align="center", size_hint=(0.2, 1)).with_background(color=arcade.color.GRAY), anchor_x="right", anchor_y="bottom")
self.settings_label = self.settings_box.add(arcade.gui.UILabel(text="Settings", font_size=24))
if os.path.exists("data.json"):
with open("data.json", "r") as file:
self.settings = json.load(file)
else:
self.settings = {}
if not "chladni_plate_simulator" in self.settings:
self.settings["chladni_plate_simulator"] = {
"k": 0.1
}
self.sources = np.empty((0, 2), dtype=np.float32)
self.dragged_source = None
self.needs_redraw = False
def add_setting(self, text, min_value, max_value, step, settings_key):
label = self.settings_box.add(arcade.gui.UILabel(text.format(value=self.settings["chladni_plate_simulator"][settings_key])))
slider = self.settings_box.add(arcade.gui.UISlider(value=self.settings["chladni_plate_simulator"][settings_key], min_value=min_value, max_value=max_value, step=step))
slider._render_steps = lambda surface: None
slider.on_change = lambda event, label=label: self.change_value(label, text, settings_key, event.new_value)
def change_value(self, label, text, settings_key, value):
label.text = text.format(value=value)
self.settings["chladni_plate_simulator"][settings_key] = value
self.needs_redraw = True
def on_update(self, delta_time):
if self.needs_redraw:
self.needs_redraw = False
self.sources_ssbo.set_data(self.sources.tobytes())
with self.shader_program:
self.shader_program["source_count"] = len(self.sources)
self.shader_program["k"] = self.settings["chladni_plate_simulator"]["k"]
self.shader_program.dispatch(self.plate_image.width, self.plate_image.height, 1)
def setup(self):
self.shader_program, self.plate_image, self.sources_ssbo = create_shader(int(self.window.width * 0.8), self.window.height)
self.image_sprite = pyglet.sprite.Sprite(img=self.plate_image)
scale_x = (self.window.width * 0.8) / self.image_sprite.width
scale_y = self.window.height / self.image_sprite.height
self.image_sprite.scale_x = scale_x
self.image_sprite.scale_y = scale_y
def add_source(self):
tx = self.window.width * 0.4
ty = self.window.height / 2
self.sources = np.vstack([self.sources, [tx, ty]]).astype(np.float32)
self.needs_redraw = True
def on_mouse_drag(self, x, y, dx, dy, _buttons, _modifiers):
if not self.dragged_source:
for i, source in enumerate(self.sources.reshape(-1, 2)):
if arcade.math.Vec2(x, y).distance(arcade.math.Vec2(*source)) <= 10:
self.dragged_source = i
break
self.sources[self.dragged_source] = [x, y]
def on_mouse_release(self, x, y, button, modifiers):
self.dragged_source = None
self.needs_redraw = True
def on_show_view(self):
super().on_show_view()
self.settings_box.add(arcade.gui.UISpace(height=self.window.height / 75))
self.add_setting("k: {value}", 0.02, 0.5, 0.01, "k")
self.add_source_button = self.settings_box.add(arcade.gui.UITextureButton(text="Add source", texture=button_texture, texture_hovered=button_hovered_texture, style=button_style, width=self.window.width * 0.2))
self.add_source_button.on_click = lambda event: self.add_source()
self.setup()
def on_key_press(self, symbol, modifiers):
if symbol == arcade.key.ESCAPE:
self.shader_program.delete()
self.sources_ssbo.delete()
from menus.main import Main
self.window.show_view(Main(self.pypresence_client))
elif symbol == arcade.key.C:
del self.sources
self.sources = np.empty((0, 2), dtype=np.float32)
self.needs_redraw = True
def on_draw(self):
super().on_draw()
self.image_sprite.draw()
for item in self.sources.reshape(-1, 2):
arcade.draw_circle_filled(item[0], item[1], 10, arcade.color.GRAY)

View File

@@ -0,0 +1,57 @@
import pyglet, pyglet.graphics
from pyglet.gl import glBindBufferBase, GL_SHADER_STORAGE_BUFFER, GL_NEAREST
shader_source = """#version 430 core
layout (std430, binding = 3) buffer Sources {
vec2 sources[];
};
uniform int source_count;
uniform float k;
layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
layout (location = 0, rgba32f) uniform image2D img_output;
void main() {
ivec2 texel_coord = ivec2(gl_GlobalInvocationID.xy);
vec2 texel_pos_float = vec2(texel_coord);
float total_wave_height = 0.0;
for (int i = 0; i < source_count; i++) {
total_wave_height += cos(k * distance(texel_pos_float, sources[i]));
}
vec4 color;
float normalized_height = total_wave_height / float(source_count);
float value = abs(normalized_height);
if (value > 0.9) {
color = vec4(1.0, 0.0, 0.0, 1.0);
} else if (value > 0.6) {
color = vec4(1.0, 1.0, 0.0, 1.0);
} else if (value > 0.3) {
color = vec4(0.0, 1.0, 0.0, 1.0);
} else {
color = vec4(0.0, 0.0, 0.0, 1.0);
}
imageStore(img_output, texel_coord, color);
}
"""
def create_shader(width, height):
shader_program = pyglet.graphics.shader.ComputeShaderProgram(shader_source)
chladni_plate_image = pyglet.image.Texture.create(width, height, internalformat=pyglet.gl.GL_RGBA32F, min_filter=GL_NEAREST, mag_filter=GL_NEAREST)
uniform_location = shader_program['img_output']
chladni_plate_image.bind_image_texture(unit=uniform_location)
sources_ssbo = pyglet.graphics.BufferObject(32 * 8, usage=pyglet.gl.GL_DYNAMIC_COPY)
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, sources_ssbo.id)
return shader_program, chladni_plate_image, sources_ssbo

View File

@@ -0,0 +1,141 @@
import arcade, arcade.gui, os, json, numpy as np
from scipy.interpolate import interp1d
class Game(arcade.gui.UIView):
def __init__(self, pypresence_client):
super().__init__()
self.pypresence_client = pypresence_client
self.pypresence_client.update(state="Playing a simulator", details="Fourier Simulator")
self.anchor = self.add_widget(arcade.gui.UIAnchorLayout(size_hint=(1, 1)))
self.settings_box = self.anchor.add(arcade.gui.UIBoxLayout(align="center", size_hint=(0.2, 1)).with_background(color=arcade.color.GRAY), anchor_x="right", anchor_y="bottom")
self.settings_label = self.settings_box.add(arcade.gui.UILabel(text="Settings", font_size=24))
if os.path.exists("data.json"):
with open("data.json", "r") as file:
self.settings = json.load(file)
else:
self.settings = {}
if not "fourier_simulator" in self.settings:
self.settings["fourier_simulator"] = {
"max_coefficients": 1000,
"speed": 1.0,
"tail_size": 1000,
"resampling_size": 512
}
self.path_points = []
self.drawing_done = False
self.fourier_coefficients = []
self.drawing_trail = []
self.time = 0.0
def on_show_view(self):
super().on_show_view()
self.settings_box.add(arcade.gui.UISpace(height=self.window.height / 75))
self.add_setting("Max Coefficients: {value}", 1, 10000, 1, "max_coefficients")
self.add_setting("Speed: {value}", 0.1, 1.5, 0.1, "speed")
self.add_setting("Tail Size: {value}", 10, 1000, 10, "tail_size")
self.add_setting("Resampling Size: {value}", 128, 8192, 128, "resampling_size")
def add_setting(self, text, min_value, max_value, step, settings_key):
label = self.settings_box.add(arcade.gui.UILabel(text.format(value=self.settings["fourier_simulator"][settings_key])))
slider = self.settings_box.add(arcade.gui.UISlider(value=self.settings["fourier_simulator"][settings_key], min_value=min_value, max_value=max_value, step=step))
slider._render_steps = lambda surface: None
slider.on_change = lambda event, label=label: self.change_value(label, text, settings_key, event.new_value)
def change_value(self, label, text, settings_key, value):
label.text = text.format(value=value)
self.settings["fourier_simulator"][settings_key] = value
def main_exit(self):
with open("data.json", "w") as file:
file.write(json.dumps(self.settings, indent=4))
from menus.main import Main
self.window.show_view(Main(self.pypresence_client))
def on_key_press(self, symbol, modifiers):
if symbol == arcade.key.ESCAPE:
self.main_exit()
def on_mouse_press(self, x, y, button, modifiers):
self.path_points = []
self.drawing_trail.clear()
self.drawing_done = False
def on_mouse_release(self, x, y, button, modifiers):
self.drawing_done = True
self.calculate_fourier_coefficients()
def calculate_drawing_point(self, t):
pos = 0j
for i, c in enumerate(self.fourier_coefficients):
k = i - (len(self.fourier_coefficients) // 2)
angle = 2 * np.pi * k * t
pos += c * np.exp(1j * angle)
return float(pos.real), float(pos.imag)
def resample_path(self, path_points, N):
t = np.linspace(0, 1, len(path_points))
fx = interp1d(t, path_points.real, kind='linear')
fy = interp1d(t, path_points.imag, kind='linear')
t_uniform = np.linspace(0, 1, N)
return fx(t_uniform) + 1j * fy(t_uniform)
def calculate_fourier_coefficients(self):
if not self.path_points:
return
c_points = np.array(self.path_points)
c_points = self.resample_path(c_points, int(self.settings["fourier_simulator"]["resampling_size"]))
coeffs = np.fft.fftshift(np.fft.fft(c_points) / len(c_points))
self.fourier_coefficients = np.array(coeffs[:int(self.settings["fourier_simulator"]["max_coefficients"])], dtype=np.complex64)
def on_mouse_drag(self, x, y, dx, dy, _buttons, _modifiers):
if not self.drawing_done:
self.path_points.append(complex(x / self.window.width, y / self.window.height))
def on_update(self, delta_time):
self.time += delta_time
if self.drawing_done:
t_normalized = (self.time * self.settings["fourier_simulator"]["speed"]) % 1.0
x, y = self.calculate_drawing_point(t_normalized)
pixel_x = x * self.window.width
pixel_y = y * self.window.height
self.drawing_trail.append((pixel_x, pixel_y))
if len(self.drawing_trail) > self.settings["fourier_simulator"]["tail_size"]:
self.drawing_trail.pop(0)
def on_draw(self):
super().on_draw()
if len(self.drawing_trail) > 1:
arcade.draw_line_strip(
self.drawing_trail,
color=arcade.color.WHITE,
line_width=2
)

View File

@@ -74,19 +74,6 @@ class Game(arcade.gui.UIView):
self.current_splash_strength = 0
def save_data(self):
self.settings.update({
"water_simulator": {
"splash_strength": self.splash_strength,
"splash_radius": self.splash_radius,
"wave_speed": self.wave_speed,
"damping": self.damping
}
})
with open("data.json", "w") as file:
file.write(json.dumps(self.settings, indent=4))
def setup_game(self):
self.shader_program, self.water_image, self.previous_heights_ssbo, self.current_heights_ssbo = create_shader()
@@ -98,7 +85,7 @@ class Game(arcade.gui.UIView):
self.image_sprite.scale_x = scale_x
self.image_sprite.scale_y = scale_y
grid = array.array('f', [random.uniform(-0.01, 0.01) for _ in range(WATER_ROWS * WATER_COLS)])
grid = array.array('f', [random.uniform(-0.1, 0.1) for _ in range(WATER_ROWS * WATER_COLS)])
self.previous_heights_ssbo.set_data(grid.tobytes())
self.current_heights_ssbo.set_data(grid.tobytes())
@@ -118,19 +105,20 @@ class Game(arcade.gui.UIView):
self.settings["water_simulator"][local_variable] = value
setattr(self, local_variable, value)
def main_exit(self):
self.shader_program.delete()
self.previous_heights_ssbo.delete()
self.current_heights_ssbo.delete()
from menus.main import Main
self.window.show_view(Main(self.pypresence_client))
def on_key_press(self, symbol, modifiers):
if symbol == arcade.key.ESCAPE:
self.save_data()
from menus.main import Main
self.window.show_view(Main(self.pypresence_client))
with open("data.json", "w") as file:
file.write(json.dumps(self.settings, indent=4))
self.main_exit()
def on_mouse_press(self, x, y, button, modifiers):
col = int(x / (self.window.width * 0.8) * WATER_COLS)

View File

@@ -52,16 +52,22 @@ class Main(arcade.gui.UIView):
self.title_label = self.box.add(arcade.gui.UILabel(text="Simulator Games", font_name="Roboto", font_size=48))
self.boid_simulator_button = self.box.add(arcade.gui.UITextureButton(text="Boid Simulator", texture=button_texture, texture_hovered=button_hovered_texture, width=self.window.width / 2, height=self.window.height / 8, style=big_button_style))
self.boid_simulator_button = self.box.add(arcade.gui.UITextureButton(text="Boid Simulator", texture=button_texture, texture_hovered=button_hovered_texture, width=self.window.width / 2, height=self.window.height / 10, style=big_button_style))
self.boid_simulator_button.on_click = lambda event: self.boid_simulator()
self.water_simulator_button = self.box.add(arcade.gui.UITextureButton(text="Water Simulator", texture=button_texture, texture_hovered=button_hovered_texture, width=self.window.width / 2, height=self.window.height / 8, style=big_button_style))
self.water_simulator_button = self.box.add(arcade.gui.UITextureButton(text="Water Splash Simulator", texture=button_texture, texture_hovered=button_hovered_texture, width=self.window.width / 2, height=self.window.height / 10, style=big_button_style))
self.water_simulator_button.on_click = lambda event: self.water_simulator()
self.physics_playground_button = self.box.add(arcade.gui.UITextureButton(text="Physics Playground", texture=button_texture, texture_hovered=button_hovered_texture, width=self.window.width / 2, height=self.window.height / 8, style=big_button_style))
self.physics_playground_button = self.box.add(arcade.gui.UITextureButton(text="Physics Playground", texture=button_texture, texture_hovered=button_hovered_texture, width=self.window.width / 2, height=self.window.height / 10, style=big_button_style))
self.physics_playground_button.on_click = lambda event: self.physics_playground()
self.settings_button = self.box.add(arcade.gui.UITextureButton(text="Settings", texture=button_texture, texture_hovered=button_hovered_texture, width=self.window.width / 2, height=self.window.height / 8, style=big_button_style))
self.fourier_simulator_button = self.box.add(arcade.gui.UITextureButton(text="Fourier Drawing Simulator", texture=button_texture, texture_hovered=button_hovered_texture, width=self.window.width / 2, height=self.window.height / 10, style=big_button_style))
self.fourier_simulator_button.on_click = lambda event: self.fourier_simulator()
self.chadni_plate_simulator_button = self.box.add(arcade.gui.UITextureButton(text="Chadni Plate Simulator", texture=button_texture, texture_hovered=button_hovered_texture, width=self.window.width / 2, height=self.window.height / 10, style=big_button_style))
self.chadni_plate_simulator_button.on_click = lambda event: self.chladni_plate_simulator()
self.settings_button = self.box.add(arcade.gui.UITextureButton(text="Settings", texture=button_texture, texture_hovered=button_hovered_texture, width=self.window.width / 2, height=self.window.height / 10, style=big_button_style))
self.settings_button.on_click = lambda event: self.settings()
def physics_playground(self):
@@ -76,6 +82,14 @@ class Main(arcade.gui.UIView):
from game.water_simulator.game import Game
self.window.show_view(Game(self.pypresence_client))
def fourier_simulator(self):
from game.fourier_simulator.game import Game
self.window.show_view(Game(self.pypresence_client))
def chladni_plate_simulator(self):
from game.chladni_plate_simulator.game import Game
self.window.show_view(Game(self.pypresence_client))
def settings(self):
from menus.settings import Settings
self.window.show_view(Settings(self.pypresence_client))

View File

@@ -8,5 +8,6 @@ dependencies = [
"arcade==3.2.0",
"cairosvg>=2.8.2",
"pypresence>=4.3.0",
"scipy>=1.16.1",
"svgpathtools>=1.7.1",
]

2
uv.lock generated
View File

@@ -399,6 +399,7 @@ dependencies = [
{ name = "arcade" },
{ name = "cairosvg" },
{ name = "pypresence" },
{ name = "scipy" },
{ name = "svgpathtools" },
]
@@ -407,6 +408,7 @@ requires-dist = [
{ name = "arcade", specifier = "==3.2.0" },
{ name = "cairosvg", specifier = ">=2.8.2" },
{ name = "pypresence", specifier = ">=4.3.0" },
{ name = "scipy", specifier = ">=1.16.1" },
{ name = "svgpathtools", specifier = ">=1.7.1" },
]