Compare commits

..

8 commits

Author SHA1 Message Date
99bbb1074e
poor man's deploy script for my server
Some checks are pending
CI / Format (push) Waiting to run
CI / Docs (push) Waiting to run
CI / Clippy lints (push) Waiting to run
CI / Bevy lints (push) Waiting to run
CI / Tests (push) Waiting to run
CI / Check web (push) Waiting to run
2025-07-17 21:12:34 +08:00
a7b66d25ce
increase player size, change layer, reduce spam again 2025-07-17 17:38:28 +08:00
f48ac15cb7
reduce debug spam again, use info! to emit collision map, works on web 2025-07-17 17:22:25 +08:00
2f727e403d
finally understand how to remap coordinates between LDtk and Bevy 😵‍💫 2025-07-17 17:00:55 +08:00
ff9007c0f2
register and bundle EntityInstance, make PlayerBundle pub 2025-07-17 16:54:48 +08:00
046cc8dba8
better var name, reduce debug logging 2025-07-17 16:52:48 +08:00
e4521e2e0c
update levels positions to work around offset bug 2025-07-17 16:50:22 +08:00
56dd566af8
change y again, add StateScoped to level and player, optimize level sel. 2025-07-08 17:30:32 +08:00
5 changed files with 1673 additions and 710 deletions

File diff suppressed because it is too large Load diff

15
deploy.sh Executable file
View file

@ -0,0 +1,15 @@
set -x
export BUILD_DIR="target/bevy_web/web-release/"
export NAME="chain-reaction-collapse"
export HOST="root@antares.digitalpha.net"
export TARGET_DIR="/var/www/"
# trunk build --release --no-default-features
# bevy build --yes --release web --bundle
# for f in "${BUILD_DIR}/build/"*.wasm; do brotli -c "$f" "$f".br; done
ssh $HOST -C "rm ${TARGET_DIR}/${NAME} -r"
ssh $HOST -C "mkdir -p ${TARGET_DIR}/${NAME}"
scp -r "${BUILD_DIR}/${NAME}" "${HOST}":"${TARGET_DIR}"/
# scp ${BUILD_DIR}/index.html "${HOST}":"${TARGET_DIR}"/
# scp -r ${BUILD_DIR}/assets "${HOST}":"${TARGET_DIR}"/
# scp ${BUILD_DIR}/build/*.js "${HOST}":"${TARGET_DIR}"/build/
# scp ${BUILD_DIR}/build/*.wasm* "${HOST}":"${TARGET_DIR}"/build/

View file

@ -6,7 +6,11 @@ use bevy::{
prelude::*,
window::PrimaryWindow,
};
use bevy_ecs_ldtk::{ldtk::NeighbourLevel, prelude::*};
use bevy_ecs_ldtk::{
ldtk::{NeighbourLevel, TileInstance},
prelude::*,
utils::int_grid_index_to_grid_coords,
};
use crate::{
asset_tracking::LoadResource, audio::music, demo::player::PlayerAssets, screens::Screen,
@ -17,6 +21,7 @@ use super::player::Player;
pub(super) fn plugin(app: &mut App) {
app.add_plugins(LdtkPlugin)
.insert_resource(LevelSelection::iid("d53f9950-c640-11ed-8430-4942c04951ff"))
// .insert_resource(LevelSelection::iid("34f51d20-8990-11ee-b0d1-cfeb0e9e30f6"))
.insert_resource(LdtkSettings {
level_spawn_behavior: LevelSpawnBehavior::UseWorldTranslation {
load_level_neighbors: true,
@ -40,7 +45,8 @@ pub(super) fn plugin(app: &mut App) {
level_selection_follow_player,
cache_wall_locations,
pan_camera,
),
)
.chain(),
);
}
@ -64,6 +70,7 @@ impl FromWorld for LevelAssets {
Self {
music: assets.load("audio/music/Fluffing A Duck.ogg"),
world: assets.load("levels/world.ldtk").into(),
// world: assets.load("levels/tile-based-game.ldtk").into(),
// world: assets.load("levels/collectathon.ldtk").into(),
}
}
@ -88,17 +95,22 @@ fn pan_camera(
}
fn translate_grid_coords_entities(
mut grid_coords_entities: Query<(&mut Transform, &GridCoords), Changed<GridCoords>>,
mut grid_coords_entities: Query<
(&mut Transform, &GridCoords),
(With<Player>, Changed<GridCoords>),
>,
pan: Res<PanLevel>,
) {
// TODO: what is this used for? Why it doesn't work for a moving Player?
for (mut transform, grid_coords) in grid_coords_entities.iter_mut() {
// info!("translated pan offset: {}", pan.offset);
info!("Changed GridCoords: {grid_coords:?}");
debug!("Previous traslation: {:?}", transform.translation);
transform.translation = (bevy_ecs_ldtk::utils::grid_coords_to_translation(
*grid_coords,
IVec2::splat(GRID_SIZE),
))
.extend(transform.translation.z);
debug!("Updated traslation: {:?}", transform.translation);
}
}
@ -117,6 +129,7 @@ pub enum Direction {
E,
S,
W,
// we ignore the diagonals NE SE NW SW
}
impl TryFrom<&str> for Direction {
@ -151,6 +164,8 @@ pub fn convert_neighbors(
#[reflect(Resource)]
pub struct LevelWalls {
wall_locations: HashSet<GridCoords>,
level_tile_pos_x: i32,
level_tile_pos_y: i32,
level_width: i32,
level_height: i32,
level_neighbours: HashMap<Direction, LevelIid>,
@ -169,22 +184,43 @@ impl LevelWalls {
}
pub fn debug_collisions(&self, player_pos: &GridCoords) {
info!(
debug!(
"map for a level that is x: {} by y: {}",
self.level_width, self.level_height
);
for y in (0..self.level_height) {
debug!("player pos: {:?}", player_pos);
debug!(
"level world coordinates: x: {} y: {}",
self.level_tile_pos_x, self.level_tile_pos_y
);
// FIXME: kwwp aligned with MultiLevelWalls.in_wall.translated_coords
let player_translated_coords = GridCoords::new(
player_pos.x - self.level_tile_pos_x,
player_pos.y - (-self.level_tile_pos_y - self.level_height),
);
debug!("Player absolute coords: {:?}", *player_pos);
info!("Player relative coords: {player_translated_coords:?}");
for y in (0..self.level_height).rev() {
let mut lineoutput = String::from("");
for x in 0..self.level_width {
let coords = GridCoords::new(x, y);
if coords == *player_pos {
print!("@");
if coords.x == 0 {
// print!("[X :{:03} Y: {:03}] ", coords.x, coords.y);
lineoutput = format!("{lineoutput}[X :{:03} Y: {:03}] ", coords.x, coords.y);
}
if coords == player_translated_coords {
lineoutput = format!("{lineoutput}@");
} else if self.in_wall(&coords) {
print!("X");
lineoutput = format!("{lineoutput}X");
} else {
print!("_");
lineoutput = format!("{lineoutput}_");
}
if coords.x == (self.level_width - 1) {
// println!("[X :{:03} Y: {:03}] ", coords.x, coords.y);
lineoutput = format!("{lineoutput} [X :{:03} Y: {:03}]", coords.x, coords.y);
info!("{lineoutput}");
}
}
println!(" [y: {y:02}]");
}
}
}
@ -197,7 +233,23 @@ pub struct MultiLevelWalls {
impl MultiLevelWalls {
pub fn in_wall(&self, level: &LevelIid, grid_coords: &GridCoords) -> bool {
self.cache[level].in_wall(grid_coords)
let translated_coords = GridCoords::new(
// FIXME: x seems to work, y... not so much.
// Level UNDER the "zero level strip" by a level_height has:
// level world coordinates: x: -16 y: 0
// Player absolute coords: GridCoords { x: -8, y: -1 } y should be 15
// Player relative coords: GridCoords { x: 8, y: -1 }
// Level ABOVE the "zero level strip" by a level_height has:
// level world coordinates: x: 32 y: -32
// Player absolute coords: GridCoords { x: 42, y: 17 }
// Player relative coords: GridCoords { x: 10, y: 17 } y should be 1
// level world coordinates: x: 32 y: -16
// Player absolute coords: GridCoords { x: 41, y: 16 }
// Player relative coords: GridCoords { x: 9, y: 16 } y should be 0
grid_coords.x - self.cache[level].level_tile_pos_x,
grid_coords.y - (-self.cache[level].level_tile_pos_y - self.cache[level].level_height),
);
self.cache[level].in_wall(&translated_coords)
}
pub fn debug_collisions(&self, level: &LevelIid, player_pos: &GridCoords) {
if let Some(level) = self.cache.get(level) {
@ -214,67 +266,27 @@ pub fn spawn_level(
window: Single<&Window, With<PrimaryWindow>>,
level_assets: Res<LevelAssets>,
) {
let half_size = window.size() / 2.0;
// let half_size = window.size() / 2.0;
commands.spawn((
Name::new("Ldtk level"),
StateScoped(Screen::Gameplay),
LdtkWorldBundle {
ldtk_handle: level_assets.world.clone(),
transform: Transform::from_xyz(-half_size.x, half_size.y, 0.0),
// transform: Transform::from_xyz(-half_size.x, half_size.y, 0.0),
..Default::default()
},
));
}
fn _old_cache_wall_locations(
level_selection: Res<LevelSelection>,
mut level_walls: ResMut<LevelWalls>,
mut level_events: EventReader<LevelEvent>,
walls: Query<&GridCoords, With<Wall>>,
ldtk_project_entities: Query<&LdtkProjectHandle>,
ldtk_project_assets: Res<Assets<LdtkProject>>,
) -> Result {
for level_event in level_events.read() {
if let LevelEvent::Spawned(level_iid) = level_event {
let ldtk_project = ldtk_project_assets
.get(ldtk_project_entities.single()?)
.expect("LdtkProject should be loaded when level is spawned");
let level = ldtk_project
.get_raw_level_by_iid(level_iid.get())
.expect("spawned level should exist in project");
let wall_locations = walls.iter().copied().collect();
info!(
"loading level of dimension x: {} by y: {}",
level.px_wid, level.px_hei
);
let new_level_walls = LevelWalls {
wall_locations,
level_width: level.px_wid / GRID_SIZE,
level_height: level.px_hei / GRID_SIZE,
..Default::default()
};
*level_walls = new_level_walls;
info!(
"new level tile dimensions are x: {} y {}",
level_walls.level_width, level_walls.level_height
);
level_walls.debug_collisions(&GridCoords::default());
}
}
Ok(())
}
fn cache_wall_locations(
mut levels_wall_cache: ResMut<MultiLevelWalls>,
mut level_events: EventReader<LevelEvent>,
walls: Query<(&ChildOf, &GridCoords), With<Wall>>,
ldtk_project_entities: Query<&LdtkProjectHandle>,
ldtk_project_assets: Res<Assets<LdtkProject>>,
) -> Result {
let multi_level_walls = levels_wall_cache.into_inner();
let pippo: TileInstance = TileInstance::default();
for level_event in level_events.read() {
if let LevelEvent::Spawned(level_iid) = level_event {
@ -286,47 +298,60 @@ fn cache_wall_locations(
.expect("spawned level should exist in project");
let mut wall_locations = HashSet::<GridCoords>::default();
info!("current level neighbours: {:?}", level.neighbours);
let mut last_coord: GridCoords = GridCoords::default();
trace!("current level neighbours: {:?}", level.neighbours);
trace!(
"Level world coordinates: x [{}], y[{}]",
level.world_x, level.world_y
);
let level_tile_pos_x = level.world_x / GRID_SIZE;
let level_tile_pos_y = level.world_y / GRID_SIZE;
let level_tile_width = level.px_wid / GRID_SIZE;
trace!(
"Level tile coordinates: x [{}], y[{}]",
level_tile_pos_x, level_tile_pos_y
);
if let Some(layers) = level.layer_instances.clone() {
// info!("layers: {:?}", layers);
layers.iter().for_each(|field| {
info!("Layer field: {:?}", field.identifier);
if field.identifier == "Walls" {
info!("Found walls layer: {:?}", field.int_grid_csv);
info!("Trying to format it");
// FIXME: a .rev() here? It doesn't look necessary from what gets printed
// remember to fix the supposed "map dragging" too
for y in (0..(level.px_hei / GRID_SIZE)) {
for x in (0..(level.px_wid / GRID_SIZE)) {
let index = (y * level.px_wid / GRID_SIZE + x) as usize;
if let Some(value) = field.int_grid_csv.get(index) {
if *value == 1 {
print!("X");
wall_locations.insert(GridCoords::new(x, y));
} else {
print!("_");
}
}
for (i, value) in field.int_grid_csv.iter().enumerate() {
let gc = int_grid_index_to_grid_coords(
i,
(level.px_wid / GRID_SIZE) as u32,
(level.px_hei / GRID_SIZE) as u32,
);
let Some(gc) = gc else {
warn!("Invalid GridCoords for index {i}");
continue;
};
last_coord = GridCoords::new(gc.x, gc.y);
if last_coord.x == 0 {
print!("[X :{:03} Y: {:03}] ", last_coord.x, last_coord.y);
}
if *value == 1 {
print!("X");
wall_locations.insert(last_coord);
} else {
print!("_");
}
if last_coord.x == (level_tile_width - 1) {
println!(" [X :{:03} Y: {:03}]", last_coord.x, last_coord.y);
}
println!(" [y: {y:02}]");
}
}
});
}
// level.iter_fields().for_each(|field| {
// info!("Field: {:?}", field);
// });
// let wall_locations = walls.iter().map(|e| e.1).copied().collect();
info!(
"loading level of dimension x: {} by y: {}",
level.px_wid, level.px_hei
);
multi_level_walls.cache.insert(
level_iid.clone(), // You'll need to clone the key since HashMap takes ownership
LevelWalls {
wall_locations,
level_tile_pos_x,
level_tile_pos_y,
level_width: level.px_wid / GRID_SIZE,
level_height: level.px_hei / GRID_SIZE,
level_neighbours: convert_neighbors(&level.neighbours).unwrap_or_default(), // Convert neighbours to a HashMap
@ -339,7 +364,6 @@ fn cache_wall_locations(
multi_level_walls.cache[level_iid].level_height,
multi_level_walls.cache[level_iid].level_neighbours,
);
multi_level_walls.cache[level_iid].debug_collisions(&GridCoords::default());
}
}
Ok(())
@ -374,6 +398,11 @@ fn level_selection_follow_player(
};
if level_bounds.contains(player_transform.translation().truncate()) {
if *level_selection == LevelSelection::Iid(level_iid.clone()) {
// Player is already in the current level, no need to change
return Ok(());
}
info!("Setting current level to {level_iid}");
*level_selection = LevelSelection::Iid(level_iid.clone());
}
}

View file

@ -78,7 +78,7 @@ fn apply_movement(
// no velocity... for now? It'd be nice to have different speed depending on the tile type
// let velocity = controller.max_speed * controller.intent;
for mut player_grid_coords in players.iter_mut() {
for mut player_abs_coords in players.iter_mut() {
let movement_direction = if controller.intent.x == 1.0 {
GridCoords::new(1, 0)
} else if controller.intent.x == -1.0 {
@ -95,14 +95,14 @@ fn apply_movement(
warn!("Unrecognized intent: {:?}", controller.intent);
return;
};
info!("player old coords: {:?}", player_grid_coords);
let destination = *player_grid_coords + movement_direction;
info!("player old absolute coords: {:?}", player_abs_coords);
let destination = *player_abs_coords + movement_direction;
info!("commanded movement player coords: {:?}", destination);
info!("Level selection: {:?}", level_selection_iid);
debug!("Level selection: {:?}", level_selection_iid);
if !level_walls.in_wall(level_selection_iid, &destination) {
*player_grid_coords = destination;
info!("new player grid_coords: {:?}", player_grid_coords);
info!(
*player_abs_coords = destination;
info!("new player grid_coords: {:?}", player_abs_coords);
trace!(
"new player screen_coords: {:?}",
player_transform_query.single()
);
@ -110,7 +110,7 @@ fn apply_movement(
} else {
info!("SDENG!");
}
level_walls.debug_collisions(level_selection_iid, &player_grid_coords);
level_walls.debug_collisions(level_selection_iid, &player_abs_coords);
}
}
}

View file

@ -10,14 +10,16 @@ use crate::{
AppSystems, PausableSystems,
asset_tracking::LoadResource,
demo::{
animation::PlayerAnimation,
movement::{MovementController, ScreenWrap},
// animation::PlayerAnimation,
movement::MovementController,
},
screens::Screen,
};
pub(super) fn plugin(app: &mut App) {
app.register_type::<Player>();
app.register_type::<EntityInstance>();
app.register_type::<PlayerAssets>();
app.load_resource::<PlayerAssets>();
app.register_ldtk_entity::<PlayerBundle>("Player");
@ -71,16 +73,21 @@ pub(super) fn plugin(app: &mut App) {
pub struct Player;
#[derive(Default, Bundle, LdtkEntity)]
struct PlayerBundle {
pub struct PlayerBundle {
#[sprite_sheet]
sprite_sheet: Sprite,
pub sprite_sheet: Sprite,
#[worldly]
worldly: Worldly,
pub worldly: Worldly,
#[grid_coords]
grid_coords: GridCoords,
// non-ecsldtk-related components
player_comp: Player,
movement: MovementController,
pub grid_coords: GridCoords,
#[from_entity_instance]
pub entity: EntityInstance,
// EntityInstance gives access to entity-specific fields defined in LDtk as
// EntityInstance.field_instances.get("field_name")
// non-ecs-ldtk-related components
pub player: Player,
pub movement: MovementController,
}
fn record_player_directional_input(
@ -89,12 +96,15 @@ fn record_player_directional_input(
) {
// Collect directional input.
let mut intent = Vec2::ZERO;
// TODO: check axes for gridcoords!
// TODO: example ldkt has down -1 and up +1... but here the opposite happens?!
// additionally: why the heck the Player is offsetted by 25 y?
// why the player is displayed at its set location but then is teleported the first time I
// update its GridCoords?
if input.just_pressed(KeyCode::KeyW) || input.pressed(KeyCode::ArrowUp) {
intent.y -= 1.0;
intent.y += 1.0;
}
if input.just_pressed(KeyCode::KeyS) || input.pressed(KeyCode::ArrowDown) {
intent.y += 1.0;
intent.y -= 1.0;
}
if input.just_pressed(KeyCode::KeyA) || input.pressed(KeyCode::ArrowLeft) {
intent.x -= 1.0;
@ -103,10 +113,6 @@ fn record_player_directional_input(
intent.x += 1.0;
}
// Normalize intent so that diagonal movement is the same speed as horizontal / vertical.
// This should be omitted if the input comes from an analog stick instead.
let intent = intent.normalize_or_zero();
// Apply movement intent to controllers.
for mut controller in &mut controller_query {
controller.intent = intent;
@ -144,7 +150,7 @@ impl FromWorld for PlayerAssets {
}
fn process_player(
mut _commands: Commands,
mut commands: Commands,
new_players: Query<(Entity, &GridCoords), Added<Player>>,
) {
for (player_entity, player_coords) in new_players.iter() {
@ -152,5 +158,8 @@ fn process_player(
"Spawned new player: {:?} at {:?}",
player_entity, player_coords
);
commands
.entity(player_entity)
.insert(StateScoped(Screen::Gameplay));
}
}