forked from makspll/bevy_mod_scripting
-
Notifications
You must be signed in to change notification settings - Fork 0
/
game_of_life.rs
263 lines (235 loc) · 7.88 KB
/
game_of_life.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
use std::{borrow::Cow, sync::Mutex};
use bevy::{
diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin},
prelude::*,
reflect::Reflect,
render::{
render_resource::{Extent3d, TextureDimension, TextureFormat},
texture::ImageSampler,
},
window::{PrimaryWindow, WindowResized},
};
use bevy_mod_scripting::prelude::*;
#[derive(Debug, Default, Reflect, Component)]
#[reflect(Component, LuaProxyable)]
pub struct LifeState {
pub cells: Vec<u8>,
}
impl_script_newtype!(
#[languages(lua)]
LifeState : Debug
lua impl {
get "cells" => |lua,s: &LuaLifeState| {
Ok(LuaVec::<u8>::new_ref(s.script_ref(lua.get_world()?).index(Cow::Borrowed("cells"))))
};
set "cells" => |lua,s,o| {
Vec::<u8>::apply_lua(&mut s.script_ref(lua.get_world()?).index(Cow::Borrowed("cells")),lua,o)
};
}
);
#[derive(Default)]
pub struct LifeAPI;
impl APIProvider for LifeAPI {
type APITarget = Mutex<Lua>;
type ScriptContext = Mutex<Lua>;
type DocTarget = LuaDocFragment;
fn attach_api(&mut self, _: &mut Self::APITarget) -> Result<(), ScriptError> {
// we don't actually provide anything global
Ok(())
}
fn get_doc_fragment(&self) -> Option<Self::DocTarget> {
// this will enable us type casting in teal
Some(LuaDocFragment::new("MyAPI", |tw| {
tw.process_type::<LuaLifeState>()
}))
}
fn register_with_app(&self, app: &mut App) {
// this will register the `LuaProxyable` typedata since we derived it
// this will resolve retrievals of this component to our custom lua object
app.register_type::<LifeState>();
app.register_type::<Settings>();
}
}
#[derive(Reflect, Resource)]
#[reflect(Resource)]
pub struct Settings {
physical_grid_dimensions: (u32, u32),
display_grid_dimensions: (u32, u32),
border_thickness: u32,
live_color: u8,
dead_color: u8,
}
impl Default for Settings {
fn default() -> Self {
Self {
border_thickness: 1,
live_color: 255u8,
dead_color: 0u8,
physical_grid_dimensions: (88, 50),
display_grid_dimensions: (0, 0),
}
}
}
pub fn setup(
mut commands: Commands,
mut assets: ResMut<Assets<Image>>,
asset_server: Res<AssetServer>,
settings: Res<Settings>,
) {
let mut image = Image::new_fill(
Extent3d {
width: settings.physical_grid_dimensions.0,
height: settings.physical_grid_dimensions.1,
depth_or_array_layers: 1,
},
TextureDimension::D2,
&[0u8],
TextureFormat::R8Unorm,
);
image.sampler_descriptor = ImageSampler::nearest();
// in release builds we want to fetch ".lua" files over ".tl" files
let script_path = bevy_mod_scripting_lua::lua_path!("game_of_life");
commands.spawn(Camera2dBundle::default());
commands
.spawn(SpriteBundle {
texture: assets.add(image),
sprite: Sprite {
custom_size: Some(Vec2::new(
settings.display_grid_dimensions.0 as f32,
settings.display_grid_dimensions.1 as f32,
)),
color: Color::TOMATO,
..Default::default()
},
..Default::default()
})
.insert(LifeState {
cells: vec![
0u8;
(settings.physical_grid_dimensions.0 * settings.physical_grid_dimensions.1)
as usize
],
})
.insert(ScriptCollection::<LuaFile> {
scripts: vec![Script::new(
script_path.to_owned(),
asset_server.load(script_path),
)],
});
}
pub fn sync_window_size(
mut resize_event: EventReader<WindowResized>,
mut settings: ResMut<Settings>,
mut query: Query<&mut Sprite, With<LifeState>>,
primary_windows: Query<(&Window, With<PrimaryWindow>)>,
) {
if let Some(e) = resize_event
.iter()
.filter(|e| primary_windows.get(e.window).is_ok())
.last()
{
let (primary_window, _) = primary_windows.get(e.window).unwrap();
settings.display_grid_dimensions = (
primary_window.physical_width(),
primary_window.physical_height(),
);
// resize all game's of life, retain aspect ratio and fit the entire game in the window
for mut sprite in query.iter_mut() {
let scale = if settings.physical_grid_dimensions.0 > settings.physical_grid_dimensions.1
{
// horizontal is longer
settings.display_grid_dimensions.1 as f32
/ settings.physical_grid_dimensions.1 as f32
} else {
// vertical is longer
settings.display_grid_dimensions.0 as f32
/ settings.physical_grid_dimensions.0 as f32
};
sprite.custom_size = Some(Vec2::new(
(settings.physical_grid_dimensions.0 as f32) * scale,
(settings.physical_grid_dimensions.1 as f32) * scale,
));
}
}
}
/// Runs after LifeState components are updated, updates their rendered representation
pub fn update_rendered_state(
mut assets: ResMut<Assets<Image>>,
query: Query<(&LifeState, &Handle<Image>)>,
) {
for (new_state, old_rendered_state) in query.iter() {
let old_rendered_state = assets
.get_mut(old_rendered_state)
.expect("World is not setup correctly");
old_rendered_state.data = new_state.cells.clone();
}
}
/// Sends events allowing scripts to drive update logic
pub fn send_on_update(mut events: PriorityEventWriter<LuaEvent<()>>) {
events.send(
LuaEvent {
hook_name: "on_update".to_owned(),
args: (),
recipients: Recipients::All,
},
1,
)
}
/// Sends initialization event
pub fn send_init(mut events: PriorityEventWriter<LuaEvent<()>>) {
events.send(
LuaEvent {
hook_name: "init".to_owned(),
args: (),
recipients: Recipients::All,
},
0,
)
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, SystemSet)]
pub enum LifeSystemSets {
Scripts,
}
/// how often to step the simulation
const UPDATE_FREQUENCY: f32 = 1.0 / 20.0;
fn main() -> std::io::Result<()> {
let mut app = App::new();
app.add_plugins(DefaultPlugins)
.insert_resource(FixedTime::new_from_secs(UPDATE_FREQUENCY))
.add_plugin(LogDiagnosticsPlugin::default())
.add_plugin(FrameTimeDiagnosticsPlugin::default())
.add_plugin(ScriptingPlugin)
.init_resource::<Settings>()
.add_startup_system(setup)
.add_startup_system(send_init)
.add_system(sync_window_size)
.add_startup_system(|asset_server: ResMut<AssetServer>| {
asset_server.asset_io().watch_for_changes().unwrap()
})
.add_system(
update_rendered_state
.after(sync_window_size)
.in_schedule(CoreSchedule::FixedUpdate),
)
.add_system(
send_on_update
.after(update_rendered_state)
.in_schedule(CoreSchedule::FixedUpdate),
)
.configure_set(
LifeSystemSets::Scripts
.after(CoreSet::UpdateFlush)
.before(CoreSet::PostUpdate),
)
.add_system(
script_event_handler::<LuaScriptHost<()>, 0, 1>
.in_set(LifeSystemSets::Scripts)
.in_schedule(CoreSchedule::FixedUpdate),
)
.add_script_host_to_base_set::<LuaScriptHost<()>, _>(CoreSet::PostUpdate)
.add_api_provider::<LuaScriptHost<()>>(Box::new(LuaBevyAPIProvider))
.add_api_provider::<LuaScriptHost<()>>(Box::new(LifeAPI))
.update_documentation::<LuaScriptHost<()>>();
app.run();
Ok(())
}