1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
//! A system responsible for executing character movements.

use amethyst::{
    core::{math::Vector3, Time, Transform},
    ecs::{
        Entities,
        Join,
        Read,
        ReadExpect,
        ReadStorage,
        System,
        Write,
        WriteExpect,
        WriteStorage,
    },
    renderer::SpriteRender,
};

use crate::{
    common::get_direction_offset,
    entities::{
        AnimationTable,
        character::{
            AllowedMovements,
            Character,
            CharacterAnimation,
            CharacterMovement,
            MovementType,
            PlayerEntity,
            StepKind,
        },
    },
    events::EventQueue,
    map::{change_player_tile, CoordinateSystem, MapHandler},
};

/// A system responsible for executing character movements. It finds characters
/// that contain a
/// [`CharacterMovement`](../../entities/character/struct.CharacterMovement.html)
/// component (typically added by a
/// [`CharacterSingleMoveEvent`](../../events/character_single_move_event/struct.CharacterSingleMoveEvent.html)
/// or by a
/// [`CharacterMoveEvent`](../../events/character_move_event/struct.CharacterMoveEvent.html)
/// ) and performs the movement described by it.
///
/// This system is not perfectly equivalent for human players and NPCs.
/// The following effects only apply to human players:
///   * If the destination tile is blocked, the movement is canceled;
///   * After the movement is completed, the following map events happen, in
///     this order:
///     * If the movement includes a map change, `OnMapEnter` is triggered on
///       the new map;
///     * `OnTileChange` map events are triggered;
///     * `OnStep` tile events are triggered.
///
/// As for NPCs, the following effects are exclusive:
///   * If the destination tile is blocked, the movement is suspended until the
///     tile becomes available again. In particular, this makes
///     `CharacterSingleMoveEvent` and `CharacterMoveEvent` "hang" until that
///     happens.
///   * During the movement, the interaction tile (i.e the tile that triggers
///     interaction with this NPC) moves along with the NPC at the start of the
///     movement.
///
pub struct CharacterMovementSystem;

impl<'a> System<'a> for CharacterMovementSystem {
    type SystemData = (
        WriteStorage<'a, Character>,
        WriteStorage<'a, CharacterMovement>,
        ReadStorage<'a, AllowedMovements>,
        WriteStorage<'a, Transform>,
        WriteStorage<'a, AnimationTable<CharacterAnimation>>,
        WriteStorage<'a, SpriteRender>,
        Entities<'a>,
        ReadExpect<'a, PlayerEntity>,
        WriteExpect<'a, MapHandler>,
        Write<'a, EventQueue>,
        Read<'a, Time>,
    );

    fn run(&mut self, (
        mut characters,
        mut movements,
        allowed_movements_storage,
        mut transforms,
        mut animation_tables,
        mut sprite_renders,
        entities,
        player_entity,
        mut map,
        mut event_queue,
        time,
    ): Self::SystemData) {
        let mut static_characters = Vec::new();

        for (
            entity,
            character,
            movement_data,
            allowed_movements,
            transform,
            animation_table,
            sprite_render
        ) in (
            &entities,
            &mut characters,
            &mut movements,
            &allowed_movements_storage,
            &mut transforms,
            &mut animation_tables,
            &mut sprite_renders,
        ).join() {
            let delta_seconds = time.delta_seconds();
            let is_player = entity == player_entity.0;

            if !movement_data.started {
                if map.is_tile_blocked(&movement_data.to) {
                    if is_player {
                        static_characters.push(entity);
                    }
                    continue;
                }

                on_movement_start(
                    character,
                    movement_data,
                    allowed_movements,
                    animation_table,
                    sprite_render,
                );

                map.mark_tile_as_solid(&movement_data.to);

                if !is_player {
                    map.change_npc_tile(&movement_data.from, &movement_data.to);
                }

                movement_data.started = true;
            }

            if movement_data.estimated_time <= delta_seconds {
                on_movement_finish(
                    character,
                    movement_data,
                    allowed_movements,
                    transform,
                    animation_table,
                    sprite_render,
                    if is_player { Some(&player_entity) } else { None },
                    &mut map,
                    &mut event_queue,
                );

                static_characters.push(entity);
                continue;
            }

            movement_data.estimated_time -= delta_seconds;

            let (offset_x, offset_y) = get_direction_offset::<f32>(&character.facing_direction);
            let frame_velocity = movement_data.velocity * delta_seconds;
            transform.prepend_translation_x(offset_x * frame_velocity);
            transform.prepend_translation_y(offset_y * frame_velocity);
        }

        for entity in static_characters {
            movements.remove(entity);
        }
    }
}

fn on_movement_start(
    character: &Character,
    movement_data: &mut CharacterMovement,
    allowed_movements: &AllowedMovements,
    animation_table: &mut AnimationTable<CharacterAnimation>,
    sprite_render: &mut SpriteRender,
) {
    let data = allowed_movements
        .get_movement_data(&movement_data.movement_type)
        .unwrap();
    sprite_render.sprite_sheet = data.sprite_sheet.clone();

    animation_table.change_animation(CharacterAnimation::Moving(
        movement_data.movement_type.clone(),
        character.facing_direction.clone(),
    ));

    if movement_data.step_kind == StepKind::Right {
        animation_table.skip_to_frame_index(2);
    }
}

fn on_movement_finish(
    character: &mut Character,
    movement_data: &mut CharacterMovement,
    allowed_movements: &AllowedMovements,
    transform: &mut Transform,
    animation_table: &mut AnimationTable<CharacterAnimation>,
    sprite_render: &mut SpriteRender,
    player_entity: Option<&PlayerEntity>,
    map: &mut MapHandler,
    event_queue: &mut EventQueue,
) {
    transform.set_translation(Vector3::new(
        movement_data.to.position.x(),
        movement_data.to.position.y(),
        0.,
    ));

    if let Some(player_entity) = player_entity {
        change_player_tile(
            &movement_data.from,
            &movement_data.to,
            &player_entity,
            map,
            event_queue,
        );
    }

    if movement_data.movement_type == MovementType::Run {
        let data = allowed_movements
            .get_movement_data(&MovementType::Walk)
            .unwrap();

        sprite_render.sprite_sheet = data.sprite_sheet.clone();
    }

    animation_table.change_animation(CharacterAnimation::Idle(
        character.facing_direction.clone(),
    ));

    character.next_step.invert();

    map.remove_solid_mark(&movement_data.from);
}