rusting_engine 2.0.3

Vulkan 3D game engine with GPU-accelerated physics for massive physics-heavy scenes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//! First slice of the 2D path: tile maps and a side-view platformer
//! controller. Sprites are `MeshRenderer`s with the `Quad` primitive and an
//! unlit material; a 2D camera is a `Camera` with an orthographic
//! projection looking down -Z; screen-space UI is `HudElement`.
//!
//! 2D scenes live in the XY plane: +X is right, +Y is up, and the camera
//! sits at +Z. CPU physics stays 3D; 2D colliders are boxes and capsules
//! centered on z = 0.

use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;

use bevy_ecs::entity::Entity;
use bevy_ecs::prelude::{
    Commands, Component, DetectChanges, Query, Ref, RemovedComponents, Res,
    ResMut, Without,
};
use serde::{Deserialize, Serialize};

use super::{
    ActionMap, CharacterMove, Collider, ColliderShape, FrameTime, MeshRenderer,
    PhysicsBody, PhysicsWorld, RigidBody, RigidBodyKind, RuntimeInput,
    PLAYER_JUMP, PLAYER_LEFT, PLAYER_RIGHT,
};
use crate::assets::{
    AlphaMode, AssetServer, Handle, MaterialAsset, MaterialModel,
    PrimitiveShape,
};
use crate::Transform;

/// How one tile character draws and collides.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct TileKind {
    /// Linear RGBA; multiplies the texture.
    pub color: [f32; 4],
    /// Image path relative to the project's `assets` folder. Transparent
    /// pixels (alpha below 0.5) are cut out.
    pub texture: Option<PathBuf>,
    /// Blocks bodies with a CPU collider.
    pub solid: bool,
}

impl Default for TileKind {
    fn default() -> Self {
        Self {
            color: [1.0; 4],
            texture: None,
            solid: true,
        }
    }
}

/// Farthest column or row `set_tile` may grow a map to; a stray coordinate
/// must not allocate gigabytes.
pub const MAX_TILE_CELLS: usize = 4096;

/// A grid of square tiles written as text rows, top row first. Each
/// character looks up its [`TileKind`] in `tiles`; characters without one
/// (such as space or `.`) are empty. The entity's `Transform` position is
/// the top-left corner of the grid; rotation and scale are not applied.
///
/// Tiles are spawned when the map is added or changed, as entities without
/// a `SceneId`, so they are never saved. Each run of solid tiles in a row
/// gets one fixed box collider.
#[derive(Component, Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct TileMap {
    /// Tile edge length in metres.
    pub tile_size: f32,
    pub rows: Vec<String>,
    /// Keyed by a one-character string.
    pub tiles: BTreeMap<String, TileKind>,
}

impl Default for TileMap {
    fn default() -> Self {
        Self {
            tile_size: 1.0,
            rows: vec!["#...#".into(), "#####".into()],
            tiles: BTreeMap::from([("#".into(), TileKind::default())]),
        }
    }
}

impl TileMap {
    /// Center of the cell at `column`, `row` relative to the map origin.
    #[must_use]
    pub fn cell_center(&self, column: usize, row: usize) -> [f32; 2] {
        [
            (column as f32 + 0.5) * self.tile_size,
            -(row as f32 + 0.5) * self.tile_size,
        ]
    }

    /// The cell under a point relative to the map origin, if the point is
    /// right of and below the origin and within [`MAX_TILE_CELLS`] of it. The
    /// cell may lie past the last row or column.
    #[must_use]
    pub fn cell_at(&self, local: [f32; 2]) -> Option<(usize, usize)> {
        let column = (local[0] / self.tile_size).floor();
        let row = (-local[1] / self.tile_size).floor();
        let range = 0.0..MAX_TILE_CELLS as f32;
        (range.contains(&column) && range.contains(&row))
            .then_some((column as usize, row as usize))
    }

    /// The character in a cell; `.` past the end of the grid.
    #[must_use]
    pub fn cell(&self, column: usize, row: usize) -> char {
        self.rows
            .get(row)
            .and_then(|text| text.chars().nth(column))
            .unwrap_or('.')
    }

    /// Writes `character` into a cell, padding with `.` to reach it.
    /// Returns false when the cell already held it.
    pub fn set_cell(
        &mut self,
        column: usize,
        row: usize,
        character: char,
    ) -> bool {
        if self.cell(column, row) == character {
            return false;
        }
        if self.rows.len() <= row {
            self.rows.resize(row + 1, String::new());
        }
        let mut cells: Vec<char> = self.rows[row].chars().collect();
        if cells.len() <= column {
            cells.resize(column + 1, '.');
        }
        cells[column] = character;
        self.rows[row] = cells.into_iter().collect();
        true
    }

    /// Writes `character` into every cell of the rectangle between two
    /// corner cells. Returns true when a cell changed.
    pub fn fill_rect(
        &mut self,
        from: (usize, usize),
        to: (usize, usize),
        character: char,
    ) -> bool {
        let columns = from.0.min(to.0)..=from.0.max(to.0);
        let mut changed = false;
        // One pass per row: `set_cell` per cell rebuilds the row each time.
        for row in from.1.min(to.1)..=from.1.max(to.1) {
            if columns
                .clone()
                .all(|column| self.cell(column, row) == character)
            {
                continue;
            }
            if self.rows.len() <= row {
                self.rows.resize(row + 1, String::new());
            }
            let mut cells: Vec<char> = self.rows[row].chars().collect();
            if cells.len() <= *columns.end() {
                cells.resize(columns.end() + 1, '.');
            }
            cells[columns.clone()].fill(character);
            self.rows[row] = cells.into_iter().collect();
            changed = true;
        }
        changed
    }

    /// Writes `character` into the cells of a straight line between two
    /// cells. Returns true when a cell changed.
    pub fn fill_line(
        &mut self,
        from: (usize, usize),
        to: (usize, usize),
        character: char,
    ) -> bool {
        let mut changed = false;
        for (column, row) in Self::line_cells(from, to) {
            changed |= self.set_cell(column, row, character);
        }
        changed
    }

    /// The cells of a straight line from `from` to `to`, both included,
    /// joined edge or corner to corner (Bresenham's line).
    #[must_use]
    pub fn line_cells(
        from: (usize, usize),
        to: (usize, usize),
    ) -> Vec<(usize, usize)> {
        let (mut x, mut y) = (from.0 as i64, from.1 as i64);
        let (end_x, end_y) = (to.0 as i64, to.1 as i64);
        let (dx, dy) = ((end_x - x).abs(), -(end_y - y).abs());
        let (step_x, step_y) = ((end_x - x).signum(), (end_y - y).signum());
        let mut error = dx + dy;
        let mut cells = vec![(from.0, from.1)];
        while (x, y) != (end_x, end_y) {
            let doubled = 2 * error;
            if doubled >= dy {
                error += dy;
                x += step_x;
            }
            if doubled <= dx {
                error += dx;
                y += step_y;
            }
            cells.push((x as usize, y as usize));
        }
        cells
    }

    /// Flood fills the cells joined edge to edge with the cell at `column`,
    /// `row` that hold the same character, inside the grid's used area. A
    /// cell outside that area fills nothing. Returns true when a cell
    /// changed.
    pub fn fill(&mut self, column: usize, row: usize, character: char) -> bool {
        let target = self.cell(column, row);
        let width = self
            .rows
            .iter()
            .map(|text| text.chars().count())
            .max()
            .unwrap_or(0);
        let height = self.rows.len();
        if target == character || column >= width || row >= height {
            return false;
        }
        let mut open = vec![(column, row)];
        let mut changed = false;
        while let Some((column, row)) = open.pop() {
            if column >= width
                || row >= height
                || self.cell(column, row) != target
            {
                continue;
            }
            changed |= self.set_cell(column, row, character);
            open.extend([(column + 1, row), (column, row + 1)]);
            open.extend(column.checked_sub(1).map(|left| (left, row)));
            open.extend(row.checked_sub(1).map(|up| (column, up)));
        }
        changed
    }

    /// The kind at `column`, `row`, if the cell is not empty.
    #[must_use]
    pub fn kind_at(&self, column: usize, row: usize) -> Option<&TileKind> {
        let character = self.rows.get(row)?.chars().nth(column)?;
        self.tiles.get(character.encode_utf8(&mut [0; 4]) as &str)
    }
}

/// Marks an entity spawned for the [`TileMap`] on the given entity.
#[derive(Component, Clone, Copy, Debug, PartialEq, Eq)]
pub struct TileOf(pub Entity);

/// Per frame: respawns the tiles of every added or changed map and removes
/// the tiles of removed maps.
pub(super) fn build_tile_maps(
    mut commands: Commands,
    assets: Option<ResMut<AssetServer>>,
    maps: Query<(Entity, Ref<TileMap>, Ref<Transform>)>,
    mut removed: RemovedComponents<TileMap>,
    tiles: Query<(Entity, &TileOf)>,
) {
    let mut stale: BTreeSet<Entity> = removed.read().collect();
    let changed: Vec<_> = maps
        .iter()
        .filter(|(_, map, transform)| {
            map.is_changed() || transform.is_changed()
        })
        .collect();
    stale.extend(changed.iter().map(|(entity, ..)| *entity));
    // Owners gone without a removal event (a scene reload in the editor).
    stale.extend(
        tiles
            .iter()
            .map(|(_, owner)| owner.0)
            .filter(|owner| !maps.contains(*owner)),
    );
    if stale.is_empty() {
        return;
    }
    for (tile, owner) in &tiles {
        if stale.contains(&owner.0) {
            commands.entity(tile).despawn();
        }
    }
    let Some(mut assets) = assets else {
        return;
    };
    let quad = assets.builtin_primitive(PrimitiveShape::Quad);
    for (entity, map, transform) in changed {
        let origin = transform.position;
        let size = map.tile_size;
        let mut materials = BTreeMap::new();
        for (row, text) in map.rows.iter().enumerate() {
            let mut run: Option<usize> = None;
            let columns = text.chars().count();
            for column in 0..=columns {
                let kind = map.kind_at(column, row);
                if let Some(kind) = kind {
                    let key = text.chars().nth(column).unwrap_or(' ');
                    let material = *materials
                        .entry(key)
                        .or_insert_with(|| tile_material(&mut assets, kind));
                    let [x, y] = map.cell_center(column, row);
                    commands.spawn((
                        Transform {
                            position: [origin[0] + x, origin[1] + y, origin[2]],
                            scale: [size, size, 1.0],
                            ..Transform::default()
                        },
                        MeshRenderer {
                            mesh: quad,
                            material,
                            cast_shadows: false,
                            receive_shadows: false,
                        },
                        TileOf(entity),
                    ));
                }
                let solid = kind.is_some_and(|kind| kind.solid);
                match (solid, run) {
                    (true, None) => run = Some(column),
                    (false, Some(start)) => {
                        run = None;
                        let width = (column - start) as f32 * size;
                        let [x, y] = map.cell_center(start, row);
                        commands.spawn((
                            Transform::new([
                                origin[0] + x - size / 2.0 + width / 2.0,
                                origin[1] + y,
                                origin[2],
                            ]),
                            PhysicsBody::default(),
                            RigidBody {
                                kind: RigidBodyKind::Fixed,
                                ..RigidBody::default()
                            },
                            Collider {
                                shape: ColliderShape::Box {
                                    half_extents: [
                                        width / 2.0,
                                        size / 2.0,
                                        size / 2.0,
                                    ],
                                },
                                ..Collider::default()
                            },
                            TileOf(entity),
                        ));
                    }
                    _ => {}
                }
            }
        }
    }
}

fn tile_material(
    assets: &mut AssetServer,
    kind: &TileKind,
) -> Handle<MaterialAsset> {
    let texture = kind.texture.as_ref().and_then(|path| {
        assets
            .textures
            .handle_for_path(path)
            .map(Ok)
            .unwrap_or_else(|| assets.load_texture(path))
            .map_err(|error| eprintln!("tile texture: {error}"))
            .ok()
    });
    let material = MaterialAsset {
        model: MaterialModel::Unlit,
        alpha_mode: if texture.is_some() {
            AlphaMode::Mask { cutoff: 0.5 }
        } else {
            AlphaMode::Opaque
        },
        base_color: kind.color,
        base_color_texture: texture,
        ..MaterialAsset::default()
    };
    let existing = assets.materials.iter().find_map(|(handle, existing)| {
        (*existing == material).then_some(handle)
    });
    existing.unwrap_or_else(|| assets.materials.insert(material))
}

/// Default body of a [`PlatformerController`] without a `Collider`: 1 m
/// tall and 0.6 m wide.
pub const DEFAULT_PLATFORMER_SHAPE: ColliderShape = ColliderShape::Capsule {
    half_height: 0.2,
    radius: 0.3,
};

/// Side-view run and jump in the XY plane. Reads `player.left`,
/// `player.right`, and `player.jump` from the [`ActionMap`]; speeds are in
/// metres per second and `gravity` in metres per second squared. Parent an
/// orthographic camera to the body to follow it.
#[derive(Component, Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct PlatformerController {
    pub run_speed: f32,
    pub jump_speed: f32,
    pub gravity: f32,
    /// Collision layers the body stops against.
    pub collision_mask: u32,
    #[serde(skip)]
    pub vertical_speed: f32,
    #[serde(skip)]
    pub grounded: bool,
    /// Seconds a jump press stays pending; set to [`JUMP_GRACE`] on press.
    #[serde(skip)]
    pub jump_buffer: f32,
    /// Seconds since the body was last grounded.
    #[serde(skip)]
    pub air_time: f32,
    /// The floor body under the controller after the last step and where
    /// it was, so a moving platform carries the controller.
    #[serde(skip)]
    pub floor: Option<(Entity, [f32; 3])>,
}

/// A jump pressed up to this long before landing, or this long after
/// running off a ledge, still jumps.
pub const JUMP_GRACE: f32 = 0.1;

impl Default for PlatformerController {
    fn default() -> Self {
        Self {
            run_speed: 5.0,
            jump_speed: 8.0,
            gravity: 20.0,
            collision_mask: u32::MAX,
            vertical_speed: 0.0,
            grounded: false,
            jump_buffer: 0.0,
            air_time: 0.0,
            floor: None,
        }
    }
}

/// Per rendered frame: remembers jump presses for the next fixed step.
pub(super) fn platformer_jump(
    input: Res<RuntimeInput>,
    actions: Res<ActionMap>,
    mut players: Query<&mut PlatformerController>,
) {
    if actions.just_pressed(&input, PLAYER_JUMP) {
        for mut player in &mut players {
            player.jump_buffer = JUMP_GRACE;
        }
    }
}

/// Per fixed step: running, gravity, jumping, and collision sliding.
#[allow(clippy::type_complexity)]
pub(super) fn platformer_move(
    time: Res<FrameTime>,
    input: Res<RuntimeInput>,
    actions: Res<ActionMap>,
    physics: Res<PhysicsWorld>,
    mut players: Query<(
        Entity,
        &mut PlatformerController,
        &mut Transform,
        Option<&Collider>,
    )>,
    floors: Query<
        (
            &Transform,
            Option<&super::Parent>,
            Option<&super::GlobalTransform>,
        ),
        Without<PlatformerController>,
    >,
) {
    let floor_at = |floor: Entity| {
        let (t, parent, global) = floors.get(floor).ok()?;
        Some(super::cpu_physics::world_position(t, parent, global))
    };
    let dt = time.fixed_delta.as_secs_f32();
    let run = f32::from(u8::from(actions.held(&input, PLAYER_RIGHT)))
        - f32::from(u8::from(actions.held(&input, PLAYER_LEFT)));
    for (entity, mut player, mut transform, collider) in &mut players {
        if player.jump_buffer > 0.0 && player.air_time <= JUMP_GRACE {
            player.vertical_speed = player.jump_speed;
            player.jump_buffer = 0.0;
            // No second jump from the same grace window.
            player.air_time = f32::INFINITY;
        }
        player.jump_buffer = (player.jump_buffer - dt).max(0.0);
        player.vertical_speed -= player.gravity * dt;
        let shape = collider
            .map_or(DEFAULT_PLATFORMER_SHAPE, |collider| collider.shape);
        let start = CharacterMove::ride(
            &physics,
            shape,
            transform.position,
            player.floor,
            player.collision_mask,
            entity,
            floor_at,
        );
        let moved = physics.move_character(
            shape,
            start,
            [run * player.run_speed * dt, player.vertical_speed * dt, 0.0],
            player.collision_mask,
            Some(entity),
        );
        player.grounded = moved.grounded;
        if moved.grounded && player.vertical_speed < 0.0 {
            player.vertical_speed = 0.0;
            player.air_time = 0.0;
        } else {
            player.air_time += dt;
        }
        if moved.ceiling && player.vertical_speed > 0.0 {
            player.vertical_speed = 0.0;
        }
        player.floor = moved
            .floor
            .and_then(|floor| Some((floor, floor_at(floor)?)));
        transform.position = moved.position;
    }
}