Skip to content

Commit d52d896

Browse files
committed
improve logs and things
1 parent 9932a86 commit d52d896

File tree

10 files changed

+167
-79
lines changed

10 files changed

+167
-79
lines changed

assets/scripts/game_of_life.lua

Lines changed: 38 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1-
print("The game_of_life.lua script just got loaded")
2-
print("Hello from Lua! I am initiating the game of life simulation state to a random state now")
3-
4-
math.randomseed(os.time())
51
LifeState = world.get_type_by_name("LifeState")
62
Settings = world.get_type_by_name("Settings")
73

4+
world.info("Lua: The game_of_life.lua script just got loaded")
5+
world.info("Lua: Hello! I am initiating the game of life simulation state with randomness!")
6+
7+
math.randomseed(os.time())
8+
89
function fetch_life_state()
910
-- find the entity with life state
1011
local life_state = nil
@@ -19,11 +20,34 @@ local life_state = fetch_life_state()
1920
local cells = life_state.cells
2021

2122
-- set some cells alive
22-
for _=1,10000 do
23+
for _=1,1000 do
2324
local index = math.random(#cells)
2425
cells[index] = 255
2526
end
2627

28+
function on_click(x,y)
29+
-- get the settings
30+
world.info("Lua: Clicked at x: " .. x .. " y: " .. y)
31+
local settings = world.get_resource(Settings)
32+
local dimensions = settings.physical_grid_dimensions
33+
local screen = settings.display_grid_dimensions
34+
35+
local dimension_x = dimensions._1
36+
local dimension_y = dimensions._2
37+
38+
local screen_x = screen._1
39+
local screen_y = screen._2
40+
41+
local cell_width = screen_x / dimension_x
42+
local cell_height = screen_y / dimension_y
43+
44+
local cell_x = math.floor(x / cell_width)
45+
local cell_y = math.floor(y / cell_height)
46+
47+
local index = (cell_y * dimension_x) + cell_x
48+
cells[index] = 255
49+
end
50+
2751
function on_update()
2852
local cells = fetch_life_state().cells
2953
world.log_all_allocations()
@@ -38,14 +62,15 @@ function on_update()
3862
prev_state[#prev_state+1] = (not(v == 0)) and 1 or 0
3963
end
4064
for i=1,(dimension_x * dimension_y) do
41-
local north = prev_state[i - dimension_x] or 1
42-
local south = prev_state[i + dimension_x] or 1
43-
local east = prev_state[i + 1] or 1
44-
local west = prev_state[i - 1] or 1
45-
local northeast = prev_state[i - dimension_x + 1] or 1
46-
local southeast = prev_state[i + dimension_x + 1] or 1
47-
local northwest = prev_state[i - dimension_x - 1] or 1
48-
local southwest = prev_state[i + dimension_x - 1] or 1
65+
-- wrap around the north and south edges
66+
local north = prev_state[i - dimension_x] or prev_state[i + dimension_x * (dimension_y - 1)]
67+
local south = prev_state[i + dimension_x] or prev_state[i - dimension_x * (dimension_y - 1)]
68+
local east = prev_state[i + 1] or 0
69+
local west = prev_state[i - 1] or 0
70+
local northeast = prev_state[i - dimension_x + 1] or 0
71+
local southeast = prev_state[i + dimension_x + 1] or 0
72+
local northwest = prev_state[i - dimension_x - 1] or 0
73+
local southwest = prev_state[i + dimension_x - 1] or 0
4974

5075
local neighbours = north + south + east + west
5176
+ northeast + southeast + northwest + southwest

crates/bevy_mod_scripting_core/src/asset.rs

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@ use std::{
44
};
55

66
use bevy::{
7-
asset::{Asset, AssetLoader, AsyncReadExt},
7+
asset::{Asset, AssetId, AssetLoader, AsyncReadExt},
88
ecs::system::Resource,
99
reflect::TypePath,
10-
utils::BoxedFuture,
10+
utils::{BoxedFuture, HashMap},
1111
};
1212

1313
use crate::{prelude::ScriptError, script::ScriptId};
@@ -84,3 +84,23 @@ impl Default for ScriptAssetSettings {
8484
pub struct AssetPathToScriptIdMapper {
8585
pub map: fn(&Path) -> ScriptId,
8686
}
87+
88+
/// A cache of asset id's to their script id's. Necessary since when we drop an asset we won't have the ability to get the path from the asset.
89+
#[derive(Default, Debug, Resource)]
90+
pub struct AssetIdToScriptIdMap {
91+
pub map: HashMap<AssetId<ScriptAsset>, ScriptId>,
92+
}
93+
94+
impl AssetIdToScriptIdMap {
95+
pub fn insert(&mut self, id: AssetId<ScriptAsset>, path: ScriptId) {
96+
self.map.insert(id, path);
97+
}
98+
99+
pub fn get(&self, id: AssetId<ScriptAsset>) -> Option<&ScriptId> {
100+
self.map.get(&id)
101+
}
102+
103+
pub fn remove(&mut self, id: AssetId<ScriptAsset>) -> Option<ScriptId> {
104+
self.map.remove(&id)
105+
}
106+
}

crates/bevy_mod_scripting_core/src/bindings/pretty_print.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@ use crate::reflection_extensions::{FakeType, TypeIdExtensions};
33
use super::{
44
script_value::ScriptValue, ReflectBase, ReflectBaseType, ReflectReference, WorldGuard,
55
};
6-
use bevy::reflect::{PartialReflect, ReflectRef};
6+
use bevy::{
7+
prelude::World,
8+
reflect::{PartialReflect, ReflectRef},
9+
};
710
use itertools::Itertools;
811
use std::{any::TypeId, borrow::Cow};
912

@@ -56,7 +59,7 @@ macro_rules! downcast_case {
5659
}
5760

5861
impl ReflectReferencePrinter {
59-
const UNREGISTERED_TYPE: &'static str = "Unregistered TypeId";
62+
const UNREGISTERED_TYPE: &'static str = "Unregistered";
6063
const UNKNOWN_FIELD: &'static str = "<Unknown Field>";
6164

6265
pub fn new(reference: ReflectReference) -> Self {
@@ -65,13 +68,7 @@ impl ReflectReferencePrinter {
6568

6669
fn pretty_print_base(base: &ReflectBaseType, world: WorldGuard, out: &mut String) {
6770
let type_id = base.type_id;
68-
let type_registry = world.type_registry();
69-
let type_registry = type_registry.read();
70-
71-
let type_path = type_registry
72-
.get_type_info(type_id)
73-
.map(|t| t.type_path_table().short_path())
74-
.unwrap_or_else(|| ReflectReferencePrinter::UNREGISTERED_TYPE);
71+
let type_path = type_id.display_with_world(world.clone());
7572

7673
let base_kind = match base.base_id {
7774
ReflectBase::Component(e, _) => format!("Component on entity {}", e),
@@ -365,6 +362,9 @@ impl DisplayWithWorld for TypeId {
365362
fn display_with_world(&self, world: WorldGuard) -> String {
366363
if *self == TypeId::of::<FakeType>() {
367364
return "Dynamic Type".to_owned();
365+
} else if *self == TypeId::of::<World>() {
366+
// does not implement Reflect, so we do this manually
367+
return "World".to_owned();
368368
}
369369

370370
let type_registry = world.type_registry();

crates/bevy_mod_scripting_core/src/commands.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ impl<P: IntoScriptPluginParams> Command for CreateOrUpdateScript<P> {
117117
match ctxt {
118118
Ok(ctxt) => contexts.insert(ctxt),
119119
Err(e) => {
120-
handle_script_errors(world, [e.with_context(format!("Loading context for script with id: {}. With runtime type: {} and context type: {}", self.id, type_name::<P::R>(), type_name::<P::C>()))].into_iter());
120+
handle_script_errors(world, [e.with_context(format!("Loading script with id: {}. Runtime type: {}, Context type: {}", self.id, type_name::<P::R>(), type_name::<P::C>()))].into_iter());
121121
return;
122122
}
123123
}

crates/bevy_mod_scripting_core/src/lib.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#![allow(clippy::arc_with_non_send_sync)]
22

33
use crate::event::ScriptErrorEvent;
4-
use asset::{ScriptAsset, ScriptAssetLoader, ScriptAssetSettings};
4+
use asset::{AssetIdToScriptIdMap, ScriptAsset, ScriptAssetLoader, ScriptAssetSettings};
55
use bevy::prelude::*;
66
use bindings::{
77
function::script_function::AppScriptFunctionRegistry, script_value::ScriptValue,
@@ -83,6 +83,7 @@ impl<P: IntoScriptPluginParams> Plugin for ScriptingPlugin<P> {
8383
.init_resource::<AppReflectAllocator>()
8484
.init_resource::<ScriptAssetSettings>()
8585
.init_resource::<Scripts>()
86+
.init_resource::<AssetIdToScriptIdMap>()
8687
.init_asset::<ScriptAsset>()
8788
.register_asset_loader(ScriptAssetLoader {
8889
language: "<>".into(),
@@ -230,6 +231,8 @@ impl<D: DocumentationFragment> StoreDocumentation<D> for App {
230231

231232
#[cfg(test)]
232233
mod test {
234+
use asset::AssetIdToScriptIdMap;
235+
233236
use super::*;
234237

235238
#[test]
@@ -261,5 +264,6 @@ mod test {
261264
.contains_resource::<ContextLoadingSettings<Plugin>>());
262265
assert!(app.world().contains_non_send::<RuntimeContainer<Plugin>>());
263266
assert!(app.world().contains_non_send::<ScriptContexts<Plugin>>());
267+
assert!(app.world().contains_resource::<AssetIdToScriptIdMap>());
264268
}
265269
}

crates/bevy_mod_scripting_core/src/systems.rs

Lines changed: 31 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use bevy::{ecs::system::SystemState, prelude::*};
22
use std::any::type_name;
33

44
use crate::{
5-
asset::{ScriptAsset, ScriptAssetSettings},
5+
asset::{AssetIdToScriptIdMap, ScriptAsset, ScriptAssetSettings},
66
bindings::{pretty_print::DisplayWithWorld, ReflectAllocator, WorldAccessGuard, WorldGuard},
77
commands::{CreateOrUpdateScript, DeleteScript},
88
context::{Context, ContextLoadingSettings, ScriptContexts},
@@ -35,39 +35,51 @@ pub fn sync_script_data<P: IntoScriptPluginParams>(
3535
mut events: EventReader<AssetEvent<ScriptAsset>>,
3636
script_assets: Res<Assets<ScriptAsset>>,
3737
asset_settings: Res<ScriptAssetSettings>,
38+
mut asset_path_map: ResMut<AssetIdToScriptIdMap>,
3839
mut commands: Commands,
3940
) {
4041
for event in events.read() {
41-
debug!("Responding to script asset event: {:?}", event);
42+
trace!("Received script asset event: {:?}", event);
4243
let (id, remove) = match event {
4344
// emitted when a new script asset is loaded for the first time
4445
AssetEvent::Added { id } => (id, false),
4546
AssetEvent::Modified { id } => (id, false),
46-
AssetEvent::Removed { id } | AssetEvent::Unused { id } => (id, true),
47+
AssetEvent::Removed { id } => (id, true),
4748
_ => continue,
4849
};
50+
info!("Responding to script asset event: {:?}", event);
4951
// get the path
5052
let asset = script_assets.get(*id);
51-
let asset = match asset.as_ref() {
52-
Some(a) => a,
53+
54+
let script_id = match asset_path_map.get(*id) {
55+
Some(id) => id.clone(),
5356
None => {
54-
if remove {
55-
debug!(
56-
"Script presumably failed to load, no need to remove anything, ignoring."
57-
);
58-
continue;
59-
} else {
60-
panic!("Asset was expected to be loaded!");
61-
}
57+
// we should only enter this branch for new assets
58+
let asset = match asset {
59+
Some(asset) => asset,
60+
None => {
61+
// this can happen if an asset is loaded and immediately unloaded, we can ignore this
62+
continue;
63+
}
64+
};
65+
66+
let path = &asset.asset_path;
67+
let converter = asset_settings.script_id_mapper.map;
68+
let script_id = converter(path);
69+
asset_path_map.insert(*id, script_id.clone());
70+
71+
script_id
6272
}
6373
};
6474

65-
let path = &asset.asset_path;
66-
// convert it to script id
67-
let converter = asset_settings.script_id_mapper.map;
68-
let script_id = converter(path);
69-
7075
if !remove {
76+
let asset = match asset {
77+
Some(asset) => asset,
78+
None => {
79+
// this can happen if an asset is loaded and immediately unloaded, we can ignore this
80+
continue;
81+
}
82+
};
7183
commands.queue(CreateOrUpdateScript::<P>::new(
7284
script_id,
7385
asset.content.clone(),
@@ -164,7 +176,7 @@ pub fn event_handler<L: IntoCallbackLabel, P: IntoScriptPluginParams>(
164176
let script = match scripts.scripts.get(script_id) {
165177
Some(s) => s,
166178
None => {
167-
info!(
179+
trace!(
168180
"Script `{}` on entity `{:?}` is either still loading or doesn't exist, ignoring.",
169181
script_id, entity
170182
);

crates/bevy_mod_scripting_functions/src/core.rs

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,7 @@ pub fn register_world_functions(reg: &mut World) -> Result<(), FunctionRegistrat
3232
.register(
3333
"get_type_by_name",
3434
|world: WorldCallbackAccess, type_name: String| {
35-
println!("get_type_by_name in: {}", type_name);
3635
let val = world.get_type_by_name(type_name)?;
37-
println!("get_type_by_name out: {:?}", val);
3836
Ok(val.map(Val))
3937
},
4038
)
@@ -151,14 +149,9 @@ pub fn register_world_functions(reg: &mut World) -> Result<(), FunctionRegistrat
151149
let world = s.try_read().expect("stale world");
152150
let allocator = world.allocator();
153151
let allocator = allocator.read();
154-
for (id,a) in allocator.iter_allocations() {
152+
for (id,_) in allocator.iter_allocations() {
155153
let raid = ReflectAccessId::for_allocation(id.clone());
156154
if world.claim_read_access(raid) {
157-
{
158-
let ptr = a.get_ptr();
159-
let a = unsafe { &*ptr };
160-
bevy::log::info!("Allocation Id: {}, value: {:?}", id.id(), a);
161-
}
162155
// Safety: ref released above
163156
unsafe { world.release_access(raid) };
164157
} else {

crates/languages/bevy_mod_scripting_lua/src/bindings/reference.rs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -144,9 +144,7 @@ fn try_call_overloads(
144144
}
145145
}
146146

147-
Err(last_error
148-
.unwrap_or_else(|| InteropError::missing_function(type_id, key.to_string()).into())
149-
.into())
147+
Err(last_error.unwrap_or_else(|| InteropError::missing_function(type_id, key.to_string())))
150148
}
151149

152150
impl UserData for LuaReflectReference {
@@ -375,8 +373,11 @@ impl UserData for LuaStaticReflectReference {
375373
return func?.into_lua(lua);
376374
}
377375
};
378-
379-
Err(InteropError::missing_function(type_id, key.to_string()).into())
376+
let world = lua.get_world();
377+
Err(
378+
InteropError::missing_function(type_id, key.display_with_world(world.clone()))
379+
.into(),
380+
)
380381
},
381382
);
382383
}

crates/languages/bevy_mod_scripting_lua/src/lib.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ use bindings::{
2727
world::{GetWorld, LuaWorld},
2828
};
2929
pub use mlua;
30-
use mlua::{Function, IntoLuaMulti, Lua};
30+
use mlua::{Function, IntoLua, IntoLuaMulti, Lua, MultiValue};
3131
pub mod bindings;
3232
pub mod prelude {
3333
pub use crate::mlua::{self, prelude::*, Value};
@@ -195,13 +195,13 @@ pub fn lua_handler(
195195
Err(_) => return Ok(()),
196196
};
197197

198-
handler
199-
.call::<()>(
200-
args.into_iter()
201-
.map(LuaScriptValue::from)
202-
.collect::<Vec<_>>(),
203-
)
204-
.map_err(ScriptError::from_mlua_error)?;
198+
let input = MultiValue::from_vec(
199+
args.into_iter()
200+
.map(|arg| LuaScriptValue::from(arg).into_lua(context))
201+
.collect::<Result<_, _>>()?,
202+
);
203+
204+
handler.call::<()>(input)?;
205205
Ok(())
206206
})
207207
}

0 commit comments

Comments
 (0)