From 74d7803ab0d4ed4ec9952d32972a121e289fe288 Mon Sep 17 00:00:00 2001 From: Milky2018 <842376130@qq.com> Date: Wed, 11 Nov 2026 20:54:31 +0800 Subject: [PATCH 1/2] refactor: give runtime state World ownership and indexed storage --- docs/CHANGELOG.md | 11 + examples/pixeladventure/systems.mbt | 49 ++-- examples/survivors/enemy.mbt | 128 +++++---- examples/survivors/pkg.generated.mbti | 4 +- selene-core/src/a11y/actions.mbt | 3 +- selene-core/src/a11y/moon.pkg | 1 + selene-core/src/a11y/tree.mbt | 50 ++-- selene-core/src/animation/animation_apply.mbt | 8 +- .../src/animation/animation_blend_eval.mbt | 18 +- .../src/animation/animation_graph_ops.mbt | 21 +- .../src/animation/animation_player_ops.mbt | 13 +- .../src/animation/animation_skinning.mbt | 65 +++-- selene-core/src/animation/animation_types.mbt | 3 +- .../src/animation/animation_wbtest.mbt | 24 ++ selene-core/src/animation/pkg.generated.mbti | 3 +- selene-core/src/app/scheduler.mbt | 2 +- selene-core/src/audio/deletion_wbtest.mbt | 24 ++ selene-core/src/audio/pkg.generated.mbti | 2 +- selene-core/src/audio/playback.mbt | 14 +- selene-core/src/autotile2d/moon.pkg | 1 - selene-core/src/autotile2d/pkg.generated.mbti | 4 +- selene-core/src/autotile2d/rules.mbt | 5 +- selene-core/src/autotile2d/runtime.mbt | 16 +- selene-core/src/autotile2d/solver.mbt | 89 +++--- selene-core/src/camera3d/camera.mbt | 11 +- selene-core/src/collision/collider.mbt | 20 +- ...omponent_test.mbt => component_wbtest.mbt} | 6 +- selene-core/src/collision/pkg.generated.mbti | 2 +- selene-core/src/collision/rapier2d_api.mbt | 14 +- selene-core/src/collision/rapier2d_events.mbt | 102 ++++--- .../src/collision/rapier2d_runtime.mbt | 86 +++--- selene-core/src/collision/rapier2d_shapes.mbt | 7 +- selene-core/src/collision/rapier2d_step.mbt | 16 +- .../src/collision/rapier2d_sync_joints.mbt | 6 +- .../src/culling2d/culling2d_wbtest.mbt | 29 ++ selene-core/src/culling2d/pkg.generated.mbti | 2 +- selene-core/src/culling2d/spatial_grid.mbt | 13 +- selene-core/src/ecs/README.md | 18 ++ selene-core/src/ecs/entity_table.mbt | 263 ++++++++++++++++++ .../src/ecs/entity_table_bench_wbtest.mbt | 66 +++++ selene-core/src/ecs/entity_table_test.mbt | 134 +++++++++ selene-core/src/ecs/pkg.generated.mbti | 18 ++ selene-core/src/ecs/spawn_draft.mbt | 16 +- selene-core/src/event/event_wbtest.mbt | 58 ++++ selene-core/src/event/events.mbt | 24 +- selene-core/src/event/pkg.generated.mbti | 4 +- selene-core/src/event/reader.mbt | 10 +- selene-core/src/event/schedule.mbt | 14 +- selene-core/src/inputs/gamepad.mbt | 5 +- selene-core/src/ldtk/ldtk_wbtest.mbt | 2 +- selene-core/src/ldtk/ldtk_world_entities.mbt | 12 +- selene-core/src/ldtk/ldtk_world_layers.mbt | 4 +- selene-core/src/ldtk/ldtk_world_registry.mbt | 2 +- selene-core/src/ldtk/ldtk_world_runtime.mbt | 14 +- selene-core/src/ldtk/ldtk_world_spawner.mbt | 6 +- selene-core/src/ldtk/ldtk_world_types.mbt | 14 +- selene-core/src/ldtk/ldtk_world_utils.mbt | 15 +- selene-core/src/ldtk/moon.pkg | 1 + selene-core/src/ldtk/pkg.generated.mbti | 5 +- selene-core/src/physics2d/physics.mbt | 4 +- selene-core/src/physics2d/pkg.generated.mbti | 2 +- .../physics3d/physics3d_constraints_sync.mbt | 10 +- .../src/physics3d/physics3d_shape_queries.mbt | 5 +- selene-core/src/physics3d/physics3d_sync.mbt | 48 ++-- .../physics3d/physics3d_transform_bridge.mbt | 50 ++-- .../src/physics3d/physics3d_wbtest.mbt | 4 +- selene-core/src/physics3d/pkg.generated.mbti | 4 +- selene-core/src/render2d/frame.mbt | 27 +- selene-core/src/render2d/moon.pkg | 1 + selene-core/src/render3d/extract.mbt | 5 +- selene-core/src/render3d_pipeline/prepare.mbt | 11 +- .../src/runtime_debug/deterministic_input.mbt | 40 ++- .../src/runtime_debug/frame_metrics.mbt | 26 +- .../src/runtime_debug/render_capture.mbt | 17 +- .../runtime_debug/runtime_debug_wbtest.mbt | 37 +++ .../snapshot_inspector_overlay.mbt | 2 +- selene-core/src/runtime_debug/world.mbt | 5 - selene-core/src/scene/spawner.mbt | 8 +- selene-core/src/scene3d/gltf_parse_node.mbt | 2 +- selene-core/src/scene3d/scene_instantiate.mbt | 9 +- selene-core/src/scene3d/scene_load_api.mbt | 5 +- selene-core/src/text2d/layout.mbt | 12 +- selene-core/src/text2d/render.mbt | 6 +- selene-core/src/tiled/moon.pkg | 1 + selene-core/src/tiled/world.mbt | 10 +- selene-core/src/touch_controls/runtime.mbt | 19 +- selene-core/src/ui/interaction.mbt | 5 +- selene-core/src/ui/layout.mbt | 9 +- selene-core/src/ui/layout_runtime.mbt | 30 +- selene-core/src/ui/layout_runtime_wbtest.mbt | 28 ++ selene-core/src/ui/model.mbt | 49 ++-- selene-core/src/ui/pkg.generated.mbti | 8 +- selene-core/src/ui/visual.mbt | 2 +- selene-core/src/visibility/pkg.generated.mbti | 4 +- selene-core/src/visibility/visibility.mbt | 25 +- selene-core/src/window/display.mbt | 5 +- selene-webgpu/src/audio.mbt | 16 +- selene-webgpu/src/draw.mbt | 28 +- selene-webgpu/src/moon.pkg | 1 + selene-webgpu/src/text_cosmic.mbt | 4 +- 100 files changed, 1420 insertions(+), 741 deletions(-) rename selene-core/src/collision/{component_test.mbt => component_wbtest.mbt} (63%) create mode 100644 selene-core/src/ecs/entity_table.mbt create mode 100644 selene-core/src/ecs/entity_table_bench_wbtest.mbt create mode 100644 selene-core/src/ecs/entity_table_test.mbt diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 0a43b51b..e7fb37e3 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -38,6 +38,17 @@ ### Changed +- Store engine runtime state, event buses, and event reader cursors in their + owning World resources instead of global World-ID maps. +- Index entity runtime data by reusable slots with full-handle validation, + insertion-ordered traversal, and explicit cleanup of orphan generations. + Read physics results with `resolved_velocity(entity)`. +- Use arrays for animation graph and glTF node indices, typed integer keys for + spatial/autotile grids and physics handles, and sets for membership tracking. + Remove unnecessary iteration snapshots and defer example entity deletions. +- Filter animation fades in place and snapshot observer subscriptions when + callbacks can modify them during dispatch. + - Destructure tuple elements directly in `for` patterns across the engine, backend, examples, and tests, removing temporary tuple bindings and projections. diff --git a/examples/pixeladventure/systems.mbt b/examples/pixeladventure/systems.mbt index d2071769..c078eea4 100644 --- a/examples/pixeladventure/systems.mbt +++ b/examples/pixeladventure/systems.mbt @@ -419,9 +419,10 @@ fn player_controller_system(world : @ecs.World) -> Unit { return } - let resolved_velocity = @physics2d.resolved_velocities() - .get(session.player) - .map_or(@math.Vec2::zero(), fn(velocity) { velocity.0 }) + let resolved_velocity = @physics2d.resolved_velocity(session.player).map_or( + @math.Vec2::zero(), + fn(velocity) { velocity.0 }, + ) let grounded = @physics2d.is_grounded(session.player) let velocity = player_motion_base_velocity( resolved_velocity, @@ -496,25 +497,26 @@ fn player_bird_contact_system(world : @ecs.World) -> Unit { guard entity_rect(session.player) is Some(player_rect) else { return } let fixed_delta = @time.fixed_delta() - let player_resolved_velocity = @physics2d.resolved_velocities() - .get(session.player) - .map_or(@math.Vec2::zero(), fn(v) { v.0 }) + let player_resolved_velocity = @physics2d.resolved_velocity(session.player).map_or( + @math.Vec2::zero(), + fn(v) { v.0 }, + ) let player_prev_rect = player_rect.shift( player_resolved_velocity.scalar_mul(-fixed_delta), ) - for (bird_entity, _) in birds().to_array() { + for bird_entity, bird in birds() { if !bird_entity.is_alive() { continue } - guard birds().get(bird_entity) is Some(bird) else { continue } if bird.is_hurt { continue } guard entity_rect(bird_entity) is Some(bird_rect) else { continue } - let bird_resolved_velocity = @physics2d.resolved_velocities() - .get(bird_entity) - .map_or(@math.Vec2::zero(), fn(v) { v.0 }) + let bird_resolved_velocity = @physics2d.resolved_velocity(bird_entity).map_or( + @math.Vec2::zero(), + fn(v) { v.0 }, + ) let bird_prev_rect = bird_rect.shift( bird_resolved_velocity.scalar_mul(-fixed_delta), ) @@ -539,12 +541,12 @@ fn player_bird_contact_system(world : @ecs.World) -> Unit { } ///| -fn bird_patrol_system(_world : @ecs.World) -> Unit { - for (bird_entity, _) in birds().to_array() { +fn bird_patrol_system(world : @ecs.World) -> Unit { + let commands = @ecs.commands(world) + for bird_entity, bird in birds() { if !bird_entity.is_alive() { continue } - guard birds().get(bird_entity) is Some(bird) else { continue } if bird.is_hurt { @physics2d.linear_velocities().set(bird_entity, @math.Vec2::zero()) if @physics2d.colliders().get(bird_entity) is Some(collider) { @@ -552,14 +554,16 @@ fn bird_patrol_system(_world : @ecs.World) -> Unit { } play_bird_animation(bird_entity, bird) if sprite_animation_finished(bird_entity) { - ignore(bird_entity.delete()) + commands.delete(bird_entity) } continue } - let resolved_x = @physics2d.resolved_velocities() - .get(bird_entity) - .map_or(0.0, fn(v) { v.0.x }) + let resolved_x = @physics2d.resolved_velocity(bird_entity).map_or(0.0, fn( + v, + ) { + v.0.x + }) let blocked = match bird.direction { Left => resolved_x > -BIRD_SPEED * 0.5 Right => resolved_x < BIRD_SPEED * 0.5 @@ -583,30 +587,31 @@ fn bird_patrol_system(_world : @ecs.World) -> Unit { ///| fn trigger_system(world : @ecs.World) -> Unit { + let commands = @ecs.commands(world) guard (world.get_resource() : GameSession?) is Some(session) else { return } if player_is_frozen(session.result) { return } - for (flag_entity, _) in flags().to_array() { + for flag_entity in flags().keys() { if !flag_entity.is_alive() { continue } if @physics2d.get_contains(flag_entity).contains(session.player) { session.score += 100 session.result = Some(Win) - ignore(flag_entity.delete()) + commands.delete(flag_entity) } } - for (apple_entity, _) in apples().to_array() { + for apple_entity in apples().keys() { if !apple_entity.is_alive() { continue } if @physics2d.get_contains(apple_entity).contains(session.player) { session.score += 10 play_sfx(coin_sound(), session.volume_on) - ignore(apple_entity.delete()) + commands.delete(apple_entity) } } } diff --git a/examples/survivors/enemy.mbt b/examples/survivors/enemy.mbt index 5675c4c6..baf82a63 100644 --- a/examples/survivors/enemy.mbt +++ b/examples/survivors/enemy.mbt @@ -183,58 +183,66 @@ fn reset_wave_state() -> Unit { } ///| -let enemy_data : Map[EnemyType, EnemyData] = { - let data = Map([]) - data.set(Creeper, { - health: 1.0, - speed: 60.0, - points: 10, - right_animation: creeper_right_animation, - left_animation: creeper_left_animation, - }) - data.set(Icecream, { - health: 2.0, - speed: 90.0, - points: 20, - right_animation: icecream_right_animation, - left_animation: icecream_left_animation, - }) - data.set(Orc, { - health: 3.0, - speed: 75, - points: 30, - right_animation: orc_right_animation, - left_animation: orc_left_animation, - }) - data.set(Skull, { - health: 5.0, - speed: 60.0, - points: 40, - right_animation: skull_right_animation, - left_animation: skull_left_animation, - }) - data.set(Teleman, { - health: 20.0, - speed: 60.0, - points: 80, - right_animation: teleman_right_animation, - left_animation: teleman_left_animation, - }) - data.set(Devil, { - health: 8.0, - speed: 90.0, - points: 50, - right_animation: devil_right_animation, - left_animation: devil_left_animation, - }) - data.set(Pirate, { - health: 500.0, - speed: 60.0, - points: 200, - right_animation: pirate_right_animation, - left_animation: pirate_left_animation, - }) - data +let creeper_data : EnemyData = { + health: 1.0, + speed: 60.0, + points: 10, + right_animation: creeper_right_animation, + left_animation: creeper_left_animation, +} + +///| +let icecream_data : EnemyData = { + health: 2.0, + speed: 90.0, + points: 20, + right_animation: icecream_right_animation, + left_animation: icecream_left_animation, +} + +///| +let orc_data : EnemyData = { + health: 3.0, + speed: 75, + points: 30, + right_animation: orc_right_animation, + left_animation: orc_left_animation, +} + +///| +let skull_data : EnemyData = { + health: 5.0, + speed: 60.0, + points: 40, + right_animation: skull_right_animation, + left_animation: skull_left_animation, +} + +///| +let teleman_data : EnemyData = { + health: 20.0, + speed: 60.0, + points: 80, + right_animation: teleman_right_animation, + left_animation: teleman_left_animation, +} + +///| +let devil_data : EnemyData = { + health: 8.0, + speed: 90.0, + points: 50, + right_animation: devil_right_animation, + left_animation: devil_left_animation, +} + +///| +let pirate_data : EnemyData = { + health: 500.0, + speed: 60.0, + points: 200, + right_animation: pirate_right_animation, + left_animation: pirate_left_animation, } ///| @@ -339,7 +347,7 @@ priv struct Enemy { } ///| -#derive(Eq, Hash) +#derive(Eq) enum EnemyType { Creeper Icecream @@ -353,9 +361,6 @@ enum EnemyType { ///| pub extend EnemyType with Eq::{not_equal, equal} -///| -pub extend EnemyType with Hash::{hash, hash_combine} - ///| fn enemies() -> @ecs.ComponentStore[Enemy] { @ecs.components() @@ -395,9 +400,14 @@ fn play_enemy_animation_state( ///| fn get_enemy_data(enemy_type : EnemyType) -> EnemyData { - match enemy_data.get(enemy_type) { - Some(data) => data - None => abort("Enemy data not found") + match enemy_type { + Creeper => creeper_data + Icecream => icecream_data + Orc => orc_data + Skull => skull_data + Teleman => teleman_data + Devil => devil_data + Pirate => pirate_data } } diff --git a/examples/survivors/pkg.generated.mbti b/examples/survivors/pkg.generated.mbti index 103eaab1..d35e9d79 100644 --- a/examples/survivors/pkg.generated.mbti +++ b/examples/survivors/pkg.generated.mbti @@ -7,11 +7,9 @@ pub fn run() -> Unit // Errors // Types and methods -#derive(Eq, Hash) +#derive(Eq) type EnemyType pub fn EnemyType::equal(Self, Self) -> Bool -pub fn EnemyType::hash(Self) -> Int32 -pub fn EnemyType::hash_combine(Self, Hasher) -> Unit pub fn EnemyType::not_equal(Self, Self) -> Bool #derive(Eq) diff --git a/selene-core/src/a11y/actions.mbt b/selene-core/src/a11y/actions.mbt index adee88ac..37c0487e 100644 --- a/selene-core/src/a11y/actions.mbt +++ b/selene-core/src/a11y/actions.mbt @@ -57,7 +57,8 @@ fn dispatch_action( fn process_action_requests() -> Unit { for request in pending_action_requests { guard request.target_tree() == a11y_tree_id else { continue } - guard current_node_entities.get(request.target_node()) is Some(entity) else { + guard a11y_runtime().current_node_entities.get(request.target_node()) + is Some(entity) else { continue } dispatch_action(entity, request.action(), request.data()) diff --git a/selene-core/src/a11y/moon.pkg b/selene-core/src/a11y/moon.pkg index 27e532ff..b3f459ab 100644 --- a/selene-core/src/a11y/moon.pkg +++ b/selene-core/src/a11y/moon.pkg @@ -1,4 +1,5 @@ import { + "moonbitlang/core/set", "Milky2018/moon_accesskit", "Milky2018/selene/ecs", "Milky2018/selene/ui", diff --git a/selene-core/src/a11y/tree.mbt b/selene-core/src/a11y/tree.mbt index eda0f126..20ba1cc8 100644 --- a/selene-core/src/a11y/tree.mbt +++ b/selene-core/src/a11y/tree.mbt @@ -16,13 +16,23 @@ let a11y_tree_id : @moon_accesskit.TreeId = @moon_accesskit.TreeId::root() ///| -let latest_tree_update_ref : Ref[@moon_accesskit.TreeUpdate?] = { val: None, } +priv struct A11yRuntime { + mut latest_update : @moon_accesskit.TreeUpdate? + entity_node_ids : @ecs.EntityTable[UInt64] + current_node_entities : Map[@moon_accesskit.NodeId, @ecs.Entity] +} ///| -let entity_node_ids : Map[@ecs.Entity, UInt64] = Map([]) +let a11y_runtime_key : @ecs.ResourceKey[A11yRuntime] = ResourceKey() ///| -let current_node_entities : Map[@moon_accesskit.NodeId, @ecs.Entity] = Map([]) +fn a11y_runtime() -> A11yRuntime { + a11y_runtime_key.get_or_insert_with(@ecs.require_current_world(), world => { + latest_update: None, + entity_node_ids: EntityTable(world), + current_node_entities: {}, + }) +} ///| let next_node_id : Ref[UInt64] = { val: 1UL, } @@ -49,12 +59,12 @@ pub fn blur() -> Unit { ///| pub fn latest_tree_update() -> @moon_accesskit.TreeUpdate? { - latest_tree_update_ref.val + a11y_runtime().latest_update } ///| pub fn latest_tree_update_json() -> Json? { - if latest_tree_update_ref.val is Some(update) { + if a11y_runtime().latest_update is Some(update) { Some(update.to_json()) } else { None @@ -63,10 +73,12 @@ pub fn latest_tree_update_json() -> Json? { ///| pub fn a11y_sync_system(_delta : Double) -> Unit { + let world = @ecs.require_current_world() + a11y_runtime().entity_node_ids.retain((entity, _) => entity.is_valid_in(world)) let ordered = collect_ordered_semantic_entities() let (roots, child_map) = build_hierarchy(ordered) let update = build_tree_update(ordered, roots, child_map) - latest_tree_update_ref.val = Some(update) + a11y_runtime().latest_update = Some(update) process_action_requests() } @@ -151,10 +163,10 @@ fn ui_children(entity : @ecs.Entity) -> Array[@ecs.Entity] { fn collect_semantic_descendants( root : @ecs.Entity, ordered : Array[@ecs.Entity], - seen : Map[@ecs.Entity, Bool], + seen : @set.Set[@ecs.Entity], ) -> Unit { if get_a11y(root) is Some(_) && !seen.contains(root) { - seen.set(root, true) + seen.add(root) ordered.push(root) } for child in ui_children(root) { @@ -165,7 +177,7 @@ fn collect_semantic_descendants( ///| fn collect_ordered_semantic_entities() -> Array[@ecs.Entity] { let ordered : Array[@ecs.Entity] = [] - let seen : Map[@ecs.Entity, Bool] = Map([]) + let seen : @set.Set[@ecs.Entity] = Set([]) for entity, _node in @ui.nodes() { guard entity.is_alive() else { continue } match entity.get_parent() { @@ -178,7 +190,7 @@ fn collect_ordered_semantic_entities() -> Array[@ecs.Entity] { guard entity.is_alive() else { continue } guard get_a11y(entity) is Some(_) else { continue } if !seen.contains(entity) { - seen.set(entity, true) + seen.add(entity) ordered.push(entity) } } @@ -200,9 +212,11 @@ fn find_semantic_parent(entity : @ecs.Entity) -> @ecs.Entity? { ///| fn build_hierarchy( ordered : Array[@ecs.Entity], -) -> (Array[@ecs.Entity], Map[@ecs.Entity, Array[@ecs.Entity]]) { +) -> (Array[@ecs.Entity], @ecs.EntityTable[Array[@ecs.Entity]]) { let roots : Array[@ecs.Entity] = [] - let children : Map[@ecs.Entity, Array[@ecs.Entity]] = Map([]) + let children : @ecs.EntityTable[Array[@ecs.Entity]] = EntityTable( + @ecs.require_current_world(), + ) for entity in ordered { if find_semantic_parent(entity) is Some(parent) { children.get_or_init(parent, () => []).push(entity) @@ -245,12 +259,12 @@ fn is_clickable(entity : @ecs.Entity, a11y : A11y) -> Bool { ///| fn get_or_create_node_id(entity : @ecs.Entity) -> @moon_accesskit.NodeId { - if entity_node_ids.get(entity) is Some(raw) { + if a11y_runtime().entity_node_ids.get(entity) is Some(raw) { NodeId(raw) } else { let raw = next_node_id.val next_node_id.val = next_node_id.val + 1UL - entity_node_ids.set(entity, raw) + a11y_runtime().entity_node_ids.set(entity, raw) NodeId(raw) } } @@ -268,9 +282,9 @@ fn focused_node_id() -> @moon_accesskit.NodeId { fn build_tree_update( ordered : Array[@ecs.Entity], roots : Array[@ecs.Entity], - child_map : Map[@ecs.Entity, Array[@ecs.Entity]], + child_map : @ecs.EntityTable[Array[@ecs.Entity]], ) -> @moon_accesskit.TreeUpdate { - current_node_entities.clear() + a11y_runtime().current_node_entities.clear() let update = @moon_accesskit.TreeUpdate(a11y_tree_id, focused_node_id()) let root = @moon_accesskit.Node(Window) root.set_label("Selene") @@ -278,7 +292,7 @@ fn build_tree_update( for entity in roots { let id = get_or_create_node_id(entity) root_children.push(id) - current_node_entities.set(id, entity) + a11y_runtime().current_node_entities.set(id, entity) } root.set_children(root_children) update.push_node(@moon_accesskit.NodeId::root(), root) @@ -286,7 +300,7 @@ fn build_tree_update( for entity in ordered { guard get_a11y(entity) is Some(a11y) else { continue } let id = get_or_create_node_id(entity) - current_node_entities.set(id, entity) + a11y_runtime().current_node_entities.set(id, entity) let node = @moon_accesskit.Node(to_accesskit_role(a11y.role)) if effective_label(entity, a11y) is Some(label) { node.set_label(label) diff --git a/selene-core/src/animation/animation_apply.mbt b/selene-core/src/animation/animation_apply.mbt index 51fdbbdb..1ae11961 100644 --- a/selene-core/src/animation/animation_apply.mbt +++ b/selene-core/src/animation/animation_apply.mbt @@ -178,12 +178,12 @@ pub fn transform_scale_field() -> AnimatedFieldHandle { ///| fn morph_weights_of(target_entity : @ecs.Entity) -> Array[Double] { - for (_, binding) in morphed_meshes().to_array() { + for _, binding in morphed_meshes() { if binding.target_entity == target_entity { return binding.morph_weights.copy() } } - for (_, binding) in skinned_meshes().to_array() { + for _, binding in skinned_meshes() { if binding.target_entity == target_entity { return binding.morph_weights.copy() } @@ -196,13 +196,13 @@ fn set_target_morph_weights( target_entity : @ecs.Entity, weights : Array[Double], ) -> Unit { - for (entity, binding) in morphed_meshes().to_array() { + for entity, binding in morphed_meshes() { if binding.target_entity == target_entity { binding.morph_weights = weights.copy() morphed_meshes().set(entity, binding) } } - for (entity, binding) in skinned_meshes().to_array() { + for entity, binding in skinned_meshes() { if binding.target_entity == target_entity { binding.morph_weights = weights.copy() skinned_meshes().set(entity, binding) diff --git a/selene-core/src/animation/animation_blend_eval.mbt b/selene-core/src/animation/animation_blend_eval.mbt index c36fa602..8c9d707d 100644 --- a/selene-core/src/animation/animation_blend_eval.mbt +++ b/selene-core/src/animation/animation_blend_eval.mbt @@ -343,11 +343,11 @@ fn resolve_sample_value( } ///| -fn collect_targets_by_player() -> Map[ - @ecs.Entity, +fn collect_targets_by_player() -> @ecs.EntityTable[ Map[AnimationTargetId, @ecs.Entity], ] { - let targets_by_player : Map[@ecs.Entity, Map[AnimationTargetId, @ecs.Entity]] = Map([], + let targets_by_player : @ecs.EntityTable[Map[AnimationTargetId, @ecs.Entity]] = EntityTable( + @ecs.require_current_world(), ) for entity in @ecs.iter_entities() { guard entity.is_alive() else { continue } @@ -367,7 +367,9 @@ fn graph_node_duration( graph : AnimationGraph, node_index : AnimationNodeIndex, ) -> Double { - guard graph.nodes.get(node_index) is Some(node) else { return 0.0 } + guard graph.nodes.get(node_index.0.reinterpret_as_int()) is Some(node) else { + return 0.0 + } match node.node_type { Clip(handle) => animation_clip_asset(handle).map_or(0.0, fn(clip) { clip.duration }) @@ -398,7 +400,9 @@ fn evaluate_graph_node( if weight <= 0.0 { return } - guard graph.nodes.get(node_index) is Some(node) else { return } + guard graph.nodes.get(node_index.0.reinterpret_as_int()) is Some(node) else { + return + } let combined_mask = inherited_mask | node.mask match node.node_type { Blend => @@ -450,7 +454,9 @@ fn collect_clip_nodes( node_index : AnimationNodeIndex, output : Array[AnimationNodeIndex], ) -> Unit { - guard graph.nodes.get(node_index) is Some(node) else { return } + guard graph.nodes.get(node_index.0.reinterpret_as_int()) is Some(node) else { + return + } match node.node_type { Clip(_) => output.push(node_index) _ => diff --git a/selene-core/src/animation/animation_graph_ops.mbt b/selene-core/src/animation/animation_graph_ops.mbt index 9ddca3d0..3233ca0e 100644 --- a/selene-core/src/animation/animation_graph_ops.mbt +++ b/selene-core/src/animation/animation_graph_ops.mbt @@ -15,23 +15,23 @@ pub fn animated_bys() -> @ecs.ComponentStore[AnimatedBy] { ///| let skinned_meshes_key : @ecs.ResourceKey[ - Map[@ecs.Entity, SkinnedMeshBinding3D], + @ecs.EntityTable[SkinnedMeshBinding3D], ] = ResourceKey() ///| -fn skinned_meshes() -> Map[@ecs.Entity, SkinnedMeshBinding3D] { - skinned_meshes_key.get_or_insert_with(@ecs.require_current_world(), _ => { - Map([]) +fn skinned_meshes() -> @ecs.EntityTable[SkinnedMeshBinding3D] { + skinned_meshes_key.get_or_insert_with(@ecs.require_current_world(), world => { + EntityTable(world) }) } ///| -let morphed_meshes_key : @ecs.ResourceKey[Map[@ecs.Entity, MorphMeshBinding3D]] = ResourceKey() +let morphed_meshes_key : @ecs.ResourceKey[@ecs.EntityTable[MorphMeshBinding3D]] = ResourceKey() ///| -fn morphed_meshes() -> Map[@ecs.Entity, MorphMeshBinding3D] { - morphed_meshes_key.get_or_insert_with(@ecs.require_current_world(), _ => { - Map([]) +fn morphed_meshes() -> @ecs.EntityTable[MorphMeshBinding3D] { + morphed_meshes_key.get_or_insert_with(@ecs.require_current_world(), world => { + EntityTable(world) }) } @@ -59,9 +59,8 @@ pub fn AnimationClip::AnimationClip(name : String) -> AnimationClip { ///| pub fn AnimationGraph::AnimationGraph() -> AnimationGraph { let root = AnimationNodeIndex(0U) - let nodes : Map[AnimationNodeIndex, AnimationGraphNode] = Map([]) - nodes.set(root, { node_type: Blend, mask: 0U, children: [], }) - { root, nodes, mask_groups: Map([]), next_node: 1U, } + let nodes = [{ node_type: Blend, mask: 0U, children: [], }] + { root, nodes, mask_groups: Map([]), } } ///| diff --git a/selene-core/src/animation/animation_player_ops.mbt b/selene-core/src/animation/animation_player_ops.mbt index 41cbf58b..c07e5ceb 100644 --- a/selene-core/src/animation/animation_player_ops.mbt +++ b/selene-core/src/animation/animation_player_ops.mbt @@ -27,9 +27,8 @@ fn allocate_node( node_type : AnimationGraphNodeType, mask : UInt32, ) -> AnimationNodeIndex { - let node = AnimationNodeIndex(graph.next_node) - graph.next_node += 1U - graph.nodes.set(node, { node_type, mask, children: [], }) + let node = AnimationNodeIndex(graph.nodes.length().reinterpret_as_uint()) + graph.nodes.push({ node_type, mask, children: [], }) node } @@ -40,7 +39,9 @@ pub fn AnimationGraph::add_edge( child : AnimationNodeIndex, weight~ : Double = 1.0, ) -> Unit { - guard self.nodes.get(parent) is Some(node) else { return } + guard self.nodes.get(parent.0.reinterpret_as_int()) is Some(node) else { + return + } node.children.push({ child, weight, }) } @@ -156,7 +157,9 @@ pub fn AnimationGraph::set_edge_weight( child : AnimationNodeIndex, weight : Double, ) -> Unit { - guard self.nodes.get(parent) is Some(node) else { return } + guard self.nodes.get(parent.0.reinterpret_as_int()) is Some(node) else { + return + } for edge in node.children { if edge.child == child { edge.weight = weight diff --git a/selene-core/src/animation/animation_skinning.mbt b/selene-core/src/animation/animation_skinning.mbt index aa971cc9..3d41847f 100644 --- a/selene-core/src/animation/animation_skinning.mbt +++ b/selene-core/src/animation/animation_skinning.mbt @@ -10,7 +10,7 @@ pub fn animation_player_system(delta : Double) -> Unit { } guard animation_graph_asset(graph_handle) is Some(graph) else { continue } let targets = targets_by_player.get_or_init(entity, fn() { Map([]) }) - for node_index, active in player.active_animations { + for (node_index, active) in player.active_animations.to_array() { if active.paused || active.finished { continue } @@ -89,7 +89,9 @@ pub fn animation_player_system(delta : Double) -> Unit { let clip_nodes : Array[AnimationNodeIndex] = [] collect_clip_nodes(graph, node_index, clip_nodes) for clip_node in clip_nodes { - guard graph.nodes.get(clip_node) is Some(node) else { continue } + guard graph.nodes.get(clip_node.0.reinterpret_as_int()) is Some(node) else { + continue + } guard node.node_type is Clip(clip_handle) else { continue } guard animation_clip_asset(clip_handle) is Some(clip) else { continue } emit_clip_events_between( @@ -110,35 +112,35 @@ pub fn animation_player_system(delta : Double) -> Unit { ///| pub fn animation_transition_system(delta : Double) -> Unit { - for (entity, transitions) in animation_transitions().to_array() { + for entity, transitions in animation_transitions() { if !entity.is_alive() { continue } guard animation_players().get(entity) is Some(player) else { continue } let mut main_weight = 1.0 - for node_index, fade in transitions.fading { - if player.active_animations.get(node_index) is Some(active) { - if fade.total <= 0.000001 { - active.weight = 0.0 - active.finished = true - player.active_animations.remove(node_index) - transitions.fading.remove(node_index) - continue - } - fade.remaining -= delta - let ratio = @cmp.maximum(0.0, fade.remaining / fade.total) - active.weight = fade.start_weight * ratio - if ratio <= 0.0 { - active.finished = true - player.active_animations.remove(node_index) - transitions.fading.remove(node_index) - } else if 1.0 - ratio < main_weight { - main_weight = 1.0 - ratio - } - } else { - transitions.fading.remove(node_index) + transitions.fading.retain((node_index, fade) => { + guard player.active_animations.get(node_index) is Some(active) else { + return false } - } + if fade.total <= 0.000001 { + active.weight = 0.0 + active.finished = true + player.active_animations.remove(node_index) + return false + } + fade.remaining -= delta + let ratio = @cmp.maximum(0.0, fade.remaining / fade.total) + active.weight = fade.start_weight * ratio + if ratio <= 0.0 { + active.finished = true + player.active_animations.remove(node_index) + return false + } + if 1.0 - ratio < main_weight { + main_weight = 1.0 - ratio + } + true + }) if transitions.main is Some(main) && player.active_animations.get(main) is Some(active) { active.weight = if transitions.fading.is_empty() { @@ -336,11 +338,11 @@ fn update_bound_mesh( ///| pub fn animation_skinning_system(_delta : Double) -> Unit { - for (entity, binding) in morphed_meshes().to_array() { + let world = @ecs.require_current_world() + morphed_meshes().retain((entity, _) => entity.is_valid_in(world)) + skinned_meshes().retain((entity, _) => entity.is_valid_in(world)) + for entity, binding in morphed_meshes() { if !entity.is_alive() { - if !entity.is_valid_in(@ecs.require_current_world()) { - morphed_meshes().remove(entity) - } continue } let (positions, normals) = apply_morph_targets( @@ -361,11 +363,8 @@ pub fn animation_skinning_system(_delta : Double) -> Unit { ) } - for (entity, binding) in skinned_meshes().to_array() { + for entity, binding in skinned_meshes() { if !entity.is_alive() { - if !entity.is_valid_in(@ecs.require_current_world()) { - skinned_meshes().remove(entity) - } continue } if binding.base_positions.length() != binding.influences.length() { diff --git a/selene-core/src/animation/animation_types.mbt b/selene-core/src/animation/animation_types.mbt index 6f355aae..16bea4f8 100644 --- a/selene-core/src/animation/animation_types.mbt +++ b/selene-core/src/animation/animation_types.mbt @@ -261,9 +261,8 @@ pub(all) struct AnimationGraphNode { ///| pub(all) struct AnimationGraph { root : AnimationNodeIndex - nodes : Map[AnimationNodeIndex, AnimationGraphNode] + nodes : Array[AnimationGraphNode] mask_groups : Map[AnimationTargetId, UInt32] - mut next_node : UInt32 } ///| diff --git a/selene-core/src/animation/animation_wbtest.mbt b/selene-core/src/animation/animation_wbtest.mbt index 607e443d..e91645c4 100644 --- a/selene-core/src/animation/animation_wbtest.mbt +++ b/selene-core/src/animation/animation_wbtest.mbt @@ -410,3 +410,27 @@ test "skinning blends four affine joints and ignores inactive influences" { assert_true(deformed.positions[0].distance(expected) < 1.0e-12) }) } + +///| +test "multiple animation fades are removed in one transition update" { + with_animation_test_world(fn() raise { + let player = AnimationPlayer() + let transitions = AnimationTransitions() + for index in 1..<=4 { + ignore( + transitions.play( + player, + AnimationNodeIndex(index.reinterpret_as_uint()), + 0.1, + ), + ) + } + ignore(@ecs.require_current_world().spawn((player, transitions))) + animation_transition_system(0.2) + assert_eq(player.playing_animations().length(), 1) + let main = transitions.get_main_animation().unwrap() + assert_true(player.is_playing_animation(main)) + assert_eq(player.animation(main).unwrap().weight(), 1.0) + assert_true(transitions.fading.is_empty()) + }) +} diff --git a/selene-core/src/animation/pkg.generated.mbti b/selene-core/src/animation/pkg.generated.mbti index 31feb0c4..827ff714 100644 --- a/selene-core/src/animation/pkg.generated.mbti +++ b/selene-core/src/animation/pkg.generated.mbti @@ -201,9 +201,8 @@ pub fn AnimationEventDescriptorHandle::to_repr(Self) -> @debug.Repr pub(all) struct AnimationGraph { root : AnimationNodeIndex - nodes : Map[AnimationNodeIndex, AnimationGraphNode] + nodes : Array[AnimationGraphNode] mask_groups : Map[AnimationTargetId, UInt32] - mut next_node : UInt32 } pub fn AnimationGraph::AnimationGraph() -> Self pub fn AnimationGraph::add_additive_blend(Self, parent? : AnimationNodeIndex, weight? : Double) -> AnimationNodeIndex diff --git a/selene-core/src/app/scheduler.mbt b/selene-core/src/app/scheduler.mbt index 1d2a0ec9..8f47333e 100644 --- a/selene-core/src/app/scheduler.mbt +++ b/selene-core/src/app/scheduler.mbt @@ -155,7 +155,7 @@ fn sort_systems_by_set( let processed : @set.Set[String] = Set([]) let sorted_keys : Array[String] = [] - while processed.to_array().length() < group_keys.length() { + while processed.length() < group_keys.length() { let mut progressed = false for key in sorted_candidates { if processed.contains(key) { diff --git a/selene-core/src/audio/deletion_wbtest.mbt b/selene-core/src/audio/deletion_wbtest.mbt index c400184e..70971725 100644 --- a/selene-core/src/audio/deletion_wbtest.mbt +++ b/selene-core/src/audio/deletion_wbtest.mbt @@ -42,3 +42,27 @@ test "audio cleanup stops deleted loops only in the active World" { assert_eq(stopped.length(), 2) assert_true(audio_sinks().is_empty()) } + +///| +test "audio cleanup retains old loop handles when the entity slot is reused" { + let previous = @ecs.current_world() + defer (match previous { + Some(world) => @ecs.set_current_world(world) + None => @ecs.clear_current_world() + }) + let world = @ecs.World() + @ecs.set_current_world(world) + let clip = @asset.load_audio("audio-slot-reuse-test.ogg") + let old = spawn_audio(clip, settings=PlaybackSettings::looped()) + audio_playback_system(0.0) + ignore(old.delete()) + let replacement = spawn_audio(clip, settings=PlaybackSettings::looped()) + assert_eq(old.slot_index(), replacement.slot_index()) + assert_true(audio_sinks().get(replacement) is None) + let stopped = [] + cleanup_orphaned_audio(instance => stopped.push(instance)) + assert_eq(stopped.length(), 1) + audio_playback_system(0.0) + assert_false(audio_sinks().contains(old)) + assert_true(audio_sinks().contains(replacement)) +} diff --git a/selene-core/src/audio/pkg.generated.mbti b/selene-core/src/audio/pkg.generated.mbti index fc8b32cb..49549853 100644 --- a/selene-core/src/audio/pkg.generated.mbti +++ b/selene-core/src/audio/pkg.generated.mbti @@ -22,7 +22,7 @@ pub fn audio_playback_system(Double) -> Unit pub fn audio_players() -> @ecs.ComponentStore[AudioPlayer] -pub fn audio_sinks() -> Map[@ecs.Entity, AudioSink] +pub fn audio_sinks() -> @ecs.EntityTable[AudioSink] pub fn global_volume() -> Double diff --git a/selene-core/src/audio/playback.mbt b/selene-core/src/audio/playback.mbt index 42399585..0b00f955 100644 --- a/selene-core/src/audio/playback.mbt +++ b/selene-core/src/audio/playback.mbt @@ -13,7 +13,7 @@ // limitations under the License. ///| -pub fn audio_sinks() -> Map[@ecs.Entity, AudioSink] { +pub fn audio_sinks() -> @ecs.EntityTable[AudioSink] { audio_runtime().sinks } @@ -34,8 +34,8 @@ priv enum AudioOverride { ///| priv struct AudioRuntime { - sinks : Map[@ecs.Entity, AudioSink] - overrides : Map[@ecs.Entity, AudioOverride] + sinks : @ecs.EntityTable[AudioSink] + overrides : @ecs.EntityTable[AudioOverride] } ///| @@ -43,9 +43,9 @@ let audio_runtime_key : @ecs.ResourceKey[AudioRuntime] = ResourceKey() ///| fn audio_runtime() -> AudioRuntime { - audio_runtime_key.get_or_insert_with(@ecs.require_current_world(), _ => { - sinks: {}, - overrides: {}, + audio_runtime_key.get_or_insert_with(@ecs.require_current_world(), world => { + sinks: EntityTable(world), + overrides: EntityTable(world), }) } @@ -199,7 +199,7 @@ pub fn audio_playback_system(_delta : Double) -> Unit { audio_playback_settings().get(entity).unwrap_or(PlaybackSettings::once()), ) } - for (entity, playback) in runtime.overrides.to_array() { + for entity, playback in runtime.overrides { if entity.is_alive() && playback is Attached(player, settings) { update_audio_playback(entity, player, settings) } diff --git a/selene-core/src/autotile2d/moon.pkg b/selene-core/src/autotile2d/moon.pkg index 01eb5a23..3c8c4ac1 100644 --- a/selene-core/src/autotile2d/moon.pkg +++ b/selene-core/src/autotile2d/moon.pkg @@ -6,7 +6,6 @@ import { "Milky2018/selene/sprite", "Milky2018/selene/transform", "moonbitlang/core/json", - "moonbitlang/core/string", } supported_targets = "all" diff --git a/selene-core/src/autotile2d/pkg.generated.mbti b/selene-core/src/autotile2d/pkg.generated.mbti index 71bfa443..1c491c1d 100644 --- a/selene-core/src/autotile2d/pkg.generated.mbti +++ b/selene-core/src/autotile2d/pkg.generated.mbti @@ -59,7 +59,7 @@ pub fn AutoTileDiff::not_equal(Self, Self) -> Bool pub fn AutoTileDiff::to_json(Self) -> @json.Json pub fn AutoTileDiff::to_repr(Self) -> @debug.Repr -#derive(Eq, @debug.Debug, @json.FromJson, @json.ToJson) +#derive(Eq, Hash, @debug.Debug, @json.FromJson, @json.ToJson) pub struct AutoTileGridPos { x : Int32 y : Int32 @@ -67,6 +67,8 @@ pub struct AutoTileGridPos { pub fn AutoTileGridPos::AutoTileGridPos(Int32, Int32) -> Self pub fn AutoTileGridPos::equal(Self, Self) -> Bool pub fn AutoTileGridPos::from_json(@json.Json, @json.JsonPath) -> Self raise @json.JsonDecodeError +pub fn AutoTileGridPos::hash(Self) -> Int32 +pub fn AutoTileGridPos::hash_combine(Self, Hasher) -> Unit pub fn AutoTileGridPos::not_equal(Self, Self) -> Bool pub fn AutoTileGridPos::to_json(Self) -> @json.Json pub fn AutoTileGridPos::to_repr(Self) -> @debug.Repr diff --git a/selene-core/src/autotile2d/rules.mbt b/selene-core/src/autotile2d/rules.mbt index 9d577cfc..dbc37a24 100644 --- a/selene-core/src/autotile2d/rules.mbt +++ b/selene-core/src/autotile2d/rules.mbt @@ -250,7 +250,7 @@ pub fn AutoTileSolvedTile::AutoTileSolvedTile( } ///| -#derive(Debug, Eq, ToJson, FromJson) +#derive(Debug, Eq, Hash, ToJson, FromJson) pub struct AutoTileGridPos { x : Int32 y : Int32 @@ -304,3 +304,6 @@ pub fn AutoTileDiff::AutoTileDiff( ) -> AutoTileDiff { { source, changed_tiles, removed_tiles, } } + +///| +pub extend AutoTileGridPos with Hash::{hash, hash_combine} diff --git a/selene-core/src/autotile2d/runtime.mbt b/selene-core/src/autotile2d/runtime.mbt index 3a113c3e..5652e06e 100644 --- a/selene-core/src/autotile2d/runtime.mbt +++ b/selene-core/src/autotile2d/runtime.mbt @@ -36,17 +36,17 @@ pub fn AutoTileRuntimeContext::AutoTileRuntimeContext( ///| priv struct RuntimeLayerState { source : AutoTileLayerSource - tile_entities : Map[String, @ecs.Entity] + tile_entities : Map[AutoTileGridPos, @ecs.Entity] context : AutoTileRuntimeContext } ///| -let runtime_layers_key : @ecs.ResourceKey[Map[@ecs.Entity, RuntimeLayerState]] = ResourceKey() +let runtime_layers_key : @ecs.ResourceKey[@ecs.EntityTable[RuntimeLayerState]] = ResourceKey() ///| -fn runtime_layers() -> Map[@ecs.Entity, RuntimeLayerState] { +fn runtime_layers() -> @ecs.EntityTable[RuntimeLayerState] { let world = @ecs.require_current_world() - runtime_layers_key.get_or_insert_with(world, _ => Map([])) + runtime_layers_key.get_or_insert_with(world, world => EntityTable(world)) } ///| @@ -113,7 +113,7 @@ pub fn register_runtime_layer( let state : RuntimeLayerState = { source, tile_entities: Map([]), context, } let plan : @ecs.SpawnPlan[(@transform.Spatial, @sprite.Sprite)] = @ecs.require_current_world().prepare_spawn() for solved in solve_autotile_layer(source) { - let key = cell_key(solved.x, solved.y) + let key = AutoTileGridPos::{ x: solved.x, y: solved.y, } if apply_tile_visual(plan, layer_entity, source, solved, context) is Some(tile_entity) { state.tile_entities.set(key, tile_entity) @@ -128,12 +128,12 @@ fn apply_diff_to_runtime( state : RuntimeLayerState, diff : AutoTileDiff, ) -> RuntimeLayerState { - let tile_entities : Map[String, @ecs.Entity] = Map([]) + let tile_entities : Map[AutoTileGridPos, @ecs.Entity] = Map([]) for key, value in state.tile_entities { tile_entities.set(key, value) } for removed in diff.removed_tiles { - let key = cell_key(removed.x, removed.y) + let key = AutoTileGridPos::{ x: removed.x, y: removed.y, } if tile_entities.get(key) is Some(entity_) { ignore(entity_.delete()) ignore(tile_entities.remove(key)) @@ -141,7 +141,7 @@ fn apply_diff_to_runtime( } let plan : @ecs.SpawnPlan[(@transform.Spatial, @sprite.Sprite)] = @ecs.require_current_world().prepare_spawn() for changed in diff.changed_tiles { - let key = cell_key(changed.x, changed.y) + let key = AutoTileGridPos::{ x: changed.x, y: changed.y, } if tile_entities.get(key) is Some(entity_) { ignore(entity_.delete()) ignore(tile_entities.remove(key)) diff --git a/selene-core/src/autotile2d/solver.mbt b/selene-core/src/autotile2d/solver.mbt index 629155a8..a449c1bd 100644 --- a/selene-core/src/autotile2d/solver.mbt +++ b/selene-core/src/autotile2d/solver.mbt @@ -1,27 +1,15 @@ ///| -fn cell_key(x : Int32, y : Int32) -> String { - x.to_string() + "," + y.to_string() -} - -///| -fn pos_of_key(key : String) -> AutoTileGridPos { - let comma = key.find(",").unwrap_or(-1) - if comma <= 0 || comma + 1 >= key.length() { - return { x: 0, y: 0, } - } - let x = @string.parse_int(key[:comma], base=10) catch { _ => 0 } - let y = @string.parse_int(key[comma + 1:], base=10) catch { _ => 0 } - { x, y, } -} - -///| -fn neighbor_terrain(cells : Map[String, Int32], x : Int32, y : Int32) -> Int32? { - cells.get(cell_key(x, y)) +fn neighbor_terrain( + cells : Map[AutoTileGridPos, Int32], + x : Int32, + y : Int32, +) -> Int32? { + cells.get({ x, y, }) } ///| fn bitmask4( - cells : Map[String, Int32], + cells : Map[AutoTileGridPos, Int32], x : Int32, y : Int32, terrain : Int32, @@ -38,7 +26,7 @@ fn bitmask4( ///| fn bitmask8( - cells : Map[String, Int32], + cells : Map[AutoTileGridPos, Int32], x : Int32, y : Int32, terrain : Int32, @@ -71,7 +59,7 @@ fn bitmask8( ///| fn wang_key( - cells : Map[String, Int32], + cells : Map[AutoTileGridPos, Int32], x : Int32, y : Int32, ) -> AutoTileWangRule { @@ -101,7 +89,7 @@ fn palette_for_terrain( ///| fn solved_tile_for( source : AutoTileLayerSource, - cells : Map[String, Int32], + cells : Map[AutoTileGridPos, Int32], x : Int32, y : Int32, terrain : Int32, @@ -164,38 +152,37 @@ fn solved_tile_for( } ///| -fn sorted_cell_keys(cells : Map[String, Int32]) -> Array[String] { - let keys : Array[String] = [] +fn sorted_cell_keys( + cells : Map[AutoTileGridPos, Int32], +) -> Array[AutoTileGridPos] { + let keys : Array[AutoTileGridPos] = [] for key, _ in cells { keys.push(key) } keys.sort_by(fn(left, right) { - let l = pos_of_key(left) - let r = pos_of_key(right) - if l.y == r.y { - l.x.compare(r.x) + if left.y == right.y { + left.x.compare(right.x) } else { - l.y.compare(r.y) + left.y.compare(right.y) } }) keys } ///| -fn cells_map_of(source : AutoTileLayerSource) -> Map[String, Int32] { - let cells : Map[String, Int32] = Map([]) +fn cells_map_of(source : AutoTileLayerSource) -> Map[AutoTileGridPos, Int32] { + let cells : Map[AutoTileGridPos, Int32] = Map([]) for cell in source.cells { - cells.set(cell_key(cell.x, cell.y), cell.terrain) + cells.set({ x: cell.x, y: cell.y, }, cell.terrain) } cells } ///| -fn cells_array_of(map : Map[String, Int32]) -> Array[AutoTileCell] { +fn cells_array_of(map : Map[AutoTileGridPos, Int32]) -> Array[AutoTileCell] { let cells : Array[AutoTileCell] = [] - for key in sorted_cell_keys(map) { - let pos = pos_of_key(key) - let terrain = map.get(key).unwrap_or(0) + for pos in sorted_cell_keys(map) { + let terrain = map.get(pos).unwrap_or(0) cells.push({ x: pos.x, y: pos.y, terrain, }) } cells @@ -204,12 +191,11 @@ fn cells_array_of(map : Map[String, Int32]) -> Array[AutoTileCell] { ///| fn solve_from_cells( source : AutoTileLayerSource, - cells : Map[String, Int32], + cells : Map[AutoTileGridPos, Int32], ) -> Array[AutoTileSolvedTile] { let solved : Array[AutoTileSolvedTile] = [] - for key in sorted_cell_keys(cells) { - let pos = pos_of_key(key) - let terrain = cells.get(key).unwrap_or(0) + for pos in sorted_cell_keys(cells) { + let terrain = cells.get(pos).unwrap_or(0) solved.push(solved_tile_for(source, cells, pos.x, pos.y, terrain)) } solved @@ -223,11 +209,11 @@ pub fn solve_autotile_layer( } ///| -fn affected_keys(x : Int32, y : Int32) -> Array[String] { - let keys : Array[String] = [] +fn affected_keys(x : Int32, y : Int32) -> Array[AutoTileGridPos] { + let keys : Array[AutoTileGridPos] = [] for dy in -1..<=1 { for dx in -1..<=1 { - keys.push(cell_key(x + dx, y + dy)) + keys.push({ x: x + dx, y: y + dy, }) } } keys @@ -236,15 +222,14 @@ fn affected_keys(x : Int32, y : Int32) -> Array[String] { ///| fn solved_map_of( source : AutoTileLayerSource, - cells : Map[String, Int32], - keys : Array[String], -) -> Map[String, AutoTileSolvedTile] { - let solved : Map[String, AutoTileSolvedTile] = Map([]) + cells : Map[AutoTileGridPos, Int32], + keys : Array[AutoTileGridPos], +) -> Map[AutoTileGridPos, AutoTileSolvedTile] { + let solved : Map[AutoTileGridPos, AutoTileSolvedTile] = Map([]) for key in keys { if cells.contains(key) { - let pos = pos_of_key(key) let terrain = cells.get(key).unwrap_or(0) - solved.set(key, solved_tile_for(source, cells, pos.x, pos.y, terrain)) + solved.set(key, solved_tile_for(source, cells, key.x, key.y, terrain)) } } solved @@ -280,11 +265,11 @@ pub fn update_cell_and_resolve_diff( terrain : Int32?, ) -> AutoTileDiff { let before_cells = cells_map_of(source) - let after_cells : Map[String, Int32] = Map([]) + let after_cells : Map[AutoTileGridPos, Int32] = Map([]) for key, value in before_cells { after_cells.set(key, value) } - let target_key = cell_key(x, y) + let target_key = AutoTileGridPos::{ x, y, } match terrain { Some(value) => after_cells.set(target_key, value) None => ignore(after_cells.remove(target_key)) @@ -302,7 +287,7 @@ pub fn update_cell_and_resolve_diff( Some(left) => match after { Some(right) => if left != right { changed.push(right) } - None => removed.push(pos_of_key(key)) + None => removed.push(key) } None => match after { diff --git a/selene-core/src/camera3d/camera.mbt b/selene-core/src/camera3d/camera.mbt index 06323bcb..e3510525 100644 --- a/selene-core/src/camera3d/camera.mbt +++ b/selene-core/src/camera3d/camera.mbt @@ -51,21 +51,16 @@ pub fn cameras3d() -> @ecs.ComponentStore[Camera3DComponent] { } ///| -let active_cameras3d_by_world : Map[UInt32, ActiveCamera3D?] = Map([]) - -///| -fn current_world_id() -> UInt32 { - @ecs.require_current_world().id() -} +let active_camera3d_key : @ecs.ResourceKey[ActiveCamera3D?] = ResourceKey() ///| pub fn get_active_camera3d() -> ActiveCamera3D? { - active_cameras3d_by_world.get(current_world_id()).unwrap_or(None) + active_camera3d_key.get_in(@ecs.require_current_world()).unwrap_or(None) } ///| pub fn set_active_camera3d(camera : ActiveCamera3D?) -> Unit { - active_cameras3d_by_world.set(current_world_id(), camera) + active_camera3d_key.insert_in(@ecs.require_current_world(), camera) } ///| diff --git a/selene-core/src/collision/collider.mbt b/selene-core/src/collision/collider.mbt index 93c90ef4..f27389ed 100644 --- a/selene-core/src/collision/collider.mbt +++ b/selene-core/src/collision/collider.mbt @@ -43,7 +43,7 @@ pub fn Collider::with_material( ///| priv struct ColliderWorldStore { - resolved_velocities : Map[@ecs.Entity, @velocity.Velocity] + resolved_velocities : @ecs.EntityTable[@velocity.Velocity] grounded_entities : Set[@ecs.Entity] } @@ -51,14 +51,16 @@ priv struct ColliderWorldStore { let collider_world_store_key : @ecs.ResourceKey[ColliderWorldStore] = ResourceKey() ///| -fn ColliderWorldStore::ColliderWorldStore() -> ColliderWorldStore { - { resolved_velocities: {}, grounded_entities: Set([]), } +fn ColliderWorldStore::ColliderWorldStore( + world : @ecs.World, +) -> ColliderWorldStore { + { resolved_velocities: EntityTable(world), grounded_entities: Set([]), } } ///| fn collider_world_store() -> ColliderWorldStore { - collider_world_store_key.get_or_insert_with(@ecs.require_current_world(), _ => { - ColliderWorldStore() + collider_world_store_key.get_or_insert_with(@ecs.require_current_world(), world => { + ColliderWorldStore(world) }) } @@ -83,7 +85,7 @@ pub let contact_event_bus : @event.Events[ContactEvent] = Events() ///| /// Effective post-solve velocities from the latest fixed step. -pub fn resolved_velocities() -> Map[@ecs.Entity, @velocity.Velocity] { +fn resolved_velocities() -> @ecs.EntityTable[@velocity.Velocity] { collider_world_store().resolved_velocities } @@ -112,3 +114,9 @@ fn set_grounded(entity : @ecs.Entity, grounded : Bool) -> Unit { grounded_entities.remove(entity) } } + +///| +/// Effective velocity produced by the latest fixed step. +pub fn resolved_velocity(entity : @ecs.Entity) -> @velocity.Velocity? { + resolved_velocities().get(entity) +} diff --git a/selene-core/src/collision/component_test.mbt b/selene-core/src/collision/component_wbtest.mbt similarity index 63% rename from selene-core/src/collision/component_test.mbt rename to selene-core/src/collision/component_wbtest.mbt index 9dc518e0..f36b3a15 100644 --- a/selene-core/src/collision/component_test.mbt +++ b/selene-core/src/collision/component_wbtest.mbt @@ -1,5 +1,5 @@ ///| -test "input velocity and resolved velocity use distinct component stores" { +test "input velocity and resolved velocity use distinct runtime storage" { let world = @ecs.World() let input : @ecs.ComponentStore[@velocity.Velocity] = @ecs.components_in( world, @@ -8,8 +8,8 @@ test "input velocity and resolved velocity use distinct component stores" { let resolved = Ref(None) @ecs.run_schedule(world, _ => { - @collision.resolved_velocities().set(entity, Vec2(1.0, 0.0)) - resolved.val = @collision.resolved_velocities().get(entity) + resolved_velocities().set(entity, Vec2(1.0, 0.0)) + resolved.val = resolved_velocity(entity) }) assert_eq(input.get(entity), Some(Vec2(2.0, 0.0))) diff --git a/selene-core/src/collision/pkg.generated.mbti b/selene-core/src/collision/pkg.generated.mbti index 82a5d6e3..8f335c0b 100644 --- a/selene-core/src/collision/pkg.generated.mbti +++ b/selene-core/src/collision/pkg.generated.mbti @@ -75,7 +75,7 @@ pub fn reset_forces(@ecs.Entity, wake_up? : Bool) -> Unit pub fn reset_torques(@ecs.Entity, wake_up? : Bool) -> Unit -pub fn resolved_velocities() -> Map[@ecs.Entity, @velocity.Velocity] +pub fn resolved_velocity(@ecs.Entity) -> @velocity.Velocity? pub fn rigid_bodies() -> @ecs.ComponentStore[RigidBody] diff --git a/selene-core/src/collision/rapier2d_api.mbt b/selene-core/src/collision/rapier2d_api.mbt index d33978a2..63174772 100644 --- a/selene-core/src/collision/rapier2d_api.mbt +++ b/selene-core/src/collision/rapier2d_api.mbt @@ -1,23 +1,22 @@ ///| -fn pending_body_torques() -> Map[@ecs.Entity, Double] { +fn pending_body_torques() -> @ecs.EntityTable[Double] { physics_world_runtime().pending_body_torques } ///| -fn pending_body_impulses() -> Map[@ecs.Entity, @math.Vec2] { +fn pending_body_impulses() -> @ecs.EntityTable[@math.Vec2] { physics_world_runtime().pending_body_impulses } ///| -fn pending_body_impulse_points() -> Map[ - @ecs.Entity, +fn pending_body_impulse_points() -> @ecs.EntityTable[ Array[(@math.Vec2, @math.Vec2)], ] { physics_world_runtime().pending_body_impulse_points } ///| -fn pending_body_torque_impulses() -> Map[@ecs.Entity, Double] { +fn pending_body_torque_impulses() -> @ecs.EntityTable[Double] { physics_world_runtime().pending_body_torque_impulses } @@ -30,7 +29,7 @@ priv struct EntityJointConfigKey { } ///| -fn entity_joint_config_keys() -> Map[@ecs.Entity, EntityJointConfigKey] { +fn entity_joint_config_keys() -> @ecs.EntityTable[EntityJointConfigKey] { physics_world_runtime().entity_joint_config_keys } @@ -43,8 +42,7 @@ priv struct EntityMultibodyJointConfigKey { } ///| -fn entity_multibody_joint_config_keys() -> Map[ - @ecs.Entity, +fn entity_multibody_joint_config_keys() -> @ecs.EntityTable[ EntityMultibodyJointConfigKey, ] { physics_world_runtime().entity_multibody_joint_config_keys diff --git a/selene-core/src/collision/rapier2d_events.mbt b/selene-core/src/collision/rapier2d_events.mbt index 672942e5..4b14383e 100644 --- a/selene-core/src/collision/rapier2d_events.mbt +++ b/selene-core/src/collision/rapier2d_events.mbt @@ -37,51 +37,33 @@ fn apply_pending_body_actions(entity : @ecs.Entity) -> Unit { ///| fn prune_pending_body_state() -> Unit { - for (entity, _) in pending_body_rotations().to_array() { - if !entity.is_alive() || !world_entity(entity) { - pending_body_rotations().remove(entity) - } - } - for (entity, _) in pending_body_linear_velocities().to_array() { - if !entity.is_alive() || !world_entity(entity) { - pending_body_linear_velocities().remove(entity) - } - } - for (entity, _) in pending_body_angular_velocities().to_array() { - if !entity.is_alive() || !world_entity(entity) { - pending_body_angular_velocities().remove(entity) - } - } - for (entity, _) in pending_body_forces().to_array() { - if !entity.is_alive() || !world_entity(entity) { - pending_body_forces().remove(entity) - } - } - for (entity, _) in pending_body_force_points().to_array() { - if !entity.is_alive() || !world_entity(entity) { - pending_body_force_points().remove(entity) - } - } - for (entity, _) in pending_body_torques().to_array() { - if !entity.is_alive() || !world_entity(entity) { - pending_body_torques().remove(entity) - } - } - for (entity, _) in pending_body_impulses().to_array() { - if !entity.is_alive() || !world_entity(entity) { - pending_body_impulses().remove(entity) - } - } - for (entity, _) in pending_body_impulse_points().to_array() { - if !entity.is_alive() || !world_entity(entity) { - pending_body_impulse_points().remove(entity) - } - } - for (entity, _) in pending_body_torque_impulses().to_array() { - if !entity.is_alive() || !world_entity(entity) { - pending_body_torque_impulses().remove(entity) - } - } + pending_body_rotations().retain((entity, _) => { + entity.is_alive() && world_entity(entity) + }) + pending_body_linear_velocities().retain((entity, _) => { + entity.is_alive() && world_entity(entity) + }) + pending_body_angular_velocities().retain((entity, _) => { + entity.is_alive() && world_entity(entity) + }) + pending_body_forces().retain((entity, _) => { + entity.is_alive() && world_entity(entity) + }) + pending_body_force_points().retain((entity, _) => { + entity.is_alive() && world_entity(entity) + }) + pending_body_torques().retain((entity, _) => { + entity.is_alive() && world_entity(entity) + }) + pending_body_impulses().retain((entity, _) => { + entity.is_alive() && world_entity(entity) + }) + pending_body_impulse_points().retain((entity, _) => { + entity.is_alive() && world_entity(entity) + }) + pending_body_torque_impulses().retain((entity, _) => { + entity.is_alive() && world_entity(entity) + }) } ///| @@ -369,10 +351,16 @@ fn remove_multibody_joint_physics(entity : @ecs.Entity) -> Unit { ///| fn sync_world_joints() -> Unit { - for (entity, handle) in world().entity_joints.to_array() { - if !should_have_joint(entity) || !world().impulse_joints.contains(handle) { - remove_joint_physics(entity) - } + let stale = world().entity_joints + .iter() + .filter(pair => { + let (entity, handle) = pair + !should_have_joint(entity) || !world().impulse_joints.contains(handle) + }) + .map(pair => pair.0) + .collect() + for entity in stale { + remove_joint_physics(entity) } for entity in @ecs.iter_entities() { @@ -404,11 +392,17 @@ fn sync_world_joints() -> Unit { ///| fn sync_world_multibody_joints() -> Unit { - for (entity, handle) in world().entity_multibody_joints.to_array() { - if !should_have_multibody_joint(entity) || - world().multibody_joints.get(handle) is None { - remove_multibody_joint_physics(entity) - } + let stale = world().entity_multibody_joints + .iter() + .filter(pair => { + let (entity, handle) = pair + !should_have_multibody_joint(entity) || + world().multibody_joints.get(handle) is None + }) + .map(pair => pair.0) + .collect() + for entity in stale { + remove_multibody_joint_physics(entity) } for entity in @ecs.iter_entities() { diff --git a/selene-core/src/collision/rapier2d_runtime.mbt b/selene-core/src/collision/rapier2d_runtime.mbt index ea8fa4cd..11cce563 100644 --- a/selene-core/src/collision/rapier2d_runtime.mbt +++ b/selene-core/src/collision/rapier2d_runtime.mbt @@ -59,43 +59,40 @@ priv struct PhysicsWorld { multibody_joints : @rapier_dynamics.MultibodyJointSet ccd_solver : @rapier_dynamics_ccd.CCDSolver event_handler : @rapier_pipeline.EventHandler - entity_bodies : Map[@ecs.Entity, @rapier_dynamics.RigidBodyHandle] - entity_colliders : Map[@ecs.Entity, @rapier_collision.ColliderHandle] - collider_entities : Map[Int32, @ecs.Entity] - entity_joints : Map[@ecs.Entity, JointHandle] - entity_multibody_joints : Map[@ecs.Entity, MultibodyJointHandle] + entity_bodies : @ecs.EntityTable[@rapier_dynamics.RigidBodyHandle] + entity_colliders : @ecs.EntityTable[@rapier_collision.ColliderHandle] + collider_entities : Map[(Int32, Int32), @ecs.Entity] + entity_joints : @ecs.EntityTable[JointHandle] + entity_multibody_joints : @ecs.EntityTable[MultibodyJointHandle] } ///| priv struct PhysicsWorldRuntime { world : PhysicsWorld - entity_physics_config_keys : Map[@ecs.Entity, EntityPhysicsConfigKey] - pending_body_rotations : Map[@ecs.Entity, Double] - pending_body_linear_velocities : Map[@ecs.Entity, @math.Vec2] - pending_body_angular_velocities : Map[@ecs.Entity, Double] - pending_body_forces : Map[@ecs.Entity, @math.Vec2] - pending_body_force_points : Map[@ecs.Entity, Array[(@math.Vec2, @math.Vec2)]] - pending_body_torques : Map[@ecs.Entity, Double] - pending_body_impulses : Map[@ecs.Entity, @math.Vec2] - pending_body_impulse_points : Map[ - @ecs.Entity, + entity_physics_config_keys : @ecs.EntityTable[EntityPhysicsConfigKey] + pending_body_rotations : @ecs.EntityTable[Double] + pending_body_linear_velocities : @ecs.EntityTable[@math.Vec2] + pending_body_angular_velocities : @ecs.EntityTable[Double] + pending_body_forces : @ecs.EntityTable[@math.Vec2] + pending_body_force_points : @ecs.EntityTable[Array[(@math.Vec2, @math.Vec2)]] + pending_body_torques : @ecs.EntityTable[Double] + pending_body_impulses : @ecs.EntityTable[@math.Vec2] + pending_body_impulse_points : @ecs.EntityTable[ Array[(@math.Vec2, @math.Vec2)], ] - pending_body_torque_impulses : Map[@ecs.Entity, Double] - entity_joint_config_keys : Map[@ecs.Entity, EntityJointConfigKey] - entity_multibody_joint_config_keys : Map[ - @ecs.Entity, + pending_body_torque_impulses : @ecs.EntityTable[Double] + entity_joint_config_keys : @ecs.EntityTable[EntityJointConfigKey] + entity_multibody_joint_config_keys : @ecs.EntityTable[ EntityMultibodyJointConfigKey, ] } ///| -let physics_world_runtimes : Map[UInt32, PhysicsWorldRuntime] = Map([]) +let physics_runtime_key : @ecs.ResourceKey[PhysicsWorldRuntime] = ResourceKey() ///| fn physics_world_runtime() -> PhysicsWorldRuntime { - let world_id = @ecs.require_current_world().id() - physics_world_runtimes.get_or_init(world_id, () => { + physics_runtime_key.get_or_insert_with(@ecs.require_current_world(), world => { world: { pipeline: PhysicsPipeline(), integration: @rapier_dynamics.IntegrationParameters::default(), @@ -108,24 +105,24 @@ fn physics_world_runtime() -> PhysicsWorldRuntime { multibody_joints: MultibodyJointSet(), ccd_solver: CCDSolver(), event_handler: EventHandler(), - entity_bodies: Map([]), - entity_colliders: Map([]), + entity_bodies: EntityTable(world), + entity_colliders: EntityTable(world), collider_entities: Map([]), - entity_joints: Map([]), - entity_multibody_joints: Map([]), + entity_joints: EntityTable(world), + entity_multibody_joints: EntityTable(world), }, - entity_physics_config_keys: Map([]), - pending_body_rotations: Map([]), - pending_body_linear_velocities: Map([]), - pending_body_angular_velocities: Map([]), - pending_body_forces: Map([]), - pending_body_force_points: Map([]), - pending_body_torques: Map([]), - pending_body_impulses: Map([]), - pending_body_impulse_points: Map([]), - pending_body_torque_impulses: Map([]), - entity_joint_config_keys: Map([]), - entity_multibody_joint_config_keys: Map([]), + entity_physics_config_keys: EntityTable(world), + pending_body_rotations: EntityTable(world), + pending_body_linear_velocities: EntityTable(world), + pending_body_angular_velocities: EntityTable(world), + pending_body_forces: EntityTable(world), + pending_body_force_points: EntityTable(world), + pending_body_torques: EntityTable(world), + pending_body_impulses: EntityTable(world), + pending_body_impulse_points: EntityTable(world), + pending_body_torque_impulses: EntityTable(world), + entity_joint_config_keys: EntityTable(world), + entity_multibody_joint_config_keys: EntityTable(world), }) } @@ -168,33 +165,32 @@ priv struct EntityPhysicsConfigKey { } ///| -fn entity_physics_config_keys() -> Map[@ecs.Entity, EntityPhysicsConfigKey] { +fn entity_physics_config_keys() -> @ecs.EntityTable[EntityPhysicsConfigKey] { physics_world_runtime().entity_physics_config_keys } ///| -fn pending_body_rotations() -> Map[@ecs.Entity, Double] { +fn pending_body_rotations() -> @ecs.EntityTable[Double] { physics_world_runtime().pending_body_rotations } ///| -fn pending_body_linear_velocities() -> Map[@ecs.Entity, @math.Vec2] { +fn pending_body_linear_velocities() -> @ecs.EntityTable[@math.Vec2] { physics_world_runtime().pending_body_linear_velocities } ///| -fn pending_body_angular_velocities() -> Map[@ecs.Entity, Double] { +fn pending_body_angular_velocities() -> @ecs.EntityTable[Double] { physics_world_runtime().pending_body_angular_velocities } ///| -fn pending_body_forces() -> Map[@ecs.Entity, @math.Vec2] { +fn pending_body_forces() -> @ecs.EntityTable[@math.Vec2] { physics_world_runtime().pending_body_forces } ///| -fn pending_body_force_points() -> Map[ - @ecs.Entity, +fn pending_body_force_points() -> @ecs.EntityTable[ Array[(@math.Vec2, @math.Vec2)], ] { physics_world_runtime().pending_body_force_points diff --git a/selene-core/src/collision/rapier2d_shapes.mbt b/selene-core/src/collision/rapier2d_shapes.mbt index 595ac82b..a60a6cd1 100644 --- a/selene-core/src/collision/rapier2d_shapes.mbt +++ b/selene-core/src/collision/rapier2d_shapes.mbt @@ -76,9 +76,10 @@ fn vec2_length_squared(value : @math.Vec2) -> Double { } ///| -fn collider_handle_id(handle : @rapier_collision.ColliderHandle) -> Int32 { - let (id, _generation) = handle.into_raw_parts() - id +fn collider_handle_key( + handle : @rapier_collision.ColliderHandle, +) -> (Int32, Int32) { + handle.into_raw_parts() } ///| diff --git a/selene-core/src/collision/rapier2d_step.mbt b/selene-core/src/collision/rapier2d_step.mbt index 727161d5..95d48b2a 100644 --- a/selene-core/src/collision/rapier2d_step.mbt +++ b/selene-core/src/collision/rapier2d_step.mbt @@ -9,7 +9,7 @@ fn remove_entity_physics(entity : @ecs.Entity) -> Unit { world().bodies, true, ) - world().collider_entities.remove(collider_handle_id(collider_handle)) + world().collider_entities.remove(collider_handle_key(collider_handle)) world().entity_colliders.remove(entity) } if world().entity_bodies.get(entity) is Some(body_handle) { @@ -42,10 +42,12 @@ fn consume_pending_body_controls(entity : @ecs.Entity) -> Unit { ///| fn sync_world_entities() -> Unit { prune_pending_body_state() - for (entity, _) in world().entity_bodies.to_array() { - if !should_have_physics(entity) { - remove_entity_physics(entity) - } + let stale = world().entity_bodies + .keys() + .filter(entity => !should_have_physics(entity)) + .collect() + for entity in stale { + remove_entity_physics(entity) } for entity in @ecs.iter_entities() { @@ -150,7 +152,7 @@ fn insert_entity_physics( ) world().entity_bodies.set(entity, body_handle) world().entity_colliders.set(entity, collider_handle) - world().collider_entities.set(collider_handle_id(collider_handle), entity) + world().collider_entities.set(collider_handle_key(collider_handle), entity) } ///| @@ -232,7 +234,7 @@ fn sync_entity_physics( fn entity_from_collider_handle( handle : @rapier_collision.ColliderHandle, ) -> @ecs.Entity? { - world().collider_entities.get(collider_handle_id(handle)) + world().collider_entities.get(collider_handle_key(handle)) } ///| diff --git a/selene-core/src/collision/rapier2d_sync_joints.mbt b/selene-core/src/collision/rapier2d_sync_joints.mbt index b7f9aa25..abf4776b 100644 --- a/selene-core/src/collision/rapier2d_sync_joints.mbt +++ b/selene-core/src/collision/rapier2d_sync_joints.mbt @@ -111,7 +111,7 @@ fn refresh_query_world() -> Unit { ///| fn accumulate_pending_vec2( - pending : Map[@ecs.Entity, @math.Vec2], + pending : @ecs.EntityTable[@math.Vec2], entity : @ecs.Entity, value : @math.Vec2, ) -> Unit { @@ -120,7 +120,7 @@ fn accumulate_pending_vec2( ///| fn accumulate_pending_scalar( - pending : Map[@ecs.Entity, Double], + pending : @ecs.EntityTable[Double], entity : @ecs.Entity, value : Double, ) -> Unit { @@ -129,7 +129,7 @@ fn accumulate_pending_scalar( ///| fn push_pending_force_point( - pending : Map[@ecs.Entity, Array[(@math.Vec2, @math.Vec2)]], + pending : @ecs.EntityTable[Array[(@math.Vec2, @math.Vec2)]], entity : @ecs.Entity, value : (@math.Vec2, @math.Vec2), ) -> Unit { diff --git a/selene-core/src/culling2d/culling2d_wbtest.mbt b/selene-core/src/culling2d/culling2d_wbtest.mbt index a0e2ae23..5ae666ab 100644 --- a/selene-core/src/culling2d/culling2d_wbtest.mbt +++ b/selene-core/src/culling2d/culling2d_wbtest.mbt @@ -19,3 +19,32 @@ test "spatial grid query returns deterministic ids from overlapping cells" { inspect(ids[0], content="2") inspect(ids[1], content="5") } + +///| +test "integer grid keys distinguish negative and positive coordinates" { + let grid = SpatialGrid2d( + [ + { + id: 3U, + bounds: { position: Vec2(-48.0, -48.0), size: Vec2(8.0, 8.0), }, + }, + { + id: 1U, + bounds: { position: Vec2(40.0, -48.0), size: Vec2(8.0, 8.0), }, + }, + { + id: 2U, + bounds: { position: Vec2(-48.0, 40.0), size: Vec2(8.0, 8.0), }, + }, + ], + cell_size=16.0, + ) + debug_inspect( + grid.query({ position: Vec2(-48.0, -48.0), size: Vec2(8.0, 8.0), }), + content="[3]", + ) + debug_inspect( + grid.query({ position: Vec2(-64.0, -64.0), size: Vec2(128.0, 128.0), }), + content="[1, 2, 3]", + ) +} diff --git a/selene-core/src/culling2d/pkg.generated.mbti b/selene-core/src/culling2d/pkg.generated.mbti index 9fcd6335..1ae652b7 100644 --- a/selene-core/src/culling2d/pkg.generated.mbti +++ b/selene-core/src/culling2d/pkg.generated.mbti @@ -23,7 +23,7 @@ pub fn CameraExtract2dContext::camera_views_for_bounds(Self, @math.Rect, @visibi pub(all) struct SpatialGrid2d { cell_size : Double - buckets : Map[String, Array[UInt32]] + buckets : Map[(Int32, Int32), Array[UInt32]] } pub fn SpatialGrid2d::SpatialGrid2d(Array[SpatialGridEntry2d], cell_size? : Double) -> Self pub fn SpatialGrid2d::query(Self, @math.Rect) -> Array[UInt32] diff --git a/selene-core/src/culling2d/spatial_grid.mbt b/selene-core/src/culling2d/spatial_grid.mbt index 67e62671..4e3b617c 100644 --- a/selene-core/src/culling2d/spatial_grid.mbt +++ b/selene-core/src/culling2d/spatial_grid.mbt @@ -7,7 +7,7 @@ pub(all) struct SpatialGridEntry2d { ///| pub(all) struct SpatialGrid2d { cell_size : Double - buckets : Map[String, Array[UInt32]] + buckets : Map[(Int32, Int32), Array[UInt32]] } ///| @@ -36,25 +36,20 @@ fn rect_cell_bounds( (min_x, min_y, max_x, max_y) } -///| -fn bucket_key(x : Int32, y : Int32) -> String { - x.to_string() + ":" + y.to_string() -} - ///| pub fn SpatialGrid2d::SpatialGrid2d( entries : Array[SpatialGridEntry2d], cell_size~ : Double = 256.0, ) -> SpatialGrid2d { let effective_size = effective_cell_size(cell_size) - let buckets : Map[String, Array[UInt32]] = Map([]) + let buckets : Map[(Int32, Int32), Array[UInt32]] = Map([]) for entry in entries { let bounds = entry.bounds guard bounds.size.x > 0.0 && bounds.size.y > 0.0 else { continue } let (min_x, min_y, max_x, max_y) = rect_cell_bounds(bounds, effective_size) for x in min_x..<(max_x + 1) { for y in min_y..<(max_y + 1) { - buckets.get_or_init(bucket_key(x, y), fn() { [] }).push(entry.id) + buckets.get_or_init((x, y), fn() { [] }).push(entry.id) } } } @@ -73,7 +68,7 @@ pub fn SpatialGrid2d::query( let (min_x, min_y, max_x, max_y) = rect_cell_bounds(region, self.cell_size) for x in min_x..<(max_x + 1) { for y in min_y..<(max_y + 1) { - match self.buckets.get(bucket_key(x, y)) { + match self.buckets.get((x, y)) { Some(ids) => for id in ids { unique.add(id) diff --git a/selene-core/src/ecs/README.md b/selene-core/src/ecs/README.md index bd501941..af205544 100644 --- a/selene-core/src/ecs/README.md +++ b/selene-core/src/ecs/README.md @@ -273,3 +273,21 @@ The generator formats its own output. Commit the generated file alongside its input and include it when publishing. MoonBit runs `dev_build` during local development. Consumers compile the generated sources included in the published package. + +## Runtime data outside components + +Use a World resource for subsystem state, including caches and event readers. +Do not keep a global `Map[WorldId, State]`: the World should own its data. + +`EntityTable[T](world)` stores World-local runtime data indexed by entity slots. +It is not a component store and does not change entity layouts. Lookups compare +full entity handles, and traversal preserves insertion order. Deleted entities' +entries remain available for explicit cleanup, including when their slots have +been reused. This lets an owner release old audio or physics resources without +confusing them with a new entity. Use `retain` to prune entries; its callback +must not structurally modify the table. Use `clear` for frame-local results. + +Prefer direct iteration for reads. Use `Map::retain` for simple filtering, and +queue entity deletions through `Commands` while traversing components. Collect a +snapshot only when callbacks or structural changes require a stable set of +entries. A snapshot preserves entries, not a deep copy of mutable values. diff --git a/selene-core/src/ecs/entity_table.mbt b/selene-core/src/ecs/entity_table.mbt new file mode 100644 index 00000000..87f1c866 --- /dev/null +++ b/selene-core/src/ecs/entity_table.mbt @@ -0,0 +1,263 @@ +///| +priv struct EntityTableEntry[T] { + entity : Entity + mut value : T + mut previous : Int32? + mut next : Int32? + mut older : Int32? +} + +///| +/// World-local runtime data indexed by reusable entity slots. Full handles +/// distinguish generations. Orphaned entries remain available until the owner +/// releases them, even if the entity slot has already been reused. +struct EntityTable[T] { + world_id : UInt32 + sparse : Array[Int32?] + entries : Array[EntityTableEntry[T]?] + free : Array[Int32] + mut head : Int32? + mut tail : Int32? + mut length : Int32 +} + +///| +pub fn[T] EntityTable::EntityTable(world : World) -> EntityTable[T] { + { + world_id: world.id(), + sparse: [], + entries: [], + free: [], + head: None, + tail: None, + length: 0, + } +} + +///| +fn[T] EntityTable::index(self : EntityTable[T], entity : Entity) -> Int32? { + guard entity.world_id == self.world_id else { None } + for next = self.sparse.get(entity.slot).unwrap_or(None) { + guard next is Some(index) else { return None } + let entry = self.entries[index].unwrap() + if entry.entity == entity { + return Some(index) + } + continue entry.older + } +} + +///| +pub fn[T] EntityTable::get(self : EntityTable[T], entity : Entity) -> T? { + self.index(entity).map(index => self.entries[index].unwrap().value) +} + +///| +pub fn[T] EntityTable::contains(self : EntityTable[T], entity : Entity) -> Bool { + self.index(entity) is Some(_) +} + +///| +pub fn[T] EntityTable::set( + self : EntityTable[T], + entity : Entity, + value : T, +) -> Unit { + guard entity.world_id == self.world_id else { + abort("entity table belongs to another World") + } + while self.sparse.length() <= entity.slot { + self.sparse.push(None) + } + let older = self.sparse[entity.slot] + if older is Some(index) { + let entry = self.entries[index].unwrap() + if entry.entity == entity { + entry.value = value + return + } + guard entity.generation > entry.entity.generation else { + abort("stale entity table write") + } + } + let entry = { entity, value, previous: self.tail, next: None, older, } + let index = match self.free.pop() { + Some(index) => { + self.entries[index] = Some(entry) + index + } + None => { + let index = self.entries.length() + self.entries.push(Some(entry)) + index + } + } + if self.tail is Some(tail) { + self.entries[tail].unwrap().next = Some(index) + } else { + self.head = Some(index) + } + self.tail = Some(index) + self.sparse[entity.slot] = Some(index) + self.length += 1 +} + +///| +pub fn[T] EntityTable::get_or_init( + self : EntityTable[T], + entity : Entity, + create : () -> T, +) -> T { + match self.get(entity) { + Some(value) => value + None => { + let value = create() + self.set(entity, value) + value + } + } +} + +///| +pub fn[T] EntityTable::remove_and_get( + self : EntityTable[T], + entity : Entity, +) -> T? { + guard self.index(entity) is Some(index) else { None } + let entry = self.entries[index].unwrap() + if self.sparse[entity.slot] == Some(index) { + self.sparse[entity.slot] = entry.older + } else { + for next = self.sparse[entity.slot] { + guard next is Some(newer) else { + abort("entity table generation chain is missing") + } + let newer_entry = self.entries[newer].unwrap() + if newer_entry.older == Some(index) { + newer_entry.older = entry.older + break + } + continue newer_entry.older + } + } + if entry.previous is Some(previous) { + self.entries[previous].unwrap().next = entry.next + } else { + self.head = entry.next + } + if entry.next is Some(next) { + self.entries[next].unwrap().previous = entry.previous + } else { + self.tail = entry.previous + } + self.entries[index] = None + self.free.push(index) + self.length -= 1 + Some(entry.value) +} + +///| +pub fn[T] EntityTable::remove(self : EntityTable[T], entity : Entity) -> Unit { + ignore(self.remove_and_get(entity)) +} + +///| +pub fn[T] EntityTable::length(self : EntityTable[T]) -> Int32 { + self.length +} + +///| +pub fn[T] EntityTable::is_empty(self : EntityTable[T]) -> Bool { + self.length == 0 +} + +///| +pub fn[T] EntityTable::clear(self : EntityTable[T]) -> Unit { + for next = self.head { + guard next is Some(index) else { break } + let entry = self.entries[index].unwrap() + self.sparse[entry.entity.slot] = None + self.entries[index] = None + self.free.push(index) + continue entry.next + } + self.head = None + self.tail = None + self.length = 0 +} + +///| +/// Visits entries in insertion order. Do not structurally modify this table +/// while iterating; use retain or collect only the pending changes instead. +pub fn[T] EntityTable::iter2(self : EntityTable[T]) -> Iter2[Entity, T] { + let mut next = self.head + Iter2::new( + () => { + guard next is Some(index) && self.entries[index] is Some(entry) else { + None + } + next = entry.next + Some((entry.entity, entry.value)) + }, + size_hint=self.length, + ) +} + +///| +pub fn[T] EntityTable::iter(self : EntityTable[T]) -> Iter[(Entity, T)] { + let entries = self.iter2() + Iter::new(() => entries.next()) +} + +///| +pub fn[T] EntityTable::keys(self : EntityTable[T]) -> Iter[Entity] { + let mut next = self.head + Iter::new( + () => { + guard next is Some(index) && self.entries[index] is Some(entry) else { + None + } + next = entry.next + Some(entry.entity) + }, + size_hint=self.length, + ) +} + +///| +pub fn[T] EntityTable::values(self : EntityTable[T]) -> Iter[T] { + let mut next = self.head + Iter::new( + () => { + guard next is Some(index) && self.entries[index] is Some(entry) else { + None + } + next = entry.next + Some(entry.value) + }, + size_hint=self.length, + ) +} + +///| +pub fn[T] EntityTable::to_array(self : EntityTable[T]) -> Array[(Entity, T)] { + self.iter().collect() +} + +///| +/// Removes entries in place, preserving insertion order. The predicate must +/// not structurally modify this table, including through another reference. +pub fn[T] EntityTable::retain( + self : EntityTable[T], + keep : (Entity, T) -> Bool, +) -> Unit { + for next = self.head { + guard next is Some(index) else { break } + let entry = self.entries[index].unwrap() + let following = entry.next + if !keep(entry.entity, entry.value) { + self.remove(entry.entity) + } + continue following + } +} diff --git a/selene-core/src/ecs/entity_table_bench_wbtest.mbt b/selene-core/src/ecs/entity_table_bench_wbtest.mbt new file mode 100644 index 00000000..cf61d17d --- /dev/null +++ b/selene-core/src/ecs/entity_table_bench_wbtest.mbt @@ -0,0 +1,66 @@ +///| +test "BENCH runtime entity side tables versus Map" (bench : @bench.T) { + let world = World() + let entities = Array::makei(8192, _ => world.spawn(())) + for stride in [1, 16] { + let map : Map[Entity, Int32] = Map([]) + let table : EntityTable[Int32] = EntityTable(world) + for index, entity in entities { + if index % stride == 0 { + map.set(entity, index) + table.set(entity, index) + } + } + let read_map = () => { + let mut sum = 0 + for entity in entities { + sum += map.get(entity).unwrap_or(0) + } + sum + } + let read_table = () => { + let mut sum = 0 + for entity in entities { + sum += table.get(entity).unwrap_or(0) + } + sum + } + assert_eq(read_map(), read_table()) + bench.bench(name="Map/read/stride=\{stride}", count=20, () => { + bench.keep(read_map()) + }) + bench.bench(name="EntityTable/read/stride=\{stride}", count=20, () => { + bench.keep(read_table()) + }) + bench.bench(name="Map/read-write/stride=\{stride}", count=20, () => { + for entity in entities { + if map.get(entity) is Some(value) { + map.set(entity, value ^ 1) + } + } + bench.keep(map.length()) + }) + bench.bench(name="EntityTable/read-write/stride=\{stride}", count=20, () => { + for entity in entities { + if table.get(entity) is Some(value) { + table.set(entity, value ^ 1) + } + } + bench.keep(table.length()) + }) + bench.bench(name="Map/scan/stride=\{stride}", count=20, () => { + let mut sum = 0 + for _, value in map { + sum += value + } + bench.keep(sum) + }) + bench.bench(name="EntityTable/scan/stride=\{stride}", count=20, () => { + let mut sum = 0 + for _, value in table { + sum += value + } + bench.keep(sum) + }) + } +} diff --git a/selene-core/src/ecs/entity_table_test.mbt b/selene-core/src/ecs/entity_table_test.mbt new file mode 100644 index 00000000..6cc85680 --- /dev/null +++ b/selene-core/src/ecs/entity_table_test.mbt @@ -0,0 +1,134 @@ +///| +test "entity side tables preserve insertion order across removal and reuse" { + let world = @ecs.World() + let table : @ecs.EntityTable[Int32] = EntityTable(world) + let entities = [ + world.spawn(()), + world.spawn(()), + world.spawn(()), + world.spawn(()), + ] + for index, entity in entities { + table.set(entity, index) + } + table.set(entities[1], 10) + assert_eq(table.remove_and_get(entities[1]), Some(10)) + assert_eq(table.remove_and_get(entities[1]), None) + assert_eq(table.get(entities[3]), Some(3)) + debug_inspect(table.values().collect(), content="[0, 2, 3]") + table.set(entities[1], 11) + debug_inspect(table.values().collect(), content="[0, 2, 3, 11]") + table.retain((_, value) => value % 2 == 1) + debug_inspect(table.values().collect(), content="[3, 11]") + assert_eq(table.length(), 2) + table.remove(entities[3]) + table.remove(entities[1]) + assert_true(table.is_empty()) + table.set(entities[0], 20) + table.clear() + assert_false(table.contains(entities[0])) + assert_true(table.keys().next() is None) + table.set(entities[2], 30) + debug_inspect(table.values().collect(), content="[30]") +} + +///| +test "entity side tables distinguish Worlds and generations while retaining orphan cleanup data" { + let previous = @ecs.current_world() + defer (match previous { + Some(world) => @ecs.set_current_world(world) + None => @ecs.clear_current_world() + }) + let first = @ecs.World() + let second = @ecs.World() + @ecs.set_current_world(first) + let old = first.spawn(()) + let other = second.spawn(()) + let table : @ecs.EntityTable[Int32] = EntityTable(first) + table.set(old, 42) + assert_eq(table.get(other), None) + assert_eq(table.remove_and_get(other), None) + assert_true(old.delete()) + let replacement = first.spawn(()) + assert_eq(replacement.slot_index(), old.slot_index()) + assert_eq(table.get(replacement), None) + // External resource cleanup must still be able to read the deleted handle. + assert_eq(table.remove_and_get(old), Some(42)) + table.set(replacement, 100) + table.remove(old) + assert_eq(table.get(replacement), Some(100)) + assert_true(replacement.delete()) + let newest = first.spawn(()) + table.set(newest, 200) + assert_eq(table.get(replacement), Some(100)) + assert_eq(table.get(newest), Some(200)) + assert_eq(table.length(), 2) + table.retain((entity, _) => entity.is_valid_in(first)) + assert_eq(table.get(replacement), None) + assert_eq(table.length(), 1) + let calls = Ref(0) + assert_eq( + table.get_or_init(newest, () => { + calls.val += 1 + 0 + }), + 200, + ) + assert_eq(calls.val, 0) +} + +///| +test "panic entity side tables reject writes from a different World" { + let first = @ecs.World() + let second = @ecs.World() + let table : @ecs.EntityTable[Int32] = EntityTable(first) + table.set(second.spawn(()), 1) +} + +///| +test "panic stale entity side table writes cannot replace a newer generation" { + let previous = @ecs.current_world() + defer (match previous { + Some(world) => @ecs.set_current_world(world) + None => @ecs.clear_current_world() + }) + let world = @ecs.World() + @ecs.set_current_world(world) + let old = world.spawn(()) + ignore(old.delete()) + let replacement = world.spawn(()) + let table : @ecs.EntityTable[Int32] = EntityTable(world) + table.set(replacement, 2) + table.set(old, 1) +} + +///| +test "multiple orphan generations survive slot reuse until explicitly released" { + let previous = @ecs.current_world() + defer (match previous { + Some(world) => @ecs.set_current_world(world) + None => @ecs.clear_current_world() + }) + let world = @ecs.World() + @ecs.set_current_world(world) + let table : @ecs.EntityTable[Int32] = EntityTable(world) + let generations = [] + for value in 0..<4 { + let entity = world.spawn(()) + table.set(entity, value) + generations.push(entity) + ignore(entity.delete()) + } + assert_eq(generations[0].slot_index(), generations[3].slot_index()) + assert_eq(table.remove_and_get(generations[1]), Some(1)) + assert_eq(table.get(generations[0]), Some(0)) + assert_eq(table.remove_and_get(generations[3]), Some(3)) + assert_eq(table.get(generations[2]), Some(2)) + debug_inspect(table.values().collect(), content="[0, 2]") + table.clear() + let entity = world.spawn(()) + table.set(entity, 4) + assert_eq(table.length(), 1) + assert_eq(table.get(generations[0]), None) + assert_eq(table.get(entity), Some(4)) +} diff --git a/selene-core/src/ecs/pkg.generated.mbti b/selene-core/src/ecs/pkg.generated.mbti index 8f01f0f3..41142f97 100644 --- a/selene-core/src/ecs/pkg.generated.mbti +++ b/selene-core/src/ecs/pkg.generated.mbti @@ -104,6 +104,24 @@ pub(all) struct EntityFilter { } pub fn EntityFilter::passes(Self, Entity) -> Bool +type EntityTable[T] +pub fn[T] EntityTable::EntityTable(World) -> Self[T] +pub fn[T] EntityTable::clear(Self[T]) -> Unit +pub fn[T] EntityTable::contains(Self[T], Entity) -> Bool +pub fn[T] EntityTable::get(Self[T], Entity) -> T? +pub fn[T] EntityTable::get_or_init(Self[T], Entity, () -> T) -> T +pub fn[T] EntityTable::is_empty(Self[T]) -> Bool +pub fn[T] EntityTable::iter(Self[T]) -> Iter[(Entity, T)] +pub fn[T] EntityTable::iter2(Self[T]) -> Iter2[Entity, T] +pub fn[T] EntityTable::keys(Self[T]) -> Iter[Entity] +pub fn[T] EntityTable::length(Self[T]) -> Int32 +pub fn[T] EntityTable::remove(Self[T], Entity) -> Unit +pub fn[T] EntityTable::remove_and_get(Self[T], Entity) -> T? +pub fn[T] EntityTable::retain(Self[T], (Entity, T) -> Bool) -> Unit +pub fn[T] EntityTable::set(Self[T], Entity, T) -> Unit +pub fn[T] EntityTable::to_array(Self[T]) -> Array[(Entity, T)] +pub fn[T] EntityTable::values(Self[T]) -> Iter[T] + pub(all) struct Query[T] { world : World storage : ComponentStore[T] diff --git a/selene-core/src/ecs/spawn_draft.mbt b/selene-core/src/ecs/spawn_draft.mbt index f7666c7a..96681c99 100644 --- a/selene-core/src/ecs/spawn_draft.mbt +++ b/selene-core/src/ecs/spawn_draft.mbt @@ -2,13 +2,13 @@ /// Collects initial component values before an entity has a handle. struct SpawnDraft { world : World - columns : Map[Int32, (Int32, Entity) -> Unit] + columns : Array[(Int32, (Int32, Entity) -> Unit)] mut spawned : Bool } ///| pub fn World::spawn_draft(self : World) -> SpawnDraft { - { world: self, columns: Map([]), spawned: false, } + { world: self, columns: [], spawned: false, } } ///| @@ -27,18 +27,18 @@ pub fn[T] SpawnDraft::add_to( guard store.belongs_to(self.world) else { abort("spawn draft component belongs to another World") } - guard !self.columns.contains(store.component) else { + guard !self.columns.any(column => column.0 == store.component) else { abort("duplicate component in spawn draft") } - self.columns.set(store.component, (table, entity) => { - store.append_new(table, entity, value) - }) + self.columns.push( + (store.component, (table, entity) => store.append_new(table, entity, value)), + ) } ///| pub fn SpawnDraft::spawn(self : SpawnDraft, parent? : Entity) -> Entity { guard !self.spawned else { abort("spawn draft already used") } - let signature = self.columns.keys().collect() + let signature = self.columns.map(column => column.0) signature.sort() let plan : SpawnPlan[Unit] = { world_id: self.world.id(), @@ -46,7 +46,7 @@ pub fn SpawnDraft::spawn(self : SpawnDraft, parent? : Entity) -> Entity { signature, table: None, append: (table, entity, _) => { - for _, append in self.columns { + for (_, append) in self.columns { append(table, entity) } }, diff --git a/selene-core/src/event/event_wbtest.mbt b/selene-core/src/event/event_wbtest.mbt index f7738b0d..67947f26 100644 --- a/selene-core/src/event/event_wbtest.mbt +++ b/selene-core/src/event/event_wbtest.mbt @@ -126,3 +126,61 @@ test "events: frame update systems are world-scoped and require explicit registr inspect(int_array_matches(events.read(reader_b), [2]), content="true") @ecs.set_current_world(@ecs.bootstrap_world()) } + +///| +test "one reader and event bus keep independent World-owned cursors and observers" { + let previous = @ecs.current_world() + defer (match previous { + Some(world) => @ecs.set_current_world(world) + None => @ecs.clear_current_world() + }) + let first = @ecs.World() + let second = @ecs.World() + let bus : Events[Int32] = Events() + let reader : EventReader[Int32] = EventReader() + let received = [] + bus.register_to_world(first) + bus.register_to_world(second) + @ecs.set_current_world(first) + ignore(bus.observe_global(item => received.push(item.event))) + bus.trigger(10, None) + debug_inspect(reader.read(bus), content="[10]") + @ecs.set_current_world(second) + bus.trigger(20, None) + debug_inspect(reader.read(bus), content="[20]") + event_observer_dispatch_system(0.0) + assert_true(received.is_empty()) + @ecs.set_current_world(first) + bus.trigger(11, None) + debug_inspect(reader.read(bus), content="[11]") + event_observer_dispatch_system(0.0) + debug_inspect(received, content="[10, 11]") + @ecs.set_current_world(second) + debug_inspect(reader.read(bus), content="[]") +} + +///| +test "observer subscriptions can change safely during a trigger" { + let previous = @ecs.current_world() + defer (match previous { + Some(world) => @ecs.set_current_world(world) + None => @ecs.clear_current_world() + }) + @ecs.set_current_world(World()) + let events : Events[Int32] = Events() + let received = [] + let first = Ref(None) + first.val = Some( + events.observe_global(item => { + received.push(item.event) + events.unobserve(first.val.unwrap()) + ignore(events.observe_global(next => received.push(next.event * 10))) + }), + ) + events.trigger(1, None) + events.dispatch_observers() + debug_inspect(received, content="[1]") + events.trigger(2, None) + events.dispatch_observers() + debug_inspect(received, content="[1, 20]") +} diff --git a/selene-core/src/event/events.mbt b/selene-core/src/event/events.mbt index 2aa6b2e4..f5f704aa 100644 --- a/selene-core/src/event/events.mbt +++ b/selene-core/src/event/events.mbt @@ -43,19 +43,13 @@ struct EventWorldStore[T] { pub struct Events[T] { id : UInt32 domain : EventDomain - stores : Map[UInt32, EventWorldStore[T]] + store_key : @ecs.ResourceKey[EventWorldStore[T]] marker : T? } -///| -fn current_world_id() -> UInt32 { - @ecs.require_current_world().id() -} - ///| fn[T] world_store(events : Events[T]) -> EventWorldStore[T] { - let world_id = current_world_id() - events.stores.get_or_init(world_id, () => { + events.store_key.get_or_insert_with(@ecs.require_current_world(), _ => { next_event_id: 0, next_observer_id: 0, older: [], @@ -67,7 +61,12 @@ fn[T] world_store(events : Events[T]) -> EventWorldStore[T] { ///| pub fn[T] Events::Events(domain~ : EventDomain = Frame) -> Events[T] { - { id: allocate_event_bus_id(), domain, stores: Map([]), marker: None, } + { + id: allocate_event_bus_id(), + domain, + store_key: ResourceKey(), + marker: None, + } } ///| @@ -75,8 +74,7 @@ pub fn[T] Events::register_to_world( self : Events[T], world : @ecs.World, ) -> Unit { - let world_id = world.id() - let buses = registered_buses_by_world.get(world_id).unwrap_or([]) + let buses = registered_buses_key.get_or_insert_with(world, _ => []) for bus in buses { if bus.id == self.id { return @@ -88,7 +86,6 @@ pub fn[T] Events::register_to_world( update: fn() { self.update() }, dispatch: fn() { self.dispatch_observers() }, }) - registered_buses_by_world.set(world_id, buses) } ///| @@ -167,10 +164,11 @@ pub fn[T] Events::update(self : Events[T]) -> Unit { } ///| +/// Subscription changes made by a callback take effect on the next trigger. pub fn[T] Events::dispatch_observers(self : Events[T]) -> Unit { let store = world_store(self) for item in store.observer_queue { - for _handle, observer in store.observers { + for observer in store.observers.values().collect() { let deliver = match observer.target { None => true Some(entity) => diff --git a/selene-core/src/event/pkg.generated.mbti b/selene-core/src/event/pkg.generated.mbti index 7fb05513..ecaa3cfe 100644 --- a/selene-core/src/event/pkg.generated.mbti +++ b/selene-core/src/event/pkg.generated.mbti @@ -41,7 +41,7 @@ pub fn EventDomain::not_equal(Self, Self) -> Bool pub fn EventDomain::to_repr(Self) -> @debug.Repr pub(all) struct EventReader[T] { - last_seen_by_world : Map[UInt32, Int32] + last_seen_key : @ecs.ResourceKey[Int32] marker : T? } pub fn[T] EventReader::EventReader() -> Self[T] @@ -59,7 +59,7 @@ pub fn[T] EventWriter::trigger(Self[T], T, target? : @ecs.Entity?) -> Unit pub struct Events[T] { id : UInt32 domain : EventDomain - stores : Map[UInt32, EventWorldStore[T]] + store_key : @ecs.ResourceKey[EventWorldStore[T]] marker : T? } pub fn[T] Events::Events(domain? : EventDomain) -> Self[T] diff --git a/selene-core/src/event/reader.mbt b/selene-core/src/event/reader.mbt index af071697..573dc275 100644 --- a/selene-core/src/event/reader.mbt +++ b/selene-core/src/event/reader.mbt @@ -1,12 +1,12 @@ ///| pub(all) struct EventReader[T] { - last_seen_by_world : Map[UInt32, Int32] + last_seen_key : @ecs.ResourceKey[Int32] marker : T? } ///| pub fn[T] EventReader::EventReader() -> EventReader[T] { - { last_seen_by_world: Map([]), marker: None, } + { last_seen_key: ResourceKey(), marker: None, } } ///| @@ -14,8 +14,8 @@ pub fn[T] EventReader::read( self : EventReader[T], events : Events[T], ) -> Array[T] { - let world_id = current_world_id() - let last_seen = self.last_seen_by_world.get(world_id).unwrap_or(-1) + let world = @ecs.require_current_world() + let last_seen = self.last_seen_key.get_in(world).unwrap_or(-1) let store = world_store(events) let values : Array[T] = [] let mut latest_id = last_seen @@ -31,7 +31,7 @@ pub fn[T] EventReader::read( latest_id = record.id } } - self.last_seen_by_world.set(world_id, latest_id) + self.last_seen_key.insert_in(world, latest_id) values } diff --git a/selene-core/src/event/schedule.mbt b/selene-core/src/event/schedule.mbt index 95abb93b..2d693f9a 100644 --- a/selene-core/src/event/schedule.mbt +++ b/selene-core/src/event/schedule.mbt @@ -21,7 +21,7 @@ priv struct RegisteredBus { } ///| -let registered_buses_by_world : Map[UInt32, Array[RegisteredBus]] = Map([]) +let registered_buses_key : @ecs.ResourceKey[Array[RegisteredBus]] = ResourceKey() ///| let next_event_bus_id : Ref[UInt32] = { val: 1U, } @@ -35,8 +35,10 @@ fn allocate_event_bus_id() -> UInt32 { ///| fn update_domain(domain : EventDomain) -> Unit { - let world_id = current_world_id() - for bus in registered_buses_by_world.get(world_id).unwrap_or([]) { + for + bus in registered_buses_key + .get_in(@ecs.require_current_world()) + .unwrap_or([]) { if bus.domain == domain { (bus.update)() } @@ -60,8 +62,10 @@ pub fn event_render_update_system(_delta : Double) -> Unit { ///| pub fn event_observer_dispatch_system(_delta : Double) -> Unit { - let world_id = current_world_id() - for bus in registered_buses_by_world.get(world_id).unwrap_or([]) { + for + bus in registered_buses_key + .get_in(@ecs.require_current_world()) + .unwrap_or([]) { (bus.dispatch)() } } diff --git a/selene-core/src/inputs/gamepad.mbt b/selene-core/src/inputs/gamepad.mbt index e3f2d25c..6107fe71 100644 --- a/selene-core/src/inputs/gamepad.mbt +++ b/selene-core/src/inputs/gamepad.mbt @@ -188,12 +188,11 @@ priv struct GamepadWorldStore { } ///| -let gamepad_world_stores : Map[UInt32, GamepadWorldStore] = Map([]) +let gamepad_world_store_key : @ecs.ResourceKey[GamepadWorldStore] = ResourceKey() ///| fn gamepad_world_store() -> GamepadWorldStore { - let world_id = @ecs.require_current_world().id() - gamepad_world_stores.get_or_init(world_id, () => { + gamepad_world_store_key.get_or_insert_with(@ecs.require_current_world(), _ => { connected_gamepads: Set([]), pressed_gamepad_buttons: Set([]), gamepad_axis_values: Map([]), diff --git a/selene-core/src/ldtk/ldtk_wbtest.mbt b/selene-core/src/ldtk/ldtk_wbtest.mbt index 56778674..b46785f6 100644 --- a/selene-core/src/ldtk/ldtk_wbtest.mbt +++ b/selene-core/src/ldtk/ldtk_wbtest.mbt @@ -47,7 +47,7 @@ fn reset_ldtk_runtime() -> Unit { despawn_ldtk_tree(entity) } ldtk_respawns().clear() - for (iid, _) in ldtk_pending_transformed_level_iids().to_array() { + for iid in ldtk_pending_transformed_level_iids().to_array() { ldtk_pending_transformed_level_iids().remove(iid) } for (key, _) in ldtk_entity_spawn_hooks().to_array() { diff --git a/selene-core/src/ldtk/ldtk_world_entities.mbt b/selene-core/src/ldtk/ldtk_world_entities.mbt index 41cdce02..226f9bdf 100644 --- a/selene-core/src/ldtk/ldtk_world_entities.mbt +++ b/selene-core/src/ldtk/ldtk_world_entities.mbt @@ -185,15 +185,9 @@ pub fn clear_ldtk_entity_default_spawn_hook() -> Unit { ///| pub fn clear_ldtk_entity_spawn_hooks() -> Unit { - for (key, _) in ldtk_entity_spawn_hooks().to_array() { - ldtk_entity_spawn_hooks().remove(key) - } - for (key, _) in ldtk_entity_layer_spawn_hooks().to_array() { - ldtk_entity_layer_spawn_hooks().remove(key) - } - for (key, _) in ldtk_entity_layer_identifier_spawn_hooks().to_array() { - ldtk_entity_layer_identifier_spawn_hooks().remove(key) - } + ldtk_entity_spawn_hooks().clear() + ldtk_entity_layer_spawn_hooks().clear() + ldtk_entity_layer_identifier_spawn_hooks().clear() ldtk_entity_default_spawn_hook().val = None } diff --git a/selene-core/src/ldtk/ldtk_world_layers.mbt b/selene-core/src/ldtk/ldtk_world_layers.mbt index 31da65fd..c507d452 100644 --- a/selene-core/src/ldtk/ldtk_world_layers.mbt +++ b/selene-core/src/ldtk/ldtk_world_layers.mbt @@ -1,8 +1,6 @@ ///| pub fn clear_ldtk_int_cell_registrations() -> Unit { - for (key, _) in ldtk_int_cell_typed_registrations().to_array() { - ldtk_int_cell_typed_registrations().remove(key) - } + ldtk_int_cell_typed_registrations().clear() } ///| diff --git a/selene-core/src/ldtk/ldtk_world_registry.mbt b/selene-core/src/ldtk/ldtk_world_registry.mbt index 5a6f03f3..fedc80c5 100644 --- a/selene-core/src/ldtk/ldtk_world_registry.mbt +++ b/selene-core/src/ldtk/ldtk_world_registry.mbt @@ -49,7 +49,7 @@ pub fn ldtk_worldly_entities() -> @ecs.ComponentStore[LdtkWorldly] { } ///| -pub fn ldtk_respawns() -> Map[@ecs.Entity, LdtkRespawn] { +pub fn ldtk_respawns() -> @ecs.EntityTable[LdtkRespawn] { ldtk_world_store().respawns } diff --git a/selene-core/src/ldtk/ldtk_world_runtime.mbt b/selene-core/src/ldtk/ldtk_world_runtime.mbt index cb1613ff..110199d8 100644 --- a/selene-core/src/ldtk/ldtk_world_runtime.mbt +++ b/selene-core/src/ldtk/ldtk_world_runtime.mbt @@ -12,9 +12,7 @@ pub fn clear_ldtk_int_grid_default_spawn_hook() -> Unit { ///| pub fn clear_ldtk_int_grid_layer_spawn_hooks() -> Unit { - for (key, _) in ldtk_int_grid_layer_spawn_hooks().to_array() { - ldtk_int_grid_layer_spawn_hooks().remove(key) - } + ldtk_int_grid_layer_spawn_hooks().clear() } ///| @@ -41,16 +39,12 @@ pub fn unregister_ldtk_int_grid_cell_spawn_hook( ///| pub fn clear_ldtk_int_grid_cell_spawn_hooks() -> Unit { - for (key, _) in ldtk_int_grid_cell_spawn_hooks().to_array() { - ldtk_int_grid_cell_spawn_hooks().remove(key) - } + ldtk_int_grid_cell_spawn_hooks().clear() } ///| pub fn clear_ldtk_int_grid_value_spawn_hooks() -> Unit { - for (key, _) in ldtk_int_grid_value_spawn_hooks().to_array() { - ldtk_int_grid_value_spawn_hooks().remove(key) - } + ldtk_int_grid_value_spawn_hooks().clear() } ///| @@ -293,7 +287,7 @@ fn ldtk_spawn_level_entity( instance, ) ldtk_level_event_bus.trigger(Spawned(indexed.level.iid), Some(level_entity)) - ldtk_pending_transformed_level_iids().set(indexed.level.iid, true) + ldtk_pending_transformed_level_iids().add(indexed.level.iid) level_entity } diff --git a/selene-core/src/ldtk/ldtk_world_spawner.mbt b/selene-core/src/ldtk/ldtk_world_spawner.mbt index 80dde1c7..4c0e1aee 100644 --- a/selene-core/src/ldtk/ldtk_world_spawner.mbt +++ b/selene-core/src/ldtk/ldtk_world_spawner.mbt @@ -1,5 +1,5 @@ ///| -pub fn ldtk_pending_transformed_level_iids() -> Map[String, Bool] { +pub fn ldtk_pending_transformed_level_iids() -> @set.Set[String] { ldtk_world_store().ldtk_pending_transformed_level_iids } @@ -120,9 +120,7 @@ pub fn unregister_default_ldtk_entity() -> Unit { ///| pub fn clear_ldtk_entity_registrations() -> Unit { - for (key, _) in ldtk_entity_typed_registrations().to_array() { - ldtk_entity_typed_registrations().remove(key) - } + ldtk_entity_typed_registrations().clear() } ///| diff --git a/selene-core/src/ldtk/ldtk_world_types.mbt b/selene-core/src/ldtk/ldtk_world_types.mbt index 00a87d26..d0f8e684 100644 --- a/selene-core/src/ldtk/ldtk_world_types.mbt +++ b/selene-core/src/ldtk/ldtk_world_types.mbt @@ -216,15 +216,15 @@ priv struct LdtkWorldStore { String, (LdtkIntGridCellSpawn) -> Unit, ] - respawns : Map[@ecs.Entity, LdtkRespawn] - ldtk_pending_transformed_level_iids : Map[String, Bool] + respawns : @ecs.EntityTable[LdtkRespawn] + ldtk_pending_transformed_level_iids : @set.Set[String] } ///| let ldtk_world_store_key : @ecs.ResourceKey[LdtkWorldStore] = ResourceKey() ///| -fn LdtkWorldStore::LdtkWorldStore() -> LdtkWorldStore { +fn LdtkWorldStore::LdtkWorldStore(world : @ecs.World) -> LdtkWorldStore { { ldtk_entity_spawn_hooks: Map([]), ldtk_entity_layer_spawn_hooks: Map([]), @@ -236,15 +236,15 @@ fn LdtkWorldStore::LdtkWorldStore() -> LdtkWorldStore { ldtk_int_grid_default_spawn_hook: { val: None, }, ldtk_entity_typed_registrations: Map([]), ldtk_int_cell_typed_registrations: Map([]), - respawns: {}, - ldtk_pending_transformed_level_iids: Map([]), + respawns: EntityTable(world), + ldtk_pending_transformed_level_iids: Set([]), } } ///| fn ldtk_world_store() -> LdtkWorldStore { - ldtk_world_store_key.get_or_insert_with(@ecs.require_current_world(), _ => { - LdtkWorldStore() + ldtk_world_store_key.get_or_insert_with(@ecs.require_current_world(), world => { + LdtkWorldStore(world) }) } diff --git a/selene-core/src/ldtk/ldtk_world_utils.mbt b/selene-core/src/ldtk/ldtk_world_utils.mbt index b9740e91..0383bf5a 100644 --- a/selene-core/src/ldtk/ldtk_world_utils.mbt +++ b/selene-core/src/ldtk/ldtk_world_utils.mbt @@ -1,19 +1,20 @@ ///| fn ldtk_emit_pending_transformed_events() -> Unit { - for (iid, _) in ldtk_pending_transformed_level_iids().to_array() { + for iid in ldtk_pending_transformed_level_iids() { ldtk_level_event_bus.trigger(Transformed(iid), None) - ldtk_pending_transformed_level_iids().remove(iid) } + ldtk_pending_transformed_level_iids().clear() } ///| fn ldtk_cleanup_dead_spawned_levels(instance : LdtkWorldInstance) -> Unit { - for (level_iid, level_entity) in instance.spawned_levels.to_array() { - if !level_entity.is_alive() { - instance.spawned_levels.remove(level_iid) - ldtk_pending_transformed_level_iids().remove(level_iid) + instance.spawned_levels.retain((level_iid, level_entity) => { + if level_entity.is_alive() { + return true } - } + ldtk_pending_transformed_level_iids().remove(level_iid) + false + }) } ///| diff --git a/selene-core/src/ldtk/moon.pkg b/selene-core/src/ldtk/moon.pkg index f90af733..4be4f540 100644 --- a/selene-core/src/ldtk/moon.pkg +++ b/selene-core/src/ldtk/moon.pkg @@ -1,4 +1,5 @@ import { + "moonbitlang/core/set", "moonbitlang/core/debug", "Milky2018/selene/asset", "Milky2018/selene/ecs", diff --git a/selene-core/src/ldtk/pkg.generated.mbti b/selene-core/src/ldtk/pkg.generated.mbti index 26758d2a..dc7df362 100644 --- a/selene-core/src/ldtk/pkg.generated.mbti +++ b/selene-core/src/ldtk/pkg.generated.mbti @@ -11,6 +11,7 @@ import { "moonbitlang/core/debug", "moonbitlang/core/json", "moonbitlang/core/ref", + "moonbitlang/core/set", } // Values @@ -206,9 +207,9 @@ pub fn ldtk_level_spawn_behavior_world_translation(Bool) -> LdtkLevelSpawnBehavi pub let ldtk_level_spawned_event_bus : @event.Events[LdtkLevelSpawnedEvent] -pub fn ldtk_pending_transformed_level_iids() -> Map[String, Bool] +pub fn ldtk_pending_transformed_level_iids() -> @set.Set[String] -pub fn ldtk_respawns() -> Map[@ecs.Entity, LdtkRespawn] +pub fn ldtk_respawns() -> @ecs.EntityTable[LdtkRespawn] pub let ldtk_settings : @ref.Ref[LdtkSettings] diff --git a/selene-core/src/physics2d/physics.mbt b/selene-core/src/physics2d/physics.mbt index 0b61ca89..ac67f73e 100644 --- a/selene-core/src/physics2d/physics.mbt +++ b/selene-core/src/physics2d/physics.mbt @@ -68,8 +68,8 @@ pub fn shapes() -> @ecs.ComponentStore[ColliderShape] { ///| /// Frame-local resolved velocities after physics step. -pub fn resolved_velocities() -> Map[@ecs.Entity, LinearVelocity] { - @collision.resolved_velocities() +pub fn resolved_velocity(entity : @ecs.Entity) -> LinearVelocity? { + @collision.resolved_velocity(entity) } ///| diff --git a/selene-core/src/physics2d/pkg.generated.mbti b/selene-core/src/physics2d/pkg.generated.mbti index ce4e7af4..28265a18 100644 --- a/selene-core/src/physics2d/pkg.generated.mbti +++ b/selene-core/src/physics2d/pkg.generated.mbti @@ -78,7 +78,7 @@ pub fn reset_forces(@ecs.Entity, wake_up? : Bool) -> Unit pub fn reset_torques(@ecs.Entity, wake_up? : Bool) -> Unit -pub fn resolved_velocities() -> Map[@ecs.Entity, @velocity.Velocity] +pub fn resolved_velocity(@ecs.Entity) -> @velocity.Velocity? pub fn rigid_bodies() -> @ecs.ComponentStore[@Milky2018/selene/collision.RigidBody] diff --git a/selene-core/src/physics3d/physics3d_constraints_sync.mbt b/selene-core/src/physics3d/physics3d_constraints_sync.mbt index 4b21e4f0..ac23cf6f 100644 --- a/selene-core/src/physics3d/physics3d_constraints_sync.mbt +++ b/selene-core/src/physics3d/physics3d_constraints_sync.mbt @@ -3,9 +3,7 @@ fn sync_impulse_joints_to_rapier() -> Unit { let world = physics3d_world() world.impulse_joints = JointSet3DReal() world.rope_joints = RopeJointSet3DReal() - for (entity, _) in impulse_joint_handles().to_array() { - impulse_joint_handles().remove(entity) - } + impulse_joint_handles().clear() for entity, impulse_joint in impulse_joints() { if !entity.is_alive() || !impulse_joint.parent.is_alive() { continue @@ -104,9 +102,7 @@ fn sync_impulse_joints_to_rapier() -> Unit { fn sync_multibody_joints_to_rapier() -> Unit { let world = physics3d_world() world.multibody_joints = MultibodyJointSet3DReal() - for (entity, _) in multibody_joint_handles().to_array() { - multibody_joint_handles().remove(entity) - } + multibody_joint_handles().clear() for entity, multibody_joint in multibody_joints() { if !entity.is_alive() || !multibody_joint.parent.is_alive() { continue @@ -141,7 +137,7 @@ fn sync_character_controllers(delta : Double) -> Unit { } let world = physics3d_world() let dt = Float::from_double(delta) - for (entity, controller) in kinematic_character_controllers().to_array() { + for entity, controller in kinematic_character_controllers() { if !entity.is_alive() { continue } diff --git a/selene-core/src/physics3d/physics3d_shape_queries.mbt b/selene-core/src/physics3d/physics3d_shape_queries.mbt index 00756a2f..d4d9901b 100644 --- a/selene-core/src/physics3d/physics3d_shape_queries.mbt +++ b/selene-core/src/physics3d/physics3d_shape_queries.mbt @@ -348,7 +348,6 @@ fn resolve_collider_entity( } ///| -fn collider_key(handle : @collision.ColliderHandle3D) -> String { - let (id, generation) = handle.into_raw_parts() - "\{id}:\{generation}" +fn collider_key(handle : @collision.ColliderHandle3D) -> (Int32, Int32) { + handle.into_raw_parts() } diff --git a/selene-core/src/physics3d/physics3d_sync.mbt b/selene-core/src/physics3d/physics3d_sync.mbt index 6da46ee6..2da8b7db 100644 --- a/selene-core/src/physics3d/physics3d_sync.mbt +++ b/selene-core/src/physics3d/physics3d_sync.mbt @@ -38,16 +38,14 @@ pub fn kinematic_character_controllers() -> @ecs.ComponentStore[ } ///| -pub fn kinematic_character_controller_outputs() -> Map[ - @ecs.Entity, +pub fn kinematic_character_controller_outputs() -> @ecs.EntityTable[ KinematicCharacterControllerOutput, ] { physics3d_world_store().controller_outputs } ///| -pub fn kinematic_character_controller_collisions() -> Map[ - @ecs.Entity, +pub fn kinematic_character_controller_collisions() -> @ecs.EntityTable[ KinematicCharacterControllerCollisions, ] { physics3d_world_store().controller_collisions @@ -71,25 +69,23 @@ priv struct Physics3DWorld { ///| priv struct Physics3DWorldStore { world : Physics3DWorld - body_handles : Map[@ecs.Entity, RapierRigidBodyHandle] - collider_handles : Map[@ecs.Entity, RapierColliderHandle] - impulse_joint_handles : Map[@ecs.Entity, RapierImpulseJointHandle] - multibody_joint_handles : Map[@ecs.Entity, RapierMultibodyJointHandle] - controller_outputs : Map[@ecs.Entity, KinematicCharacterControllerOutput] - controller_collisions : Map[ - @ecs.Entity, + body_handles : @ecs.EntityTable[RapierRigidBodyHandle] + collider_handles : @ecs.EntityTable[RapierColliderHandle] + impulse_joint_handles : @ecs.EntityTable[RapierImpulseJointHandle] + multibody_joint_handles : @ecs.EntityTable[RapierMultibodyJointHandle] + controller_outputs : @ecs.EntityTable[KinematicCharacterControllerOutput] + controller_collisions : @ecs.EntityTable[ KinematicCharacterControllerCollisions, ] - collider_entities_by_key : Map[String, @ecs.Entity] + collider_entities_by_key : Map[(Int32, Int32), @ecs.Entity] } ///| -let physics3d_world_stores : Map[UInt32, Physics3DWorldStore] = Map([]) +let physics3d_world_store_key : @ecs.ResourceKey[Physics3DWorldStore] = ResourceKey() ///| fn physics3d_world_store() -> Physics3DWorldStore { - let world_id = @ecs.require_current_world().id() - physics3d_world_stores.get_or_init(world_id, () => { + physics3d_world_store_key.get_or_insert_with(@ecs.require_current_world(), world => { world: { pipeline: PhysicsPipeline3D(), integration: @dynamics.IntegrationParameters::default(), @@ -103,12 +99,12 @@ fn physics3d_world_store() -> Physics3DWorldStore { multibody_joints: MultibodyJointSet3DReal(), event_handler: EventHandler3D(), }, - body_handles: Map([]), - collider_handles: Map([]), - impulse_joint_handles: Map([]), - multibody_joint_handles: Map([]), - controller_outputs: {}, - controller_collisions: {}, + body_handles: EntityTable(world), + collider_handles: EntityTable(world), + impulse_joint_handles: EntityTable(world), + multibody_joint_handles: EntityTable(world), + controller_outputs: EntityTable(world), + controller_collisions: EntityTable(world), collider_entities_by_key: Map([]), }) } @@ -119,27 +115,27 @@ fn physics3d_world() -> Physics3DWorld { } ///| -fn body_handles() -> Map[@ecs.Entity, RapierRigidBodyHandle] { +fn body_handles() -> @ecs.EntityTable[RapierRigidBodyHandle] { physics3d_world_store().body_handles } ///| -fn collider_handles() -> Map[@ecs.Entity, RapierColliderHandle] { +fn collider_handles() -> @ecs.EntityTable[RapierColliderHandle] { physics3d_world_store().collider_handles } ///| -fn collider_entities_by_key() -> Map[String, @ecs.Entity] { +fn collider_entities_by_key() -> Map[(Int32, Int32), @ecs.Entity] { physics3d_world_store().collider_entities_by_key } ///| -fn impulse_joint_handles() -> Map[@ecs.Entity, RapierImpulseJointHandle] { +fn impulse_joint_handles() -> @ecs.EntityTable[RapierImpulseJointHandle] { physics3d_world_store().impulse_joint_handles } ///| -fn multibody_joint_handles() -> Map[@ecs.Entity, RapierMultibodyJointHandle] { +fn multibody_joint_handles() -> @ecs.EntityTable[RapierMultibodyJointHandle] { physics3d_world_store().multibody_joint_handles } diff --git a/selene-core/src/physics3d/physics3d_transform_bridge.mbt b/selene-core/src/physics3d/physics3d_transform_bridge.mbt index 023deb36..c44591d0 100644 --- a/selene-core/src/physics3d/physics3d_transform_bridge.mbt +++ b/selene-core/src/physics3d/physics3d_transform_bridge.mbt @@ -51,37 +51,33 @@ fn cleanup_world_components() -> Unit { let impulse_joint_handles = impulse_joint_handles() let multibody_joint_handles = multibody_joint_handles() let collider_entities_by_key = collider_entities_by_key() - for (entity, handle) in collider_handles.to_array() { - let missing_component = !colliders().contains(entity) - if !entity.is_alive() || - missing_component || - collider_transform(entity, attached_rigid_body_entity(entity)) is None { - world.colliders.remove(handle) |> ignore - collider_handles.remove(entity) - collider_entities_by_key.remove(collider_key(handle)) + collider_handles.retain((entity, handle) => { + if entity.is_alive() && + colliders().contains(entity) && + collider_transform(entity, attached_rigid_body_entity(entity)) is Some(_) { + return true } - } - - for (entity, handle) in body_handles.to_array() { - if !entity.is_alive() || - !rigid_bodies().contains(entity) || - current_world_transform(entity) is None { - world.bodies.remove(handle) |> ignore - body_handles.remove(entity) + ignore(world.colliders.remove(handle)) + collider_entities_by_key.remove(collider_key(handle)) + false + }) + body_handles.retain((entity, handle) => { + if entity.is_alive() && + rigid_bodies().contains(entity) && + current_world_transform(entity) is Some(_) { + return true } - } + ignore(world.bodies.remove(handle)) + false + }) - for (entity, _) in impulse_joint_handles.to_array() { - if !entity.is_alive() || !impulse_joints().contains(entity) { - impulse_joint_handles.remove(entity) - } - } + impulse_joint_handles.retain((entity, _) => { + entity.is_alive() && impulse_joints().contains(entity) + }) - for (entity, _) in multibody_joint_handles.to_array() { - if !entity.is_alive() || !multibody_joints().contains(entity) { - multibody_joint_handles.remove(entity) - } - } + multibody_joint_handles.retain((entity, _) => { + entity.is_alive() && multibody_joints().contains(entity) + }) } ///| diff --git a/selene-core/src/physics3d/physics3d_wbtest.mbt b/selene-core/src/physics3d/physics3d_wbtest.mbt index 07cf220e..77f72a83 100644 --- a/selene-core/src/physics3d/physics3d_wbtest.mbt +++ b/selene-core/src/physics3d/physics3d_wbtest.mbt @@ -128,8 +128,8 @@ test "query filter groups and contact force events work in 3d" { 2.0, ), ) - collider_entities_by_key().set("1:0", filtered) - collider_entities_by_key().set("2:0", excluded) + collider_entities_by_key().set((1, 0), filtered) + collider_entities_by_key().set((2, 0), excluded) collect_events() let reader : @event.EventReader[ContactForceEvent] = EventReader() let events = reader.read(contact_force_event_bus) diff --git a/selene-core/src/physics3d/pkg.generated.mbti b/selene-core/src/physics3d/pkg.generated.mbti index df532ceb..d7ff9b82 100644 --- a/selene-core/src/physics3d/pkg.generated.mbti +++ b/selene-core/src/physics3d/pkg.generated.mbti @@ -55,9 +55,9 @@ pub fn impulse_joint_handle(@ecs.Entity) -> @dynamics.JointHandle3DReal? pub fn impulse_joints() -> @ecs.ComponentStore[ImpulseJoint] -pub fn kinematic_character_controller_collisions() -> Map[@ecs.Entity, KinematicCharacterControllerCollisions] +pub fn kinematic_character_controller_collisions() -> @ecs.EntityTable[KinematicCharacterControllerCollisions] -pub fn kinematic_character_controller_outputs() -> Map[@ecs.Entity, KinematicCharacterControllerOutput] +pub fn kinematic_character_controller_outputs() -> @ecs.EntityTable[KinematicCharacterControllerOutput] pub fn kinematic_character_controllers() -> @ecs.ComponentStore[KinematicCharacterController] diff --git a/selene-core/src/render2d/frame.mbt b/selene-core/src/render2d/frame.mbt index d96cdfa1..5315756c 100644 --- a/selene-core/src/render2d/frame.mbt +++ b/selene-core/src/render2d/frame.mbt @@ -29,25 +29,22 @@ priv struct RenderFrameState2D { } ///| -let frame2d_by_world : Map[UInt32, RenderFrameState2D] = Map([]) +let frame2d_key : @ecs.ResourceKey[RenderFrameState2D] = ResourceKey() ///| fn frame2d() -> RenderFrameState2D { - let world_id = @ecs.require_current_world().id() - frame2d_by_world.get_or_init(world_id, fn() { - { - screen_world_commands: [], - screen_ui_commands: [], - camera_world_commands: Map([]), - camera_ui_commands: Map([]), - next_order: 0, - } + frame2d_key.get_or_insert_with(@ecs.require_current_world(), _ => { + screen_world_commands: [], + screen_ui_commands: [], + camera_world_commands: Map([]), + camera_ui_commands: Map([]), + next_order: 0, }) } ///| pub fn begin_frame2d_system(_delta : Double) -> Unit { - frame2d_by_world.set(@ecs.require_current_world().id(), { + frame2d_key.insert_in(@ecs.require_current_world(), { screen_world_commands: [], screen_ui_commands: [], camera_world_commands: Map([]), @@ -163,14 +160,14 @@ fn sorted_world_commands( ///| fn sorted_camera_entity_ids() -> Array[UInt32] { - let unique : Map[UInt32, Unit] = Map([]) + let unique : @set.Set[UInt32] = Set([]) for id in frame2d().camera_world_commands.keys() { - unique.set(id, ()) + unique.add(id) } for id in frame2d().camera_ui_commands.keys() { - unique.set(id, ()) + unique.add(id) } - let sorted = unique.keys().to_array() + let sorted = unique.to_array() sorted.sort_by(fn(lhs, rhs) { lhs.compare(rhs) }) sorted } diff --git a/selene-core/src/render2d/moon.pkg b/selene-core/src/render2d/moon.pkg index 477375f1..498e9850 100644 --- a/selene-core/src/render2d/moon.pkg +++ b/selene-core/src/render2d/moon.pkg @@ -1,4 +1,5 @@ import { + "moonbitlang/core/set", "moonbitlang/core/debug", "Milky2018/selene/camera", "Milky2018/selene/ecs", diff --git a/selene-core/src/render3d/extract.mbt b/selene-core/src/render3d/extract.mbt index 91251147..52377fcf 100644 --- a/selene-core/src/render3d/extract.mbt +++ b/selene-core/src/render3d/extract.mbt @@ -21,12 +21,11 @@ priv struct Render3DWorldState { } ///| -let render3d_world_states : Map[UInt32, Render3DWorldState] = Map([]) +let render3d_world_state_key : @ecs.ResourceKey[Render3DWorldState] = ResourceKey() ///| fn render3d_world_state() -> Render3DWorldState { - let world_id = @ecs.require_current_world().id() - render3d_world_states.get_or_init(world_id, () => { + render3d_world_state_key.get_or_insert_with(@ecs.require_current_world(), _ => { ambient_light: None, directional_shadow_map: DirectionalLightShadowMap3D(), point_shadow_map: PointLightShadowMap3D(), diff --git a/selene-core/src/render3d_pipeline/prepare.mbt b/selene-core/src/render3d_pipeline/prepare.mbt index 9a83e42c..cacf3c5c 100644 --- a/selene-core/src/render3d_pipeline/prepare.mbt +++ b/selene-core/src/render3d_pipeline/prepare.mbt @@ -13,18 +13,19 @@ // limitations under the License. ///| -let prepared_frame3d_by_world : Map[UInt32, @render3d.RenderFrame3D] = Map([]) +let prepared_frame3d_key : @ecs.ResourceKey[@render3d.RenderFrame3D] = ResourceKey() ///| fn prepared_frame3d() -> @render3d.RenderFrame3D { - let world_id = @ecs.require_current_world().id() - prepared_frame3d_by_world.get_or_init(world_id, () => RenderFrame3D()) + prepared_frame3d_key.get_or_insert_with(@ecs.require_current_world(), _ => { + RenderFrame3D() + }) } ///| pub fn render3d_prepare_system(_delta : Double) -> Unit { - prepared_frame3d_by_world.set( - @ecs.require_current_world().id(), + prepared_frame3d_key.insert_in( + @ecs.require_current_world(), @render3d.get_extracted_frame3d(), ) } diff --git a/selene-core/src/runtime_debug/deterministic_input.mbt b/selene-core/src/runtime_debug/deterministic_input.mbt index 6aa30bca..caebe411 100644 --- a/selene-core/src/runtime_debug/deterministic_input.mbt +++ b/selene-core/src/runtime_debug/deterministic_input.mbt @@ -22,16 +22,16 @@ pub(all) enum InputInjectionEvent { } ///| -let deterministic_mode_by_world : Map[UInt32, DeterministicModeConfig] = Map([]) +let deterministic_mode_key : @ecs.ResourceKey[DeterministicModeConfig] = ResourceKey() ///| -let rng_state_by_world : Map[UInt32, UInt32] = Map([]) +let rng_state_key : @ecs.ResourceKey[UInt32] = ResourceKey() ///| -let queued_inputs_by_world : Map[UInt32, Array[@inputs.InputSnapshot]] = Map([]) +let queued_inputs_key : @ecs.ResourceKey[Array[@inputs.InputSnapshot]] = ResourceKey() ///| -let staged_input_by_world : Map[UInt32, @inputs.InputSnapshot] = Map([]) +let staged_input_key : @ecs.ResourceKey[@inputs.InputSnapshot] = ResourceKey() ///| fn DeterministicModeConfig::DeterministicModeConfig() -> DeterministicModeConfig { @@ -45,23 +45,21 @@ fn DeterministicModeConfig::DeterministicModeConfig() -> DeterministicModeConfig ///| pub fn set_deterministic_mode(config : DeterministicModeConfig) -> Unit { - let world_id = current_world_id() - deterministic_mode_by_world.set(world_id, config) - rng_state_by_world.set(world_id, config.rng_seed) + deterministic_mode_key.insert_in(current_world(), config) + rng_state_key.insert_in(current_world(), config.rng_seed) } ///| pub fn deterministic_mode() -> DeterministicModeConfig { - deterministic_mode_by_world.get_or_init(current_world_id(), () => { + deterministic_mode_key.get_or_insert_with(current_world(), _ => { DeterministicModeConfig() }) } ///| pub fn clear_deterministic_mode() -> Unit { - let world_id = current_world_id() - deterministic_mode_by_world.remove(world_id) - rng_state_by_world.remove(world_id) + deterministic_mode_key.insert_in(current_world(), DeterministicModeConfig()) + rng_state_key.insert_in(current_world(), 0U) } ///| @@ -81,20 +79,19 @@ pub fn deterministic_ordering_enabled() -> Bool { ///| pub fn set_atlas_overlay_enabled(enabled : Bool) -> Unit { - atlas_overlay_enabled_by_world.set(current_world_id(), enabled) + atlas_overlay_enabled_key.insert_in(current_world(), enabled) } ///| pub fn atlas_overlay_enabled() -> Bool { - atlas_overlay_enabled_by_world.get(current_world_id()).unwrap_or(false) + atlas_overlay_enabled_key.get_in(current_world()).unwrap_or(false) } ///| pub fn set_rng_seed(seed : UInt32) -> Unit { - let world_id = current_world_id() let mode = deterministic_mode() - deterministic_mode_by_world.set(world_id, { ..mode, rng_seed: seed, }) - rng_state_by_world.set(world_id, seed) + deterministic_mode_key.insert_in(current_world(), { ..mode, rng_seed: seed, }) + rng_state_key.insert_in(current_world(), seed) } ///| @@ -104,8 +101,7 @@ pub fn rng_seed() -> UInt32 { ///| pub fn next_deterministic_u32() -> UInt32 { - let world_id = current_world_id() - let mut x = rng_state_by_world.get_or_init(world_id, () => { + let mut x = rng_state_key.get_or_insert_with(current_world(), _ => { deterministic_mode().rng_seed }) if x == 0U { @@ -114,7 +110,7 @@ pub fn next_deterministic_u32() -> UInt32 { x = x ^ (x << 13) x = x ^ (x >> 17) x = x ^ (x << 5) - rng_state_by_world.set(world_id, x) + rng_state_key.insert_in(current_world(), x) x } @@ -173,12 +169,12 @@ fn copy_snapshot(snapshot : @inputs.InputSnapshot) -> @inputs.InputSnapshot { ///| fn staged_snapshot() -> @inputs.InputSnapshot { - staged_input_by_world.get_or_init(current_world_id(), () => InputSnapshot()) + staged_input_key.get_or_insert_with(current_world(), _ => InputSnapshot()) } ///| fn queued_inputs() -> Array[@inputs.InputSnapshot] { - queued_inputs_by_world.get_or_init(current_world_id(), () => []) + queued_inputs_key.get_or_insert_with(current_world(), _ => []) } ///| @@ -241,6 +237,6 @@ pub fn consume_injected_input_or( for index in 1.. FramePerformanceMetrics { let world = current_world() - frame_metrics_by_world.get_or_init(world.id(), () => { + frame_metrics_key.get_or_insert_with(world, _ => { FramePerformanceMetrics(world) }) } @@ -46,7 +45,7 @@ fn ensure_metrics() -> FramePerformanceMetrics { ///| pub fn begin_frame_metrics() -> Unit { let world = current_world() - frame_metrics_by_world.set(world.id(), { + frame_metrics_key.insert_in(world, { frame_index: world.frame_index(), fixed_step_index: world.fixed_step_index(), fixed_steps_this_frame: 0, @@ -61,9 +60,8 @@ pub fn begin_frame_metrics() -> Unit { ///| pub fn note_fixed_step(delta : Double) -> Unit { - let world_id = current_world_id() let metrics = ensure_metrics() - frame_metrics_by_world.set(world_id, { + frame_metrics_key.insert_in(current_world(), { ..metrics, fixed_steps_this_frame: metrics.fixed_steps_this_frame + 1, fixed_delta_total: metrics.fixed_delta_total + @cmp.maximum(0.0, delta), @@ -72,9 +70,8 @@ pub fn note_fixed_step(delta : Double) -> Unit { ///| pub fn note_update(update_delta : Double, entity_count : Int32) -> Unit { - let world_id = current_world_id() let metrics = ensure_metrics() - frame_metrics_by_world.set(world_id, { + frame_metrics_key.insert_in(current_world(), { ..metrics, update_delta: @cmp.maximum(0.0, update_delta), entity_count: @cmp.maximum(0, entity_count), @@ -87,7 +84,6 @@ pub fn note_render( draw2d_count : Int32, draw3d_count : Int32, ) -> Unit { - let world_id = current_world_id() let metrics = ensure_metrics() let next_metrics = { ..metrics, @@ -95,8 +91,10 @@ pub fn note_render( draw2d_count: @cmp.maximum(0, draw2d_count), draw3d_count: @cmp.maximum(0, draw3d_count), } - frame_metrics_by_world.set(world_id, next_metrics) - let history = frame_metrics_history_by_world.get_or_init(world_id, () => []) + frame_metrics_key.insert_in(current_world(), next_metrics) + let history = frame_metrics_history_key.get_or_insert_with(current_world(), _ => { + [] + }) history.push({ ..next_metrics, }) let max_samples = 120 if history.length() > max_samples { @@ -116,7 +114,5 @@ pub fn latest_metrics() -> FramePerformanceMetrics { ///| pub fn rolling_metrics() -> Array[FramePerformanceMetrics] { - frame_metrics_history_by_world - .get_or_init(current_world_id(), () => []) - .copy() + frame_metrics_history_key.get_or_insert_with(current_world(), _ => []).copy() } diff --git a/selene-core/src/runtime_debug/render_capture.mbt b/selene-core/src/runtime_debug/render_capture.mbt index a9778fd3..65386801 100644 --- a/selene-core/src/runtime_debug/render_capture.mbt +++ b/selene-core/src/runtime_debug/render_capture.mbt @@ -108,11 +108,10 @@ pub(all) struct FrameCaptureArtifact { pub extend FrameCaptureArtifact with @moonbitlang/core/debug.Debug::{to_repr} ///| -let render_submission_by_world : Map[UInt32, RenderSubmissionDebug] = Map([]) +let render_submission_key : @ecs.ResourceKey[RenderSubmissionDebug] = ResourceKey() ///| -let latest_render_frame_by_world : Map[UInt32, @render_pipeline.RenderFrame] = Map([], -) +let latest_render_frame_key : @ecs.ResourceKey[@render_pipeline.RenderFrame] = ResourceKey() ///| fn draw2d_info( @@ -256,8 +255,8 @@ pub fn record_render_submission( } let draw3d = frame.frame3d.items.map(draw3d_info) let world = current_world() - latest_render_frame_by_world.set(world.id(), frame) - render_submission_by_world.set(world.id(), { + latest_render_frame_key.insert_in(world, frame) + render_submission_key.insert_in(world, { frame_index: world.frame_index(), fixed_step_index: world.fixed_step_index(), draw2d, @@ -267,7 +266,7 @@ pub fn record_render_submission( ///| pub fn latest_render_submission() -> RenderSubmissionDebug? { - render_submission_by_world.get(current_world_id()) + render_submission_key.get_in(current_world()) } ///| @@ -310,9 +309,7 @@ fn metrics_export( pub fn capture_last_frame_metadata() -> FrameCaptureMetadata? { guard latest_render_submission() is Some(submission) else { return None } let draw2d = submission.draw2d.map(draw2d_metadata_entry) - let metrics = frame_metrics_by_world - .get(current_world_id()) - .map(metrics_export) + let metrics = frame_metrics_key.get_in(current_world()).map(metrics_export) Some({ frame_index: submission.frame_index, fixed_step_index: submission.fixed_step_index, @@ -366,7 +363,7 @@ pub fn capture_last_frame_with_metadata( ///| pub fn render_last_frame_offscreen_png(width : Int32, height : Int32) -> Bytes? { - guard latest_render_frame_by_world.get(current_world_id()) is Some(frame) else { + guard latest_render_frame_key.get_in(current_world()) is Some(frame) else { return None } @platform_render.render_offscreen_png(frame, width, height) diff --git a/selene-core/src/runtime_debug/runtime_debug_wbtest.mbt b/selene-core/src/runtime_debug/runtime_debug_wbtest.mbt index ef5d13c6..940ae95a 100644 --- a/selene-core/src/runtime_debug/runtime_debug_wbtest.mbt +++ b/selene-core/src/runtime_debug/runtime_debug_wbtest.mbt @@ -318,3 +318,40 @@ test "export texture region png returns false for missing image path" { ) }) } + +///| +test "World-owned metrics RNG and injected input remain isolated" { + let previous = @ecs.current_world() + defer (match previous { + Some(world) => @ecs.set_current_world(world) + None => @ecs.clear_current_world() + }) + let first = @ecs.World() + let second = @ecs.World() + @ecs.set_current_world(first) + set_rng_seed(123U) + let first_value = next_deterministic_u32() + set_atlas_overlay_enabled(true) + queue_input_snapshot(InputSnapshot()) + begin_frame_metrics() + note_fixed_step(0.25) + note_render(0.1, 3, 4) + @ecs.set_current_world(second) + assert_eq(queued_input_count(), 0) + assert_false(atlas_overlay_enabled()) + assert_eq(rolling_metrics().length(), 0) + assert_eq(latest_metrics().fixed_steps_this_frame, 0) + set_rng_seed(123U) + assert_eq(next_deterministic_u32(), first_value) + let second_value = next_deterministic_u32() + @ecs.set_current_world(first) + assert_eq(next_deterministic_u32(), second_value) + assert_eq(queued_input_count(), 1) + assert_true(atlas_overlay_enabled()) + assert_eq(rolling_metrics().length(), 1) + assert_eq(latest_metrics().draw2d_count, 3) + clear_deterministic_mode() + assert_eq(rng_seed(), 0U) + @ecs.set_current_world(second) + assert_eq(rng_seed(), 123U) +} diff --git a/selene-core/src/runtime_debug/snapshot_inspector_overlay.mbt b/selene-core/src/runtime_debug/snapshot_inspector_overlay.mbt index 45883d42..127b3b14 100644 --- a/selene-core/src/runtime_debug/snapshot_inspector_overlay.mbt +++ b/selene-core/src/runtime_debug/snapshot_inspector_overlay.mbt @@ -133,7 +133,7 @@ pub type SnapshotProvider = (@ecs.World) -> String let snapshot_providers : Map[String, SnapshotProvider] = Map([]) ///| -let atlas_overlay_enabled_by_world : Map[UInt32, Bool] = Map([]) +let atlas_overlay_enabled_key : @ecs.ResourceKey[Bool] = ResourceKey() ///| pub fn register_snapshot_provider( diff --git a/selene-core/src/runtime_debug/world.mbt b/selene-core/src/runtime_debug/world.mbt index 545f1780..54b09ff8 100644 --- a/selene-core/src/runtime_debug/world.mbt +++ b/selene-core/src/runtime_debug/world.mbt @@ -2,8 +2,3 @@ fn current_world() -> @ecs.World { @ecs.require_current_world() } - -///| -fn current_world_id() -> UInt32 { - current_world().id() -} diff --git a/selene-core/src/scene/spawner.mbt b/selene-core/src/scene/spawner.mbt index 7aebb143..08a99cf7 100644 --- a/selene-core/src/scene/spawner.mbt +++ b/selene-core/src/scene/spawner.mbt @@ -23,12 +23,12 @@ pub extend SceneInstanceReadyEvent with @moonbitlang/core/debug.Debug::{to_repr} pub extend SceneInstanceReadyEvent with Eq::{not_equal, equal} ///| -let scene_instances_key : @ecs.ResourceKey[Map[@ecs.Entity, SceneHandle]] = ResourceKey() +let scene_instances_key : @ecs.ResourceKey[@ecs.EntityTable[SceneHandle]] = ResourceKey() ///| -fn scene_instances() -> Map[@ecs.Entity, SceneHandle] { - scene_instances_key.get_or_insert_with(@ecs.require_current_world(), _ => { - Map([]) +fn scene_instances() -> @ecs.EntityTable[SceneHandle] { + scene_instances_key.get_or_insert_with(@ecs.require_current_world(), world => { + EntityTable(world) }) } diff --git a/selene-core/src/scene3d/gltf_parse_node.mbt b/selene-core/src/scene3d/gltf_parse_node.mbt index 16d1b152..b80288a9 100644 --- a/selene-core/src/scene3d/gltf_parse_node.mbt +++ b/selene-core/src/scene3d/gltf_parse_node.mbt @@ -195,7 +195,7 @@ fn max_attribute_set_index( prefix : String, ) -> Int32 { let mut max_index = -1 - for (key, _) in attributes_object.to_array() { + for key in attributes_object.keys() { if !key.has_prefix(prefix) { continue } diff --git a/selene-core/src/scene3d/scene_instantiate.mbt b/selene-core/src/scene3d/scene_instantiate.mbt index 2d5bbf99..eb79f5f9 100644 --- a/selene-core/src/scene3d/scene_instantiate.mbt +++ b/selene-core/src/scene3d/scene_instantiate.mbt @@ -1,7 +1,7 @@ ///| fn resolve_scene_skin_bindings( template : SceneTemplate, - node_entities : Map[Int32, @ecs.Entity], + node_entities : Array[@ecs.Entity?], pending_skin_bindings : Array[PendingSkinBinding], ) -> Unit { for pending in pending_skin_bindings { @@ -13,7 +13,8 @@ fn resolve_scene_skin_bindings( let joint_entities : Array[@ecs.Entity] = [] let mut complete = true for joint_node_index in skin.joints { - guard node_entities.get(joint_node_index) is Some(joint_entity) else { + guard node_entities.get(joint_node_index).unwrap_or(None) + is Some(joint_entity) else { complete = false break } @@ -98,7 +99,7 @@ fn instantiate_scene_node( node_index : Int32, parent : @ecs.Entity, root_entity : @ecs.Entity, - node_entities : Map[Int32, @ecs.Entity], + node_entities : Array[@ecs.Entity?], pending_skin_bindings : Array[PendingSkinBinding], parts : Map[String, @ecs.Entity], parent_path : String, @@ -156,7 +157,7 @@ fn instantiate_scene_node( } let entity = draft.spawn(parent~) parts.set(entity_path, entity) - node_entities.set(node_index, entity) + node_entities[node_index] = Some(entity) if single_renderer is Some((renderer, skinned)) { if node.skin_index is Some(skin_index) && skinned is Some(skinned) && diff --git a/selene-core/src/scene3d/scene_load_api.mbt b/selene-core/src/scene3d/scene_load_api.mbt index 5199379e..efece1a8 100644 --- a/selene-core/src/scene3d/scene_load_api.mbt +++ b/selene-core/src/scene3d/scene_load_api.mbt @@ -120,7 +120,10 @@ pub fn instantiate_scene_instance( draft.add(@animation.AnimationTransitions()) } let root = draft.spawn(parent?) - let node_entities : Map[Int32, @ecs.Entity] = Map([]) + let node_entities : Array[@ecs.Entity?] = Array::make( + template.nodes.length(), + None, + ) let pending_skin_bindings : Array[PendingSkinBinding] = [] for root_order, node_index in template.roots { instantiate_scene_node( diff --git a/selene-core/src/text2d/layout.mbt b/selene-core/src/text2d/layout.mbt index 88f8e5d7..6d14c877 100644 --- a/selene-core/src/text2d/layout.mbt +++ b/selene-core/src/text2d/layout.mbt @@ -24,26 +24,26 @@ priv struct CachedTextLayout2d { ///| priv struct Text2dWorldStore { - text_layout_caches : Map[@ecs.Entity, CachedTextLayout2d] + text_layout_caches : @ecs.EntityTable[CachedTextLayout2d] } ///| let text2d_world_store_key : @ecs.ResourceKey[Text2dWorldStore] = ResourceKey() ///| -fn Text2dWorldStore::Text2dWorldStore() -> Text2dWorldStore { - { text_layout_caches: Map([]), } +fn Text2dWorldStore::Text2dWorldStore(world : @ecs.World) -> Text2dWorldStore { + { text_layout_caches: EntityTable(world), } } ///| fn text2d_world_store() -> Text2dWorldStore { - text2d_world_store_key.get_or_insert_with(@ecs.require_current_world(), _ => { - Text2dWorldStore() + text2d_world_store_key.get_or_insert_with(@ecs.require_current_world(), world => { + Text2dWorldStore(world) }) } ///| -fn text_layout_caches() -> Map[@ecs.Entity, CachedTextLayout2d] { +fn text_layout_caches() -> @ecs.EntityTable[CachedTextLayout2d] { text2d_world_store().text_layout_caches } diff --git a/selene-core/src/text2d/render.mbt b/selene-core/src/text2d/render.mbt index cac1b07a..936e5c9f 100644 --- a/selene-core/src/text2d/render.mbt +++ b/selene-core/src/text2d/render.mbt @@ -12,11 +12,7 @@ fn anchor_origin(anchor : @sprite.Anchor, size : @math.Vec2) -> @math.Vec2 { ///| pub fn render_text2d_system(delta : Double) -> Unit { ignore(delta) - for (entity, _) in text_layout_caches().to_array() { - if !entity.is_alive() { - text_layout_caches().remove(entity) - } - } + text_layout_caches().retain((entity, _) => entity.is_alive()) let camera_views = @camera.active_camera2d_views() let camera_extract = @culling2d.CameraExtract2dContext(camera_views) for entity, text2d in text2ds() { diff --git a/selene-core/src/tiled/moon.pkg b/selene-core/src/tiled/moon.pkg index 3051df05..2bd4a97c 100644 --- a/selene-core/src/tiled/moon.pkg +++ b/selene-core/src/tiled/moon.pkg @@ -1,4 +1,5 @@ import { + "moonbitlang/core/set", "Milky2018/selene/window", "Milky2018/selene/render2d_types", "Milky2018/zstd", diff --git a/selene-core/src/tiled/world.mbt b/selene-core/src/tiled/world.mbt index 868ffa78..01fa8494 100644 --- a/selene-core/src/tiled/world.mbt +++ b/selene-core/src/tiled/world.mbt @@ -415,22 +415,22 @@ fn parse_tiled_world_patterns( ///| fn tiled_world_collect_maps(world : TiledWorld) -> Array[TiledWorldMap] { - let resolved_paths : Map[String, Bool] = Map([]) + let resolved_paths : @set.Set[String] = Set([]) let maps : Array[TiledWorldMap] = [] for world_map in world.maps { let resolved = world.resolve_map_path(world_map.file_name) - if resolved_paths.get(resolved) is Some(_) { + if resolved_paths.contains(resolved) { continue } - resolved_paths.set(resolved, true) + resolved_paths.add(resolved) maps.push(world_map) } for world_map in tiled_world_expand_patterns(world) { let resolved = world.resolve_map_path(world_map.file_name) - if resolved_paths.get(resolved) is Some(_) { + if resolved_paths.contains(resolved) { continue } - resolved_paths.set(resolved, true) + resolved_paths.add(resolved) maps.push(world_map) } maps diff --git a/selene-core/src/touch_controls/runtime.mbt b/selene-core/src/touch_controls/runtime.mbt index e1a667bb..0d251059 100644 --- a/selene-core/src/touch_controls/runtime.mbt +++ b/selene-core/src/touch_controls/runtime.mbt @@ -1,18 +1,15 @@ ///| -let touch_control_stores : Map[UInt32, TouchControlsWorldStore] = Map([]) +let touch_control_store_key : @ecs.ResourceKey[TouchControlsWorldStore] = ResourceKey() ///| fn store() -> TouchControlsWorldStore { - let world_id = @ecs.require_current_world().id() - touch_control_stores.get_or_init(world_id, fn() { - { - sticks: Map([]), - buttons: Map([]), - stick_runtimes: Map([]), - button_runtimes: Map([]), - enabled: true, - visible: true, - } + touch_control_store_key.get_or_insert_with(@ecs.require_current_world(), _ => { + sticks: Map([]), + buttons: Map([]), + stick_runtimes: Map([]), + button_runtimes: Map([]), + enabled: true, + visible: true, }) } diff --git a/selene-core/src/ui/interaction.mbt b/selene-core/src/ui/interaction.mbt index 00851a6e..2fc95efc 100644 --- a/selene-core/src/ui/interaction.mbt +++ b/selene-core/src/ui/interaction.mbt @@ -96,12 +96,11 @@ priv struct UiInteractionRuntime { } ///| -let ui_interaction_runtimes : Map[UInt32, UiInteractionRuntime] = Map([]) +let ui_interaction_runtime_key : @ecs.ResourceKey[UiInteractionRuntime] = ResourceKey() ///| fn ui_interaction_runtime() -> UiInteractionRuntime { - let world_id = @ecs.require_current_world().id() - ui_interaction_runtimes.get_or_init(world_id, () => { + ui_interaction_runtime_key.get_or_insert_with(@ecs.require_current_world(), _ => { hovered_entity: None, pressed_entity: None, pressed_pointer: None, diff --git a/selene-core/src/ui/layout.mbt b/selene-core/src/ui/layout.mbt index 1b848b43..a7fbe302 100644 --- a/selene-core/src/ui/layout.mbt +++ b/selene-core/src/ui/layout.mbt @@ -445,14 +445,15 @@ fn cleanup_dead_ui_state() -> Unit { fn apply_layout_recursive( entity : @ecs.Entity, chicle : @tree.ChicleTree[@ecs.Entity], - entity_to_node_id : Map[@ecs.Entity, Int32], + layout_nodes : @ecs.EntityTable[UiLayoutNodeRuntime], parent_layout_origin : @math.Vec2, parent_clip : @math.Rect?, inherited_use_rounding : Bool, layout_space : UiLayoutSpace, projected : Set[@ecs.Entity], ) -> Unit { - guard entity_to_node_id.get(entity) is Some(node_id) else { return } + guard layout_nodes.get(entity) is Some(runtime_node) else { return } + let node_id = runtime_node.node_id guard nodes().get(entity) is Some(node) else { return } let effective_layout_space = match ui_target_cameras().get(entity) { Some(target) => ui_layout_space(Some(target.camera)) @@ -562,8 +563,8 @@ fn apply_layout_recursive( ) for child in ui_children(entity) { apply_layout_recursive( - child, chicle, entity_to_node_id, next_origin, current_clip, use_rounding, - effective_layout_space, projected, + child, chicle, layout_nodes, next_origin, current_clip, use_rounding, effective_layout_space, + projected, ) } } diff --git a/selene-core/src/ui/layout_runtime.mbt b/selene-core/src/ui/layout_runtime.mbt index d2b61771..dbbd7f7c 100644 --- a/selene-core/src/ui/layout_runtime.mbt +++ b/selene-core/src/ui/layout_runtime.mbt @@ -44,6 +44,7 @@ priv struct UiChicleStyleSnapshot { ///| priv struct UiLayoutNodeRuntime { + node_id : Int32 mut source_node : Node mut chicle_style : UiChicleStyleSnapshot mut measure : UiMeasureSnapshot @@ -71,9 +72,8 @@ priv struct UiLayoutRootRuntime { ///| priv struct UiLayoutRuntime { tree : @tree.ChicleTree[@ecs.Entity] - node_ids : Map[@ecs.Entity, Int32] - nodes : Map[@ecs.Entity, UiLayoutNodeRuntime] - roots : Map[@ecs.Entity, UiLayoutRootRuntime] + nodes : @ecs.EntityTable[UiLayoutNodeRuntime] + roots : @ecs.EntityTable[UiLayoutRootRuntime] mut layout_revision : UInt32 mut projection_revision : UInt32 mut stacking_revision : UInt32 @@ -87,16 +87,14 @@ priv struct UiLayoutDirty { } ///| -let ui_layout_runtimes : Map[UInt32, UiLayoutRuntime] = Map([]) +let ui_layout_runtime_key : @ecs.ResourceKey[UiLayoutRuntime] = ResourceKey() ///| fn ui_layout_runtime() -> UiLayoutRuntime { - let world_id = @ecs.require_current_world().id() - ui_layout_runtimes.get_or_init(world_id, () => { + ui_layout_runtime_key.get_or_insert_with(@ecs.require_current_world(), world => { tree: ChicleTree(), - node_ids: Map([]), - nodes: Map([]), - roots: Map([]), + nodes: EntityTable(world), + roots: EntityTable(world), layout_revision: 0U, projection_revision: 0U, stacking_revision: 0U, @@ -338,7 +336,7 @@ fn sync_layout_node( let stack = ui_stack_snapshot(entity, node) let (node_id, state) = match runtime.nodes.get(entity) { Some(state) => { - let node_id = runtime.node_ids.get(entity).unwrap() + let node_id = state.node_id if node != state.source_node { let chicle_style = chicle_style_snapshot(node) if chicle_style != state.chicle_style { @@ -369,6 +367,7 @@ fn sync_layout_node( entity, ) let state = { + node_id, source_node: clone_layout_node(node), chicle_style: chicle_style_snapshot(node), measure, @@ -376,7 +375,6 @@ fn sync_layout_node( stack, children: [], } - runtime.node_ids.set(entity, node_id) runtime.nodes.set(entity, state) dirty.layout = true dirty.projection = true @@ -421,10 +419,9 @@ fn remove_stale_layout_nodes( } } for entity in stale { - if runtime.node_ids.get(entity) is Some(node_id) { - remove_chicle_node(runtime, node_id) + if runtime.nodes.get(entity) is Some(state) { + remove_chicle_node(runtime, state.node_id) } - runtime.node_ids.remove(entity) runtime.nodes.remove(entity) dirty.layout = true dirty.projection = true @@ -439,7 +436,8 @@ fn sync_layout_roots( dirty : UiLayoutDirty, ) -> Unit { for root in roots { - guard runtime.node_ids.get(root) is Some(root_node_id) else { continue } + guard runtime.nodes.get(root) is Some(root_node) else { continue } + let root_node_id = root_node.node_id let snapshot = ui_root_snapshot(root) match runtime.roots.get(root) { Some(root_runtime) => { @@ -545,7 +543,7 @@ fn project_layout( apply_layout_recursive( root, runtime.tree, - runtime.node_ids, + runtime.nodes, @math.Vec2::zero(), None, true, diff --git a/selene-core/src/ui/layout_runtime_wbtest.mbt b/selene-core/src/ui/layout_runtime_wbtest.mbt index 940ca9db..dd16da11 100644 --- a/selene-core/src/ui/layout_runtime_wbtest.mbt +++ b/selene-core/src/ui/layout_runtime_wbtest.mbt @@ -190,3 +190,31 @@ test "retained UI compares normalized Chicle styles" { cleanup_layout_test_entity(entity) ui_layout_system(0.0) } + +///| +test "layout frees the old Chicle node when a deleted entity slot is reused" { + let previous = @ecs.current_world() + defer (match previous { + Some(world) => @ecs.set_current_world(world) + None => @ecs.clear_current_world() + }) + let world = @ecs.World() + @ecs.set_current_world(world) + let old = world.spawn1(Node(width=Val::px(10.0))) + ui_layout_system(0.0) + let runtime = ui_layout_runtime() + let old_node = runtime.nodes.get(old).unwrap().node_id + ignore(old.delete()) + let replacement = world.spawn1(Node(width=Val::px(30.0))) + assert_eq(old.slot_index(), replacement.slot_index()) + ui_layout_system(0.0) + assert_true(computed_ui_node(old) is None) + assert_eq(computed_ui_node(replacement).unwrap().size.x, 30.0) + assert_false(runtime.nodes.contains(old)) + assert_eq(runtime.nodes.length(), 1) + try runtime.tree.dirty(old_node) catch { + _ => () + } noraise { + _ => fail("deleted Chicle node was not released") + } +} diff --git a/selene-core/src/ui/model.mbt b/selene-core/src/ui/model.mbt index 93da1fb7..66395e99 100644 --- a/selene-core/src/ui/model.mbt +++ b/selene-core/src/ui/model.mbt @@ -12,17 +12,16 @@ pub extend UiScaleMode with @moonbitlang/core/debug.Debug::{to_repr} pub extend UiScaleMode with Eq::{not_equal, equal} ///| -let ui_scale_modes : Map[UInt32, UiScaleMode] = Map([]) +let ui_scale_mode_key : @ecs.ResourceKey[UiScaleMode] = ResourceKey() ///| fn ui_scale_mode() -> UiScaleMode { - let world_id = @ecs.require_current_world().id() - ui_scale_modes.get_or_init(world_id, fn() { Screen }) + ui_scale_mode_key.get_or_insert_with(@ecs.require_current_world(), _ => Screen) } ///| pub fn set_ui_scale_mode(mode : UiScaleMode) -> Unit { - ui_scale_modes.set(@ecs.require_current_world().id(), mode) + ui_scale_mode_key.insert_in(@ecs.require_current_world(), mode) } ///| @@ -960,12 +959,12 @@ pub fn RelativeCursorPosition::mouse_over( ///| priv struct UiModelWorldStore { - scroll_positions : Map[@ecs.Entity, ScrollPosition] - tree_orders : Map[@ecs.Entity, Int32] - geometry : Map[@ecs.Entity, UiGeometry] - calculated_clips : Map[@ecs.Entity, CalculatedClip] - focuseds : Map[@ecs.Entity, Focused] - interactions : Map[@ecs.Entity, Interaction] + scroll_positions : @ecs.EntityTable[ScrollPosition] + tree_orders : @ecs.EntityTable[Int32] + geometry : @ecs.EntityTable[UiGeometry] + calculated_clips : @ecs.EntityTable[CalculatedClip] + focuseds : @ecs.EntityTable[Focused] + interactions : @ecs.EntityTable[Interaction] ui_stack_entities : Array[@ecs.Entity] extracted_entities : Array[@ecs.Entity] } @@ -974,14 +973,16 @@ priv struct UiModelWorldStore { let ui_model_world_store_key : @ecs.ResourceKey[UiModelWorldStore] = ResourceKey() ///| -fn UiModelWorldStore::UiModelWorldStore() -> UiModelWorldStore { +fn UiModelWorldStore::UiModelWorldStore( + world : @ecs.World, +) -> UiModelWorldStore { { - scroll_positions: {}, - tree_orders: {}, - geometry: {}, - calculated_clips: {}, - focuseds: {}, - interactions: {}, + scroll_positions: EntityTable(world), + tree_orders: EntityTable(world), + geometry: EntityTable(world), + calculated_clips: EntityTable(world), + focuseds: EntityTable(world), + interactions: EntityTable(world), ui_stack_entities: [], extracted_entities: [], } @@ -989,8 +990,8 @@ fn UiModelWorldStore::UiModelWorldStore() -> UiModelWorldStore { ///| fn ui_model_world_store() -> UiModelWorldStore { - ui_model_world_store_key.get_or_insert_with(@ecs.require_current_world(), _ => { - UiModelWorldStore() + ui_model_world_store_key.get_or_insert_with(@ecs.require_current_world(), world => { + UiModelWorldStore(world) }) } @@ -1006,7 +1007,7 @@ priv struct UiGeometry { } ///| -fn ui_geometry() -> Map[@ecs.Entity, UiGeometry] { +fn ui_geometry() -> @ecs.EntityTable[UiGeometry] { ui_model_world_store().geometry } @@ -1026,7 +1027,7 @@ pub fn ui_target_cameras() -> @ecs.ComponentStore[UiTargetCamera] { } ///| -pub fn calculated_clips() -> Map[@ecs.Entity, CalculatedClip] { +pub fn calculated_clips() -> @ecs.EntityTable[CalculatedClip] { ui_model_world_store().calculated_clips } @@ -1046,7 +1047,7 @@ pub fn global_zindexes() -> @ecs.ComponentStore[GlobalZIndex] { } ///| -pub fn scroll_positions() -> Map[@ecs.Entity, ScrollPosition] { +pub fn scroll_positions() -> @ecs.EntityTable[ScrollPosition] { ui_model_world_store().scroll_positions } @@ -1066,7 +1067,7 @@ pub fn focusables() -> @ecs.ComponentStore[Focusable] { } ///| -pub fn focuseds() -> Map[@ecs.Entity, Focused] { +pub fn focuseds() -> @ecs.EntityTable[Focused] { ui_model_world_store().focuseds } @@ -1083,7 +1084,7 @@ pub fn relative_cursor_positions() -> @ecs.ComponentStore[ } ///| -fn tree_orders() -> Map[@ecs.Entity, Int32] { +fn tree_orders() -> @ecs.EntityTable[Int32] { ui_model_world_store().tree_orders } diff --git a/selene-core/src/ui/pkg.generated.mbti b/selene-core/src/ui/pkg.generated.mbti index 10422ee2..fbf5d2bf 100644 --- a/selene-core/src/ui/pkg.generated.mbti +++ b/selene-core/src/ui/pkg.generated.mbti @@ -45,7 +45,7 @@ pub fn box_shadows() -> @ecs.ComponentStore[BoxShadow] pub fn buttons() -> @ecs.ComponentStore[Button] -pub fn calculated_clips() -> Map[@ecs.Entity, CalculatedClip] +pub fn calculated_clips() -> @ecs.EntityTable[CalculatedClip] pub let click_event_bus : @event.Events[UiClickEvent] @@ -79,7 +79,7 @@ pub fn focusables() -> @ecs.ComponentStore[Focusable] pub fn focused_entity() -> @ecs.Entity? -pub fn focuseds() -> Map[@ecs.Entity, Focused] +pub fn focuseds() -> @ecs.EntityTable[Focused] pub fn get_ui_scale_mode() -> UiScaleMode @@ -127,7 +127,7 @@ pub fn grid_span(Int32) -> GridPlacement pub fn hovered_entity() -> @ecs.Entity? -pub fn interactions() -> Map[@ecs.Entity, Interaction] +pub fn interactions() -> @ecs.EntityTable[Interaction] pub fn is_pointer_consumed(@inputs.PointerId) -> Bool @@ -169,7 +169,7 @@ pub fn release_ui_material_asset(UiMaterialHandle) -> Unit pub fn rgba(Int32, Int32, Int32, Double) -> @render.Color -pub fn scroll_positions() -> Map[@ecs.Entity, ScrollPosition] +pub fn scroll_positions() -> @ecs.EntityTable[ScrollPosition] pub fn set_ui_scale_mode(UiScaleMode) -> Unit diff --git a/selene-core/src/ui/visual.mbt b/selene-core/src/ui/visual.mbt index d26362d7..b822b439 100644 --- a/selene-core/src/ui/visual.mbt +++ b/selene-core/src/ui/visual.mbt @@ -557,7 +557,7 @@ pub fn buttons() -> @ecs.ComponentStore[Button] { } ///| -pub fn interactions() -> Map[@ecs.Entity, Interaction] { +pub fn interactions() -> @ecs.EntityTable[Interaction] { ui_model_world_store().interactions } diff --git a/selene-core/src/visibility/pkg.generated.mbti b/selene-core/src/visibility/pkg.generated.mbti index 12296653..7b5eca6f 100644 --- a/selene-core/src/visibility/pkg.generated.mbti +++ b/selene-core/src/visibility/pkg.generated.mbti @@ -9,7 +9,7 @@ import { // Values pub fn entity_render_layers(@ecs.Entity) -> RenderLayers -pub fn inherited_visibilities() -> Map[@ecs.Entity, InheritedVisibility] +pub fn inherited_visibilities() -> @ecs.EntityTable[InheritedVisibility] pub fn is_visible(@ecs.Entity) -> Bool @@ -21,7 +21,7 @@ pub fn matches(RenderLayers, RenderLayers) -> Bool pub fn render_layers() -> @ecs.ComponentStore[RenderLayers] -pub fn view_visibilities() -> Map[@ecs.Entity, ViewVisibility] +pub fn view_visibilities() -> @ecs.EntityTable[ViewVisibility] pub fn visibilities() -> @ecs.ComponentStore[Visibility] diff --git a/selene-core/src/visibility/visibility.mbt b/selene-core/src/visibility/visibility.mbt index 21362d09..7feaf125 100644 --- a/selene-core/src/visibility/visibility.mbt +++ b/selene-core/src/visibility/visibility.mbt @@ -46,35 +46,35 @@ let visibility_state_key : @ecs.ResourceKey[VisibilityState] = ResourceKey() ///| priv struct VisibilityState { - inherited : Map[@ecs.Entity, InheritedVisibility] - view : Map[@ecs.Entity, ViewVisibility] + inherited : @ecs.EntityTable[InheritedVisibility] + view : @ecs.EntityTable[ViewVisibility] } ///| fn visibility_state() -> VisibilityState { - visibility_state_key.get_or_insert_with(@ecs.require_current_world(), _ => { - inherited: {}, - view: {}, + visibility_state_key.get_or_insert_with(@ecs.require_current_world(), world => { + inherited: EntityTable(world), + view: EntityTable(world), }) } ///| -pub fn inherited_visibilities() -> Map[@ecs.Entity, InheritedVisibility] { +pub fn inherited_visibilities() -> @ecs.EntityTable[InheritedVisibility] { visibility_state().inherited } ///| -pub fn view_visibilities() -> Map[@ecs.Entity, ViewVisibility] { +pub fn view_visibilities() -> @ecs.EntityTable[ViewVisibility] { visibility_state().view } ///| fn compute_inherited_visibility( entity : @ecs.Entity, - cache : Map[@ecs.Entity, Bool], + cache : @ecs.EntityTable[InheritedVisibility], ) -> Bool { if cache.get(entity) is Some(visible) { - return visible + return visible.visible } let own_visible = visibilities().get(entity).unwrap_or(Visible) is Visible let parent_visible = match entity.get_parent() { @@ -82,7 +82,7 @@ fn compute_inherited_visibility( None => true } let visible = own_visible && parent_visible - cache.set(entity, visible) + cache.set(entity, { visible, }) visible } @@ -92,13 +92,12 @@ pub fn visibility_propagate_system(_delta : Double) -> Unit { let view_visibilities = view_visibilities() inherited_visibilities.clear() view_visibilities.clear() - let cache : Map[@ecs.Entity, Bool] = Map([]) for entity in @ecs.iter_entities() { guard entity.is_alive() else { continue } - let visible = compute_inherited_visibility(entity, cache) - inherited_visibilities.set(entity, { visible, }) + let visible = compute_inherited_visibility(entity, inherited_visibilities) view_visibilities.set(entity, { visible, }) } + inherited_visibilities.retain((entity, _) => entity.is_alive()) } ///| diff --git a/selene-core/src/window/display.mbt b/selene-core/src/window/display.mbt index 8fad8bb6..d936af7d 100644 --- a/selene-core/src/window/display.mbt +++ b/selene-core/src/window/display.mbt @@ -20,12 +20,11 @@ priv struct DisplayState { } ///| -let display_world_states : Map[UInt32, DisplayState] = Map([]) +let display_state_key : @ecs.ResourceKey[DisplayState] = ResourceKey() ///| fn display_state() -> DisplayState { - let world_id = @ecs.require_current_world().id() - display_world_states.get_or_init(world_id, () => { + display_state_key.get_or_insert_with(@ecs.require_current_world(), _ => { viewport_size: Vec2(512.0, 256.0), screen_size: Vec2(512.0, 256.0), zoom: 1.0, diff --git a/selene-webgpu/src/audio.mbt b/selene-webgpu/src/audio.mbt index 0e93ab60..9de2715d 100644 --- a/selene-webgpu/src/audio.mbt +++ b/selene-webgpu/src/audio.mbt @@ -213,17 +213,17 @@ fn create_audio_instance(path : String) -> (AudioInstance, AudioPlayback) { ///| fn reset_audio_runtime() -> Unit { - for (_, playback) in audio_instances.to_array() { + for playback in audio_instances.values() { playback.audio.pause() playback.audio.set_current_time(0.0) } audio_instances.clear() - for (_, template) in preloaded_audio_templates.to_array() { + for template in preloaded_audio_templates.values() { template.pause() template.set_current_time(0.0) } preloaded_audio_templates.clear() - for (_, entry) in cached_audio_sources.to_array() { + for entry in cached_audio_sources.values() { if entry.blob_owned { revoke_object_url(entry.src) } @@ -316,11 +316,12 @@ pub fn is_finished(instance~ : AudioInstance) -> Bool { ///| pub fn tick_audio() -> Unit { let activation_epoch = current_audio_activation_epoch() - for (instance, playback) in audio_instances.to_array() { + audio_instances.retain((_instance, playback) => { let play_state = audio_play_state(playback.audio) if playback.audio.is_ended() || play_state == AUDIO_PLAY_STATE_FAILED { - audio_instances.remove(instance) - } else if should_retry_blocked_audio_playback( + return false + } + if should_retry_blocked_audio_playback( play_state, playback.requested_paused, activation_epoch, @@ -328,7 +329,8 @@ pub fn tick_audio() -> Unit { ) { request_audio_playback(playback) } - } + true + }) } ///| diff --git a/selene-webgpu/src/draw.mbt b/selene-webgpu/src/draw.mbt index 5c4a8691..e077c45e 100644 --- a/selene-webgpu/src/draw.mbt +++ b/selene-webgpu/src/draw.mbt @@ -267,7 +267,7 @@ let webgpu_resource_frame : Ref[Int32] = Ref(0) let primitive_mesh_resource_last_seen : Map[String, Int32] = Map([]) ///| -let uploaded_primitive_mesh_resources : Map[String, Bool] = Map([]) +let uploaded_primitive_mesh_resources : @set.Set[String] = Set([]) ///| fn Render3DSubmissionStats::Render3DSubmissionStats() -> Render3DSubmissionStats { @@ -1481,7 +1481,7 @@ fn ensure_lit_primitive_mesh_resource( receive_shadows, ) webgpu_upload_lit_primitive_mesh_resource(marked_key, vertices) - uploaded_primitive_mesh_resources.set(marked_key, true) + uploaded_primitive_mesh_resources.add(marked_key) } marked_key } @@ -1490,13 +1490,14 @@ fn ensure_lit_primitive_mesh_resource( fn prune_stale_primitive_mesh_resources() -> Unit { let min_live_frame = webgpu_resource_frame.val - WEBGPU_PRIMITIVE_MESH_RESOURCE_TTL_FRAMES - for (key, last_seen) in primitive_mesh_resource_last_seen.to_array() { - if last_seen < min_live_frame { - ignore(primitive_mesh_resource_last_seen.remove(key)) - ignore(uploaded_primitive_mesh_resources.remove(key)) - webgpu_release_primitive_mesh_resource(key) + primitive_mesh_resource_last_seen.retain((key, last_seen) => { + if last_seen >= min_live_frame { + return true } - } + ignore(uploaded_primitive_mesh_resources.remove(key)) + webgpu_release_primitive_mesh_resource(key) + false + }) } ///| @@ -1509,12 +1510,13 @@ fn mark_retained_instance_buffer_key(key : String) -> String { fn prune_stale_retained_instance_buffers3d() -> Unit { let min_live_frame = webgpu_resource_frame.val - WEBGPU_PRIMITIVE_MESH_RESOURCE_TTL_FRAMES - for (key, last_seen) in retained_render3d_instance_last_seen.to_array() { - if last_seen < min_live_frame { - ignore(retained_render3d_instance_last_seen.remove(key)) - webgpu_release_retained_instance_buffer_3d(key) + retained_render3d_instance_last_seen.retain((key, last_seen) => { + if last_seen >= min_live_frame { + return true } - } + webgpu_release_retained_instance_buffer_3d(key) + false + }) } ///| diff --git a/selene-webgpu/src/moon.pkg b/selene-webgpu/src/moon.pkg index 43f17d14..e268502f 100644 --- a/selene-webgpu/src/moon.pkg +++ b/selene-webgpu/src/moon.pkg @@ -1,4 +1,5 @@ import { + "moonbitlang/core/set", "moonbitlang/core/cmp", "moonbitlang/core/debug", "moonbit-community/js-ffi/js", diff --git a/selene-webgpu/src/text_cosmic.mbt b/selene-webgpu/src/text_cosmic.mbt index 31a7e33f..97c2c207 100644 --- a/selene-webgpu/src/text_cosmic.mbt +++ b/selene-webgpu/src/text_cosmic.mbt @@ -36,7 +36,7 @@ let cosmic_swash_cache : Ref[@cosmic.SwashCache] = Ref( ) ///| -let cosmic_loaded_families : Map[String, Bool] = Map([]) +let cosmic_loaded_families : @set.Set[String] = Set([]) ///| let cosmic_text_cache : Map[String, CosmicTextCacheEntry] = Map([]) @@ -125,7 +125,7 @@ fn ensure_font_loaded(family : String) -> Bool { raw_bytes.iter().map(fn(value) { saturating_byte(value) }), ) cosmic_font_system.val = cosmic_font_system.val.load_font_data(bytes) - cosmic_loaded_families.set(family, true) + cosmic_loaded_families.add(family) cosmic_text_cache.clear() true } From 7921c9953c2d38009f937b981b891838da6c08ea Mon Sep 17 00:00:00 2001 From: Milky2018 <842376130@qq.com> Date: Thu, 12 Nov 2026 10:05:38 +0800 Subject: [PATCH 2/2] refactor: encapsulate subsystem runtime access --- docs/CHANGELOG.md | 9 ++++ selene-core/src/animation/animation_apply.mbt | 6 +-- selene-core/src/audio/pkg.generated.mbti | 14 +----- selene-core/src/audio/playback.mbt | 10 +++- selene-core/src/audio/runtime_access_test.mbt | 26 +++++++++++ selene-core/src/audio/sink.mbt | 2 +- selene-core/src/ecs/README.md | 34 +++++++++++--- selene-core/src/ldtk/ldtk_world_registry.mbt | 2 +- selene-core/src/ldtk/ldtk_world_spawner.mbt | 8 ++++ selene-core/src/ldtk/ldtk_world_types.mbt | 2 +- selene-core/src/ldtk/pkg.generated.mbti | 8 +--- selene-core/src/ldtk/respawn_test.mbt | 26 +++++++++++ .../physics3d/physics3d_constraints_sync.mbt | 4 +- .../src/physics3d/physics3d_joints.mbt | 2 +- selene-core/src/physics3d/physics3d_sync.mbt | 25 +++++++++- .../src/physics3d/physics3d_wbtest.mbt | 33 ++++++++++++- selene-core/src/physics3d/pkg.generated.mbti | 4 +- selene-core/src/render3d/render3d_wbtest.mbt | 5 +- selene-core/src/ui/interaction.mbt | 1 + selene-core/src/ui/interaction_wbtest.mbt | 27 ++++------- selene-core/src/ui/layout_runtime_wbtest.mbt | 12 +++-- selene-core/src/ui/layout_wbtest.mbt | 14 +++--- selene-core/src/ui/model.mbt | 46 +++++++++++++++++-- selene-core/src/ui/pkg.generated.mbti | 17 +++---- selene-core/src/ui/runtime_access_test.mbt | 41 +++++++++++++++++ selene-core/src/ui/visual.mbt | 9 +++- selene-core/src/visibility/pkg.generated.mbti | 4 +- .../src/visibility/runtime_access_test.mbt | 27 +++++++++++ selene-core/src/visibility/visibility.mbt | 18 +++++++- 29 files changed, 341 insertions(+), 95 deletions(-) create mode 100644 selene-core/src/audio/runtime_access_test.mbt create mode 100644 selene-core/src/ldtk/respawn_test.mbt create mode 100644 selene-core/src/ui/runtime_access_test.mbt create mode 100644 selene-core/src/visibility/runtime_access_test.mbt diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index e7fb37e3..a3098ee9 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -38,6 +38,15 @@ ### Changed +- Remove redundant runtime-table writes after mutating morph weights. + +- Keep entity runtime tables private to their subsystems. Read individual UI, + visibility, audio, and character controller results instead of mutating their + stores. Use `set_scroll_position`, focus operations, and LDtk respawn operations + for writes. Scroll positions and contact arrays are snapshots; `AudioSink` + exposes playback methods without public fields. Hide the internal `Focused` + and `LdtkRespawn` marker types. + - Store engine runtime state, event buses, and event reader cursors in their owning World resources instead of global World-ID maps. - Index entity runtime data by reusable slots with full-handle validation, diff --git a/selene-core/src/animation/animation_apply.mbt b/selene-core/src/animation/animation_apply.mbt index 1ae11961..fa821a4a 100644 --- a/selene-core/src/animation/animation_apply.mbt +++ b/selene-core/src/animation/animation_apply.mbt @@ -196,16 +196,14 @@ fn set_target_morph_weights( target_entity : @ecs.Entity, weights : Array[Double], ) -> Unit { - for entity, binding in morphed_meshes() { + for binding in morphed_meshes().values() { if binding.target_entity == target_entity { binding.morph_weights = weights.copy() - morphed_meshes().set(entity, binding) } } - for entity, binding in skinned_meshes() { + for binding in skinned_meshes().values() { if binding.target_entity == target_entity { binding.morph_weights = weights.copy() - skinned_meshes().set(entity, binding) } } } diff --git a/selene-core/src/audio/pkg.generated.mbti b/selene-core/src/audio/pkg.generated.mbti index 49549853..c28e7683 100644 --- a/selene-core/src/audio/pkg.generated.mbti +++ b/selene-core/src/audio/pkg.generated.mbti @@ -5,7 +5,6 @@ import { "Milky2018/selene/asset_types", "Milky2018/selene/ecs", "Milky2018/selene/event", - "Milky2018/selene/platform_audio", "moonbitlang/core/debug", } @@ -22,7 +21,7 @@ pub fn audio_playback_system(Double) -> Unit pub fn audio_players() -> @ecs.ComponentStore[AudioPlayer] -pub fn audio_sinks() -> @ecs.EntityTable[AudioSink] +pub fn audio_sink(@ecs.Entity) -> AudioSink? pub fn global_volume() -> Double @@ -62,16 +61,7 @@ pub fn AudioPlayer::not_equal(Self, Self) -> Bool pub fn AudioPlayer::to_repr(Self) -> @debug.Repr pub impl @ecs.Component for AudioPlayer -pub(all) struct AudioSink { - instance : @platform_audio.AudioInstance - mode : PlaybackMode - mut volume : Double - mut speed : Double - mut paused : Bool - mut muted : Bool - mut stopped : Bool - mut finished : Bool -} +type AudioSink pub fn AudioSink::finished(Self) -> Bool pub fn AudioSink::mode(Self) -> PlaybackMode pub fn AudioSink::muted(Self) -> Bool diff --git a/selene-core/src/audio/playback.mbt b/selene-core/src/audio/playback.mbt index 0b00f955..e84cd44b 100644 --- a/selene-core/src/audio/playback.mbt +++ b/selene-core/src/audio/playback.mbt @@ -13,7 +13,7 @@ // limitations under the License. ///| -pub fn audio_sinks() -> @ecs.EntityTable[AudioSink] { +fn audio_sinks() -> @ecs.EntityTable[AudioSink] { audio_runtime().sinks } @@ -218,3 +218,11 @@ fn update_audio_playback( start_audio_sink(entity, player, normalize_settings(settings)) } } + +///| +/// Returns the playback control handle for an entity in the active World. +/// A sink is available after the audio playback system starts its instance. +pub fn audio_sink(entity : @ecs.Entity) -> AudioSink? { + guard entity.is_valid_in(@ecs.require_current_world()) else { None } + audio_sinks().get(entity) +} diff --git a/selene-core/src/audio/runtime_access_test.mbt b/selene-core/src/audio/runtime_access_test.mbt new file mode 100644 index 00000000..09fb4ad8 --- /dev/null +++ b/selene-core/src/audio/runtime_access_test.mbt @@ -0,0 +1,26 @@ +///| +test "audio control handles are read per entity without exposing sink storage" { + let previous = @ecs.current_world() + defer (match previous { + Some(world) => @ecs.set_current_world(world) + None => @ecs.clear_current_world() + }) + let first = @ecs.World() + let second = @ecs.World() + @ecs.set_current_world(first) + let entity = @audio.spawn_audio(@asset.load_audio("audio-access-test.ogg")) + assert_true(@audio.audio_sink(entity) is None) + @audio.audio_playback_system(0.0) + let sink = @audio.audio_sink(entity).unwrap() + sink.set_volume(0.25) + sink.pause() + assert_eq(@audio.audio_sink(entity).unwrap().volume(), 0.25) + assert_true(@audio.audio_sink(entity).unwrap().paused()) + @ecs.set_current_world(second) + assert_true(@audio.audio_sink(entity) is None) + @ecs.set_current_world(first) + @audio.stop_audio(entity) + assert_true(@audio.audio_sink(entity) is None) + assert_true(entity.delete()) + assert_true(@audio.audio_sink(entity) is None) +} diff --git a/selene-core/src/audio/sink.mbt b/selene-core/src/audio/sink.mbt index 04924e76..b2d26e33 100644 --- a/selene-core/src/audio/sink.mbt +++ b/selene-core/src/audio/sink.mbt @@ -13,7 +13,7 @@ // limitations under the License. ///| -pub(all) struct AudioSink { +struct AudioSink { instance : @platform_audio.AudioInstance mode : PlaybackMode mut volume : Double diff --git a/selene-core/src/ecs/README.md b/selene-core/src/ecs/README.md index af205544..4005a078 100644 --- a/selene-core/src/ecs/README.md +++ b/selene-core/src/ecs/README.md @@ -279,13 +279,33 @@ generated sources included in the published package. Use a World resource for subsystem state, including caches and event readers. Do not keep a global `Map[WorldId, State]`: the World should own its data. -`EntityTable[T](world)` stores World-local runtime data indexed by entity slots. -It is not a component store and does not change entity layouts. Lookups compare -full entity handles, and traversal preserves insertion order. Deleted entities' -entries remain available for explicit cleanup, including when their slots have -been reused. This lets an owner release old audio or physics resources without -confusing them with a new entity. Use `retain` to prune entries; its callback -must not structurally modify the table. Use `clear` for frame-local results. +Engine subsystems keep entity-indexed runtime caches inside those resources. +Game code accesses individual results or control handles rather than mutable +cache containers: + +```moonbit +let interaction = @ui.interaction(entity) +let clip = @ui.calculated_clip(entity) +let position = @ui.scroll_position(entity) // a snapshot +@ui.set_scroll_position(entity, { x: 0.0, y: 100.0 }) +@ui.focus(entity) + +if @audio.audio_sink(entity) is Some(sink) { + sink.set_volume(0.5) + sink.pause() +} +``` + +Scroll position updates are applied and clamped during layout. Readers return +copies of mutable value data, including scroll positions and character contact +arrays. Audio sinks are opaque control handles with playback operations. +Visibility and character motion readers return results from the latest +propagation or physics pass. LDtk respawn requests use `mark_ldtk_respawn`, +`clear_ldtk_respawn`, and `is_ldtk_respawn_requested`. + +The underlying entity tables can retain deleted generations until the owning +subsystem releases external resources. Public readers reject deleted handles +and do not expose those cleanup records. Prefer direct iteration for reads. Use `Map::retain` for simple filtering, and queue entity deletions through `Commands` while traversing components. Collect a diff --git a/selene-core/src/ldtk/ldtk_world_registry.mbt b/selene-core/src/ldtk/ldtk_world_registry.mbt index fedc80c5..06904189 100644 --- a/selene-core/src/ldtk/ldtk_world_registry.mbt +++ b/selene-core/src/ldtk/ldtk_world_registry.mbt @@ -49,7 +49,7 @@ pub fn ldtk_worldly_entities() -> @ecs.ComponentStore[LdtkWorldly] { } ///| -pub fn ldtk_respawns() -> @ecs.EntityTable[LdtkRespawn] { +fn ldtk_respawns() -> @ecs.EntityTable[LdtkRespawn] { ldtk_world_store().respawns } diff --git a/selene-core/src/ldtk/ldtk_world_spawner.mbt b/selene-core/src/ldtk/ldtk_world_spawner.mbt index 4c0e1aee..0eb453d6 100644 --- a/selene-core/src/ldtk/ldtk_world_spawner.mbt +++ b/selene-core/src/ldtk/ldtk_world_spawner.mbt @@ -208,3 +208,11 @@ pub fn unregister_default_ldtk_int_cell_for_layer( pub fn unregister_default_ldtk_int_cell() -> Unit { unregister_ldtk_int_cell_for_layer_optional(None, None) } + +///| +/// Whether an entity in the active World has a pending respawn request. Use mark_ldtk_respawn +/// and clear_ldtk_respawn to update requests. +pub fn is_ldtk_respawn_requested(entity : @ecs.Entity) -> Bool { + entity.is_valid_in(@ecs.require_current_world()) && + ldtk_respawns().get(entity).map_or(false, request => request.requested) +} diff --git a/selene-core/src/ldtk/ldtk_world_types.mbt b/selene-core/src/ldtk/ldtk_world_types.mbt index d0f8e684..076e1d95 100644 --- a/selene-core/src/ldtk/ldtk_world_types.mbt +++ b/selene-core/src/ldtk/ldtk_world_types.mbt @@ -138,7 +138,7 @@ pub struct LdtkWorldly { } ///| -pub struct LdtkRespawn { +priv struct LdtkRespawn { requested : Bool } diff --git a/selene-core/src/ldtk/pkg.generated.mbti b/selene-core/src/ldtk/pkg.generated.mbti index dc7df362..087dfaeb 100644 --- a/selene-core/src/ldtk/pkg.generated.mbti +++ b/selene-core/src/ldtk/pkg.generated.mbti @@ -89,6 +89,8 @@ pub fn default_ldtk_level_selection() -> LdtkLevelSelection pub fn despawn_ldtk_tree(@ecs.Entity) -> Unit +pub fn is_ldtk_respawn_requested(@ecs.Entity) -> Bool + pub fn ldtk_entity_by_iid(@ecs.Entity, String) -> @ecs.Entity? pub fn ldtk_entity_default_spawn_hook() -> @ref.Ref[((LdtkEntitySpawnedEvent) -> Unit)?] @@ -209,8 +211,6 @@ pub let ldtk_level_spawned_event_bus : @event.Events[LdtkLevelSpawnedEvent] pub fn ldtk_pending_transformed_level_iids() -> @set.Set[String] -pub fn ldtk_respawns() -> @ecs.EntityTable[LdtkRespawn] - pub let ldtk_settings : @ref.Ref[LdtkSettings] pub fn ldtk_spawned_entity_instances() -> @ecs.ComponentStore[LdtkSpawnedEntityInstance] @@ -800,10 +800,6 @@ pub struct LdtkProjectDefinitions { } pub fn LdtkProjectDefinitions::LdtkProjectDefinitions() -> Self -pub struct LdtkRespawn { - requested : Bool -} - pub struct LdtkSettings { level_spawn_behavior : LdtkLevelSpawnBehavior int_grid_rendering : LdtkIntGridRendering diff --git a/selene-core/src/ldtk/respawn_test.mbt b/selene-core/src/ldtk/respawn_test.mbt new file mode 100644 index 00000000..051a7cf0 --- /dev/null +++ b/selene-core/src/ldtk/respawn_test.mbt @@ -0,0 +1,26 @@ +///| +test "respawn requests are changed through operations and queried per entity" { + let previous = @ecs.current_world() + defer (match previous { + Some(world) => @ecs.set_current_world(world) + None => @ecs.clear_current_world() + }) + let first = @ecs.World() + let second = @ecs.World() + @ecs.set_current_world(first) + let entity = first.spawn(()) + assert_false(@ldtk.is_ldtk_respawn_requested(entity)) + @ldtk.mark_ldtk_respawn(entity) + assert_true(@ldtk.is_ldtk_respawn_requested(entity)) + @ldtk.clear_ldtk_respawn(entity) + assert_false(@ldtk.is_ldtk_respawn_requested(entity)) + @ldtk.mark_ldtk_respawn(entity) + @ecs.set_current_world(second) + assert_false(@ldtk.is_ldtk_respawn_requested(entity)) + @ecs.set_current_world(first) + assert_true(entity.delete()) + let replacement = first.spawn(()) + assert_eq(entity.slot_index(), replacement.slot_index()) + assert_false(@ldtk.is_ldtk_respawn_requested(entity)) + assert_false(@ldtk.is_ldtk_respawn_requested(replacement)) +} diff --git a/selene-core/src/physics3d/physics3d_constraints_sync.mbt b/selene-core/src/physics3d/physics3d_constraints_sync.mbt index ac23cf6f..eb79e940 100644 --- a/selene-core/src/physics3d/physics3d_constraints_sync.mbt +++ b/selene-core/src/physics3d/physics3d_constraints_sync.mbt @@ -152,7 +152,7 @@ fn sync_character_controllers(delta : Double) -> Unit { } guard colliders().get(entity) is Some(shape) else { kinematic_character_controller_outputs().set(entity, output) - kinematic_character_controller_collisions().set( + controller_collisions().set( entity, KinematicCharacterControllerCollisions(), ) @@ -199,7 +199,7 @@ fn sync_character_controllers(delta : Double) -> Unit { grounded: movement.is_grounded(), is_sliding_down_slope: movement.is_sliding_down_slope(), }) - kinematic_character_controller_collisions().set(entity, { + controller_collisions().set(entity, { collisions: rapier_collisions.map(collision => { entity: resolve_collider_entity(collision.handle()), character_translation_applied: vec3_from_rapier( diff --git a/selene-core/src/physics3d/physics3d_joints.mbt b/selene-core/src/physics3d/physics3d_joints.mbt index 804fa493..a4097368 100644 --- a/selene-core/src/physics3d/physics3d_joints.mbt +++ b/selene-core/src/physics3d/physics3d_joints.mbt @@ -162,7 +162,7 @@ fn collider_desc(entity : @ecs.Entity, shape : Collider) -> ColliderDesc { ///| fn clear_controller_outputs() -> Unit { kinematic_character_controller_outputs().clear() - kinematic_character_controller_collisions().clear() + controller_collisions().clear() } ///| diff --git a/selene-core/src/physics3d/physics3d_sync.mbt b/selene-core/src/physics3d/physics3d_sync.mbt index 2da8b7db..669b3c9e 100644 --- a/selene-core/src/physics3d/physics3d_sync.mbt +++ b/selene-core/src/physics3d/physics3d_sync.mbt @@ -38,14 +38,14 @@ pub fn kinematic_character_controllers() -> @ecs.ComponentStore[ } ///| -pub fn kinematic_character_controller_outputs() -> @ecs.EntityTable[ +fn kinematic_character_controller_outputs() -> @ecs.EntityTable[ KinematicCharacterControllerOutput, ] { physics3d_world_store().controller_outputs } ///| -pub fn kinematic_character_controller_collisions() -> @ecs.EntityTable[ +fn controller_collisions() -> @ecs.EntityTable[ KinematicCharacterControllerCollisions, ] { physics3d_world_store().controller_collisions @@ -179,3 +179,24 @@ pub fn multibody_joint_handle( ) -> RapierMultibodyJointHandle? { multibody_joint_handles().get(entity) } + +///| +/// Reads the character motion result from the latest physics step. +pub fn kinematic_character_controller_output( + entity : @ecs.Entity, +) -> KinematicCharacterControllerOutput? { + guard entity.is_valid_in(@ecs.require_current_world()) else { None } + kinematic_character_controller_outputs().get(entity) +} + +///| +/// Reads character contacts from the latest physics step. The returned array +/// is a copy, so modifying it cannot change the stored physics result. +pub fn kinematic_character_controller_collisions( + entity : @ecs.Entity, +) -> KinematicCharacterControllerCollisions? { + guard entity.is_valid_in(@ecs.require_current_world()) else { None } + controller_collisions() + .get(entity) + .map(result => { collisions: result.collisions.copy(), }) +} diff --git a/selene-core/src/physics3d/physics3d_wbtest.mbt b/selene-core/src/physics3d/physics3d_wbtest.mbt index 77f72a83..b04afcdc 100644 --- a/selene-core/src/physics3d/physics3d_wbtest.mbt +++ b/selene-core/src/physics3d/physics3d_wbtest.mbt @@ -899,10 +899,10 @@ test "kinematic character controller writes output and clears consumed translati step_physics(1) - let output = kinematic_character_controller_outputs().get(actor).unwrap() + let output = kinematic_character_controller_output(actor).unwrap() inspect(output.desired_translation.y < 0.0, content="true") inspect( - kinematic_character_controller_collisions().get(actor).unwrap().collisions.length() >= + kinematic_character_controller_collisions(actor).unwrap().collisions.length() >= 0, content="true", ) @@ -1132,3 +1132,32 @@ test "3D physics removes sheared poses and restores valid colliders" { assert_eq(cast().unwrap().entity, child) }) } + +///| +test "character contacts expose snapshots instead of mutable output storage" { + with_physics3d_test_world(fn() raise { + let world = @ecs.require_current_world() + let entity = world.spawn(()) + controller_collisions().set(entity, { + collisions: [ + { + entity: None, + character_translation_applied: @math.Vec3::zero(), + character_translation_remaining: @math.Vec3::zero(), + toi: 0.0, + normal: @math.Vec3::y_axis(), + }, + ], + }) + let snapshot = kinematic_character_controller_collisions(entity).unwrap() + snapshot.collisions.clear() + assert_eq( + kinematic_character_controller_collisions(entity).unwrap().collisions.length(), + 1, + ) + ignore(entity.delete()) + let replacement = world.spawn(()) + assert_true(kinematic_character_controller_collisions(entity) is None) + assert_true(kinematic_character_controller_collisions(replacement) is None) + }) +} diff --git a/selene-core/src/physics3d/pkg.generated.mbti b/selene-core/src/physics3d/pkg.generated.mbti index d7ff9b82..cf269eb0 100644 --- a/selene-core/src/physics3d/pkg.generated.mbti +++ b/selene-core/src/physics3d/pkg.generated.mbti @@ -55,9 +55,9 @@ pub fn impulse_joint_handle(@ecs.Entity) -> @dynamics.JointHandle3DReal? pub fn impulse_joints() -> @ecs.ComponentStore[ImpulseJoint] -pub fn kinematic_character_controller_collisions() -> @ecs.EntityTable[KinematicCharacterControllerCollisions] +pub fn kinematic_character_controller_collisions(@ecs.Entity) -> KinematicCharacterControllerCollisions? -pub fn kinematic_character_controller_outputs() -> @ecs.EntityTable[KinematicCharacterControllerOutput] +pub fn kinematic_character_controller_output(@ecs.Entity) -> KinematicCharacterControllerOutput? pub fn kinematic_character_controllers() -> @ecs.ComponentStore[KinematicCharacterController] diff --git a/selene-core/src/render3d/render3d_wbtest.mbt b/selene-core/src/render3d/render3d_wbtest.mbt index eb7d02ee..215c29c7 100644 --- a/selene-core/src/render3d/render3d_wbtest.mbt +++ b/selene-core/src/render3d/render3d_wbtest.mbt @@ -17,8 +17,7 @@ test "render3d extract preserves mesh shadow toggles" { @visibility.Visibility::Visible, ), ) - @visibility.inherited_visibilities().set(entity, { visible: true, }) - @visibility.view_visibilities().set(entity, { visible: true, }) + @visibility.visibility_propagate_system(0.0) @transform.transform_propagate_system(0.0) render3d_extract_system(0.0) @@ -28,8 +27,6 @@ test "render3d extract preserves mesh shadow toggles" { inspect(frame.items[0].cast_shadows, content="false") inspect(frame.items[0].receive_shadows, content="false") - ignore(@visibility.inherited_visibilities().remove(entity)) - ignore(@visibility.view_visibilities().remove(entity)) meshes.remove(mesh) materials.remove(material) render3d_world_state().extracted_frame = RenderFrame3D() diff --git a/selene-core/src/ui/interaction.mbt b/selene-core/src/ui/interaction.mbt index 2fc95efc..90fa7705 100644 --- a/selene-core/src/ui/interaction.mbt +++ b/selene-core/src/ui/interaction.mbt @@ -200,6 +200,7 @@ fn set_focus_marker(entity : @ecs.Entity) -> Unit { ///| pub fn focus(entity : @ecs.Entity) -> Unit { + guard entity.is_alive() else { return } let runtime = ui_interaction_runtime() if runtime.focused_entity is Some(current) && current == entity { return diff --git a/selene-core/src/ui/interaction_wbtest.mbt b/selene-core/src/ui/interaction_wbtest.mbt index 9c410bd9..ef2ede47 100644 --- a/selene-core/src/ui/interaction_wbtest.mbt +++ b/selene-core/src/ui/interaction_wbtest.mbt @@ -237,18 +237,12 @@ test "ui mouse click uses the unified pointer event stream" { apply_ui_mouse_frame(position, true) ui_interaction_system(0.0) - inspect( - interactions().get(entity).unwrap_or(None) == Pressed, - content="true", - ) + inspect(interaction(entity) == Pressed, content="true") apply_ui_mouse_frame(position, false) ui_interaction_system(0.0) inspect(click_event_bus.read(click_reader).length(), content="1") - inspect( - interactions().get(entity).unwrap_or(None) == Hovered, - content="true", - ) + inspect(interaction(entity) == Hovered, content="true") cleanup_interaction_test_entity(entity) reset_interaction_test_state() @@ -304,10 +298,7 @@ test "ui touch tap clicks interactive button without sticky hover" { touch_event(id, Started, press), ]) ui_interaction_system(0.0) - inspect( - interactions().get(entity).unwrap_or(None) == Pressed, - content="true", - ) + inspect(interaction(entity) == Pressed, content="true") apply_ui_touch_frame(None, [touch_event(id, Ended, press)]) ui_interaction_system(0.0) @@ -316,7 +307,7 @@ test "ui touch tap clicks interactive button without sticky hover" { inspect(pointer_up_event_bus.read(up_reader).length(), content="1") inspect(click_event_bus.read(click_reader).length(), content="1") inspect(pointer_enter_event_bus.read(enter_reader).length(), content="0") - inspect(interactions().get(entity).unwrap_or(None) == None, content="true") + inspect(interaction(entity) == None, content="true") cleanup_interaction_test_entity(entity) reset_interaction_test_state() @@ -343,7 +334,7 @@ test "ui cancelled touch clears pressed state without click" { ui_interaction_system(0.0) inspect(click_event_bus.read(click_reader).length(), content="0") - inspect(interactions().get(entity).unwrap_or(None) == None, content="true") + inspect(interaction(entity) == None, content="true") cleanup_interaction_test_entity(entity) reset_interaction_test_state() @@ -375,7 +366,7 @@ test "ui touch release outside pressed target does not click" { inspect(pointer_up_event_bus.read(up_reader).length(), content="1") inspect(click_event_bus.read(click_reader).length(), content="0") - inspect(interactions().get(entity).unwrap_or(None) == None, content="true") + inspect(interaction(entity) == None, content="true") cleanup_interaction_test_entity(entity) reset_interaction_test_state() @@ -404,7 +395,7 @@ test "ui touch drag scrolls non-button scrollable panels" { ) ui_interaction_system(0.0) - let scroll = scroll_positions().get(entity).unwrap() + let scroll = scroll_position(entity).unwrap() inspect(scroll.y, content="20") cleanup_interaction_test_entity(child) @@ -430,13 +421,13 @@ test "ui scroll deltas stop at the computed content bounds" { debug_inspect( [ computed_ui_node(entity).unwrap().max_scroll_position.y, - scroll_positions().get(entity).unwrap().y, + scroll_position(entity).unwrap().y, ], content="[120, 120]", ) apply_scroll_delta(entity, Vec2(0.0, -1000.0)) - inspect(scroll_positions().get(entity).unwrap().y, content="0") + inspect(scroll_position(entity).unwrap().y, content="0") cleanup_interaction_test_entity(child) cleanup_interaction_test_entity(entity) diff --git a/selene-core/src/ui/layout_runtime_wbtest.mbt b/selene-core/src/ui/layout_runtime_wbtest.mbt index dd16da11..de7018ee 100644 --- a/selene-core/src/ui/layout_runtime_wbtest.mbt +++ b/selene-core/src/ui/layout_runtime_wbtest.mbt @@ -63,7 +63,11 @@ test "retained UI layout updates replaced subtrees" { ///| test "retained UI stacking changes do not reproject or relayout" { let entity = @ecs.require_current_world().spawn( - (Node(width=Val::px(100.0), height=Val::px(100.0)), ZIndex(0)), + ( + Node(width=Val::px(100.0), height=Val::px(100.0)), + ZIndex(0), + @visibility.Visibility::Visible, + ), ) ui_layout_system(0.0) let runtime = ui_layout_runtime() @@ -77,14 +81,14 @@ test "retained UI stacking changes do not reproject or relayout" { assert_eq(runtime.projection_revision, projection_revision) assert_eq(runtime.stacking_revision, stacking_revision + 1U) - @visibility.view_visibilities().set(entity, { visible: false, }) + @visibility.visibilities().set(entity, Hidden) + @visibility.visibility_propagate_system(0.0) ui_layout_system(0.0) assert_eq(runtime.layout_revision, layout_revision) assert_eq(runtime.projection_revision, projection_revision) assert_eq(runtime.stacking_revision, stacking_revision + 2U) assert_false(ui_stack().contains(entity)) - ignore(@visibility.view_visibilities().remove(entity)) cleanup_layout_test_entity(entity) ui_layout_system(0.0) } @@ -123,7 +127,7 @@ test "retained UI projection changes do not rebuild layout or stacking" { let projection_revision = runtime.projection_revision let stacking_revision = runtime.stacking_revision - scroll_positions().set(root, { x: 10.0, y: 0.0, }) + set_scroll_position(root, { x: 10.0, y: 0.0, }) ui_layout_system(0.0) assert_eq(runtime.layout_revision, layout_revision) assert_eq(runtime.projection_revision, projection_revision + 1U) diff --git a/selene-core/src/ui/layout_wbtest.mbt b/selene-core/src/ui/layout_wbtest.mbt index 52e86f19..4a5412d1 100644 --- a/selene-core/src/ui/layout_wbtest.mbt +++ b/selene-core/src/ui/layout_wbtest.mbt @@ -402,11 +402,11 @@ test "ui layout clamps scroll positions to overflowing content" { Node(width=Val::px(100.0), height=Val::px(300.0), flex_shrink=0.0), parent~, ) - scroll_positions().set(parent, { x: 80.0, y: 1000.0, }) + set_scroll_position(parent, { x: 80.0, y: 1000.0, }) ui_layout_system(0.0) - let scroll = scroll_positions().get(parent).unwrap() + let scroll = scroll_position(parent).unwrap() debug_inspect([scroll.x, scroll.y], content="[0, 200]") let initial = computed_ui_node(parent).unwrap() assert_eq(initial.max_scroll_position, Vec2(0.0, 200.0)) @@ -419,7 +419,7 @@ test "ui layout clamps scroll positions to overflowing content" { ui_layout_system(0.0) let resized = computed_ui_node(parent).unwrap() debug_inspect( - [resized.max_scroll_position.y, scroll_positions().get(parent).unwrap().y], + [resized.max_scroll_position.y, scroll_position(parent).unwrap().y], content="[50, 50]", ) @@ -430,7 +430,7 @@ test "ui layout clamps scroll positions to overflowing content" { ui_layout_system(0.0) let shrunk = computed_ui_node(parent).unwrap() debug_inspect( - [shrunk.max_scroll_position.y, scroll_positions().get(parent).unwrap().y], + [shrunk.max_scroll_position.y, scroll_position(parent).unwrap().y], content="[0, 0]", ) @@ -438,7 +438,7 @@ test "ui layout clamps scroll positions to overflowing content" { child, Node(width=Val::px(100.0), height=Val::px(300.0), flex_shrink=0.0), ) - scroll_positions().set(parent, { x: 0.0, y: 70.0, }) + set_scroll_position(parent, { x: 0.0, y: 70.0, }) nodes().set( parent, Node::absolute(Vec2(0.0, 0.0), size=Vec2(100.0, 100.0), overflow_y=Hidden), @@ -446,7 +446,7 @@ test "ui layout clamps scroll positions to overflowing content" { ui_layout_system(0.0) let disabled = computed_ui_node(parent).unwrap() debug_inspect( - [disabled.max_scroll_position.y, scroll_positions().get(parent).unwrap().y], + [disabled.max_scroll_position.y, scroll_position(parent).unwrap().y], content="[0, 0]", ) @@ -469,7 +469,7 @@ test "ui scrolling preserves nested border and padding offsets" { Node(width=Val::px(84.0), height=Val::px(300.0), flex_shrink=0.0), parent~, ) - scroll_positions().set(parent, { x: 0.0, y: 20.0, }) + set_scroll_position(parent, { x: 0.0, y: 20.0, }) ui_layout_system(0.0) diff --git a/selene-core/src/ui/model.mbt b/selene-core/src/ui/model.mbt index 66395e99..43f45d08 100644 --- a/selene-core/src/ui/model.mbt +++ b/selene-core/src/ui/model.mbt @@ -893,12 +893,12 @@ pub extend FocusPolicy with @moonbitlang/core/debug.Debug::{to_repr} pub extend FocusPolicy with Eq::{not_equal, equal} ///| -pub(all) struct Focused { +priv struct Focused { _tag : Unit } ///| -pub fn Focused::Focused() -> Focused { +fn Focused::Focused() -> Focused { { _tag: (), } } @@ -1027,7 +1027,7 @@ pub fn ui_target_cameras() -> @ecs.ComponentStore[UiTargetCamera] { } ///| -pub fn calculated_clips() -> @ecs.EntityTable[CalculatedClip] { +fn calculated_clips() -> @ecs.EntityTable[CalculatedClip] { ui_model_world_store().calculated_clips } @@ -1047,7 +1047,7 @@ pub fn global_zindexes() -> @ecs.ComponentStore[GlobalZIndex] { } ///| -pub fn scroll_positions() -> @ecs.EntityTable[ScrollPosition] { +fn scroll_positions() -> @ecs.EntityTable[ScrollPosition] { ui_model_world_store().scroll_positions } @@ -1067,7 +1067,7 @@ pub fn focusables() -> @ecs.ComponentStore[Focusable] { } ///| -pub fn focuseds() -> @ecs.EntityTable[Focused] { +fn focuseds() -> @ecs.EntityTable[Focused] { ui_model_world_store().focuseds } @@ -1295,3 +1295,39 @@ fn rebuild_ui_stack() -> Unit { } } } + +///| +/// Reads the clipping rectangle calculated by the latest UI layout pass. +pub fn calculated_clip(entity : @ecs.Entity) -> CalculatedClip? { + guard entity.is_valid_in(@ecs.require_current_world()) else { None } + calculated_clips().get(entity) +} + +///| +/// Returns a copy of the stored scroll position. Use set_scroll_position to +/// request a change; layout clamps the position to the current scroll bounds. +pub fn scroll_position(entity : @ecs.Entity) -> ScrollPosition? { + guard entity.is_valid_in(@ecs.require_current_world()) else { None } + scroll_positions().get(entity).map(position => { ..position, }) +} + +///| +/// Requests a scroll position for a UI node in the active World. The next +/// layout pass clamps it to the node's scroll bounds. Copies the input value. +pub fn set_scroll_position( + entity : @ecs.Entity, + position : ScrollPosition, +) -> Unit { + guard entity.is_valid_in(@ecs.require_current_world()) && + nodes().contains(entity) else { + return + } + scroll_positions().set(entity, { ..position, }) +} + +///| +/// Whether this live entity currently has UI focus. Change focus with focus +/// or blur so the focus state and focus events remain synchronized. +pub fn is_focused(entity : @ecs.Entity) -> Bool { + entity.is_alive() && focuseds().contains(entity) +} diff --git a/selene-core/src/ui/pkg.generated.mbti b/selene-core/src/ui/pkg.generated.mbti index fbf5d2bf..2e3dab1c 100644 --- a/selene-core/src/ui/pkg.generated.mbti +++ b/selene-core/src/ui/pkg.generated.mbti @@ -45,7 +45,7 @@ pub fn box_shadows() -> @ecs.ComponentStore[BoxShadow] pub fn buttons() -> @ecs.ComponentStore[Button] -pub fn calculated_clips() -> @ecs.EntityTable[CalculatedClip] +pub fn calculated_clip(@ecs.Entity) -> CalculatedClip? pub let click_event_bus : @event.Events[UiClickEvent] @@ -79,8 +79,6 @@ pub fn focusables() -> @ecs.ComponentStore[Focusable] pub fn focused_entity() -> @ecs.Entity? -pub fn focuseds() -> @ecs.EntityTable[Focused] - pub fn get_ui_scale_mode() -> UiScaleMode pub fn global_ui_node(@ecs.Entity) -> GlobalUiNode? @@ -127,7 +125,9 @@ pub fn grid_span(Int32) -> GridPlacement pub fn hovered_entity() -> @ecs.Entity? -pub fn interactions() -> @ecs.EntityTable[Interaction] +pub fn interaction(@ecs.Entity) -> Interaction + +pub fn is_focused(@ecs.Entity) -> Bool pub fn is_pointer_consumed(@inputs.PointerId) -> Bool @@ -169,7 +169,9 @@ pub fn release_ui_material_asset(UiMaterialHandle) -> Unit pub fn rgba(Int32, Int32, Int32, Double) -> @render.Color -pub fn scroll_positions() -> @ecs.EntityTable[ScrollPosition] +pub fn scroll_position(@ecs.Entity) -> ScrollPosition? + +pub fn set_scroll_position(@ecs.Entity, ScrollPosition) -> Unit pub fn set_ui_scale_mode(UiScaleMode) -> Unit @@ -362,11 +364,6 @@ pub(all) struct Focusable { pub fn Focusable::Focusable() -> Self pub impl @ecs.Component for Focusable -pub(all) struct Focused { - _tag : Unit -} -pub fn Focused::Focused() -> Self - pub(all) struct GlobalUiNode { logical_rect : @math.Rect screen_rect : @math.Rect diff --git a/selene-core/src/ui/runtime_access_test.mbt b/selene-core/src/ui/runtime_access_test.mbt new file mode 100644 index 00000000..be864544 --- /dev/null +++ b/selene-core/src/ui/runtime_access_test.mbt @@ -0,0 +1,41 @@ +///| +test "UI runtime access uses operations and copies scroll positions" { + let previous = @ecs.current_world() + defer (match previous { + Some(world) => @ecs.set_current_world(world) + None => @ecs.clear_current_world() + }) + let first = @ecs.World() + let second = @ecs.World() + @ecs.set_current_world(first) + let entity = first.spawn1(@ui.Node()) + assert_true(@ui.scroll_position(entity) is None) + assert_true(@ui.calculated_clip(entity) is None) + assert_eq(@ui.interaction(entity), None) + let requested : @ui.ScrollPosition = { x: 10.0, y: 20.0, } + @ui.set_scroll_position(entity, requested) + requested.x = 99.0 + let snapshot = @ui.scroll_position(entity).unwrap() + assert_eq(snapshot.x, 10.0) + snapshot.y = 99.0 + assert_eq(@ui.scroll_position(entity).unwrap().y, 20.0) + @ui.focus(entity) + assert_true(@ui.is_focused(entity)) + @ui.blur() + assert_false(@ui.is_focused(entity)) + @ecs.set_current_world(second) + assert_true(@ui.scroll_position(entity) is None) + @ui.set_scroll_position(entity, { x: 100.0, y: 100.0, }) + @ui.focus(entity) + assert_true(@ui.focused_entity() is None) + assert_false(@ui.is_focused(entity)) + @ecs.set_current_world(first) + assert_eq(@ui.scroll_position(entity).unwrap().x, 10.0) + assert_true(entity.delete()) + let replacement = first.spawn1(@ui.Node()) + assert_eq(entity.slot_index(), replacement.slot_index()) + assert_true(@ui.scroll_position(entity) is None) + assert_true(@ui.scroll_position(replacement) is None) + @ui.focus(entity) + assert_false(@ui.is_focused(replacement)) +} diff --git a/selene-core/src/ui/visual.mbt b/selene-core/src/ui/visual.mbt index b822b439..b05d39db 100644 --- a/selene-core/src/ui/visual.mbt +++ b/selene-core/src/ui/visual.mbt @@ -557,7 +557,7 @@ pub fn buttons() -> @ecs.ComponentStore[Button] { } ///| -pub fn interactions() -> @ecs.EntityTable[Interaction] { +fn interactions() -> @ecs.EntityTable[Interaction] { ui_model_world_store().interactions } @@ -624,3 +624,10 @@ pub fn text_style_for(entity : @ecs.Entity) -> @render2d_types.TextStyle2D? { baseline: layout.baseline, }) } + +///| +/// Reads the interaction state produced by the latest UI interaction pass. +pub fn interaction(entity : @ecs.Entity) -> Interaction { + guard entity.is_alive() else { None } + interactions().get(entity).unwrap_or(None) +} diff --git a/selene-core/src/visibility/pkg.generated.mbti b/selene-core/src/visibility/pkg.generated.mbti index 7b5eca6f..bc9dcdcb 100644 --- a/selene-core/src/visibility/pkg.generated.mbti +++ b/selene-core/src/visibility/pkg.generated.mbti @@ -9,7 +9,7 @@ import { // Values pub fn entity_render_layers(@ecs.Entity) -> RenderLayers -pub fn inherited_visibilities() -> @ecs.EntityTable[InheritedVisibility] +pub fn inherited_visibility(@ecs.Entity) -> InheritedVisibility? pub fn is_visible(@ecs.Entity) -> Bool @@ -21,7 +21,7 @@ pub fn matches(RenderLayers, RenderLayers) -> Bool pub fn render_layers() -> @ecs.ComponentStore[RenderLayers] -pub fn view_visibilities() -> @ecs.EntityTable[ViewVisibility] +pub fn view_visibility(@ecs.Entity) -> ViewVisibility? pub fn visibilities() -> @ecs.ComponentStore[Visibility] diff --git a/selene-core/src/visibility/runtime_access_test.mbt b/selene-core/src/visibility/runtime_access_test.mbt new file mode 100644 index 00000000..ad2fa682 --- /dev/null +++ b/selene-core/src/visibility/runtime_access_test.mbt @@ -0,0 +1,27 @@ +///| +test "visibility results follow authored components and reject stale handles" { + let previous = @ecs.current_world() + defer (match previous { + Some(world) => @ecs.set_current_world(world) + None => @ecs.clear_current_world() + }) + let first = @ecs.World() + let second = @ecs.World() + @ecs.set_current_world(first) + let parent = first.spawn1(@visibility.Visibility::Hidden) + let child = first.spawn((), parent~) + assert_true(@visibility.view_visibility(child) is None) + @visibility.visibility_propagate_system(0.0) + assert_false(@visibility.inherited_visibility(child).unwrap().visible) + assert_false(@visibility.view_visibility(child).unwrap().visible) + @visibility.visibilities().set(parent, Visible) + @visibility.visibility_propagate_system(0.0) + assert_true(@visibility.is_visible(child)) + @ecs.set_current_world(second) + assert_true(@visibility.inherited_visibility(child) is None) + @ecs.set_current_world(first) + assert_true(parent.delete()) + assert_true(@visibility.view_visibility(child) is None) + let replacement = first.spawn(()) + assert_true(@visibility.view_visibility(replacement) is None) +} diff --git a/selene-core/src/visibility/visibility.mbt b/selene-core/src/visibility/visibility.mbt index 7feaf125..cbc47545 100644 --- a/selene-core/src/visibility/visibility.mbt +++ b/selene-core/src/visibility/visibility.mbt @@ -59,12 +59,12 @@ fn visibility_state() -> VisibilityState { } ///| -pub fn inherited_visibilities() -> @ecs.EntityTable[InheritedVisibility] { +fn inherited_visibilities() -> @ecs.EntityTable[InheritedVisibility] { visibility_state().inherited } ///| -pub fn view_visibilities() -> @ecs.EntityTable[ViewVisibility] { +fn view_visibilities() -> @ecs.EntityTable[ViewVisibility] { visibility_state().view } @@ -104,3 +104,17 @@ pub fn visibility_propagate_system(_delta : Double) -> Unit { pub fn is_visible(entity : @ecs.Entity) -> Bool { view_visibilities().get(entity).map(fn(v) { v.visible }).unwrap_or(true) } + +///| +/// Reads inherited visibility produced by the latest propagation pass. +pub fn inherited_visibility(entity : @ecs.Entity) -> InheritedVisibility? { + guard entity.is_valid_in(@ecs.require_current_world()) else { None } + inherited_visibilities().get(entity) +} + +///| +/// Reads view visibility produced by the latest propagation pass. +pub fn view_visibility(entity : @ecs.Entity) -> ViewVisibility? { + guard entity.is_valid_in(@ecs.require_current_world()) else { None } + view_visibilities().get(entity) +}