bevy_elements 0.7.2

Living environments for Bevy: sun, moon and stars, climate-driven weather, GPU wind, volumetric clouds, rain, snow and fog, lightning, terrain with hydraulic and thermal erosion, flooding, snow cover, wetness and dust — simulated in compute shaders.
Documentation
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! Trails: a walker and a four-wheeled vehicle press tracks into snow, sand or mud.
//!
//! `cargo run --release --example trails`
//!
//! `ELEMENTS_GROUND=snow` (default: the hills under forced snow; grow it before the first frame
//! with `ELEMENTS_GROW_HOURS=24`, then the sky clears), `sand` (the dunes preset, dry) or `mud`
//! (the hills after rain: `ELEMENTS_GROW_HOURS=6`). The walker
//! circles 6 m around the scene's centre, planting a foot every half second (an ellipse
//! 0.10 × 0.26 m, 760 N); the vehicle (four wheels, 0.20 × 0.32 m, 3400 N each) drives a 14 m loop
//! at 4 m/s. `ELEMENTS_HOUR` holds an hour (default 10.5), `ELEMENTS_EYE=x,y,z` places the camera
//! that many metres above the ground (default `0,2.2,-11`), `ELEMENTS_LOOK=x,z` aims it (default
//! the centre), `ELEMENTS_PRESET` replaces the weather after the ground is grown (e.g. `Snow` to
//! watch new snow fill the tracks, with `ELEMENTS_SCALE=600` for ten game minutes a second).
//! `ELEMENTS_TERRAIN=mesh` replaces the crate's terrain with a game's own: a hilly mesh in
//! `WeatheredMaterial` (`with_trails()`), described to the trails by a `TrailGround` of the same
//! height function, its snow and wetness `SurfaceWeathering`'s, no `Terrain` spawned
//! (`docs/research/trails-game-ground.md`). `ELEMENTS_DETAIL` and `ELEMENTS_FINEST_M` set
//! `TerrainLook`'s detail knobs (the route grain follows them). `ELEMENTS_FRAMES` and `ELEMENTS_SHOT` work as in the
//! other examples.

mod common;

use std::f32::consts::TAU;
use std::time::Duration;

use bevy::ecs::system::SystemParam;
use bevy::prelude::*;
use bevy_elements::*;
use common::{ExampleHarness, camera, terrain_look_env};

/// The loops' centre, world XZ.
const CENTRE: Vec2 = Vec2::new(0.0, 0.0);
const WALK_RADIUS_M: f32 = 6.0;
const WALK_SPEED_MS: f32 = 1.4;
const STEP_S: f32 = 0.5;
const STEP_WIDTH_M: f32 = 0.11;
const FOOT_HALF: Vec2 = Vec2::new(0.05, 0.13);
const FOOT_LOAD_N: f32 = 760.0;
const DRIVE_RADIUS_M: f32 = 14.0;
const DRIVE_SPEED_MS: f32 = 4.0;
const WHEELBASE_M: f32 = 2.6;
const TRACK_M: f32 = 1.5;
const WHEEL_HALF: Vec2 = Vec2::new(0.10, 0.16);
const WHEEL_LOAD_N: f32 = 3400.0;

#[derive(Clone, Copy, PartialEq)]
enum Ground {
    Snow,
    Sand,
    Mud,
}

#[derive(Resource)]
struct Scene {
    ground: Ground,
    preset: Option<WeatherPreset>,
    /// The ground is a game's own mesh, not the crate's terrain.
    mesh: bool,
}

/// The game's own ground under `ELEMENTS_TERRAIN=mesh`: gentle hills, world height at world XZ.
fn hills(xz: Vec2) -> f32 {
    1.6 * (0.07 * xz.x).sin() * (0.05 * xz.y).cos() + 0.5 * (0.19 * xz.x + 0.13 * xz.y).sin()
}

/// A grid mesh of `hills` over `extent` metres, a vertex every `step` metres, with analytic
/// normals.
fn hills_mesh(extent: f32, step: f32) -> Mesh {
    let n = (extent / step) as u32 + 1;
    let mut positions = Vec::with_capacity((n * n) as usize);
    let mut normals = Vec::with_capacity((n * n) as usize);
    let mut uvs = Vec::with_capacity((n * n) as usize);
    let e = 0.05;
    for j in 0..n {
        for i in 0..n {
            let xz = Vec2::new(i as f32, j as f32) * step - Vec2::splat(0.5 * extent);
            let y = hills(xz);
            let dx = (hills(xz + Vec2::X * e) - hills(xz - Vec2::X * e)) / (2.0 * e);
            let dz = (hills(xz + Vec2::Y * e) - hills(xz - Vec2::Y * e)) / (2.0 * e);
            positions.push([xz.x, y, xz.y]);
            normals.push(Vec3::new(-dx, 1.0, -dz).normalize().to_array());
            uvs.push([xz.x, xz.y]);
        }
    }
    let mut indices = Vec::with_capacity(((n - 1) * (n - 1) * 6) as usize);
    for j in 0..n - 1 {
        for i in 0..n - 1 {
            let a = j * n + i;
            let (b, c, d) = (a + 1, a + n, a + n + 1);
            indices.extend_from_slice(&[a, c, b, b, c, d]);
        }
    }
    Mesh::new(
        bevy::mesh::PrimitiveTopology::TriangleList,
        bevy::asset::RenderAssetUsages::default(),
    )
    .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions)
    .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
    .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs)
    .with_inserted_indices(bevy::mesh::Indices::U32(indices))
}

/// A foot of the walker: left (-1) or right (+1).
#[derive(Component)]
struct Foot(f32);

/// A wheel: (+1 front, -1 rear), (-1 left, +1 right).
#[derive(Component)]
struct Wheel(f32, f32);

#[derive(Component)]
struct Walker;

#[derive(Component)]
struct Vehicle;

fn env_f32(name: &str, default: f32) -> f32 {
    std::env::var(name)
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(default)
}

fn env_vec(name: &str) -> Option<Vec<f32>> {
    std::env::var(name)
        .ok()
        .map(|v| v.split(',').filter_map(|s| s.trim().parse().ok()).collect())
}

fn main() {
    let ground = match std::env::var("ELEMENTS_GROUND").as_deref() {
        Ok("sand") => Ground::Sand,
        Ok("mud") => Ground::Mud,
        _ => Ground::Snow,
    };
    let mesh = std::env::var("ELEMENTS_TERRAIN").is_ok_and(|v| v.eq_ignore_ascii_case("mesh"));
    let preset = std::env::var("ELEMENTS_PRESET").ok().and_then(|name| {
        WeatherPreset::ALL
            .into_iter()
            .find(|p| format!("{p:?}").eq_ignore_ascii_case(&name))
    });
    // Snow in January; sand and mud in June, so the rain stays rain.
    let date = if ground == Ground::Snow {
        CivilDate::new(2026, 1, 15)
    } else {
        CivilDate::new(2026, 6, 15)
    };
    let clock = WorldClock::new(date)
        .at_hour(f64::from(env_f32("ELEMENTS_HOUR", 10.5)))
        .with_time_scale(env_f32("ELEMENTS_SCALE", 1.0));
    let mut app = App::new();
    if mesh {
        let trail_ground = TrailGround::new(hills);
        app.insert_resource(if ground == Ground::Sand {
            trail_ground.with_sand()
        } else {
            trail_ground
        });
    }
    if let Some(look) = terrain_look_env() {
        app.insert_resource(look);
    }
    app.add_plugins((DefaultPlugins, ElementsPlugins, ExampleHarness))
        .insert_resource(clock)
        .insert_resource(if ground == Ground::Sand {
            Climate::desert()
        } else {
            Climate::temperate()
        })
        .insert_resource(ErosionSettings {
            enabled: false,
            ..default()
        })
        .insert_resource(Scene {
            ground,
            preset,
            mesh,
        })
        .add_systems(Startup, (setup, lay_paths))
        .add_systems(Update, mark_paths.after(ElementsSystems::Readback))
        .add_systems(
            Update,
            (settle_weather, walk, drive).after(ElementsSystems::Readback),
        )
        .run();
}

fn setup(
    mut commands: Commands,
    scene: Res<Scene>,
    mut director: ResMut<WeatherDirector>,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    mut weathered: ResMut<Assets<WeatheredMaterial>>,
) {
    if scene.mesh {
        // The game's own ground: grass, soil or sand that draws the trails pressed into it.
        let color = match scene.ground {
            Ground::Snow => Color::srgb(0.30, 0.34, 0.22),
            Ground::Sand => Color::srgb(0.72, 0.62, 0.45),
            Ground::Mud => Color::srgb(0.30, 0.25, 0.18),
        };
        commands.spawn((
            Mesh3d(meshes.add(hills_mesh(160.0, 0.5))),
            MeshMaterial3d(weathered.add(WeatheredMaterial {
                base: StandardMaterial {
                    base_color: color,
                    perceptual_roughness: 0.9,
                    ..default()
                },
                extension: WeatheredExtension::default().with_trails(),
            })),
        ));
    } else {
        commands.spawn(Terrain::procedural(match scene.ground {
            Ground::Sand => ProceduralTerrain::dunes(7),
            _ => ProceduralTerrain::hills(42),
        }));
    }
    // The ground is grown under its weather (`ELEMENTS_GROW_HOURS` in the harness), then the
    // sky clears in `settle_weather`.
    director.force(
        match scene.ground {
            Ground::Snow => WeatherPreset::Snow,
            Ground::Sand => WeatherPreset::Clear,
            Ground::Mud => WeatherPreset::Rain,
        },
        Duration::ZERO,
    );
    let eye = env_vec("ELEMENTS_EYE").unwrap_or_else(|| vec![0.0, 2.2, -11.0]);
    let look = env_vec("ELEMENTS_LOOK").unwrap_or_else(|| vec![CENTRE.x, CENTRE.y]);
    let (eye, look) = (
        Vec3::new(eye[0], 100.0 + eye[1], eye[2]),
        Vec3::new(look[0], 100.0, look[1]),
    );
    commands.spawn((camera(eye, look), EyeHeight(eye.y - 100.0), Aim(look.xz())));

    let body = materials.add(StandardMaterial {
        base_color: Color::srgb(0.25, 0.27, 0.32),
        perceptual_roughness: 0.8,
        ..default()
    });
    commands.spawn((
        Walker,
        Mesh3d(meshes.add(Capsule3d::new(0.22, 1.2))),
        MeshMaterial3d(body.clone()),
        Transform::from_xyz(0.0, -100.0, 0.0),
    ));
    for side in [-1.0, 1.0] {
        commands.spawn((Foot(side), Imprint::new(FOOT_HALF, FOOT_LOAD_N)));
    }
    let paint = materials.add(StandardMaterial {
        base_color: Color::srgb(0.55, 0.12, 0.08),
        perceptual_roughness: 0.4,
        ..default()
    });
    commands.spawn((
        Vehicle,
        Mesh3d(meshes.add(Cuboid::new(1.7, 1.1, 3.6))),
        MeshMaterial3d(paint),
        Transform::from_xyz(0.0, -100.0, 0.0),
    ));
    for front in [-1.0, 1.0] {
        for side in [-1.0, 1.0] {
            commands.spawn((Wheel(front, side), Imprint::new(WHEEL_HALF, WHEEL_LOAD_N)));
        }
    }
}

/// The camera's height above the ground and the point it looks at, applied once the terrain's
/// heights are read back.
#[derive(Component)]
struct EyeHeight(f32);

#[derive(Component)]
struct Aim(Vec2);

/// The undisturbed ground the feet and wheels stand on.
#[derive(SystemParam)]
struct Surface<'w> {
    env: Environment<'w>,
    game: Option<Res<'w, TrailGround>>,
    snow: Option<Res<'w, SurfaceWeathering>>,
}

impl Surface<'_> {
    /// The surface's world height (ground plus snow) at XZ: the game's ground, or the terrain
    /// once read back.
    fn at(&self, xz: Vec2) -> Option<f32> {
        match &self.game {
            Some(g) => Some(g.height(xz) + self.snow.as_ref().map_or(0.0, |s| s.snow_depth_m)),
            None => Some(self.env.terrain_height(xz)? + self.env.snow_depth(xz).unwrap_or(0.0)),
        }
    }
}

/// Once the ground is grown: the camera settles, and the sky clears (or turns to
/// `ELEMENTS_PRESET`).
fn settle_weather(
    mut commands: Commands,
    surface: Surface,
    scene: Res<Scene>,
    mut director: ResMut<WeatherDirector>,
    mut cameras: Query<(Entity, &mut Transform, &EyeHeight, &Aim)>,
    mut done: Local<bool>,
    mut frames: Local<u32>,
) {
    // A game's ground is known at once, but the harness grows the weather over its first frames
    // (one an hour, `ELEMENTS_GROW_HOURS`): settle after a second, past any growth of up to two
    // days. The terrain is settled once read back, which comes later.
    *frames += 1;
    if scene.mesh && *frames < 60 {
        return;
    }
    for (entity, mut transform, eye, aim) in &mut cameras {
        let (Some(here), Some(there)) = (
            surface.at(transform.translation.xz()),
            surface.at(aim.0),
        ) else {
            continue;
        };
        transform.translation.y = here + eye.0;
        transform.look_at(Vec3::new(aim.0.x, there + 0.3, aim.0.y), Vec3::Y);
        commands.entity(entity).remove::<(EyeHeight, Aim)>();
        if !*done {
            *done = true;
            director.force(scene.preset.unwrap_or(WeatherPreset::Clear), Duration::ZERO);
        }
    }
}

/// A point on a circle of `radius` round the centre at arc length `s`, and the direction along it.
fn on_circle(radius: f32, s: f32) -> (Vec2, Vec2) {
    let a = s / radius;
    let (sin, cos) = a.sin_cos();
    (CENTRE + radius * Vec2::new(cos, sin), Vec2::new(-sin, cos))
}

/// The walker: each foot is planted for a step and swings through the next; a planted foot sits
/// 5 cm below the surface the readback reports, so it is in contact whatever the readback's lag.
fn walk(
    surface: Surface,
    time: Res<Time<Virtual>>,
    mut feet: Query<(&Foot, &mut Transform), Without<Walker>>,
    mut body: Query<&mut Transform, With<Walker>>,
) {
    let t = time.elapsed_secs();
    let s = WALK_SPEED_MS * t;
    let (centre, _) = on_circle(WALK_RADIUS_M, s);
    if let (Ok(mut b), Some(y)) = (body.single_mut(), surface.at(centre)) {
        b.translation = Vec3::new(centre.x, y + 0.85, centre.y);
    }
    let step = WALK_SPEED_MS * STEP_S;
    for (foot, mut transform) in &mut feet {
        // Left plants on even steps, right on odd ones; a foot plants where the body will be
        // half a step later, and swings over the next step.
        let phase = t / STEP_S + if foot.0 < 0.0 { 0.0 } else { 1.0 };
        let index = (phase / 2.0).floor();
        let within = phase - 2.0 * index;
        let planted = within < 1.0;
        let plant_s = (2.0 * index * STEP_S - if foot.0 < 0.0 { 0.0 } else { STEP_S })
            * WALK_SPEED_MS
            + 0.5 * step;
        let (at, along) = if planted {
            on_circle(WALK_RADIUS_M, plant_s)
        } else {
            let k = within - 1.0;
            on_circle(WALK_RADIUS_M, plant_s + 2.0 * step * k)
        };
        let side = Vec2::new(along.y, -along.x) * foot.0 * STEP_WIDTH_M;
        let xz = at + side;
        let Some(y) = surface.at(xz) else {
            continue;
        };
        let lift = if planted {
            -0.05
        } else {
            0.3 * (TAU * 0.5 * (within - 1.0)).sin().abs() + 0.3
        };
        *transform = Transform::from_xyz(xz.x, y + lift, xz.y)
            .looking_to(Vec3::new(along.x, 0.0, along.y), Vec3::Y);
    }
}

/// The vehicle: four wheels on a circle, each pressing where it is.
fn drive(
    surface: Surface,
    time: Res<Time<Virtual>>,
    mut wheels: Query<(&Wheel, &mut Transform), Without<Vehicle>>,
    mut body: Query<&mut Transform, With<Vehicle>>,
) {
    let s = DRIVE_SPEED_MS * time.elapsed_secs();
    let (centre, along) = on_circle(DRIVE_RADIUS_M, s);
    let side = Vec2::new(along.y, -along.x);
    if let (Ok(mut b), Some(y)) = (body.single_mut(), surface.at(centre)) {
        *b = Transform::from_xyz(centre.x, y + 0.85, centre.y)
            .looking_to(Vec3::new(along.x, 0.0, along.y), Vec3::Y);
    }
    for (wheel, mut transform) in &mut wheels {
        let xz = centre + along * wheel.0 * 0.5 * WHEELBASE_M + side * wheel.1 * 0.5 * TRACK_M;
        let Some(y) = surface.at(xz) else {
            continue;
        };
        *transform = Transform::from_xyz(xz.x, y - 0.05, xz.y)
            .looking_to(Vec3::new(along.x, 0.0, along.y), Vec3::Y);
    }
}

/// `ELEMENTS_PATHS`: the routes a game lays across this ground (`docs/research/paths.md`).
fn lay_paths(mut commands: Commands) {
    let Ok(which) = std::env::var("ELEMENTS_PATHS") else {
        return;
    };
    let which = which.to_ascii_lowercase();
    let all = which == "all";
    let mut paths = Vec::new();
    if all || which == "lane" {
        paths.push(Path::new(
            vec![
                Vec3::new(-24.0, 0.0, -18.0),
                Vec3::new(-9.0, 0.0, -6.0),
                Vec3::new(-2.0, 0.0, 2.0),
                Vec3::new(6.0, 0.0, 9.0),
                Vec3::new(20.0, 0.0, 15.0),
            ],
            0.35,
            PathKind::Earth,
        ));
    }
    if all || which == "track" {
        paths.push(
            Path::new(
                vec![
                    Vec3::new(-26.0, 0.0, 5.0),
                    Vec3::new(-12.0, 0.0, 4.0),
                    Vec3::new(0.0, 0.0, 3.0),
                    Vec3::new(13.0, 0.0, 6.0),
                    Vec3::new(26.0, 0.0, 10.0),
                ],
                1.0,
                PathKind::Earth,
            )
            .with_ruts(0.06),
        );
    }
    if all || which == "road" {
        paths.push(
            Path::new(
                vec![
                    Vec3::new(-30.0, 0.0, -24.0),
                    Vec3::new(-16.0, 0.0, -14.0),
                    Vec3::new(-4.0, 0.0, -10.0),
                    Vec3::new(10.0, 0.0, -12.0),
                    Vec3::new(26.0, 0.0, -20.0),
                ],
                2.5,
                PathKind::Gravel,
            )
            .with_ruts(0.03),
        );
    }
    if all || which == "stone" {
        paths.push(Path::new(
            vec![
                Vec3::new(-26.0, 0.0, 20.0),
                Vec3::new(-8.0, 0.0, 18.0),
                Vec3::new(8.0, 0.0, 19.0),
                Vec3::new(26.0, 0.0, 22.0),
            ],
            1.6,
            PathKind::Stone,
        ));
    }
    if all || which == "packed" {
        paths.push(Path::new(
            vec![
                Vec3::new(-26.0, 0.0, -2.0),
                Vec3::new(-8.0, 0.0, -1.0),
                Vec3::new(8.0, 0.0, -3.0),
                Vec3::new(26.0, 0.0, -1.0),
            ],
            1.2,
            PathKind::Snow,
        ));
    }
    if !paths.is_empty() {
        commands.insert_resource(PathNetwork::new(paths));
    }
    if std::env::var("ELEMENTS_PATHS_MARK").is_ok() {
        commands.insert_resource(PathMarks { placed: false });
    }
}

/// `ELEMENTS_PATHS_MARK=1`: posts placed by the crate's own query, each 2 m clear of the nearest
/// route's **edge** (`nearest_path`'s distance), so a capture shows the query and the drawn verge
/// agreeing (`docs/research/path-query.md` Validation 7).
#[derive(Resource)]
struct PathMarks {
    placed: bool,
}

fn mark_paths(
    mut commands: Commands,
    env: Environment,
    paths: Option<Res<PathNetwork>>,
    marks: Option<ResMut<PathMarks>>,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    let Some(mut marks) = marks else {
        return;
    };
    let Some(network) = paths.as_deref() else {
        return;
    };
    if marks.placed {
        return;
    }
    let post = meshes.add(Cuboid::new(0.18, 2.4, 0.18));
    let white = materials.add(StandardMaterial {
        base_color: Color::srgb(0.95, 0.95, 0.98),
        perceptual_roughness: 0.7,
        ..default()
    });
    // The proof of Validation 7: walk each route's own centre line, ask the query for the point's
    // signed distance to the edge, and stand a post exactly 2 m beyond it. If the query and the
    // drawn verge agree, the posts trace every verge at one constant offset.
    let mut placed = 0;
    {
        for path in &network.paths {
            for pair in path.points.windows(2) {
                let (a, b) = (pair[0].xz(), pair[1].xz());
                let span = a.distance(b);
                let steps = (span / 3.0).ceil().max(1.0) as i32;
                for k in 0..=steps {
                    let on = a.lerp(b, k as f32 / steps as f32);
                    let Some(hit) = env.nearest_path(on) else {
                        continue;
                    };
                    // Away from the route, along the direction from its centre line to this point:
                    // the route's normal, from the query's own nearest point.
                    let normal = if on == hit.point {
                        let ab = (b - a).normalize_or_zero();
                        Vec2::new(-ab.y, ab.x)
                    } else {
                        (on - hit.point).normalize_or_zero()
                    };
                    let target = hit.point + normal * (hit.surface.half_width_m);
                    // The verge: 2 m beyond the edge the query just measured.
                    let Some(edge_hit) = env.nearest_path(target) else {
                        continue;
                    };
                    debug_assert!(edge_hit.distance_m.abs() < 0.35, "{edge_hit:?}");
                    let outside = target + normal * 2.0;
                    // The example's terrain readback covers its grid; a post beyond it stands at
                    // the crate's own ground query's answer or, failing that, the flat plane.
                    let ground = env.terrain_height(outside).unwrap_or(0.0);
                    commands.spawn((
                        Mesh3d(post.clone()),
                        MeshMaterial3d(white.clone()),
                        Transform::from_xyz(outside.x, ground + 1.2, outside.y),
                    ));
                    placed += 1;
                }
                let _ = span;
            }
        }
    }
    eprintln!("path marks: {placed} posts placed by nearest_path");
    // A diagnostic: the query at the road's own start point, and at a few known places.
    for probe in [
        Vec2::new(-30.0, -24.0),
        Vec2::new(-4.0, -10.0),
        Vec2::new(10.0, -12.0),
        Vec2::new(0.0, 0.0),
        Vec2::new(0.0, 3.0),
    ] {
        eprintln!("  at {probe:?}: {:?}", env.nearest_path(probe));
    }
    marks.placed = true;
}